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(context_, var)};
54     const auto *rhs{GetExpr(context_, expr)};
55     if (lhs && rhs) {
56       Tristate isDefined{semantics::IsDefinedAssignment(
57           lhs->GetType(), lhs->Rank(), rhs->GetType(), rhs->Rank())};
58       if (isDefined == Tristate::Yes) {
59         context_.Say(expr.source,
60             "Defined assignment statement is not "
61             "allowed in a WORKSHARE construct"_err_en_US);
62       }
63     }
64     return true;
65   }
66 
67   bool Pre(const parser::Expr &expr) {
68     if (const auto *e{GetExpr(context_, expr)}) {
69       for (const Symbol &symbol : evaluate::CollectSymbols(*e)) {
70         const Symbol &root{GetAssociationRoot(symbol)};
71         if (IsFunction(root) &&
72             !(root.attrs().test(Attr::ELEMENTAL) ||
73                 root.attrs().test(Attr::INTRINSIC))) {
74           context_.Say(expr.source,
75               "User defined non-ELEMENTAL function "
76               "'%s' is not allowed in a WORKSHARE construct"_err_en_US,
77               root.name());
78         }
79       }
80     }
81     return false;
82   }
83 
84 private:
85   SemanticsContext &context_;
86   parser::CharBlock source_;
87 };
88 
89 class OmpCycleChecker {
90 public:
91   OmpCycleChecker(SemanticsContext &context, std::int64_t cycleLevel)
92       : context_{context}, cycleLevel_{cycleLevel} {}
93 
94   template <typename T> bool Pre(const T &) { return true; }
95   template <typename T> void Post(const T &) {}
96 
97   bool Pre(const parser::DoConstruct &dc) {
98     cycleLevel_--;
99     const auto &labelName{std::get<0>(std::get<0>(dc.t).statement.t)};
100     if (labelName) {
101       labelNamesandLevels_.emplace(labelName.value().ToString(), cycleLevel_);
102     }
103     return true;
104   }
105 
106   bool Pre(const parser::CycleStmt &cyclestmt) {
107     std::map<std::string, std::int64_t>::iterator it;
108     bool err{false};
109     if (cyclestmt.v) {
110       it = labelNamesandLevels_.find(cyclestmt.v->source.ToString());
111       err = (it != labelNamesandLevels_.end() && it->second > 0);
112     }
113     if (cycleLevel_ > 0 || err) {
114       context_.Say(*cycleSource_,
115           "CYCLE statement to non-innermost associated loop of an OpenMP DO construct"_err_en_US);
116     }
117     return true;
118   }
119 
120   bool Pre(const parser::Statement<parser::ActionStmt> &actionstmt) {
121     cycleSource_ = &actionstmt.source;
122     return true;
123   }
124 
125 private:
126   SemanticsContext &context_;
127   const parser::CharBlock *cycleSource_;
128   std::int64_t cycleLevel_;
129   std::map<std::string, std::int64_t> labelNamesandLevels_;
130 };
131 
132 bool OmpStructureChecker::IsCloselyNestedRegion(const OmpDirectiveSet &set) {
133   // Definition of close nesting:
134   //
135   // `A region nested inside another region with no parallel region nested
136   // between them`
137   //
138   // Examples:
139   //   non-parallel construct 1
140   //    non-parallel construct 2
141   //      parallel construct
142   //        construct 3
143   // In the above example, construct 3 is NOT closely nested inside construct 1
144   // or 2
145   //
146   //   non-parallel construct 1
147   //    non-parallel construct 2
148   //        construct 3
149   // In the above example, construct 3 is closely nested inside BOTH construct 1
150   // and 2
151   //
152   // Algorithm:
153   // Starting from the parent context, Check in a bottom-up fashion, each level
154   // of the context stack. If we have a match for one of the (supplied)
155   // violating directives, `close nesting` is satisfied. If no match is there in
156   // the entire stack, `close nesting` is not satisfied. If at any level, a
157   // `parallel` region is found, `close nesting` is not satisfied.
158 
159   if (CurrentDirectiveIsNested()) {
160     int index = dirContext_.size() - 2;
161     while (index != -1) {
162       if (set.test(dirContext_[index].directive)) {
163         return true;
164       } else if (llvm::omp::parallelSet.test(dirContext_[index].directive)) {
165         return false;
166       }
167       index--;
168     }
169   }
170   return false;
171 }
172 
173 void OmpStructureChecker::CheckMultListItems() {
174   semantics::UnorderedSymbolSet listVars;
175   auto checkMultipleOcurrence = [&](const std::list<parser::Name> &nameList,
176                                     const parser::CharBlock &item,
177                                     const std::string &clauseName) {
178     for (auto const &var : nameList) {
179       if (llvm::is_contained(listVars, *(var.symbol))) {
180         context_.Say(item,
181             "List item '%s' present at multiple %s clauses"_err_en_US,
182             var.ToString(), clauseName);
183       }
184       listVars.insert(*(var.symbol));
185     }
186   };
187 
188   // Aligned clause
189   auto alignedClauses{FindClauses(llvm::omp::Clause::OMPC_aligned)};
190   for (auto itr = alignedClauses.first; itr != alignedClauses.second; ++itr) {
191     const auto &alignedClause{
192         std::get<parser::OmpClause::Aligned>(itr->second->u)};
193     const auto &alignedNameList{
194         std::get<std::list<parser::Name>>(alignedClause.v.t)};
195     checkMultipleOcurrence(alignedNameList, itr->second->source, "ALIGNED");
196   }
197 
198   // Nontemporal clause
199   auto nonTemporalClauses{FindClauses(llvm::omp::Clause::OMPC_nontemporal)};
200   for (auto itr = nonTemporalClauses.first; itr != nonTemporalClauses.second;
201        ++itr) {
202     const auto &nontempClause{
203         std::get<parser::OmpClause::Nontemporal>(itr->second->u)};
204     const auto &nontempNameList{nontempClause.v};
205     checkMultipleOcurrence(nontempNameList, itr->second->source, "NONTEMPORAL");
206   }
207 }
208 
209 bool OmpStructureChecker::HasInvalidWorksharingNesting(
210     const parser::CharBlock &source, const OmpDirectiveSet &set) {
211   // set contains all the invalid closely nested directives
212   // for the given directive (`source` here)
213   if (IsCloselyNestedRegion(set)) {
214     context_.Say(source,
215         "A worksharing region may not be closely nested inside a "
216         "worksharing, explicit task, taskloop, critical, ordered, atomic, or "
217         "master region"_err_en_US);
218     return true;
219   }
220   return false;
221 }
222 
223 void OmpStructureChecker::HasInvalidDistributeNesting(
224     const parser::OpenMPLoopConstruct &x) {
225   bool violation{false};
226 
227   OmpDirectiveSet distributeSet{llvm::omp::Directive::OMPD_distribute,
228       llvm::omp::Directive::OMPD_distribute_parallel_do,
229       llvm::omp::Directive::OMPD_distribute_parallel_do_simd,
230       llvm::omp::Directive::OMPD_distribute_parallel_for,
231       llvm::omp::Directive::OMPD_distribute_parallel_for_simd,
232       llvm::omp::Directive::OMPD_distribute_simd};
233 
234   const auto &beginLoopDir{std::get<parser::OmpBeginLoopDirective>(x.t)};
235   const auto &beginDir{std::get<parser::OmpLoopDirective>(beginLoopDir.t)};
236   if (distributeSet.test(beginDir.v)) {
237     // `distribute` region has to be nested
238     if (!CurrentDirectiveIsNested()) {
239       violation = true;
240     } else {
241       // `distribute` region has to be strictly nested inside `teams`
242       if (!llvm::omp::teamSet.test(GetContextParent().directive)) {
243         violation = true;
244       }
245     }
246   }
247   if (violation) {
248     context_.Say(beginDir.source,
249         "`DISTRIBUTE` region has to be strictly nested inside `TEAMS` region."_err_en_US);
250   }
251 }
252 
253 void OmpStructureChecker::HasInvalidTeamsNesting(
254     const llvm::omp::Directive &dir, const parser::CharBlock &source) {
255   OmpDirectiveSet allowedSet{llvm::omp::Directive::OMPD_parallel,
256       llvm::omp::Directive::OMPD_parallel_do,
257       llvm::omp::Directive::OMPD_parallel_do_simd,
258       llvm::omp::Directive::OMPD_parallel_for,
259       llvm::omp::Directive::OMPD_parallel_for_simd,
260       llvm::omp::Directive::OMPD_parallel_master,
261       llvm::omp::Directive::OMPD_parallel_master_taskloop,
262       llvm::omp::Directive::OMPD_parallel_master_taskloop_simd,
263       llvm::omp::Directive::OMPD_parallel_sections,
264       llvm::omp::Directive::OMPD_parallel_workshare,
265       llvm::omp::Directive::OMPD_distribute,
266       llvm::omp::Directive::OMPD_distribute_parallel_do,
267       llvm::omp::Directive::OMPD_distribute_parallel_do_simd,
268       llvm::omp::Directive::OMPD_distribute_parallel_for,
269       llvm::omp::Directive::OMPD_distribute_parallel_for_simd,
270       llvm::omp::Directive::OMPD_distribute_simd};
271 
272   if (!allowedSet.test(dir)) {
273     context_.Say(source,
274         "Only `DISTRIBUTE` or `PARALLEL` regions are allowed to be strictly nested inside `TEAMS` region."_err_en_US);
275   }
276 }
277 
278 void OmpStructureChecker::CheckPredefinedAllocatorRestriction(
279     const parser::CharBlock &source, const parser::Name &name) {
280   if (const auto *symbol{name.symbol}) {
281     const auto *commonBlock{FindCommonBlockContaining(*symbol)};
282     const auto &scope{context_.FindScope(symbol->name())};
283     const Scope &containingScope{GetProgramUnitContaining(scope)};
284     if (!isPredefinedAllocator &&
285         (IsSave(*symbol) || commonBlock ||
286             containingScope.kind() == Scope::Kind::Module)) {
287       context_.Say(source,
288           "If list items within the ALLOCATE directive have the "
289           "SAVE attribute, are a common block name, or are "
290           "declared in the scope of a module, then only "
291           "predefined memory allocator parameters can be used "
292           "in the allocator clause"_err_en_US);
293     }
294   }
295 }
296 
297 void OmpStructureChecker::CheckPredefinedAllocatorRestriction(
298     const parser::CharBlock &source,
299     const parser::OmpObjectList &ompObjectList) {
300   for (const auto &ompObject : ompObjectList.v) {
301     common::visit(
302         common::visitors{
303             [&](const parser::Designator &designator) {
304               if (const auto *dataRef{
305                       std::get_if<parser::DataRef>(&designator.u)}) {
306                 if (const auto *name{std::get_if<parser::Name>(&dataRef->u)}) {
307                   CheckPredefinedAllocatorRestriction(source, *name);
308                 }
309               }
310             },
311             [&](const parser::Name &name) {
312               CheckPredefinedAllocatorRestriction(source, name);
313             },
314         },
315         ompObject.u);
316   }
317 }
318 
319 void OmpStructureChecker::Enter(const parser::OpenMPConstruct &x) {
320   // Simd Construct with Ordered Construct Nesting check
321   // We cannot use CurrentDirectiveIsNested() here because
322   // PushContextAndClauseSets() has not been called yet, it is
323   // called individually for each construct.  Therefore a
324   // dirContext_ size `1` means the current construct is nested
325   if (dirContext_.size() >= 1) {
326     if (GetDirectiveNest(SIMDNest) > 0) {
327       CheckSIMDNest(x);
328     }
329     if (GetDirectiveNest(TargetNest) > 0) {
330       CheckTargetNest(x);
331     }
332   }
333 }
334 
335 void OmpStructureChecker::Enter(const parser::OpenMPLoopConstruct &x) {
336   const auto &beginLoopDir{std::get<parser::OmpBeginLoopDirective>(x.t)};
337   const auto &beginDir{std::get<parser::OmpLoopDirective>(beginLoopDir.t)};
338 
339   // check matching, End directive is optional
340   if (const auto &endLoopDir{
341           std::get<std::optional<parser::OmpEndLoopDirective>>(x.t)}) {
342     const auto &endDir{
343         std::get<parser::OmpLoopDirective>(endLoopDir.value().t)};
344 
345     CheckMatching<parser::OmpLoopDirective>(beginDir, endDir);
346   }
347 
348   PushContextAndClauseSets(beginDir.source, beginDir.v);
349   if (llvm::omp::simdSet.test(GetContext().directive)) {
350     EnterDirectiveNest(SIMDNest);
351   }
352 
353   if (beginDir.v == llvm::omp::Directive::OMPD_do) {
354     // 2.7.1 do-clause -> private-clause |
355     //                    firstprivate-clause |
356     //                    lastprivate-clause |
357     //                    linear-clause |
358     //                    reduction-clause |
359     //                    schedule-clause |
360     //                    collapse-clause |
361     //                    ordered-clause
362 
363     // nesting check
364     HasInvalidWorksharingNesting(
365         beginDir.source, llvm::omp::nestedWorkshareErrSet);
366   }
367   SetLoopInfo(x);
368 
369   if (const auto &doConstruct{
370           std::get<std::optional<parser::DoConstruct>>(x.t)}) {
371     const auto &doBlock{std::get<parser::Block>(doConstruct->t)};
372     CheckNoBranching(doBlock, beginDir.v, beginDir.source);
373   }
374   CheckDoWhile(x);
375   CheckLoopItrVariableIsInt(x);
376   CheckCycleConstraints(x);
377   HasInvalidDistributeNesting(x);
378   if (CurrentDirectiveIsNested() &&
379       llvm::omp::teamSet.test(GetContextParent().directive)) {
380     HasInvalidTeamsNesting(beginDir.v, beginDir.source);
381   }
382   if ((beginDir.v == llvm::omp::Directive::OMPD_distribute_parallel_do_simd) ||
383       (beginDir.v == llvm::omp::Directive::OMPD_distribute_simd)) {
384     CheckDistLinear(x);
385   }
386 }
387 const parser::Name OmpStructureChecker::GetLoopIndex(
388     const parser::DoConstruct *x) {
389   using Bounds = parser::LoopControl::Bounds;
390   return std::get<Bounds>(x->GetLoopControl()->u).name.thing;
391 }
392 void OmpStructureChecker::SetLoopInfo(const parser::OpenMPLoopConstruct &x) {
393   if (const auto &loopConstruct{
394           std::get<std::optional<parser::DoConstruct>>(x.t)}) {
395     const parser::DoConstruct *loop{&*loopConstruct};
396     if (loop && loop->IsDoNormal()) {
397       const parser::Name &itrVal{GetLoopIndex(loop)};
398       SetLoopIv(itrVal.symbol);
399     }
400   }
401 }
402 void OmpStructureChecker::CheckDoWhile(const parser::OpenMPLoopConstruct &x) {
403   const auto &beginLoopDir{std::get<parser::OmpBeginLoopDirective>(x.t)};
404   const auto &beginDir{std::get<parser::OmpLoopDirective>(beginLoopDir.t)};
405   if (beginDir.v == llvm::omp::Directive::OMPD_do) {
406     if (const auto &doConstruct{
407             std::get<std::optional<parser::DoConstruct>>(x.t)}) {
408       if (doConstruct.value().IsDoWhile()) {
409         const auto &doStmt{std::get<parser::Statement<parser::NonLabelDoStmt>>(
410             doConstruct.value().t)};
411         context_.Say(doStmt.source,
412             "The DO loop cannot be a DO WHILE with DO directive."_err_en_US);
413       }
414     }
415   }
416 }
417 
418 void OmpStructureChecker::CheckLoopItrVariableIsInt(
419     const parser::OpenMPLoopConstruct &x) {
420   if (const auto &loopConstruct{
421           std::get<std::optional<parser::DoConstruct>>(x.t)}) {
422 
423     for (const parser::DoConstruct *loop{&*loopConstruct}; loop;) {
424       if (loop->IsDoNormal()) {
425         const parser::Name &itrVal{GetLoopIndex(loop)};
426         if (itrVal.symbol) {
427           const auto *type{itrVal.symbol->GetType()};
428           if (!type->IsNumeric(TypeCategory::Integer)) {
429             context_.Say(itrVal.source,
430                 "The DO loop iteration"
431                 " variable must be of the type integer."_err_en_US,
432                 itrVal.ToString());
433           }
434         }
435       }
436       // Get the next DoConstruct if block is not empty.
437       const auto &block{std::get<parser::Block>(loop->t)};
438       const auto it{block.begin()};
439       loop = it != block.end() ? parser::Unwrap<parser::DoConstruct>(*it)
440                                : nullptr;
441     }
442   }
443 }
444 
445 void OmpStructureChecker::CheckSIMDNest(const parser::OpenMPConstruct &c) {
446   // Check the following:
447   //  The only OpenMP constructs that can be encountered during execution of
448   // a simd region are the `atomic` construct, the `loop` construct, the `simd`
449   // construct and the `ordered` construct with the `simd` clause.
450   // TODO:  Expand the check to include `LOOP` construct as well when it is
451   // supported.
452 
453   // Check if the parent context has the SIMD clause
454   // Please note that we use GetContext() instead of GetContextParent()
455   // because PushContextAndClauseSets() has not been called on the
456   // current context yet.
457   // TODO: Check for declare simd regions.
458   bool eligibleSIMD{false};
459   common::visit(Fortran::common::visitors{
460                     // Allow `!$OMP ORDERED SIMD`
461                     [&](const parser::OpenMPBlockConstruct &c) {
462                       const auto &beginBlockDir{
463                           std::get<parser::OmpBeginBlockDirective>(c.t)};
464                       const auto &beginDir{
465                           std::get<parser::OmpBlockDirective>(beginBlockDir.t)};
466                       if (beginDir.v == llvm::omp::Directive::OMPD_ordered) {
467                         const auto &clauses{
468                             std::get<parser::OmpClauseList>(beginBlockDir.t)};
469                         for (const auto &clause : clauses.v) {
470                           if (std::get_if<parser::OmpClause::Simd>(&clause.u)) {
471                             eligibleSIMD = true;
472                             break;
473                           }
474                         }
475                       }
476                     },
477                     [&](const parser::OpenMPSimpleStandaloneConstruct &c) {
478                       const auto &dir{
479                           std::get<parser::OmpSimpleStandaloneDirective>(c.t)};
480                       if (dir.v == llvm::omp::Directive::OMPD_ordered) {
481                         const auto &clauses{
482                             std::get<parser::OmpClauseList>(c.t)};
483                         for (const auto &clause : clauses.v) {
484                           if (std::get_if<parser::OmpClause::Simd>(&clause.u)) {
485                             eligibleSIMD = true;
486                             break;
487                           }
488                         }
489                       }
490                     },
491                     // Allowing SIMD construct
492                     [&](const parser::OpenMPLoopConstruct &c) {
493                       const auto &beginLoopDir{
494                           std::get<parser::OmpBeginLoopDirective>(c.t)};
495                       const auto &beginDir{
496                           std::get<parser::OmpLoopDirective>(beginLoopDir.t)};
497                       if ((beginDir.v == llvm::omp::Directive::OMPD_simd) ||
498                           (beginDir.v == llvm::omp::Directive::OMPD_do_simd)) {
499                         eligibleSIMD = true;
500                       }
501                     },
502                     [&](const parser::OpenMPAtomicConstruct &c) {
503                       // Allow `!$OMP ATOMIC`
504                       eligibleSIMD = true;
505                     },
506                     [&](const auto &c) {},
507                 },
508       c.u);
509   if (!eligibleSIMD) {
510     context_.Say(parser::FindSourceLocation(c),
511         "The only OpenMP constructs that can be encountered during execution "
512         "of a 'SIMD'"
513         " region are the `ATOMIC` construct, the `LOOP` construct, the `SIMD`"
514         " construct and the `ORDERED` construct with the `SIMD` clause."_err_en_US);
515   }
516 }
517 
518 void OmpStructureChecker::CheckTargetNest(const parser::OpenMPConstruct &c) {
519   // 2.12.5 Target Construct Restriction
520   bool eligibleTarget{true};
521   llvm::omp::Directive ineligibleTargetDir;
522   common::visit(
523       common::visitors{
524           [&](const parser::OpenMPBlockConstruct &c) {
525             const auto &beginBlockDir{
526                 std::get<parser::OmpBeginBlockDirective>(c.t)};
527             const auto &beginDir{
528                 std::get<parser::OmpBlockDirective>(beginBlockDir.t)};
529             if (beginDir.v == llvm::omp::Directive::OMPD_target_data) {
530               eligibleTarget = false;
531               ineligibleTargetDir = beginDir.v;
532             }
533           },
534           [&](const parser::OpenMPStandaloneConstruct &c) {
535             common::visit(
536                 common::visitors{
537                     [&](const parser::OpenMPSimpleStandaloneConstruct &c) {
538                       const auto &dir{
539                           std::get<parser::OmpSimpleStandaloneDirective>(c.t)};
540                       if (dir.v == llvm::omp::Directive::OMPD_target_update ||
541                           dir.v ==
542                               llvm::omp::Directive::OMPD_target_enter_data ||
543                           dir.v ==
544                               llvm::omp::Directive::OMPD_target_exit_data) {
545                         eligibleTarget = false;
546                         ineligibleTargetDir = dir.v;
547                       }
548                     },
549                     [&](const auto &c) {},
550                 },
551                 c.u);
552           },
553           [&](const auto &c) {},
554       },
555       c.u);
556   if (!eligibleTarget) {
557     context_.Say(parser::FindSourceLocation(c),
558         "If %s directive is nested inside TARGET region, the behaviour "
559         "is unspecified"_port_en_US,
560         parser::ToUpperCaseLetters(
561             getDirectiveName(ineligibleTargetDir).str()));
562   }
563 }
564 
565 std::int64_t OmpStructureChecker::GetOrdCollapseLevel(
566     const parser::OpenMPLoopConstruct &x) {
567   const auto &beginLoopDir{std::get<parser::OmpBeginLoopDirective>(x.t)};
568   const auto &clauseList{std::get<parser::OmpClauseList>(beginLoopDir.t)};
569   std::int64_t orderedCollapseLevel{1};
570   std::int64_t orderedLevel{0};
571   std::int64_t collapseLevel{0};
572 
573   for (const auto &clause : clauseList.v) {
574     if (const auto *collapseClause{
575             std::get_if<parser::OmpClause::Collapse>(&clause.u)}) {
576       if (const auto v{GetIntValue(collapseClause->v)}) {
577         collapseLevel = *v;
578       }
579     }
580     if (const auto *orderedClause{
581             std::get_if<parser::OmpClause::Ordered>(&clause.u)}) {
582       if (const auto v{GetIntValue(orderedClause->v)}) {
583         orderedLevel = *v;
584       }
585     }
586   }
587   if (orderedLevel >= collapseLevel) {
588     orderedCollapseLevel = orderedLevel;
589   } else {
590     orderedCollapseLevel = collapseLevel;
591   }
592   return orderedCollapseLevel;
593 }
594 
595 void OmpStructureChecker::CheckCycleConstraints(
596     const parser::OpenMPLoopConstruct &x) {
597   std::int64_t ordCollapseLevel{GetOrdCollapseLevel(x)};
598   OmpCycleChecker ompCycleChecker{context_, ordCollapseLevel};
599   parser::Walk(x, ompCycleChecker);
600 }
601 
602 void OmpStructureChecker::CheckDistLinear(
603     const parser::OpenMPLoopConstruct &x) {
604 
605   const auto &beginLoopDir{std::get<parser::OmpBeginLoopDirective>(x.t)};
606   const auto &clauses{std::get<parser::OmpClauseList>(beginLoopDir.t)};
607 
608   semantics::UnorderedSymbolSet indexVars;
609 
610   // Collect symbols of all the variables from linear clauses
611   for (const auto &clause : clauses.v) {
612     if (const auto *linearClause{
613             std::get_if<parser::OmpClause::Linear>(&clause.u)}) {
614 
615       std::list<parser::Name> values;
616       // Get the variant type
617       if (std::holds_alternative<parser::OmpLinearClause::WithModifier>(
618               linearClause->v.u)) {
619         const auto &withM{
620             std::get<parser::OmpLinearClause::WithModifier>(linearClause->v.u)};
621         values = withM.names;
622       } else {
623         const auto &withOutM{std::get<parser::OmpLinearClause::WithoutModifier>(
624             linearClause->v.u)};
625         values = withOutM.names;
626       }
627       for (auto const &v : values) {
628         indexVars.insert(*(v.symbol));
629       }
630     }
631   }
632 
633   if (!indexVars.empty()) {
634     // Get collapse level, if given, to find which loops are "associated."
635     std::int64_t collapseVal{GetOrdCollapseLevel(x)};
636     // Include the top loop if no collapse is specified
637     if (collapseVal == 0) {
638       collapseVal = 1;
639     }
640 
641     // Match the loop index variables with the collected symbols from linear
642     // clauses.
643     if (const auto &loopConstruct{
644             std::get<std::optional<parser::DoConstruct>>(x.t)}) {
645       for (const parser::DoConstruct *loop{&*loopConstruct}; loop;) {
646         if (loop->IsDoNormal()) {
647           const parser::Name &itrVal{GetLoopIndex(loop)};
648           if (itrVal.symbol) {
649             // Remove the symbol from the collcted set
650             indexVars.erase(*(itrVal.symbol));
651           }
652           collapseVal--;
653           if (collapseVal == 0) {
654             break;
655           }
656         }
657         // Get the next DoConstruct if block is not empty.
658         const auto &block{std::get<parser::Block>(loop->t)};
659         const auto it{block.begin()};
660         loop = it != block.end() ? parser::Unwrap<parser::DoConstruct>(*it)
661                                  : nullptr;
662       }
663     }
664 
665     // Show error for the remaining variables
666     for (auto var : indexVars) {
667       const Symbol &root{GetAssociationRoot(var)};
668       context_.Say(parser::FindSourceLocation(x),
669           "Variable '%s' not allowed in `LINEAR` clause, only loop iterator can be specified in `LINEAR` clause of a construct combined with `DISTRIBUTE`"_err_en_US,
670           root.name());
671     }
672   }
673 }
674 
675 void OmpStructureChecker::Leave(const parser::OpenMPLoopConstruct &) {
676   if (llvm::omp::simdSet.test(GetContext().directive)) {
677     ExitDirectiveNest(SIMDNest);
678   }
679   dirContext_.pop_back();
680 }
681 
682 void OmpStructureChecker::Enter(const parser::OmpEndLoopDirective &x) {
683   const auto &dir{std::get<parser::OmpLoopDirective>(x.t)};
684   ResetPartialContext(dir.source);
685   switch (dir.v) {
686   // 2.7.1 end-do -> END DO [nowait-clause]
687   // 2.8.3 end-do-simd -> END DO SIMD [nowait-clause]
688   case llvm::omp::Directive::OMPD_do:
689   case llvm::omp::Directive::OMPD_do_simd:
690     SetClauseSets(dir.v);
691     break;
692   default:
693     // no clauses are allowed
694     break;
695   }
696 }
697 
698 void OmpStructureChecker::Enter(const parser::OpenMPBlockConstruct &x) {
699   const auto &beginBlockDir{std::get<parser::OmpBeginBlockDirective>(x.t)};
700   const auto &endBlockDir{std::get<parser::OmpEndBlockDirective>(x.t)};
701   const auto &beginDir{std::get<parser::OmpBlockDirective>(beginBlockDir.t)};
702   const auto &endDir{std::get<parser::OmpBlockDirective>(endBlockDir.t)};
703   const parser::Block &block{std::get<parser::Block>(x.t)};
704 
705   CheckMatching<parser::OmpBlockDirective>(beginDir, endDir);
706 
707   PushContextAndClauseSets(beginDir.source, beginDir.v);
708   if (GetContext().directive == llvm::omp::Directive::OMPD_target) {
709     EnterDirectiveNest(TargetNest);
710   }
711 
712   if (CurrentDirectiveIsNested()) {
713     if (llvm::omp::teamSet.test(GetContextParent().directive)) {
714       HasInvalidTeamsNesting(beginDir.v, beginDir.source);
715     }
716     if (GetContext().directive == llvm::omp::Directive::OMPD_master) {
717       CheckMasterNesting(x);
718     }
719     // A teams region can only be strictly nested within the implicit parallel
720     // region or a target region.
721     if (GetContext().directive == llvm::omp::Directive::OMPD_teams &&
722         GetContextParent().directive != llvm::omp::Directive::OMPD_target) {
723       context_.Say(parser::FindSourceLocation(x),
724           "%s region can only be strictly nested within the implicit parallel "
725           "region or TARGET region"_err_en_US,
726           ContextDirectiveAsFortran());
727     }
728     // If a teams construct is nested within a target construct, that target
729     // construct must contain no statements, declarations or directives outside
730     // of the teams construct.
731     if (GetContext().directive == llvm::omp::Directive::OMPD_teams &&
732         GetContextParent().directive == llvm::omp::Directive::OMPD_target &&
733         !GetDirectiveNest(TargetBlockOnlyTeams)) {
734       context_.Say(GetContextParent().directiveSource,
735           "TARGET construct with nested TEAMS region contains statements or "
736           "directives outside of the TEAMS construct"_err_en_US);
737     }
738   }
739 
740   CheckNoBranching(block, beginDir.v, beginDir.source);
741 
742   switch (beginDir.v) {
743   case llvm::omp::Directive::OMPD_target:
744     if (CheckTargetBlockOnlyTeams(block)) {
745       EnterDirectiveNest(TargetBlockOnlyTeams);
746     }
747     break;
748   case llvm::omp::OMPD_workshare:
749   case llvm::omp::OMPD_parallel_workshare:
750     CheckWorkshareBlockStmts(block, beginDir.source);
751     HasInvalidWorksharingNesting(
752         beginDir.source, llvm::omp::nestedWorkshareErrSet);
753     break;
754   case llvm::omp::Directive::OMPD_single:
755     // TODO: This check needs to be extended while implementing nesting of
756     // regions checks.
757     HasInvalidWorksharingNesting(
758         beginDir.source, llvm::omp::nestedWorkshareErrSet);
759     break;
760   default:
761     break;
762   }
763 }
764 
765 void OmpStructureChecker::CheckMasterNesting(
766     const parser::OpenMPBlockConstruct &x) {
767   // A MASTER region may not be `closely nested` inside a worksharing, loop,
768   // task, taskloop, or atomic region.
769   // TODO:  Expand the check to include `LOOP` construct as well when it is
770   // supported.
771   if (IsCloselyNestedRegion(llvm::omp::nestedMasterErrSet)) {
772     context_.Say(parser::FindSourceLocation(x),
773         "`MASTER` region may not be closely nested inside of `WORKSHARING`, "
774         "`LOOP`, `TASK`, `TASKLOOP`,"
775         " or `ATOMIC` region."_err_en_US);
776   }
777 }
778 
779 void OmpStructureChecker::Leave(const parser::OpenMPBlockConstruct &) {
780   if (GetDirectiveNest(TargetBlockOnlyTeams)) {
781     ExitDirectiveNest(TargetBlockOnlyTeams);
782   }
783   if (GetContext().directive == llvm::omp::Directive::OMPD_target) {
784     ExitDirectiveNest(TargetNest);
785   }
786   dirContext_.pop_back();
787 }
788 
789 void OmpStructureChecker::ChecksOnOrderedAsBlock() {
790   if (FindClause(llvm::omp::Clause::OMPC_depend)) {
791     context_.Say(GetContext().clauseSource,
792         "DEPEND(*) clauses are not allowed when ORDERED construct is a block"
793         " construct with an ORDERED region"_err_en_US);
794     return;
795   }
796 
797   OmpDirectiveSet notAllowedParallelSet{llvm::omp::Directive::OMPD_parallel,
798       llvm::omp::Directive::OMPD_target_parallel,
799       llvm::omp::Directive::OMPD_parallel_sections,
800       llvm::omp::Directive::OMPD_parallel_workshare};
801   bool isNestedInDo{false};
802   bool isNestedInDoSIMD{false};
803   bool isNestedInSIMD{false};
804   bool noOrderedClause{false};
805   bool isOrderedClauseWithPara{false};
806   bool isCloselyNestedRegion{true};
807   if (CurrentDirectiveIsNested()) {
808     for (int i = (int)dirContext_.size() - 2; i >= 0; i--) {
809       if (llvm::omp::nestedOrderedErrSet.test(dirContext_[i].directive)) {
810         context_.Say(GetContext().directiveSource,
811             "`ORDERED` region may not be closely nested inside of `CRITICAL`, "
812             "`ORDERED`, explicit `TASK` or `TASKLOOP` region."_err_en_US);
813         break;
814       } else if (llvm::omp::doSet.test(dirContext_[i].directive)) {
815         isNestedInDo = true;
816         isNestedInDoSIMD = llvm::omp::doSimdSet.test(dirContext_[i].directive);
817         if (const auto *clause{
818                 FindClause(dirContext_[i], llvm::omp::Clause::OMPC_ordered)}) {
819           const auto &orderedClause{
820               std::get<parser::OmpClause::Ordered>(clause->u)};
821           const auto orderedValue{GetIntValue(orderedClause.v)};
822           isOrderedClauseWithPara = orderedValue > 0;
823         } else {
824           noOrderedClause = true;
825         }
826         break;
827       } else if (llvm::omp::simdSet.test(dirContext_[i].directive)) {
828         isNestedInSIMD = true;
829         break;
830       } else if (notAllowedParallelSet.test(dirContext_[i].directive)) {
831         isCloselyNestedRegion = false;
832         break;
833       }
834     }
835   }
836 
837   if (!isCloselyNestedRegion) {
838     context_.Say(GetContext().directiveSource,
839         "An ORDERED directive without the DEPEND clause must be closely nested "
840         "in a SIMD, worksharing-loop, or worksharing-loop SIMD "
841         "region"_err_en_US);
842   } else {
843     if (CurrentDirectiveIsNested() &&
844         FindClause(llvm::omp::Clause::OMPC_simd) &&
845         (!isNestedInDoSIMD && !isNestedInSIMD)) {
846       context_.Say(GetContext().directiveSource,
847           "An ORDERED directive with SIMD clause must be closely nested in a "
848           "SIMD or worksharing-loop SIMD region"_err_en_US);
849     }
850     if (isNestedInDo && (noOrderedClause || isOrderedClauseWithPara)) {
851       context_.Say(GetContext().directiveSource,
852           "An ORDERED directive without the DEPEND clause must be closely "
853           "nested in a worksharing-loop (or worksharing-loop SIMD) region with "
854           "ORDERED clause without the parameter"_err_en_US);
855     }
856   }
857 }
858 
859 void OmpStructureChecker::Leave(const parser::OmpBeginBlockDirective &) {
860   switch (GetContext().directive) {
861   case llvm::omp::Directive::OMPD_ordered:
862     // [5.1] 2.19.9 Ordered Construct Restriction
863     ChecksOnOrderedAsBlock();
864     break;
865   default:
866     break;
867   }
868 }
869 
870 void OmpStructureChecker::Enter(const parser::OpenMPSectionsConstruct &x) {
871   const auto &beginSectionsDir{
872       std::get<parser::OmpBeginSectionsDirective>(x.t)};
873   const auto &endSectionsDir{std::get<parser::OmpEndSectionsDirective>(x.t)};
874   const auto &beginDir{
875       std::get<parser::OmpSectionsDirective>(beginSectionsDir.t)};
876   const auto &endDir{std::get<parser::OmpSectionsDirective>(endSectionsDir.t)};
877   CheckMatching<parser::OmpSectionsDirective>(beginDir, endDir);
878 
879   PushContextAndClauseSets(beginDir.source, beginDir.v);
880   const auto &sectionBlocks{std::get<parser::OmpSectionBlocks>(x.t)};
881   for (const parser::OpenMPConstruct &block : sectionBlocks.v) {
882     CheckNoBranching(std::get<parser::OpenMPSectionConstruct>(block.u).v,
883         beginDir.v, beginDir.source);
884   }
885   HasInvalidWorksharingNesting(
886       beginDir.source, llvm::omp::nestedWorkshareErrSet);
887 }
888 
889 void OmpStructureChecker::Leave(const parser::OpenMPSectionsConstruct &) {
890   dirContext_.pop_back();
891 }
892 
893 void OmpStructureChecker::Enter(const parser::OmpEndSectionsDirective &x) {
894   const auto &dir{std::get<parser::OmpSectionsDirective>(x.t)};
895   ResetPartialContext(dir.source);
896   switch (dir.v) {
897     // 2.7.2 end-sections -> END SECTIONS [nowait-clause]
898   case llvm::omp::Directive::OMPD_sections:
899     PushContextAndClauseSets(
900         dir.source, llvm::omp::Directive::OMPD_end_sections);
901     break;
902   default:
903     // no clauses are allowed
904     break;
905   }
906 }
907 
908 // TODO: Verify the popping of dirContext requirement after nowait
909 // implementation, as there is an implicit barrier at the end of the worksharing
910 // constructs unless a nowait clause is specified. Only OMPD_end_sections is
911 // popped becuase it is pushed while entering the EndSectionsDirective.
912 void OmpStructureChecker::Leave(const parser::OmpEndSectionsDirective &x) {
913   if (GetContext().directive == llvm::omp::Directive::OMPD_end_sections) {
914     dirContext_.pop_back();
915   }
916 }
917 
918 void OmpStructureChecker::CheckThreadprivateOrDeclareTargetVar(
919     const parser::OmpObjectList &objList) {
920   for (const auto &ompObject : objList.v) {
921     common::visit(
922         common::visitors{
923             [&](const parser::Designator &) {
924               if (const auto *name{parser::Unwrap<parser::Name>(ompObject)}) {
925                 const auto &useScope{
926                     context_.FindScope(GetContext().directiveSource)};
927                 const auto &declScope{
928                     GetProgramUnitContaining(name->symbol->GetUltimate())};
929                 const auto *sym =
930                     declScope.parent().FindSymbol(name->symbol->name());
931                 if (sym &&
932                     (sym->has<MainProgramDetails>() ||
933                         sym->has<ModuleDetails>())) {
934                   context_.Say(name->source,
935                       "The module name or main program name cannot be in a %s "
936                       "directive"_err_en_US,
937                       ContextDirectiveAsFortran());
938                 } else if (name->symbol->GetUltimate().IsSubprogram()) {
939                   if (GetContext().directive ==
940                       llvm::omp::Directive::OMPD_threadprivate)
941                     context_.Say(name->source,
942                         "The procedure name cannot be in a %s "
943                         "directive"_err_en_US,
944                         ContextDirectiveAsFortran());
945                   // TODO: Check for procedure name in declare target directive.
946                 } else if (name->symbol->attrs().test(Attr::PARAMETER)) {
947                   if (GetContext().directive ==
948                       llvm::omp::Directive::OMPD_threadprivate)
949                     context_.Say(name->source,
950                         "The entity with PARAMETER attribute cannot be in a %s "
951                         "directive"_err_en_US,
952                         ContextDirectiveAsFortran());
953                   else if (GetContext().directive ==
954                       llvm::omp::Directive::OMPD_declare_target)
955                     context_.Say(name->source,
956                         "The entity with PARAMETER attribute is used in a %s "
957                         "directive"_warn_en_US,
958                         ContextDirectiveAsFortran());
959                 } else if (FindCommonBlockContaining(*name->symbol)) {
960                   context_.Say(name->source,
961                       "A variable in a %s directive cannot be an element of a "
962                       "common block"_err_en_US,
963                       ContextDirectiveAsFortran());
964                 } else if (!IsSave(*name->symbol) &&
965                     declScope.kind() != Scope::Kind::MainProgram &&
966                     declScope.kind() != Scope::Kind::Module) {
967                   context_.Say(name->source,
968                       "A variable that appears in a %s directive must be "
969                       "declared in the scope of a module or have the SAVE "
970                       "attribute, either explicitly or implicitly"_err_en_US,
971                       ContextDirectiveAsFortran());
972                 } else if (useScope != declScope) {
973                   context_.Say(name->source,
974                       "The %s directive and the common block or variable in it "
975                       "must appear in the same declaration section of a "
976                       "scoping unit"_err_en_US,
977                       ContextDirectiveAsFortran());
978                 } else if (FindEquivalenceSet(*name->symbol)) {
979                   context_.Say(name->source,
980                       "A variable in a %s directive cannot appear in an "
981                       "EQUIVALENCE statement"_err_en_US,
982                       ContextDirectiveAsFortran());
983                 } else if (name->symbol->test(Symbol::Flag::OmpThreadprivate) &&
984                     GetContext().directive ==
985                         llvm::omp::Directive::OMPD_declare_target) {
986                   context_.Say(name->source,
987                       "A THREADPRIVATE variable cannot appear in a %s "
988                       "directive"_err_en_US,
989                       ContextDirectiveAsFortran());
990                 }
991               }
992             },
993             [&](const parser::Name &) {}, // common block
994         },
995         ompObject.u);
996   }
997 }
998 
999 void OmpStructureChecker::Enter(const parser::OpenMPThreadprivate &c) {
1000   const auto &dir{std::get<parser::Verbatim>(c.t)};
1001   PushContextAndClauseSets(
1002       dir.source, llvm::omp::Directive::OMPD_threadprivate);
1003 }
1004 
1005 void OmpStructureChecker::Leave(const parser::OpenMPThreadprivate &c) {
1006   const auto &dir{std::get<parser::Verbatim>(c.t)};
1007   const auto &objectList{std::get<parser::OmpObjectList>(c.t)};
1008   CheckIsVarPartOfAnotherVar(dir.source, objectList);
1009   CheckThreadprivateOrDeclareTargetVar(objectList);
1010   dirContext_.pop_back();
1011 }
1012 
1013 void OmpStructureChecker::Enter(const parser::OpenMPDeclareSimdConstruct &x) {
1014   const auto &dir{std::get<parser::Verbatim>(x.t)};
1015   PushContextAndClauseSets(dir.source, llvm::omp::Directive::OMPD_declare_simd);
1016 }
1017 
1018 void OmpStructureChecker::Leave(const parser::OpenMPDeclareSimdConstruct &) {
1019   dirContext_.pop_back();
1020 }
1021 
1022 void OmpStructureChecker::Enter(const parser::OpenMPDeclarativeAllocate &x) {
1023   isPredefinedAllocator = true;
1024   const auto &dir{std::get<parser::Verbatim>(x.t)};
1025   const auto &objectList{std::get<parser::OmpObjectList>(x.t)};
1026   PushContextAndClauseSets(dir.source, llvm::omp::Directive::OMPD_allocate);
1027   CheckIsVarPartOfAnotherVar(dir.source, objectList);
1028 }
1029 
1030 void OmpStructureChecker::Leave(const parser::OpenMPDeclarativeAllocate &x) {
1031   const auto &dir{std::get<parser::Verbatim>(x.t)};
1032   const auto &objectList{std::get<parser::OmpObjectList>(x.t)};
1033   CheckPredefinedAllocatorRestriction(dir.source, objectList);
1034   dirContext_.pop_back();
1035 }
1036 
1037 void OmpStructureChecker::Enter(const parser::OmpClause::Allocator &x) {
1038   CheckAllowed(llvm::omp::Clause::OMPC_allocator);
1039   // Note: Predefined allocators are stored in ScalarExpr as numbers
1040   //   whereas custom allocators are stored as strings, so if the ScalarExpr
1041   //   actually has an int value, then it must be a predefined allocator
1042   isPredefinedAllocator = GetIntValue(x.v).has_value();
1043   RequiresPositiveParameter(llvm::omp::Clause::OMPC_allocator, x.v);
1044 }
1045 
1046 void OmpStructureChecker::Enter(const parser::OpenMPDeclareTargetConstruct &x) {
1047   const auto &dir{std::get<parser::Verbatim>(x.t)};
1048   PushContext(dir.source, llvm::omp::Directive::OMPD_declare_target);
1049   const auto &spec{std::get<parser::OmpDeclareTargetSpecifier>(x.t)};
1050   if (std::holds_alternative<parser::OmpDeclareTargetWithClause>(spec.u)) {
1051     SetClauseSets(llvm::omp::Directive::OMPD_declare_target);
1052   }
1053 }
1054 
1055 void OmpStructureChecker::Leave(const parser::OpenMPDeclareTargetConstruct &x) {
1056   const auto &dir{std::get<parser::Verbatim>(x.t)};
1057   const auto &spec{std::get<parser::OmpDeclareTargetSpecifier>(x.t)};
1058   if (const auto *objectList{parser::Unwrap<parser::OmpObjectList>(spec.u)}) {
1059     CheckIsVarPartOfAnotherVar(dir.source, *objectList);
1060     CheckThreadprivateOrDeclareTargetVar(*objectList);
1061   } else if (const auto *clauseList{
1062                  parser::Unwrap<parser::OmpClauseList>(spec.u)}) {
1063     for (const auto &clause : clauseList->v) {
1064       if (const auto *toClause{std::get_if<parser::OmpClause::To>(&clause.u)}) {
1065         CheckIsVarPartOfAnotherVar(dir.source, toClause->v);
1066         CheckThreadprivateOrDeclareTargetVar(toClause->v);
1067       } else if (const auto *linkClause{
1068                      std::get_if<parser::OmpClause::Link>(&clause.u)}) {
1069         CheckIsVarPartOfAnotherVar(dir.source, linkClause->v);
1070         CheckThreadprivateOrDeclareTargetVar(linkClause->v);
1071       }
1072     }
1073   }
1074   dirContext_.pop_back();
1075 }
1076 
1077 void OmpStructureChecker::Enter(const parser::OpenMPExecutableAllocate &x) {
1078   isPredefinedAllocator = true;
1079   const auto &dir{std::get<parser::Verbatim>(x.t)};
1080   const auto &objectList{std::get<std::optional<parser::OmpObjectList>>(x.t)};
1081   PushContextAndClauseSets(dir.source, llvm::omp::Directive::OMPD_allocate);
1082   if (objectList) {
1083     CheckIsVarPartOfAnotherVar(dir.source, *objectList);
1084   }
1085 }
1086 
1087 void OmpStructureChecker::Leave(const parser::OpenMPExecutableAllocate &x) {
1088   const auto &dir{std::get<parser::Verbatim>(x.t)};
1089   const auto &objectList{std::get<std::optional<parser::OmpObjectList>>(x.t)};
1090   if (objectList)
1091     CheckPredefinedAllocatorRestriction(dir.source, *objectList);
1092   dirContext_.pop_back();
1093 }
1094 
1095 void OmpStructureChecker::CheckBarrierNesting(
1096     const parser::OpenMPSimpleStandaloneConstruct &x) {
1097   // A barrier region may not be `closely nested` inside a worksharing, loop,
1098   // task, taskloop, critical, ordered, atomic, or master region.
1099   // TODO:  Expand the check to include `LOOP` construct as well when it is
1100   // supported.
1101   if (GetContext().directive == llvm::omp::Directive::OMPD_barrier) {
1102     if (IsCloselyNestedRegion(llvm::omp::nestedBarrierErrSet)) {
1103       context_.Say(parser::FindSourceLocation(x),
1104           "`BARRIER` region may not be closely nested inside of `WORKSHARING`, "
1105           "`LOOP`, `TASK`, `TASKLOOP`,"
1106           "`CRITICAL`, `ORDERED`, `ATOMIC` or `MASTER` region."_err_en_US);
1107     }
1108   }
1109 }
1110 
1111 void OmpStructureChecker::ChecksOnOrderedAsStandalone() {
1112   if (FindClause(llvm::omp::Clause::OMPC_threads) ||
1113       FindClause(llvm::omp::Clause::OMPC_simd)) {
1114     context_.Say(GetContext().clauseSource,
1115         "THREADS, SIMD clauses are not allowed when ORDERED construct is a "
1116         "standalone construct with no ORDERED region"_err_en_US);
1117   }
1118 
1119   bool isSinkPresent{false};
1120   int dependSourceCount{0};
1121   auto clauseAll = FindClauses(llvm::omp::Clause::OMPC_depend);
1122   for (auto itr = clauseAll.first; itr != clauseAll.second; ++itr) {
1123     const auto &dependClause{
1124         std::get<parser::OmpClause::Depend>(itr->second->u)};
1125     if (std::get_if<parser::OmpDependClause::Source>(&dependClause.v.u)) {
1126       dependSourceCount++;
1127       if (isSinkPresent) {
1128         context_.Say(itr->second->source,
1129             "DEPEND(SOURCE) is not allowed when DEPEND(SINK: vec) is present "
1130             "on ORDERED directive"_err_en_US);
1131       }
1132       if (dependSourceCount > 1) {
1133         context_.Say(itr->second->source,
1134             "At most one DEPEND(SOURCE) clause can appear on the ORDERED "
1135             "directive"_err_en_US);
1136       }
1137     } else if (std::get_if<parser::OmpDependClause::Sink>(&dependClause.v.u)) {
1138       isSinkPresent = true;
1139       if (dependSourceCount > 0) {
1140         context_.Say(itr->second->source,
1141             "DEPEND(SINK: vec) is not allowed when DEPEND(SOURCE) is present "
1142             "on ORDERED directive"_err_en_US);
1143       }
1144     } else {
1145       context_.Say(itr->second->source,
1146           "Only DEPEND(SOURCE) or DEPEND(SINK: vec) are allowed when ORDERED "
1147           "construct is a standalone construct with no ORDERED "
1148           "region"_err_en_US);
1149     }
1150   }
1151 
1152   OmpDirectiveSet allowedDoSet{llvm::omp::Directive::OMPD_do,
1153       llvm::omp::Directive::OMPD_parallel_do,
1154       llvm::omp::Directive::OMPD_target_parallel_do};
1155   bool isNestedInDoOrderedWithPara{false};
1156   if (CurrentDirectiveIsNested() &&
1157       allowedDoSet.test(GetContextParent().directive)) {
1158     if (const auto *clause{
1159             FindClause(GetContextParent(), llvm::omp::Clause::OMPC_ordered)}) {
1160       const auto &orderedClause{
1161           std::get<parser::OmpClause::Ordered>(clause->u)};
1162       const auto orderedValue{GetIntValue(orderedClause.v)};
1163       if (orderedValue > 0) {
1164         isNestedInDoOrderedWithPara = true;
1165         CheckOrderedDependClause(orderedValue);
1166       }
1167     }
1168   }
1169 
1170   if (FindClause(llvm::omp::Clause::OMPC_depend) &&
1171       !isNestedInDoOrderedWithPara) {
1172     context_.Say(GetContext().clauseSource,
1173         "An ORDERED construct with the DEPEND clause must be closely nested "
1174         "in a worksharing-loop (or parallel worksharing-loop) construct with "
1175         "ORDERED clause with a parameter"_err_en_US);
1176   }
1177 }
1178 
1179 void OmpStructureChecker::CheckOrderedDependClause(
1180     std::optional<std::int64_t> orderedValue) {
1181   auto clauseAll{FindClauses(llvm::omp::Clause::OMPC_depend)};
1182   for (auto itr = clauseAll.first; itr != clauseAll.second; ++itr) {
1183     const auto &dependClause{
1184         std::get<parser::OmpClause::Depend>(itr->second->u)};
1185     if (const auto *sinkVectors{
1186             std::get_if<parser::OmpDependClause::Sink>(&dependClause.v.u)}) {
1187       std::int64_t numVar = sinkVectors->v.size();
1188       if (orderedValue != numVar) {
1189         context_.Say(itr->second->source,
1190             "The number of variables in DEPEND(SINK: vec) clause does not "
1191             "match the parameter specified in ORDERED clause"_err_en_US);
1192       }
1193     }
1194   }
1195 }
1196 
1197 void OmpStructureChecker::Enter(
1198     const parser::OpenMPSimpleStandaloneConstruct &x) {
1199   const auto &dir{std::get<parser::OmpSimpleStandaloneDirective>(x.t)};
1200   PushContextAndClauseSets(dir.source, dir.v);
1201   CheckBarrierNesting(x);
1202 }
1203 
1204 void OmpStructureChecker::Leave(
1205     const parser::OpenMPSimpleStandaloneConstruct &) {
1206   switch (GetContext().directive) {
1207   case llvm::omp::Directive::OMPD_ordered:
1208     // [5.1] 2.19.9 Ordered Construct Restriction
1209     ChecksOnOrderedAsStandalone();
1210     break;
1211   default:
1212     break;
1213   }
1214   dirContext_.pop_back();
1215 }
1216 
1217 void OmpStructureChecker::Enter(const parser::OpenMPFlushConstruct &x) {
1218   const auto &dir{std::get<parser::Verbatim>(x.t)};
1219   PushContextAndClauseSets(dir.source, llvm::omp::Directive::OMPD_flush);
1220 }
1221 
1222 void OmpStructureChecker::Leave(const parser::OpenMPFlushConstruct &x) {
1223   if (FindClause(llvm::omp::Clause::OMPC_acquire) ||
1224       FindClause(llvm::omp::Clause::OMPC_release) ||
1225       FindClause(llvm::omp::Clause::OMPC_acq_rel)) {
1226     if (const auto &flushList{
1227             std::get<std::optional<parser::OmpObjectList>>(x.t)}) {
1228       context_.Say(parser::FindSourceLocation(flushList),
1229           "If memory-order-clause is RELEASE, ACQUIRE, or ACQ_REL, list items "
1230           "must not be specified on the FLUSH directive"_err_en_US);
1231     }
1232   }
1233   dirContext_.pop_back();
1234 }
1235 
1236 void OmpStructureChecker::Enter(const parser::OpenMPCancelConstruct &x) {
1237   const auto &dir{std::get<parser::Verbatim>(x.t)};
1238   const auto &type{std::get<parser::OmpCancelType>(x.t)};
1239   PushContextAndClauseSets(dir.source, llvm::omp::Directive::OMPD_cancel);
1240   CheckCancellationNest(dir.source, type.v);
1241 }
1242 
1243 void OmpStructureChecker::Leave(const parser::OpenMPCancelConstruct &) {
1244   dirContext_.pop_back();
1245 }
1246 
1247 void OmpStructureChecker::Enter(const parser::OpenMPCriticalConstruct &x) {
1248   const auto &dir{std::get<parser::OmpCriticalDirective>(x.t)};
1249   const auto &endDir{std::get<parser::OmpEndCriticalDirective>(x.t)};
1250   PushContextAndClauseSets(dir.source, llvm::omp::Directive::OMPD_critical);
1251   const auto &block{std::get<parser::Block>(x.t)};
1252   CheckNoBranching(block, llvm::omp::Directive::OMPD_critical, dir.source);
1253   const auto &dirName{std::get<std::optional<parser::Name>>(dir.t)};
1254   const auto &endDirName{std::get<std::optional<parser::Name>>(endDir.t)};
1255   const auto &ompClause{std::get<parser::OmpClauseList>(dir.t)};
1256   if (dirName && endDirName &&
1257       dirName->ToString().compare(endDirName->ToString())) {
1258     context_
1259         .Say(endDirName->source,
1260             parser::MessageFormattedText{
1261                 "CRITICAL directive names do not match"_err_en_US})
1262         .Attach(dirName->source, "should be "_en_US);
1263   } else if (dirName && !endDirName) {
1264     context_
1265         .Say(dirName->source,
1266             parser::MessageFormattedText{
1267                 "CRITICAL directive names do not match"_err_en_US})
1268         .Attach(dirName->source, "should be NULL"_en_US);
1269   } else if (!dirName && endDirName) {
1270     context_
1271         .Say(endDirName->source,
1272             parser::MessageFormattedText{
1273                 "CRITICAL directive names do not match"_err_en_US})
1274         .Attach(endDirName->source, "should be NULL"_en_US);
1275   }
1276   if (!dirName && !ompClause.source.empty() &&
1277       ompClause.source.NULTerminatedToString() != "hint(omp_sync_hint_none)") {
1278     context_.Say(dir.source,
1279         parser::MessageFormattedText{
1280             "Hint clause other than omp_sync_hint_none cannot be specified for an unnamed CRITICAL directive"_err_en_US});
1281   }
1282 }
1283 
1284 void OmpStructureChecker::Leave(const parser::OpenMPCriticalConstruct &) {
1285   dirContext_.pop_back();
1286 }
1287 
1288 void OmpStructureChecker::Enter(
1289     const parser::OpenMPCancellationPointConstruct &x) {
1290   const auto &dir{std::get<parser::Verbatim>(x.t)};
1291   const auto &type{std::get<parser::OmpCancelType>(x.t)};
1292   PushContextAndClauseSets(
1293       dir.source, llvm::omp::Directive::OMPD_cancellation_point);
1294   CheckCancellationNest(dir.source, type.v);
1295 }
1296 
1297 void OmpStructureChecker::Leave(
1298     const parser::OpenMPCancellationPointConstruct &) {
1299   dirContext_.pop_back();
1300 }
1301 
1302 void OmpStructureChecker::CheckCancellationNest(
1303     const parser::CharBlock &source, const parser::OmpCancelType::Type &type) {
1304   if (CurrentDirectiveIsNested()) {
1305     // If construct-type-clause is taskgroup, the cancellation construct must be
1306     // closely nested inside a task or a taskloop construct and the cancellation
1307     // region must be closely nested inside a taskgroup region. If
1308     // construct-type-clause is sections, the cancellation construct must be
1309     // closely nested inside a sections or section construct. Otherwise, the
1310     // cancellation construct must be closely nested inside an OpenMP construct
1311     // that matches the type specified in construct-type-clause of the
1312     // cancellation construct.
1313 
1314     OmpDirectiveSet allowedTaskgroupSet{
1315         llvm::omp::Directive::OMPD_task, llvm::omp::Directive::OMPD_taskloop};
1316     OmpDirectiveSet allowedSectionsSet{llvm::omp::Directive::OMPD_sections,
1317         llvm::omp::Directive::OMPD_parallel_sections};
1318     OmpDirectiveSet allowedDoSet{llvm::omp::Directive::OMPD_do,
1319         llvm::omp::Directive::OMPD_distribute_parallel_do,
1320         llvm::omp::Directive::OMPD_parallel_do,
1321         llvm::omp::Directive::OMPD_target_parallel_do,
1322         llvm::omp::Directive::OMPD_target_teams_distribute_parallel_do,
1323         llvm::omp::Directive::OMPD_teams_distribute_parallel_do};
1324     OmpDirectiveSet allowedParallelSet{llvm::omp::Directive::OMPD_parallel,
1325         llvm::omp::Directive::OMPD_target_parallel};
1326 
1327     bool eligibleCancellation{false};
1328     switch (type) {
1329     case parser::OmpCancelType::Type::Taskgroup:
1330       if (allowedTaskgroupSet.test(GetContextParent().directive)) {
1331         eligibleCancellation = true;
1332         if (dirContext_.size() >= 3) {
1333           // Check if the cancellation region is closely nested inside a
1334           // taskgroup region when there are more than two levels of directives
1335           // in the directive context stack.
1336           if (GetContextParent().directive == llvm::omp::Directive::OMPD_task ||
1337               FindClauseParent(llvm::omp::Clause::OMPC_nogroup)) {
1338             for (int i = dirContext_.size() - 3; i >= 0; i--) {
1339               if (dirContext_[i].directive ==
1340                   llvm::omp::Directive::OMPD_taskgroup) {
1341                 break;
1342               }
1343               if (allowedParallelSet.test(dirContext_[i].directive)) {
1344                 eligibleCancellation = false;
1345                 break;
1346               }
1347             }
1348           }
1349         }
1350       }
1351       if (!eligibleCancellation) {
1352         context_.Say(source,
1353             "With %s clause, %s construct must be closely nested inside TASK "
1354             "or TASKLOOP construct and %s region must be closely nested inside "
1355             "TASKGROUP region"_err_en_US,
1356             parser::ToUpperCaseLetters(
1357                 parser::OmpCancelType::EnumToString(type)),
1358             ContextDirectiveAsFortran(), ContextDirectiveAsFortran());
1359       }
1360       return;
1361     case parser::OmpCancelType::Type::Sections:
1362       if (allowedSectionsSet.test(GetContextParent().directive)) {
1363         eligibleCancellation = true;
1364       }
1365       break;
1366     case Fortran::parser::OmpCancelType::Type::Do:
1367       if (allowedDoSet.test(GetContextParent().directive)) {
1368         eligibleCancellation = true;
1369       }
1370       break;
1371     case parser::OmpCancelType::Type::Parallel:
1372       if (allowedParallelSet.test(GetContextParent().directive)) {
1373         eligibleCancellation = true;
1374       }
1375       break;
1376     }
1377     if (!eligibleCancellation) {
1378       context_.Say(source,
1379           "With %s clause, %s construct cannot be closely nested inside %s "
1380           "construct"_err_en_US,
1381           parser::ToUpperCaseLetters(parser::OmpCancelType::EnumToString(type)),
1382           ContextDirectiveAsFortran(),
1383           parser::ToUpperCaseLetters(
1384               getDirectiveName(GetContextParent().directive).str()));
1385     }
1386   } else {
1387     // The cancellation directive cannot be orphaned.
1388     switch (type) {
1389     case parser::OmpCancelType::Type::Taskgroup:
1390       context_.Say(source,
1391           "%s %s directive is not closely nested inside "
1392           "TASK or TASKLOOP"_err_en_US,
1393           ContextDirectiveAsFortran(),
1394           parser::ToUpperCaseLetters(
1395               parser::OmpCancelType::EnumToString(type)));
1396       break;
1397     case parser::OmpCancelType::Type::Sections:
1398       context_.Say(source,
1399           "%s %s directive is not closely nested inside "
1400           "SECTION or SECTIONS"_err_en_US,
1401           ContextDirectiveAsFortran(),
1402           parser::ToUpperCaseLetters(
1403               parser::OmpCancelType::EnumToString(type)));
1404       break;
1405     case Fortran::parser::OmpCancelType::Type::Do:
1406       context_.Say(source,
1407           "%s %s directive is not closely nested inside "
1408           "the construct that matches the DO clause type"_err_en_US,
1409           ContextDirectiveAsFortran(),
1410           parser::ToUpperCaseLetters(
1411               parser::OmpCancelType::EnumToString(type)));
1412       break;
1413     case parser::OmpCancelType::Type::Parallel:
1414       context_.Say(source,
1415           "%s %s directive is not closely nested inside "
1416           "the construct that matches the PARALLEL clause type"_err_en_US,
1417           ContextDirectiveAsFortran(),
1418           parser::ToUpperCaseLetters(
1419               parser::OmpCancelType::EnumToString(type)));
1420       break;
1421     }
1422   }
1423 }
1424 
1425 void OmpStructureChecker::Enter(const parser::OmpEndBlockDirective &x) {
1426   const auto &dir{std::get<parser::OmpBlockDirective>(x.t)};
1427   ResetPartialContext(dir.source);
1428   switch (dir.v) {
1429   // 2.7.3 end-single-clause -> copyprivate-clause |
1430   //                            nowait-clause
1431   case llvm::omp::Directive::OMPD_single:
1432     PushContextAndClauseSets(dir.source, llvm::omp::Directive::OMPD_end_single);
1433     break;
1434   // 2.7.4 end-workshare -> END WORKSHARE [nowait-clause]
1435   case llvm::omp::Directive::OMPD_workshare:
1436     PushContextAndClauseSets(
1437         dir.source, llvm::omp::Directive::OMPD_end_workshare);
1438     break;
1439   default:
1440     // no clauses are allowed
1441     break;
1442   }
1443 }
1444 
1445 // TODO: Verify the popping of dirContext requirement after nowait
1446 // implementation, as there is an implicit barrier at the end of the worksharing
1447 // constructs unless a nowait clause is specified. Only OMPD_end_single and
1448 // end_workshareare popped as they are pushed while entering the
1449 // EndBlockDirective.
1450 void OmpStructureChecker::Leave(const parser::OmpEndBlockDirective &x) {
1451   if ((GetContext().directive == llvm::omp::Directive::OMPD_end_single) ||
1452       (GetContext().directive == llvm::omp::Directive::OMPD_end_workshare)) {
1453     dirContext_.pop_back();
1454   }
1455 }
1456 
1457 template <typename T, typename D>
1458 bool OmpStructureChecker::IsOperatorValid(const T &node, const D &variable) {
1459   using AllowedBinaryOperators =
1460       std::variant<parser::Expr::Add, parser::Expr::Multiply,
1461           parser::Expr::Subtract, parser::Expr::Divide, parser::Expr::AND,
1462           parser::Expr::OR, parser::Expr::EQV, parser::Expr::NEQV>;
1463   using BinaryOperators = std::variant<parser::Expr::Add,
1464       parser::Expr::Multiply, parser::Expr::Subtract, parser::Expr::Divide,
1465       parser::Expr::AND, parser::Expr::OR, parser::Expr::EQV,
1466       parser::Expr::NEQV, parser::Expr::Power, parser::Expr::Concat,
1467       parser::Expr::LT, parser::Expr::LE, parser::Expr::EQ, parser::Expr::NE,
1468       parser::Expr::GE, parser::Expr::GT>;
1469 
1470   if constexpr (common::HasMember<T, BinaryOperators>) {
1471     const auto &variableName{variable.GetSource().ToString()};
1472     const auto &exprLeft{std::get<0>(node.t)};
1473     const auto &exprRight{std::get<1>(node.t)};
1474     if ((exprLeft.value().source.ToString() != variableName) &&
1475         (exprRight.value().source.ToString() != variableName)) {
1476       context_.Say(variable.GetSource(),
1477           "Atomic update variable '%s' not found in the RHS of the "
1478           "assignment statement in an ATOMIC (UPDATE) construct"_err_en_US,
1479           variableName);
1480     }
1481     return common::HasMember<T, AllowedBinaryOperators>;
1482   }
1483   return true;
1484 }
1485 
1486 void OmpStructureChecker::CheckAtomicUpdateAssignmentStmt(
1487     const parser::AssignmentStmt &assignment) {
1488   const auto &expr{std::get<parser::Expr>(assignment.t)};
1489   const auto &var{std::get<parser::Variable>(assignment.t)};
1490   common::visit(
1491       common::visitors{
1492           [&](const common::Indirection<parser::FunctionReference> &x) {
1493             const auto &procedureDesignator{
1494                 std::get<parser::ProcedureDesignator>(x.value().v.t)};
1495             const parser::Name *name{
1496                 std::get_if<parser::Name>(&procedureDesignator.u)};
1497             if (name &&
1498                 !(name->source == "max" || name->source == "min" ||
1499                     name->source == "iand" || name->source == "ior" ||
1500                     name->source == "ieor")) {
1501               context_.Say(expr.source,
1502                   "Invalid intrinsic procedure name in "
1503                   "OpenMP ATOMIC (UPDATE) statement"_err_en_US);
1504             } else if (name) {
1505               bool foundMatch{false};
1506               if (auto varDesignatorIndirection =
1507                       std::get_if<Fortran::common::Indirection<
1508                           Fortran::parser::Designator>>(&var.u)) {
1509                 const auto &varDesignator = varDesignatorIndirection->value();
1510                 if (const auto *dataRef = std::get_if<Fortran::parser::DataRef>(
1511                         &varDesignator.u)) {
1512                   if (const auto *name =
1513                           std::get_if<Fortran::parser::Name>(&dataRef->u)) {
1514                     const auto &varSymbol = *name->symbol;
1515                     if (const auto *e{GetExpr(context_, expr)}) {
1516                       for (const Symbol &symbol :
1517                           evaluate::CollectSymbols(*e)) {
1518                         if (symbol == varSymbol) {
1519                           foundMatch = true;
1520                           break;
1521                         }
1522                       }
1523                     }
1524                   }
1525                 }
1526               }
1527               if (!foundMatch) {
1528                 context_.Say(expr.source,
1529                     "Atomic update variable '%s' not found in the "
1530                     "argument list of intrinsic procedure"_err_en_US,
1531                     var.GetSource().ToString());
1532               }
1533             }
1534           },
1535           [&](const auto &x) {
1536             if (!IsOperatorValid(x, var)) {
1537               context_.Say(expr.source,
1538                   "Invalid operator in OpenMP ATOMIC (UPDATE) statement"_err_en_US);
1539             }
1540           },
1541       },
1542       expr.u);
1543 }
1544 
1545 void OmpStructureChecker::CheckAtomicMemoryOrderClause(
1546     const parser::OmpAtomicClauseList &clauseList) {
1547   int numMemoryOrderClause = 0;
1548   for (const auto &clause : clauseList.v) {
1549     if (std::get_if<Fortran::parser::OmpMemoryOrderClause>(&clause.u)) {
1550       numMemoryOrderClause++;
1551       if (numMemoryOrderClause > 1) {
1552         context_.Say(clause.source,
1553             "More than one memory order clause not allowed on OpenMP "
1554             "Atomic construct"_err_en_US);
1555         return;
1556       }
1557     }
1558   }
1559 }
1560 
1561 void OmpStructureChecker::CheckAtomicMemoryOrderClause(
1562     const parser::OmpAtomicClauseList &leftHandClauseList,
1563     const parser::OmpAtomicClauseList &rightHandClauseList) {
1564   int numMemoryOrderClause = 0;
1565   for (const auto &clause : leftHandClauseList.v) {
1566     if (std::get_if<Fortran::parser::OmpMemoryOrderClause>(&clause.u)) {
1567       numMemoryOrderClause++;
1568       if (numMemoryOrderClause > 1) {
1569         context_.Say(clause.source,
1570             "More than one memory order clause not allowed on "
1571             "OpenMP Atomic construct"_err_en_US);
1572         return;
1573       }
1574     }
1575   }
1576   for (const auto &clause : rightHandClauseList.v) {
1577     if (std::get_if<Fortran::parser::OmpMemoryOrderClause>(&clause.u)) {
1578       numMemoryOrderClause++;
1579       if (numMemoryOrderClause > 1) {
1580         context_.Say(clause.source,
1581             "More than one memory order clause not "
1582             "allowed on OpenMP Atomic construct"_err_en_US);
1583         return;
1584       }
1585     }
1586   }
1587 }
1588 
1589 void OmpStructureChecker::Enter(const parser::OpenMPAtomicConstruct &x) {
1590   common::visit(
1591       common::visitors{
1592           [&](const parser::OmpAtomic &atomicConstruct) {
1593             const auto &dir{std::get<parser::Verbatim>(atomicConstruct.t)};
1594             PushContextAndClauseSets(
1595                 dir.source, llvm::omp::Directive::OMPD_atomic);
1596             CheckAtomicUpdateAssignmentStmt(
1597                 std::get<parser::Statement<parser::AssignmentStmt>>(
1598                     atomicConstruct.t)
1599                     .statement);
1600             CheckAtomicMemoryOrderClause(
1601                 std::get<parser::OmpAtomicClauseList>(atomicConstruct.t));
1602           },
1603           [&](const parser::OmpAtomicUpdate &atomicConstruct) {
1604             const auto &dir{std::get<parser::Verbatim>(atomicConstruct.t)};
1605             PushContextAndClauseSets(
1606                 dir.source, llvm::omp::Directive::OMPD_atomic);
1607             CheckAtomicUpdateAssignmentStmt(
1608                 std::get<parser::Statement<parser::AssignmentStmt>>(
1609                     atomicConstruct.t)
1610                     .statement);
1611             CheckAtomicMemoryOrderClause(
1612                 std::get<0>(atomicConstruct.t), std::get<2>(atomicConstruct.t));
1613           },
1614           [&](const auto &atomicConstruct) {
1615             const auto &dir{std::get<parser::Verbatim>(atomicConstruct.t)};
1616             PushContextAndClauseSets(
1617                 dir.source, llvm::omp::Directive::OMPD_atomic);
1618             CheckAtomicMemoryOrderClause(
1619                 std::get<0>(atomicConstruct.t), std::get<2>(atomicConstruct.t));
1620           },
1621       },
1622       x.u);
1623 }
1624 
1625 void OmpStructureChecker::Leave(const parser::OpenMPAtomicConstruct &) {
1626   dirContext_.pop_back();
1627 }
1628 
1629 // Clauses
1630 // Mainly categorized as
1631 // 1. Checks on 'OmpClauseList' from 'parse-tree.h'.
1632 // 2. Checks on clauses which fall under 'struct OmpClause' from parse-tree.h.
1633 // 3. Checks on clauses which are not in 'struct OmpClause' from parse-tree.h.
1634 
1635 void OmpStructureChecker::Leave(const parser::OmpClauseList &) {
1636   // 2.7.1 Loop Construct Restriction
1637   if (llvm::omp::doSet.test(GetContext().directive)) {
1638     if (auto *clause{FindClause(llvm::omp::Clause::OMPC_schedule)}) {
1639       // only one schedule clause is allowed
1640       const auto &schedClause{std::get<parser::OmpClause::Schedule>(clause->u)};
1641       if (ScheduleModifierHasType(schedClause.v,
1642               parser::OmpScheduleModifierType::ModType::Nonmonotonic)) {
1643         if (FindClause(llvm::omp::Clause::OMPC_ordered)) {
1644           context_.Say(clause->source,
1645               "The NONMONOTONIC modifier cannot be specified "
1646               "if an ORDERED clause is specified"_err_en_US);
1647         }
1648         if (ScheduleModifierHasType(schedClause.v,
1649                 parser::OmpScheduleModifierType::ModType::Monotonic)) {
1650           context_.Say(clause->source,
1651               "The MONOTONIC and NONMONOTONIC modifiers "
1652               "cannot be both specified"_err_en_US);
1653         }
1654       }
1655     }
1656 
1657     if (auto *clause{FindClause(llvm::omp::Clause::OMPC_ordered)}) {
1658       // only one ordered clause is allowed
1659       const auto &orderedClause{
1660           std::get<parser::OmpClause::Ordered>(clause->u)};
1661 
1662       if (orderedClause.v) {
1663         CheckNotAllowedIfClause(
1664             llvm::omp::Clause::OMPC_ordered, {llvm::omp::Clause::OMPC_linear});
1665 
1666         if (auto *clause2{FindClause(llvm::omp::Clause::OMPC_collapse)}) {
1667           const auto &collapseClause{
1668               std::get<parser::OmpClause::Collapse>(clause2->u)};
1669           // ordered and collapse both have parameters
1670           if (const auto orderedValue{GetIntValue(orderedClause.v)}) {
1671             if (const auto collapseValue{GetIntValue(collapseClause.v)}) {
1672               if (*orderedValue > 0 && *orderedValue < *collapseValue) {
1673                 context_.Say(clause->source,
1674                     "The parameter of the ORDERED clause must be "
1675                     "greater than or equal to "
1676                     "the parameter of the COLLAPSE clause"_err_en_US);
1677               }
1678             }
1679           }
1680         }
1681       }
1682 
1683       // TODO: ordered region binding check (requires nesting implementation)
1684     }
1685   } // doSet
1686 
1687   // 2.8.1 Simd Construct Restriction
1688   if (llvm::omp::simdSet.test(GetContext().directive)) {
1689     if (auto *clause{FindClause(llvm::omp::Clause::OMPC_simdlen)}) {
1690       if (auto *clause2{FindClause(llvm::omp::Clause::OMPC_safelen)}) {
1691         const auto &simdlenClause{
1692             std::get<parser::OmpClause::Simdlen>(clause->u)};
1693         const auto &safelenClause{
1694             std::get<parser::OmpClause::Safelen>(clause2->u)};
1695         // simdlen and safelen both have parameters
1696         if (const auto simdlenValue{GetIntValue(simdlenClause.v)}) {
1697           if (const auto safelenValue{GetIntValue(safelenClause.v)}) {
1698             if (*safelenValue > 0 && *simdlenValue > *safelenValue) {
1699               context_.Say(clause->source,
1700                   "The parameter of the SIMDLEN clause must be less than or "
1701                   "equal to the parameter of the SAFELEN clause"_err_en_US);
1702             }
1703           }
1704         }
1705       }
1706     }
1707     // Sema checks related to presence of multiple list items within the same
1708     // clause
1709     CheckMultListItems();
1710   } // SIMD
1711 
1712   // 2.7.3 Single Construct Restriction
1713   if (GetContext().directive == llvm::omp::Directive::OMPD_end_single) {
1714     CheckNotAllowedIfClause(
1715         llvm::omp::Clause::OMPC_copyprivate, {llvm::omp::Clause::OMPC_nowait});
1716   }
1717 
1718   auto testThreadprivateVarErr = [&](Symbol sym, parser::Name name,
1719                                      llvmOmpClause clauseTy) {
1720     if (sym.test(Symbol::Flag::OmpThreadprivate))
1721       context_.Say(name.source,
1722           "A THREADPRIVATE variable cannot be in %s clause"_err_en_US,
1723           parser::ToUpperCaseLetters(getClauseName(clauseTy).str()));
1724   };
1725 
1726   // [5.1] 2.21.2 Threadprivate Directive Restriction
1727   OmpClauseSet threadprivateAllowedSet{llvm::omp::Clause::OMPC_copyin,
1728       llvm::omp::Clause::OMPC_copyprivate, llvm::omp::Clause::OMPC_schedule,
1729       llvm::omp::Clause::OMPC_num_threads, llvm::omp::Clause::OMPC_thread_limit,
1730       llvm::omp::Clause::OMPC_if};
1731   for (auto it : GetContext().clauseInfo) {
1732     llvmOmpClause type = it.first;
1733     const auto *clause = it.second;
1734     if (!threadprivateAllowedSet.test(type)) {
1735       if (const auto *objList{GetOmpObjectList(*clause)}) {
1736         for (const auto &ompObject : objList->v) {
1737           common::visit(
1738               common::visitors{
1739                   [&](const parser::Designator &) {
1740                     if (const auto *name{
1741                             parser::Unwrap<parser::Name>(ompObject)})
1742                       testThreadprivateVarErr(
1743                           name->symbol->GetUltimate(), *name, type);
1744                   },
1745                   [&](const parser::Name &name) {
1746                     if (name.symbol) {
1747                       for (const auto &mem :
1748                           name.symbol->get<CommonBlockDetails>().objects()) {
1749                         testThreadprivateVarErr(mem->GetUltimate(), name, type);
1750                         break;
1751                       }
1752                     }
1753                   },
1754               },
1755               ompObject.u);
1756         }
1757       }
1758     }
1759   }
1760 
1761   CheckRequireAtLeastOneOf();
1762 }
1763 
1764 void OmpStructureChecker::Enter(const parser::OmpClause &x) {
1765   SetContextClause(x);
1766 }
1767 
1768 // Following clauses do not have a separate node in parse-tree.h.
1769 CHECK_SIMPLE_CLAUSE(AcqRel, OMPC_acq_rel)
1770 CHECK_SIMPLE_CLAUSE(Acquire, OMPC_acquire)
1771 CHECK_SIMPLE_CLAUSE(AtomicDefaultMemOrder, OMPC_atomic_default_mem_order)
1772 CHECK_SIMPLE_CLAUSE(Affinity, OMPC_affinity)
1773 CHECK_SIMPLE_CLAUSE(Allocate, OMPC_allocate)
1774 CHECK_SIMPLE_CLAUSE(Capture, OMPC_capture)
1775 CHECK_SIMPLE_CLAUSE(Copyin, OMPC_copyin)
1776 CHECK_SIMPLE_CLAUSE(Default, OMPC_default)
1777 CHECK_SIMPLE_CLAUSE(Depobj, OMPC_depobj)
1778 CHECK_SIMPLE_CLAUSE(Destroy, OMPC_destroy)
1779 CHECK_SIMPLE_CLAUSE(Detach, OMPC_detach)
1780 CHECK_SIMPLE_CLAUSE(DeviceType, OMPC_device_type)
1781 CHECK_SIMPLE_CLAUSE(DistSchedule, OMPC_dist_schedule)
1782 CHECK_SIMPLE_CLAUSE(DynamicAllocators, OMPC_dynamic_allocators)
1783 CHECK_SIMPLE_CLAUSE(Exclusive, OMPC_exclusive)
1784 CHECK_SIMPLE_CLAUSE(Final, OMPC_final)
1785 CHECK_SIMPLE_CLAUSE(Flush, OMPC_flush)
1786 CHECK_SIMPLE_CLAUSE(From, OMPC_from)
1787 CHECK_SIMPLE_CLAUSE(Full, OMPC_full)
1788 CHECK_SIMPLE_CLAUSE(Hint, OMPC_hint)
1789 CHECK_SIMPLE_CLAUSE(InReduction, OMPC_in_reduction)
1790 CHECK_SIMPLE_CLAUSE(Inclusive, OMPC_inclusive)
1791 CHECK_SIMPLE_CLAUSE(Match, OMPC_match)
1792 CHECK_SIMPLE_CLAUSE(Nontemporal, OMPC_nontemporal)
1793 CHECK_SIMPLE_CLAUSE(Order, OMPC_order)
1794 CHECK_SIMPLE_CLAUSE(Read, OMPC_read)
1795 CHECK_SIMPLE_CLAUSE(ReverseOffload, OMPC_reverse_offload)
1796 CHECK_SIMPLE_CLAUSE(Threadprivate, OMPC_threadprivate)
1797 CHECK_SIMPLE_CLAUSE(Threads, OMPC_threads)
1798 CHECK_SIMPLE_CLAUSE(Inbranch, OMPC_inbranch)
1799 CHECK_SIMPLE_CLAUSE(IsDevicePtr, OMPC_is_device_ptr)
1800 CHECK_SIMPLE_CLAUSE(HasDeviceAddr, OMPC_has_device_addr)
1801 CHECK_SIMPLE_CLAUSE(Link, OMPC_link)
1802 CHECK_SIMPLE_CLAUSE(Indirect, OMPC_indirect)
1803 CHECK_SIMPLE_CLAUSE(Mergeable, OMPC_mergeable)
1804 CHECK_SIMPLE_CLAUSE(Nogroup, OMPC_nogroup)
1805 CHECK_SIMPLE_CLAUSE(Notinbranch, OMPC_notinbranch)
1806 CHECK_SIMPLE_CLAUSE(Nowait, OMPC_nowait)
1807 CHECK_SIMPLE_CLAUSE(Partial, OMPC_partial)
1808 CHECK_SIMPLE_CLAUSE(ProcBind, OMPC_proc_bind)
1809 CHECK_SIMPLE_CLAUSE(Release, OMPC_release)
1810 CHECK_SIMPLE_CLAUSE(Relaxed, OMPC_relaxed)
1811 CHECK_SIMPLE_CLAUSE(SeqCst, OMPC_seq_cst)
1812 CHECK_SIMPLE_CLAUSE(Simd, OMPC_simd)
1813 CHECK_SIMPLE_CLAUSE(Sizes, OMPC_sizes)
1814 CHECK_SIMPLE_CLAUSE(TaskReduction, OMPC_task_reduction)
1815 CHECK_SIMPLE_CLAUSE(To, OMPC_to)
1816 CHECK_SIMPLE_CLAUSE(UnifiedAddress, OMPC_unified_address)
1817 CHECK_SIMPLE_CLAUSE(UnifiedSharedMemory, OMPC_unified_shared_memory)
1818 CHECK_SIMPLE_CLAUSE(Uniform, OMPC_uniform)
1819 CHECK_SIMPLE_CLAUSE(Unknown, OMPC_unknown)
1820 CHECK_SIMPLE_CLAUSE(Untied, OMPC_untied)
1821 CHECK_SIMPLE_CLAUSE(UseDevicePtr, OMPC_use_device_ptr)
1822 CHECK_SIMPLE_CLAUSE(UsesAllocators, OMPC_uses_allocators)
1823 CHECK_SIMPLE_CLAUSE(Update, OMPC_update)
1824 CHECK_SIMPLE_CLAUSE(UseDeviceAddr, OMPC_use_device_addr)
1825 CHECK_SIMPLE_CLAUSE(Write, OMPC_write)
1826 CHECK_SIMPLE_CLAUSE(Init, OMPC_init)
1827 CHECK_SIMPLE_CLAUSE(Use, OMPC_use)
1828 CHECK_SIMPLE_CLAUSE(Novariants, OMPC_novariants)
1829 CHECK_SIMPLE_CLAUSE(Nocontext, OMPC_nocontext)
1830 CHECK_SIMPLE_CLAUSE(Filter, OMPC_filter)
1831 CHECK_SIMPLE_CLAUSE(When, OMPC_when)
1832 CHECK_SIMPLE_CLAUSE(AdjustArgs, OMPC_adjust_args)
1833 CHECK_SIMPLE_CLAUSE(AppendArgs, OMPC_append_args)
1834 CHECK_SIMPLE_CLAUSE(MemoryOrder, OMPC_memory_order)
1835 CHECK_SIMPLE_CLAUSE(Bind, OMPC_bind)
1836 CHECK_SIMPLE_CLAUSE(Align, OMPC_align)
1837 CHECK_SIMPLE_CLAUSE(Compare, OMPC_compare)
1838 CHECK_SIMPLE_CLAUSE(CancellationConstructType, OMPC_cancellation_construct_type)
1839 
1840 CHECK_REQ_SCALAR_INT_CLAUSE(Grainsize, OMPC_grainsize)
1841 CHECK_REQ_SCALAR_INT_CLAUSE(NumTasks, OMPC_num_tasks)
1842 CHECK_REQ_SCALAR_INT_CLAUSE(NumTeams, OMPC_num_teams)
1843 CHECK_REQ_SCALAR_INT_CLAUSE(NumThreads, OMPC_num_threads)
1844 CHECK_REQ_SCALAR_INT_CLAUSE(Priority, OMPC_priority)
1845 CHECK_REQ_SCALAR_INT_CLAUSE(ThreadLimit, OMPC_thread_limit)
1846 CHECK_REQ_SCALAR_INT_CLAUSE(Device, OMPC_device)
1847 
1848 CHECK_REQ_CONSTANT_SCALAR_INT_CLAUSE(Collapse, OMPC_collapse)
1849 CHECK_REQ_CONSTANT_SCALAR_INT_CLAUSE(Safelen, OMPC_safelen)
1850 CHECK_REQ_CONSTANT_SCALAR_INT_CLAUSE(Simdlen, OMPC_simdlen)
1851 
1852 // Restrictions specific to each clause are implemented apart from the
1853 // generalized restrictions.
1854 void OmpStructureChecker::Enter(const parser::OmpClause::Reduction &x) {
1855   CheckAllowed(llvm::omp::Clause::OMPC_reduction);
1856   if (CheckReductionOperators(x)) {
1857     CheckReductionTypeList(x);
1858   }
1859 }
1860 bool OmpStructureChecker::CheckReductionOperators(
1861     const parser::OmpClause::Reduction &x) {
1862 
1863   const auto &definedOp{std::get<0>(x.v.t)};
1864   bool ok = false;
1865   common::visit(
1866       common::visitors{
1867           [&](const parser::DefinedOperator &dOpr) {
1868             const auto &intrinsicOp{
1869                 std::get<parser::DefinedOperator::IntrinsicOperator>(dOpr.u)};
1870             ok = CheckIntrinsicOperator(intrinsicOp);
1871           },
1872           [&](const parser::ProcedureDesignator &procD) {
1873             const parser::Name *name{std::get_if<parser::Name>(&procD.u)};
1874             if (name) {
1875               if (name->source == "max" || name->source == "min" ||
1876                   name->source == "iand" || name->source == "ior" ||
1877                   name->source == "ieor") {
1878                 ok = true;
1879               } else {
1880                 context_.Say(GetContext().clauseSource,
1881                     "Invalid reduction identifier in REDUCTION clause."_err_en_US,
1882                     ContextDirectiveAsFortran());
1883               }
1884             }
1885           },
1886       },
1887       definedOp.u);
1888 
1889   return ok;
1890 }
1891 bool OmpStructureChecker::CheckIntrinsicOperator(
1892     const parser::DefinedOperator::IntrinsicOperator &op) {
1893 
1894   switch (op) {
1895   case parser::DefinedOperator::IntrinsicOperator::Add:
1896   case parser::DefinedOperator::IntrinsicOperator::Subtract:
1897   case parser::DefinedOperator::IntrinsicOperator::Multiply:
1898   case parser::DefinedOperator::IntrinsicOperator::AND:
1899   case parser::DefinedOperator::IntrinsicOperator::OR:
1900   case parser::DefinedOperator::IntrinsicOperator::EQV:
1901   case parser::DefinedOperator::IntrinsicOperator::NEQV:
1902     return true;
1903   default:
1904     context_.Say(GetContext().clauseSource,
1905         "Invalid reduction operator in REDUCTION clause."_err_en_US,
1906         ContextDirectiveAsFortran());
1907   }
1908   return false;
1909 }
1910 
1911 void OmpStructureChecker::CheckReductionTypeList(
1912     const parser::OmpClause::Reduction &x) {
1913   const auto &ompObjectList{std::get<parser::OmpObjectList>(x.v.t)};
1914   CheckIntentInPointerAndDefinable(
1915       ompObjectList, llvm::omp::Clause::OMPC_reduction);
1916   CheckReductionArraySection(ompObjectList);
1917   CheckMultipleAppearanceAcrossContext(ompObjectList);
1918 }
1919 
1920 void OmpStructureChecker::CheckIntentInPointerAndDefinable(
1921     const parser::OmpObjectList &objectList, const llvm::omp::Clause clause) {
1922   for (const auto &ompObject : objectList.v) {
1923     if (const auto *name{parser::Unwrap<parser::Name>(ompObject)}) {
1924       if (const auto *symbol{name->symbol}) {
1925         if (IsPointer(symbol->GetUltimate()) &&
1926             IsIntentIn(symbol->GetUltimate())) {
1927           context_.Say(GetContext().clauseSource,
1928               "Pointer '%s' with the INTENT(IN) attribute may not appear "
1929               "in a %s clause"_err_en_US,
1930               symbol->name(),
1931               parser::ToUpperCaseLetters(getClauseName(clause).str()));
1932         }
1933         if (auto msg{
1934                 WhyNotModifiable(*symbol, context_.FindScope(name->source))}) {
1935           context_
1936               .Say(GetContext().clauseSource,
1937                   "Variable '%s' on the %s clause is not definable"_err_en_US,
1938                   symbol->name(),
1939                   parser::ToUpperCaseLetters(getClauseName(clause).str()))
1940               .Attach(std::move(*msg));
1941         }
1942       }
1943     }
1944   }
1945 }
1946 
1947 void OmpStructureChecker::CheckReductionArraySection(
1948     const parser::OmpObjectList &ompObjectList) {
1949   for (const auto &ompObject : ompObjectList.v) {
1950     if (const auto *dataRef{parser::Unwrap<parser::DataRef>(ompObject)}) {
1951       if (const auto *arrayElement{
1952               parser::Unwrap<parser::ArrayElement>(ompObject)}) {
1953         if (arrayElement) {
1954           CheckArraySection(*arrayElement, GetLastName(*dataRef),
1955               llvm::omp::Clause::OMPC_reduction);
1956         }
1957       }
1958     }
1959   }
1960 }
1961 
1962 void OmpStructureChecker::CheckMultipleAppearanceAcrossContext(
1963     const parser::OmpObjectList &redObjectList) {
1964   //  TODO: Verify the assumption here that the immediately enclosing region is
1965   //  the parallel region to which the worksharing construct having reduction
1966   //  binds to.
1967   if (auto *enclosingContext{GetEnclosingDirContext()}) {
1968     for (auto it : enclosingContext->clauseInfo) {
1969       llvmOmpClause type = it.first;
1970       const auto *clause = it.second;
1971       if (llvm::omp::privateReductionSet.test(type)) {
1972         if (const auto *objList{GetOmpObjectList(*clause)}) {
1973           for (const auto &ompObject : objList->v) {
1974             if (const auto *name{parser::Unwrap<parser::Name>(ompObject)}) {
1975               if (const auto *symbol{name->symbol}) {
1976                 for (const auto &redOmpObject : redObjectList.v) {
1977                   if (const auto *rname{
1978                           parser::Unwrap<parser::Name>(redOmpObject)}) {
1979                     if (const auto *rsymbol{rname->symbol}) {
1980                       if (rsymbol->name() == symbol->name()) {
1981                         context_.Say(GetContext().clauseSource,
1982                             "%s variable '%s' is %s in outer context must"
1983                             " be shared in the parallel regions to which any"
1984                             " of the worksharing regions arising from the "
1985                             "worksharing"
1986                             " construct bind."_err_en_US,
1987                             parser::ToUpperCaseLetters(
1988                                 getClauseName(llvm::omp::Clause::OMPC_reduction)
1989                                     .str()),
1990                             symbol->name(),
1991                             parser::ToUpperCaseLetters(
1992                                 getClauseName(type).str()));
1993                       }
1994                     }
1995                   }
1996                 }
1997               }
1998             }
1999           }
2000         }
2001       }
2002     }
2003   }
2004 }
2005 
2006 void OmpStructureChecker::Enter(const parser::OmpClause::Ordered &x) {
2007   CheckAllowed(llvm::omp::Clause::OMPC_ordered);
2008   // the parameter of ordered clause is optional
2009   if (const auto &expr{x.v}) {
2010     RequiresConstantPositiveParameter(llvm::omp::Clause::OMPC_ordered, *expr);
2011     // 2.8.3 Loop SIMD Construct Restriction
2012     if (llvm::omp::doSimdSet.test(GetContext().directive)) {
2013       context_.Say(GetContext().clauseSource,
2014           "No ORDERED clause with a parameter can be specified "
2015           "on the %s directive"_err_en_US,
2016           ContextDirectiveAsFortran());
2017     }
2018   }
2019 }
2020 
2021 void OmpStructureChecker::Enter(const parser::OmpClause::Shared &x) {
2022   CheckAllowed(llvm::omp::Clause::OMPC_shared);
2023   CheckIsVarPartOfAnotherVar(GetContext().clauseSource, x.v);
2024 }
2025 void OmpStructureChecker::Enter(const parser::OmpClause::Private &x) {
2026   CheckAllowed(llvm::omp::Clause::OMPC_private);
2027   CheckIsVarPartOfAnotherVar(GetContext().clauseSource, x.v);
2028   CheckIntentInPointer(x.v, llvm::omp::Clause::OMPC_private);
2029 }
2030 
2031 bool OmpStructureChecker::IsDataRefTypeParamInquiry(
2032     const parser::DataRef *dataRef) {
2033   bool dataRefIsTypeParamInquiry{false};
2034   if (const auto *structComp{
2035           parser::Unwrap<parser::StructureComponent>(dataRef)}) {
2036     if (const auto *compSymbol{structComp->component.symbol}) {
2037       if (const auto *compSymbolMiscDetails{
2038               std::get_if<MiscDetails>(&compSymbol->details())}) {
2039         const auto detailsKind = compSymbolMiscDetails->kind();
2040         dataRefIsTypeParamInquiry =
2041             (detailsKind == MiscDetails::Kind::KindParamInquiry ||
2042                 detailsKind == MiscDetails::Kind::LenParamInquiry);
2043       } else if (compSymbol->has<TypeParamDetails>()) {
2044         dataRefIsTypeParamInquiry = true;
2045       }
2046     }
2047   }
2048   return dataRefIsTypeParamInquiry;
2049 }
2050 
2051 void OmpStructureChecker::CheckIsVarPartOfAnotherVar(
2052     const parser::CharBlock &source, const parser::OmpObjectList &objList) {
2053   OmpDirectiveSet nonPartialVarSet{llvm::omp::Directive::OMPD_allocate,
2054       llvm::omp::Directive::OMPD_threadprivate,
2055       llvm::omp::Directive::OMPD_declare_target};
2056   for (const auto &ompObject : objList.v) {
2057     common::visit(
2058         common::visitors{
2059             [&](const parser::Designator &designator) {
2060               if (const auto *dataRef{
2061                       std::get_if<parser::DataRef>(&designator.u)}) {
2062                 if (IsDataRefTypeParamInquiry(dataRef)) {
2063                   context_.Say(source,
2064                       "A type parameter inquiry cannot appear on the %s "
2065                       "directive"_err_en_US,
2066                       ContextDirectiveAsFortran());
2067                 } else if (parser::Unwrap<parser::StructureComponent>(
2068                                ompObject) ||
2069                     parser::Unwrap<parser::ArrayElement>(ompObject)) {
2070                   if (nonPartialVarSet.test(GetContext().directive)) {
2071                     context_.Say(source,
2072                         "A variable that is part of another variable (as an "
2073                         "array or structure element) cannot appear on the %s "
2074                         "directive"_err_en_US,
2075                         ContextDirectiveAsFortran());
2076                   } else {
2077                     context_.Say(source,
2078                         "A variable that is part of another variable (as an "
2079                         "array or structure element) cannot appear in a "
2080                         "PRIVATE or SHARED clause"_err_en_US);
2081                   }
2082                 }
2083               }
2084             },
2085             [&](const parser::Name &name) {},
2086         },
2087         ompObject.u);
2088   }
2089 }
2090 
2091 void OmpStructureChecker::Enter(const parser::OmpClause::Firstprivate &x) {
2092   CheckAllowed(llvm::omp::Clause::OMPC_firstprivate);
2093   CheckIsLoopIvPartOfClause(llvmOmpClause::OMPC_firstprivate, x.v);
2094 
2095   SymbolSourceMap currSymbols;
2096   GetSymbolsInObjectList(x.v, currSymbols);
2097 
2098   DirectivesClauseTriple dirClauseTriple;
2099   // Check firstprivate variables in worksharing constructs
2100   dirClauseTriple.emplace(llvm::omp::Directive::OMPD_do,
2101       std::make_pair(
2102           llvm::omp::Directive::OMPD_parallel, llvm::omp::privateReductionSet));
2103   dirClauseTriple.emplace(llvm::omp::Directive::OMPD_sections,
2104       std::make_pair(
2105           llvm::omp::Directive::OMPD_parallel, llvm::omp::privateReductionSet));
2106   dirClauseTriple.emplace(llvm::omp::Directive::OMPD_single,
2107       std::make_pair(
2108           llvm::omp::Directive::OMPD_parallel, llvm::omp::privateReductionSet));
2109   // Check firstprivate variables in distribute construct
2110   dirClauseTriple.emplace(llvm::omp::Directive::OMPD_distribute,
2111       std::make_pair(
2112           llvm::omp::Directive::OMPD_teams, llvm::omp::privateReductionSet));
2113   dirClauseTriple.emplace(llvm::omp::Directive::OMPD_distribute,
2114       std::make_pair(llvm::omp::Directive::OMPD_target_teams,
2115           llvm::omp::privateReductionSet));
2116   // Check firstprivate variables in task and taskloop constructs
2117   dirClauseTriple.emplace(llvm::omp::Directive::OMPD_task,
2118       std::make_pair(llvm::omp::Directive::OMPD_parallel,
2119           OmpClauseSet{llvm::omp::Clause::OMPC_reduction}));
2120   dirClauseTriple.emplace(llvm::omp::Directive::OMPD_taskloop,
2121       std::make_pair(llvm::omp::Directive::OMPD_parallel,
2122           OmpClauseSet{llvm::omp::Clause::OMPC_reduction}));
2123 
2124   CheckPrivateSymbolsInOuterCxt(
2125       currSymbols, dirClauseTriple, llvm::omp::Clause::OMPC_firstprivate);
2126 }
2127 
2128 void OmpStructureChecker::CheckIsLoopIvPartOfClause(
2129     llvmOmpClause clause, const parser::OmpObjectList &ompObjectList) {
2130   for (const auto &ompObject : ompObjectList.v) {
2131     if (const parser::Name * name{parser::Unwrap<parser::Name>(ompObject)}) {
2132       if (name->symbol == GetContext().loopIV) {
2133         context_.Say(name->source,
2134             "DO iteration variable %s is not allowed in %s clause."_err_en_US,
2135             name->ToString(),
2136             parser::ToUpperCaseLetters(getClauseName(clause).str()));
2137       }
2138     }
2139   }
2140 }
2141 // Following clauses have a seperate node in parse-tree.h.
2142 // Atomic-clause
2143 CHECK_SIMPLE_PARSER_CLAUSE(OmpAtomicRead, OMPC_read)
2144 CHECK_SIMPLE_PARSER_CLAUSE(OmpAtomicWrite, OMPC_write)
2145 CHECK_SIMPLE_PARSER_CLAUSE(OmpAtomicUpdate, OMPC_update)
2146 CHECK_SIMPLE_PARSER_CLAUSE(OmpAtomicCapture, OMPC_capture)
2147 
2148 void OmpStructureChecker::Leave(const parser::OmpAtomicRead &) {
2149   CheckNotAllowedIfClause(llvm::omp::Clause::OMPC_read,
2150       {llvm::omp::Clause::OMPC_release, llvm::omp::Clause::OMPC_acq_rel});
2151 }
2152 void OmpStructureChecker::Leave(const parser::OmpAtomicWrite &) {
2153   CheckNotAllowedIfClause(llvm::omp::Clause::OMPC_write,
2154       {llvm::omp::Clause::OMPC_acquire, llvm::omp::Clause::OMPC_acq_rel});
2155 }
2156 void OmpStructureChecker::Leave(const parser::OmpAtomicUpdate &) {
2157   CheckNotAllowedIfClause(llvm::omp::Clause::OMPC_update,
2158       {llvm::omp::Clause::OMPC_acquire, llvm::omp::Clause::OMPC_acq_rel});
2159 }
2160 // OmpAtomic node represents atomic directive without atomic-clause.
2161 // atomic-clause - READ,WRITE,UPDATE,CAPTURE.
2162 void OmpStructureChecker::Leave(const parser::OmpAtomic &) {
2163   if (const auto *clause{FindClause(llvm::omp::Clause::OMPC_acquire)}) {
2164     context_.Say(clause->source,
2165         "Clause ACQUIRE is not allowed on the ATOMIC directive"_err_en_US);
2166   }
2167   if (const auto *clause{FindClause(llvm::omp::Clause::OMPC_acq_rel)}) {
2168     context_.Say(clause->source,
2169         "Clause ACQ_REL is not allowed on the ATOMIC directive"_err_en_US);
2170   }
2171 }
2172 // Restrictions specific to each clause are implemented apart from the
2173 // generalized restrictions.
2174 void OmpStructureChecker::Enter(const parser::OmpClause::Aligned &x) {
2175   CheckAllowed(llvm::omp::Clause::OMPC_aligned);
2176 
2177   if (const auto &expr{
2178           std::get<std::optional<parser::ScalarIntConstantExpr>>(x.v.t)}) {
2179     RequiresConstantPositiveParameter(llvm::omp::Clause::OMPC_aligned, *expr);
2180   }
2181   // 2.8.1 TODO: list-item attribute check
2182 }
2183 void OmpStructureChecker::Enter(const parser::OmpClause::Defaultmap &x) {
2184   CheckAllowed(llvm::omp::Clause::OMPC_defaultmap);
2185   using VariableCategory = parser::OmpDefaultmapClause::VariableCategory;
2186   if (!std::get<std::optional<VariableCategory>>(x.v.t)) {
2187     context_.Say(GetContext().clauseSource,
2188         "The argument TOFROM:SCALAR must be specified on the DEFAULTMAP "
2189         "clause"_err_en_US);
2190   }
2191 }
2192 void OmpStructureChecker::Enter(const parser::OmpClause::If &x) {
2193   CheckAllowed(llvm::omp::Clause::OMPC_if);
2194   using dirNameModifier = parser::OmpIfClause::DirectiveNameModifier;
2195   static std::unordered_map<dirNameModifier, OmpDirectiveSet>
2196       dirNameModifierMap{{dirNameModifier::Parallel, llvm::omp::parallelSet},
2197           {dirNameModifier::Target, llvm::omp::targetSet},
2198           {dirNameModifier::TargetEnterData,
2199               {llvm::omp::Directive::OMPD_target_enter_data}},
2200           {dirNameModifier::TargetExitData,
2201               {llvm::omp::Directive::OMPD_target_exit_data}},
2202           {dirNameModifier::TargetData,
2203               {llvm::omp::Directive::OMPD_target_data}},
2204           {dirNameModifier::TargetUpdate,
2205               {llvm::omp::Directive::OMPD_target_update}},
2206           {dirNameModifier::Task, {llvm::omp::Directive::OMPD_task}},
2207           {dirNameModifier::Taskloop, llvm::omp::taskloopSet}};
2208   if (const auto &directiveName{
2209           std::get<std::optional<dirNameModifier>>(x.v.t)}) {
2210     auto search{dirNameModifierMap.find(*directiveName)};
2211     if (search == dirNameModifierMap.end() ||
2212         !search->second.test(GetContext().directive)) {
2213       context_
2214           .Say(GetContext().clauseSource,
2215               "Unmatched directive name modifier %s on the IF clause"_err_en_US,
2216               parser::ToUpperCaseLetters(
2217                   parser::OmpIfClause::EnumToString(*directiveName)))
2218           .Attach(
2219               GetContext().directiveSource, "Cannot apply to directive"_en_US);
2220     }
2221   }
2222 }
2223 
2224 void OmpStructureChecker::Enter(const parser::OmpClause::Linear &x) {
2225   CheckAllowed(llvm::omp::Clause::OMPC_linear);
2226 
2227   // 2.7 Loop Construct Restriction
2228   if ((llvm::omp::doSet | llvm::omp::simdSet).test(GetContext().directive)) {
2229     if (std::holds_alternative<parser::OmpLinearClause::WithModifier>(x.v.u)) {
2230       context_.Say(GetContext().clauseSource,
2231           "A modifier may not be specified in a LINEAR clause "
2232           "on the %s directive"_err_en_US,
2233           ContextDirectiveAsFortran());
2234     }
2235   }
2236 }
2237 
2238 void OmpStructureChecker::CheckAllowedMapTypes(
2239     const parser::OmpMapType::Type &type,
2240     const std::list<parser::OmpMapType::Type> &allowedMapTypeList) {
2241   const auto found{std::find(
2242       std::begin(allowedMapTypeList), std::end(allowedMapTypeList), type)};
2243   if (found == std::end(allowedMapTypeList)) {
2244     std::string commaSeperatedMapTypes;
2245     llvm::interleave(
2246         allowedMapTypeList.begin(), allowedMapTypeList.end(),
2247         [&](const parser::OmpMapType::Type &mapType) {
2248           commaSeperatedMapTypes.append(parser::ToUpperCaseLetters(
2249               parser::OmpMapType::EnumToString(mapType)));
2250         },
2251         [&] { commaSeperatedMapTypes.append(", "); });
2252     context_.Say(GetContext().clauseSource,
2253         "Only the %s map types are permitted "
2254         "for MAP clauses on the %s directive"_err_en_US,
2255         commaSeperatedMapTypes, ContextDirectiveAsFortran());
2256   }
2257 }
2258 
2259 void OmpStructureChecker::Enter(const parser::OmpClause::Map &x) {
2260   CheckAllowed(llvm::omp::Clause::OMPC_map);
2261 
2262   if (const auto &maptype{std::get<std::optional<parser::OmpMapType>>(x.v.t)}) {
2263     using Type = parser::OmpMapType::Type;
2264     const Type &type{std::get<Type>(maptype->t)};
2265     switch (GetContext().directive) {
2266     case llvm::omp::Directive::OMPD_target:
2267     case llvm::omp::Directive::OMPD_target_teams:
2268     case llvm::omp::Directive::OMPD_target_teams_distribute:
2269     case llvm::omp::Directive::OMPD_target_teams_distribute_simd:
2270     case llvm::omp::Directive::OMPD_target_teams_distribute_parallel_do:
2271     case llvm::omp::Directive::OMPD_target_teams_distribute_parallel_do_simd:
2272     case llvm::omp::Directive::OMPD_target_data:
2273       CheckAllowedMapTypes(
2274           type, {Type::To, Type::From, Type::Tofrom, Type::Alloc});
2275       break;
2276     case llvm::omp::Directive::OMPD_target_enter_data:
2277       CheckAllowedMapTypes(type, {Type::To, Type::Alloc});
2278       break;
2279     case llvm::omp::Directive::OMPD_target_exit_data:
2280       CheckAllowedMapTypes(type, {Type::From, Type::Release, Type::Delete});
2281       break;
2282     default:
2283       break;
2284     }
2285   }
2286 }
2287 
2288 bool OmpStructureChecker::ScheduleModifierHasType(
2289     const parser::OmpScheduleClause &x,
2290     const parser::OmpScheduleModifierType::ModType &type) {
2291   const auto &modifier{
2292       std::get<std::optional<parser::OmpScheduleModifier>>(x.t)};
2293   if (modifier) {
2294     const auto &modType1{
2295         std::get<parser::OmpScheduleModifier::Modifier1>(modifier->t)};
2296     const auto &modType2{
2297         std::get<std::optional<parser::OmpScheduleModifier::Modifier2>>(
2298             modifier->t)};
2299     if (modType1.v.v == type || (modType2 && modType2->v.v == type)) {
2300       return true;
2301     }
2302   }
2303   return false;
2304 }
2305 void OmpStructureChecker::Enter(const parser::OmpClause::Schedule &x) {
2306   CheckAllowed(llvm::omp::Clause::OMPC_schedule);
2307   const parser::OmpScheduleClause &scheduleClause = x.v;
2308 
2309   // 2.7 Loop Construct Restriction
2310   if (llvm::omp::doSet.test(GetContext().directive)) {
2311     const auto &kind{std::get<1>(scheduleClause.t)};
2312     const auto &chunk{std::get<2>(scheduleClause.t)};
2313     if (chunk) {
2314       if (kind == parser::OmpScheduleClause::ScheduleType::Runtime ||
2315           kind == parser::OmpScheduleClause::ScheduleType::Auto) {
2316         context_.Say(GetContext().clauseSource,
2317             "When SCHEDULE clause has %s specified, "
2318             "it must not have chunk size specified"_err_en_US,
2319             parser::ToUpperCaseLetters(
2320                 parser::OmpScheduleClause::EnumToString(kind)));
2321       }
2322       if (const auto &chunkExpr{std::get<std::optional<parser::ScalarIntExpr>>(
2323               scheduleClause.t)}) {
2324         RequiresPositiveParameter(
2325             llvm::omp::Clause::OMPC_schedule, *chunkExpr, "chunk size");
2326       }
2327     }
2328 
2329     if (ScheduleModifierHasType(scheduleClause,
2330             parser::OmpScheduleModifierType::ModType::Nonmonotonic)) {
2331       if (kind != parser::OmpScheduleClause::ScheduleType::Dynamic &&
2332           kind != parser::OmpScheduleClause::ScheduleType::Guided) {
2333         context_.Say(GetContext().clauseSource,
2334             "The NONMONOTONIC modifier can only be specified with "
2335             "SCHEDULE(DYNAMIC) or SCHEDULE(GUIDED)"_err_en_US);
2336       }
2337     }
2338   }
2339 }
2340 
2341 void OmpStructureChecker::Enter(const parser::OmpClause::Depend &x) {
2342   CheckAllowed(llvm::omp::Clause::OMPC_depend);
2343   if (const auto *inOut{std::get_if<parser::OmpDependClause::InOut>(&x.v.u)}) {
2344     const auto &designators{std::get<std::list<parser::Designator>>(inOut->t)};
2345     for (const auto &ele : designators) {
2346       if (const auto *dataRef{std::get_if<parser::DataRef>(&ele.u)}) {
2347         CheckDependList(*dataRef);
2348         if (const auto *arr{
2349                 std::get_if<common::Indirection<parser::ArrayElement>>(
2350                     &dataRef->u)}) {
2351           CheckArraySection(arr->value(), GetLastName(*dataRef),
2352               llvm::omp::Clause::OMPC_depend);
2353         }
2354       }
2355     }
2356   }
2357 }
2358 
2359 void OmpStructureChecker::Enter(const parser::OmpClause::Copyprivate &x) {
2360   CheckAllowed(llvm::omp::Clause::OMPC_copyprivate);
2361   CheckIntentInPointer(x.v, llvm::omp::Clause::OMPC_copyprivate);
2362 }
2363 
2364 void OmpStructureChecker::Enter(const parser::OmpClause::Lastprivate &x) {
2365   CheckAllowed(llvm::omp::Clause::OMPC_lastprivate);
2366 
2367   DirectivesClauseTriple dirClauseTriple;
2368   SymbolSourceMap currSymbols;
2369   GetSymbolsInObjectList(x.v, currSymbols);
2370   CheckDefinableObjects(currSymbols, GetClauseKindForParserClass(x));
2371 
2372   // Check lastprivate variables in worksharing constructs
2373   dirClauseTriple.emplace(llvm::omp::Directive::OMPD_do,
2374       std::make_pair(
2375           llvm::omp::Directive::OMPD_parallel, llvm::omp::privateReductionSet));
2376   dirClauseTriple.emplace(llvm::omp::Directive::OMPD_sections,
2377       std::make_pair(
2378           llvm::omp::Directive::OMPD_parallel, llvm::omp::privateReductionSet));
2379 
2380   CheckPrivateSymbolsInOuterCxt(
2381       currSymbols, dirClauseTriple, GetClauseKindForParserClass(x));
2382 }
2383 
2384 llvm::StringRef OmpStructureChecker::getClauseName(llvm::omp::Clause clause) {
2385   return llvm::omp::getOpenMPClauseName(clause);
2386 }
2387 
2388 llvm::StringRef OmpStructureChecker::getDirectiveName(
2389     llvm::omp::Directive directive) {
2390   return llvm::omp::getOpenMPDirectiveName(directive);
2391 }
2392 
2393 void OmpStructureChecker::CheckDependList(const parser::DataRef &d) {
2394   common::visit(
2395       common::visitors{
2396           [&](const common::Indirection<parser::ArrayElement> &elem) {
2397             // Check if the base element is valid on Depend Clause
2398             CheckDependList(elem.value().base);
2399           },
2400           [&](const common::Indirection<parser::StructureComponent> &) {
2401             context_.Say(GetContext().clauseSource,
2402                 "A variable that is part of another variable "
2403                 "(such as an element of a structure) but is not an array "
2404                 "element or an array section cannot appear in a DEPEND "
2405                 "clause"_err_en_US);
2406           },
2407           [&](const common::Indirection<parser::CoindexedNamedObject> &) {
2408             context_.Say(GetContext().clauseSource,
2409                 "Coarrays are not supported in DEPEND clause"_err_en_US);
2410           },
2411           [&](const parser::Name &) { return; },
2412       },
2413       d.u);
2414 }
2415 
2416 // Called from both Reduction and Depend clause.
2417 void OmpStructureChecker::CheckArraySection(
2418     const parser::ArrayElement &arrayElement, const parser::Name &name,
2419     const llvm::omp::Clause clause) {
2420   if (!arrayElement.subscripts.empty()) {
2421     for (const auto &subscript : arrayElement.subscripts) {
2422       if (const auto *triplet{
2423               std::get_if<parser::SubscriptTriplet>(&subscript.u)}) {
2424         if (std::get<0>(triplet->t) && std::get<1>(triplet->t)) {
2425           const auto &lower{std::get<0>(triplet->t)};
2426           const auto &upper{std::get<1>(triplet->t)};
2427           if (lower && upper) {
2428             const auto lval{GetIntValue(lower)};
2429             const auto uval{GetIntValue(upper)};
2430             if (lval && uval && *uval < *lval) {
2431               context_.Say(GetContext().clauseSource,
2432                   "'%s' in %s clause"
2433                   " is a zero size array section"_err_en_US,
2434                   name.ToString(),
2435                   parser::ToUpperCaseLetters(getClauseName(clause).str()));
2436               break;
2437             } else if (std::get<2>(triplet->t)) {
2438               const auto &strideExpr{std::get<2>(triplet->t)};
2439               if (strideExpr) {
2440                 if (clause == llvm::omp::Clause::OMPC_depend) {
2441                   context_.Say(GetContext().clauseSource,
2442                       "Stride should not be specified for array section in "
2443                       "DEPEND "
2444                       "clause"_err_en_US);
2445                 }
2446                 const auto stride{GetIntValue(strideExpr)};
2447                 if ((stride && stride != 1)) {
2448                   context_.Say(GetContext().clauseSource,
2449                       "A list item that appears in a REDUCTION clause"
2450                       " should have a contiguous storage array section."_err_en_US,
2451                       ContextDirectiveAsFortran());
2452                   break;
2453                 }
2454               }
2455             }
2456           }
2457         }
2458       }
2459     }
2460   }
2461 }
2462 
2463 void OmpStructureChecker::CheckIntentInPointer(
2464     const parser::OmpObjectList &objectList, const llvm::omp::Clause clause) {
2465   SymbolSourceMap symbols;
2466   GetSymbolsInObjectList(objectList, symbols);
2467   for (auto it{symbols.begin()}; it != symbols.end(); ++it) {
2468     const auto *symbol{it->first};
2469     const auto source{it->second};
2470     if (IsPointer(*symbol) && IsIntentIn(*symbol)) {
2471       context_.Say(source,
2472           "Pointer '%s' with the INTENT(IN) attribute may not appear "
2473           "in a %s clause"_err_en_US,
2474           symbol->name(),
2475           parser::ToUpperCaseLetters(getClauseName(clause).str()));
2476     }
2477   }
2478 }
2479 
2480 void OmpStructureChecker::GetSymbolsInObjectList(
2481     const parser::OmpObjectList &objectList, SymbolSourceMap &symbols) {
2482   for (const auto &ompObject : objectList.v) {
2483     if (const auto *name{parser::Unwrap<parser::Name>(ompObject)}) {
2484       if (const auto *symbol{name->symbol}) {
2485         if (const auto *commonBlockDetails{
2486                 symbol->detailsIf<CommonBlockDetails>()}) {
2487           for (const auto &object : commonBlockDetails->objects()) {
2488             symbols.emplace(&object->GetUltimate(), name->source);
2489           }
2490         } else {
2491           symbols.emplace(&symbol->GetUltimate(), name->source);
2492         }
2493       }
2494     }
2495   }
2496 }
2497 
2498 void OmpStructureChecker::CheckDefinableObjects(
2499     SymbolSourceMap &symbols, const llvm::omp::Clause clause) {
2500   for (auto it{symbols.begin()}; it != symbols.end(); ++it) {
2501     const auto *symbol{it->first};
2502     const auto source{it->second};
2503     if (auto msg{WhyNotModifiable(*symbol, context_.FindScope(source))}) {
2504       context_
2505           .Say(source,
2506               "Variable '%s' on the %s clause is not definable"_err_en_US,
2507               symbol->name(),
2508               parser::ToUpperCaseLetters(getClauseName(clause).str()))
2509           .Attach(std::move(*msg));
2510     }
2511   }
2512 }
2513 
2514 void OmpStructureChecker::CheckPrivateSymbolsInOuterCxt(
2515     SymbolSourceMap &currSymbols, DirectivesClauseTriple &dirClauseTriple,
2516     const llvm::omp::Clause currClause) {
2517   SymbolSourceMap enclosingSymbols;
2518   auto range{dirClauseTriple.equal_range(GetContext().directive)};
2519   for (auto dirIter{range.first}; dirIter != range.second; ++dirIter) {
2520     auto enclosingDir{dirIter->second.first};
2521     auto enclosingClauseSet{dirIter->second.second};
2522     if (auto *enclosingContext{GetEnclosingContextWithDir(enclosingDir)}) {
2523       for (auto it{enclosingContext->clauseInfo.begin()};
2524            it != enclosingContext->clauseInfo.end(); ++it) {
2525         if (enclosingClauseSet.test(it->first)) {
2526           if (const auto *ompObjectList{GetOmpObjectList(*it->second)}) {
2527             GetSymbolsInObjectList(*ompObjectList, enclosingSymbols);
2528           }
2529         }
2530       }
2531 
2532       // Check if the symbols in current context are private in outer context
2533       for (auto iter{currSymbols.begin()}; iter != currSymbols.end(); ++iter) {
2534         const auto *symbol{iter->first};
2535         const auto source{iter->second};
2536         if (enclosingSymbols.find(symbol) != enclosingSymbols.end()) {
2537           context_.Say(source,
2538               "%s variable '%s' is PRIVATE in outer context"_err_en_US,
2539               parser::ToUpperCaseLetters(getClauseName(currClause).str()),
2540               symbol->name());
2541         }
2542       }
2543     }
2544   }
2545 }
2546 
2547 bool OmpStructureChecker::CheckTargetBlockOnlyTeams(
2548     const parser::Block &block) {
2549   bool nestedTeams{false};
2550   auto it{block.begin()};
2551 
2552   if (const auto *ompConstruct{parser::Unwrap<parser::OpenMPConstruct>(*it)}) {
2553     if (const auto *ompBlockConstruct{
2554             std::get_if<parser::OpenMPBlockConstruct>(&ompConstruct->u)}) {
2555       const auto &beginBlockDir{
2556           std::get<parser::OmpBeginBlockDirective>(ompBlockConstruct->t)};
2557       const auto &beginDir{
2558           std::get<parser::OmpBlockDirective>(beginBlockDir.t)};
2559       if (beginDir.v == llvm::omp::Directive::OMPD_teams) {
2560         nestedTeams = true;
2561       }
2562     }
2563   }
2564 
2565   if (nestedTeams && ++it == block.end()) {
2566     return true;
2567   }
2568   return false;
2569 }
2570 
2571 void OmpStructureChecker::CheckWorkshareBlockStmts(
2572     const parser::Block &block, parser::CharBlock source) {
2573   OmpWorkshareBlockChecker ompWorkshareBlockChecker{context_, source};
2574 
2575   for (auto it{block.begin()}; it != block.end(); ++it) {
2576     if (parser::Unwrap<parser::AssignmentStmt>(*it) ||
2577         parser::Unwrap<parser::ForallStmt>(*it) ||
2578         parser::Unwrap<parser::ForallConstruct>(*it) ||
2579         parser::Unwrap<parser::WhereStmt>(*it) ||
2580         parser::Unwrap<parser::WhereConstruct>(*it)) {
2581       parser::Walk(*it, ompWorkshareBlockChecker);
2582     } else if (const auto *ompConstruct{
2583                    parser::Unwrap<parser::OpenMPConstruct>(*it)}) {
2584       if (const auto *ompAtomicConstruct{
2585               std::get_if<parser::OpenMPAtomicConstruct>(&ompConstruct->u)}) {
2586         // Check if assignment statements in the enclosing OpenMP Atomic
2587         // construct are allowed in the Workshare construct
2588         parser::Walk(*ompAtomicConstruct, ompWorkshareBlockChecker);
2589       } else if (const auto *ompCriticalConstruct{
2590                      std::get_if<parser::OpenMPCriticalConstruct>(
2591                          &ompConstruct->u)}) {
2592         // All the restrictions on the Workshare construct apply to the
2593         // statements in the enclosing critical constructs
2594         const auto &criticalBlock{
2595             std::get<parser::Block>(ompCriticalConstruct->t)};
2596         CheckWorkshareBlockStmts(criticalBlock, source);
2597       } else {
2598         // Check if OpenMP constructs enclosed in the Workshare construct are
2599         // 'Parallel' constructs
2600         auto currentDir{llvm::omp::Directive::OMPD_unknown};
2601         const OmpDirectiveSet parallelDirSet{
2602             llvm::omp::Directive::OMPD_parallel,
2603             llvm::omp::Directive::OMPD_parallel_do,
2604             llvm::omp::Directive::OMPD_parallel_sections,
2605             llvm::omp::Directive::OMPD_parallel_workshare,
2606             llvm::omp::Directive::OMPD_parallel_do_simd};
2607 
2608         if (const auto *ompBlockConstruct{
2609                 std::get_if<parser::OpenMPBlockConstruct>(&ompConstruct->u)}) {
2610           const auto &beginBlockDir{
2611               std::get<parser::OmpBeginBlockDirective>(ompBlockConstruct->t)};
2612           const auto &beginDir{
2613               std::get<parser::OmpBlockDirective>(beginBlockDir.t)};
2614           currentDir = beginDir.v;
2615         } else if (const auto *ompLoopConstruct{
2616                        std::get_if<parser::OpenMPLoopConstruct>(
2617                            &ompConstruct->u)}) {
2618           const auto &beginLoopDir{
2619               std::get<parser::OmpBeginLoopDirective>(ompLoopConstruct->t)};
2620           const auto &beginDir{
2621               std::get<parser::OmpLoopDirective>(beginLoopDir.t)};
2622           currentDir = beginDir.v;
2623         } else if (const auto *ompSectionsConstruct{
2624                        std::get_if<parser::OpenMPSectionsConstruct>(
2625                            &ompConstruct->u)}) {
2626           const auto &beginSectionsDir{
2627               std::get<parser::OmpBeginSectionsDirective>(
2628                   ompSectionsConstruct->t)};
2629           const auto &beginDir{
2630               std::get<parser::OmpSectionsDirective>(beginSectionsDir.t)};
2631           currentDir = beginDir.v;
2632         }
2633 
2634         if (!parallelDirSet.test(currentDir)) {
2635           context_.Say(source,
2636               "OpenMP constructs enclosed in WORKSHARE construct may consist "
2637               "of ATOMIC, CRITICAL or PARALLEL constructs only"_err_en_US);
2638         }
2639       }
2640     } else {
2641       context_.Say(source,
2642           "The structured block in a WORKSHARE construct may consist of only "
2643           "SCALAR or ARRAY assignments, FORALL or WHERE statements, "
2644           "FORALL, WHERE, ATOMIC, CRITICAL or PARALLEL constructs"_err_en_US);
2645     }
2646   }
2647 }
2648 
2649 const parser::OmpObjectList *OmpStructureChecker::GetOmpObjectList(
2650     const parser::OmpClause &clause) {
2651 
2652   // Clauses with OmpObjectList as its data member
2653   using MemberObjectListClauses = std::tuple<parser::OmpClause::Copyprivate,
2654       parser::OmpClause::Copyin, parser::OmpClause::Firstprivate,
2655       parser::OmpClause::From, parser::OmpClause::Lastprivate,
2656       parser::OmpClause::Link, parser::OmpClause::Private,
2657       parser::OmpClause::Shared, parser::OmpClause::To>;
2658 
2659   // Clauses with OmpObjectList in the tuple
2660   using TupleObjectListClauses = std::tuple<parser::OmpClause::Allocate,
2661       parser::OmpClause::Map, parser::OmpClause::Reduction>;
2662 
2663   // TODO:: Generate the tuples using TableGen.
2664   // Handle other constructs with OmpObjectList such as OpenMPThreadprivate.
2665   return common::visit(
2666       common::visitors{
2667           [&](const auto &x) -> const parser::OmpObjectList * {
2668             using Ty = std::decay_t<decltype(x)>;
2669             if constexpr (common::HasMember<Ty, MemberObjectListClauses>) {
2670               return &x.v;
2671             } else if constexpr (common::HasMember<Ty,
2672                                      TupleObjectListClauses>) {
2673               return &(std::get<parser::OmpObjectList>(x.v.t));
2674             } else {
2675               return nullptr;
2676             }
2677           },
2678       },
2679       clause.u);
2680 }
2681 
2682 } // namespace Fortran::semantics
2683