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