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 IsWholeAssumedSizeArray(const parser::OmpObject &object);
110
111bool IsExtendedListItem(
112 const parser::OmpObject &object, SemanticsContext *semaCtx);
113bool IsLocatorListItem(
114 const parser::OmpObject &object, SemanticsContext *semaCtx);
115bool IsVariableListItem(
116 const parser::OmpObject &object, SemanticsContext *semaCtx);
117
118// Analyzes potential substrings and retains diagnostics; may modify semantic
119// state and the parse tree. A missing result indicates an invalid designator,
120// already diagnosed.
121std::optional<bool> IsSubstringAndValidate(
122 const parser::OmpObject &object, SemanticsContext *semaCtx);
123bool IsArrayElement(const parser::OmpObject &object, SemanticsContext *semaCtx);
124
125const Symbol *GetHostSymbol(const Symbol &sym);
126
127// Resolve a user-defined reduction visible in scope under the mangled name
128// mangledName (e.g. "op.myop." for operator(.myop.), or a named reduction).
129// Follows USE associations, operator renames, private visibility, and merged
130// generics exactly as the OpenMP semantic checks do, returning the found
131// (non-ultimate) reduction symbol, or null if none is visible. When type is
132// non-null, only a reduction that supports that type is accepted (used to
133// disambiguate an operator that carries reductions for several types). When
134// ambiguous is non-null, it is set true if more than one distinct reduction
135// supports the type (an operator merged from several modules that each declare
136// a reduction for it, or a mangled reduction name that collides across
137// modules).
138const Symbol *FindUserReductionSymbol(const Scope &scope,
139 const parser::CharBlock &mangledName, const DeclTypeSpec *type = nullptr,
140 bool *ambiguous = nullptr);
141
142// Resolve the user-defined reduction associated with the defined-operator
143// symbol operatorSym. Delegates to FindUserReductionSymbol from scope (the
144// scope where the reduction clause appears) with the operator's mangled
145// ("op...") name. Searching from the clause scope, not the operator's owning
146// scope, finds a reduction that is local, host-, or use-associated there (a
147// reduction may be declared in a contained procedure that host-associates the
148// operator from an enclosing module). type filters by supported type as above.
149const Symbol *FindOperatorUserReductionSymbol(const Scope &scope,
150 const Symbol &operatorSym, const DeclTypeSpec *type = nullptr);
151
152bool IsMapEnteringType(parser::OmpMapType::Value type);
153bool IsMapExitingType(parser::OmpMapType::Value type);
154
155// Returns true if the symbol has a temporary stack-allocated descriptor.
156// This includes assumed-shape and assumed-rank dummy arguments that are
157// not allocatable or pointer. These descriptors are created on the caller's
158// stack and become invalid after the function returns.
159bool HasTemporaryStackDescriptor(const Symbol &symbol);
160
161MaybeExpr GetEvaluateExpr(const parser::Expr &parserExpr);
162template <typename T> MaybeExpr GetEvaluateExpr(const T &inp) {
163 return GetEvaluateExpr(parser::UnwrapRef<parser::Expr>(inp));
164}
165
166std::optional<evaluate::DynamicType> GetDynamicType(
167 const parser::Expr &parserExpr);
168
169std::optional<bool> GetLogicalValue(const SomeExpr &expr);
170std::optional<int64_t> GetIntValueFromExpr(
171 const parser::Expr &parserExpr, SemanticsContext *semaCtx = nullptr);
172
173template <typename T>
174std::optional<int64_t> GetIntValueFromExpr(
175 const T &wrappedExpr, SemanticsContext *semaCtx = nullptr) {
176 if (auto *parserExpr{parser::Unwrap<parser::Expr>(wrappedExpr)}) {
177 return GetIntValueFromExpr(*parserExpr, semaCtx);
178 }
179 return std::nullopt;
180}
181
182// There are several clauses that take an optional, compile-time
183// constant bool argument. Those clauses are stored as std::optional, e.g.
184// OmpClause::ReverseOffload -> std::optional<OmpReverseOffloadClause>.
185// Retrieve the logical value if present.
186template <typename ClauseTy>
187std::optional<bool> GetLogicalArgument(
188 const std::optional<ClauseTy> &maybeClause, SemanticsContext &semaCtx) {
189 if (maybeClause) {
190 // Scalar<Logical<Constant<common::Indirection<Expr>>>>
191 auto &parserExpr{parser::UnwrapRef<parser::Expr>(*maybeClause)};
192 evaluate::ExpressionAnalyzer ea{semaCtx};
193 if (auto &&maybeExpr{ea.Analyze(parserExpr)}) {
194 if (auto v{GetLogicalValue(*maybeExpr)}) {
195 return *v;
196 }
197 }
198 }
199 return std::nullopt;
200}
201
202std::optional<bool> IsContiguous(
203 SemanticsContext &semaCtx, const parser::OmpObject &object);
204
207 const parser::ScalarExpr *expr;
208 parser::CharBlock source;
209};
210
215enum class UnsupportedSelectorFeature {
216 None,
218 TargetDevice,
222 ClauseOrExtensionProperty,
223};
224
228UnsupportedSelectorFeature FindUnsupportedSelectorFeature(
230 SemanticsContext &semaCtx);
231
240std::optional<DynamicUserCondition> MakeVariantMatchInfo(
241 llvm::omp::VariantMatchInfo &vmi,
243 SemanticsContext &semaCtx);
244
248class OmpVariantMatchContext : public llvm::omp::OMPContext {
249public:
250 OmpVariantMatchContext(bool isDeviceCompilation, llvm::Triple targetTriple,
251 llvm::Triple targetOffloadTriple, std::string targetFeatures,
252 llvm::ArrayRef<llvm::omp::TraitProperty> constructTraits = {});
253 OmpVariantMatchContext(const SemanticsContext &context,
254 llvm::ArrayRef<llvm::omp::TraitProperty> constructTraits = {});
255 bool matchesISATrait(llvm::StringRef rawString) const override;
256
257private:
258 std::string features_;
259};
260
261struct MetadirectiveCandidate {
262 MetadirectiveCandidate(const parser::OmpDirectiveSpecification *spec,
263 llvm::omp::VariantMatchInfo vmi, bool isExplicit,
264 std::optional<DynamicUserCondition> dynamicCondition = std::nullopt,
265 bool conditionShouldBeTrue = true)
266 : spec{spec}, vmi{std::move(vmi)}, isExplicit{isExplicit},
267 dynamicCondition{dynamicCondition},
268 conditionShouldBeTrue{conditionShouldBeTrue} {}
269
270 const parser::OmpDirectiveSpecification *spec{nullptr};
271 llvm::omp::VariantMatchInfo vmi;
272 bool isExplicit{false};
273 std::optional<DynamicUserCondition> dynamicCondition;
274 bool conditionShouldBeTrue{true};
275};
276
282
287std::optional<MetadirectiveCandidateSet> BuildMetadirectiveCandidateSet(
288 const parser::OmpClauseList &clauses, SemanticsContext &context,
289 const OmpVariantMatchContext &matchContext);
290
291std::optional<unsigned> SelectBestMetadirectiveCandidate(
292 llvm::ArrayRef<unsigned> candidateIndices,
294 const OmpVariantMatchContext &matchContext);
295
298bool IsRepeatableMetadirectiveCondition(
299 const parser::ScalarExpr &condition, SemanticsContext &context);
300
302bool AreSameRepeatableMetadirectiveCondition(const parser::ScalarExpr &left,
303 const parser::ScalarExpr &right, SemanticsContext &context);
304
307llvm::SmallVector<unsigned, 4> GetMetadirectiveElsePathCandidates(
308 unsigned selectedIndex, llvm::ArrayRef<unsigned> candidateIndices,
310 const OmpVariantMatchContext &matchContext, SemanticsContext &context);
311
315GetReachableMetadirectiveVariants(const MetadirectiveCandidateSet &candidateSet,
316 const OmpVariantMatchContext &matchContext, SemanticsContext &context);
317
324bool MayVariantBeSelected(
326 SemanticsContext &context, OmpVariantMatchContext &matchContext);
327
328std::vector<SomeExpr> GetTopLevelDesignators(const SomeExpr &expr);
329const SomeExpr *HasStorageOverlap(
330 const SomeExpr &base, llvm::ArrayRef<SomeExpr> exprs);
331
332bool IsAssignment(const parser::ActionStmt *x);
333bool IsPointerAssignment(const evaluate::Assignment &x);
334
335MaybeExpr MakeEvaluateExpr(const parser::OmpStylizedInstance &inp);
336
337enum struct ListItemKind : uint32_t {
338 Depend,
339 DirectiveName,
340 DirectiveSpecification,
341 Extended,
342 IntegerExpression,
343 Interop,
344 Locator,
345 Operation,
346 Parameter,
347 ProcedureArgument,
348 Variable,
349};
350
351std::optional<ListItemKind> GetArgumentListItemKind(
352 llvm::omp::Clause clause, llvm::omp::Version version);
353
354bool IsLoopTransforming(llvm::omp::Directive dir);
355bool HasDataEnvironment(llvm::omp::Directive dir);
356
357bool IsFullUnroll(const parser::OmpDirectiveSpecification &spec);
358
363 parser::OmpAtClause::ActionTime at{
364 parser::OmpAtClause::ActionTime::Compilation};
365 parser::OmpSeverityClause::SevLevel severity{
366 parser::OmpSeverityClause::SevLevel::Fatal};
367 const parser::Expr *message{nullptr};
368};
369
372OmpErrorArgs GetErrorDirectiveArgs(
374OmpErrorArgs GetErrorDirectiveArgs(const parser::OmpErrorDirective &errDir);
375
376inline bool IsDoConcurrentLegal(llvm::omp::Version version) {
377 // DO CONCURRENT is allowed (as an alternative to a Canonical Loop Nest)
378 // in OpenMP 6.0+.
379 return version >= 60;
380}
381
382struct LoopControl {
383 LoopControl(LoopControl &&x) = default;
384 LoopControl(const LoopControl &x) = default;
385 LoopControl(const parser::LoopControl::Bounds &x);
386 LoopControl(const parser::ConcurrentControl &x);
387
388 const parser::Name &iv;
389 parser::omp::WithSource<MaybeExpr> lbound, ubound, step;
390
391private:
392 static parser::omp::WithSource<MaybeExpr> fromParserExpr(
393 const parser::Expr &x);
394};
395
396std::vector<LoopControl> GetLoopControls(const parser::DoConstruct &x);
397
399struct Reason {
400 Reason() = default;
401 Reason(Reason &&) = default;
402 Reason(const Reason &);
403 Reason &operator=(Reason &&) = default;
404 Reason &operator=(const Reason &);
405
406 parser::Messages msgs;
407
408 template <typename... Ts> Reason &Say(Ts &&...args) {
409 msgs.Say(std::forward<Ts>(args)...);
410 return *this;
411 }
412 parser::Message &AttachTo(parser::Message &msg);
413 Reason &Append(const Reason &other) {
414 CopyFrom(other);
415 return *this;
416 }
417 operator bool() const { return !msgs.empty(); }
418
419private:
420 void CopyFrom(const Reason &other);
421};
422
423// A property with an explanation of its value. Both, the property and the
424// reason are optional (the reason can have no messages in it).
425template <typename T> struct WithReason {
426 std::optional<T> value;
427 Reason reason;
428
429 WithReason() = default;
430 WithReason(std::optional<T> v, const Reason &r = Reason())
431 : value(v), reason(r) {}
432 operator bool() const { return value.has_value(); }
433};
434
435WithReason<int64_t> GetArgumentValueWithReason(
436 const parser::OmpDirectiveSpecification &spec, llvm::omp::Clause clauseId,
437 llvm::omp::Version version, SemanticsContext *semaCtx = nullptr);
438WithReason<int64_t> GetNumArgumentsWithReason(
439 const parser::OmpDirectiveSpecification &spec, llvm::omp::Clause clauseId,
440 llvm::omp::Version version, SemanticsContext *semaCtx = nullptr);
441WithReason<int64_t> GetHeightWithReason(
442 const parser::OmpDirectiveSpecification &spec, llvm::omp::Version version,
443 SemanticsContext *semaCtx = nullptr);
444
447std::pair<WithReason<int64_t>, bool> GetAffectedNestDepthWithReason(
448 const parser::OmpDirectiveSpecification &spec, llvm::omp::Version version,
449 SemanticsContext *semaCtx = nullptr);
452std::pair<WithReason<int64_t>, bool> GetGeneratedNestDepthWithReason(
453 const parser::OmpDirectiveSpecification &spec, llvm::omp::Version version,
454 SemanticsContext *semaCtx = nullptr);
458WithReason<std::pair<int64_t, int64_t>> GetAffectedLoopRangeWithReason(
459 const parser::OmpDirectiveSpecification &spec, llvm::omp::Version version,
460 SemanticsContext *semaCtx = nullptr);
462WithReason<int64_t> GetRectangularNestDepthWithReason(
463 const parser::OmpDirectiveSpecification &spec, llvm::omp::Version version,
464 SemanticsContext *semaCtx = nullptr);
465
469std::optional<int64_t> GetMinimumSequenceCount(
470 std::optional<int64_t> first, std::optional<int64_t> count);
471std::optional<int64_t> GetMinimumSequenceCount(
472 std::optional<std::pair<int64_t, int64_t>> range);
473
479std::optional<std::vector<const parser::DoConstruct *>> CollectAffectedDoLoops(
480 const parser::OpenMPLoopConstruct &x, llvm::omp::Version version,
481 SemanticsContext *semaCtx = nullptr);
482
487bool IsDoacrossAffected(const parser::OpenMPLoopConstruct &x);
488
489struct LoopSequence {
490 LoopSequence(const parser::ExecutionPartConstruct &root,
491 llvm::omp::Version version, bool allowAllLoops = false,
492 SemanticsContext *semaCtx = nullptr);
493
494 template <typename R, typename = std::enable_if_t<is_range_v<R>>>
495 LoopSequence(const R &range, llvm::omp::Version version,
496 bool allowAllLoops = false, SemanticsContext *semaCtx = nullptr)
497 : version_(version), allowAllLoops_(allowAllLoops), semaCtx_(semaCtx) {
498 entry_ = std::make_unique<Construct>(range, nullptr);
499 createChildrenFromRange(entry_->location);
500 precalculate();
501 }
502
503 struct Depth {
504 // If this sequence is a nest, the depth of the Canonical Loop Nest rooted
505 // at this sequence. Otherwise unspecified.
506 WithReason<int64_t> semantic;
507 // If this sequence is a nest, the depth of the perfect Canonical Loop Nest
508 // rooted at this sequence. Otherwise unspecified.
509 WithReason<int64_t> perfect;
510 };
511
512 bool isNest() const { return length_.value == 1; }
513 const WithReason<int64_t> &length() const { return length_; }
514 const WithReason<int64_t> &height() const { return height_; }
515 const Depth &depth() const { return depth_; }
516 const std::vector<LoopSequence> &children() const { return children_; }
517 const parser::ExecutionPartConstruct *owner() const { return entry_->owner; }
518
519 WithReason<bool> isWellFormedSequence() const;
520 WithReason<bool> isWellFormedNest() const;
521
524 const LoopSequence *getNestedDoConcurrent() const;
525
526 std::vector<LoopControl> getLoopControls() const;
527 // Check if this loop's bounds are invariant in each of the `outer`
528 // constructs.
529 WithReason<bool> isRectangular(
530 const std::vector<const LoopSequence *> &outer) const;
531
532private:
533 using Construct = ExecutionPartIterator::Construct;
534
535 LoopSequence(std::unique_ptr<Construct> entry, llvm::omp::Version version,
536 bool allowAllLoops, SemanticsContext *semaCtx = nullptr);
537
538 template <typename R, typename = std::enable_if_t<is_range_v<R>>>
539 void createChildrenFromRange(const R &range) {
540 createChildrenFromRange(range.begin(), range.end());
541 }
542
543 std::unique_ptr<Construct> createConstructEntry(
544 const parser::ExecutionPartConstruct &code);
545
546 void createChildrenFromRange( //
547 ExecutionPartIterator::IteratorType begin,
548 ExecutionPartIterator::IteratorType end);
549
551 void precalculate();
552
553 WithReason<int64_t> calculateLength() const;
554 WithReason<int64_t> getNestedLength() const;
555 Depth calculateDepths() const;
556 Depth getNestedDepths() const;
557 WithReason<int64_t> calculateHeight() const;
558
562 const parser::ExecutionPartConstruct *invalidIC_{nullptr};
566 const parser::ExecutionPartConstruct *opaqueIC_{nullptr};
567
572 WithReason<int64_t> length_;
574 Depth depth_;
581 WithReason<int64_t> height_;
582
583 // The core structure of the class:
584 llvm::omp::Version version_; // Needed for GetXyzWithReason
585 bool allowAllLoops_;
586 std::unique_ptr<Construct> entry_;
587 std::vector<LoopSequence> children_;
588 SemanticsContext *semaCtx_{nullptr};
589};
590
591// ---------------------------------------------------------------------------
592// Trait-matching helpers shared between metadirective lowering and
593// declare-variant semantic recording.
594// ---------------------------------------------------------------------------
595
597llvm::omp::TraitSet MapTraitSet(parser::OmpTraitSetSelectorName::Value name);
598
601llvm::omp::TraitSelector MapTraitSelector(
602 const parser::OmpTraitSelectorName &name, llvm::omp::TraitSet set);
603
605std::optional<bool> EvaluateUserCondition(
606 SemanticsContext &semaCtx, const parser::ScalarExpr &scalarExpr);
607
609llvm::APInt *GetTraitScore(
610 const std::optional<parser::OmpTraitSelector::Properties> &props,
611 SemanticsContext &semaCtx, std::optional<llvm::APInt> &scoreStorage);
612
616void ProcessTraitProperties(llvm::omp::VariantMatchInfo &vmi,
617 llvm::omp::TraitSet set, llvm::omp::TraitSelector selector,
618 const std::optional<parser::OmpTraitSelector::Properties> &props,
619 llvm::APInt *scorePtr);
620
621} // namespace omp
622} // namespace Fortran::semantics
623
624#endif // FORTRAN_SEMANTICS_OPENMP_UTILS_H
Definition expression.h:923
Definition char-block.h:27
Definition message.h:202
Definition message.h:334
Definition scope.h:68
Definition semantics.h:71
Definition symbol.h:916
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:5287
Definition parse-tree.h:5294
Definition parse-tree.h:5361
Definition parse-tree.h:3634
Definition parse-tree.h:3659
Definition parse-tree.h:5667
Definition parse-tree.h:3757
Definition openmp-utils.h:113
Non-constant user condition expression and source for runtime lowering.
Definition openmp-utils.h:206
const LoopSequence * getNestedDoConcurrent() const
Definition openmp-utils.cpp:1874
const parser::OmpDirectiveSpecification * fallback
Null represents either a clause-free NOTHING fallback or no fallback.
Definition openmp-utils.h:280
Definition openmp-utils.h:362
A representation of a "because" message.
Definition openmp-utils.h:399
Definition openmp-utils.h:58
Definition openmp-utils.h:83
Definition openmp-utils.h:425