FLANG
openmp-utils.h
1//===-- flang/Parser/openmp-utils.h ---------------------------------------===//
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// Common OpenMP utilities.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef FORTRAN_PARSER_OPENMP_UTILS_H
14#define FORTRAN_PARSER_OPENMP_UTILS_H
15
16#include "flang/Common/indirection.h"
17#include "flang/Parser/char-block.h"
18#include "flang/Parser/parse-tree.h"
19#include "llvm/ADT/iterator_range.h"
20#include "llvm/Frontend/OpenMP/OMP.h"
21#include "llvm/Frontend/OpenMP/OMPDescriptors.h"
22
23#include <cassert>
24#include <iterator>
25#include <limits>
26#include <tuple>
27#include <type_traits>
28#include <utility>
29#include <variant>
30#include <vector>
31
32namespace Fortran::parser::omp {
33
34template <typename T> constexpr auto addr_if(std::optional<T> &x) {
35 return x ? &*x : nullptr;
36}
37template <typename T> constexpr auto addr_if(const std::optional<T> &x) {
38 return x ? &*x : nullptr;
39}
40
41namespace descriptor {
42// Generic interfaces for entities that are "containers":
43// * Clause:
44// ├─ Elements: Modifiers
45// ╰─ Sets: ModifierSets
46// * Directive
47// ├─ Elements: Clauses
48// ╰─ Sets: ClauseSets
49// * ClauseSet:
50// ╰─ Elements: Clauses
51// * ModifierSet:
52// ╰─ Elements: Modifiers
53llvm::omp::Modifiers GetElements(
54 const llvm::omp::descriptor::Clause &desc, llvm::omp::Version version);
55llvm::omp::ModifierSets GetSets(
56 const llvm::omp::descriptor::Clause &desc, llvm::omp::Version version);
57llvm::omp::Clauses GetElements(
58 const llvm::omp::descriptor::Directive &desc, llvm::omp::Version version);
59llvm::omp::ClauseSets GetSets(
60 const llvm::omp::descriptor::Directive &desc, llvm::omp::Version version);
61llvm::omp::Clauses GetElements(
62 const llvm::omp::descriptor::ClauseSet &desc, llvm::omp::Version version);
63llvm::omp::Modifiers GetElements(
64 const llvm::omp::descriptor::ModifierSet &desc, llvm::omp::Version version);
65
66// The set of "elements" allowed on a given "container" is the union of all
67// elements listed explicitly, and elements of all sets. E.g. the set of all
68// clauses allowed on a given directive is the set of clauses listed in the
69// descriptor, plus the union of all clause sets.
70template <typename DescriptorTy>
71auto GetAllowedElements(const DescriptorTy &desc, llvm::omp::Version version) {
72 auto allowed{GetElements(desc, version)};
73 for (auto s : GetSets(desc, version)) {
74 allowed |= GetElements(llvm::omp::getDescriptor(s), version);
75 }
76 return allowed;
77}
78
79template <typename ElemTy, typename OwnerTy>
80llvm::directive::VersionRange GetVersionRangeForElement(
81 ElemTy elemId, OwnerTy ownerId) {
82 llvm::omp::Version minVer{std::numeric_limits<int>::max()};
83 llvm::omp::Version maxVer{0u};
84 const auto &desc{llvm::omp::getDescriptor(ownerId)};
85 for (llvm::omp::Version v : desc.getVersions()) {
86 if (GetAllowedElements(desc, v).test(elemId)) {
87 minVer = std::min(minVer, v);
88 maxVer = std::max(maxVer, v);
89 }
90 }
91 return llvm::directive::VersionRange{
92 static_cast<int>(static_cast<unsigned>(minVer)),
93 static_cast<int>(static_cast<unsigned>(maxVer))};
94}
95} // namespace descriptor
96
97const parser::Designator *GetDesignatorFromObj(const parser::OmpObject &object);
98const parser::DataRef *GetDataRefFromObj(const parser::OmpObject &object);
99const parser::OmpLocator *GetLocatorFromObj(const parser::OmpObject &object);
100const parser::Name *GetCommonBlockFromObj(const parser::OmpObject &object);
101
102const parser::ArrayElement *GetArrayElementFromObj(
103 const parser::OmpObject &object);
104std::optional<parser::CharBlock> GetObjectSource(
105 const parser::OmpObject &object);
106const parser::OmpObject *GetArgumentObject(const parser::OmpArgument &argument);
107
108const OmpDirectiveSpecification &GetOmpDirectiveSpecification(
109 const OpenMPConstruct &x);
110const OmpDirectiveSpecification &GetOmpDirectiveSpecification(
111 const OpenMPDeclarativeConstruct &x);
112
113template <typename T> struct WithSource {
114 template < //
115 typename U = std::remove_reference_t<T>,
116 typename = std::enable_if_t<std::is_default_constructible_v<U>>>
117 WithSource() : value(), source() {}
118 WithSource(const WithSource<T> &) = default;
119 WithSource(WithSource<T> &&) = default;
120 WithSource(const T &t, parser::CharBlock s) : value(t), source(s) {}
121 WithSource(T &&t, parser::CharBlock s) : value(std::move(t)), source(s) {}
122 WithSource &operator=(const WithSource<T> &) = default;
123 WithSource &operator=(WithSource<T> &&) = default;
124
125 using value_type = T;
126 T value;
127 parser::CharBlock source;
128};
129
130namespace detail {
132 static OmpDirectiveName MakeName(CharBlock source = {},
133 llvm::omp::Directive id = llvm::omp::Directive::OMPD_unknown) {
134 OmpDirectiveName name;
135 name.source = source;
136 name.v = id;
137 return name;
138 }
139
140 static OmpDirectiveName GetOmpDirectiveName(const OmpDirectiveName &x) {
141 return x;
142 }
143
144 static OmpDirectiveName GetOmpDirectiveName(const OmpSectionDirective &x) {
145 if (auto &spec{std::get<std::optional<OmpDirectiveSpecification>>(x.t)}) {
146 return spec->DirName();
147 } else {
148 return MakeName({}, llvm::omp::Directive::OMPD_section);
149 }
150 }
151
152 static OmpDirectiveName GetOmpDirectiveName(
153 const OmpBeginSectionsDirective &x) {
154 return x.DirName();
155 }
156
157 template <typename T>
158 static OmpDirectiveName GetOmpDirectiveName(const T &x) {
159 if constexpr (WrapperTrait<T>) {
160 return GetOmpDirectiveName(x.v);
161 } else if constexpr (TupleTrait<T>) {
162 if constexpr (std::is_base_of_v<OmpBlockConstruct, T>) {
163 return std::get<OmpBeginDirective>(x.t).DirName();
164 } else {
165 return GetFromTuple(
166 x.t, std::make_index_sequence<std::tuple_size_v<decltype(x.t)>>{});
167 }
168 } else if constexpr (UnionTrait<T>) {
169 return common::visit(
170 [](auto &&s) { return GetOmpDirectiveName(s); }, x.u);
171 } else {
172 return MakeName();
173 }
174 }
175
176 template <typename... Ts, size_t... Is>
177 static OmpDirectiveName GetFromTuple(
178 const std::tuple<Ts...> &t, std::index_sequence<Is...>) {
179 OmpDirectiveName name = MakeName();
180 auto accumulate = [&](const OmpDirectiveName &n) {
181 if (name.v == llvm::omp::Directive::OMPD_unknown) {
182 name = n;
183 } else {
184 assert(
185 n.v == llvm::omp::Directive::OMPD_unknown && "Conflicting names");
186 }
187 };
188 (accumulate(GetOmpDirectiveName(std::get<Is>(t))), ...);
189 return name;
190 }
191
192 template <typename T>
193 static OmpDirectiveName GetOmpDirectiveName(const common::Indirection<T> &x) {
194 return GetOmpDirectiveName(x.value());
195 }
196};
197} // namespace detail
198
199template <typename T> OmpDirectiveName GetOmpDirectiveName(const T &x) {
200 return detail::DirectiveNameScope::GetOmpDirectiveName(x);
201}
202
203std::string GetUpperName(
204 llvm::omp::Clause id, llvm::omp::Version version, bool annotate = true);
205std::string GetUpperName(
206 llvm::omp::Directive id, llvm::omp::Version version, bool annotate = true);
207
209const OpenMPConstruct *GetOmp(const ExecutionPartConstruct &x);
210
211const OpenMPLoopConstruct *GetOmpLoop(const ExecutionPartConstruct &x);
212const DoConstruct *GetDoConstruct(const ExecutionPartConstruct &x);
213
214namespace detail {
216 template <typename T> static const OmpObjectList *Get(const T &x) {
217 if constexpr (std::is_same_v<OmpObjectList, T>) {
218 return &x;
219 } else if constexpr (WrapperTrait<T>) {
220 return Get(x.v);
221 } else if constexpr (UnionTrait<T>) {
222 return std::visit([](auto &&s) { return Get(s); }, x.u);
223 } else if constexpr (TupleTrait<T>) {
224 return GetFromTuple(
225 x.t, std::make_index_sequence<std::tuple_size_v<decltype(x.t)>>{});
226 } else if constexpr (ConstraintTrait<T>) {
227 return Get(x.thing);
228 } else {
229 return nullptr;
230 }
231 }
232
233 template <typename T>
234 static const OmpObjectList *Get(const common::Indirection<T> &x) {
235 return Get(x.value());
236 }
237
238 template <typename... Ts, size_t... Is>
239 static const OmpObjectList *GetFromTuple(
240 const std::tuple<Ts...> &t, std::index_sequence<Is...>) {
241 const OmpObjectList *objects{nullptr};
242 ((objects = objects ? objects : Get(std::get<Is>(t))), ...);
243 return objects;
244 }
245};
246} // namespace detail
247
248template <typename T> const OmpObjectList *GetOmpObjectList(const T &clause) {
249 static_assert(std::is_class_v<T>, "Unexpected argument type");
250 return detail::OmpObjectListScope::Get(clause);
251}
252
253template <typename T>
254const T *GetFirstArgument(const OmpDirectiveSpecification &spec) {
255 for (const OmpArgument &arg : spec.Arguments().v) {
256 if (auto *t{std::get_if<T>(&arg.u)}) {
257 return t;
258 }
259 }
260 return nullptr;
261}
262
263const OmpClause *FindClause(
264 const OmpDirectiveSpecification &spec, llvm::omp::Clause clauseId);
265
266const BlockConstruct *GetFortranBlockConstruct(
267 const ExecutionPartConstruct &epc);
268const Block &GetInnermostExecPart(const Block &block);
269bool IsStrictlyStructuredBlock(const Block &block);
270
271const OmpCombinerExpression *GetCombinerExpr(const OmpReductionSpecifier &x);
272const OmpCombinerExpression *GetCombinerExpr(const OmpClause &x);
273const OmpInitializerExpression *GetInitializerExpr(const OmpClause &x);
274
276 std::vector<const OmpAllocateDirective *> dirs;
277 const ExecutionPartConstruct *body{nullptr};
278};
279
280OmpAllocateInfo SplitOmpAllocate(const OmpAllocateDirective &x);
281
282namespace detail {
283template <typename ClauseTy, typename VoidTy = void> struct HasModifierImpl {
284 static constexpr bool value{false};
285};
286template <typename ClauseTy>
287struct HasModifierImpl<ClauseTy, std::void_t<typename ClauseTy::Modifier>> {
288 static constexpr bool value{true};
289};
290} // namespace detail
291template <typename ClauseTy>
292static constexpr bool HasModifier = detail::HasModifierImpl<ClauseTy>::value;
293
294template <typename R, typename = void, typename = void> struct is_range {
295 static constexpr bool value{false};
296};
297
298template <typename R>
299struct is_range<R, //
300 std::void_t<decltype(std::declval<R>().begin())>,
301 std::void_t<decltype(std::declval<R>().end())>> {
302 static constexpr bool value{true};
303};
304
305template <typename R> constexpr bool is_range_v = is_range<R>::value;
306
307// Iterate over a range of parser::Block::const_iterator's. When the end
308// of the range is reached, the iterator becomes invalid.
309// Treat BLOCK constructs as if they were transparent, i.e. as if the
310// BLOCK/ENDBLOCK statements, and the specification part contained within
311// were removed. The stepping determines whether the iterator steps "into"
312// DO loops and OpenMP loop constructs, or steps "over" them.
313//
314// Example: consecutive locations of the iterator:
315//
316// Step::Into Step::Over
317// block block
318// 1 => stmt1 1 => stmt1
319// block block
320// integer :: x integer :: x
321// 2 => stmt2 2 => stmt2
322// block block
323// end block end block
324// end block end block
325// 3 => do i = 1, n 3 => do i = 1, n
326// 4 => continue continue
327// end do end do
328// 5 => stmt3 4 => stmt3
329// end block end block
330//
331// 6 => <invalid> 5 => <invalid>
332//
333// The iterator is in a legal state (position) if it's at an
334// ExecutionPartConstruct that is not a BlockConstruct, or is invalid.
335struct ExecutionPartIterator {
336 enum class Step {
337 Into,
338 Over,
339 Default = Into,
340 };
341
342 using IteratorType = Block::const_iterator;
343 using IteratorRange = llvm::iterator_range<IteratorType>;
344
345 // An iterator range with a third iterator indicating a position inside
346 // the range.
347 struct IteratorGauge : public IteratorRange {
348 IteratorGauge(IteratorType b, IteratorType e)
349 : IteratorRange(b, e), at(b) {}
350 IteratorGauge(IteratorRange r) : IteratorRange(r), at(r.begin()) {}
351
352 bool atEnd() const { return at == end(); }
353 IteratorType at;
354 };
355
356 struct Construct {
357 Construct(IteratorType b, IteratorType e, const ExecutionPartConstruct *c)
358 : location(b, e), owner(c) {}
359 template <typename R>
360 Construct(const R &r, const ExecutionPartConstruct *c)
361 : location(r), owner(c) {}
362 Construct(const Construct &c) = default;
363 // The original range of the construct with the current position in it.
364 // The location.at is the construct currently being pointed at, or
365 // stepped into.
366 IteratorGauge location;
367 const ExecutionPartConstruct *owner;
368 };
369
370 ExecutionPartIterator() = default;
371
372 ExecutionPartIterator(IteratorType b, IteratorType e, Step s = Step::Default,
373 const ExecutionPartConstruct *c = nullptr)
374 : stepping_(s) {
375 stack_.emplace_back(b, e, c);
376 adjust();
377 }
378 template <typename R, typename = std::enable_if_t<is_range_v<R>>>
379 ExecutionPartIterator(const R &range, Step stepping = Step::Default,
380 const ExecutionPartConstruct *construct = nullptr)
381 : ExecutionPartIterator(range.begin(), range.end(), stepping, construct) {
382 }
383
384 // Advance the iterator to the next legal position. If the current position
385 // is a DO-loop or a loop construct, step into the contained Block.
386 void step();
387
388 // Advance the iterator to the next legal position. If the current position
389 // is a DO-loop or a loop construct, step to the next legal position following
390 // the DO-loop or loop construct.
391 void next();
392
393 bool valid() const { return !stack_.empty(); }
394
395 const std::vector<Construct> &stack() const { return stack_; }
396 decltype(auto) operator*() const { return *at(); }
397 bool operator==(const ExecutionPartIterator &other) const {
398 if (valid() != other.valid()) {
399 return false;
400 }
401 // Invalid iterators are considered equal.
402 return !valid() ||
403 stack_.back().location.at == other.stack_.back().location.at;
404 }
405 bool operator!=(const ExecutionPartIterator &other) const {
406 return !(*this == other);
407 }
408
409 ExecutionPartIterator &operator++() {
410 if (stepping_ == Step::Into) {
411 step();
412 } else {
413 assert(stepping_ == Step::Over && "Unexpected stepping");
414 next();
415 }
416 return *this;
417 }
418
419 ExecutionPartIterator operator++(int) {
420 ExecutionPartIterator copy{*this};
421 operator++();
422 return copy;
423 }
424
425 using difference_type = IteratorType::difference_type;
426 using value_type = IteratorType::value_type;
427 using reference = IteratorType::reference;
428 using pointer = IteratorType::pointer;
429 using iterator_category = std::forward_iterator_tag;
430
431private:
432 IteratorType at() const { return stack_.back().location.at; };
433
434 // If the iterator is not at a legal location, keep advancing it until
435 // it lands at a legal location or becomes invalid.
436 void adjust();
437
438 const Step stepping_ = Step::Default;
439 std::vector<Construct> stack_;
440};
441
442template <typename Iterator = ExecutionPartIterator> struct ExecutionPartRange {
443 using Step = typename Iterator::Step;
444
445 ExecutionPartRange(Block::const_iterator begin, Block::const_iterator end,
446 Step stepping = Step::Default,
447 const ExecutionPartConstruct *owner = nullptr)
448 : begin_(begin, end, stepping, owner), end_() {}
449 template <typename R, typename = std::enable_if_t<is_range_v<R>>>
450 ExecutionPartRange(const R &range, Step stepping = Step::Default,
451 const ExecutionPartConstruct *owner = nullptr)
452 : ExecutionPartRange(range.begin(), range.end(), stepping, owner) {}
453
454 Iterator begin() const { return begin_; }
455 Iterator end() const { return end_; }
456
457private:
458 Iterator begin_, end_;
459};
460
461struct LoopNestIterator : public ExecutionPartIterator {
462 LoopNestIterator() = default;
463
464 LoopNestIterator(IteratorType b, IteratorType e, Step s = Step::Default,
465 const ExecutionPartConstruct *c = nullptr)
466 : ExecutionPartIterator(b, e, s, c) {
467 adjust();
468 }
469 template <typename R, typename = std::enable_if_t<is_range_v<R>>>
470 LoopNestIterator(const R &range, Step stepping = Step::Default,
471 const ExecutionPartConstruct *construct = nullptr)
472 : LoopNestIterator(range.begin(), range.end(), stepping, construct) {}
473
474 LoopNestIterator &operator++() {
475 ExecutionPartIterator::operator++();
476 adjust();
477 return *this;
478 }
479
480 LoopNestIterator operator++(int) {
481 LoopNestIterator copy{*this};
482 operator++();
483 return copy;
484 }
485
486private:
487 static bool isLoop(const ExecutionPartConstruct &c);
488
489 void adjust() {
490 while (valid() && !isLoop(**this)) {
491 ExecutionPartIterator::operator++();
492 }
493 }
494};
495
498
499} // namespace Fortran::parser::omp
500
501#endif // FORTRAN_PARSER_OPENMP_UTILS_H
Definition indirection.h:31
Definition char-block.h:27
Definition parse-tree.h:442
Definition parse-tree.h:2379
Definition parse-tree.h:559
Definition parse-tree.h:5529
Definition parse-tree.h:5393
Definition parse-tree.h:3591
Definition parse-tree.h:5294
Definition parse-tree.h:3646
Definition parse-tree.h:5407
Definition parse-tree.h:5681
Definition parse-tree.h:5667
Definition parse-tree.h:3757
Definition openmp-utils.h:335
Definition openmp-utils.h:442
Definition openmp-utils.h:275
Definition openmp-utils.h:294