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/Evaluate/type.h"
17#include "flang/Parser/char-block.h"
18#include "flang/Parser/message.h"
19#include "flang/Parser/openmp-utils.h"
20#include "flang/Parser/parse-tree.h"
21#include "flang/Parser/tools.h"
22#include "flang/Semantics/tools.h"
23
24#include "llvm/ADT/APInt.h"
25#include "llvm/ADT/ArrayRef.h"
26#include "llvm/Frontend/OpenMP/OMPContext.h"
27
28#include <memory>
29#include <optional>
30#include <string>
31#include <type_traits>
32#include <utility>
33#include <vector>
34
35namespace Fortran::semantics {
36class Scope;
38class Symbol;
39
40// Add this namespace to avoid potential conflicts
41namespace omp {
42using Fortran::parser::omp::BlockRange;
43using Fortran::parser::omp::ExecutionPartIterator;
44using Fortran::parser::omp::is_range_v;
45using Fortran::parser::omp::LoopNestIterator;
46using Fortran::parser::omp::LoopRange;
47
48template <typename T, typename U = std::remove_const_t<T>> U AsRvalue(T &t) {
49 return U(t);
50}
51
52template <typename T> T &&AsRvalue(T &&t) { return std::move(t); }
53
54const Scope &GetScopingUnit(const Scope &scope);
55const Scope &GetProgramUnit(const Scope &scope);
56
57template <typename T> struct WithSource {
58 template < //
59 typename U = std::remove_reference_t<T>,
60 typename = std::enable_if_t<std::is_default_constructible_v<U>>>
61 WithSource() : value(), source() {}
62 WithSource(const WithSource<T> &) = default;
63 WithSource(WithSource<T> &&) = default;
64 WithSource(const T &t, parser::CharBlock s) : value(t), source(s) {}
65 WithSource(T &&t, parser::CharBlock s) : value(std::move(t)), source(s) {}
66 WithSource &operator=(const WithSource<T> &) = default;
67 WithSource &operator=(WithSource<T> &&) = default;
68
69 using value_type = T;
70 T value;
71 parser::CharBlock source;
72};
73
74// There is no consistent way to get the source of an ActionStmt, but there
75// is "source" in Statement<T>. This structure keeps the ActionStmt with the
76// extracted source for further use.
77struct SourcedActionStmt : public WithSource<const parser::ActionStmt *> {
78 using WithSource<value_type>::WithSource;
79 value_type stmt() const { return value; }
80 operator bool() const { return stmt() != nullptr; }
81};
82
84SourcedActionStmt GetActionStmt(const parser::Block &block);
85
86std::string ThisVersion(unsigned version);
87std::string TryVersion(unsigned version);
88
89const Symbol *GetObjectSymbol(
90 const parser::OmpObject &object, bool ultimate = false);
91const Symbol *GetArgumentSymbol(
92 const parser::OmpArgument &argument, bool ultimate = false);
93
94bool IsCommonBlock(const Symbol &sym);
95bool IsExtendedListItem(const Symbol &sym);
96bool IsVariableListItem(const Symbol &sym);
97bool IsTypeParamInquiry(const Symbol &sym);
98bool IsComplexPart(const Symbol &sym);
99bool IsStructureComponent(const Symbol &sym);
100bool IsPrivatizable(const Symbol &sym);
101bool IsVarOrFunctionRef(const MaybeExpr &expr);
102
103bool IsWholeAssumedSizeArray(const parser::OmpObject &object);
104
105bool IsExtendedListItem(
106 const parser::OmpObject &object, SemanticsContext *semaCtx);
107bool IsLocatorListItem(
108 const parser::OmpObject &object, SemanticsContext *semaCtx);
109bool IsVariableListItem(
110 const parser::OmpObject &object, SemanticsContext *semaCtx);
111
112bool IsSubstring(const parser::OmpObject &object, SemanticsContext *semaCtx);
113bool IsArrayElement(const parser::OmpObject &object, SemanticsContext *semaCtx);
114
115const Symbol *GetHostSymbol(const Symbol &sym);
116
117bool IsMapEnteringType(parser::OmpMapType::Value type);
118bool IsMapExitingType(parser::OmpMapType::Value type);
119
120// Returns true if the symbol has a temporary stack-allocated descriptor.
121// This includes assumed-shape and assumed-rank dummy arguments that are
122// not allocatable or pointer. These descriptors are created on the caller's
123// stack and become invalid after the function returns.
124bool HasTemporaryStackDescriptor(const Symbol &symbol);
125
126MaybeExpr GetEvaluateExpr(const parser::Expr &parserExpr);
127template <typename T> MaybeExpr GetEvaluateExpr(const T &inp) {
128 return GetEvaluateExpr(parser::UnwrapRef<parser::Expr>(inp));
129}
130
131std::optional<evaluate::DynamicType> GetDynamicType(
132 const parser::Expr &parserExpr);
133
134std::optional<bool> GetLogicalValue(const SomeExpr &expr);
135std::optional<int64_t> GetIntValueFromExpr(
136 const parser::Expr &parserExpr, SemanticsContext *semaCtx = nullptr);
137
138template <typename T>
139std::optional<int64_t> GetIntValueFromExpr(
140 const T &wrappedExpr, SemanticsContext *semaCtx = nullptr) {
141 if (auto *parserExpr{parser::Unwrap<parser::Expr>(wrappedExpr)}) {
142 return GetIntValueFromExpr(*parserExpr, semaCtx);
143 }
144 return std::nullopt;
145}
146
147// There are several clauses that take an optional, compile-time
148// constant bool argument. Those clauses are stored as std::optional, e.g.
149// OmpClause::ReverseOffload -> std::optional<OmpReverseOffloadClause>.
150// Retrieve the logical value if present.
151template <typename ClauseTy>
152std::optional<bool> GetLogicalArgument(
153 const std::optional<ClauseTy> &maybeClause, SemanticsContext &semaCtx) {
154 if (maybeClause) {
155 // Scalar<Logical<Constant<common::Indirection<Expr>>>>
156 auto &parserExpr{parser::UnwrapRef<parser::Expr>(*maybeClause)};
157 evaluate::ExpressionAnalyzer ea{semaCtx};
158 if (auto &&maybeExpr{ea.Analyze(parserExpr)}) {
159 if (auto v{GetLogicalValue(*maybeExpr)}) {
160 return *v;
161 }
162 }
163 }
164 return std::nullopt;
165}
166
167std::optional<bool> IsContiguous(
168 SemanticsContext &semaCtx, const parser::OmpObject &object);
169
172 const parser::ScalarExpr *expr;
173 parser::CharBlock source;
174};
175
180enum class UnsupportedSelectorFeature {
181 None,
183 TargetDevice,
187 ClauseOrExtensionProperty,
188};
189
193UnsupportedSelectorFeature FindUnsupportedSelectorFeature(
195 SemanticsContext &semaCtx);
196
205std::optional<DynamicUserCondition> MakeVariantMatchInfo(
206 llvm::omp::VariantMatchInfo &vmi,
208 SemanticsContext &semaCtx);
209
213class OmpVariantMatchContext : public llvm::omp::OMPContext {
214public:
215 OmpVariantMatchContext(bool isDeviceCompilation, llvm::Triple targetTriple,
216 llvm::Triple targetOffloadTriple, std::string targetFeatures,
217 llvm::ArrayRef<llvm::omp::TraitProperty> constructTraits = {});
218 OmpVariantMatchContext(const SemanticsContext &context,
219 llvm::ArrayRef<llvm::omp::TraitProperty> constructTraits = {});
220 bool matchesISATrait(llvm::StringRef rawString) const override;
221
222private:
223 std::string features_;
224};
225
226std::vector<SomeExpr> GetTopLevelDesignators(const SomeExpr &expr);
227const SomeExpr *HasStorageOverlap(
228 const SomeExpr &base, llvm::ArrayRef<SomeExpr> exprs);
229
230bool IsAssignment(const parser::ActionStmt *x);
231bool IsPointerAssignment(const evaluate::Assignment &x);
232
233MaybeExpr MakeEvaluateExpr(const parser::OmpStylizedInstance &inp);
234
235enum struct ListItemKind : uint32_t {
236 Depend,
237 DirectiveName,
238 DirectiveSpecification,
239 Extended,
240 IntegerExpression,
241 Interop,
242 Locator,
243 Operation,
244 Parameter,
245 ProcedureArgument,
246 Variable,
247};
248
249std::optional<ListItemKind> GetArgumentListItemKind(
250 llvm::omp::Clause clause, unsigned version);
251
252bool IsLoopTransforming(llvm::omp::Directive dir);
253bool HasDataEnvironment(llvm::omp::Directive dir);
254
255bool IsFullUnroll(const parser::OmpDirectiveSpecification &spec);
256
257inline bool IsDoConcurrentLegal(unsigned version) {
258 // DO CONCURRENT is allowed (as an alternative to a Canonical Loop Nest)
259 // in OpenMP 6.0+.
260 return version >= 60;
261}
262
263struct LoopControl {
264 LoopControl(LoopControl &&x) = default;
265 LoopControl(const LoopControl &x) = default;
266 LoopControl(const parser::LoopControl::Bounds &x);
267 LoopControl(const parser::ConcurrentControl &x);
268
269 const parser::Name &iv;
270 WithSource<MaybeExpr> lbound, ubound, step;
271
272private:
273 static WithSource<MaybeExpr> fromParserExpr(const parser::Expr &x);
274};
275
276std::vector<LoopControl> GetLoopControls(const parser::DoConstruct &x);
277
279struct Reason {
280 Reason() = default;
281 Reason(Reason &&) = default;
282 Reason(const Reason &);
283 Reason &operator=(Reason &&) = default;
284 Reason &operator=(const Reason &);
285
286 parser::Messages msgs;
287
288 template <typename... Ts> Reason &Say(Ts &&...args) {
289 msgs.Say(std::forward<Ts>(args)...);
290 return *this;
291 }
292 parser::Message &AttachTo(parser::Message &msg);
293 Reason &Append(const Reason &other) {
294 CopyFrom(other);
295 return *this;
296 }
297 operator bool() const { return !msgs.empty(); }
298
299private:
300 void CopyFrom(const Reason &other);
301};
302
303// A property with an explanation of its value. Both, the property and the
304// reason are optional (the reason can have no messages in it).
305template <typename T> struct WithReason {
306 std::optional<T> value;
307 Reason reason;
308
309 WithReason() = default;
310 WithReason(std::optional<T> v, const Reason &r = Reason())
311 : value(v), reason(r) {}
312 operator bool() const { return value.has_value(); }
313};
314
315WithReason<int64_t> GetArgumentValueWithReason(
316 const parser::OmpDirectiveSpecification &spec, llvm::omp::Clause clauseId,
317 unsigned version, SemanticsContext *semaCtx = nullptr);
318WithReason<int64_t> GetNumArgumentsWithReason(
319 const parser::OmpDirectiveSpecification &spec, llvm::omp::Clause clauseId,
320 unsigned version, SemanticsContext *semaCtx = nullptr);
321WithReason<int64_t> GetHeightWithReason(
322 const parser::OmpDirectiveSpecification &spec, unsigned version,
323 SemanticsContext *semaCtx = nullptr);
324
327std::pair<WithReason<int64_t>, bool> GetAffectedNestDepthWithReason(
328 const parser::OmpDirectiveSpecification &spec, unsigned version,
329 SemanticsContext *semaCtx = nullptr);
332std::pair<WithReason<int64_t>, bool> GetGeneratedNestDepthWithReason(
333 const parser::OmpDirectiveSpecification &spec, unsigned version,
334 SemanticsContext *semaCtx = nullptr);
338WithReason<std::pair<int64_t, int64_t>> GetAffectedLoopRangeWithReason(
339 const parser::OmpDirectiveSpecification &spec, unsigned version,
340 SemanticsContext *semaCtx = nullptr);
342WithReason<int64_t> GetRectangularNestDepthWithReason(
343 const parser::OmpDirectiveSpecification &spec, unsigned version,
344 SemanticsContext *semaCtx = nullptr);
345
349std::optional<int64_t> GetMinimumSequenceCount(
350 std::optional<int64_t> first, std::optional<int64_t> count);
351std::optional<int64_t> GetMinimumSequenceCount(
352 std::optional<std::pair<int64_t, int64_t>> range);
353
359std::optional<std::vector<const parser::DoConstruct *>> CollectAffectedDoLoops(
360 const parser::OpenMPLoopConstruct &x, unsigned version,
361 SemanticsContext *semaCtx = nullptr);
362
363struct LoopSequence {
364 LoopSequence(const parser::ExecutionPartConstruct &root, unsigned version,
365 bool allowAllLoops = false, SemanticsContext *semaCtx = nullptr);
366
367 template <typename R, typename = std::enable_if_t<is_range_v<R>>>
368 LoopSequence(const R &range, unsigned version, bool allowAllLoops = false,
369 SemanticsContext *semaCtx = nullptr)
370 : version_(version), allowAllLoops_(allowAllLoops), semaCtx_(semaCtx) {
371 entry_ = std::make_unique<Construct>(range, nullptr);
372 createChildrenFromRange(entry_->location);
373 precalculate();
374 }
375
376 struct Depth {
377 // If this sequence is a nest, the depth of the Canonical Loop Nest rooted
378 // at this sequence. Otherwise unspecified.
379 WithReason<int64_t> semantic;
380 // If this sequence is a nest, the depth of the perfect Canonical Loop Nest
381 // rooted at this sequence. Otherwise unspecified.
382 WithReason<int64_t> perfect;
383 };
384
385 bool isNest() const { return length_.value == 1; }
386 const WithReason<int64_t> &length() const { return length_; }
387 const WithReason<int64_t> &height() const { return height_; }
388 const Depth &depth() const { return depth_; }
389 const std::vector<LoopSequence> &children() const { return children_; }
390 const parser::ExecutionPartConstruct *owner() const { return entry_->owner; }
391
392 WithReason<bool> isWellFormedSequence() const;
393 WithReason<bool> isWellFormedNest() const;
394
397 const LoopSequence *getNestedDoConcurrent() const;
398
399 std::vector<LoopControl> getLoopControls() const;
400 // Check if this loop's bounds are invariant in each of the `outer`
401 // constructs.
402 WithReason<bool> isRectangular(
403 const std::vector<const LoopSequence *> &outer) const;
404
405private:
406 using Construct = ExecutionPartIterator::Construct;
407
408 LoopSequence(std::unique_ptr<Construct> entry, unsigned version,
409 bool allowAllLoops, SemanticsContext *semaCtx = nullptr);
410
411 template <typename R, typename = std::enable_if_t<is_range_v<R>>>
412 void createChildrenFromRange(const R &range) {
413 createChildrenFromRange(range.begin(), range.end());
414 }
415
416 std::unique_ptr<Construct> createConstructEntry(
417 const parser::ExecutionPartConstruct &code);
418
419 void createChildrenFromRange( //
420 ExecutionPartIterator::IteratorType begin,
421 ExecutionPartIterator::IteratorType end);
422
424 void precalculate();
425
426 WithReason<int64_t> calculateLength() const;
427 WithReason<int64_t> getNestedLength() const;
428 Depth calculateDepths() const;
429 Depth getNestedDepths() const;
430 WithReason<int64_t> calculateHeight() const;
431
435 const parser::ExecutionPartConstruct *invalidIC_{nullptr};
439 const parser::ExecutionPartConstruct *opaqueIC_{nullptr};
440
445 WithReason<int64_t> length_;
447 Depth depth_;
454 WithReason<int64_t> height_;
455
456 // The core structure of the class:
457 unsigned version_; // Needed for GetXyzWithReason
458 bool allowAllLoops_;
459 std::unique_ptr<Construct> entry_;
460 std::vector<LoopSequence> children_;
461 SemanticsContext *semaCtx_{nullptr};
462};
463
464// ---------------------------------------------------------------------------
465// Trait-matching helpers shared between metadirective lowering and
466// declare-variant semantic recording.
467// ---------------------------------------------------------------------------
468
470llvm::omp::TraitSet MapTraitSet(parser::OmpTraitSetSelectorName::Value name);
471
474llvm::omp::TraitSelector MapTraitSelector(
475 const parser::OmpTraitSelectorName &name, llvm::omp::TraitSet set);
476
478std::optional<bool> EvaluateUserCondition(
479 SemanticsContext &semaCtx, const parser::ScalarExpr &scalarExpr);
480
482llvm::APInt *GetTraitScore(
483 const std::optional<parser::OmpTraitSelector::Properties> &props,
484 SemanticsContext &semaCtx, std::optional<llvm::APInt> &scoreStorage);
485
489void ProcessTraitProperties(llvm::omp::VariantMatchInfo &vmi,
490 llvm::omp::TraitSet set, llvm::omp::TraitSelector selector,
491 const std::optional<parser::OmpTraitSelector::Properties> &props,
492 llvm::APInt *scorePtr);
493
494} // namespace omp
495} // namespace Fortran::semantics
496
497#endif // FORTRAN_SEMANTICS_OPENMP_UTILS_H
Definition expression.h:920
Definition char-block.h:26
Definition message.h:200
Definition message.h:332
Definition scope.h:68
Definition semantics.h:67
Definition symbol.h:893
Definition FIRType.h:106
Definition parse-tree.h:500
Definition parse-tree.h:2278
Definition parse-tree.h:2365
Definition parse-tree.h:558
Definition parse-tree.h:1735
Definition parse-tree.h:591
Definition parse-tree.h:5162
Definition parse-tree.h:3620
Definition parse-tree.h:3645
Definition parse-tree.h:5535
Definition parse-tree.h:3742
Non-constant user condition expression and source for runtime lowering.
Definition openmp-utils.h:171
const LoopSequence * getNestedDoConcurrent() const
Definition openmp-utils.cpp:1736
A representation of a "because" message.
Definition openmp-utils.h:279
Definition openmp-utils.h:77
Definition openmp-utils.h:305
Definition openmp-utils.h:57