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