1 //===-- lib/Semantics/check-omp-structure.cpp -----------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "check-omp-structure.h"
10 #include "flang/Parser/parse-tree.h"
11 #include "flang/Semantics/tools.h"
12 #include <algorithm>
13 
14 namespace Fortran::semantics {
15 
16 // Use when clause falls under 'struct OmpClause' in 'parse-tree.h'.
17 #define CHECK_SIMPLE_CLAUSE(X, Y) \
18   void OmpStructureChecker::Enter(const parser::OmpClause::X &) { \
19     CheckAllowed(llvm::omp::Clause::Y); \
20   }
21 
22 #define CHECK_REQ_CONSTANT_SCALAR_INT_CLAUSE(X, Y) \
23   void OmpStructureChecker::Enter(const parser::OmpClause::X &c) { \
24     CheckAllowed(llvm::omp::Clause::Y); \
25     RequiresConstantPositiveParameter(llvm::omp::Clause::Y, c.v); \
26   }
27 
28 #define CHECK_REQ_SCALAR_INT_CLAUSE(X, Y) \
29   void OmpStructureChecker::Enter(const parser::OmpClause::X &c) { \
30     CheckAllowed(llvm::omp::Clause::Y); \
31     RequiresPositiveParameter(llvm::omp::Clause::Y, c.v); \
32   }
33 
34 // Use when clause don't falls under 'struct OmpClause' in 'parse-tree.h'.
35 #define CHECK_SIMPLE_PARSER_CLAUSE(X, Y) \
36   void OmpStructureChecker::Enter(const parser::X &) { \
37     CheckAllowed(llvm::omp::Y); \
38   }
39 
40 // 'OmpWorkshareBlockChecker' is used to check the validity of the assignment
41 // statements and the expressions enclosed in an OpenMP Workshare construct
42 class OmpWorkshareBlockChecker {
43 public:
44   OmpWorkshareBlockChecker(SemanticsContext &context, parser::CharBlock source)
45       : context_{context}, source_{source} {}
46 
47   template <typename T> bool Pre(const T &) { return true; }
48   template <typename T> void Post(const T &) {}
49 
50   bool Pre(const parser::AssignmentStmt &assignment) {
51     const auto &var{std::get<parser::Variable>(assignment.t)};
52     const auto &expr{std::get<parser::Expr>(assignment.t)};
53     const auto *lhs{GetExpr(var)};
54     const auto *rhs{GetExpr(expr)};
55     Tristate isDefined{semantics::IsDefinedAssignment(
56         lhs->GetType(), lhs->Rank(), rhs->GetType(), rhs->Rank())};
57     if (isDefined == Tristate::Yes) {
58       context_.Say(expr.source,
59           "Defined assignment statement is not "
60           "allowed in a WORKSHARE construct"_err_en_US);
61     }
62     return true;
63   }
64 
65   bool Pre(const parser::Expr &expr) {
66     if (const auto *e{GetExpr(expr)}) {
67       for (const Symbol &symbol : evaluate::CollectSymbols(*e)) {
68         const Symbol &root{GetAssociationRoot(symbol)};
69         if (IsFunction(root) &&
70             !(root.attrs().test(Attr::ELEMENTAL) ||
71                 root.attrs().test(Attr::INTRINSIC))) {
72           context_.Say(expr.source,
73               "User defined non-ELEMENTAL function "
74               "'%s' is not allowed in a WORKSHARE construct"_err_en_US,
75               root.name());
76         }
77       }
78     }
79     return false;
80   }
81 
82 private:
83   SemanticsContext &context_;
84   parser::CharBlock source_;
85 };
86 
87 class OmpCycleChecker {
88 public:
89   OmpCycleChecker(SemanticsContext &context, std::int64_t cycleLevel)
90       : context_{context}, cycleLevel_{cycleLevel} {}
91 
92   template <typename T> bool Pre(const T &) { return true; }
93   template <typename T> void Post(const T &) {}
94 
95   bool Pre(const parser::DoConstruct &dc) {
96     cycleLevel_--;
97     const auto &labelName{std::get<0>(std::get<0>(dc.t).statement.t)};
98     if (labelName) {
99       labelNamesandLevels_.emplace(labelName.value().ToString(), cycleLevel_);
100     }
101     return true;
102   }
103 
104   bool Pre(const parser::CycleStmt &cyclestmt) {
105     std::map<std::string, std::int64_t>::iterator it;
106     bool err{false};
107     if (cyclestmt.v) {
108       it = labelNamesandLevels_.find(cyclestmt.v->source.ToString());
109       err = (it != labelNamesandLevels_.end() && it->second > 0);
110     }
111     if (cycleLevel_ > 0 || err) {
112       context_.Say(*cycleSource_,
113           "CYCLE statement to non-innermost associated loop of an OpenMP DO construct"_err_en_US);
114     }
115     return true;
116   }
117 
118   bool Pre(const parser::Statement<parser::ActionStmt> &actionstmt) {
119     cycleSource_ = &actionstmt.source;
120     return true;
121   }
122 
123 private:
124   SemanticsContext &context_;
125   const parser::CharBlock *cycleSource_;
126   std::int64_t cycleLevel_;
127   std::map<std::string, std::int64_t> labelNamesandLevels_;
128 };
129 
130 bool OmpStructureChecker::IsCloselyNestedRegion(const OmpDirectiveSet &set) {
131   // Definition of close nesting:
132   //
133   // `A region nested inside another region with no parallel region nested
134   // between them`
135   //
136   // Examples:
137   //   non-parallel construct 1
138   //    non-parallel construct 2
139   //      parallel construct
140   //        construct 3
141   // In the above example, construct 3 is NOT closely nested inside construct 1
142   // or 2
143   //
144   //   non-parallel construct 1
145   //    non-parallel construct 2
146   //        construct 3
147   // In the above example, construct 3 is closely nested inside BOTH construct 1
148   // and 2
149   //
150   // Algorithm:
151   // Starting from the parent context, Check in a bottom-up fashion, each level
152   // of the context stack. If we have a match for one of the (supplied)
153   // violating directives, `close nesting` is satisfied. If no match is there in
154   // the entire stack, `close nesting` is not satisfied. If at any level, a
155   // `parallel` region is found, `close nesting` is not satisfied.
156 
157   if (CurrentDirectiveIsNested()) {
158     int index = dirContext_.size() - 2;
159     while (index != -1) {
160       if (set.test(dirContext_[index].directive)) {
161         return true;
162       } else if (llvm::omp::parallelSet.test(dirContext_[index].directive)) {
163         return false;
164       }
165       index--;
166     }
167   }
168   return false;
169 }
170 
171 bool OmpStructureChecker::HasInvalidWorksharingNesting(
172     const parser::CharBlock &source, const OmpDirectiveSet &set) {
173   // set contains all the invalid closely nested directives
174   // for the given directive (`source` here)
175   if (IsCloselyNestedRegion(set)) {
176     context_.Say(source,
177         "A worksharing region may not be closely nested inside a "
178         "worksharing, explicit task, taskloop, critical, ordered, atomic, or "
179         "master region"_err_en_US);
180     return true;
181   }
182   return false;
183 }
184 
185 void OmpStructureChecker::Enter(const parser::OpenMPConstruct &) {
186   // 2.8.1 TODO: Simd Construct with Ordered Construct Nesting check
187 }
188 
189 void OmpStructureChecker::Enter(const parser::OpenMPLoopConstruct &x) {
190   const auto &beginLoopDir{std::get<parser::OmpBeginLoopDirective>(x.t)};
191   const auto &beginDir{std::get<parser::OmpLoopDirective>(beginLoopDir.t)};
192 
193   // check matching, End directive is optional
194   if (const auto &endLoopDir{
195           std::get<std::optional<parser::OmpEndLoopDirective>>(x.t)}) {
196     const auto &endDir{
197         std::get<parser::OmpLoopDirective>(endLoopDir.value().t)};
198 
199     CheckMatching<parser::OmpLoopDirective>(beginDir, endDir);
200   }
201 
202   PushContextAndClauseSets(beginDir.source, beginDir.v);
203 
204   if (beginDir.v == llvm::omp::Directive::OMPD_do) {
205     // 2.7.1 do-clause -> private-clause |
206     //                    firstprivate-clause |
207     //                    lastprivate-clause |
208     //                    linear-clause |
209     //                    reduction-clause |
210     //                    schedule-clause |
211     //                    collapse-clause |
212     //                    ordered-clause
213 
214     // nesting check
215     HasInvalidWorksharingNesting(beginDir.source,
216         {llvm::omp::Directive::OMPD_do, llvm::omp::Directive::OMPD_sections,
217             llvm::omp::Directive::OMPD_single,
218             llvm::omp::Directive::OMPD_workshare,
219             llvm::omp::Directive::OMPD_task,
220             llvm::omp::Directive::OMPD_taskloop,
221             llvm::omp::Directive::OMPD_critical,
222             llvm::omp::Directive::OMPD_ordered,
223             llvm::omp::Directive::OMPD_atomic,
224             llvm::omp::Directive::OMPD_master});
225   }
226   SetLoopInfo(x);
227 
228   if (const auto &doConstruct{
229           std::get<std::optional<parser::DoConstruct>>(x.t)}) {
230     const auto &doBlock{std::get<parser::Block>(doConstruct->t)};
231     CheckNoBranching(doBlock, beginDir.v, beginDir.source);
232   }
233   CheckDoWhile(x);
234   CheckLoopItrVariableIsInt(x);
235   CheckCycleConstraints(x);
236 }
237 const parser::Name OmpStructureChecker::GetLoopIndex(
238     const parser::DoConstruct *x) {
239   using Bounds = parser::LoopControl::Bounds;
240   return std::get<Bounds>(x->GetLoopControl()->u).name.thing;
241 }
242 void OmpStructureChecker::SetLoopInfo(const parser::OpenMPLoopConstruct &x) {
243   if (const auto &loopConstruct{
244           std::get<std::optional<parser::DoConstruct>>(x.t)}) {
245     const parser::DoConstruct *loop{&*loopConstruct};
246     if (loop && loop->IsDoNormal()) {
247       const parser::Name &itrVal{GetLoopIndex(loop)};
248       SetLoopIv(itrVal.symbol);
249     }
250   }
251 }
252 void OmpStructureChecker::CheckDoWhile(const parser::OpenMPLoopConstruct &x) {
253   const auto &beginLoopDir{std::get<parser::OmpBeginLoopDirective>(x.t)};
254   const auto &beginDir{std::get<parser::OmpLoopDirective>(beginLoopDir.t)};
255   if (beginDir.v == llvm::omp::Directive::OMPD_do) {
256     if (const auto &doConstruct{
257             std::get<std::optional<parser::DoConstruct>>(x.t)}) {
258       if (doConstruct.value().IsDoWhile()) {
259         const auto &doStmt{std::get<parser::Statement<parser::NonLabelDoStmt>>(
260             doConstruct.value().t)};
261         context_.Say(doStmt.source,
262             "The DO loop cannot be a DO WHILE with DO directive."_err_en_US);
263       }
264     }
265   }
266 }
267 
268 void OmpStructureChecker::CheckLoopItrVariableIsInt(
269     const parser::OpenMPLoopConstruct &x) {
270   if (const auto &loopConstruct{
271           std::get<std::optional<parser::DoConstruct>>(x.t)}) {
272 
273     for (const parser::DoConstruct *loop{&*loopConstruct}; loop;) {
274       if (loop->IsDoNormal()) {
275         const parser::Name &itrVal{GetLoopIndex(loop)};
276         if (itrVal.symbol) {
277           const auto *type{itrVal.symbol->GetType()};
278           if (!type->IsNumeric(TypeCategory::Integer)) {
279             context_.Say(itrVal.source,
280                 "The DO loop iteration"
281                 " variable must be of the type integer."_err_en_US,
282                 itrVal.ToString());
283           }
284         }
285       }
286       // Get the next DoConstruct if block is not empty.
287       const auto &block{std::get<parser::Block>(loop->t)};
288       const auto it{block.begin()};
289       loop = it != block.end() ? parser::Unwrap<parser::DoConstruct>(*it)
290                                : nullptr;
291     }
292   }
293 }
294 
295 std::int64_t OmpStructureChecker::GetOrdCollapseLevel(
296     const parser::OpenMPLoopConstruct &x) {
297   const auto &beginLoopDir{std::get<parser::OmpBeginLoopDirective>(x.t)};
298   const auto &clauseList{std::get<parser::OmpClauseList>(beginLoopDir.t)};
299   std::int64_t orderedCollapseLevel{1};
300   std::int64_t orderedLevel{0};
301   std::int64_t collapseLevel{0};
302 
303   for (const auto &clause : clauseList.v) {
304     if (const auto *collapseClause{
305             std::get_if<parser::OmpClause::Collapse>(&clause.u)}) {
306       if (const auto v{GetIntValue(collapseClause->v)}) {
307         collapseLevel = *v;
308       }
309     }
310     if (const auto *orderedClause{
311             std::get_if<parser::OmpClause::Ordered>(&clause.u)}) {
312       if (const auto v{GetIntValue(orderedClause->v)}) {
313         orderedLevel = *v;
314       }
315     }
316   }
317   if (orderedLevel >= collapseLevel) {
318     orderedCollapseLevel = orderedLevel;
319   } else {
320     orderedCollapseLevel = collapseLevel;
321   }
322   return orderedCollapseLevel;
323 }
324 
325 void OmpStructureChecker::CheckCycleConstraints(
326     const parser::OpenMPLoopConstruct &x) {
327   std::int64_t ordCollapseLevel{GetOrdCollapseLevel(x)};
328   OmpCycleChecker ompCycleChecker{context_, ordCollapseLevel};
329   parser::Walk(x, ompCycleChecker);
330 }
331 
332 void OmpStructureChecker::Leave(const parser::OpenMPLoopConstruct &) {
333   dirContext_.pop_back();
334 }
335 
336 void OmpStructureChecker::Enter(const parser::OmpEndLoopDirective &x) {
337   const auto &dir{std::get<parser::OmpLoopDirective>(x.t)};
338   ResetPartialContext(dir.source);
339   switch (dir.v) {
340   // 2.7.1 end-do -> END DO [nowait-clause]
341   // 2.8.3 end-do-simd -> END DO SIMD [nowait-clause]
342   case llvm::omp::Directive::OMPD_do:
343   case llvm::omp::Directive::OMPD_do_simd:
344     SetClauseSets(dir.v);
345     break;
346   default:
347     // no clauses are allowed
348     break;
349   }
350 }
351 
352 void OmpStructureChecker::Enter(const parser::OpenMPBlockConstruct &x) {
353   const auto &beginBlockDir{std::get<parser::OmpBeginBlockDirective>(x.t)};
354   const auto &endBlockDir{std::get<parser::OmpEndBlockDirective>(x.t)};
355   const auto &beginDir{std::get<parser::OmpBlockDirective>(beginBlockDir.t)};
356   const auto &endDir{std::get<parser::OmpBlockDirective>(endBlockDir.t)};
357   const parser::Block &block{std::get<parser::Block>(x.t)};
358 
359   CheckMatching<parser::OmpBlockDirective>(beginDir, endDir);
360 
361   PushContextAndClauseSets(beginDir.source, beginDir.v);
362 
363   // TODO: This check needs to be extended while implementing nesting of regions
364   // checks.
365   if (beginDir.v == llvm::omp::Directive::OMPD_single) {
366     HasInvalidWorksharingNesting(
367         beginDir.source, {llvm::omp::Directive::OMPD_do});
368   }
369   if (CurrentDirectiveIsNested())
370     CheckIfDoOrderedClause(beginDir);
371 
372   CheckNoBranching(block, beginDir.v, beginDir.source);
373 
374   switch (beginDir.v) {
375   case llvm::omp::OMPD_workshare:
376   case llvm::omp::OMPD_parallel_workshare:
377     CheckWorkshareBlockStmts(block, beginDir.source);
378     break;
379   default:
380     break;
381   }
382 }
383 
384 void OmpStructureChecker::CheckIfDoOrderedClause(
385     const parser::OmpBlockDirective &blkDirective) {
386   if (blkDirective.v == llvm::omp::OMPD_ordered) {
387     // Loops
388     if (llvm::omp::doSet.test(GetContextParent().directive) &&
389         !FindClauseParent(llvm::omp::Clause::OMPC_ordered)) {
390       context_.Say(blkDirective.source,
391           "The ORDERED clause must be present on the loop"
392           " construct if any ORDERED region ever binds"
393           " to a loop region arising from the loop construct."_err_en_US);
394     }
395     // Other disallowed nestings, these directives do not support
396     // ordered clause in them, so no need to check
397     else if (IsCloselyNestedRegion(llvm::omp::nestedOrderedErrSet)) {
398       context_.Say(blkDirective.source,
399           "`ORDERED` region may not be closely nested inside of "
400           "`CRITICAL`, `ORDERED`, explicit `TASK` or `TASKLOOP` region."_err_en_US);
401     }
402   }
403 }
404 
405 void OmpStructureChecker::Leave(const parser::OpenMPBlockConstruct &) {
406   dirContext_.pop_back();
407 }
408 
409 void OmpStructureChecker::Enter(const parser::OpenMPSectionsConstruct &x) {
410   const auto &beginSectionsDir{
411       std::get<parser::OmpBeginSectionsDirective>(x.t)};
412   const auto &endSectionsDir{std::get<parser::OmpEndSectionsDirective>(x.t)};
413   const auto &beginDir{
414       std::get<parser::OmpSectionsDirective>(beginSectionsDir.t)};
415   const auto &endDir{std::get<parser::OmpSectionsDirective>(endSectionsDir.t)};
416   CheckMatching<parser::OmpSectionsDirective>(beginDir, endDir);
417 
418   PushContextAndClauseSets(beginDir.source, beginDir.v);
419   const auto &sectionBlocks{std::get<parser::OmpSectionBlocks>(x.t)};
420   for (const auto &block : sectionBlocks.v) {
421     CheckNoBranching(block, beginDir.v, beginDir.source);
422   }
423 }
424 
425 void OmpStructureChecker::Leave(const parser::OpenMPSectionsConstruct &) {
426   dirContext_.pop_back();
427 }
428 
429 void OmpStructureChecker::Enter(const parser::OmpEndSectionsDirective &x) {
430   const auto &dir{std::get<parser::OmpSectionsDirective>(x.t)};
431   ResetPartialContext(dir.source);
432   switch (dir.v) {
433     // 2.7.2 end-sections -> END SECTIONS [nowait-clause]
434   case llvm::omp::Directive::OMPD_sections:
435     PushContextAndClauseSets(
436         dir.source, llvm::omp::Directive::OMPD_end_sections);
437     break;
438   default:
439     // no clauses are allowed
440     break;
441   }
442 }
443 
444 // TODO: Verify the popping of dirContext requirement after nowait
445 // implementation, as there is an implicit barrier at the end of the worksharing
446 // constructs unless a nowait clause is specified. Only OMPD_end_sections is
447 // popped becuase it is pushed while entering the EndSectionsDirective.
448 void OmpStructureChecker::Leave(const parser::OmpEndSectionsDirective &x) {
449   if (GetContext().directive == llvm::omp::Directive::OMPD_end_sections) {
450     dirContext_.pop_back();
451   }
452 }
453 
454 void OmpStructureChecker::Enter(const parser::OpenMPDeclareSimdConstruct &x) {
455   const auto &dir{std::get<parser::Verbatim>(x.t)};
456   PushContextAndClauseSets(dir.source, llvm::omp::Directive::OMPD_declare_simd);
457 }
458 
459 void OmpStructureChecker::Leave(const parser::OpenMPDeclareSimdConstruct &) {
460   dirContext_.pop_back();
461 }
462 
463 void OmpStructureChecker::Enter(const parser::OpenMPDeclarativeAllocate &x) {
464   const auto &dir{std::get<parser::Verbatim>(x.t)};
465   PushContextAndClauseSets(dir.source, llvm::omp::Directive::OMPD_allocate);
466 }
467 
468 void OmpStructureChecker::Leave(const parser::OpenMPDeclarativeAllocate &) {
469   dirContext_.pop_back();
470 }
471 
472 void OmpStructureChecker::Enter(const parser::OpenMPDeclareTargetConstruct &x) {
473   const auto &dir{std::get<parser::Verbatim>(x.t)};
474   PushContext(dir.source, llvm::omp::Directive::OMPD_declare_target);
475   const auto &spec{std::get<parser::OmpDeclareTargetSpecifier>(x.t)};
476   if (std::holds_alternative<parser::OmpDeclareTargetWithClause>(spec.u)) {
477     SetClauseSets(llvm::omp::Directive::OMPD_declare_target);
478   }
479 }
480 
481 void OmpStructureChecker::Leave(const parser::OpenMPDeclareTargetConstruct &) {
482   dirContext_.pop_back();
483 }
484 
485 void OmpStructureChecker::Enter(const parser::OpenMPExecutableAllocate &x) {
486   const auto &dir{std::get<parser::Verbatim>(x.t)};
487   PushContextAndClauseSets(dir.source, llvm::omp::Directive::OMPD_allocate);
488 }
489 
490 void OmpStructureChecker::Leave(const parser::OpenMPExecutableAllocate &) {
491   dirContext_.pop_back();
492 }
493 
494 void OmpStructureChecker::Enter(
495     const parser::OpenMPSimpleStandaloneConstruct &x) {
496   const auto &dir{std::get<parser::OmpSimpleStandaloneDirective>(x.t)};
497   PushContextAndClauseSets(dir.source, dir.v);
498 }
499 
500 void OmpStructureChecker::Leave(
501     const parser::OpenMPSimpleStandaloneConstruct &) {
502   dirContext_.pop_back();
503 }
504 
505 void OmpStructureChecker::Enter(const parser::OpenMPFlushConstruct &x) {
506   const auto &dir{std::get<parser::Verbatim>(x.t)};
507   PushContextAndClauseSets(dir.source, llvm::omp::Directive::OMPD_flush);
508 }
509 
510 void OmpStructureChecker::Leave(const parser::OpenMPFlushConstruct &x) {
511   if (FindClause(llvm::omp::Clause::OMPC_acquire) ||
512       FindClause(llvm::omp::Clause::OMPC_release) ||
513       FindClause(llvm::omp::Clause::OMPC_acq_rel)) {
514     if (const auto &flushList{
515             std::get<std::optional<parser::OmpObjectList>>(x.t)}) {
516       context_.Say(parser::FindSourceLocation(flushList),
517           "If memory-order-clause is RELEASE, ACQUIRE, or ACQ_REL, list items "
518           "must not be specified on the FLUSH directive"_err_en_US);
519     }
520   }
521   dirContext_.pop_back();
522 }
523 
524 void OmpStructureChecker::Enter(const parser::OpenMPCancelConstruct &x) {
525   const auto &dir{std::get<parser::Verbatim>(x.t)};
526   PushContextAndClauseSets(dir.source, llvm::omp::Directive::OMPD_cancel);
527 }
528 
529 void OmpStructureChecker::Leave(const parser::OpenMPCancelConstruct &) {
530   dirContext_.pop_back();
531 }
532 
533 void OmpStructureChecker::Enter(const parser::OpenMPCriticalConstruct &x) {
534   const auto &dir{std::get<parser::OmpCriticalDirective>(x.t)};
535   PushContextAndClauseSets(dir.source, llvm::omp::Directive::OMPD_critical);
536   const auto &block{std::get<parser::Block>(x.t)};
537   CheckNoBranching(block, llvm::omp::Directive::OMPD_critical, dir.source);
538 }
539 
540 void OmpStructureChecker::Leave(const parser::OpenMPCriticalConstruct &) {
541   dirContext_.pop_back();
542 }
543 
544 void OmpStructureChecker::Enter(
545     const parser::OpenMPCancellationPointConstruct &x) {
546   const auto &dir{std::get<parser::Verbatim>(x.t)};
547   PushContextAndClauseSets(
548       dir.source, llvm::omp::Directive::OMPD_cancellation_point);
549 }
550 
551 void OmpStructureChecker::Leave(
552     const parser::OpenMPCancellationPointConstruct &) {
553   dirContext_.pop_back();
554 }
555 
556 void OmpStructureChecker::Enter(const parser::OmpEndBlockDirective &x) {
557   const auto &dir{std::get<parser::OmpBlockDirective>(x.t)};
558   ResetPartialContext(dir.source);
559   switch (dir.v) {
560   // 2.7.3 end-single-clause -> copyprivate-clause |
561   //                            nowait-clause
562   case llvm::omp::Directive::OMPD_single:
563     PushContextAndClauseSets(dir.source, llvm::omp::Directive::OMPD_end_single);
564     break;
565   // 2.7.4 end-workshare -> END WORKSHARE [nowait-clause]
566   case llvm::omp::Directive::OMPD_workshare:
567     PushContextAndClauseSets(
568         dir.source, llvm::omp::Directive::OMPD_end_workshare);
569     break;
570   default:
571     // no clauses are allowed
572     break;
573   }
574 }
575 
576 // TODO: Verify the popping of dirContext requirement after nowait
577 // implementation, as there is an implicit barrier at the end of the worksharing
578 // constructs unless a nowait clause is specified. Only OMPD_end_single and
579 // end_workshareare popped as they are pushed while entering the
580 // EndBlockDirective.
581 void OmpStructureChecker::Leave(const parser::OmpEndBlockDirective &x) {
582   if ((GetContext().directive == llvm::omp::Directive::OMPD_end_single) ||
583       (GetContext().directive == llvm::omp::Directive::OMPD_end_workshare)) {
584     dirContext_.pop_back();
585   }
586 }
587 
588 void OmpStructureChecker::Enter(const parser::OpenMPAtomicConstruct &x) {
589   std::visit(
590       common::visitors{
591           [&](const auto &someAtomicConstruct) {
592             const auto &dir{std::get<parser::Verbatim>(someAtomicConstruct.t)};
593             PushContextAndClauseSets(
594                 dir.source, llvm::omp::Directive::OMPD_atomic);
595           },
596       },
597       x.u);
598 }
599 
600 void OmpStructureChecker::Leave(const parser::OpenMPAtomicConstruct &) {
601   dirContext_.pop_back();
602 }
603 
604 // Clauses
605 // Mainly categorized as
606 // 1. Checks on 'OmpClauseList' from 'parse-tree.h'.
607 // 2. Checks on clauses which fall under 'struct OmpClause' from parse-tree.h.
608 // 3. Checks on clauses which are not in 'struct OmpClause' from parse-tree.h.
609 
610 void OmpStructureChecker::Leave(const parser::OmpClauseList &) {
611   // 2.7 Loop Construct Restriction
612   if (llvm::omp::doSet.test(GetContext().directive)) {
613     if (auto *clause{FindClause(llvm::omp::Clause::OMPC_schedule)}) {
614       // only one schedule clause is allowed
615       const auto &schedClause{std::get<parser::OmpClause::Schedule>(clause->u)};
616       if (ScheduleModifierHasType(schedClause.v,
617               parser::OmpScheduleModifierType::ModType::Nonmonotonic)) {
618         if (FindClause(llvm::omp::Clause::OMPC_ordered)) {
619           context_.Say(clause->source,
620               "The NONMONOTONIC modifier cannot be specified "
621               "if an ORDERED clause is specified"_err_en_US);
622         }
623         if (ScheduleModifierHasType(schedClause.v,
624                 parser::OmpScheduleModifierType::ModType::Monotonic)) {
625           context_.Say(clause->source,
626               "The MONOTONIC and NONMONOTONIC modifiers "
627               "cannot be both specified"_err_en_US);
628         }
629       }
630     }
631 
632     if (auto *clause{FindClause(llvm::omp::Clause::OMPC_ordered)}) {
633       // only one ordered clause is allowed
634       const auto &orderedClause{
635           std::get<parser::OmpClause::Ordered>(clause->u)};
636 
637       if (orderedClause.v) {
638         CheckNotAllowedIfClause(
639             llvm::omp::Clause::OMPC_ordered, {llvm::omp::Clause::OMPC_linear});
640 
641         if (auto *clause2{FindClause(llvm::omp::Clause::OMPC_collapse)}) {
642           const auto &collapseClause{
643               std::get<parser::OmpClause::Collapse>(clause2->u)};
644           // ordered and collapse both have parameters
645           if (const auto orderedValue{GetIntValue(orderedClause.v)}) {
646             if (const auto collapseValue{GetIntValue(collapseClause.v)}) {
647               if (*orderedValue > 0 && *orderedValue < *collapseValue) {
648                 context_.Say(clause->source,
649                     "The parameter of the ORDERED clause must be "
650                     "greater than or equal to "
651                     "the parameter of the COLLAPSE clause"_err_en_US);
652               }
653             }
654           }
655         }
656       }
657 
658       // TODO: ordered region binding check (requires nesting implementation)
659     }
660   } // doSet
661 
662   // 2.8.1 Simd Construct Restriction
663   if (llvm::omp::simdSet.test(GetContext().directive)) {
664     if (auto *clause{FindClause(llvm::omp::Clause::OMPC_simdlen)}) {
665       if (auto *clause2{FindClause(llvm::omp::Clause::OMPC_safelen)}) {
666         const auto &simdlenClause{
667             std::get<parser::OmpClause::Simdlen>(clause->u)};
668         const auto &safelenClause{
669             std::get<parser::OmpClause::Safelen>(clause2->u)};
670         // simdlen and safelen both have parameters
671         if (const auto simdlenValue{GetIntValue(simdlenClause.v)}) {
672           if (const auto safelenValue{GetIntValue(safelenClause.v)}) {
673             if (*safelenValue > 0 && *simdlenValue > *safelenValue) {
674               context_.Say(clause->source,
675                   "The parameter of the SIMDLEN clause must be less than or "
676                   "equal to the parameter of the SAFELEN clause"_err_en_US);
677             }
678           }
679         }
680       }
681     }
682     // A list-item cannot appear in more than one aligned clause
683     semantics::UnorderedSymbolSet alignedVars;
684     auto clauseAll = FindClauses(llvm::omp::Clause::OMPC_aligned);
685     for (auto itr = clauseAll.first; itr != clauseAll.second; ++itr) {
686       const auto &alignedClause{
687           std::get<parser::OmpClause::Aligned>(itr->second->u)};
688       const auto &alignedNameList{
689           std::get<std::list<parser::Name>>(alignedClause.v.t)};
690       for (auto const &var : alignedNameList) {
691         if (alignedVars.count(*(var.symbol)) == 1) {
692           context_.Say(itr->second->source,
693               "List item '%s' present at multiple ALIGNED clauses"_err_en_US,
694               var.ToString());
695           break;
696         }
697         alignedVars.insert(*(var.symbol));
698       }
699     }
700   } // SIMD
701 
702   // 2.7.3 Single Construct Restriction
703   if (GetContext().directive == llvm::omp::Directive::OMPD_end_single) {
704     CheckNotAllowedIfClause(
705         llvm::omp::Clause::OMPC_copyprivate, {llvm::omp::Clause::OMPC_nowait});
706   }
707 
708   CheckRequireAtLeastOneOf();
709 }
710 
711 void OmpStructureChecker::Enter(const parser::OmpClause &x) {
712   SetContextClause(x);
713 }
714 
715 // Following clauses do not have a separate node in parse-tree.h.
716 CHECK_SIMPLE_CLAUSE(AcqRel, OMPC_acq_rel)
717 CHECK_SIMPLE_CLAUSE(Acquire, OMPC_acquire)
718 CHECK_SIMPLE_CLAUSE(AtomicDefaultMemOrder, OMPC_atomic_default_mem_order)
719 CHECK_SIMPLE_CLAUSE(Affinity, OMPC_affinity)
720 CHECK_SIMPLE_CLAUSE(Allocate, OMPC_allocate)
721 CHECK_SIMPLE_CLAUSE(Capture, OMPC_capture)
722 CHECK_SIMPLE_CLAUSE(Copyin, OMPC_copyin)
723 CHECK_SIMPLE_CLAUSE(Default, OMPC_default)
724 CHECK_SIMPLE_CLAUSE(Depobj, OMPC_depobj)
725 CHECK_SIMPLE_CLAUSE(Destroy, OMPC_destroy)
726 CHECK_SIMPLE_CLAUSE(Detach, OMPC_detach)
727 CHECK_SIMPLE_CLAUSE(Device, OMPC_device)
728 CHECK_SIMPLE_CLAUSE(DeviceType, OMPC_device_type)
729 CHECK_SIMPLE_CLAUSE(DistSchedule, OMPC_dist_schedule)
730 CHECK_SIMPLE_CLAUSE(DynamicAllocators, OMPC_dynamic_allocators)
731 CHECK_SIMPLE_CLAUSE(Exclusive, OMPC_exclusive)
732 CHECK_SIMPLE_CLAUSE(Final, OMPC_final)
733 CHECK_SIMPLE_CLAUSE(Flush, OMPC_flush)
734 CHECK_SIMPLE_CLAUSE(From, OMPC_from)
735 CHECK_SIMPLE_CLAUSE(Hint, OMPC_hint)
736 CHECK_SIMPLE_CLAUSE(InReduction, OMPC_in_reduction)
737 CHECK_SIMPLE_CLAUSE(Inclusive, OMPC_inclusive)
738 CHECK_SIMPLE_CLAUSE(Match, OMPC_match)
739 CHECK_SIMPLE_CLAUSE(Nontemporal, OMPC_nontemporal)
740 CHECK_SIMPLE_CLAUSE(Order, OMPC_order)
741 CHECK_SIMPLE_CLAUSE(Read, OMPC_read)
742 CHECK_SIMPLE_CLAUSE(ReverseOffload, OMPC_reverse_offload)
743 CHECK_SIMPLE_CLAUSE(Threadprivate, OMPC_threadprivate)
744 CHECK_SIMPLE_CLAUSE(Threads, OMPC_threads)
745 CHECK_SIMPLE_CLAUSE(Inbranch, OMPC_inbranch)
746 CHECK_SIMPLE_CLAUSE(IsDevicePtr, OMPC_is_device_ptr)
747 CHECK_SIMPLE_CLAUSE(Link, OMPC_link)
748 CHECK_SIMPLE_CLAUSE(Mergeable, OMPC_mergeable)
749 CHECK_SIMPLE_CLAUSE(Nogroup, OMPC_nogroup)
750 CHECK_SIMPLE_CLAUSE(Notinbranch, OMPC_notinbranch)
751 CHECK_SIMPLE_CLAUSE(Nowait, OMPC_nowait)
752 CHECK_SIMPLE_CLAUSE(ProcBind, OMPC_proc_bind)
753 CHECK_SIMPLE_CLAUSE(Release, OMPC_release)
754 CHECK_SIMPLE_CLAUSE(Relaxed, OMPC_relaxed)
755 CHECK_SIMPLE_CLAUSE(SeqCst, OMPC_seq_cst)
756 CHECK_SIMPLE_CLAUSE(Simd, OMPC_simd)
757 CHECK_SIMPLE_CLAUSE(Sizes, OMPC_sizes)
758 CHECK_SIMPLE_CLAUSE(TaskReduction, OMPC_task_reduction)
759 CHECK_SIMPLE_CLAUSE(To, OMPC_to)
760 CHECK_SIMPLE_CLAUSE(UnifiedAddress, OMPC_unified_address)
761 CHECK_SIMPLE_CLAUSE(UnifiedSharedMemory, OMPC_unified_shared_memory)
762 CHECK_SIMPLE_CLAUSE(Uniform, OMPC_uniform)
763 CHECK_SIMPLE_CLAUSE(Unknown, OMPC_unknown)
764 CHECK_SIMPLE_CLAUSE(Untied, OMPC_untied)
765 CHECK_SIMPLE_CLAUSE(UseDevicePtr, OMPC_use_device_ptr)
766 CHECK_SIMPLE_CLAUSE(UsesAllocators, OMPC_uses_allocators)
767 CHECK_SIMPLE_CLAUSE(Update, OMPC_update)
768 CHECK_SIMPLE_CLAUSE(UseDeviceAddr, OMPC_use_device_addr)
769 CHECK_SIMPLE_CLAUSE(Write, OMPC_write)
770 CHECK_SIMPLE_CLAUSE(Init, OMPC_init)
771 CHECK_SIMPLE_CLAUSE(Use, OMPC_use)
772 CHECK_SIMPLE_CLAUSE(Novariants, OMPC_novariants)
773 CHECK_SIMPLE_CLAUSE(Nocontext, OMPC_nocontext)
774 CHECK_SIMPLE_CLAUSE(Filter, OMPC_filter)
775 
776 CHECK_REQ_SCALAR_INT_CLAUSE(Allocator, OMPC_allocator)
777 CHECK_REQ_SCALAR_INT_CLAUSE(Grainsize, OMPC_grainsize)
778 CHECK_REQ_SCALAR_INT_CLAUSE(NumTasks, OMPC_num_tasks)
779 CHECK_REQ_SCALAR_INT_CLAUSE(NumTeams, OMPC_num_teams)
780 CHECK_REQ_SCALAR_INT_CLAUSE(NumThreads, OMPC_num_threads)
781 CHECK_REQ_SCALAR_INT_CLAUSE(Priority, OMPC_priority)
782 CHECK_REQ_SCALAR_INT_CLAUSE(ThreadLimit, OMPC_thread_limit)
783 
784 CHECK_REQ_CONSTANT_SCALAR_INT_CLAUSE(Collapse, OMPC_collapse)
785 CHECK_REQ_CONSTANT_SCALAR_INT_CLAUSE(Safelen, OMPC_safelen)
786 CHECK_REQ_CONSTANT_SCALAR_INT_CLAUSE(Simdlen, OMPC_simdlen)
787 
788 // Restrictions specific to each clause are implemented apart from the
789 // generalized restrictions.
790 void OmpStructureChecker::Enter(const parser::OmpClause::Reduction &x) {
791   CheckAllowed(llvm::omp::Clause::OMPC_reduction);
792   if (CheckReductionOperators(x)) {
793     CheckReductionTypeList(x);
794   }
795 }
796 bool OmpStructureChecker::CheckReductionOperators(
797     const parser::OmpClause::Reduction &x) {
798 
799   const auto &definedOp{std::get<0>(x.v.t)};
800   bool ok = false;
801   std::visit(
802       common::visitors{
803           [&](const parser::DefinedOperator &dOpr) {
804             const auto &intrinsicOp{
805                 std::get<parser::DefinedOperator::IntrinsicOperator>(dOpr.u)};
806             ok = CheckIntrinsicOperator(intrinsicOp);
807           },
808           [&](const parser::ProcedureDesignator &procD) {
809             const parser::Name *name{std::get_if<parser::Name>(&procD.u)};
810             if (name) {
811               if (name->source == "max" || name->source == "min" ||
812                   name->source == "iand" || name->source == "ior" ||
813                   name->source == "ieor") {
814                 ok = true;
815               } else {
816                 context_.Say(GetContext().clauseSource,
817                     "Invalid reduction identifier in REDUCTION clause."_err_en_US,
818                     ContextDirectiveAsFortran());
819               }
820             }
821           },
822       },
823       definedOp.u);
824 
825   return ok;
826 }
827 bool OmpStructureChecker::CheckIntrinsicOperator(
828     const parser::DefinedOperator::IntrinsicOperator &op) {
829 
830   switch (op) {
831   case parser::DefinedOperator::IntrinsicOperator::Add:
832   case parser::DefinedOperator::IntrinsicOperator::Subtract:
833   case parser::DefinedOperator::IntrinsicOperator::Multiply:
834   case parser::DefinedOperator::IntrinsicOperator::AND:
835   case parser::DefinedOperator::IntrinsicOperator::OR:
836   case parser::DefinedOperator::IntrinsicOperator::EQV:
837   case parser::DefinedOperator::IntrinsicOperator::NEQV:
838     return true;
839   default:
840     context_.Say(GetContext().clauseSource,
841         "Invalid reduction operator in REDUCTION clause."_err_en_US,
842         ContextDirectiveAsFortran());
843   }
844   return false;
845 }
846 
847 void OmpStructureChecker::CheckReductionTypeList(
848     const parser::OmpClause::Reduction &x) {
849   const auto &ompObjectList{std::get<parser::OmpObjectList>(x.v.t)};
850   CheckIntentInPointerAndDefinable(
851       ompObjectList, llvm::omp::Clause::OMPC_reduction);
852   CheckReductionArraySection(ompObjectList);
853   CheckMultipleAppearanceAcrossContext(ompObjectList);
854 }
855 
856 void OmpStructureChecker::CheckIntentInPointerAndDefinable(
857     const parser::OmpObjectList &objectList, const llvm::omp::Clause clause) {
858   for (const auto &ompObject : objectList.v) {
859     if (const auto *name{parser::Unwrap<parser::Name>(ompObject)}) {
860       if (const auto *symbol{name->symbol}) {
861         if (IsPointer(symbol->GetUltimate()) &&
862             IsIntentIn(symbol->GetUltimate())) {
863           context_.Say(GetContext().clauseSource,
864               "Pointer '%s' with the INTENT(IN) attribute may not appear "
865               "in a %s clause"_err_en_US,
866               symbol->name(),
867               parser::ToUpperCaseLetters(getClauseName(clause).str()));
868         }
869         if (auto msg{
870                 WhyNotModifiable(*symbol, context_.FindScope(name->source))}) {
871           context_.Say(GetContext().clauseSource,
872               "Variable '%s' on the %s clause is not definable"_err_en_US,
873               symbol->name(),
874               parser::ToUpperCaseLetters(getClauseName(clause).str()));
875         }
876       }
877     }
878   }
879 }
880 
881 void OmpStructureChecker::CheckReductionArraySection(
882     const parser::OmpObjectList &ompObjectList) {
883   for (const auto &ompObject : ompObjectList.v) {
884     if (const auto *dataRef{parser::Unwrap<parser::DataRef>(ompObject)}) {
885       if (const auto *arrayElement{
886               parser::Unwrap<parser::ArrayElement>(ompObject)}) {
887         if (arrayElement) {
888           CheckArraySection(*arrayElement, GetLastName(*dataRef),
889               llvm::omp::Clause::OMPC_reduction);
890         }
891       }
892     }
893   }
894 }
895 
896 void OmpStructureChecker::CheckMultipleAppearanceAcrossContext(
897     const parser::OmpObjectList &redObjectList) {
898   //  TODO: Verify the assumption here that the immediately enclosing region is
899   //  the parallel region to which the worksharing construct having reduction
900   //  binds to.
901   if (auto *enclosingContext{GetEnclosingDirContext()}) {
902     for (auto it : enclosingContext->clauseInfo) {
903       llvmOmpClause type = it.first;
904       const auto *clause = it.second;
905       if (llvm::omp::privateReductionSet.test(type)) {
906         if (const auto *objList{GetOmpObjectList(*clause)}) {
907           for (const auto &ompObject : objList->v) {
908             if (const auto *name{parser::Unwrap<parser::Name>(ompObject)}) {
909               if (const auto *symbol{name->symbol}) {
910                 for (const auto &redOmpObject : redObjectList.v) {
911                   if (const auto *rname{
912                           parser::Unwrap<parser::Name>(redOmpObject)}) {
913                     if (const auto *rsymbol{rname->symbol}) {
914                       if (rsymbol->name() == symbol->name()) {
915                         context_.Say(GetContext().clauseSource,
916                             "%s variable '%s' is %s in outer context must"
917                             " be shared in the parallel regions to which any"
918                             " of the worksharing regions arising from the "
919                             "worksharing"
920                             " construct bind."_err_en_US,
921                             parser::ToUpperCaseLetters(
922                                 getClauseName(llvm::omp::Clause::OMPC_reduction)
923                                     .str()),
924                             symbol->name(),
925                             parser::ToUpperCaseLetters(
926                                 getClauseName(type).str()));
927                       }
928                     }
929                   }
930                 }
931               }
932             }
933           }
934         }
935       }
936     }
937   }
938 }
939 
940 void OmpStructureChecker::Enter(const parser::OmpClause::Ordered &x) {
941   CheckAllowed(llvm::omp::Clause::OMPC_ordered);
942   // the parameter of ordered clause is optional
943   if (const auto &expr{x.v}) {
944     RequiresConstantPositiveParameter(llvm::omp::Clause::OMPC_ordered, *expr);
945     // 2.8.3 Loop SIMD Construct Restriction
946     if (llvm::omp::doSimdSet.test(GetContext().directive)) {
947       context_.Say(GetContext().clauseSource,
948           "No ORDERED clause with a parameter can be specified "
949           "on the %s directive"_err_en_US,
950           ContextDirectiveAsFortran());
951     }
952   }
953 }
954 
955 void OmpStructureChecker::Enter(const parser::OmpClause::Shared &x) {
956   CheckAllowed(llvm::omp::Clause::OMPC_shared);
957   CheckIsVarPartOfAnotherVar(x.v);
958 }
959 void OmpStructureChecker::Enter(const parser::OmpClause::Private &x) {
960   CheckAllowed(llvm::omp::Clause::OMPC_private);
961   CheckIsVarPartOfAnotherVar(x.v);
962   CheckIntentInPointer(x.v, llvm::omp::Clause::OMPC_private);
963 }
964 
965 void OmpStructureChecker::CheckIsVarPartOfAnotherVar(
966     const parser::OmpObjectList &objList) {
967   for (const auto &ompObject : objList.v) {
968     if ((parser::Unwrap<parser::StructureComponent>(ompObject)) ||
969         (parser::Unwrap<parser::ArrayElement>(ompObject))) {
970       context_.Say(GetContext().clauseSource,
971           "A variable that is part of another variable (as an "
972           "array or structure element)"
973           " cannot appear in a PRIVATE or SHARED clause."_err_en_US);
974     }
975   }
976 }
977 void OmpStructureChecker::Enter(const parser::OmpClause::Firstprivate &x) {
978   CheckAllowed(llvm::omp::Clause::OMPC_firstprivate);
979   CheckIsLoopIvPartOfClause(llvmOmpClause::OMPC_firstprivate, x.v);
980 
981   SymbolSourceMap currSymbols;
982   GetSymbolsInObjectList(x.v, currSymbols);
983 
984   DirectivesClauseTriple dirClauseTriple;
985   // Check firstprivate variables in worksharing constructs
986   dirClauseTriple.emplace(llvm::omp::Directive::OMPD_do,
987       std::make_pair(
988           llvm::omp::Directive::OMPD_parallel, llvm::omp::privateReductionSet));
989   dirClauseTriple.emplace(llvm::omp::Directive::OMPD_sections,
990       std::make_pair(
991           llvm::omp::Directive::OMPD_parallel, llvm::omp::privateReductionSet));
992   dirClauseTriple.emplace(llvm::omp::Directive::OMPD_single,
993       std::make_pair(
994           llvm::omp::Directive::OMPD_parallel, llvm::omp::privateReductionSet));
995   // Check firstprivate variables in distribute construct
996   dirClauseTriple.emplace(llvm::omp::Directive::OMPD_distribute,
997       std::make_pair(
998           llvm::omp::Directive::OMPD_teams, llvm::omp::privateReductionSet));
999   dirClauseTriple.emplace(llvm::omp::Directive::OMPD_distribute,
1000       std::make_pair(llvm::omp::Directive::OMPD_target_teams,
1001           llvm::omp::privateReductionSet));
1002   // Check firstprivate variables in task and taskloop constructs
1003   dirClauseTriple.emplace(llvm::omp::Directive::OMPD_task,
1004       std::make_pair(llvm::omp::Directive::OMPD_parallel,
1005           OmpClauseSet{llvm::omp::Clause::OMPC_reduction}));
1006   dirClauseTriple.emplace(llvm::omp::Directive::OMPD_taskloop,
1007       std::make_pair(llvm::omp::Directive::OMPD_parallel,
1008           OmpClauseSet{llvm::omp::Clause::OMPC_reduction}));
1009 
1010   CheckPrivateSymbolsInOuterCxt(
1011       currSymbols, dirClauseTriple, llvm::omp::Clause::OMPC_firstprivate);
1012 }
1013 
1014 void OmpStructureChecker::CheckIsLoopIvPartOfClause(
1015     llvmOmpClause clause, const parser::OmpObjectList &ompObjectList) {
1016   for (const auto &ompObject : ompObjectList.v) {
1017     if (const parser::Name * name{parser::Unwrap<parser::Name>(ompObject)}) {
1018       if (name->symbol == GetContext().loopIV) {
1019         context_.Say(name->source,
1020             "DO iteration variable %s is not allowed in %s clause."_err_en_US,
1021             name->ToString(),
1022             parser::ToUpperCaseLetters(getClauseName(clause).str()));
1023       }
1024     }
1025   }
1026 }
1027 // Following clauses have a seperate node in parse-tree.h.
1028 // Atomic-clause
1029 CHECK_SIMPLE_PARSER_CLAUSE(OmpAtomicRead, OMPC_read)
1030 CHECK_SIMPLE_PARSER_CLAUSE(OmpAtomicWrite, OMPC_write)
1031 CHECK_SIMPLE_PARSER_CLAUSE(OmpAtomicUpdate, OMPC_update)
1032 CHECK_SIMPLE_PARSER_CLAUSE(OmpAtomicCapture, OMPC_capture)
1033 
1034 void OmpStructureChecker::Leave(const parser::OmpAtomicRead &) {
1035   CheckNotAllowedIfClause(llvm::omp::Clause::OMPC_read,
1036       {llvm::omp::Clause::OMPC_release, llvm::omp::Clause::OMPC_acq_rel});
1037 }
1038 void OmpStructureChecker::Leave(const parser::OmpAtomicWrite &) {
1039   CheckNotAllowedIfClause(llvm::omp::Clause::OMPC_write,
1040       {llvm::omp::Clause::OMPC_acquire, llvm::omp::Clause::OMPC_acq_rel});
1041 }
1042 void OmpStructureChecker::Leave(const parser::OmpAtomicUpdate &) {
1043   CheckNotAllowedIfClause(llvm::omp::Clause::OMPC_update,
1044       {llvm::omp::Clause::OMPC_acquire, llvm::omp::Clause::OMPC_acq_rel});
1045 }
1046 // OmpAtomic node represents atomic directive without atomic-clause.
1047 // atomic-clause - READ,WRITE,UPDATE,CAPTURE.
1048 void OmpStructureChecker::Leave(const parser::OmpAtomic &) {
1049   if (const auto *clause{FindClause(llvm::omp::Clause::OMPC_acquire)}) {
1050     context_.Say(clause->source,
1051         "Clause ACQUIRE is not allowed on the ATOMIC directive"_err_en_US);
1052   }
1053   if (const auto *clause{FindClause(llvm::omp::Clause::OMPC_acq_rel)}) {
1054     context_.Say(clause->source,
1055         "Clause ACQ_REL is not allowed on the ATOMIC directive"_err_en_US);
1056   }
1057 }
1058 // Restrictions specific to each clause are implemented apart from the
1059 // generalized restrictions.
1060 void OmpStructureChecker::Enter(const parser::OmpClause::Aligned &x) {
1061   CheckAllowed(llvm::omp::Clause::OMPC_aligned);
1062 
1063   if (const auto &expr{
1064           std::get<std::optional<parser::ScalarIntConstantExpr>>(x.v.t)}) {
1065     RequiresConstantPositiveParameter(llvm::omp::Clause::OMPC_aligned, *expr);
1066   }
1067   // 2.8.1 TODO: list-item attribute check
1068 }
1069 void OmpStructureChecker::Enter(const parser::OmpClause::Defaultmap &x) {
1070   CheckAllowed(llvm::omp::Clause::OMPC_defaultmap);
1071   using VariableCategory = parser::OmpDefaultmapClause::VariableCategory;
1072   if (!std::get<std::optional<VariableCategory>>(x.v.t)) {
1073     context_.Say(GetContext().clauseSource,
1074         "The argument TOFROM:SCALAR must be specified on the DEFAULTMAP "
1075         "clause"_err_en_US);
1076   }
1077 }
1078 void OmpStructureChecker::Enter(const parser::OmpClause::If &x) {
1079   CheckAllowed(llvm::omp::Clause::OMPC_if);
1080   using dirNameModifier = parser::OmpIfClause::DirectiveNameModifier;
1081   static std::unordered_map<dirNameModifier, OmpDirectiveSet>
1082       dirNameModifierMap{{dirNameModifier::Parallel, llvm::omp::parallelSet},
1083           {dirNameModifier::Target, llvm::omp::targetSet},
1084           {dirNameModifier::TargetEnterData,
1085               {llvm::omp::Directive::OMPD_target_enter_data}},
1086           {dirNameModifier::TargetExitData,
1087               {llvm::omp::Directive::OMPD_target_exit_data}},
1088           {dirNameModifier::TargetData,
1089               {llvm::omp::Directive::OMPD_target_data}},
1090           {dirNameModifier::TargetUpdate,
1091               {llvm::omp::Directive::OMPD_target_update}},
1092           {dirNameModifier::Task, {llvm::omp::Directive::OMPD_task}},
1093           {dirNameModifier::Taskloop, llvm::omp::taskloopSet}};
1094   if (const auto &directiveName{
1095           std::get<std::optional<dirNameModifier>>(x.v.t)}) {
1096     auto search{dirNameModifierMap.find(*directiveName)};
1097     if (search == dirNameModifierMap.end() ||
1098         !search->second.test(GetContext().directive)) {
1099       context_
1100           .Say(GetContext().clauseSource,
1101               "Unmatched directive name modifier %s on the IF clause"_err_en_US,
1102               parser::ToUpperCaseLetters(
1103                   parser::OmpIfClause::EnumToString(*directiveName)))
1104           .Attach(
1105               GetContext().directiveSource, "Cannot apply to directive"_en_US);
1106     }
1107   }
1108 }
1109 
1110 void OmpStructureChecker::Enter(const parser::OmpClause::Linear &x) {
1111   CheckAllowed(llvm::omp::Clause::OMPC_linear);
1112 
1113   // 2.7 Loop Construct Restriction
1114   if ((llvm::omp::doSet | llvm::omp::simdSet).test(GetContext().directive)) {
1115     if (std::holds_alternative<parser::OmpLinearClause::WithModifier>(x.v.u)) {
1116       context_.Say(GetContext().clauseSource,
1117           "A modifier may not be specified in a LINEAR clause "
1118           "on the %s directive"_err_en_US,
1119           ContextDirectiveAsFortran());
1120     }
1121   }
1122 }
1123 
1124 void OmpStructureChecker::CheckAllowedMapTypes(
1125     const parser::OmpMapType::Type &type,
1126     const std::list<parser::OmpMapType::Type> &allowedMapTypeList) {
1127   const auto found{std::find(
1128       std::begin(allowedMapTypeList), std::end(allowedMapTypeList), type)};
1129   if (found == std::end(allowedMapTypeList)) {
1130     std::string commaSeperatedMapTypes;
1131     llvm::interleave(
1132         allowedMapTypeList.begin(), allowedMapTypeList.end(),
1133         [&](const parser::OmpMapType::Type &mapType) {
1134           commaSeperatedMapTypes.append(parser::ToUpperCaseLetters(
1135               parser::OmpMapType::EnumToString(mapType)));
1136         },
1137         [&] { commaSeperatedMapTypes.append(", "); });
1138     context_.Say(GetContext().clauseSource,
1139         "Only the %s map types are permitted "
1140         "for MAP clauses on the %s directive"_err_en_US,
1141         commaSeperatedMapTypes, ContextDirectiveAsFortran());
1142   }
1143 }
1144 
1145 void OmpStructureChecker::Enter(const parser::OmpClause::Map &x) {
1146   CheckAllowed(llvm::omp::Clause::OMPC_map);
1147 
1148   if (const auto &maptype{std::get<std::optional<parser::OmpMapType>>(x.v.t)}) {
1149     using Type = parser::OmpMapType::Type;
1150     const Type &type{std::get<Type>(maptype->t)};
1151     switch (GetContext().directive) {
1152     case llvm::omp::Directive::OMPD_target:
1153     case llvm::omp::Directive::OMPD_target_teams:
1154     case llvm::omp::Directive::OMPD_target_teams_distribute:
1155     case llvm::omp::Directive::OMPD_target_teams_distribute_simd:
1156     case llvm::omp::Directive::OMPD_target_teams_distribute_parallel_do:
1157     case llvm::omp::Directive::OMPD_target_teams_distribute_parallel_do_simd:
1158     case llvm::omp::Directive::OMPD_target_data:
1159       CheckAllowedMapTypes(
1160           type, {Type::To, Type::From, Type::Tofrom, Type::Alloc});
1161       break;
1162     case llvm::omp::Directive::OMPD_target_enter_data:
1163       CheckAllowedMapTypes(type, {Type::To, Type::Alloc});
1164       break;
1165     case llvm::omp::Directive::OMPD_target_exit_data:
1166       CheckAllowedMapTypes(type, {Type::From, Type::Release, Type::Delete});
1167       break;
1168     default:
1169       break;
1170     }
1171   }
1172 }
1173 
1174 bool OmpStructureChecker::ScheduleModifierHasType(
1175     const parser::OmpScheduleClause &x,
1176     const parser::OmpScheduleModifierType::ModType &type) {
1177   const auto &modifier{
1178       std::get<std::optional<parser::OmpScheduleModifier>>(x.t)};
1179   if (modifier) {
1180     const auto &modType1{
1181         std::get<parser::OmpScheduleModifier::Modifier1>(modifier->t)};
1182     const auto &modType2{
1183         std::get<std::optional<parser::OmpScheduleModifier::Modifier2>>(
1184             modifier->t)};
1185     if (modType1.v.v == type || (modType2 && modType2->v.v == type)) {
1186       return true;
1187     }
1188   }
1189   return false;
1190 }
1191 void OmpStructureChecker::Enter(const parser::OmpClause::Schedule &x) {
1192   CheckAllowed(llvm::omp::Clause::OMPC_schedule);
1193   const parser::OmpScheduleClause &scheduleClause = x.v;
1194 
1195   // 2.7 Loop Construct Restriction
1196   if (llvm::omp::doSet.test(GetContext().directive)) {
1197     const auto &kind{std::get<1>(scheduleClause.t)};
1198     const auto &chunk{std::get<2>(scheduleClause.t)};
1199     if (chunk) {
1200       if (kind == parser::OmpScheduleClause::ScheduleType::Runtime ||
1201           kind == parser::OmpScheduleClause::ScheduleType::Auto) {
1202         context_.Say(GetContext().clauseSource,
1203             "When SCHEDULE clause has %s specified, "
1204             "it must not have chunk size specified"_err_en_US,
1205             parser::ToUpperCaseLetters(
1206                 parser::OmpScheduleClause::EnumToString(kind)));
1207       }
1208       if (const auto &chunkExpr{std::get<std::optional<parser::ScalarIntExpr>>(
1209               scheduleClause.t)}) {
1210         RequiresPositiveParameter(
1211             llvm::omp::Clause::OMPC_schedule, *chunkExpr, "chunk size");
1212       }
1213     }
1214 
1215     if (ScheduleModifierHasType(scheduleClause,
1216             parser::OmpScheduleModifierType::ModType::Nonmonotonic)) {
1217       if (kind != parser::OmpScheduleClause::ScheduleType::Dynamic &&
1218           kind != parser::OmpScheduleClause::ScheduleType::Guided) {
1219         context_.Say(GetContext().clauseSource,
1220             "The NONMONOTONIC modifier can only be specified with "
1221             "SCHEDULE(DYNAMIC) or SCHEDULE(GUIDED)"_err_en_US);
1222       }
1223     }
1224   }
1225 }
1226 
1227 void OmpStructureChecker::Enter(const parser::OmpClause::Depend &x) {
1228   CheckAllowed(llvm::omp::Clause::OMPC_depend);
1229   if (const auto *inOut{std::get_if<parser::OmpDependClause::InOut>(&x.v.u)}) {
1230     const auto &designators{std::get<std::list<parser::Designator>>(inOut->t)};
1231     for (const auto &ele : designators) {
1232       if (const auto *dataRef{std::get_if<parser::DataRef>(&ele.u)}) {
1233         CheckDependList(*dataRef);
1234         if (const auto *arr{
1235                 std::get_if<common::Indirection<parser::ArrayElement>>(
1236                     &dataRef->u)}) {
1237           CheckArraySection(arr->value(), GetLastName(*dataRef),
1238               llvm::omp::Clause::OMPC_depend);
1239         }
1240       }
1241     }
1242   }
1243 }
1244 
1245 void OmpStructureChecker::Enter(const parser::OmpClause::Copyprivate &x) {
1246   CheckAllowed(llvm::omp::Clause::OMPC_copyprivate);
1247   CheckIntentInPointer(x.v, llvm::omp::Clause::OMPC_copyprivate);
1248 }
1249 
1250 void OmpStructureChecker::Enter(const parser::OmpClause::Lastprivate &x) {
1251   CheckAllowed(llvm::omp::Clause::OMPC_lastprivate);
1252 
1253   DirectivesClauseTriple dirClauseTriple;
1254   SymbolSourceMap currSymbols;
1255   GetSymbolsInObjectList(x.v, currSymbols);
1256   CheckDefinableObjects(currSymbols, GetClauseKindForParserClass(x));
1257 
1258   // Check lastprivate variables in worksharing constructs
1259   dirClauseTriple.emplace(llvm::omp::Directive::OMPD_do,
1260       std::make_pair(
1261           llvm::omp::Directive::OMPD_parallel, llvm::omp::privateReductionSet));
1262   dirClauseTriple.emplace(llvm::omp::Directive::OMPD_sections,
1263       std::make_pair(
1264           llvm::omp::Directive::OMPD_parallel, llvm::omp::privateReductionSet));
1265 
1266   CheckPrivateSymbolsInOuterCxt(
1267       currSymbols, dirClauseTriple, GetClauseKindForParserClass(x));
1268 }
1269 
1270 llvm::StringRef OmpStructureChecker::getClauseName(llvm::omp::Clause clause) {
1271   return llvm::omp::getOpenMPClauseName(clause);
1272 }
1273 
1274 llvm::StringRef OmpStructureChecker::getDirectiveName(
1275     llvm::omp::Directive directive) {
1276   return llvm::omp::getOpenMPDirectiveName(directive);
1277 }
1278 
1279 void OmpStructureChecker::CheckDependList(const parser::DataRef &d) {
1280   std::visit(
1281       common::visitors{
1282           [&](const common::Indirection<parser::ArrayElement> &elem) {
1283             // Check if the base element is valid on Depend Clause
1284             CheckDependList(elem.value().base);
1285           },
1286           [&](const common::Indirection<parser::StructureComponent> &) {
1287             context_.Say(GetContext().clauseSource,
1288                 "A variable that is part of another variable "
1289                 "(such as an element of a structure) but is not an array "
1290                 "element or an array section cannot appear in a DEPEND "
1291                 "clause"_err_en_US);
1292           },
1293           [&](const common::Indirection<parser::CoindexedNamedObject> &) {
1294             context_.Say(GetContext().clauseSource,
1295                 "Coarrays are not supported in DEPEND clause"_err_en_US);
1296           },
1297           [&](const parser::Name &) { return; },
1298       },
1299       d.u);
1300 }
1301 
1302 // Called from both Reduction and Depend clause.
1303 void OmpStructureChecker::CheckArraySection(
1304     const parser::ArrayElement &arrayElement, const parser::Name &name,
1305     const llvm::omp::Clause clause) {
1306   if (!arrayElement.subscripts.empty()) {
1307     for (const auto &subscript : arrayElement.subscripts) {
1308       if (const auto *triplet{
1309               std::get_if<parser::SubscriptTriplet>(&subscript.u)}) {
1310         if (std::get<0>(triplet->t) && std::get<1>(triplet->t)) {
1311           const auto &lower{std::get<0>(triplet->t)};
1312           const auto &upper{std::get<1>(triplet->t)};
1313           if (lower && upper) {
1314             const auto lval{GetIntValue(lower)};
1315             const auto uval{GetIntValue(upper)};
1316             if (lval && uval && *uval < *lval) {
1317               context_.Say(GetContext().clauseSource,
1318                   "'%s' in %s clause"
1319                   " is a zero size array section"_err_en_US,
1320                   name.ToString(),
1321                   parser::ToUpperCaseLetters(getClauseName(clause).str()));
1322               break;
1323             } else if (std::get<2>(triplet->t)) {
1324               const auto &strideExpr{std::get<2>(triplet->t)};
1325               if (strideExpr) {
1326                 if (clause == llvm::omp::Clause::OMPC_depend) {
1327                   context_.Say(GetContext().clauseSource,
1328                       "Stride should not be specified for array section in "
1329                       "DEPEND "
1330                       "clause"_err_en_US);
1331                 }
1332                 const auto stride{GetIntValue(strideExpr)};
1333                 if ((stride && stride != 1)) {
1334                   context_.Say(GetContext().clauseSource,
1335                       "A list item that appears in a REDUCTION clause"
1336                       " should have a contiguous storage array section."_err_en_US,
1337                       ContextDirectiveAsFortran());
1338                   break;
1339                 }
1340               }
1341             }
1342           }
1343         }
1344       }
1345     }
1346   }
1347 }
1348 
1349 void OmpStructureChecker::CheckIntentInPointer(
1350     const parser::OmpObjectList &objectList, const llvm::omp::Clause clause) {
1351   SymbolSourceMap symbols;
1352   GetSymbolsInObjectList(objectList, symbols);
1353   for (auto it{symbols.begin()}; it != symbols.end(); ++it) {
1354     const auto *symbol{it->first};
1355     const auto source{it->second};
1356     if (IsPointer(*symbol) && IsIntentIn(*symbol)) {
1357       context_.Say(source,
1358           "Pointer '%s' with the INTENT(IN) attribute may not appear "
1359           "in a %s clause"_err_en_US,
1360           symbol->name(),
1361           parser::ToUpperCaseLetters(getClauseName(clause).str()));
1362     }
1363   }
1364 }
1365 
1366 void OmpStructureChecker::GetSymbolsInObjectList(
1367     const parser::OmpObjectList &objectList, SymbolSourceMap &symbols) {
1368   for (const auto &ompObject : objectList.v) {
1369     if (const auto *name{parser::Unwrap<parser::Name>(ompObject)}) {
1370       if (const auto *symbol{name->symbol}) {
1371         if (const auto *commonBlockDetails{
1372                 symbol->detailsIf<CommonBlockDetails>()}) {
1373           for (const auto &object : commonBlockDetails->objects()) {
1374             symbols.emplace(&object->GetUltimate(), name->source);
1375           }
1376         } else {
1377           symbols.emplace(&symbol->GetUltimate(), name->source);
1378         }
1379       }
1380     }
1381   }
1382 }
1383 
1384 void OmpStructureChecker::CheckDefinableObjects(
1385     SymbolSourceMap &symbols, const llvm::omp::Clause clause) {
1386   for (auto it{symbols.begin()}; it != symbols.end(); ++it) {
1387     const auto *symbol{it->first};
1388     const auto source{it->second};
1389     if (auto msg{WhyNotModifiable(*symbol, context_.FindScope(source))}) {
1390       context_
1391           .Say(source,
1392               "Variable '%s' on the %s clause is not definable"_err_en_US,
1393               symbol->name(),
1394               parser::ToUpperCaseLetters(getClauseName(clause).str()))
1395           .Attach(source, std::move(*msg), symbol->name());
1396     }
1397   }
1398 }
1399 
1400 void OmpStructureChecker::CheckPrivateSymbolsInOuterCxt(
1401     SymbolSourceMap &currSymbols, DirectivesClauseTriple &dirClauseTriple,
1402     const llvm::omp::Clause currClause) {
1403   SymbolSourceMap enclosingSymbols;
1404   auto range{dirClauseTriple.equal_range(GetContext().directive)};
1405   for (auto dirIter{range.first}; dirIter != range.second; ++dirIter) {
1406     auto enclosingDir{dirIter->second.first};
1407     auto enclosingClauseSet{dirIter->second.second};
1408     if (auto *enclosingContext{GetEnclosingContextWithDir(enclosingDir)}) {
1409       for (auto it{enclosingContext->clauseInfo.begin()};
1410            it != enclosingContext->clauseInfo.end(); ++it) {
1411         if (enclosingClauseSet.test(it->first)) {
1412           if (const auto *ompObjectList{GetOmpObjectList(*it->second)}) {
1413             GetSymbolsInObjectList(*ompObjectList, enclosingSymbols);
1414           }
1415         }
1416       }
1417 
1418       // Check if the symbols in current context are private in outer context
1419       for (auto iter{currSymbols.begin()}; iter != currSymbols.end(); ++iter) {
1420         const auto *symbol{iter->first};
1421         const auto source{iter->second};
1422         if (enclosingSymbols.find(symbol) != enclosingSymbols.end()) {
1423           context_.Say(source,
1424               "%s variable '%s' is PRIVATE in outer context"_err_en_US,
1425               parser::ToUpperCaseLetters(getClauseName(currClause).str()),
1426               symbol->name());
1427         }
1428       }
1429     }
1430   }
1431 }
1432 
1433 void OmpStructureChecker::CheckWorkshareBlockStmts(
1434     const parser::Block &block, parser::CharBlock source) {
1435   OmpWorkshareBlockChecker ompWorkshareBlockChecker{context_, source};
1436 
1437   for (auto it{block.begin()}; it != block.end(); ++it) {
1438     if (parser::Unwrap<parser::AssignmentStmt>(*it) ||
1439         parser::Unwrap<parser::ForallStmt>(*it) ||
1440         parser::Unwrap<parser::ForallConstruct>(*it) ||
1441         parser::Unwrap<parser::WhereStmt>(*it) ||
1442         parser::Unwrap<parser::WhereConstruct>(*it)) {
1443       parser::Walk(*it, ompWorkshareBlockChecker);
1444     } else if (const auto *ompConstruct{
1445                    parser::Unwrap<parser::OpenMPConstruct>(*it)}) {
1446       if (const auto *ompAtomicConstruct{
1447               std::get_if<parser::OpenMPAtomicConstruct>(&ompConstruct->u)}) {
1448         // Check if assignment statements in the enclosing OpenMP Atomic
1449         // construct are allowed in the Workshare construct
1450         parser::Walk(*ompAtomicConstruct, ompWorkshareBlockChecker);
1451       } else if (const auto *ompCriticalConstruct{
1452                      std::get_if<parser::OpenMPCriticalConstruct>(
1453                          &ompConstruct->u)}) {
1454         // All the restrictions on the Workshare construct apply to the
1455         // statements in the enclosing critical constructs
1456         const auto &criticalBlock{
1457             std::get<parser::Block>(ompCriticalConstruct->t)};
1458         CheckWorkshareBlockStmts(criticalBlock, source);
1459       } else {
1460         // Check if OpenMP constructs enclosed in the Workshare construct are
1461         // 'Parallel' constructs
1462         auto currentDir{llvm::omp::Directive::OMPD_unknown};
1463         const OmpDirectiveSet parallelDirSet{
1464             llvm::omp::Directive::OMPD_parallel,
1465             llvm::omp::Directive::OMPD_parallel_do,
1466             llvm::omp::Directive::OMPD_parallel_sections,
1467             llvm::omp::Directive::OMPD_parallel_workshare,
1468             llvm::omp::Directive::OMPD_parallel_do_simd};
1469 
1470         if (const auto *ompBlockConstruct{
1471                 std::get_if<parser::OpenMPBlockConstruct>(&ompConstruct->u)}) {
1472           const auto &beginBlockDir{
1473               std::get<parser::OmpBeginBlockDirective>(ompBlockConstruct->t)};
1474           const auto &beginDir{
1475               std::get<parser::OmpBlockDirective>(beginBlockDir.t)};
1476           currentDir = beginDir.v;
1477         } else if (const auto *ompLoopConstruct{
1478                        std::get_if<parser::OpenMPLoopConstruct>(
1479                            &ompConstruct->u)}) {
1480           const auto &beginLoopDir{
1481               std::get<parser::OmpBeginLoopDirective>(ompLoopConstruct->t)};
1482           const auto &beginDir{
1483               std::get<parser::OmpLoopDirective>(beginLoopDir.t)};
1484           currentDir = beginDir.v;
1485         } else if (const auto *ompSectionsConstruct{
1486                        std::get_if<parser::OpenMPSectionsConstruct>(
1487                            &ompConstruct->u)}) {
1488           const auto &beginSectionsDir{
1489               std::get<parser::OmpBeginSectionsDirective>(
1490                   ompSectionsConstruct->t)};
1491           const auto &beginDir{
1492               std::get<parser::OmpSectionsDirective>(beginSectionsDir.t)};
1493           currentDir = beginDir.v;
1494         }
1495 
1496         if (!parallelDirSet.test(currentDir)) {
1497           context_.Say(source,
1498               "OpenMP constructs enclosed in WORKSHARE construct may consist "
1499               "of ATOMIC, CRITICAL or PARALLEL constructs only"_err_en_US);
1500         }
1501       }
1502     } else {
1503       context_.Say(source,
1504           "The structured block in a WORKSHARE construct may consist of only "
1505           "SCALAR or ARRAY assignments, FORALL or WHERE statements, "
1506           "FORALL, WHERE, ATOMIC, CRITICAL or PARALLEL constructs"_err_en_US);
1507     }
1508   }
1509 }
1510 
1511 const parser::OmpObjectList *OmpStructureChecker::GetOmpObjectList(
1512     const parser::OmpClause &clause) {
1513 
1514   // Clauses with OmpObjectList as its data member
1515   using MemberObjectListClauses = std::tuple<parser::OmpClause::Copyprivate,
1516       parser::OmpClause::Copyin, parser::OmpClause::Firstprivate,
1517       parser::OmpClause::From, parser::OmpClause::Lastprivate,
1518       parser::OmpClause::Link, parser::OmpClause::Private,
1519       parser::OmpClause::Shared, parser::OmpClause::To>;
1520 
1521   // Clauses with OmpObjectList in the tuple
1522   using TupleObjectListClauses = std::tuple<parser::OmpClause::Allocate,
1523       parser::OmpClause::Map, parser::OmpClause::Reduction>;
1524 
1525   // TODO:: Generate the tuples using TableGen.
1526   // Handle other constructs with OmpObjectList such as OpenMPThreadprivate.
1527   return std::visit(
1528       common::visitors{
1529           [&](const auto &x) -> const parser::OmpObjectList * {
1530             using Ty = std::decay_t<decltype(x)>;
1531             if constexpr (common::HasMember<Ty, MemberObjectListClauses>) {
1532               return &x.v;
1533             } else if constexpr (common::HasMember<Ty,
1534                                      TupleObjectListClauses>) {
1535               return &(std::get<parser::OmpObjectList>(x.v.t));
1536             } else {
1537               return nullptr;
1538             }
1539           },
1540       },
1541       clause.u);
1542 }
1543 
1544 } // namespace Fortran::semantics
1545