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/ADT/SmallVector.h"
27#include "llvm/Frontend/OpenMP/OMPContext.h"
28
29#include <memory>
30#include <optional>
31#include <string>
32#include <type_traits>
33#include <utility>
34#include <vector>
35
36namespace Fortran::semantics {
37class DeclTypeSpec;
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
119// Resolve a user-defined reduction visible in scope under the mangled name
120// mangledName (e.g. "op.myop." for operator(.myop.), or a named reduction).
121// Follows USE associations, operator renames, private visibility, and merged
122// generics exactly as the OpenMP semantic checks do, returning the found
123// (non-ultimate) reduction symbol, or null if none is visible. When type is
124// non-null, only a reduction that supports that type is accepted (used to
125// disambiguate an operator that carries reductions for several types). When
126// ambiguous is non-null, it is set true if more than one distinct reduction
127// supports the type (an operator merged from several modules that each declare
128// a reduction for it, or a mangled reduction name that collides across
129// modules).
130const Symbol *FindUserReductionSymbol(const Scope &scope,
131 const parser::CharBlock &mangledName, const DeclTypeSpec *type = nullptr,
132 bool *ambiguous = nullptr);
133
134// Resolve the user-defined reduction associated with the defined-operator
135// symbol operatorSym. Delegates to FindUserReductionSymbol from scope (the
136// scope where the reduction clause appears) with the operator's mangled
137// ("op...") name. Searching from the clause scope, not the operator's owning
138// scope, finds a reduction that is local, host-, or use-associated there (a
139// reduction may be declared in a contained procedure that host-associates the
140// operator from an enclosing module). type filters by supported type as above.
141const Symbol *FindOperatorUserReductionSymbol(const Scope &scope,
142 const Symbol &operatorSym, const DeclTypeSpec *type = nullptr);
143
144// Mangled reduction name ("op.+", "op.*", "op.AND", ...) that semantics stores
145// an intrinsic-operator user reduction under, produced by the same
146// MakeNameFromOperator the reduction-declaration semantics use so a clause-side
147// lookup matches byte-for-byte.
148parser::CharBlock MangledIntrinsicOperatorReductionName(
149 parser::DefinedOperator::IntrinsicOperator op, SemanticsContext &context);
150
151bool IsMapEnteringType(parser::OmpMapType::Value type);
152bool IsMapExitingType(parser::OmpMapType::Value type);
153
154// Returns true if the symbol has a temporary stack-allocated descriptor.
155// This includes assumed-shape and assumed-rank dummy arguments that are
156// not allocatable or pointer. These descriptors are created on the caller's
157// stack and become invalid after the function returns.
158bool HasTemporaryStackDescriptor(const Symbol &symbol);
159
160MaybeExpr GetEvaluateExpr(const parser::Expr &parserExpr);
161template <typename T> MaybeExpr GetEvaluateExpr(const T &inp) {
162 return GetEvaluateExpr(parser::UnwrapRef<parser::Expr>(inp));
163}
164
165std::optional<evaluate::DynamicType> GetDynamicType(
166 const parser::Expr &parserExpr);
167
168std::optional<bool> GetLogicalValue(const SomeExpr &expr);
169std::optional<int64_t> GetIntValueFromExpr(
170 const parser::Expr &parserExpr, SemanticsContext *semaCtx = nullptr);
171
172template <typename T>
173std::optional<int64_t> GetIntValueFromExpr(
174 const T &wrappedExpr, SemanticsContext *semaCtx = nullptr) {
175 if (auto *parserExpr{parser::Unwrap<parser::Expr>(wrappedExpr)}) {
176 return GetIntValueFromExpr(*parserExpr, semaCtx);
177 }
178 return std::nullopt;
179}
180
181// There are several clauses that take an optional, compile-time
182// constant bool argument. Those clauses are stored as std::optional, e.g.
183// OmpClause::ReverseOffload -> std::optional<OmpReverseOffloadClause>.
184// Retrieve the logical value if present.
185template <typename ClauseTy>
186std::optional<bool> GetLogicalArgument(
187 const std::optional<ClauseTy> &maybeClause, SemanticsContext &semaCtx) {
188 if (maybeClause) {
189 // Scalar<Logical<Constant<common::Indirection<Expr>>>>
190 auto &parserExpr{parser::UnwrapRef<parser::Expr>(*maybeClause)};
191 evaluate::ExpressionAnalyzer ea{semaCtx};
192 if (auto &&maybeExpr{ea.Analyze(parserExpr)}) {
193 if (auto v{GetLogicalValue(*maybeExpr)}) {
194 return *v;
195 }
196 }
197 }
198 return std::nullopt;
199}
200
201std::optional<bool> IsContiguous(
202 SemanticsContext &semaCtx, const parser::OmpObject &object);
203
206 const parser::ScalarExpr *expr;
207 parser::CharBlock source;
208};
209
214enum class UnsupportedSelectorFeature {
215 None,
217 TargetDevice,
221 ClauseOrExtensionProperty,
222};
223
227UnsupportedSelectorFeature FindUnsupportedSelectorFeature(
229 SemanticsContext &semaCtx);
230
239std::optional<DynamicUserCondition> MakeVariantMatchInfo(
240 llvm::omp::VariantMatchInfo &vmi,
242 SemanticsContext &semaCtx);
243
247class OmpVariantMatchContext : public llvm::omp::OMPContext {
248public:
249 OmpVariantMatchContext(bool isDeviceCompilation, llvm::Triple targetTriple,
250 llvm::Triple targetOffloadTriple, std::string targetFeatures,
251 llvm::ArrayRef<llvm::omp::TraitProperty> constructTraits = {});
252 OmpVariantMatchContext(const SemanticsContext &context,
253 llvm::ArrayRef<llvm::omp::TraitProperty> constructTraits = {});
254 bool matchesISATrait(llvm::StringRef rawString) const override;
255
256private:
257 std::string features_;
258};
259
266bool MayVariantBeSelected(
268 SemanticsContext &context, OmpVariantMatchContext &matchContext);
269
270std::vector<SomeExpr> GetTopLevelDesignators(const SomeExpr &expr);
271const SomeExpr *HasStorageOverlap(
272 const SomeExpr &base, llvm::ArrayRef<SomeExpr> exprs);
273
274bool IsAssignment(const parser::ActionStmt *x);
275bool IsPointerAssignment(const evaluate::Assignment &x);
276
277MaybeExpr MakeEvaluateExpr(const parser::OmpStylizedInstance &inp);
278
279enum struct ListItemKind : uint32_t {
280 Depend,
281 DirectiveName,
282 DirectiveSpecification,
283 Extended,
284 IntegerExpression,
285 Interop,
286 Locator,
287 Operation,
288 Parameter,
289 ProcedureArgument,
290 Variable,
291};
292
293std::optional<ListItemKind> GetArgumentListItemKind(
294 llvm::omp::Clause clause, unsigned version);
295
296bool IsLoopTransforming(llvm::omp::Directive dir);
297bool HasDataEnvironment(llvm::omp::Directive dir);
298
299bool IsFullUnroll(const parser::OmpDirectiveSpecification &spec);
300
305 parser::OmpAtClause::ActionTime at{
306 parser::OmpAtClause::ActionTime::Compilation};
307 parser::OmpSeverityClause::SevLevel severity{
308 parser::OmpSeverityClause::SevLevel::Fatal};
309 const parser::Expr *message{nullptr};
310};
311
314OmpErrorArgs GetErrorDirectiveArgs(const parser::OmpErrorDirective &errDir);
315
316inline bool IsDoConcurrentLegal(unsigned version) {
317 // DO CONCURRENT is allowed (as an alternative to a Canonical Loop Nest)
318 // in OpenMP 6.0+.
319 return version >= 60;
320}
321
322struct LoopControl {
323 LoopControl(LoopControl &&x) = default;
324 LoopControl(const LoopControl &x) = default;
325 LoopControl(const parser::LoopControl::Bounds &x);
326 LoopControl(const parser::ConcurrentControl &x);
327
328 const parser::Name &iv;
329 WithSource<MaybeExpr> lbound, ubound, step;
330
331private:
332 static WithSource<MaybeExpr> fromParserExpr(const parser::Expr &x);
333};
334
335std::vector<LoopControl> GetLoopControls(const parser::DoConstruct &x);
336
338struct Reason {
339 Reason() = default;
340 Reason(Reason &&) = default;
341 Reason(const Reason &);
342 Reason &operator=(Reason &&) = default;
343 Reason &operator=(const Reason &);
344
345 parser::Messages msgs;
346
347 template <typename... Ts> Reason &Say(Ts &&...args) {
348 msgs.Say(std::forward<Ts>(args)...);
349 return *this;
350 }
351 parser::Message &AttachTo(parser::Message &msg);
352 Reason &Append(const Reason &other) {
353 CopyFrom(other);
354 return *this;
355 }
356 operator bool() const { return !msgs.empty(); }
357
358private:
359 void CopyFrom(const Reason &other);
360};
361
362// A property with an explanation of its value. Both, the property and the
363// reason are optional (the reason can have no messages in it).
364template <typename T> struct WithReason {
365 std::optional<T> value;
366 Reason reason;
367
368 WithReason() = default;
369 WithReason(std::optional<T> v, const Reason &r = Reason())
370 : value(v), reason(r) {}
371 operator bool() const { return value.has_value(); }
372};
373
374WithReason<int64_t> GetArgumentValueWithReason(
375 const parser::OmpDirectiveSpecification &spec, llvm::omp::Clause clauseId,
376 unsigned version, SemanticsContext *semaCtx = nullptr);
377WithReason<int64_t> GetNumArgumentsWithReason(
378 const parser::OmpDirectiveSpecification &spec, llvm::omp::Clause clauseId,
379 unsigned version, SemanticsContext *semaCtx = nullptr);
380WithReason<int64_t> GetHeightWithReason(
381 const parser::OmpDirectiveSpecification &spec, unsigned version,
382 SemanticsContext *semaCtx = nullptr);
383
386std::pair<WithReason<int64_t>, bool> GetAffectedNestDepthWithReason(
387 const parser::OmpDirectiveSpecification &spec, unsigned version,
388 SemanticsContext *semaCtx = nullptr);
391std::pair<WithReason<int64_t>, bool> GetGeneratedNestDepthWithReason(
392 const parser::OmpDirectiveSpecification &spec, unsigned version,
393 SemanticsContext *semaCtx = nullptr);
397WithReason<std::pair<int64_t, int64_t>> GetAffectedLoopRangeWithReason(
398 const parser::OmpDirectiveSpecification &spec, unsigned version,
399 SemanticsContext *semaCtx = nullptr);
401WithReason<int64_t> GetRectangularNestDepthWithReason(
402 const parser::OmpDirectiveSpecification &spec, unsigned version,
403 SemanticsContext *semaCtx = nullptr);
404
408std::optional<int64_t> GetMinimumSequenceCount(
409 std::optional<int64_t> first, std::optional<int64_t> count);
410std::optional<int64_t> GetMinimumSequenceCount(
411 std::optional<std::pair<int64_t, int64_t>> range);
412
418std::optional<std::vector<const parser::DoConstruct *>> CollectAffectedDoLoops(
419 const parser::OpenMPLoopConstruct &x, unsigned version,
420 SemanticsContext *semaCtx = nullptr);
421
426bool IsDoacrossAffected(const parser::OpenMPLoopConstruct &x);
427
428struct LoopSequence {
429 LoopSequence(const parser::ExecutionPartConstruct &root, unsigned version,
430 bool allowAllLoops = false, SemanticsContext *semaCtx = nullptr);
431
432 template <typename R, typename = std::enable_if_t<is_range_v<R>>>
433 LoopSequence(const R &range, unsigned version, bool allowAllLoops = false,
434 SemanticsContext *semaCtx = nullptr)
435 : version_(version), allowAllLoops_(allowAllLoops), semaCtx_(semaCtx) {
436 entry_ = std::make_unique<Construct>(range, nullptr);
437 createChildrenFromRange(entry_->location);
438 precalculate();
439 }
440
441 struct Depth {
442 // If this sequence is a nest, the depth of the Canonical Loop Nest rooted
443 // at this sequence. Otherwise unspecified.
444 WithReason<int64_t> semantic;
445 // If this sequence is a nest, the depth of the perfect Canonical Loop Nest
446 // rooted at this sequence. Otherwise unspecified.
447 WithReason<int64_t> perfect;
448 };
449
450 bool isNest() const { return length_.value == 1; }
451 const WithReason<int64_t> &length() const { return length_; }
452 const WithReason<int64_t> &height() const { return height_; }
453 const Depth &depth() const { return depth_; }
454 const std::vector<LoopSequence> &children() const { return children_; }
455 const parser::ExecutionPartConstruct *owner() const { return entry_->owner; }
456
457 WithReason<bool> isWellFormedSequence() const;
458 WithReason<bool> isWellFormedNest() const;
459
462 const LoopSequence *getNestedDoConcurrent() const;
463
464 std::vector<LoopControl> getLoopControls() const;
465 // Check if this loop's bounds are invariant in each of the `outer`
466 // constructs.
467 WithReason<bool> isRectangular(
468 const std::vector<const LoopSequence *> &outer) const;
469
470private:
471 using Construct = ExecutionPartIterator::Construct;
472
473 LoopSequence(std::unique_ptr<Construct> entry, unsigned version,
474 bool allowAllLoops, SemanticsContext *semaCtx = nullptr);
475
476 template <typename R, typename = std::enable_if_t<is_range_v<R>>>
477 void createChildrenFromRange(const R &range) {
478 createChildrenFromRange(range.begin(), range.end());
479 }
480
481 std::unique_ptr<Construct> createConstructEntry(
482 const parser::ExecutionPartConstruct &code);
483
484 void createChildrenFromRange( //
485 ExecutionPartIterator::IteratorType begin,
486 ExecutionPartIterator::IteratorType end);
487
489 void precalculate();
490
491 WithReason<int64_t> calculateLength() const;
492 WithReason<int64_t> getNestedLength() const;
493 Depth calculateDepths() const;
494 Depth getNestedDepths() const;
495 WithReason<int64_t> calculateHeight() const;
496
500 const parser::ExecutionPartConstruct *invalidIC_{nullptr};
504 const parser::ExecutionPartConstruct *opaqueIC_{nullptr};
505
510 WithReason<int64_t> length_;
512 Depth depth_;
519 WithReason<int64_t> height_;
520
521 // The core structure of the class:
522 unsigned version_; // Needed for GetXyzWithReason
523 bool allowAllLoops_;
524 std::unique_ptr<Construct> entry_;
525 std::vector<LoopSequence> children_;
526 SemanticsContext *semaCtx_{nullptr};
527};
528
529// ---------------------------------------------------------------------------
530// Trait-matching helpers shared between metadirective lowering and
531// declare-variant semantic recording.
532// ---------------------------------------------------------------------------
533
535llvm::omp::TraitSet MapTraitSet(parser::OmpTraitSetSelectorName::Value name);
536
539llvm::omp::TraitSelector MapTraitSelector(
540 const parser::OmpTraitSelectorName &name, llvm::omp::TraitSet set);
541
543std::optional<bool> EvaluateUserCondition(
544 SemanticsContext &semaCtx, const parser::ScalarExpr &scalarExpr);
545
547llvm::APInt *GetTraitScore(
548 const std::optional<parser::OmpTraitSelector::Properties> &props,
549 SemanticsContext &semaCtx, std::optional<llvm::APInt> &scoreStorage);
550
554void ProcessTraitProperties(llvm::omp::VariantMatchInfo &vmi,
555 llvm::omp::TraitSet set, llvm::omp::TraitSelector selector,
556 const std::optional<parser::OmpTraitSelector::Properties> &props,
557 llvm::APInt *scorePtr);
558
559} // namespace omp
560} // namespace Fortran::semantics
561
562#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:896
Definition FIRType.h:106
Definition parse-tree.h:500
Definition parse-tree.h:2280
Definition parse-tree.h:2367
Definition parse-tree.h:558
Definition parse-tree.h:1737
Definition parse-tree.h:591
Definition parse-tree.h:5166
Definition parse-tree.h:5233
Definition parse-tree.h:3622
Definition parse-tree.h:3647
Definition parse-tree.h:5539
Definition parse-tree.h:3744
Non-constant user condition expression and source for runtime lowering.
Definition openmp-utils.h:205
const LoopSequence * getNestedDoConcurrent() const
Definition openmp-utils.cpp:1837
Definition openmp-utils.h:304
A representation of a "because" message.
Definition openmp-utils.h:338
Definition openmp-utils.h:79
Definition openmp-utils.h:364
Definition openmp-utils.h:59