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/DenseMap.h"
27#include "llvm/ADT/SmallVector.h"
28#include "llvm/Frontend/OpenMP/OMPContext.h"
29#include "llvm/Frontend/OpenMP/OMPVersion.h"
30
31#include <memory>
32#include <optional>
33#include <string>
34#include <type_traits>
35#include <utility>
36#include <vector>
37
38namespace Fortran::semantics {
39class DeclTypeSpec;
40class Scope;
42class Symbol;
43
44// Add this namespace to avoid potential conflicts
45namespace omp {
46using Fortran::parser::omp::BlockRange;
47using Fortran::parser::omp::ExecutionPartIterator;
48using Fortran::parser::omp::is_range_v;
49using Fortran::parser::omp::LoopNestIterator;
50using Fortran::parser::omp::LoopRange;
51
52template <typename T, typename U = std::remove_const_t<T>> U AsRvalue(T &t) {
53 return U(t);
54}
55
56template <typename T> T &&AsRvalue(T &&t) { return std::move(t); }
57
59 // Map of clauses and which directives they are considered to be allowed on
60 // for the purpose of this compilation despite not being allowed by strict
61 // interpretation of the selected spec version.
62 // This is to record cases where we allow a clause because a past/future
63 // spec allows it. This is needed for consistent treatment of clauses as
64 // allowed/disallowed.
65 llvm::DenseMap<llvm::omp::Clause, llvm::omp::Directives> allowedClauses;
66};
67
68bool IsClauseAllowedOnDirective(llvm::omp::Clause clauseId,
69 llvm::omp::Directive dirId, llvm::omp::Version ver,
70 SemanticOverrides *overrides);
71
72bool IsClauseAllowedOnDirective(llvm::omp::Clause clauseId,
73 llvm::omp::Directive dirId, llvm::omp::Version version,
74 SemanticsContext *semaCtx);
75
76const Scope &GetScopingUnit(const Scope &scope);
77const Scope &GetProgramUnit(const Scope &scope);
78
79// There is no consistent way to get the source of an ActionStmt, but there
80// is "source" in Statement<T>. This structure keeps the ActionStmt with the
81// extracted source for further use.
83 : public parser::omp::WithSource<const parser::ActionStmt *> {
84 using parser::omp::WithSource<value_type>::WithSource;
85 value_type stmt() const { return value; }
86 operator bool() const { return stmt() != nullptr; }
87};
88
90SourcedActionStmt GetActionStmt(const parser::Block &block);
91
92std::string ThisVersion(llvm::omp::Version version);
93std::string TryVersion(llvm::omp::Version version);
94
95const Symbol *GetObjectSymbol(
96 const parser::OmpObject &object, bool ultimate = false);
97const Symbol *GetArgumentSymbol(
98 const parser::OmpArgument &argument, bool ultimate = false);
99
100bool IsCommonBlock(const Symbol &sym);
101bool IsExtendedListItem(const Symbol &sym);
102bool IsVariableListItem(const Symbol &sym);
103bool IsTypeParamInquiry(const Symbol &sym);
104bool IsComplexPart(const Symbol &sym);
105bool IsStructureComponent(const Symbol &sym);
106bool IsPrivatizable(const Symbol &sym);
107bool IsVarOrFunctionRef(const MaybeExpr &expr);
108
109bool IsCoindexedObject(const parser::OmpObject &object);
110
111bool IsWholeAssumedSizeArray(const parser::OmpObject &object);
112
113bool IsExtendedListItem(
114 const parser::OmpObject &object, SemanticsContext *semaCtx);
115bool IsLocatorListItem(
116 const parser::OmpObject &object, SemanticsContext *semaCtx);
117bool IsVariableListItem(
118 const parser::OmpObject &object, SemanticsContext *semaCtx);
119
120// Analyzes potential substrings and retains diagnostics; may modify semantic
121// state and the parse tree. A missing result indicates an invalid designator,
122// already diagnosed.
123std::optional<bool> IsSubstringAndValidate(
124 const parser::OmpObject &object, SemanticsContext *semaCtx);
125bool IsArrayElement(const parser::OmpObject &object, SemanticsContext *semaCtx);
126
127const Symbol *GetHostSymbol(const Symbol &sym);
128
129// Could a value of type "actual" be passed to a function taking the type
130// of "formal". This is not symmetric.
131bool IsTypeCompatible(const DeclTypeSpec &formal, const DeclTypeSpec &actual);
132
133// Resolve a user-defined reduction visible in scope under the mangled name
134// mangledName (e.g. "op.myop." for operator(.myop.), or a named reduction).
135// Follows USE associations, operator renames, private visibility, and merged
136// generics exactly as the OpenMP semantic checks do, returning the found
137// (non-ultimate) reduction symbol, or null if none is visible. When type is
138// non-null, only a reduction that supports that type is accepted (used to
139// disambiguate an operator that carries reductions for several types). When
140// ambiguous is non-null, it is set true if more than one distinct reduction
141// supports the type (an operator merged from several modules that each declare
142// a reduction for it, or a mangled reduction name that collides across
143// modules).
144const Symbol *FindUserReductionSymbol(const Scope &scope,
145 const parser::CharBlock &mangledName, const DeclTypeSpec *type = nullptr,
146 bool *ambiguous = nullptr);
147
148// Resolve the user-defined reduction associated with the defined-operator
149// symbol operatorSym. Delegates to FindUserReductionSymbol from scope (the
150// scope where the reduction clause appears) with the operator's mangled
151// ("op...") name. Searching from the clause scope, not the operator's owning
152// scope, finds a reduction that is local, host-, or use-associated there (a
153// reduction may be declared in a contained procedure that host-associates the
154// operator from an enclosing module). type filters by supported type as above.
155const Symbol *FindOperatorUserReductionSymbol(const Scope &scope,
156 const Symbol &operatorSym, const DeclTypeSpec *type = nullptr);
157
158bool IsMapEnteringType(parser::OmpMapType::Value type);
159bool IsMapExitingType(parser::OmpMapType::Value type);
160
161// Returns true if the symbol has a temporary stack-allocated descriptor.
162// This includes assumed-shape and assumed-rank dummy arguments that are
163// not allocatable or pointer. These descriptors are created on the caller's
164// stack and become invalid after the function returns.
165bool HasTemporaryStackDescriptor(const Symbol &symbol);
166
167MaybeExpr GetEvaluateExpr(const parser::Expr &parserExpr);
168template <typename T> MaybeExpr GetEvaluateExpr(const T &inp) {
169 return GetEvaluateExpr(parser::UnwrapRef<parser::Expr>(inp));
170}
171
172std::optional<evaluate::DynamicType> GetDynamicType(
173 const parser::Expr &parserExpr);
174
175std::optional<bool> GetLogicalValue(const SomeExpr &expr);
176std::optional<int64_t> GetIntValueFromExpr(
177 const parser::Expr &parserExpr, SemanticsContext *semaCtx = nullptr);
178
179template <typename T>
180std::optional<int64_t> GetIntValueFromExpr(
181 const T &wrappedExpr, SemanticsContext *semaCtx = nullptr) {
182 if (auto *parserExpr{parser::Unwrap<parser::Expr>(wrappedExpr)}) {
183 return GetIntValueFromExpr(*parserExpr, semaCtx);
184 }
185 return std::nullopt;
186}
187
188// There are several clauses that take an optional, compile-time
189// constant bool argument. Those clauses are stored as std::optional, e.g.
190// OmpClause::ReverseOffload -> std::optional<OmpReverseOffloadClause>.
191// Retrieve the logical value if present.
192template <typename ClauseTy>
193std::optional<bool> GetLogicalArgument(
194 const std::optional<ClauseTy> &maybeClause, SemanticsContext &semaCtx) {
195 if (maybeClause) {
196 // Scalar<Logical<Constant<common::Indirection<Expr>>>>
197 auto &parserExpr{parser::UnwrapRef<parser::Expr>(*maybeClause)};
198 evaluate::ExpressionAnalyzer ea{semaCtx};
199 if (auto &&maybeExpr{ea.Analyze(parserExpr)}) {
200 if (auto v{GetLogicalValue(*maybeExpr)}) {
201 return *v;
202 }
203 }
204 }
205 return std::nullopt;
206}
207
208std::optional<bool> IsContiguous(
209 SemanticsContext &semaCtx, const parser::OmpObject &object);
210
213 const parser::ScalarExpr *expr;
214 parser::CharBlock source;
215};
216
221enum class UnsupportedSelectorFeature {
222 None,
224 TargetDevice,
228 ClauseOrExtensionProperty,
229};
230
234UnsupportedSelectorFeature FindUnsupportedSelectorFeature(
236 SemanticsContext &semaCtx);
237
246std::optional<DynamicUserCondition> MakeVariantMatchInfo(
247 llvm::omp::VariantMatchInfo &vmi,
249 SemanticsContext &semaCtx);
250
254class OmpVariantMatchContext : public llvm::omp::OMPContext {
255public:
256 OmpVariantMatchContext(bool isDeviceCompilation, llvm::Triple targetTriple,
257 llvm::Triple targetOffloadTriple, std::string targetFeatures,
258 llvm::ArrayRef<llvm::omp::TraitProperty> constructTraits = {});
259 OmpVariantMatchContext(const SemanticsContext &context,
260 llvm::ArrayRef<llvm::omp::TraitProperty> constructTraits = {});
261 bool matchesISATrait(llvm::StringRef rawString) const override;
262
263private:
264 std::string features_;
265};
266
267struct MetadirectiveCandidate {
268 MetadirectiveCandidate(const parser::OmpDirectiveSpecification *spec,
269 llvm::omp::VariantMatchInfo vmi, bool isExplicit,
270 std::optional<DynamicUserCondition> dynamicCondition = std::nullopt,
271 bool conditionShouldBeTrue = true)
272 : spec{spec}, vmi{std::move(vmi)}, isExplicit{isExplicit},
273 dynamicCondition{dynamicCondition},
274 conditionShouldBeTrue{conditionShouldBeTrue} {}
275
276 const parser::OmpDirectiveSpecification *spec{nullptr};
277 llvm::omp::VariantMatchInfo vmi;
278 bool isExplicit{false};
279 std::optional<DynamicUserCondition> dynamicCondition;
280 bool conditionShouldBeTrue{true};
281};
282
288
289const parser::OmpContextSelector *GetContextSelector(
290 const parser::OmpClause &clause);
291const parser::OmpDirectiveSpecification *GetDirectiveVariant(
292 const parser::OmpClause &clause);
293
298std::optional<MetadirectiveCandidateSet> BuildMetadirectiveCandidateSet(
299 const parser::OmpClauseList &clauses, SemanticsContext &context,
300 const OmpVariantMatchContext &matchContext);
301
302std::optional<unsigned> SelectBestMetadirectiveCandidate(
303 llvm::ArrayRef<unsigned> candidateIndices,
305 const OmpVariantMatchContext &matchContext);
306
309bool IsRepeatableMetadirectiveCondition(
310 const parser::ScalarExpr &condition, SemanticsContext &context);
311
313bool AreSameRepeatableMetadirectiveCondition(const parser::ScalarExpr &left,
314 const parser::ScalarExpr &right, SemanticsContext &context);
315
318llvm::SmallVector<unsigned, 4> GetMetadirectiveElsePathCandidates(
319 unsigned selectedIndex, llvm::ArrayRef<unsigned> candidateIndices,
321 const OmpVariantMatchContext &matchContext, SemanticsContext &context);
322
326GetReachableMetadirectiveVariants(const MetadirectiveCandidateSet &candidateSet,
327 const OmpVariantMatchContext &matchContext, SemanticsContext &context);
328
335bool MayVariantBeSelected(
337 SemanticsContext &context, OmpVariantMatchContext &matchContext);
338
339std::vector<SomeExpr> GetTopLevelDesignators(const SomeExpr &expr);
340const SomeExpr *HasStorageOverlap(
341 const SomeExpr &base, llvm::ArrayRef<SomeExpr> exprs);
342
343bool IsAssignment(const parser::ActionStmt *x);
344bool IsPointerAssignment(const evaluate::Assignment &x);
345
346MaybeExpr MakeEvaluateExpr(const parser::OmpStylizedInstance &inp);
347
348enum struct ListItemKind : uint32_t {
349 Depend,
350 DirectiveName,
351 DirectiveSpecification,
352 Extended,
353 IntegerExpression,
354 Interop,
355 Locator,
356 Operation,
357 Parameter,
358 ProcedureArgument,
359 Variable,
360};
361
362std::optional<ListItemKind> GetArgumentListItemKind(
363 llvm::omp::Clause clause, llvm::omp::Version version);
364
365bool IsLoopTransforming(llvm::omp::Directive dir);
366bool HasDataEnvironment(llvm::omp::Directive dir);
367
368bool IsFullUnroll(const parser::OmpDirectiveSpecification &spec);
369
374 parser::OmpAtClause::ActionTime at{
375 parser::OmpAtClause::ActionTime::Compilation};
376 parser::OmpSeverityClause::SevLevel severity{
377 parser::OmpSeverityClause::SevLevel::Fatal};
378 const parser::Expr *message{nullptr};
379};
380
383OmpErrorArgs GetErrorDirectiveArgs(
385OmpErrorArgs GetErrorDirectiveArgs(const parser::OmpErrorDirective &errDir);
386
387inline bool IsDoConcurrentLegal(llvm::omp::Version version) {
388 // DO CONCURRENT is allowed (as an alternative to a Canonical Loop Nest)
389 // in OpenMP 6.0+.
390 return version >= 60;
391}
392
393struct LoopControl {
394 LoopControl(LoopControl &&x) = default;
395 LoopControl(const LoopControl &x) = default;
396 LoopControl(const parser::LoopControl::Bounds &x);
397 LoopControl(const parser::ConcurrentControl &x);
398
399 const parser::Name &iv;
400 parser::omp::WithSource<MaybeExpr> lbound, ubound, step;
401
402private:
403 static parser::omp::WithSource<MaybeExpr> fromParserExpr(
404 const parser::Expr &x);
405};
406
407std::vector<LoopControl> GetLoopControls(const parser::DoConstruct &x);
408
410struct Reason {
411 Reason() = default;
412 Reason(Reason &&) = default;
413 Reason(const Reason &);
414 Reason &operator=(Reason &&) = default;
415 Reason &operator=(const Reason &);
416
417 parser::Messages msgs;
418
419 template <typename... Ts> Reason &Say(Ts &&...args) {
420 msgs.Say(std::forward<Ts>(args)...);
421 return *this;
422 }
423 parser::Message &AttachTo(parser::Message &msg);
424 Reason &Append(const Reason &other) {
425 CopyFrom(other);
426 return *this;
427 }
428 operator bool() const { return !msgs.empty(); }
429
430private:
431 void CopyFrom(const Reason &other);
432};
433
434// A property with an explanation of its value. Both, the property and the
435// reason are optional (the reason can have no messages in it).
436template <typename T> struct WithReason {
437 std::optional<T> value;
438 Reason reason;
439
440 WithReason() = default;
441 WithReason(std::optional<T> v, const Reason &r = Reason())
442 : value(v), reason(r) {}
443 operator bool() const { return value.has_value(); }
444};
445
446WithReason<int64_t> GetArgumentValueWithReason(
447 const parser::OmpDirectiveSpecification &spec, llvm::omp::Clause clauseId,
448 llvm::omp::Version version, SemanticsContext *semaCtx = nullptr);
449WithReason<int64_t> GetNumArgumentsWithReason(
450 const parser::OmpDirectiveSpecification &spec, llvm::omp::Clause clauseId,
451 llvm::omp::Version version, SemanticsContext *semaCtx = nullptr);
452WithReason<int64_t> GetHeightWithReason(
453 const parser::OmpDirectiveSpecification &spec, llvm::omp::Version version,
454 SemanticsContext *semaCtx = nullptr);
455
458std::pair<WithReason<int64_t>, bool> GetAffectedNestDepthWithReason(
459 const parser::OmpDirectiveSpecification &spec, llvm::omp::Version version,
460 SemanticsContext *semaCtx = nullptr);
463std::pair<WithReason<int64_t>, bool> GetGeneratedNestDepthWithReason(
464 const parser::OmpDirectiveSpecification &spec, llvm::omp::Version version,
465 SemanticsContext *semaCtx = nullptr);
469WithReason<std::pair<int64_t, int64_t>> GetAffectedLoopRangeWithReason(
470 const parser::OmpDirectiveSpecification &spec, llvm::omp::Version version,
471 SemanticsContext *semaCtx = nullptr);
473WithReason<int64_t> GetRectangularNestDepthWithReason(
474 const parser::OmpDirectiveSpecification &spec, llvm::omp::Version version,
475 SemanticsContext *semaCtx = nullptr);
476
480std::optional<int64_t> GetMinimumSequenceCount(
481 std::optional<int64_t> first, std::optional<int64_t> count);
482std::optional<int64_t> GetMinimumSequenceCount(
483 std::optional<std::pair<int64_t, int64_t>> range);
484
490std::optional<std::vector<const parser::DoConstruct *>> CollectAffectedDoLoops(
491 const parser::OpenMPLoopConstruct &x, llvm::omp::Version version,
492 SemanticsContext *semaCtx = nullptr);
493
498bool IsDoacrossAffected(const parser::OpenMPLoopConstruct &x);
499
500struct LoopSequence {
501 LoopSequence(const parser::ExecutionPartConstruct &root,
502 llvm::omp::Version version, bool allowAllLoops = false,
503 SemanticsContext *semaCtx = nullptr);
504
505 template <typename R, typename = std::enable_if_t<is_range_v<R>>>
506 LoopSequence(const R &range, llvm::omp::Version version,
507 bool allowAllLoops = false, SemanticsContext *semaCtx = nullptr)
508 : version_(version), allowAllLoops_(allowAllLoops), semaCtx_(semaCtx) {
509 entry_ = std::make_unique<Construct>(range, nullptr);
510 createChildrenFromRange(entry_->location);
511 precalculate();
512 }
513
514 struct Depth {
515 // If this sequence is a nest, the depth of the Canonical Loop Nest rooted
516 // at this sequence. Otherwise unspecified.
517 WithReason<int64_t> semantic;
518 // If this sequence is a nest, the depth of the perfect Canonical Loop Nest
519 // rooted at this sequence. Otherwise unspecified.
520 WithReason<int64_t> perfect;
521 };
522
523 bool isNest() const { return length_.value == 1; }
524 const WithReason<int64_t> &length() const { return length_; }
525 const WithReason<int64_t> &height() const { return height_; }
526 const Depth &depth() const { return depth_; }
527 const std::vector<LoopSequence> &children() const { return children_; }
528 const parser::ExecutionPartConstruct *owner() const { return entry_->owner; }
529
530 WithReason<bool> isWellFormedSequence() const;
531 WithReason<bool> isWellFormedNest() const;
532
535 const LoopSequence *getNestedDoConcurrent() const;
536
537 std::vector<LoopControl> getLoopControls() const;
538 // Check if this loop's bounds are invariant in each of the `outer`
539 // constructs.
540 WithReason<bool> isRectangular(
541 const std::vector<const LoopSequence *> &outer) const;
542
543private:
544 using Construct = ExecutionPartIterator::Construct;
545
546 LoopSequence(std::unique_ptr<Construct> entry, llvm::omp::Version version,
547 bool allowAllLoops, SemanticsContext *semaCtx = nullptr);
548
549 template <typename R, typename = std::enable_if_t<is_range_v<R>>>
550 void createChildrenFromRange(const R &range) {
551 createChildrenFromRange(range.begin(), range.end());
552 }
553
554 std::unique_ptr<Construct> createConstructEntry(
555 const parser::ExecutionPartConstruct &code);
556
557 void createChildrenFromRange( //
558 ExecutionPartIterator::IteratorType begin,
559 ExecutionPartIterator::IteratorType end);
560
562 void precalculate();
563
564 WithReason<int64_t> calculateLength() const;
565 WithReason<int64_t> getNestedLength() const;
566 Depth calculateDepths() const;
567 Depth getNestedDepths() const;
568 WithReason<int64_t> calculateHeight() const;
569
573 const parser::ExecutionPartConstruct *invalidIC_{nullptr};
577 const parser::ExecutionPartConstruct *opaqueIC_{nullptr};
578
583 WithReason<int64_t> length_;
585 Depth depth_;
592 WithReason<int64_t> height_;
593
594 // The core structure of the class:
595 llvm::omp::Version version_; // Needed for GetXyzWithReason
596 bool allowAllLoops_;
597 std::unique_ptr<Construct> entry_;
598 std::vector<LoopSequence> children_;
599 SemanticsContext *semaCtx_{nullptr};
600};
601
602// ---------------------------------------------------------------------------
603// Trait-matching helpers shared between metadirective lowering and
604// declare-variant semantic recording.
605// ---------------------------------------------------------------------------
606
608llvm::omp::TraitSet MapTraitSet(parser::OmpTraitSetSelectorName::Value name);
609
612llvm::omp::TraitSelector MapTraitSelector(
613 const parser::OmpTraitSelectorName &name, llvm::omp::TraitSet set);
614
616std::optional<bool> EvaluateUserCondition(
617 SemanticsContext &semaCtx, const parser::ScalarExpr &scalarExpr);
618
620llvm::APInt *GetTraitScore(
621 const std::optional<parser::OmpTraitSelector::Properties> &props,
622 SemanticsContext &semaCtx, std::optional<llvm::APInt> &scoreStorage);
623
627void ProcessTraitProperties(llvm::omp::VariantMatchInfo &vmi,
628 llvm::omp::TraitSet set, llvm::omp::TraitSelector selector,
629 const std::optional<parser::OmpTraitSelector::Properties> &props,
630 llvm::APInt *scorePtr);
631
632} // namespace omp
633} // namespace Fortran::semantics
634
635#endif // FORTRAN_SEMANTICS_OPENMP_UTILS_H
Definition expression.h:960
Definition char-block.h:27
Definition message.h:202
Definition message.h:334
Definition scope.h:68
Definition semantics.h:71
Definition symbol.h:911
Definition FIRType.h:106
Definition OpenACC.h:20
Definition parse-tree.h:501
Definition parse-tree.h:2292
Definition parse-tree.h:2379
Definition parse-tree.h:559
Definition parse-tree.h:1749
Definition parse-tree.h:592
Definition parse-tree.h:5298
Definition parse-tree.h:5282
Definition parse-tree.h:5305
Definition parse-tree.h:5372
Definition parse-tree.h:3642
Definition parse-tree.h:3667
Definition parse-tree.h:5678
Definition parse-tree.h:3765
Definition openmp-utils.h:114
Non-constant user condition expression and source for runtime lowering.
Definition openmp-utils.h:212
const LoopSequence * getNestedDoConcurrent() const
Definition openmp-utils.cpp:1897
const parser::OmpDirectiveSpecification * fallback
Null represents either a clause-free NOTHING fallback or no fallback.
Definition openmp-utils.h:286
Definition openmp-utils.h:373
A representation of a "because" message.
Definition openmp-utils.h:410
Definition openmp-utils.h:58
Definition openmp-utils.h:83
Definition openmp-utils.h:436