FLANG
openmp-utils.h
1//===-- lib/Semantics/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 utilities used in OpenMP semantic checks.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef FORTRAN_SEMANTICS_OPENMP_UTILS_H
14#define FORTRAN_SEMANTICS_OPENMP_UTILS_H
15
16#include "flang/Common/indirection.h"
17#include "flang/Evaluate/type.h"
18#include "flang/Parser/char-block.h"
19#include "flang/Parser/message.h"
20#include "flang/Parser/openmp-utils.h"
21#include "flang/Parser/parse-tree.h"
22#include "flang/Parser/tools.h"
23#include "flang/Semantics/tools.h"
24
25#include "llvm/ADT/APInt.h"
26#include "llvm/ADT/ArrayRef.h"
27#include "llvm/Frontend/OpenMP/OMPContext.h"
28
29#include <memory>
30#include <optional>
31#include <string>
32#include <tuple>
33#include <type_traits>
34#include <utility>
35#include <vector>
36
37namespace Fortran::semantics {
38class Scope;
40class Symbol;
41
42// Add this namespace to avoid potential conflicts
43namespace omp {
44using Fortran::parser::omp::BlockRange;
45using Fortran::parser::omp::ExecutionPartIterator;
46using Fortran::parser::omp::is_range_v;
47using Fortran::parser::omp::LoopNestIterator;
48using Fortran::parser::omp::LoopRange;
49
50template <typename T, typename U = std::remove_const_t<T>> U AsRvalue(T &t) {
51 return U(t);
52}
53
54template <typename T> T &&AsRvalue(T &&t) { return std::move(t); }
55
56const Scope &GetScopingUnit(const Scope &scope);
57const Scope &GetProgramUnit(const Scope &scope);
58
59template <typename T> struct WithSource {
60 template < //
61 typename U = std::remove_reference_t<T>,
62 typename = std::enable_if_t<std::is_default_constructible_v<U>>>
63 WithSource() : value(), source() {}
64 WithSource(const WithSource<T> &) = default;
65 WithSource(WithSource<T> &&) = default;
66 WithSource(const T &t, parser::CharBlock s) : value(t), source(s) {}
67 WithSource(T &&t, parser::CharBlock s) : value(std::move(t)), source(s) {}
68 WithSource &operator=(const WithSource<T> &) = default;
69 WithSource &operator=(WithSource<T> &&) = default;
70
71 using value_type = T;
72 T value;
73 parser::CharBlock source;
74};
75
76// There is no consistent way to get the source of an ActionStmt, but there
77// is "source" in Statement<T>. This structure keeps the ActionStmt with the
78// extracted source for further use.
79struct SourcedActionStmt : public WithSource<const parser::ActionStmt *> {
80 using WithSource<value_type>::WithSource;
81 value_type stmt() const { return value; }
82 operator bool() const { return stmt() != nullptr; }
83};
84
86SourcedActionStmt GetActionStmt(const parser::Block &block);
87
88std::string ThisVersion(unsigned version);
89std::string TryVersion(unsigned version);
90
91const Symbol *GetObjectSymbol(
92 const parser::OmpObject &object, bool ultimate = false);
93const Symbol *GetArgumentSymbol(
94 const parser::OmpArgument &argument, bool ultimate = false);
95
96bool IsCommonBlock(const Symbol &sym);
97bool IsExtendedListItem(const Symbol &sym);
98bool IsVariableListItem(const Symbol &sym);
99bool IsTypeParamInquiry(const Symbol &sym);
100bool IsComplexPart(const Symbol &sym);
101bool IsStructureComponent(const Symbol &sym);
102bool IsPrivatizable(const Symbol &sym);
103bool IsVarOrFunctionRef(const MaybeExpr &expr);
104
105bool IsWholeAssumedSizeArray(const parser::OmpObject &object);
106
107bool IsExtendedListItem(
108 const parser::OmpObject &object, SemanticsContext *semaCtx);
109bool IsLocatorListItem(
110 const parser::OmpObject &object, SemanticsContext *semaCtx);
111bool IsVariableListItem(
112 const parser::OmpObject &object, SemanticsContext *semaCtx);
113
114bool IsSubstring(const parser::OmpObject &object, SemanticsContext *semaCtx);
115bool IsArrayElement(const parser::OmpObject &object, SemanticsContext *semaCtx);
116
117const Symbol *GetHostSymbol(const Symbol &sym);
118
119bool IsMapEnteringType(parser::OmpMapType::Value type);
120bool IsMapExitingType(parser::OmpMapType::Value type);
121
122MaybeExpr GetEvaluateExpr(const parser::Expr &parserExpr);
123template <typename T> MaybeExpr GetEvaluateExpr(const T &inp) {
124 return GetEvaluateExpr(parser::UnwrapRef<parser::Expr>(inp));
125}
126
127std::optional<evaluate::DynamicType> GetDynamicType(
128 const parser::Expr &parserExpr);
129
130std::optional<bool> GetLogicalValue(const SomeExpr &expr);
131std::optional<int64_t> GetIntValueFromExpr(
132 const parser::Expr &parserExpr, SemanticsContext *semaCtx = nullptr);
133
134template <typename T>
135std::optional<int64_t> GetIntValueFromExpr(
136 const T &wrappedExpr, SemanticsContext *semaCtx = nullptr) {
137 if (auto *parserExpr{parser::Unwrap<parser::Expr>(wrappedExpr)}) {
138 return GetIntValueFromExpr(*parserExpr, semaCtx);
139 }
140 return std::nullopt;
141}
142
143// There are several clauses that take an optional, compile-time
144// constant bool argument. Those clauses are stored as std::optional, e.g.
145// OmpClause::ReverseOffload -> std::optional<OmpReverseOffloadClause>.
146// Retrieve the logical value if present.
147template <typename ClauseTy>
148std::optional<bool> GetLogicalArgument(
149 const std::optional<ClauseTy> &maybeClause, SemanticsContext &semaCtx) {
150 if (maybeClause) {
151 // Scalar<Logical<Constant<common::Indirection<Expr>>>>
152 auto &parserExpr{parser::UnwrapRef<parser::Expr>(*maybeClause)};
153 evaluate::ExpressionAnalyzer ea{semaCtx};
154 if (auto &&maybeExpr{ea.Analyze(parserExpr)}) {
155 if (auto v{GetLogicalValue(*maybeExpr)}) {
156 return *v;
157 }
158 }
159 }
160 return std::nullopt;
161}
162
163std::optional<bool> IsContiguous(
164 SemanticsContext &semaCtx, const parser::OmpObject &object);
165
166std::vector<SomeExpr> GetTopLevelDesignators(const SomeExpr &expr);
167const SomeExpr *HasStorageOverlap(
168 const SomeExpr &base, llvm::ArrayRef<SomeExpr> exprs);
169
170bool IsAssignment(const parser::ActionStmt *x);
171bool IsPointerAssignment(const evaluate::Assignment &x);
172
173MaybeExpr MakeEvaluateExpr(const parser::OmpStylizedInstance &inp);
174
175enum struct ListItemKind : uint32_t {
176 Depend,
177 DirectiveName,
178 DirectiveSpecification,
179 Extended,
180 IntegerExpression,
181 Interop,
182 Locator,
183 Operation,
184 Parameter,
185 ProcedureArgument,
186 Variable,
187};
188
189std::optional<ListItemKind> GetArgumentListItemKind(
190 llvm::omp::Clause clause, unsigned version);
191
192bool IsLoopTransforming(llvm::omp::Directive dir);
193bool HasDataEnvironment(llvm::omp::Directive dir);
194
195bool IsFullUnroll(const parser::OmpDirectiveSpecification &spec);
196
197inline bool IsDoConcurrentLegal(unsigned version) {
198 // DO CONCURRENT is allowed (as an alternative to a Canonical Loop Nest)
199 // in OpenMP 6.0+.
200 return version >= 60;
201}
202
203struct LoopControl {
204 LoopControl(LoopControl &&x) = default;
205 LoopControl(const LoopControl &x) = default;
206 LoopControl(const parser::LoopControl::Bounds &x);
207 LoopControl(const parser::ConcurrentControl &x);
208
209 const parser::Name &iv;
210 WithSource<MaybeExpr> lbound, ubound, step;
211
212private:
213 static WithSource<MaybeExpr> fromParserExpr(const parser::Expr &x);
214};
215
216std::vector<LoopControl> GetLoopControls(const parser::DoConstruct &x);
217
219struct Reason {
220 Reason() = default;
221 Reason(Reason &&) = default;
222 Reason(const Reason &);
223 Reason &operator=(Reason &&) = default;
224 Reason &operator=(const Reason &);
225
226 parser::Messages msgs;
227
228 template <typename... Ts> Reason &Say(Ts &&...args) {
229 msgs.Say(std::forward<Ts>(args)...);
230 return *this;
231 }
232 parser::Message &AttachTo(parser::Message &msg);
233 Reason &Append(const Reason &other) {
234 CopyFrom(other);
235 return *this;
236 }
237 operator bool() const { return !msgs.empty(); }
238
239private:
240 void CopyFrom(const Reason &other);
241};
242
243// A property with an explanation of its value. Both, the property and the
244// reason are optional (the reason can have no messages in it).
245template <typename T> struct WithReason {
246 std::optional<T> value;
247 Reason reason;
248
249 WithReason() = default;
250 WithReason(std::optional<T> v, const Reason &r = Reason())
251 : value(v), reason(r) {}
252 operator bool() const { return value.has_value(); }
253};
254
255WithReason<int64_t> GetArgumentValueWithReason(
256 const parser::OmpDirectiveSpecification &spec, llvm::omp::Clause clauseId,
257 unsigned version, SemanticsContext *semaCtx = nullptr);
258WithReason<int64_t> GetNumArgumentsWithReason(
259 const parser::OmpDirectiveSpecification &spec, llvm::omp::Clause clauseId,
260 unsigned version, SemanticsContext *semaCtx = nullptr);
261WithReason<int64_t> GetHeightWithReason(
262 const parser::OmpDirectiveSpecification &spec, unsigned version,
263 SemanticsContext *semaCtx = nullptr);
264
267std::pair<WithReason<int64_t>, bool> GetAffectedNestDepthWithReason(
268 const parser::OmpDirectiveSpecification &spec, unsigned version,
269 SemanticsContext *semaCtx = nullptr);
272std::pair<WithReason<int64_t>, bool> GetGeneratedNestDepthWithReason(
273 const parser::OmpDirectiveSpecification &spec, unsigned version,
274 SemanticsContext *semaCtx = nullptr);
278WithReason<std::pair<int64_t, int64_t>> GetAffectedLoopRangeWithReason(
279 const parser::OmpDirectiveSpecification &spec, unsigned version,
280 SemanticsContext *semaCtx = nullptr);
282WithReason<int64_t> GetRectangularNestDepthWithReason(
283 const parser::OmpDirectiveSpecification &spec, unsigned version,
284 SemanticsContext *semaCtx = nullptr);
285
289std::optional<int64_t> GetMinimumSequenceCount(
290 std::optional<int64_t> first, std::optional<int64_t> count);
291std::optional<int64_t> GetMinimumSequenceCount(
292 std::optional<std::pair<int64_t, int64_t>> range);
293
299std::optional<std::vector<const parser::DoConstruct *>> CollectAffectedDoLoops(
300 const parser::OpenMPLoopConstruct &x, unsigned version,
301 SemanticsContext *semaCtx = nullptr);
302
303struct LoopSequence {
304 LoopSequence(const parser::ExecutionPartConstruct &root, unsigned version,
305 bool allowAllLoops = false, SemanticsContext *semaCtx = nullptr);
306
307 template <typename R, typename = std::enable_if_t<is_range_v<R>>>
308 LoopSequence(const R &range, unsigned version, bool allowAllLoops = false,
309 SemanticsContext *semaCtx = nullptr)
310 : version_(version), allowAllLoops_(allowAllLoops), semaCtx_(semaCtx) {
311 entry_ = std::make_unique<Construct>(range, nullptr);
312 createChildrenFromRange(entry_->location);
313 precalculate();
314 }
315
316 struct Depth {
317 // If this sequence is a nest, the depth of the Canonical Loop Nest rooted
318 // at this sequence. Otherwise unspecified.
319 WithReason<int64_t> semantic;
320 // If this sequence is a nest, the depth of the perfect Canonical Loop Nest
321 // rooted at this sequence. Otherwise unspecified.
322 WithReason<int64_t> perfect;
323 };
324
325 bool isNest() const { return length_.value == 1; }
326 const WithReason<int64_t> &length() const { return length_; }
327 const WithReason<int64_t> &height() const { return height_; }
328 const Depth &depth() const { return depth_; }
329 const std::vector<LoopSequence> &children() const { return children_; }
330 const parser::ExecutionPartConstruct *owner() const { return entry_->owner; }
331
332 WithReason<bool> isWellFormedSequence() const;
333 WithReason<bool> isWellFormedNest() const;
334
337 const LoopSequence *getNestedDoConcurrent() const;
338
339 std::vector<LoopControl> getLoopControls() const;
340 // Check if this loop's bounds are invariant in each of the `outer`
341 // constructs.
342 WithReason<bool> isRectangular(
343 const std::vector<const LoopSequence *> &outer) const;
344
345private:
346 using Construct = ExecutionPartIterator::Construct;
347
348 LoopSequence(std::unique_ptr<Construct> entry, unsigned version,
349 bool allowAllLoops, SemanticsContext *semaCtx = nullptr);
350
351 template <typename R, typename = std::enable_if_t<is_range_v<R>>>
352 void createChildrenFromRange(const R &range) {
353 createChildrenFromRange(range.begin(), range.end());
354 }
355
356 std::unique_ptr<Construct> createConstructEntry(
357 const parser::ExecutionPartConstruct &code);
358
359 void createChildrenFromRange( //
360 ExecutionPartIterator::IteratorType begin,
361 ExecutionPartIterator::IteratorType end);
362
364 void precalculate();
365
366 WithReason<int64_t> calculateLength() const;
367 WithReason<int64_t> getNestedLength() const;
368 Depth calculateDepths() const;
369 Depth getNestedDepths() const;
370 WithReason<int64_t> calculateHeight() const;
371
375 const parser::ExecutionPartConstruct *invalidIC_{nullptr};
379 const parser::ExecutionPartConstruct *opaqueIC_{nullptr};
380
385 WithReason<int64_t> length_;
387 Depth depth_;
394 WithReason<int64_t> height_;
395
396 // The core structure of the class:
397 unsigned version_; // Needed for GetXyzWithReason
398 bool allowAllLoops_;
399 std::unique_ptr<Construct> entry_;
400 std::vector<LoopSequence> children_;
401 SemanticsContext *semaCtx_{nullptr};
402};
403
404// ---------------------------------------------------------------------------
405// Trait-matching helpers shared between metadirective lowering and
406// declare-variant semantic recording.
407// ---------------------------------------------------------------------------
408
410llvm::omp::TraitSet MapTraitSet(parser::OmpTraitSetSelectorName::Value name);
411
414llvm::omp::TraitSelector MapTraitSelector(
415 const parser::OmpTraitSelectorName &name, llvm::omp::TraitSet set);
416
418std::optional<bool> EvaluateUserCondition(
419 SemanticsContext &semaCtx, const parser::ScalarExpr &scalarExpr);
420
422llvm::APInt *GetTraitScore(
423 const std::optional<parser::OmpTraitSelector::Properties> &props,
424 SemanticsContext &semaCtx, std::optional<llvm::APInt> &scoreStorage);
425
429void ProcessTraitProperties(llvm::omp::VariantMatchInfo &vmi,
430 llvm::omp::TraitSet set, llvm::omp::TraitSelector selector,
431 const std::optional<parser::OmpTraitSelector::Properties> &props,
432 llvm::APInt *scorePtr);
433
434} // namespace omp
435} // namespace Fortran::semantics
436
437#endif // FORTRAN_SEMANTICS_OPENMP_UTILS_H
Definition char-block.h:28
Definition message.h:200
Definition message.h:332
Definition scope.h:68
Definition semantics.h:68
Definition symbol.h:881
Definition parse-tree.h:2279
Definition parse-tree.h:2366
Definition parse-tree.h:559
Definition parse-tree.h:1736
Definition parse-tree.h:592
Definition parse-tree.h:5129
Definition parse-tree.h:3606
Definition parse-tree.h:5502
Definition parse-tree.h:3737
const LoopSequence * getNestedDoConcurrent() const
Definition openmp-utils.cpp:1677
A representation of a "because" message.
Definition openmp-utils.h:219
Definition openmp-utils.h:79
Definition openmp-utils.h:245
Definition openmp-utils.h:59