Debian Codegraph @

flang/lib/Semantics/resolve-directives.cpp

raw
1 //===----------------------------------------------------------------------===//
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 "resolve-directives.h"
10
11 #include "check-acc-structure.h"
12 #include "check-omp-structure.h"
13 #include "resolve-names-utils.h"
14 #include "flang/Common/idioms.h"
15 #include "flang/Evaluate/fold.h"
16 #include "flang/Evaluate/tools.h"
17 #include "flang/Evaluate/type.h"
18 #include "flang/Parser/parse-tree-visitor.h"
19 #include "flang/Parser/parse-tree.h"
20 #include "flang/Parser/tools.h"
21 #include "flang/Semantics/expression.h"
22 #include <list>
23 #include <map>
24 #include <sstream>
25
26 template <typename T>
27 static Fortran::semantics::Scope *GetScope(
28 Fortran::semantics::SemanticsContext &context, const T &x) {
29 std::optional<Fortran::parser::CharBlock> source{GetLastSource(x)};
30 return source ? &context.FindScope(*source) : nullptr;
31 }
32
33 namespace Fortran::semantics {
34
35 template <typename T> class DirectiveAttributeVisitor {
36 public:
37 explicit DirectiveAttributeVisitor(SemanticsContext &context)
38 : context_{context} {}
39
40 template <typename A> bool Pre(const A &) { return true; }
41 template <typename A> void Post(const A &) {}
42
43 protected:
44 struct DirContext {
45 DirContext(const parser::CharBlock &source, T d, Scope &s)
46 : directiveSource{source}, directive{d}, scope{s} {}
47 parser::CharBlock directiveSource;
48 T directive;
49 Scope &scope;
50 Symbol::Flag defaultDSA{Symbol::Flag::AccShared}; // TODOACC
51 std::map<const Symbol *, Symbol::Flag> objectWithDSA;
52 bool withinConstruct{false};
53 std::int64_t associatedLoopLevel{0};
54 };
55
56 DirContext &GetContext() {
57 CHECK(!dirContext_.empty());
58 return dirContext_.back();
59 }
60 std::optional<DirContext> GetContextIf() {
61 return dirContext_.empty()
62 ? std::nullopt
63 : std::make_optional<DirContext>(dirContext_.back());
64 }
65 void PushContext(const parser::CharBlock &source, T dir, Scope &scope) {
66 dirContext_.emplace_back(source, dir, scope);
67 }
68 void PushContext(const parser::CharBlock &source, T dir) {
69 dirContext_.emplace_back(source, dir, context_.FindScope(source));
70 }
71 void PopContext() { dirContext_.pop_back(); }
72 void SetContextDirectiveSource(parser::CharBlock &dir) {
73 GetContext().directiveSource = dir;
74 }
75 Scope &currScope() { return GetContext().scope; }
76 void SetContextDefaultDSA(Symbol::Flag flag) {
77 GetContext().defaultDSA = flag;
78 }
79 void AddToContextObjectWithDSA(
80 const Symbol &symbol, Symbol::Flag flag, DirContext &context) {
81 context.objectWithDSA.emplace(&symbol, flag);
82 }
83 void AddToContextObjectWithDSA(const Symbol &symbol, Symbol::Flag flag) {
84 AddToContextObjectWithDSA(symbol, flag, GetContext());
85 }
86 bool IsObjectWithDSA(const Symbol &symbol) {
87 auto it{GetContext().objectWithDSA.find(&symbol)};
88 return it != GetContext().objectWithDSA.end();
89 }
90 void SetContextAssociatedLoopLevel(std::int64_t level) {
91 GetContext().associatedLoopLevel = level;
92 }
93 Symbol &MakeAssocSymbol(const SourceName &name, Symbol &prev, Scope &scope) {
94 const auto pair{scope.try_emplace(name, Attrs{}, HostAssocDetails{prev})};
95 return *pair.first->second;
96 }
97 Symbol &MakeAssocSymbol(const SourceName &name, Symbol &prev) {
98 return MakeAssocSymbol(name, prev, currScope());
99 }
100 void AddDataSharingAttributeObject(SymbolRef object) {
101 dataSharingAttributeObjects_.insert(object);
102 }
103 void ClearDataSharingAttributeObjects() {
104 dataSharingAttributeObjects_.clear();
105 }
106 bool HasDataSharingAttributeObject(const Symbol &);
107 const parser::Name *GetLoopIndex(const parser::DoConstruct &);
108 const parser::DoConstruct *GetDoConstructIf(
109 const parser::ExecutionPartConstruct &);
110 Symbol *DeclarePrivateAccessEntity(
111 const parser::Name &, Symbol::Flag, Scope &);
112 Symbol *DeclarePrivateAccessEntity(Symbol &, Symbol::Flag, Scope &);
113 Symbol *DeclareOrMarkOtherAccessEntity(const parser::Name &, Symbol::Flag);
114
115 UnorderedSymbolSet dataSharingAttributeObjects_; // on one directive
116 SemanticsContext &context_;
117 std::vector<DirContext> dirContext_; // used as a stack
118 };
119
120 class AccAttributeVisitor : DirectiveAttributeVisitor<llvm::acc::Directive> {
121 public:
122 explicit AccAttributeVisitor(SemanticsContext &context, Scope *topScope)
123 : DirectiveAttributeVisitor(context), topScope_(topScope) {}
124
125 template <typename A> void Walk(const A &x) { parser::Walk(x, *this); }
126 template <typename A> bool Pre(const A &) { return true; }
127 template <typename A> void Post(const A &) {}
128
129 bool Pre(const parser::OpenACCBlockConstruct &);
130 void Post(const parser::OpenACCBlockConstruct &) { PopContext(); }
131 bool Pre(const parser::OpenACCCombinedConstruct &);
132 void Post(const parser::OpenACCCombinedConstruct &) { PopContext(); }
133
134 bool Pre(const parser::OpenACCDeclarativeConstruct &);
135 void Post(const parser::OpenACCDeclarativeConstruct &) { PopContext(); }
136
137 void Post(const parser::AccDeclarativeDirective &) {
138 GetContext().withinConstruct = true;
139 }
140
141 bool Pre(const parser::OpenACCRoutineConstruct &);
142 bool Pre(const parser::AccBindClause &);
143 void Post(const parser::OpenACCStandaloneDeclarativeConstruct &);
144
145 void Post(const parser::AccBeginBlockDirective &) {
146 GetContext().withinConstruct = true;
147 }
148
149 bool Pre(const parser::OpenACCLoopConstruct &);
150 void Post(const parser::OpenACCLoopConstruct &) { PopContext(); }
151 void Post(const parser::AccLoopDirective &) {
152 GetContext().withinConstruct = true;
153 }
154
155 bool Pre(const parser::OpenACCStandaloneConstruct &);
156 void Post(const parser::OpenACCStandaloneConstruct &) { PopContext(); }
157 void Post(const parser::AccStandaloneDirective &) {
158 GetContext().withinConstruct = true;
159 }
160
161 bool Pre(const parser::OpenACCCacheConstruct &);
162 void Post(const parser::OpenACCCacheConstruct &) { PopContext(); }
163
164 void Post(const parser::AccDefaultClause &);
165
166 bool Pre(const parser::AccClause::Attach &);
167 bool Pre(const parser::AccClause::Detach &);
168
169 bool Pre(const parser::AccClause::Copy &x) {
170 ResolveAccObjectList(x.v, Symbol::Flag::AccCopy);
171 return false;
172 }
173
174 bool Pre(const parser::AccClause::Create &x) {
175 const auto &objectList{std::get<parser::AccObjectList>(x.v.t)};
176 ResolveAccObjectList(objectList, Symbol::Flag::AccCreate);
177 return false;
178 }
179
180 bool Pre(const parser::AccClause::Copyin &x) {
181 const auto &objectList{std::get<parser::AccObjectList>(x.v.t)};
182 const auto &modifier{
183 std::get<std::optional<parser::AccDataModifier>>(x.v.t)};
184 if (modifier &&
185 (*modifier).v == parser::AccDataModifier::Modifier::ReadOnly) {
186 ResolveAccObjectList(objectList, Symbol::Flag::AccCopyInReadOnly);
187 } else {
188 ResolveAccObjectList(objectList, Symbol::Flag::AccCopyIn);
189 }
190 return false;
191 }
192
193 bool Pre(const parser::AccClause::Copyout &x) {
194 const auto &objectList{std::get<parser::AccObjectList>(x.v.t)};
195 ResolveAccObjectList(objectList, Symbol::Flag::AccCopyOut);
196 return false;
197 }
198
199 bool Pre(const parser::AccClause::Present &x) {
200 ResolveAccObjectList(x.v, Symbol::Flag::AccPresent);
201 return false;
202 }
203 bool Pre(const parser::AccClause::Private &x) {
204 ResolveAccObjectList(x.v, Symbol::Flag::AccPrivate);
205 return false;
206 }
207 bool Pre(const parser::AccClause::Firstprivate &x) {
208 ResolveAccObjectList(x.v, Symbol::Flag::AccFirstPrivate);
209 return false;
210 }
211
212 bool Pre(const parser::AccClause::Device &x) {
213 ResolveAccObjectList(x.v, Symbol::Flag::AccDevice);
214 return false;
215 }
216
217 bool Pre(const parser::AccClause::DeviceResident &x) {
218 ResolveAccObjectList(x.v, Symbol::Flag::AccDeviceResident);
219 return false;
220 }
221
222 bool Pre(const parser::AccClause::Deviceptr &x) {
223 ResolveAccObjectList(x.v, Symbol::Flag::AccDevicePtr);
224 return false;
225 }
226
227 bool Pre(const parser::AccClause::Link &x) {
228 ResolveAccObjectList(x.v, Symbol::Flag::AccLink);
229 return false;
230 }
231
232 bool Pre(const parser::AccClause::Host &x) {
233 ResolveAccObjectList(x.v, Symbol::Flag::AccHost);
234 return false;
235 }
236
237 bool Pre(const parser::AccClause::Self &x) {
238 const std::optional<parser::AccSelfClause> &accSelfClause = x.v;
239 if (accSelfClause &&
240 std::holds_alternative<parser::AccObjectList>((*accSelfClause).u)) {
241 const auto &accObjectList =
242 std::get<parser::AccObjectList>((*accSelfClause).u);
243 ResolveAccObjectList(accObjectList, Symbol::Flag::AccSelf);
244 }
245 return false;
246 }
247
248 void Post(const parser::Name &);
249
250 private:
251 std::int64_t GetAssociatedLoopLevelFromClauses(const parser::AccClauseList &);
252
253 Symbol::Flags dataSharingAttributeFlags{Symbol::Flag::AccShared,
254 Symbol::Flag::AccPrivate, Symbol::Flag::AccFirstPrivate,
255 Symbol::Flag::AccReduction};
256
257 Symbol::Flags dataMappingAttributeFlags{Symbol::Flag::AccCreate,
258 Symbol::Flag::AccCopyIn, Symbol::Flag::AccCopyOut,
259 Symbol::Flag::AccDelete, Symbol::Flag::AccPresent};
260
261 Symbol::Flags accDataMvtFlags{
262 Symbol::Flag::AccDevice, Symbol::Flag::AccHost, Symbol::Flag::AccSelf};
263
264 Symbol::Flags accFlagsRequireMark{Symbol::Flag::AccCreate,
265 Symbol::Flag::AccCopyIn, Symbol::Flag::AccCopyInReadOnly,
266 Symbol::Flag::AccCopy, Symbol::Flag::AccCopyOut,
267 Symbol::Flag::AccDevicePtr, Symbol::Flag::AccDeviceResident,
268 Symbol::Flag::AccLink, Symbol::Flag::AccPresent};
269
270 void CheckAssociatedLoop(const parser::DoConstruct &);
271 void ResolveAccObjectList(const parser::AccObjectList &, Symbol::Flag);
272 void ResolveAccObject(const parser::AccObject &, Symbol::Flag);
273 Symbol *ResolveAcc(const parser::Name &, Symbol::Flag, Scope &);
274 Symbol *ResolveAcc(Symbol &, Symbol::Flag, Scope &);
275 Symbol *ResolveName(const parser::Name &, bool parentScope = false);
276 Symbol *ResolveFctName(const parser::Name &);
277 Symbol *ResolveAccCommonBlockName(const parser::Name *);
278 Symbol *DeclareOrMarkOtherAccessEntity(const parser::Name &, Symbol::Flag);
279 Symbol *DeclareOrMarkOtherAccessEntity(Symbol &, Symbol::Flag);
280 void CheckMultipleAppearances(
281 const parser::Name &, const Symbol &, Symbol::Flag);
282 void AllowOnlyArrayAndSubArray(const parser::AccObjectList &objectList);
283 void DoNotAllowAssumedSizedArray(const parser::AccObjectList &objectList);
284 void AllowOnlyVariable(const parser::AccObject &object);
285 void EnsureAllocatableOrPointer(
286 const llvm::acc::Clause clause, const parser::AccObjectList &objectList);
287 void AddRoutineInfoToSymbol(
288 Symbol &, const parser::OpenACCRoutineConstruct &);
289 Scope *topScope_;
290 };
291
292 // Data-sharing and Data-mapping attributes for data-refs in OpenMP construct
293 class OmpAttributeVisitor : DirectiveAttributeVisitor<llvm::omp::Directive> {
294 public:
295 explicit OmpAttributeVisitor(SemanticsContext &context)
296 : DirectiveAttributeVisitor(context) {}
297
298 template <typename A> void Walk(const A &x) { parser::Walk(x, *this); }
299 template <typename A> bool Pre(const A &) { return true; }
300 template <typename A> void Post(const A &) {}
301
302 template <typename A> bool Pre(const parser::Statement<A> &statement) {
303 currentStatementSource_ = statement.source;
304 // Keep track of the labels in all the labelled statements
305 if (statement.label) {
306 auto label{statement.label.value()};
307 // Get the context to check if the labelled statement is in an
308 // enclosing OpenMP construct
309 std::optional<DirContext> thisContext{GetContextIf()};
310 targetLabels_.emplace(
311 label, std::make_pair(currentStatementSource_, thisContext));
312 // Check if a statement that causes a jump to the 'label'
313 // has already been encountered
314 auto range{sourceLabels_.equal_range(label)};
315 for (auto it{range.first}; it != range.second; ++it) {
316 // Check if both the statement with 'label' and the statement that
317 // causes a jump to the 'label' are in the same scope
318 CheckLabelContext(it->second.first, currentStatementSource_,
319 it->second.second, thisContext);
320 }
321 }
322 return true;
323 }
324
325 bool Pre(const parser::InternalSubprogram &) {
326 // Clear the labels being tracked in the previous scope
327 ClearLabels();
328 return true;
329 }
330
331 bool Pre(const parser::ModuleSubprogram &) {
332 // Clear the labels being tracked in the previous scope
333 ClearLabels();
334 return true;
335 }
336
337 bool Pre(const parser::StmtFunctionStmt &x) {
338 const auto &parsedExpr{std::get<parser::Scalar<parser::Expr>>(x.t)};
339 if (const auto *expr{GetExpr(context_, parsedExpr)}) {
340 for (const Symbol &symbol : evaluate::CollectSymbols(*expr)) {
341 if (!IsStmtFunctionDummy(symbol)) {
342 stmtFunctionExprSymbols_.insert(symbol.GetUltimate());
343 }
344 }
345 }
346 return true;
347 }
348
349 bool Pre(const parser::OpenMPBlockConstruct &);
350 void Post(const parser::OpenMPBlockConstruct &);
351
352 void Post(const parser::OmpBeginBlockDirective &) {
353 GetContext().withinConstruct = true;
354 }
355
356 bool Pre(const parser::OpenMPSimpleStandaloneConstruct &);
357 void Post(const parser::OpenMPSimpleStandaloneConstruct &) { PopContext(); }
358
359 bool Pre(const parser::OpenMPLoopConstruct &);
360 void Post(const parser::OpenMPLoopConstruct &) { PopContext(); }
361 void Post(const parser::OmpBeginLoopDirective &) {
362 GetContext().withinConstruct = true;
363 }
364 bool Pre(const parser::DoConstruct &);
365
366 bool Pre(const parser::OpenMPSectionsConstruct &);
367 void Post(const parser::OpenMPSectionsConstruct &) { PopContext(); }
368
369 bool Pre(const parser::OpenMPCriticalConstruct &critical);
370 void Post(const parser::OpenMPCriticalConstruct &) { PopContext(); }
371
372 bool Pre(const parser::OpenMPDeclareSimdConstruct &x) {
373 PushContext(x.source, llvm::omp::Directive::OMPD_declare_simd);
374 const auto &name{std::get<std::optional<parser::Name>>(x.t)};
375 if (name) {
376 ResolveOmpName(*name, Symbol::Flag::OmpDeclareSimd);
377 }
378 return true;
379 }
380 void Post(const parser::OpenMPDeclareSimdConstruct &) { PopContext(); }
381
382 bool Pre(const parser::OpenMPRequiresConstruct &x) {
383 using Flags = WithOmpDeclarative::RequiresFlags;
384 using Requires = WithOmpDeclarative::RequiresFlag;
385 PushContext(x.source, llvm::omp::Directive::OMPD_requires);
386
387 // Gather information from the clauses.
388 Flags flags;
389 std::optional<common::OmpAtomicDefaultMemOrderType> memOrder;
390 for (const auto &clause : std::get<parser::OmpClauseList>(x.t).v) {
391 flags |= common::visit(
392 common::visitors{
393 [&memOrder](
394 const parser::OmpClause::AtomicDefaultMemOrder &atomic) {
395 memOrder = atomic.v.v;
396 return Flags{};
397 },
398 [](const parser::OmpClause::ReverseOffload &) {
399 return Flags{Requires::ReverseOffload};
400 },
401 [](const parser::OmpClause::UnifiedAddress &) {
402 return Flags{Requires::UnifiedAddress};
403 },
404 [](const parser::OmpClause::UnifiedSharedMemory &) {
405 return Flags{Requires::UnifiedSharedMemory};
406 },
407 [](const parser::OmpClause::DynamicAllocators &) {
408 return Flags{Requires::DynamicAllocators};
409 },
410 [](const auto &) { return Flags{}; }},
411 clause.u);
412 }
413 // Merge clauses into parents' symbols details.
414 AddOmpRequiresToScope(currScope(), flags, memOrder);
415 return true;
416 }
417 void Post(const parser::OpenMPRequiresConstruct &) { PopContext(); }
418
419 bool Pre(const parser::OpenMPDeclareTargetConstruct &);
420 void Post(const parser::OpenMPDeclareTargetConstruct &) { PopContext(); }
421
422 bool Pre(const parser::OpenMPThreadprivate &);
423 void Post(const parser::OpenMPThreadprivate &) { PopContext(); }
424
425 bool Pre(const parser::OpenMPDeclarativeAllocate &);
426 void Post(const parser::OpenMPDeclarativeAllocate &) { PopContext(); }
427
428 bool Pre(const parser::OpenMPExecutableAllocate &);
429 void Post(const parser::OpenMPExecutableAllocate &);
430
431 bool Pre(const parser::OpenMPAllocatorsConstruct &);
432 void Post(const parser::OpenMPAllocatorsConstruct &);
433
434 // 2.15.3 Data-Sharing Attribute Clauses
435 void Post(const parser::OmpDefaultClause &);
436 bool Pre(const parser::OmpClause::Shared &x) {
437 ResolveOmpObjectList(x.v, Symbol::Flag::OmpShared);
438 return false;
439 }
440 bool Pre(const parser::OmpClause::Private &x) {
441 ResolveOmpObjectList(x.v, Symbol::Flag::OmpPrivate);
442 return false;
443 }
444 bool Pre(const parser::OmpAllocateClause &x) {
445 const auto &objectList{std::get<parser::OmpObjectList>(x.t)};
446 ResolveOmpObjectList(objectList, Symbol::Flag::OmpAllocate);
447 return false;
448 }
449 bool Pre(const parser::OmpClause::Firstprivate &x) {
450 ResolveOmpObjectList(x.v, Symbol::Flag::OmpFirstPrivate);
451 return false;
452 }
453 bool Pre(const parser::OmpClause::Lastprivate &x) {
454 ResolveOmpObjectList(x.v, Symbol::Flag::OmpLastPrivate);
455 return false;
456 }
457 bool Pre(const parser::OmpClause::Copyin &x) {
458 ResolveOmpObjectList(x.v, Symbol::Flag::OmpCopyIn);
459 return false;
460 }
461 bool Pre(const parser::OmpClause::Copyprivate &x) {
462 ResolveOmpObjectList(x.v, Symbol::Flag::OmpCopyPrivate);
463 return false;
464 }
465 bool Pre(const parser::OmpLinearClause &x) {
466 common::visit(common::visitors{
467 [&](const parser::OmpLinearClause::WithoutModifier
468 &linearWithoutModifier) {
469 ResolveOmpNameList(linearWithoutModifier.names,
470 Symbol::Flag::OmpLinear);
471 },
472 [&](const parser::OmpLinearClause::WithModifier
473 &linearWithModifier) {
474 ResolveOmpNameList(
475 linearWithModifier.names, Symbol::Flag::OmpLinear);
476 },
477 },
478 x.u);
479 return false;
480 }
481
482 bool Pre(const parser::OmpClause::Reduction &x) {
483 const parser::OmpReductionOperator &opr{
484 std::get<parser::OmpReductionOperator>(x.v.t)};
485 auto createDummyProcSymbol = [&](const parser::Name *name) {
486 // If name resolution failed, create a dummy symbol
487 const auto namePair{
488 currScope().try_emplace(name->source, Attrs{}, ProcEntityDetails{})};
489 auto &newSymbol{*namePair.first->second};
490 if (context_.intrinsics().IsIntrinsic(name->ToString())) {
491 newSymbol.attrs().set(Attr::INTRINSIC);
492 }
493 name->symbol = &newSymbol;
494 };
495 if (const auto *procD{parser::Unwrap<parser::ProcedureDesignator>(opr.u)}) {
496 if (const auto *name{parser::Unwrap<parser::Name>(procD->u)}) {
497 if (!name->symbol) {
498 if (!ResolveName(name)) {
499 createDummyProcSymbol(name);
500 }
501 }
502 }
503 if (const auto *procRef{
504 parser::Unwrap<parser::ProcComponentRef>(procD->u)}) {
505 if (!procRef->v.thing.component.symbol) {
506 if (!ResolveName(&procRef->v.thing.component)) {
507 createDummyProcSymbol(&procRef->v.thing.component);
508 }
509 }
510 }
511 }
512 const auto &objList{std::get<parser::OmpObjectList>(x.v.t)};
513 ResolveOmpObjectList(objList, Symbol::Flag::OmpReduction);
514 return false;
515 }
516
517 bool Pre(const parser::OmpAlignedClause &x) {
518 const auto &alignedNameList{std::get<parser::OmpObjectList>(x.t)};
519 ResolveOmpObjectList(alignedNameList, Symbol::Flag::OmpAligned);
520 return false;
521 }
522
523 bool Pre(const parser::OmpClause::Nontemporal &x) {
524 const auto &nontemporalNameList{x.v};
525 ResolveOmpNameList(nontemporalNameList, Symbol::Flag::OmpNontemporal);
526 return false;
527 }
528
529 bool Pre(const parser::OmpDependClause &x) {
530 if (const auto *dependSink{
531 std::get_if<parser::OmpDependClause::Sink>(&x.u)}) {
532 const auto &dependSinkVec{dependSink->v};
533 for (const auto &dependSinkElement : dependSinkVec) {
534 const auto &name{std::get<parser::Name>(dependSinkElement.t)};
535 ResolveName(&name);
536 }
537 }
538 return false;
539 }
540
541 bool Pre(const parser::OmpClause::UseDevicePtr &x) {
542 ResolveOmpObjectList(x.v, Symbol::Flag::OmpUseDevicePtr);
543 return false;
544 }
545
546 bool Pre(const parser::OmpClause::UseDeviceAddr &x) {
547 ResolveOmpObjectList(x.v, Symbol::Flag::OmpUseDeviceAddr);
548 return false;
549 }
550
551 bool Pre(const parser::OmpClause::IsDevicePtr &x) {
552 ResolveOmpObjectList(x.v, Symbol::Flag::OmpIsDevicePtr);
553 return false;
554 }
555
556 bool Pre(const parser::OmpClause::HasDeviceAddr &x) {
557 ResolveOmpObjectList(x.v, Symbol::Flag::OmpHasDeviceAddr);
558 return false;
559 }
560
561 void Post(const parser::Name &);
562
563 // Keep track of labels in the statements that causes jumps to target labels
564 void Post(const parser::GotoStmt &gotoStmt) { CheckSourceLabel(gotoStmt.v); }
565 void Post(const parser::ComputedGotoStmt &computedGotoStmt) {
566 for (auto &label : std::get<std::list<parser::Label>>(computedGotoStmt.t)) {
567 CheckSourceLabel(label);
568 }
569 }
570 void Post(const parser::ArithmeticIfStmt &arithmeticIfStmt) {
571 CheckSourceLabel(std::get<1>(arithmeticIfStmt.t));
572 CheckSourceLabel(std::get<2>(arithmeticIfStmt.t));
573 CheckSourceLabel(std::get<3>(arithmeticIfStmt.t));
574 }
575 void Post(const parser::AssignedGotoStmt &assignedGotoStmt) {
576 for (auto &label : std::get<std::list<parser::Label>>(assignedGotoStmt.t)) {
577 CheckSourceLabel(label);
578 }
579 }
580 void Post(const parser::AltReturnSpec &altReturnSpec) {
581 CheckSourceLabel(altReturnSpec.v);
582 }
583 void Post(const parser::ErrLabel &errLabel) { CheckSourceLabel(errLabel.v); }
584 void Post(const parser::EndLabel &endLabel) { CheckSourceLabel(endLabel.v); }
585 void Post(const parser::EorLabel &eorLabel) { CheckSourceLabel(eorLabel.v); }
586
587 void Post(const parser::OmpMapClause &x) {
588 Symbol::Flag ompFlag = Symbol::Flag::OmpMapToFrom;
589 if (const auto &maptype{std::get<std::optional<parser::OmpMapType>>(x.t)}) {
590 using Type = parser::OmpMapType::Type;
591 const Type &type{std::get<Type>(maptype->t)};
592 switch (type) {
593 case Type::To:
594 ompFlag = Symbol::Flag::OmpMapTo;
595 break;
596 case Type::From:
597 ompFlag = Symbol::Flag::OmpMapFrom;
598 break;
599 case Type::Tofrom:
600 ompFlag = Symbol::Flag::OmpMapToFrom;
601 break;
602 case Type::Alloc:
603 ompFlag = Symbol::Flag::OmpMapAlloc;
604 break;
605 case Type::Release:
606 ompFlag = Symbol::Flag::OmpMapRelease;
607 break;
608 case Type::Delete:
609 ompFlag = Symbol::Flag::OmpMapDelete;
610 break;
611 }
612 }
613 const auto &ompObjList{std::get<parser::OmpObjectList>(x.t)};
614 for (const auto &ompObj : ompObjList.v) {
615 common::visit(
616 common::visitors{
617 [&](const parser::Designator &designator) {
618 if (const auto *name{
619 semantics::getDesignatorNameIfDataRef(designator)}) {
620 if (name->symbol) {
621 name->symbol->set(ompFlag);
622 AddToContextObjectWithDSA(*name->symbol, ompFlag);
623 }
624 if (name->symbol &&
625 semantics::IsAssumedSizeArray(*name->symbol)) {
626 context_.Say(designator.source,
627 "Assumed-size whole arrays may not appear on the %s "
628 "clause"_err_en_US,
629 "MAP");
630 }
631 }
632 },
633 [&](const auto &name) {},
634 },
635 ompObj.u);
636
637 ResolveOmpObject(ompObj, ompFlag);
638 }
639 }
640
641 const parser::OmpClause *associatedClause{nullptr};
642 void SetAssociatedClause(const parser::OmpClause &c) {
643 associatedClause = &c;
644 }
645 const parser::OmpClause *GetAssociatedClause() { return associatedClause; }
646
647 private:
648 std::int64_t GetAssociatedLoopLevelFromClauses(const parser::OmpClauseList &);
649
650 Symbol::Flags dataSharingAttributeFlags{Symbol::Flag::OmpShared,
651 Symbol::Flag::OmpPrivate, Symbol::Flag::OmpFirstPrivate,
652 Symbol::Flag::OmpLastPrivate, Symbol::Flag::OmpReduction,
653 Symbol::Flag::OmpLinear};
654
655 Symbol::Flags privateDataSharingAttributeFlags{Symbol::Flag::OmpPrivate,
656 Symbol::Flag::OmpFirstPrivate, Symbol::Flag::OmpLastPrivate};
657
658 Symbol::Flags ompFlagsRequireNewSymbol{Symbol::Flag::OmpPrivate,
659 Symbol::Flag::OmpLinear, Symbol::Flag::OmpFirstPrivate,
660 Symbol::Flag::OmpLastPrivate, Symbol::Flag::OmpReduction,
661 Symbol::Flag::OmpCriticalLock, Symbol::Flag::OmpCopyIn,
662 Symbol::Flag::OmpUseDevicePtr, Symbol::Flag::OmpUseDeviceAddr,
663 Symbol::Flag::OmpIsDevicePtr, Symbol::Flag::OmpHasDeviceAddr};
664
665 Symbol::Flags ompFlagsRequireMark{
666 Symbol::Flag::OmpThreadprivate, Symbol::Flag::OmpDeclareTarget};
667
668 Symbol::Flags dataCopyingAttributeFlags{
669 Symbol::Flag::OmpCopyIn, Symbol::Flag::OmpCopyPrivate};
670
671 std::vector<const parser::Name *> allocateNames_; // on one directive
672 UnorderedSymbolSet privateDataSharingAttributeObjects_; // on one directive
673 UnorderedSymbolSet stmtFunctionExprSymbols_;
674 std::multimap<const parser::Label,
675 std::pair<parser::CharBlock, std::optional<DirContext>>>
676 sourceLabels_;
677 std::map<const parser::Label,
678 std::pair<parser::CharBlock, std::optional<DirContext>>>
679 targetLabels_;
680 parser::CharBlock currentStatementSource_;
681
682 void AddAllocateName(const parser::Name *&object) {
683 allocateNames_.push_back(object);
684 }
685 void ClearAllocateNames() { allocateNames_.clear(); }
686
687 void AddPrivateDataSharingAttributeObjects(SymbolRef object) {
688 privateDataSharingAttributeObjects_.insert(object);
689 }
690 void ClearPrivateDataSharingAttributeObjects() {
691 privateDataSharingAttributeObjects_.clear();
692 }
693
694 // Predetermined DSA rules
695 void PrivatizeAssociatedLoopIndexAndCheckLoopLevel(
696 const parser::OpenMPLoopConstruct &);
697 void ResolveSeqLoopIndexInParallelOrTaskConstruct(const parser::Name &);
698
699 bool IsNestedInDirective(llvm::omp::Directive directive);
700 void ResolveOmpObjectList(const parser::OmpObjectList &, Symbol::Flag);
701 void ResolveOmpObject(const parser::OmpObject &, Symbol::Flag);
702 Symbol *ResolveOmp(const parser::Name &, Symbol::Flag, Scope &);
703 Symbol *ResolveOmp(Symbol &, Symbol::Flag, Scope &);
704 Symbol *ResolveOmpCommonBlockName(const parser::Name *);
705 void ResolveOmpNameList(const std::list<parser::Name> &, Symbol::Flag);
706 void ResolveOmpName(const parser::Name &, Symbol::Flag);
707 Symbol *ResolveName(const parser::Name *);
708 Symbol *ResolveOmpObjectScope(const parser::Name *);
709 Symbol *DeclareOrMarkOtherAccessEntity(const parser::Name &, Symbol::Flag);
710 Symbol *DeclareOrMarkOtherAccessEntity(Symbol &, Symbol::Flag);
711 void CheckMultipleAppearances(
712 const parser::Name &, const Symbol &, Symbol::Flag);
713
714 void CheckDataCopyingClause(
715 const parser::Name &, const Symbol &, Symbol::Flag);
716 void CheckAssocLoopLevel(std::int64_t level, const parser::OmpClause *clause);
717 void CheckObjectInNamelist(
718 const parser::Name &, const Symbol &, Symbol::Flag);
719 void CheckSourceLabel(const parser::Label &);
720 void CheckLabelContext(const parser::CharBlock, const parser::CharBlock,
721 std::optional<DirContext>, std::optional<DirContext>);
722 void ClearLabels() {
723 sourceLabels_.clear();
724 targetLabels_.clear();
725 };
726 void CheckAllNamesInAllocateStmt(const parser::CharBlock &source,
727 const parser::OmpObjectList &ompObjectList,
728 const parser::AllocateStmt &allocate);
729 void CheckNameInAllocateStmt(const parser::CharBlock &source,
730 const parser::Name &ompObject, const parser::AllocateStmt &allocate);
731
732 bool HasSymbolInEnclosingScope(const Symbol &, Scope &);
733 std::int64_t ordCollapseLevel{0};
734
735 void AddOmpRequiresToScope(Scope &, WithOmpDeclarative::RequiresFlags,
736 std::optional<common::OmpAtomicDefaultMemOrderType>);
737 };
738
739 template <typename T>
740 bool DirectiveAttributeVisitor<T>::HasDataSharingAttributeObject(
741 const Symbol &object) {
742 auto it{dataSharingAttributeObjects_.find(object)};
743 return it != dataSharingAttributeObjects_.end();
744 }
745
746 template <typename T>
747 const parser::Name *DirectiveAttributeVisitor<T>::GetLoopIndex(
748 const parser::DoConstruct &x) {
749 using Bounds = parser::LoopControl::Bounds;
750 if (x.GetLoopControl()) {
751 if (const Bounds * b{std::get_if<Bounds>(&x.GetLoopControl()->u)}) {
752 return &b->name.thing;
753 } else {
754 return nullptr;
755 }
756 } else {
757 context_
758 .Say(std::get<parser::Statement<parser::NonLabelDoStmt>>(x.t).source,
759 "Loop control is not present in the DO LOOP"_err_en_US)
760 .Attach(GetContext().directiveSource,
761 "associated with the enclosing LOOP construct"_en_US);
762 return nullptr;
763 }
764 }
765
766 template <typename T>
767 const parser::DoConstruct *DirectiveAttributeVisitor<T>::GetDoConstructIf(
768 const parser::ExecutionPartConstruct &x) {
769 return parser::Unwrap<parser::DoConstruct>(x);
770 }
771
772 template <typename T>
773 Symbol *DirectiveAttributeVisitor<T>::DeclarePrivateAccessEntity(
774 const parser::Name &name, Symbol::Flag flag, Scope &scope) {
775 if (!name.symbol) {
776 return nullptr; // not resolved by Name Resolution step, do nothing
777 }
778 name.symbol = DeclarePrivateAccessEntity(*name.symbol, flag, scope);
779 return name.symbol;
780 }
781
782 template <typename T>
783 Symbol *DirectiveAttributeVisitor<T>::DeclarePrivateAccessEntity(
784 Symbol &object, Symbol::Flag flag, Scope &scope) {
785 if (object.owner() != currScope()) {
786 auto &symbol{MakeAssocSymbol(object.name(), object, scope)};
787 symbol.set(flag);
788 if (flag == Symbol::Flag::OmpCopyIn) {
789 // The symbol in copyin clause must be threadprivate entity.
790 symbol.set(Symbol::Flag::OmpThreadprivate);
791 }
792 return &symbol;
793 } else {
794 object.set(flag);
795 return &object;
796 }
797 }
798
799 bool AccAttributeVisitor::Pre(const parser::OpenACCBlockConstruct &x) {
800 const auto &beginBlockDir{std::get<parser::AccBeginBlockDirective>(x.t)};
801 const auto &blockDir{std::get<parser::AccBlockDirective>(beginBlockDir.t)};
802 switch (blockDir.v) {
803 case llvm::acc::Directive::ACCD_data:
804 case llvm::acc::Directive::ACCD_host_data:
805 case llvm::acc::Directive::ACCD_kernels:
806 case llvm::acc::Directive::ACCD_parallel:
807 case llvm::acc::Directive::ACCD_serial:
808 PushContext(blockDir.source, blockDir.v);
809 break;
810 default:
811 break;
812 }
813 ClearDataSharingAttributeObjects();
814 return true;
815 }
816
817 bool AccAttributeVisitor::Pre(const parser::OpenACCDeclarativeConstruct &x) {
818 if (const auto *declConstruct{
819 std::get_if<parser::OpenACCStandaloneDeclarativeConstruct>(&x.u)}) {
820 const auto &declDir{
821 std::get<parser::AccDeclarativeDirective>(declConstruct->t)};
822 PushContext(declDir.source, llvm::acc::Directive::ACCD_declare);
823 }
824 ClearDataSharingAttributeObjects();
825 return true;
826 }
827
828 static const parser::AccObjectList &GetAccObjectList(
829 const parser::AccClause &clause) {
830 if (const auto *copyClause =
831 std::get_if<Fortran::parser::AccClause::Copy>(&clause.u)) {
832 return copyClause->v;
833 } else if (const auto *createClause =
834 std::get_if<Fortran::parser::AccClause::Create>(&clause.u)) {
835 const Fortran::parser::AccObjectListWithModifier &listWithModifier =
836 createClause->v;
837 const Fortran::parser::AccObjectList &accObjectList =
838 std::get<Fortran::parser::AccObjectList>(listWithModifier.t);
839 return accObjectList;
840 } else if (const auto *copyinClause =
841 std::get_if<Fortran::parser::AccClause::Copyin>(&clause.u)) {
842 const Fortran::parser::AccObjectListWithModifier &listWithModifier =
843 copyinClause->v;
844 const Fortran::parser::AccObjectList &accObjectList =
845 std::get<Fortran::parser::AccObjectList>(listWithModifier.t);
846 return accObjectList;
847 } else if (const auto *copyoutClause =
848 std::get_if<Fortran::parser::AccClause::Copyout>(&clause.u)) {
849 const Fortran::parser::AccObjectListWithModifier &listWithModifier =
850 copyoutClause->v;
851 const Fortran::parser::AccObjectList &accObjectList =
852 std::get<Fortran::parser::AccObjectList>(listWithModifier.t);
853 return accObjectList;
854 } else if (const auto *presentClause =
855 std::get_if<Fortran::parser::AccClause::Present>(&clause.u)) {
856 return presentClause->v;
857 } else if (const auto *deviceptrClause =
858 std::get_if<Fortran::parser::AccClause::Deviceptr>(
859 &clause.u)) {
860 return deviceptrClause->v;
861 } else if (const auto *deviceResidentClause =
862 std::get_if<Fortran::parser::AccClause::DeviceResident>(
863 &clause.u)) {
864 return deviceResidentClause->v;
865 } else if (const auto *linkClause =
866 std::get_if<Fortran::parser::AccClause::Link>(&clause.u)) {
867 return linkClause->v;
868 } else {
869 llvm_unreachable("Clause without object list!");
870 }
871 }
872
873 void AccAttributeVisitor::Post(
874 const parser::OpenACCStandaloneDeclarativeConstruct &x) {
875 const auto &clauseList = std::get<parser::AccClauseList>(x.t);
876 for (const auto &clause : clauseList.v) {
877 // Restriction - line 2414
878 DoNotAllowAssumedSizedArray(GetAccObjectList(clause));
879 }
880 }
881
882 bool AccAttributeVisitor::Pre(const parser::OpenACCLoopConstruct &x) {
883 const auto &beginDir{std::get<parser::AccBeginLoopDirective>(x.t)};
884 const auto &loopDir{std::get<parser::AccLoopDirective>(beginDir.t)};
885 const auto &clauseList{std::get<parser::AccClauseList>(beginDir.t)};
886 if (loopDir.v == llvm::acc::Directive::ACCD_loop) {
887 PushContext(loopDir.source, loopDir.v);
888 }
889 ClearDataSharingAttributeObjects();
890 SetContextAssociatedLoopLevel(GetAssociatedLoopLevelFromClauses(clauseList));
891 const auto &outer{std::get<std::optional<parser::DoConstruct>>(x.t)};
892 CheckAssociatedLoop(*outer);
893 return true;
894 }
895
896 bool AccAttributeVisitor::Pre(const parser::OpenACCStandaloneConstruct &x) {
897 const auto &standaloneDir{std::get<parser::AccStandaloneDirective>(x.t)};
898 switch (standaloneDir.v) {
899 case llvm::acc::Directive::ACCD_enter_data:
900 case llvm::acc::Directive::ACCD_exit_data:
901 case llvm::acc::Directive::ACCD_init:
902 case llvm::acc::Directive::ACCD_set:
903 case llvm::acc::Directive::ACCD_shutdown:
904 case llvm::acc::Directive::ACCD_update:
905 PushContext(standaloneDir.source, standaloneDir.v);
906 break;
907 default:
908 break;
909 }
910 ClearDataSharingAttributeObjects();
911 return true;
912 }
913
914 Symbol *AccAttributeVisitor::ResolveName(
915 const parser::Name &name, bool parentScope) {
916 Symbol *prev{currScope().FindSymbol(name.source)};
917 // Check in parent scope if asked for.
918 if (!prev && parentScope) {
919 prev = currScope().parent().FindSymbol(name.source);
920 }
921 if (prev != name.symbol) {
922 name.symbol = prev;
923 }
924 return prev;
925 }
926
927 Symbol *AccAttributeVisitor::ResolveFctName(const parser::Name &name) {
928 Symbol *prev{currScope().FindSymbol(name.source)};
929 if (!prev || (prev && prev->IsFuncResult())) {
930 prev = currScope().parent().FindSymbol(name.source);
931 if (!prev) {
932 prev = &context_.globalScope().MakeSymbol(
933 name.source, Attrs{}, ProcEntityDetails{});
934 }
935 }
936 if (prev != name.symbol) {
937 name.symbol = prev;
938 }
939 return prev;
940 }
941
942 template <typename T>
943 common::IfNoLvalue<T, T> FoldExpr(
944 evaluate::FoldingContext &foldingContext, T &&expr) {
945 return evaluate::Fold(foldingContext, std::move(expr));
946 }
947
948 template <typename T>
949 MaybeExpr EvaluateExpr(
950 Fortran::semantics::SemanticsContext &semanticsContext, const T &expr) {
951 return FoldExpr(
952 semanticsContext.foldingContext(), AnalyzeExpr(semanticsContext, expr));
953 }
954
955 void AccAttributeVisitor::AddRoutineInfoToSymbol(
956 Symbol &symbol, const parser::OpenACCRoutineConstruct &x) {
957 if (symbol.has<SubprogramDetails>()) {
958 Fortran::semantics::OpenACCRoutineInfo info;
959 const auto &clauses = std::get<Fortran::parser::AccClauseList>(x.t);
960 for (const Fortran::parser::AccClause &clause : clauses.v) {
961 if (std::get_if<Fortran::parser::AccClause::Seq>(&clause.u)) {
962 if (info.deviceTypeInfos().empty()) {
963 info.set_isSeq();
964 } else {
965 info.deviceTypeInfos().back().set_isSeq();
966 }
967 } else if (const auto *gangClause =
968 std::get_if<Fortran::parser::AccClause::Gang>(&clause.u)) {
969 if (info.deviceTypeInfos().empty()) {
970 info.set_isGang();
971 } else {
972 info.deviceTypeInfos().back().set_isGang();
973 }
974 if (gangClause->v) {
975 const Fortran::parser::AccGangArgList &x = *gangClause->v;
976 for (const Fortran::parser::AccGangArg &gangArg : x.v) {
977 if (const auto *dim =
978 std::get_if<Fortran::parser::AccGangArg::Dim>(&gangArg.u)) {
979 if (const auto v{EvaluateInt64(context_, dim->v)}) {
980 if (info.deviceTypeInfos().empty()) {
981 info.set_gangDim(*v);
982 } else {
983 info.deviceTypeInfos().back().set_gangDim(*v);
984 }
985 }
986 }
987 }
988 }
989 } else if (std::get_if<Fortran::parser::AccClause::Vector>(&clause.u)) {
990 if (info.deviceTypeInfos().empty()) {
991 info.set_isVector();
992 } else {
993 info.deviceTypeInfos().back().set_isVector();
994 }
995 } else if (std::get_if<Fortran::parser::AccClause::Worker>(&clause.u)) {
996 if (info.deviceTypeInfos().empty()) {
997 info.set_isWorker();
998 } else {
999 info.deviceTypeInfos().back().set_isWorker();
1000 }
1001 } else if (std::get_if<Fortran::parser::AccClause::Nohost>(&clause.u)) {
1002 info.set_isNohost();
1003 } else if (const auto *bindClause =
1004 std::get_if<Fortran::parser::AccClause::Bind>(&clause.u)) {
1005 if (const auto *name =
1006 std::get_if<Fortran::parser::Name>(&bindClause->v.u)) {
1007 if (Symbol *sym = ResolveFctName(*name)) {
1008 if (info.deviceTypeInfos().empty()) {
1009 info.set_bindName(sym->name().ToString());
1010 } else {
1011 info.deviceTypeInfos().back().set_bindName(
1012 sym->name().ToString());
1013 }
1014 } else {
1015 context_.Say((*name).source,
1016 "No function or subroutine declared for '%s'"_err_en_US,
1017 (*name).source);
1018 }
1019 } else if (const auto charExpr =
1020 std::get_if<Fortran::parser::ScalarDefaultCharExpr>(
1021 &bindClause->v.u)) {
1022 auto *charConst =
1023 Fortran::parser::Unwrap<Fortran::parser::CharLiteralConstant>(
1024 *charExpr);
1025 std::string str{std::get<std::string>(charConst->t)};
1026 std::stringstream bindName;
1027 bindName << "\"" << str << "\"";
1028 if (info.deviceTypeInfos().empty()) {
1029 info.set_bindName(bindName.str());
1030 } else {
1031 info.deviceTypeInfos().back().set_bindName(bindName.str());
1032 }
1033 }
1034 } else if (const auto *dType =
1035 std::get_if<Fortran::parser::AccClause::DeviceType>(
1036 &clause.u)) {
1037 const parser::AccDeviceTypeExprList &deviceTypeExprList = dType->v;
1038 OpenACCRoutineDeviceTypeInfo dtypeInfo;
1039 dtypeInfo.set_dType(deviceTypeExprList.v.front().v);
1040 info.add_deviceTypeInfo(dtypeInfo);
1041 }
1042 }
1043 symbol.get<SubprogramDetails>().add_openACCRoutineInfo(info);
1044 }
1045 }
1046
1047 bool AccAttributeVisitor::Pre(const parser::OpenACCRoutineConstruct &x) {
1048 const auto &verbatim{std::get<parser::Verbatim>(x.t)};
1049 if (topScope_) {
1050 PushContext(
1051 verbatim.source, llvm::acc::Directive::ACCD_routine, *topScope_);
1052 } else {
1053 PushContext(verbatim.source, llvm::acc::Directive::ACCD_routine);
1054 }
1055 const auto &optName{std::get<std::optional<parser::Name>>(x.t)};
1056 if (optName) {
1057 if (Symbol *sym = ResolveFctName(*optName)) {
1058 Symbol &ultimate{sym->GetUltimate()};
1059 AddRoutineInfoToSymbol(ultimate, x);
1060 } else {
1061 context_.Say((*optName).source,
1062 "No function or subroutine declared for '%s'"_err_en_US,
1063 (*optName).source);
1064 }
1065 } else {
1066 if (currScope().symbol()) {
1067 AddRoutineInfoToSymbol(*currScope().symbol(), x);
1068 }
1069 }
1070 return true;
1071 }
1072
1073 bool AccAttributeVisitor::Pre(const parser::AccBindClause &x) {
1074 if (const auto *name{std::get_if<parser::Name>(&x.u)}) {
1075 if (!ResolveFctName(*name)) {
1076 context_.Say(name->source,
1077 "No function or subroutine declared for '%s'"_err_en_US,
1078 name->source);
1079 }
1080 }
1081 return true;
1082 }
1083
1084 bool AccAttributeVisitor::Pre(const parser::OpenACCCombinedConstruct &x) {
1085 const auto &beginBlockDir{std::get<parser::AccBeginCombinedDirective>(x.t)};
1086 const auto &combinedDir{
1087 std::get<parser::AccCombinedDirective>(beginBlockDir.t)};
1088 switch (combinedDir.v) {
1089 case llvm::acc::Directive::ACCD_kernels_loop:
1090 case llvm::acc::Directive::ACCD_parallel_loop:
1091 case llvm::acc::Directive::ACCD_serial_loop:
1092 PushContext(combinedDir.source, combinedDir.v);
1093 break;
1094 default:
1095 break;
1096 }
1097 const auto &clauseList{std::get<parser::AccClauseList>(beginBlockDir.t)};
1098 SetContextAssociatedLoopLevel(GetAssociatedLoopLevelFromClauses(clauseList));
1099 const auto &outer{std::get<std::optional<parser::DoConstruct>>(x.t)};
1100 CheckAssociatedLoop(*outer);
1101 ClearDataSharingAttributeObjects();
1102 return true;
1103 }
1104
1105 static bool IsLastNameArray(const parser::Designator &designator) {
1106 const auto &name{GetLastName(designator)};
1107 const evaluate::DataRef dataRef{*(name.symbol)};
1108 return common::visit(
1109 common::visitors{
1110 [](const evaluate::SymbolRef &ref) {
1111 return ref->Rank() > 0 ||
1112 ref->GetType()->category() == DeclTypeSpec::Numeric;
1113 },
1114 [](const evaluate::ArrayRef &aref) {
1115 return aref.base().IsSymbol() ||
1116 aref.base().GetComponent().base().Rank() == 0;
1117 },
1118 [](const auto &) { return false; },
1119 },
1120 dataRef.u);
1121 }
1122
1123 void AccAttributeVisitor::AllowOnlyArrayAndSubArray(
1124 const parser::AccObjectList &objectList) {
1125 for (const auto &accObject : objectList.v) {
1126 common::visit(
1127 common::visitors{
1128 [&](const parser::Designator &designator) {
1129 if (!IsLastNameArray(designator)) {
1130 context_.Say(designator.source,
1131 "Only array element or subarray are allowed in %s directive"_err_en_US,
1132 parser::ToUpperCaseLetters(
1133 llvm::acc::getOpenACCDirectiveName(
1134 GetContext().directive)
1135 .str()));
1136 }
1137 },
1138 [&](const auto &name) {
1139 context_.Say(name.source,
1140 "Only array element or subarray are allowed in %s directive"_err_en_US,
1141 parser::ToUpperCaseLetters(
1142 llvm::acc::getOpenACCDirectiveName(GetContext().directive)
1143 .str()));
1144 },
1145 },
1146 accObject.u);
1147 }
1148 }
1149
1150 void AccAttributeVisitor::DoNotAllowAssumedSizedArray(
1151 const parser::AccObjectList &objectList) {
1152 for (const auto &accObject : objectList.v) {
1153 common::visit(
1154 common::visitors{
1155 [&](const parser::Designator &designator) {
1156 const auto &name{GetLastName(designator)};
1157 if (name.symbol && semantics::IsAssumedSizeArray(*name.symbol)) {
1158 context_.Say(designator.source,
1159 "Assumed-size dummy arrays may not appear on the %s "
1160 "directive"_err_en_US,
1161 parser::ToUpperCaseLetters(
1162 llvm::acc::getOpenACCDirectiveName(
1163 GetContext().directive)
1164 .str()));
1165 }
1166 },
1167 [&](const auto &name) {
1168
1169 },
1170 },
1171 accObject.u);
1172 }
1173 }
1174
1175 void AccAttributeVisitor::AllowOnlyVariable(const parser::AccObject &object) {
1176 common::visit(
1177 common::visitors{
1178 [&](const parser::Designator &designator) {
1179 const auto &name{GetLastName(designator)};
1180 if (name.symbol && !semantics::IsVariableName(*name.symbol) &&
1181 !semantics::IsNamedConstant(*name.symbol)) {
1182 context_.Say(designator.source,
1183 "Only variables are allowed in data clauses on the %s "
1184 "directive"_err_en_US,
1185 parser::ToUpperCaseLetters(
1186 llvm::acc::getOpenACCDirectiveName(GetContext().directive)
1187 .str()));
1188 }
1189 },
1190 [&](const auto &name) {},
1191 },
1192 object.u);
1193 }
1194
1195 bool AccAttributeVisitor::Pre(const parser::OpenACCCacheConstruct &x) {
1196 const auto &verbatim{std::get<parser::Verbatim>(x.t)};
1197 PushContext(verbatim.source, llvm::acc::Directive::ACCD_cache);
1198 ClearDataSharingAttributeObjects();
1199
1200 const auto &objectListWithModifier =
1201 std::get<parser::AccObjectListWithModifier>(x.t);
1202 const auto &objectList =
1203 std::get<Fortran::parser::AccObjectList>(objectListWithModifier.t);
1204
1205 // 2.10 Cache directive restriction: A var in a cache directive must be a
1206 // single array element or a simple subarray.
1207 AllowOnlyArrayAndSubArray(objectList);
1208
1209 return true;
1210 }
1211
1212 std::int64_t AccAttributeVisitor::GetAssociatedLoopLevelFromClauses(
1213 const parser::AccClauseList &x) {
1214 std::int64_t collapseLevel{0};
1215 for (const auto &clause : x.v) {
1216 if (const auto *collapseClause{
1217 std::get_if<parser::AccClause::Collapse>(&clause.u)}) {
1218 const parser::AccCollapseArg &arg = collapseClause->v;
1219 const auto &collapseValue{std::get<parser::ScalarIntConstantExpr>(arg.t)};
1220 if (const auto v{EvaluateInt64(context_, collapseValue)}) {
1221 collapseLevel = *v;
1222 }
1223 }
1224 }
1225
1226 if (collapseLevel) {
1227 return collapseLevel;
1228 }
1229 return 1; // default is outermost loop
1230 }
1231
1232 void AccAttributeVisitor::CheckAssociatedLoop(
1233 const parser::DoConstruct &outerDoConstruct) {
1234 std::int64_t level{GetContext().associatedLoopLevel};
1235 if (level <= 0) { // collapse value was negative or 0
1236 return;
1237 }
1238
1239 const auto getNextDoConstruct =
1240 [this](const parser::Block &block,
1241 std::int64_t &level) -> const parser::DoConstruct * {
1242 for (const auto &entry : block) {
1243 if (const auto *doConstruct = GetDoConstructIf(entry)) {
1244 return doConstruct;
1245 } else if (parser::Unwrap<parser::CompilerDirective>(entry)) {
1246 // It is allowed to have a compiler directive associated with the loop.
1247 continue;
1248 } else if (const auto &accLoop{
1249 parser::Unwrap<parser::OpenACCLoopConstruct>(entry)}) {
1250 if (level == 0)
1251 break;
1252 const auto &beginDir{
1253 std::get<parser::AccBeginLoopDirective>(accLoop->t)};
1254 context_.Say(beginDir.source,
1255 "LOOP directive not expected in COLLAPSE loop nest"_err_en_US);
1256 level = 0;
1257 } else {
1258 break;
1259 }
1260 }
1261 return nullptr;
1262 };
1263
1264 auto checkExprHasSymbols = [&](llvm::SmallVector<Symbol *> &ivs,
1265 semantics::UnorderedSymbolSet &symbols) {
1266 for (auto iv : ivs) {
1267 if (symbols.count(*iv) != 0) {
1268 context_.Say(GetContext().directiveSource,
1269 "Trip count must be computable and invariant"_err_en_US);
1270 }
1271 }
1272 };
1273
1274 Symbol::Flag flag = Symbol::Flag::AccPrivate;
1275 llvm::SmallVector<Symbol *> ivs;
1276 using Bounds = parser::LoopControl::Bounds;
1277 for (const parser::DoConstruct *loop{&outerDoConstruct}; loop && level > 0;) {
1278 // Go through all nested loops to ensure index variable exists.
1279 if (const parser::Name * ivName{GetLoopIndex(*loop)}) {
1280 if (auto *symbol{ResolveAcc(*ivName, flag, currScope())}) {
1281 if (auto &control{loop->GetLoopControl()}) {
1282 if (const Bounds * b{std::get_if<Bounds>(&control->u)}) {
1283 if (auto lowerExpr{semantics::AnalyzeExpr(context_, b->lower)}) {
1284 semantics::UnorderedSymbolSet lowerSyms =
1285 evaluate::CollectSymbols(*lowerExpr);
1286 checkExprHasSymbols(ivs, lowerSyms);
1287 }
1288 if (auto upperExpr{semantics::AnalyzeExpr(context_, b->upper)}) {
1289 semantics::UnorderedSymbolSet upperSyms =
1290 evaluate::CollectSymbols(*upperExpr);
1291 checkExprHasSymbols(ivs, upperSyms);
1292 }
1293 }
1294 }
1295 ivs.push_back(symbol);
1296 }
1297 }
1298
1299 const auto &block{std::get<parser::Block>(loop->t)};
1300 --level;
1301 loop = getNextDoConstruct(block, level);
1302 }
1303 CHECK(level == 0);
1304 }
1305
1306 void AccAttributeVisitor::EnsureAllocatableOrPointer(
1307 const llvm::acc::Clause clause, const parser::AccObjectList &objectList) {
1308 for (const auto &accObject : objectList.v) {
1309 common::visit(
1310 common::visitors{
1311 [&](const parser::Designator &designator) {
1312 const auto &lastName{GetLastName(designator)};
1313 if (!IsAllocatableOrObjectPointer(lastName.symbol)) {
1314 context_.Say(designator.source,
1315 "Argument `%s` on the %s clause must be a variable or "
1316 "array with the POINTER or ALLOCATABLE attribute"_err_en_US,
1317 lastName.symbol->name(),
1318 parser::ToUpperCaseLetters(
1319 llvm::acc::getOpenACCClauseName(clause).str()));
1320 }
1321 },
1322 [&](const auto &name) {
1323 context_.Say(name.source,
1324 "Argument on the %s clause must be a variable or "
1325 "array with the POINTER or ALLOCATABLE attribute"_err_en_US,
1326 parser::ToUpperCaseLetters(
1327 llvm::acc::getOpenACCClauseName(clause).str()));
1328 },
1329 },
1330 accObject.u);
1331 }
1332 }
1333
1334 bool AccAttributeVisitor::Pre(const parser::AccClause::Attach &x) {
1335 // Restriction - line 1708-1709
1336 EnsureAllocatableOrPointer(llvm::acc::Clause::ACCC_attach, x.v);
1337 return true;
1338 }
1339
1340 bool AccAttributeVisitor::Pre(const parser::AccClause::Detach &x) {
1341 // Restriction - line 1715-1717
1342 EnsureAllocatableOrPointer(llvm::acc::Clause::ACCC_detach, x.v);
1343 return true;
1344 }
1345
1346 void AccAttributeVisitor::Post(const parser::AccDefaultClause &x) {
1347 if (!dirContext_.empty()) {
1348 switch (x.v) {
1349 case llvm::acc::DefaultValue::ACC_Default_present:
1350 SetContextDefaultDSA(Symbol::Flag::AccPresent);
1351 break;
1352 case llvm::acc::DefaultValue::ACC_Default_none:
1353 SetContextDefaultDSA(Symbol::Flag::AccNone);
1354 break;
1355 }
1356 }
1357 }
1358
1359 // For OpenACC constructs, check all the data-refs within the constructs
1360 // and adjust the symbol for each Name if necessary
1361 void AccAttributeVisitor::Post(const parser::Name &name) {
1362 auto *symbol{name.symbol};
1363 if (symbol && !dirContext_.empty() && GetContext().withinConstruct) {
1364 if (!symbol->owner().IsDerivedType() && !symbol->has<ProcEntityDetails>() &&
1365 !symbol->has<SubprogramDetails>() && !IsObjectWithDSA(*symbol)) {
1366 if (Symbol * found{currScope().FindSymbol(name.source)}) {
1367 if (symbol != found) {
1368 name.symbol = found; // adjust the symbol within region
1369 } else if (GetContext().defaultDSA == Symbol::Flag::AccNone) {
1370 // 2.5.14.
1371 context_.Say(name.source,
1372 "The DEFAULT(NONE) clause requires that '%s' must be listed in "
1373 "a data-mapping clause"_err_en_US,
1374 symbol->name());
1375 }
1376 }
1377 }
1378 } // within OpenACC construct
1379 }
1380
1381 Symbol *AccAttributeVisitor::ResolveAccCommonBlockName(
1382 const parser::Name *name) {
1383 if (auto *prev{name
1384 ? GetContext().scope.parent().FindCommonBlock(name->source)
1385 : nullptr}) {
1386 name->symbol = prev;
1387 return prev;
1388 }
1389 // Check if the Common Block is declared in the current scope
1390 if (auto *commonBlockSymbol{
1391 name ? GetContext().scope.FindCommonBlock(name->source) : nullptr}) {
1392 name->symbol = commonBlockSymbol;
1393 return commonBlockSymbol;
1394 }
1395 return nullptr;
1396 }
1397
1398 void AccAttributeVisitor::ResolveAccObjectList(
1399 const parser::AccObjectList &accObjectList, Symbol::Flag accFlag) {
1400 for (const auto &accObject : accObjectList.v) {
1401 AllowOnlyVariable(accObject);
1402 ResolveAccObject(accObject, accFlag);
1403 }
1404 }
1405
1406 void AccAttributeVisitor::ResolveAccObject(
1407 const parser::AccObject &accObject, Symbol::Flag accFlag) {
1408 common::visit(
1409 common::visitors{
1410 [&](const parser::Designator &designator) {
1411 if (const auto *name{
1412 semantics::getDesignatorNameIfDataRef(designator)}) {
1413 if (auto *symbol{ResolveAcc(*name, accFlag, currScope())}) {
1414 AddToContextObjectWithDSA(*symbol, accFlag);
1415 if (dataSharingAttributeFlags.test(accFlag)) {
1416 CheckMultipleAppearances(*name, *symbol, accFlag);
1417 }
1418 }
1419 } else {
1420 // Array sections to be changed to substrings as needed
1421 if (AnalyzeExpr(context_, designator)) {
1422 if (std::holds_alternative<parser::Substring>(designator.u)) {
1423 context_.Say(designator.source,
1424 "Substrings are not allowed on OpenACC "
1425 "directives or clauses"_err_en_US);
1426 }
1427 }
1428 // other checks, more TBD
1429 }
1430 },
1431 [&](const parser::Name &name) { // common block
1432 if (auto *symbol{ResolveAccCommonBlockName(&name)}) {
1433 CheckMultipleAppearances(
1434 name, *symbol, Symbol::Flag::AccCommonBlock);
1435 for (auto &object : symbol->get<CommonBlockDetails>().objects()) {
1436 if (auto *resolvedObject{
1437 ResolveAcc(*object, accFlag, currScope())}) {
1438 AddToContextObjectWithDSA(*resolvedObject, accFlag);
1439 }
1440 }
1441 } else {
1442 context_.Say(name.source,
1443 "COMMON block must be declared in the same scoping unit "
1444 "in which the OpenACC directive or clause appears"_err_en_US);
1445 }
1446 },
1447 },
1448 accObject.u);
1449 }
1450
1451 Symbol *AccAttributeVisitor::ResolveAcc(
1452 const parser::Name &name, Symbol::Flag accFlag, Scope &scope) {
1453 return DeclareOrMarkOtherAccessEntity(name, accFlag);
1454 }
1455
1456 Symbol *AccAttributeVisitor::ResolveAcc(
1457 Symbol &symbol, Symbol::Flag accFlag, Scope &scope) {
1458 return DeclareOrMarkOtherAccessEntity(symbol, accFlag);
1459 }
1460
1461 Symbol *AccAttributeVisitor::DeclareOrMarkOtherAccessEntity(
1462 const parser::Name &name, Symbol::Flag accFlag) {
1463 Symbol *prev{currScope().FindSymbol(name.source)};
1464 if (!name.symbol || !prev) {
1465 return nullptr;
1466 } else if (prev != name.symbol) {
1467 name.symbol = prev;
1468 }
1469 return DeclareOrMarkOtherAccessEntity(*prev, accFlag);
1470 }
1471
1472 Symbol *AccAttributeVisitor::DeclareOrMarkOtherAccessEntity(
1473 Symbol &object, Symbol::Flag accFlag) {
1474 if (accFlagsRequireMark.test(accFlag)) {
1475 if (GetContext().directive == llvm::acc::ACCD_declare) {
1476 object.set(Symbol::Flag::AccDeclare);
1477 object.set(accFlag);
1478 }
1479 }
1480 return &object;
1481 }
1482
1483 static bool WithMultipleAppearancesAccException(
1484 const Symbol &symbol, Symbol::Flag flag) {
1485 return false; // Place holder
1486 }
1487
1488 void AccAttributeVisitor::CheckMultipleAppearances(
1489 const parser::Name &name, const Symbol &symbol, Symbol::Flag accFlag) {
1490 const auto *target{&symbol};
1491 if (HasDataSharingAttributeObject(*target) &&
1492 !WithMultipleAppearancesAccException(symbol, accFlag)) {
1493 context_.Say(name.source,
1494 "'%s' appears in more than one data-sharing clause "
1495 "on the same OpenACC directive"_err_en_US,
1496 name.ToString());
1497 } else {
1498 AddDataSharingAttributeObject(*target);
1499 }
1500 }
1501
1502 bool OmpAttributeVisitor::Pre(const parser::OpenMPBlockConstruct &x) {
1503 const auto &beginBlockDir{std::get<parser::OmpBeginBlockDirective>(x.t)};
1504 const auto &beginDir{std::get<parser::OmpBlockDirective>(beginBlockDir.t)};
1505 switch (beginDir.v) {
1506 case llvm::omp::Directive::OMPD_masked:
1507 case llvm::omp::Directive::OMPD_parallel_masked:
1508 case llvm::omp::Directive::OMPD_master:
1509 case llvm::omp::Directive::OMPD_ordered:
1510 case llvm::omp::Directive::OMPD_parallel:
1511 case llvm::omp::Directive::OMPD_single:
1512 case llvm::omp::Directive::OMPD_target:
1513 case llvm::omp::Directive::OMPD_target_data:
1514 case llvm::omp::Directive::OMPD_task:
1515 case llvm::omp::Directive::OMPD_taskgroup:
1516 case llvm::omp::Directive::OMPD_teams:
1517 case llvm::omp::Directive::OMPD_workshare:
1518 case llvm::omp::Directive::OMPD_parallel_workshare:
1519 case llvm::omp::Directive::OMPD_target_teams:
1520 case llvm::omp::Directive::OMPD_target_parallel:
1521 PushContext(beginDir.source, beginDir.v);
1522 break;
1523 default:
1524 // TODO others
1525 break;
1526 }
1527 ClearDataSharingAttributeObjects();
1528 ClearPrivateDataSharingAttributeObjects();
1529 ClearAllocateNames();
1530 return true;
1531 }
1532
1533 void OmpAttributeVisitor::Post(const parser::OpenMPBlockConstruct &x) {
1534 const auto &beginBlockDir{std::get<parser::OmpBeginBlockDirective>(x.t)};
1535 const auto &beginDir{std::get<parser::OmpBlockDirective>(beginBlockDir.t)};
1536 switch (beginDir.v) {
1537 case llvm::omp::Directive::OMPD_masked:
1538 case llvm::omp::Directive::OMPD_parallel_masked:
1539 case llvm::omp::Directive::OMPD_parallel:
1540 case llvm::omp::Directive::OMPD_single:
1541 case llvm::omp::Directive::OMPD_target:
1542 case llvm::omp::Directive::OMPD_task:
1543 case llvm::omp::Directive::OMPD_teams:
1544 case llvm::omp::Directive::OMPD_parallel_workshare:
1545 case llvm::omp::Directive::OMPD_target_teams:
1546 case llvm::omp::Directive::OMPD_target_parallel: {
1547 bool hasPrivate;
1548 for (const auto *allocName : allocateNames_) {
1549 hasPrivate = false;
1550 for (auto privateObj : privateDataSharingAttributeObjects_) {
1551 const Symbol &symbolPrivate{*privateObj};
1552 if (allocName->source == symbolPrivate.name()) {
1553 hasPrivate = true;
1554 break;
1555 }
1556 }
1557 if (!hasPrivate) {
1558 context_.Say(allocName->source,
1559 "The ALLOCATE clause requires that '%s' must be listed in a "
1560 "private "
1561 "data-sharing attribute clause on the same directive"_err_en_US,
1562 allocName->ToString());
1563 }
1564 }
1565 break;
1566 }
1567 default:
1568 break;
1569 }
1570 PopContext();
1571 }
1572
1573 bool OmpAttributeVisitor::Pre(
1574 const parser::OpenMPSimpleStandaloneConstruct &x) {
1575 const auto &standaloneDir{
1576 std::get<parser::OmpSimpleStandaloneDirective>(x.t)};
1577 switch (standaloneDir.v) {
1578 case llvm::omp::Directive::OMPD_barrier:
1579 case llvm::omp::Directive::OMPD_ordered:
1580 case llvm::omp::Directive::OMPD_target_enter_data:
1581 case llvm::omp::Directive::OMPD_target_exit_data:
1582 case llvm::omp::Directive::OMPD_target_update:
1583 case llvm::omp::Directive::OMPD_taskwait:
1584 case llvm::omp::Directive::OMPD_taskyield:
1585 PushContext(standaloneDir.source, standaloneDir.v);
1586 break;
1587 default:
1588 break;
1589 }
1590 ClearDataSharingAttributeObjects();
1591 return true;
1592 }
1593
1594 bool OmpAttributeVisitor::Pre(const parser::OpenMPLoopConstruct &x) {
1595 const auto &beginLoopDir{std::get<parser::OmpBeginLoopDirective>(x.t)};
1596 const auto &beginDir{std::get<parser::OmpLoopDirective>(beginLoopDir.t)};
1597 const auto &clauseList{std::get<parser::OmpClauseList>(beginLoopDir.t)};
1598 switch (beginDir.v) {
1599 case llvm::omp::Directive::OMPD_distribute:
1600 case llvm::omp::Directive::OMPD_distribute_parallel_do:
1601 case llvm::omp::Directive::OMPD_distribute_parallel_do_simd:
1602 case llvm::omp::Directive::OMPD_distribute_simd:
1603 case llvm::omp::Directive::OMPD_do:
1604 case llvm::omp::Directive::OMPD_do_simd:
1605 case llvm::omp::Directive::OMPD_loop:
1606 case llvm::omp::Directive::OMPD_masked_taskloop_simd:
1607 case llvm::omp::Directive::OMPD_masked_taskloop:
1608 case llvm::omp::Directive::OMPD_parallel_do:
1609 case llvm::omp::Directive::OMPD_parallel_do_simd:
1610 case llvm::omp::Directive::OMPD_parallel_masked_taskloop_simd:
1611 case llvm::omp::Directive::OMPD_parallel_masked_taskloop:
1612 case llvm::omp::Directive::OMPD_simd:
1613 case llvm::omp::Directive::OMPD_target_loop:
1614 case llvm::omp::Directive::OMPD_target_parallel_do:
1615 case llvm::omp::Directive::OMPD_target_parallel_do_simd:
1616 case llvm::omp::Directive::OMPD_target_parallel_loop:
1617 case llvm::omp::Directive::OMPD_target_teams_distribute:
1618 case llvm::omp::Directive::OMPD_target_teams_distribute_parallel_do:
1619 case llvm::omp::Directive::OMPD_target_teams_distribute_parallel_do_simd:
1620 case llvm::omp::Directive::OMPD_target_teams_distribute_simd:
1621 case llvm::omp::Directive::OMPD_target_teams_loop:
1622 case llvm::omp::Directive::OMPD_target_simd:
1623 case llvm::omp::Directive::OMPD_taskloop:
1624 case llvm::omp::Directive::OMPD_taskloop_simd:
1625 case llvm::omp::Directive::OMPD_teams_distribute:
1626 case llvm::omp::Directive::OMPD_teams_distribute_parallel_do:
1627 case llvm::omp::Directive::OMPD_teams_distribute_parallel_do_simd:
1628 case llvm::omp::Directive::OMPD_teams_distribute_simd:
1629 case llvm::omp::Directive::OMPD_tile:
1630 case llvm::omp::Directive::OMPD_unroll:
1631 PushContext(beginDir.source, beginDir.v);
1632 break;
1633 default:
1634 break;
1635 }
1636 if (beginDir.v == llvm::omp::Directive::OMPD_target_loop)
1637 if (context_.ShouldWarn(common::UsageWarning::OpenMPUsage)) {
1638 context_.Say(beginDir.source,
1639 "Usage of directive %s is non-confirming to OpenMP standard"_warn_en_US,
1640 llvm::omp::getOpenMPDirectiveName(beginDir.v).str());
1641 }
1642 ClearDataSharingAttributeObjects();
1643 SetContextAssociatedLoopLevel(GetAssociatedLoopLevelFromClauses(clauseList));
1644
1645 if (beginDir.v == llvm::omp::Directive::OMPD_do) {
1646 if (const auto &doConstruct{
1647 std::get<std::optional<parser::DoConstruct>>(x.t)}) {
1648 if (doConstruct.value().IsDoWhile()) {
1649 return true;
1650 }
1651 }
1652 }
1653 PrivatizeAssociatedLoopIndexAndCheckLoopLevel(x);
1654 ordCollapseLevel = GetAssociatedLoopLevelFromClauses(clauseList) + 1;
1655 return true;
1656 }
1657
1658 void OmpAttributeVisitor::ResolveSeqLoopIndexInParallelOrTaskConstruct(
1659 const parser::Name &iv) {
1660 // Find the parallel or task generating construct enclosing the
1661 // sequential loop.
1662 auto targetIt{dirContext_.rbegin()};
1663 for (;; ++targetIt) {
1664 if (targetIt == dirContext_.rend()) {
1665 return;
1666 }
1667 if (llvm::omp::allParallelSet.test(targetIt->directive) ||
1668 llvm::omp::taskGeneratingSet.test(targetIt->directive)) {
1669 break;
1670 }
1671 }
1672 // If this symbol already has a data-sharing attribute then there is nothing
1673 // to do here.
1674 if (const Symbol * symbol{iv.symbol}) {
1675 for (auto symMap : targetIt->objectWithDSA) {
1676 if (symMap.first->name() == symbol->name()) {
1677 return;
1678 }
1679 }
1680 }
1681 // If this symbol is already Private or Firstprivate in the enclosing
1682 // OpenMP parallel or task then there is nothing to do here.
1683 if (auto *symbol{targetIt->scope.FindSymbol(iv.source)}) {
1684 if (symbol->owner() == targetIt->scope) {
1685 if (symbol->test(Symbol::Flag::OmpPrivate) ||
1686 symbol->test(Symbol::Flag::OmpFirstPrivate)) {
1687 return;
1688 }
1689 }
1690 }
1691 // Otherwise find the symbol and make it Private for the entire enclosing
1692 // parallel or task
1693 if (auto *symbol{ResolveOmp(iv, Symbol::Flag::OmpPrivate, targetIt->scope)}) {
1694 targetIt++;
1695 symbol->set(Symbol::Flag::OmpPreDetermined);
1696 iv.symbol = symbol; // adjust the symbol within region
1697 for (auto it{dirContext_.rbegin()}; it != targetIt; ++it) {
1698 AddToContextObjectWithDSA(*symbol, Symbol::Flag::OmpPrivate, *it);
1699 }
1700 }
1701 }
1702
1703 // [OMP-4.5]2.15.1.1 Data-sharing Attribute Rules - Predetermined
1704 // - A loop iteration variable for a sequential loop in a parallel
1705 // or task generating construct is private in the innermost such
1706 // construct that encloses the loop
1707 // Loop iteration variables are not well defined for DO WHILE loop.
1708 // Use of DO CONCURRENT inside OpenMP construct is unspecified behavior
1709 // till OpenMP-5.0 standard.
1710 // In above both cases we skip the privatization of iteration variables.
1711 // [OpenMP 5.1] DO CONCURRENT indices are private
1712 bool OmpAttributeVisitor::Pre(const parser::DoConstruct &x) {
1713 if (!dirContext_.empty() && GetContext().withinConstruct) {
1714 llvm::SmallVector<const parser::Name *> ivs;
1715 if (x.IsDoNormal()) {
1716 const parser::Name *iv{GetLoopIndex(x)};
1717 if (iv && iv->symbol)
1718 ivs.push_back(iv);
1719 } else if (x.IsDoConcurrent()) {
1720 const Fortran::parser::LoopControl *loopControl = &*x.GetLoopControl();
1721 const Fortran::parser::LoopControl::Concurrent &concurrent =
1722 std::get<Fortran::parser::LoopControl::Concurrent>(loopControl->u);
1723 const Fortran::parser::ConcurrentHeader &concurrentHeader =
1724 std::get<Fortran::parser::ConcurrentHeader>(concurrent.t);
1725 const std::list<Fortran::parser::ConcurrentControl> &controls =
1726 std::get<std::list<Fortran::parser::ConcurrentControl>>(
1727 concurrentHeader.t);
1728 for (const auto &control : controls) {
1729 const parser::Name *iv{&std::get<0>(control.t)};
1730 if (iv && iv->symbol)
1731 ivs.push_back(iv);
1732 }
1733 }
1734 ordCollapseLevel--;
1735 for (auto iv : ivs) {
1736 if (!iv->symbol->test(Symbol::Flag::OmpPreDetermined)) {
1737 ResolveSeqLoopIndexInParallelOrTaskConstruct(*iv);
1738 } else {
1739 // TODO: conflict checks with explicitly determined DSA
1740 }
1741 if (ordCollapseLevel) {
1742 if (const auto *details{iv->symbol->detailsIf<HostAssocDetails>()}) {
1743 const Symbol *tpSymbol = &details->symbol();
1744 // TODO: DoConcurrent won't capture the following check because a new
1745 // symbol is declared in ResolveIndexName(), which will not have the
1746 // OmpThreadprivate flag.
1747 if (tpSymbol->test(Symbol::Flag::OmpThreadprivate)) {
1748 context_.Say(iv->source,
1749 "Loop iteration variable %s is not allowed in THREADPRIVATE."_err_en_US,
1750 iv->ToString());
1751 }
1752 }
1753 }
1754 }
1755 }
1756 return true;
1757 }
1758
1759 std::int64_t OmpAttributeVisitor::GetAssociatedLoopLevelFromClauses(
1760 const parser::OmpClauseList &x) {
1761 std::int64_t orderedLevel{0};
1762 std::int64_t collapseLevel{0};
1763
1764 const parser::OmpClause *ordClause{nullptr};
1765 const parser::OmpClause *collClause{nullptr};
1766
1767 for (const auto &clause : x.v) {
1768 if (const auto *orderedClause{
1769 std::get_if<parser::OmpClause::Ordered>(&clause.u)}) {
1770 if (const auto v{EvaluateInt64(context_, orderedClause->v)}) {
1771 orderedLevel = *v;
1772 }
1773 ordClause = &clause;
1774 }
1775 if (const auto *collapseClause{
1776 std::get_if<parser::OmpClause::Collapse>(&clause.u)}) {
1777 if (const auto v{EvaluateInt64(context_, collapseClause->v)}) {
1778 collapseLevel = *v;
1779 }
1780 collClause = &clause;
1781 }
1782 }
1783
1784 if (orderedLevel && (!collapseLevel || orderedLevel >= collapseLevel)) {
1785 SetAssociatedClause(*ordClause);
1786 return orderedLevel;
1787 } else if (!orderedLevel && collapseLevel) {
1788 SetAssociatedClause(*collClause);
1789 return collapseLevel;
1790 } // orderedLevel < collapseLevel is an error handled in structural checks
1791 return 1; // default is outermost loop
1792 }
1793
1794 // 2.15.1.1 Data-sharing Attribute Rules - Predetermined
1795 // - The loop iteration variable(s) in the associated do-loop(s) of a do,
1796 // parallel do, taskloop, or distribute construct is (are) private.
1797 // - The loop iteration variable in the associated do-loop of a simd construct
1798 // with just one associated do-loop is linear with a linear-step that is the
1799 // increment of the associated do-loop.
1800 // - The loop iteration variables in the associated do-loops of a simd
1801 // construct with multiple associated do-loops are lastprivate.
1802 void OmpAttributeVisitor::PrivatizeAssociatedLoopIndexAndCheckLoopLevel(
1803 const parser::OpenMPLoopConstruct &x) {
1804 std::int64_t level{GetContext().associatedLoopLevel};
1805 if (level <= 0) {
1806 return;
1807 }
1808 Symbol::Flag ivDSA;
1809 if (!llvm::omp::allSimdSet.test(GetContext().directive)) {
1810 ivDSA = Symbol::Flag::OmpPrivate;
1811 } else if (level == 1) {
1812 ivDSA = Symbol::Flag::OmpLinear;
1813 } else {
1814 ivDSA = Symbol::Flag::OmpLastPrivate;
1815 }
1816
1817 const auto &outer{std::get<std::optional<parser::DoConstruct>>(x.t)};
1818 for (const parser::DoConstruct *loop{&*outer}; loop && level > 0; --level) {
1819 // go through all the nested do-loops and resolve index variables
1820 const parser::Name *iv{GetLoopIndex(*loop)};
1821 if (iv) {
1822 if (auto *symbol{ResolveOmp(*iv, ivDSA, currScope())}) {
1823 symbol->set(Symbol::Flag::OmpPreDetermined);
1824 iv->symbol = symbol; // adjust the symbol within region
1825 AddToContextObjectWithDSA(*symbol, ivDSA);
1826 }
1827
1828 const auto &block{std::get<parser::Block>(loop->t)};
1829 const auto it{block.begin()};
1830 loop = it != block.end() ? GetDoConstructIf(*it) : nullptr;
1831 }
1832 }
1833 CheckAssocLoopLevel(level, GetAssociatedClause());
1834 }
1835 void OmpAttributeVisitor::CheckAssocLoopLevel(
1836 std::int64_t level, const parser::OmpClause *clause) {
1837 if (clause && level != 0) {
1838 context_.Say(clause->source,
1839 "The value of the parameter in the COLLAPSE or ORDERED clause must"
1840 " not be larger than the number of nested loops"
1841 " following the construct."_err_en_US);
1842 }
1843 }
1844
1845 bool OmpAttributeVisitor::Pre(const parser::OpenMPSectionsConstruct &x) {
1846 const auto &beginSectionsDir{
1847 std::get<parser::OmpBeginSectionsDirective>(x.t)};
1848 const auto &beginDir{
1849 std::get<parser::OmpSectionsDirective>(beginSectionsDir.t)};
1850 switch (beginDir.v) {
1851 case llvm::omp::Directive::OMPD_parallel_sections:
1852 case llvm::omp::Directive::OMPD_sections:
1853 PushContext(beginDir.source, beginDir.v);
1854 GetContext().withinConstruct = true;
1855 break;
1856 default:
1857 break;
1858 }
1859 ClearDataSharingAttributeObjects();
1860 return true;
1861 }
1862
1863 bool OmpAttributeVisitor::Pre(const parser::OpenMPCriticalConstruct &x) {
1864 const auto &beginCriticalDir{std::get<parser::OmpCriticalDirective>(x.t)};
1865 const auto &endCriticalDir{std::get<parser::OmpEndCriticalDirective>(x.t)};
1866 PushContext(beginCriticalDir.source, llvm::omp::Directive::OMPD_critical);
1867 GetContext().withinConstruct = true;
1868 if (const auto &criticalName{
1869 std::get<std::optional<parser::Name>>(beginCriticalDir.t)}) {
1870 ResolveOmpName(*criticalName, Symbol::Flag::OmpCriticalLock);
1871 }
1872 if (const auto &endCriticalName{
1873 std::get<std::optional<parser::Name>>(endCriticalDir.t)}) {
1874 ResolveOmpName(*endCriticalName, Symbol::Flag::OmpCriticalLock);
1875 }
1876 return true;
1877 }
1878
1879 bool OmpAttributeVisitor::Pre(const parser::OpenMPDeclareTargetConstruct &x) {
1880 PushContext(x.source, llvm::omp::Directive::OMPD_declare_target);
1881 const auto &spec{std::get<parser::OmpDeclareTargetSpecifier>(x.t)};
1882 if (const auto *objectList{parser::Unwrap<parser::OmpObjectList>(spec.u)}) {
1883 ResolveOmpObjectList(*objectList, Symbol::Flag::OmpDeclareTarget);
1884 } else if (const auto *clauseList{
1885 parser::Unwrap<parser::OmpClauseList>(spec.u)}) {
1886 for (const auto &clause : clauseList->v) {
1887 if (const auto *toClause{std::get_if<parser::OmpClause::To>(&clause.u)}) {
1888 ResolveOmpObjectList(toClause->v, Symbol::Flag::OmpDeclareTarget);
1889 } else if (const auto *linkClause{
1890 std::get_if<parser::OmpClause::Link>(&clause.u)}) {
1891 ResolveOmpObjectList(linkClause->v, Symbol::Flag::OmpDeclareTarget);
1892 } else if (const auto *enterClause{
1893 std::get_if<parser::OmpClause::Enter>(&clause.u)}) {
1894 ResolveOmpObjectList(enterClause->v, Symbol::Flag::OmpDeclareTarget);
1895 }
1896 }
1897 }
1898 return true;
1899 }
1900
1901 bool OmpAttributeVisitor::Pre(const parser::OpenMPThreadprivate &x) {
1902 PushContext(x.source, llvm::omp::Directive::OMPD_threadprivate);
1903 const auto &list{std::get<parser::OmpObjectList>(x.t)};
1904 ResolveOmpObjectList(list, Symbol::Flag::OmpThreadprivate);
1905 return true;
1906 }
1907
1908 bool OmpAttributeVisitor::Pre(const parser::OpenMPDeclarativeAllocate &x) {
1909 PushContext(x.source, llvm::omp::Directive::OMPD_allocate);
1910 const auto &list{std::get<parser::OmpObjectList>(x.t)};
1911 ResolveOmpObjectList(list, Symbol::Flag::OmpDeclarativeAllocateDirective);
1912 return false;
1913 }
1914
1915 bool OmpAttributeVisitor::Pre(const parser::OpenMPExecutableAllocate &x) {
1916 PushContext(x.source, llvm::omp::Directive::OMPD_allocate);
1917 const auto &list{std::get<std::optional<parser::OmpObjectList>>(x.t)};
1918 if (list) {
1919 ResolveOmpObjectList(*list, Symbol::Flag::OmpExecutableAllocateDirective);
1920 }
1921 return true;
1922 }
1923
1924 bool OmpAttributeVisitor::Pre(const parser::OpenMPAllocatorsConstruct &x) {
1925 PushContext(x.source, llvm::omp::Directive::OMPD_allocators);
1926 const auto &clauseList{std::get<parser::OmpClauseList>(x.t)};
1927 for (const auto &clause : clauseList.v) {
1928 if (const auto *allocClause{
1929 std::get_if<parser::OmpClause::Allocate>(&clause.u)}) {
1930 ResolveOmpObjectList(std::get<parser::OmpObjectList>(allocClause->v.t),
1931 Symbol::Flag::OmpExecutableAllocateDirective);
1932 }
1933 }
1934 return true;
1935 }
1936
1937 void OmpAttributeVisitor::Post(const parser::OmpDefaultClause &x) {
1938 if (!dirContext_.empty()) {
1939 switch (x.v) {
1940 case parser::OmpDefaultClause::Type::Private:
1941 SetContextDefaultDSA(Symbol::Flag::OmpPrivate);
1942 break;
1943 case parser::OmpDefaultClause::Type::Firstprivate:
1944 SetContextDefaultDSA(Symbol::Flag::OmpFirstPrivate);
1945 break;
1946 case parser::OmpDefaultClause::Type::Shared:
1947 SetContextDefaultDSA(Symbol::Flag::OmpShared);
1948 break;
1949 case parser::OmpDefaultClause::Type::None:
1950 SetContextDefaultDSA(Symbol::Flag::OmpNone);
1951 break;
1952 }
1953 }
1954 }
1955
1956 bool OmpAttributeVisitor::IsNestedInDirective(llvm::omp::Directive directive) {
1957 if (dirContext_.size() >= 1) {
1958 for (std::size_t i = dirContext_.size() - 1; i > 0; --i) {
1959 if (dirContext_[i - 1].directive == directive) {
1960 return true;
1961 }
1962 }
1963 }
1964 return false;
1965 }
1966
1967 void OmpAttributeVisitor::Post(const parser::OpenMPExecutableAllocate &x) {
1968 bool hasAllocator = false;
1969 // TODO: Investigate whether searching the clause list can be done with
1970 // parser::Unwrap instead of the following loop
1971 const auto &clauseList{std::get<parser::OmpClauseList>(x.t)};
1972 for (const auto &clause : clauseList.v) {
1973 if (std::get_if<parser::OmpClause::Allocator>(&clause.u)) {
1974 hasAllocator = true;
1975 }
1976 }
1977
1978 if (IsNestedInDirective(llvm::omp::Directive::OMPD_target) && !hasAllocator) {
1979 // TODO: expand this check to exclude the case when a requires
1980 // directive with the dynamic_allocators clause is present
1981 // in the same compilation unit (OMP5.0 2.11.3).
1982 context_.Say(x.source,
1983 "ALLOCATE directives that appear in a TARGET region "
1984 "must specify an allocator clause"_err_en_US);
1985 }
1986
1987 const auto &allocateStmt =
1988 std::get<parser::Statement<parser::AllocateStmt>>(x.t).statement;
1989 if (const auto &list{std::get<std::optional<parser::OmpObjectList>>(x.t)}) {
1990 CheckAllNamesInAllocateStmt(
1991 std::get<parser::Verbatim>(x.t).source, *list, allocateStmt);
1992 }
1993 if (const auto &subDirs{
1994 std::get<std::optional<std::list<parser::OpenMPDeclarativeAllocate>>>(
1995 x.t)}) {
1996 for (const auto &dalloc : *subDirs) {
1997 CheckAllNamesInAllocateStmt(std::get<parser::Verbatim>(dalloc.t).source,
1998 std::get<parser::OmpObjectList>(dalloc.t), allocateStmt);
1999 }
2000 }
2001 PopContext();
2002 }
2003
2004 void OmpAttributeVisitor::Post(const parser::OpenMPAllocatorsConstruct &x) {
2005 const auto &dir{std::get<parser::Verbatim>(x.t)};
2006 const auto &clauseList{std::get<parser::OmpClauseList>(x.t)};
2007 for (const auto &clause : clauseList.v) {
2008 if (const auto *alloc{
2009 std::get_if<parser::OmpClause::Allocate>(&clause.u)}) {
2010 CheckAllNamesInAllocateStmt(dir.source,
2011 std::get<parser::OmpObjectList>(alloc->v.t),
2012 std::get<parser::Statement<parser::AllocateStmt>>(x.t).statement);
2013
2014 const auto &allocMod{
2015 std::get<std::optional<parser::OmpAllocateClause::AllocateModifier>>(
2016 alloc->v.t)};
2017 // TODO: As with allocate directive, exclude the case when a requires
2018 // directive with the dynamic_allocators clause is present in
2019 // the same compilation unit (OMP5.0 2.11.3).
2020 if (IsNestedInDirective(llvm::omp::Directive::OMPD_target) &&
2021 (!allocMod.has_value() ||
2022 std::holds_alternative<
2023 parser::OmpAllocateClause::AllocateModifier::Align>(
2024 allocMod->u))) {
2025 context_.Say(x.source,
2026 "ALLOCATORS directives that appear in a TARGET region "
2027 "must specify an allocator"_err_en_US);
2028 }
2029 }
2030 }
2031 PopContext();
2032 }
2033
2034 // For OpenMP constructs, check all the data-refs within the constructs
2035 // and adjust the symbol for each Name if necessary
2036 void OmpAttributeVisitor::Post(const parser::Name &name) {
2037 auto *symbol{name.symbol};
2038 if (symbol && !dirContext_.empty() && GetContext().withinConstruct) {
2039 // Exclude construct-names
2040 if (auto *details{symbol->detailsIf<semantics::MiscDetails>()}) {
2041 if (details->kind() == semantics::MiscDetails::Kind::ConstructName) {
2042 return;
2043 }
2044 }
2045 if (!symbol->owner().IsDerivedType() && !IsProcedure(*symbol) &&
2046 !IsObjectWithDSA(*symbol) && !IsNamedConstant(*symbol)) {
2047 // TODO: create a separate function to go through the rules for
2048 // predetermined, explicitly determined, and implicitly
2049 // determined data-sharing attributes (2.15.1.1).
2050 if (Symbol * found{currScope().FindSymbol(name.source)}) {
2051 if (symbol != found) {
2052 name.symbol = found; // adjust the symbol within region
2053 } else if (GetContext().defaultDSA == Symbol::Flag::OmpNone &&
2054 !symbol->test(Symbol::Flag::OmpThreadprivate) &&
2055 // Exclude indices of sequential loops that are privatised in
2056 // the scope of the parallel region, and not in this scope.
2057 // TODO: check whether this should be caught in IsObjectWithDSA
2058 !symbol->test(Symbol::Flag::OmpPrivate)) {
2059 context_.Say(name.source,
2060 "The DEFAULT(NONE) clause requires that '%s' must be listed in "
2061 "a data-sharing attribute clause"_err_en_US,
2062 symbol->name());
2063 }
2064 }
2065 }
2066
2067 if (Symbol * found{currScope().FindSymbol(name.source)}) {
2068 if (found->test(semantics::Symbol::Flag::OmpThreadprivate))
2069 return;
2070 }
2071
2072 // Implicitly determined DSAs
2073 // OMP 5.2 5.1.1 - Variables Referenced in a Construct
2074 Symbol *lastDeclSymbol = nullptr;
2075 std::optional<Symbol::Flag> prevDSA;
2076 for (int dirDepth{0}; dirDepth < (int)dirContext_.size(); ++dirDepth) {
2077 DirContext &dirContext = dirContext_[dirDepth];
2078 std::optional<Symbol::Flag> dsa;
2079
2080 for (auto symMap : dirContext.objectWithDSA) {
2081 // if the `symbol` already has a data-sharing attribute
2082 if (symMap.first->name() == name.symbol->name()) {
2083 dsa = symMap.second;
2084 break;
2085 }
2086 }
2087
2088 // When handling each implicit rule, either a new private symbol is
2089 // declared or the last declared symbol is used.
2090 // In the latter case, it's necessary to insert a new symbol in the scope
2091 // being processed, associated with the last declared symbol.
2092 // This captures the fact that, although we are using the last declared
2093 // symbol, its DSA could be different in this scope.
2094 // Also, because of how symbols are collected in lowering, not inserting
2095 // a new symbol in this scope could lead to the conclusion that the
2096 // symbol was declared in this construct, which would result in wrong
2097 // privatization code being generated.
2098 // Consider the following example:
2099 //
2100 // !$omp parallel default(private) ! p1
2101 // !$omp parallel default(private) shared(x) ! p2
2102 // x = 10
2103 // !$omp end parallel
2104 // !$omp end parallel
2105 //
2106 // If a new x symbol was not inserted in the inner parallel construct
2107 // (p2), it would use the x symbol definition from the enclosing scope.
2108 // Then, when p2's default symbols were collected in lowering, the x
2109 // symbol from the outer parallel construct (p1) would be collected, as
2110 // it would have the private flag set (note that symbols that don't have
2111 // any private flag are considered as shared).
2112 // This would make x appear to be defined in p2, causing it to be
2113 // privatized in p2 and its privatization in p1 to be skipped.
2114 auto declNewSymbol = [&](Symbol::Flag flag) {
2115 Symbol *hostSymbol =
2116 lastDeclSymbol ? lastDeclSymbol : &symbol->GetUltimate();
2117 lastDeclSymbol = DeclarePrivateAccessEntity(
2118 *hostSymbol, flag, context_.FindScope(dirContext.directiveSource));
2119 return lastDeclSymbol;
2120 };
2121 auto useLastDeclSymbol = [&]() {
2122 if (lastDeclSymbol)
2123 MakeAssocSymbol(symbol->name(), *lastDeclSymbol,
2124 context_.FindScope(dirContext.directiveSource));
2125 };
2126
2127 if (dsa.has_value()) {
2128 useLastDeclSymbol();
2129 prevDSA = dsa;
2130 continue;
2131 }
2132
2133 bool taskGenDir = llvm::omp::taskGeneratingSet.test(dirContext.directive);
2134 bool targetDir = llvm::omp::allTargetSet.test(dirContext.directive);
2135 bool parallelDir = llvm::omp::allParallelSet.test(dirContext.directive);
2136
2137 if (dirContext.defaultDSA == Symbol::Flag::OmpPrivate ||
2138 dirContext.defaultDSA == Symbol::Flag::OmpFirstPrivate ||
2139 dirContext.defaultDSA == Symbol::Flag::OmpShared) {
2140 // 1) default
2141 // Allowed only with parallel, teams and task generating constructs.
2142 assert(parallelDir || taskGenDir ||
2143 llvm::omp::allTeamsSet.test(dirContext.directive));
2144 if (dirContext.defaultDSA != Symbol::Flag::OmpShared)
2145 declNewSymbol(dirContext.defaultDSA);
2146 else
2147 useLastDeclSymbol();
2148 dsa = dirContext.defaultDSA;
2149 } else if (parallelDir) {
2150 // 2) parallel -> shared
2151 useLastDeclSymbol();
2152 dsa = Symbol::Flag::OmpShared;
2153 } else if (!taskGenDir && !targetDir) {
2154 // 3) enclosing context
2155 useLastDeclSymbol();
2156 dsa = prevDSA;
2157 } else if (targetDir) {
2158 // TODO 4) not mapped target variable -> firstprivate
2159 dsa = prevDSA;
2160 } else if (taskGenDir) {
2161 // TODO 5) dummy arg in orphaned taskgen construct -> firstprivate
2162 if (prevDSA == Symbol::Flag::OmpShared) {
2163 // 6) shared in enclosing context -> shared
2164 useLastDeclSymbol();
2165 dsa = Symbol::Flag::OmpShared;
2166 } else {
2167 // 7) firstprivate
2168 dsa = Symbol::Flag::OmpFirstPrivate;
2169 declNewSymbol(*dsa)->set(Symbol::Flag::OmpImplicit);
2170 }
2171 }
2172 prevDSA = dsa;
2173 }
2174 } // within OpenMP construct
2175 }
2176
2177 Symbol *OmpAttributeVisitor::ResolveName(const parser::Name *name) {
2178 if (auto *resolvedSymbol{
2179 name ? GetContext().scope.FindSymbol(name->source) : nullptr}) {
2180 name->symbol = resolvedSymbol;
2181 return resolvedSymbol;
2182 } else {
2183 return nullptr;
2184 }
2185 }
2186
2187 void OmpAttributeVisitor::ResolveOmpName(
2188 const parser::Name &name, Symbol::Flag ompFlag) {
2189 if (ResolveName(&name)) {
2190 if (auto *resolvedSymbol{ResolveOmp(name, ompFlag, currScope())}) {
2191 if (dataSharingAttributeFlags.test(ompFlag)) {
2192 AddToContextObjectWithDSA(*resolvedSymbol, ompFlag);
2193 }
2194 }
2195 } else if (ompFlag == Symbol::Flag::OmpCriticalLock) {
2196 const auto pair{
2197 GetContext().scope.try_emplace(name.source, Attrs{}, UnknownDetails{})};
2198 CHECK(pair.second);
2199 name.symbol = &pair.first->second.get();
2200 }
2201 }
2202
2203 void OmpAttributeVisitor::ResolveOmpNameList(
2204 const std::list<parser::Name> &nameList, Symbol::Flag ompFlag) {
2205 for (const auto &name : nameList) {
2206 ResolveOmpName(name, ompFlag);
2207 }
2208 }
2209
2210 Symbol *OmpAttributeVisitor::ResolveOmpCommonBlockName(
2211 const parser::Name *name) {
2212 if (!name) {
2213 return nullptr;
2214 }
2215 if (auto *cb{GetProgramUnitOrBlockConstructContaining(GetContext().scope)
2216 .FindCommonBlock(name->source)}) {
2217 name->symbol = cb;
2218 return cb;
2219 }
2220 return nullptr;
2221 }
2222
2223 // Use this function over ResolveOmpName when an omp object's scope needs
2224 // resolving, it's symbol flag isn't important and a simple check for resolution
2225 // failure is desired. Using ResolveOmpName means needing to work with the
2226 // context to check for failure, whereas here a pointer comparison is all that's
2227 // needed.
2228 Symbol *OmpAttributeVisitor::ResolveOmpObjectScope(const parser::Name *name) {
2229
2230 // TODO: Investigate whether the following block can be replaced by, or
2231 // included in, the ResolveOmpName function
2232 if (auto *prev{name ? GetContext().scope.parent().FindSymbol(name->source)
2233 : nullptr}) {
2234 name->symbol = prev;
2235 return nullptr;
2236 }
2237
2238 // TODO: Investigate whether the following block can be replaced by, or
2239 // included in, the ResolveOmpName function
2240 if (auto *ompSymbol{
2241 name ? GetContext().scope.FindSymbol(name->source) : nullptr}) {
2242 name->symbol = ompSymbol;
2243 return ompSymbol;
2244 }
2245 return nullptr;
2246 }
2247
2248 void OmpAttributeVisitor::ResolveOmpObjectList(
2249 const parser::OmpObjectList &ompObjectList, Symbol::Flag ompFlag) {
2250 for (const auto &ompObject : ompObjectList.v) {
2251 ResolveOmpObject(ompObject, ompFlag);
2252 }
2253 }
2254
2255 void OmpAttributeVisitor::ResolveOmpObject(
2256 const parser::OmpObject &ompObject, Symbol::Flag ompFlag) {
2257 common::visit(
2258 common::visitors{
2259 [&](const parser::Designator &designator) {
2260 if (const auto *name{
2261 semantics::getDesignatorNameIfDataRef(designator)}) {
2262 if (auto *symbol{ResolveOmp(*name, ompFlag, currScope())}) {
2263 auto checkExclusivelists =
2264 [&](const Symbol *symbol1, Symbol::Flag firstOmpFlag,
2265 Symbol *symbol2, Symbol::Flag secondOmpFlag) {
2266 if ((symbol1->test(firstOmpFlag) &&
2267 symbol2->test(secondOmpFlag)) ||
2268 (symbol1->test(secondOmpFlag) &&
2269 symbol2->test(firstOmpFlag))) {
2270 context_.Say(designator.source,
2271 "Variable '%s' may not "
2272 "appear on both %s and %s "
2273 "clauses on a %s construct"_err_en_US,
2274 symbol2->name(),
2275 const_cast<Symbol *>(symbol1)->OmpFlagToClauseName(
2276 firstOmpFlag),
2277 symbol2->OmpFlagToClauseName(secondOmpFlag),
2278 parser::ToUpperCaseLetters(
2279 llvm::omp::getOpenMPDirectiveName(
2280 GetContext().directive)
2281 .str()));
2282 }
2283 };
2284 if (dataCopyingAttributeFlags.test(ompFlag)) {
2285 CheckDataCopyingClause(*name, *symbol, ompFlag);
2286 } else {
2287 AddToContextObjectWithDSA(*symbol, ompFlag);
2288 if (dataSharingAttributeFlags.test(ompFlag)) {
2289 CheckMultipleAppearances(*name, *symbol, ompFlag);
2290 }
2291 if (privateDataSharingAttributeFlags.test(ompFlag)) {
2292 CheckObjectInNamelist(*name, *symbol, ompFlag);
2293 }
2294
2295 if (ompFlag == Symbol::Flag::OmpAllocate) {
2296 AddAllocateName(name);
2297 }
2298 }
2299 if (ompFlag == Symbol::Flag::OmpDeclarativeAllocateDirective &&
2300 IsAllocatable(*symbol) &&
2301 !IsNestedInDirective(llvm::omp::Directive::OMPD_allocate)) {
2302 context_.Say(designator.source,
2303 "List items specified in the ALLOCATE directive must not "
2304 "have the ALLOCATABLE attribute unless the directive is "
2305 "associated with an ALLOCATE statement"_err_en_US);
2306 }
2307 if ((ompFlag == Symbol::Flag::OmpDeclarativeAllocateDirective ||
2308 ompFlag ==
2309 Symbol::Flag::OmpExecutableAllocateDirective) &&
2310 ResolveOmpObjectScope(name) == nullptr) {
2311 context_.Say(designator.source, // 2.15.3
2312 "List items must be declared in the same scoping unit "
2313 "in which the %s directive appears"_err_en_US,
2314 parser::ToUpperCaseLetters(
2315 llvm::omp::getOpenMPDirectiveName(
2316 GetContext().directive)
2317 .str()));
2318 }
2319 if (GetContext().directive ==
2320 llvm::omp::Directive::OMPD_target_data) {
2321 checkExclusivelists(symbol, Symbol::Flag::OmpUseDevicePtr,
2322 symbol, Symbol::Flag::OmpUseDeviceAddr);
2323 }
2324 if (llvm::omp::allDistributeSet.test(GetContext().directive)) {
2325 checkExclusivelists(symbol, Symbol::Flag::OmpFirstPrivate,
2326 symbol, Symbol::Flag::OmpLastPrivate);
2327 }
2328 if (llvm::omp::allTargetSet.test(GetContext().directive)) {
2329 checkExclusivelists(symbol, Symbol::Flag::OmpIsDevicePtr,
2330 symbol, Symbol::Flag::OmpHasDeviceAddr);
2331 const auto *hostAssocSym{symbol};
2332 if (!(symbol->test(Symbol::Flag::OmpIsDevicePtr) ||
2333 symbol->test(Symbol::Flag::OmpHasDeviceAddr))) {
2334 if (const auto *details{
2335 symbol->detailsIf<HostAssocDetails>()}) {
2336 hostAssocSym = &details->symbol();
2337 }
2338 }
2339 Symbol::Flag dataMappingAttributeFlags[] = {
2340 Symbol::Flag::OmpMapTo, Symbol::Flag::OmpMapFrom,
2341 Symbol::Flag::OmpMapToFrom, Symbol::Flag::OmpMapAlloc,
2342 Symbol::Flag::OmpMapRelease, Symbol::Flag::OmpMapDelete,
2343 Symbol::Flag::OmpIsDevicePtr,
2344 Symbol::Flag::OmpHasDeviceAddr};
2345
2346 Symbol::Flag dataSharingAttributeFlags[] = {
2347 Symbol::Flag::OmpPrivate, Symbol::Flag::OmpFirstPrivate,
2348 Symbol::Flag::OmpLastPrivate, Symbol::Flag::OmpShared,
2349 Symbol::Flag::OmpLinear};
2350
2351 for (Symbol::Flag ompFlag1 : dataMappingAttributeFlags) {
2352 for (Symbol::Flag ompFlag2 : dataSharingAttributeFlags) {
2353 checkExclusivelists(
2354 hostAssocSym, ompFlag1, symbol, ompFlag2);
2355 }
2356 }
2357 }
2358 }
2359 } else {
2360 // Array sections to be changed to substrings as needed
2361 if (AnalyzeExpr(context_, designator)) {
2362 if (std::holds_alternative<parser::Substring>(designator.u)) {
2363 context_.Say(designator.source,
2364 "Substrings are not allowed on OpenMP "
2365 "directives or clauses"_err_en_US);
2366 }
2367 }
2368 // other checks, more TBD
2369 }
2370 },
2371 [&](const parser::Name &name) { // common block
2372 if (auto *symbol{ResolveOmpCommonBlockName(&name)}) {
2373 if (!dataCopyingAttributeFlags.test(ompFlag)) {
2374 CheckMultipleAppearances(
2375 name, *symbol, Symbol::Flag::OmpCommonBlock);
2376 }
2377 // 2.15.3 When a named common block appears in a list, it has the
2378 // same meaning as if every explicit member of the common block
2379 // appeared in the list
2380 auto &details{symbol->get<CommonBlockDetails>()};
2381 unsigned index{0};
2382 for (auto &object : details.objects()) {
2383 if (auto *resolvedObject{
2384 ResolveOmp(*object, ompFlag, currScope())}) {
2385 if (dataCopyingAttributeFlags.test(ompFlag)) {
2386 CheckDataCopyingClause(name, *resolvedObject, ompFlag);
2387 } else {
2388 AddToContextObjectWithDSA(*resolvedObject, ompFlag);
2389 }
2390 details.replace_object(*resolvedObject, index);
2391 }
2392 index++;
2393 }
2394 } else {
2395 context_.Say(name.source, // 2.15.3
2396 "COMMON block must be declared in the same scoping unit "
2397 "in which the OpenMP directive or clause appears"_err_en_US);
2398 }
2399 },
2400 },
2401 ompObject.u);
2402 }
2403
2404 Symbol *OmpAttributeVisitor::ResolveOmp(
2405 const parser::Name &name, Symbol::Flag ompFlag, Scope &scope) {
2406 if (ompFlagsRequireNewSymbol.test(ompFlag)) {
2407 return DeclarePrivateAccessEntity(name, ompFlag, scope);
2408 } else {
2409 return DeclareOrMarkOtherAccessEntity(name, ompFlag);
2410 }
2411 }
2412
2413 Symbol *OmpAttributeVisitor::ResolveOmp(
2414 Symbol &symbol, Symbol::Flag ompFlag, Scope &scope) {
2415 if (ompFlagsRequireNewSymbol.test(ompFlag)) {
2416 return DeclarePrivateAccessEntity(symbol, ompFlag, scope);
2417 } else {
2418 return DeclareOrMarkOtherAccessEntity(symbol, ompFlag);
2419 }
2420 }
2421
2422 Symbol *OmpAttributeVisitor::DeclareOrMarkOtherAccessEntity(
2423 const parser::Name &name, Symbol::Flag ompFlag) {
2424 Symbol *prev{currScope().FindSymbol(name.source)};
2425 if (!name.symbol || !prev) {
2426 return nullptr;
2427 } else if (prev != name.symbol) {
2428 name.symbol = prev;
2429 }
2430 return DeclareOrMarkOtherAccessEntity(*prev, ompFlag);
2431 }
2432
2433 Symbol *OmpAttributeVisitor::DeclareOrMarkOtherAccessEntity(
2434 Symbol &object, Symbol::Flag ompFlag) {
2435 if (ompFlagsRequireMark.test(ompFlag)) {
2436 object.set(ompFlag);
2437 }
2438 return &object;
2439 }
2440
2441 static bool WithMultipleAppearancesOmpException(
2442 const Symbol &symbol, Symbol::Flag flag) {
2443 return (flag == Symbol::Flag::OmpFirstPrivate &&
2444 symbol.test(Symbol::Flag::OmpLastPrivate)) ||
2445 (flag == Symbol::Flag::OmpLastPrivate &&
2446 symbol.test(Symbol::Flag::OmpFirstPrivate));
2447 }
2448
2449 void OmpAttributeVisitor::CheckMultipleAppearances(
2450 const parser::Name &name, const Symbol &symbol, Symbol::Flag ompFlag) {
2451 const auto *target{&symbol};
2452 if (ompFlagsRequireNewSymbol.test(ompFlag)) {
2453 if (const auto *details{symbol.detailsIf<HostAssocDetails>()}) {
2454 target = &details->symbol();
2455 }
2456 }
2457 if (HasDataSharingAttributeObject(*target) &&
2458 !WithMultipleAppearancesOmpException(symbol, ompFlag)) {
2459 context_.Say(name.source,
2460 "'%s' appears in more than one data-sharing clause "
2461 "on the same OpenMP directive"_err_en_US,
2462 name.ToString());
2463 } else {
2464 AddDataSharingAttributeObject(*target);
2465 if (privateDataSharingAttributeFlags.test(ompFlag)) {
2466 AddPrivateDataSharingAttributeObjects(*target);
2467 }
2468 }
2469 }
2470
2471 void ResolveAccParts(SemanticsContext &context, const parser::ProgramUnit &node,
2472 Scope *topScope) {
2473 if (context.IsEnabled(common::LanguageFeature::OpenACC)) {
2474 AccAttributeVisitor{context, topScope}.Walk(node);
2475 }
2476 }
2477
2478 void ResolveOmpParts(
2479 SemanticsContext &context, const parser::ProgramUnit &node) {
2480 if (context.IsEnabled(common::LanguageFeature::OpenMP)) {
2481 OmpAttributeVisitor{context}.Walk(node);
2482 if (!context.AnyFatalError()) {
2483 // The data-sharing attribute of the loop iteration variable for a
2484 // sequential loop (2.15.1.1) can only be determined when visiting
2485 // the corresponding DoConstruct, a second walk is to adjust the
2486 // symbols for all the data-refs of that loop iteration variable
2487 // prior to the DoConstruct.
2488 OmpAttributeVisitor{context}.Walk(node);
2489 }
2490 }
2491 }
2492
2493 void ResolveOmpTopLevelParts(
2494 SemanticsContext &context, const parser::Program &program) {
2495 if (!context.IsEnabled(common::LanguageFeature::OpenMP)) {
2496 return;
2497 }
2498
2499 // Gather REQUIRES clauses from all non-module top-level program unit symbols,
2500 // combine them together ensuring compatibility and apply them to all these
2501 // program units. Modules are skipped because their REQUIRES clauses should be
2502 // propagated via USE statements instead.
2503 WithOmpDeclarative::RequiresFlags combinedFlags;
2504 std::optional<common::OmpAtomicDefaultMemOrderType> combinedMemOrder;
2505
2506 // Function to go through non-module top level program units and extract
2507 // REQUIRES information to be processed by a function-like argument.
2508 auto processProgramUnits{[&](auto processFn) {
2509 for (const parser::ProgramUnit &unit : program.v) {
2510 if (!std::holds_alternative<common::Indirection<parser::Module>>(
2511 unit.u) &&
2512 !std::holds_alternative<common::Indirection<parser::Submodule>>(
2513 unit.u) &&
2514 !std::holds_alternative<
2515 common::Indirection<parser::CompilerDirective>>(unit.u)) {
2516 Symbol *symbol{common::visit(
2517 [&context](auto &x) {
2518 Scope *scope = GetScope(context, x.value());
2519 return scope ? scope->symbol() : nullptr;
2520 },
2521 unit.u)};
2522 // FIXME There is no symbol defined for MainProgram units in certain
2523 // circumstances, so REQUIRES information has no place to be stored in
2524 // these cases.
2525 if (!symbol) {
2526 continue;
2527 }
2528 common::visit(
2529 [&](auto &details) {
2530 if constexpr (std::is_convertible_v<decltype(&details),
2531 WithOmpDeclarative *>) {
2532 processFn(*symbol, details);
2533 }
2534 },
2535 symbol->details());
2536 }
2537 }
2538 }};
2539
2540 // Combine global REQUIRES information from all program units except modules
2541 // and submodules.
2542 processProgramUnits([&](Symbol &symbol, WithOmpDeclarative &details) {
2543 if (const WithOmpDeclarative::RequiresFlags *
2544 flags{details.ompRequires()}) {
2545 combinedFlags |= *flags;
2546 }
2547 if (const common::OmpAtomicDefaultMemOrderType *
2548 memOrder{details.ompAtomicDefaultMemOrder()}) {
2549 if (combinedMemOrder && *combinedMemOrder != *memOrder) {
2550 context.Say(symbol.scope()->sourceRange(),
2551 "Conflicting '%s' REQUIRES clauses found in compilation "
2552 "unit"_err_en_US,
2553 parser::ToUpperCaseLetters(llvm::omp::getOpenMPClauseName(
2554 llvm::omp::Clause::OMPC_atomic_default_mem_order)
2555 .str()));
2556 }
2557 combinedMemOrder = *memOrder;
2558 }
2559 });
2560
2561 // Update all program units except modules and submodules with the combined
2562 // global REQUIRES information.
2563 processProgramUnits([&](Symbol &, WithOmpDeclarative &details) {
2564 if (combinedFlags.any()) {
2565 details.set_ompRequires(combinedFlags);
2566 }
2567 if (combinedMemOrder) {
2568 details.set_ompAtomicDefaultMemOrder(*combinedMemOrder);
2569 }
2570 });
2571 }
2572
2573 void OmpAttributeVisitor::CheckDataCopyingClause(
2574 const parser::Name &name, const Symbol &symbol, Symbol::Flag ompFlag) {
2575 const auto *checkSymbol{&symbol};
2576 if (const auto *details{symbol.detailsIf<HostAssocDetails>()}) {
2577 checkSymbol = &details->symbol();
2578 }
2579
2580 if (ompFlag == Symbol::Flag::OmpCopyIn) {
2581 // List of items/objects that can appear in a 'copyin' clause must be
2582 // 'threadprivate'
2583 if (!checkSymbol->test(Symbol::Flag::OmpThreadprivate)) {
2584 context_.Say(name.source,
2585 "Non-THREADPRIVATE object '%s' in COPYIN clause"_err_en_US,
2586 checkSymbol->name());
2587 }
2588 } else if (ompFlag == Symbol::Flag::OmpCopyPrivate &&
2589 GetContext().directive == llvm::omp::Directive::OMPD_single) {
2590 // A list item that appears in a 'copyprivate' clause may not appear on a
2591 // 'private' or 'firstprivate' clause on a single construct
2592 if (IsObjectWithDSA(symbol) &&
2593 (symbol.test(Symbol::Flag::OmpPrivate) ||
2594 symbol.test(Symbol::Flag::OmpFirstPrivate))) {
2595 context_.Say(name.source,
2596 "COPYPRIVATE variable '%s' may not appear on a PRIVATE or "
2597 "FIRSTPRIVATE clause on a SINGLE construct"_err_en_US,
2598 symbol.name());
2599 } else {
2600 // List of items/objects that can appear in a 'copyprivate' clause must be
2601 // either 'private' or 'threadprivate' in enclosing context.
2602 if (!checkSymbol->test(Symbol::Flag::OmpThreadprivate) &&
2603 !(HasSymbolInEnclosingScope(symbol, currScope()) &&
2604 (symbol.test(Symbol::Flag::OmpPrivate) ||
2605 symbol.test(Symbol::Flag::OmpFirstPrivate)))) {
2606 context_.Say(name.source,
2607 "COPYPRIVATE variable '%s' is not PRIVATE or THREADPRIVATE in "
2608 "outer context"_err_en_US,
2609 symbol.name());
2610 }
2611 }
2612 }
2613 }
2614
2615 void OmpAttributeVisitor::CheckObjectInNamelist(
2616 const parser::Name &name, const Symbol &symbol, Symbol::Flag ompFlag) {
2617 const auto &ultimateSymbol{symbol.GetUltimate()};
2618 llvm::StringRef clauseName{"PRIVATE"};
2619 if (ompFlag == Symbol::Flag::OmpFirstPrivate) {
2620 clauseName = "FIRSTPRIVATE";
2621 } else if (ompFlag == Symbol::Flag::OmpLastPrivate) {
2622 clauseName = "LASTPRIVATE";
2623 }
2624
2625 if (ultimateSymbol.test(Symbol::Flag::InNamelist)) {
2626 context_.Say(name.source,
2627 "Variable '%s' in NAMELIST cannot be in a %s clause"_err_en_US,
2628 name.ToString(), clauseName.str());
2629 }
2630 }
2631
2632 void OmpAttributeVisitor::CheckSourceLabel(const parser::Label &label) {
2633 // Get the context to check if the statement causing a jump to the 'label' is
2634 // in an enclosing OpenMP construct
2635 std::optional<DirContext> thisContext{GetContextIf()};
2636 sourceLabels_.emplace(
2637 label, std::make_pair(currentStatementSource_, thisContext));
2638 // Check if the statement with 'label' to which a jump is being introduced
2639 // has already been encountered
2640 auto it{targetLabels_.find(label)};
2641 if (it != targetLabels_.end()) {
2642 // Check if both the statement with 'label' and the statement that causes a
2643 // jump to the 'label' are in the same scope
2644 CheckLabelContext(currentStatementSource_, it->second.first, thisContext,
2645 it->second.second);
2646 }
2647 }
2648
2649 // Check for invalid branch into or out of OpenMP structured blocks
2650 void OmpAttributeVisitor::CheckLabelContext(const parser::CharBlock source,
2651 const parser::CharBlock target, std::optional<DirContext> sourceContext,
2652 std::optional<DirContext> targetContext) {
2653 if (targetContext &&
2654 (!sourceContext ||
2655 (sourceContext->scope != targetContext->scope &&
2656 !DoesScopeContain(
2657 &targetContext->scope, sourceContext->scope)))) {
2658 context_
2659 .Say(source, "invalid branch into an OpenMP structured block"_err_en_US)
2660 .Attach(target, "In the enclosing %s directive branched into"_en_US,
2661 parser::ToUpperCaseLetters(
2662 llvm::omp::getOpenMPDirectiveName(targetContext->directive)
2663 .str()));
2664 }
2665 if (sourceContext &&
2666 (!targetContext ||
2667 (sourceContext->scope != targetContext->scope &&
2668 !DoesScopeContain(
2669 &sourceContext->scope, targetContext->scope)))) {
2670 context_
2671 .Say(source,
2672 "invalid branch leaving an OpenMP structured block"_err_en_US)
2673 .Attach(target, "Outside the enclosing %s directive"_en_US,
2674 parser::ToUpperCaseLetters(
2675 llvm::omp::getOpenMPDirectiveName(sourceContext->directive)
2676 .str()));
2677 }
2678 }
2679
2680 bool OmpAttributeVisitor::HasSymbolInEnclosingScope(
2681 const Symbol &symbol, Scope &scope) {
2682 const auto symbols{scope.parent().GetSymbols()};
2683 return llvm::is_contained(symbols, symbol);
2684 }
2685
2686 // Goes through the names in an OmpObjectList and checks if each name appears
2687 // in the given allocate statement
2688 void OmpAttributeVisitor::CheckAllNamesInAllocateStmt(
2689 const parser::CharBlock &source, const parser::OmpObjectList &ompObjectList,
2690 const parser::AllocateStmt &allocate) {
2691 for (const auto &obj : ompObjectList.v) {
2692 if (const auto *d{std::get_if<parser::Designator>(&obj.u)}) {
2693 if (const auto *ref{std::get_if<parser::DataRef>(&d->u)}) {
2694 if (const auto *n{std::get_if<parser::Name>(&ref->u)}) {
2695 CheckNameInAllocateStmt(source, *n, allocate);
2696 }
2697 }
2698 }
2699 }
2700 }
2701
2702 void OmpAttributeVisitor::CheckNameInAllocateStmt(
2703 const parser::CharBlock &source, const parser::Name &name,
2704 const parser::AllocateStmt &allocate) {
2705 for (const auto &allocation :
2706 std::get<std::list<parser::Allocation>>(allocate.t)) {
2707 const auto &allocObj = std::get<parser::AllocateObject>(allocation.t);
2708 if (const auto *n{std::get_if<parser::Name>(&allocObj.u)}) {
2709 if (n->source == name.source) {
2710 return;
2711 }
2712 }
2713 }
2714 context_.Say(source,
2715 "Object '%s' in %s directive not "
2716 "found in corresponding ALLOCATE statement"_err_en_US,
2717 name.ToString(),
2718 parser::ToUpperCaseLetters(
2719 llvm::omp::getOpenMPDirectiveName(GetContext().directive).str()));
2720 }
2721
2722 void OmpAttributeVisitor::AddOmpRequiresToScope(Scope &scope,
2723 WithOmpDeclarative::RequiresFlags flags,
2724 std::optional<common::OmpAtomicDefaultMemOrderType> memOrder) {
2725 Scope *scopeIter = &scope;
2726 do {
2727 if (Symbol * symbol{scopeIter->symbol()}) {
2728 common::visit(
2729 [&](auto &details) {
2730 // Store clauses information into the symbol for the parent and
2731 // enclosing modules, programs, functions and subroutines.
2732 if constexpr (std::is_convertible_v<decltype(&details),
2733 WithOmpDeclarative *>) {
2734 if (flags.any()) {
2735 if (const WithOmpDeclarative::RequiresFlags *
2736 otherFlags{details.ompRequires()}) {
2737 flags |= *otherFlags;
2738 }
2739 details.set_ompRequires(flags);
2740 }
2741 if (memOrder) {
2742 if (details.has_ompAtomicDefaultMemOrder() &&
2743 *details.ompAtomicDefaultMemOrder() != *memOrder) {
2744 context_.Say(scopeIter->sourceRange(),
2745 "Conflicting '%s' REQUIRES clauses found in compilation "
2746 "unit"_err_en_US,
2747 parser::ToUpperCaseLetters(llvm::omp::getOpenMPClauseName(
2748 llvm::omp::Clause::OMPC_atomic_default_mem_order)
2749 .str()));
2750 }
2751 details.set_ompAtomicDefaultMemOrder(*memOrder);
2752 }
2753 }
2754 },
2755 symbol->details());
2756 }
2757 scopeIter = &scopeIter->parent();
2758 } while (!scopeIter->IsGlobal());
2759 }
2760
2761 } // namespace Fortran::semantics