Debian Codegraph @

flang/lib/Semantics/definable.cpp

raw
1 //===-- lib/Semantics/definable.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 "definable.h"
10 #include "flang/Evaluate/tools.h"
11 #include "flang/Semantics/tools.h"
12
13 using namespace Fortran::parser::literals;
14
15 namespace Fortran::semantics {
16
17 template <typename... A>
18 static parser::Message BlameSymbol(parser::CharBlock at,
19 const parser::MessageFixedText &text, const Symbol &original, A &&...x) {
20 parser::Message message{at, text, original.name(), std::forward<A>(x)...};
21 message.set_severity(parser::Severity::Error);
22 evaluate::AttachDeclaration(message, original);
23 return message;
24 }
25
26 static bool IsPointerDummyOfPureFunction(const Symbol &x) {
27 return IsPointerDummy(x) && FindPureProcedureContaining(x.owner()) &&
28 x.owner().symbol() && IsFunction(*x.owner().symbol());
29 }
30
31 // See C1594, first paragraph. These conditions enable checks on both
32 // left-hand and right-hand sides in various circumstances.
33 const char *WhyBaseObjectIsSuspicious(const Symbol &x, const Scope &scope) {
34 if (IsHostAssociatedIntoSubprogram(x, scope)) {
35 return "host-associated";
36 } else if (IsUseAssociated(x, scope)) {
37 return "USE-associated";
38 } else if (IsPointerDummyOfPureFunction(x)) {
39 return "a POINTER dummy argument of a pure function";
40 } else if (IsIntentIn(x)) {
41 return "an INTENT(IN) dummy argument";
42 } else if (FindCommonBlockContaining(x)) {
43 return "in a COMMON block";
44 } else {
45 return nullptr;
46 }
47 }
48
49 // Checks C1594(1,2); false if check fails
50 static std::optional<parser::Message> CheckDefinabilityInPureScope(
51 SourceName at, const Symbol &original, const Symbol &ultimate,
52 const Scope &context, const Scope &pure) {
53 if (pure.symbol()) {
54 if (const char *why{WhyBaseObjectIsSuspicious(ultimate, context)}) {
55 return BlameSymbol(at,
56 "'%s' may not be defined in pure subprogram '%s' because it is %s"_en_US,
57 original, pure.symbol()->name(), why);
58 }
59 }
60 return std::nullopt;
61 }
62
63 // True when the object being defined is not a subobject of the base
64 // object, e.g. X%PTR = 1., X%PTR%PTR2 => T (but not X%PTR => T).
65 // F'2023 9.4.2p5
66 static bool DefinesComponentPointerTarget(
67 const evaluate::DataRef &dataRef, DefinabilityFlags flags) {
68 if (const evaluate::Component *
69 component{common::visit(
70 common::visitors{
71 [](const SymbolRef &) -> const evaluate::Component * {
72 return nullptr;
73 },
74 [](const evaluate::Component &component) { return &component; },
75 [](const evaluate::ArrayRef &aRef) {
76 return aRef.base().UnwrapComponent();
77 },
78 [](const evaluate::CoarrayRef &aRef)
79 -> const evaluate::Component * { return nullptr; },
80 },
81 dataRef.u)}) {
82 const Symbol &compSym{component->GetLastSymbol()};
83 if (IsPointer(compSym) ||
84 (flags.test(DefinabilityFlag::AcceptAllocatable) &&
85 IsAllocatable(compSym))) {
86 if (!flags.test(DefinabilityFlag::PointerDefinition)) {
87 return true;
88 }
89 }
90 flags.reset(DefinabilityFlag::PointerDefinition);
91 return DefinesComponentPointerTarget(component->base(), flags);
92 } else {
93 return false;
94 }
95 }
96
97 // Check the leftmost (or only) symbol from a data-ref or expression.
98 static std::optional<parser::Message> WhyNotDefinableBase(parser::CharBlock at,
99 const Scope &scope, DefinabilityFlags flags, const Symbol &original,
100 bool isWholeSymbol, bool isComponentPointerTarget) {
101 const Symbol &ultimate{original.GetUltimate()};
102 bool isPointerDefinition{flags.test(DefinabilityFlag::PointerDefinition)};
103 bool acceptAllocatable{flags.test(DefinabilityFlag::AcceptAllocatable)};
104 bool isTargetDefinition{!isPointerDefinition && IsPointer(ultimate)};
105 if (const auto *association{ultimate.detailsIf<AssocEntityDetails>()}) {
106 if (!IsVariable(association->expr())) {
107 return BlameSymbol(at,
108 "'%s' is construct associated with an expression"_en_US, original);
109 } else if (evaluate::HasVectorSubscript(association->expr().value())) {
110 return BlameSymbol(at,
111 "Construct association '%s' has a vector subscript"_en_US, original);
112 } else if (auto dataRef{evaluate::ExtractDataRef(
113 *association->expr(), true, true)}) {
114 return WhyNotDefinableBase(at, scope, flags, dataRef->GetFirstSymbol(),
115 isWholeSymbol &&
116 std::holds_alternative<evaluate::SymbolRef>(dataRef->u),
117 isComponentPointerTarget ||
118 DefinesComponentPointerTarget(*dataRef, flags));
119 }
120 }
121 if (isTargetDefinition || isComponentPointerTarget) {
122 } else if (!isPointerDefinition && !IsVariableName(ultimate)) {
123 return BlameSymbol(at, "'%s' is not a variable"_en_US, original);
124 } else if (IsProtected(ultimate) && IsUseAssociated(original, scope)) {
125 return BlameSymbol(at, "'%s' is protected in this scope"_en_US, original);
126 } else if (IsIntentIn(ultimate) &&
127 (!IsPointer(ultimate) || (isWholeSymbol && isPointerDefinition))) {
128 return BlameSymbol(
129 at, "'%s' is an INTENT(IN) dummy argument"_en_US, original);
130 }
131 if (const Scope * pure{FindPureProcedureContaining(scope)}) {
132 // Additional checking for pure subprograms.
133 if (!isTargetDefinition || isComponentPointerTarget) {
134 if (auto msg{CheckDefinabilityInPureScope(
135 at, original, ultimate, scope, *pure)}) {
136 return msg;
137 }
138 }
139 if (const Symbol *
140 visible{FindExternallyVisibleObject(
141 ultimate, *pure, isPointerDefinition)}) {
142 return BlameSymbol(at,
143 "'%s' is externally visible via '%s' and not definable in a pure subprogram"_en_US,
144 original, visible->name());
145 }
146 }
147 if (const Scope * deviceContext{FindCUDADeviceContext(&scope)}) {
148 bool isOwnedByDeviceCode{deviceContext->Contains(ultimate.owner())};
149 if (isPointerDefinition && !acceptAllocatable) {
150 return BlameSymbol(at,
151 "'%s' is a pointer and may not be associated in a device subprogram"_err_en_US,
152 original);
153 } else if (auto cudaDataAttr{GetCUDADataAttr(&ultimate)}) {
154 if (*cudaDataAttr == common::CUDADataAttr::Constant) {
155 return BlameSymbol(at,
156 "'%s' has ATTRIBUTES(CONSTANT) and is not definable in a device subprogram"_err_en_US,
157 original);
158 } else if (acceptAllocatable && !isOwnedByDeviceCode) {
159 return BlameSymbol(at,
160 "'%s' is a host-associated allocatable and is not definable in a device subprogram"_err_en_US,
161 original);
162 } else if (*cudaDataAttr != common::CUDADataAttr::Device &&
163 *cudaDataAttr != common::CUDADataAttr::Managed &&
164 *cudaDataAttr != common::CUDADataAttr::Shared) {
165 return BlameSymbol(at,
166 "'%s' is not device or managed or shared data and is not definable in a device subprogram"_err_en_US,
167 original);
168 }
169 } else if (!isOwnedByDeviceCode) {
170 return BlameSymbol(at,
171 "'%s' is a host variable and is not definable in a device subprogram"_err_en_US,
172 original);
173 }
174 }
175 return std::nullopt;
176 }
177
178 static std::optional<parser::Message> WhyNotDefinableLast(parser::CharBlock at,
179 const Scope &scope, DefinabilityFlags flags, const Symbol &original) {
180 const Symbol &ultimate{original.GetUltimate()};
181 if (const auto *association{ultimate.detailsIf<AssocEntityDetails>()};
182 association &&
183 (association->rank().has_value() ||
184 !flags.test(DefinabilityFlag::PointerDefinition))) {
185 if (auto dataRef{
186 evaluate::ExtractDataRef(*association->expr(), true, true)}) {
187 return WhyNotDefinableLast(at, scope, flags, dataRef->GetLastSymbol());
188 }
189 }
190 if (flags.test(DefinabilityFlag::PointerDefinition)) {
191 if (flags.test(DefinabilityFlag::AcceptAllocatable)) {
192 if (!IsAllocatableOrObjectPointer(&ultimate)) {
193 return BlameSymbol(
194 at, "'%s' is neither a pointer nor an allocatable"_en_US, original);
195 }
196 } else if (!IsPointer(ultimate)) {
197 return BlameSymbol(at, "'%s' is not a pointer"_en_US, original);
198 }
199 return std::nullopt; // pointer assignment - skip following checks
200 }
201 if (IsOrContainsEventOrLockComponent(ultimate)) {
202 return BlameSymbol(at,
203 "'%s' is an entity with either an EVENT_TYPE or LOCK_TYPE"_en_US,
204 original);
205 }
206 if (FindPureProcedureContaining(scope)) {
207 if (auto dyType{evaluate::DynamicType::From(ultimate)}) {
208 if (!flags.test(DefinabilityFlag::PolymorphicOkInPure)) {
209 if (dyType->IsPolymorphic()) { // C1596
210 return BlameSymbol(
211 at, "'%s' is polymorphic in a pure subprogram"_en_US, original);
212 }
213 }
214 if (const Symbol * impure{HasImpureFinal(ultimate)}) {
215 return BlameSymbol(at, "'%s' has an impure FINAL procedure '%s'"_en_US,
216 original, impure->name());
217 }
218 if (const DerivedTypeSpec * derived{GetDerivedTypeSpec(dyType)}) {
219 if (!flags.test(DefinabilityFlag::PolymorphicOkInPure)) {
220 if (auto bad{FindPolymorphicAllocatableUltimateComponent(*derived)}) {
221 return BlameSymbol(at,
222 "'%s' has polymorphic component '%s' in a pure subprogram"_en_US,
223 original, bad.BuildResultDesignatorName());
224 }
225 }
226 }
227 }
228 }
229 return std::nullopt;
230 }
231
232 // Checks a data-ref
233 static std::optional<parser::Message> WhyNotDefinable(parser::CharBlock at,
234 const Scope &scope, DefinabilityFlags flags,
235 const evaluate::DataRef &dataRef) {
236 auto whyNotBase{
237 WhyNotDefinableBase(at, scope, flags, dataRef.GetFirstSymbol(),
238 std::holds_alternative<evaluate::SymbolRef>(dataRef.u),
239 DefinesComponentPointerTarget(dataRef, flags))};
240 if (!whyNotBase || !whyNotBase->IsFatal()) {
241 if (auto whyNotLast{
242 WhyNotDefinableLast(at, scope, flags, dataRef.GetLastSymbol())}) {
243 if (whyNotLast->IsFatal() || !whyNotBase) {
244 return whyNotLast;
245 }
246 }
247 }
248 return whyNotBase;
249 }
250
251 std::optional<parser::Message> WhyNotDefinable(parser::CharBlock at,
252 const Scope &scope, DefinabilityFlags flags, const Symbol &original) {
253 auto whyNotBase{WhyNotDefinableBase(at, scope, flags, original,
254 /*isWholeSymbol=*/true, /*isComponentPointerTarget=*/false)};
255 if (!whyNotBase || !whyNotBase->IsFatal()) {
256 if (auto whyNotLast{WhyNotDefinableLast(at, scope, flags, original)}) {
257 if (whyNotLast->IsFatal() || !whyNotBase) {
258 return whyNotLast;
259 }
260 }
261 }
262 return whyNotBase;
263 }
264
265 class DuplicatedSubscriptFinder
266 : public evaluate::AnyTraverse<DuplicatedSubscriptFinder, bool> {
267 using Base = evaluate::AnyTraverse<DuplicatedSubscriptFinder, bool>;
268
269 public:
270 explicit DuplicatedSubscriptFinder(evaluate::FoldingContext &foldingContext)
271 : Base{*this}, foldingContext_{foldingContext} {}
272 using Base::operator();
273 bool operator()(const evaluate::ActualArgument &) {
274 return false; // don't descend into argument expressions
275 }
276 bool operator()(const evaluate::ArrayRef &aRef) {
277 bool anyVector{false};
278 for (const auto &ss : aRef.subscript()) {
279 if (ss.Rank() > 0) {
280 anyVector = true;
281 if (const auto *vecExpr{
282 std::get_if<evaluate::IndirectSubscriptIntegerExpr>(&ss.u)}) {
283 auto folded{evaluate::Fold(foldingContext_,
284 evaluate::Expr<evaluate::SubscriptInteger>{vecExpr->value()})};
285 if (const auto *con{
286 evaluate::UnwrapConstantValue<evaluate::SubscriptInteger>(
287 folded)}) {
288 std::set<std::int64_t> values;
289 for (const auto &j : con->values()) {
290 if (auto pair{values.emplace(j.ToInt64())}; !pair.second) {
291 return true; // duplicate
292 }
293 }
294 }
295 return false;
296 }
297 }
298 }
299 return anyVector ? false : (*this)(aRef.base());
300 }
301
302 private:
303 evaluate::FoldingContext &foldingContext_;
304 };
305
306 std::optional<parser::Message> WhyNotDefinable(parser::CharBlock at,
307 const Scope &scope, DefinabilityFlags flags,
308 const evaluate::Expr<evaluate::SomeType> &expr) {
309 std::optional<parser::Message> portabilityWarning;
310 if (auto dataRef{evaluate::ExtractDataRef(expr, true, true)}) {
311 if (evaluate::HasVectorSubscript(expr)) {
312 if (flags.test(DefinabilityFlag::VectorSubscriptIsOk)) {
313 if (auto type{expr.GetType()}) {
314 if (!type->IsUnlimitedPolymorphic() &&
315 type->category() == TypeCategory::Derived) {
316 // Seek the FINAL subroutine that should but cannot be called
317 // for this definition of an array with a vector-valued subscript.
318 // If there's an elemental FINAL subroutine, all is well; otherwise,
319 // if there is a FINAL subroutine with a matching or assumed rank
320 // dummy argument, there's no way to call it.
321 int rank{expr.Rank()};
322 const DerivedTypeSpec *spec{&type->GetDerivedTypeSpec()};
323 while (spec) {
324 bool anyElemental{false};
325 const Symbol *anyRankMatch{nullptr};
326 for (auto ref : FinalsForDerivedTypeInstantiation(*spec)) {
327 const Symbol &ultimate{ref->GetUltimate()};
328 anyElemental |= ultimate.attrs().test(Attr::ELEMENTAL);
329 if (const auto *subp{ultimate.detailsIf<SubprogramDetails>()}) {
330 if (!subp->dummyArgs().empty()) {
331 if (const Symbol * arg{subp->dummyArgs()[0]}) {
332 const auto *object{arg->detailsIf<ObjectEntityDetails>()};
333 if (arg->Rank() == rank ||
334 (object && object->IsAssumedRank())) {
335 anyRankMatch = &*ref;
336 }
337 }
338 }
339 }
340 }
341 if (anyRankMatch && !anyElemental) {
342 if (!portabilityWarning &&
343 scope.context().languageFeatures().ShouldWarn(
344 common::UsageWarning::VectorSubscriptFinalization)) {
345 portabilityWarning = parser::Message{at,
346 "Variable '%s' has a vector subscript and will be finalized by non-elemental subroutine '%s'"_port_en_US,
347 expr.AsFortran(), anyRankMatch->name()};
348 }
349 break;
350 }
351 const auto *parent{FindParentTypeSpec(*spec)};
352 spec = parent ? parent->AsDerived() : nullptr;
353 }
354 }
355 }
356 if (!flags.test(DefinabilityFlag::DuplicatesAreOk) &&
357 DuplicatedSubscriptFinder{scope.context().foldingContext()}(expr)) {
358 return parser::Message{at,
359 "Variable has a vector subscript with a duplicated element"_err_en_US};
360 }
361 } else {
362 return parser::Message{at,
363 "Variable '%s' has a vector subscript"_err_en_US, expr.AsFortran()};
364 }
365 }
366 if (FindPureProcedureContaining(scope) &&
367 evaluate::ExtractCoarrayRef(expr)) {
368 return parser::Message(at,
369 "A pure subprogram may not define the coindexed object '%s'"_err_en_US,
370 expr.AsFortran());
371 }
372 if (auto whyNotDataRef{WhyNotDefinable(at, scope, flags, *dataRef)}) {
373 return whyNotDataRef;
374 }
375 } else if (evaluate::IsNullPointer(expr)) {
376 return parser::Message{
377 at, "'%s' is a null pointer"_err_en_US, expr.AsFortran()};
378 } else if (flags.test(DefinabilityFlag::PointerDefinition)) {
379 if (const auto *procDesignator{
380 std::get_if<evaluate::ProcedureDesignator>(&expr.u)}) {
381 // Defining a procedure pointer
382 if (const Symbol * procSym{procDesignator->GetSymbol()}) {
383 if (evaluate::ExtractCoarrayRef(expr)) { // C1027
384 return BlameSymbol(at,
385 "Procedure pointer '%s' may not be a coindexed object"_err_en_US,
386 *procSym, expr.AsFortran());
387 }
388 if (const auto *component{procDesignator->GetComponent()}) {
389 flags.reset(DefinabilityFlag::PointerDefinition);
390 return WhyNotDefinableBase(at, scope, flags,
391 component->base().GetFirstSymbol(), false,
392 DefinesComponentPointerTarget(component->base(), flags));
393 } else {
394 return WhyNotDefinable(at, scope, flags, *procSym);
395 }
396 }
397 }
398 return parser::Message{
399 at, "'%s' is not a definable pointer"_err_en_US, expr.AsFortran()};
400 } else if (!evaluate::IsVariable(expr)) {
401 return parser::Message{
402 at, "'%s' is not a variable or pointer"_err_en_US, expr.AsFortran()};
403 }
404 return portabilityWarning;
405 }
406
407 } // namespace Fortran::semantics