MLIR 24.0.0git
OpenACCUtils.h
Go to the documentation of this file.
1//===- OpenACCUtils.h - OpenACC Utilities -----------------------*- C++ -*-===//
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#ifndef MLIR_DIALECT_OPENACC_OPENACCUTILS_H_
10#define MLIR_DIALECT_OPENACC_OPENACCUTILS_H_
11
14#include "mlir/IR/Diagnostics.h"
15#include "mlir/IR/Remarks.h"
16#include "llvm/ADT/SmallVector.h"
17#include "llvm/ADT/StringRef.h"
18#include "llvm/ADT/Twine.h"
19#include <optional>
20#include <string>
21
22namespace mlir {
23class DominanceInfo;
25namespace acc {
26
27/// Used to obtain the enclosing compute construct operation that contains
28/// the provided `region`. Returns nullptr if no compute construct operation
29/// is found. The returned operation is one of types defined by
30/// `ACC_COMPUTE_CONSTRUCT_OPS`.
31mlir::Operation *getEnclosingComputeOp(mlir::Region &region);
32
33/// If `v` is not a block argument of an `acc.compute_region` body, returns
34/// nullptr. Otherwise maps the block argument to its operand and returns it.
35mlir::Value getACCOperandForBlockArg(mlir::Value v);
36
37/// If `operand` is a `launch` or `ins` operand of an `acc.compute_region`,
38/// returns the body block argument it is threaded to; otherwise nullptr.
39/// Unlike `ComputeRegionOp::getBlockArg`, duplicate operands are distinguished.
40mlir::BlockArgument getACCBlockArgForOperand(mlir::OpOperand &operand);
41
42/// If `v` is not a block argument of an `acc.compute_region` body, returns
43/// nullptr. Otherwise maps the block argument to its operand and returns the
44/// defining operation if it is one of `ACC_DATA_ENTRY_OPS`.
45mlir::Operation *getACCDataClauseOpForBlockArg(mlir::Value v);
46
47/// Returns true if this value is only used by `acc.private` operations in the
48/// `region`.
49bool isOnlyUsedByPrivateClauses(mlir::Value val, mlir::Region &region);
50
51/// Returns true if this value is only used by `acc.reduction` operations in
52/// the `region`.
53bool isOnlyUsedByReductionClauses(mlir::Value val, mlir::Region &region);
54
55/// Looks for an OpenACC default attribute on the current operation `op` or in
56/// a parent operation which encloses `op`. This is useful because OpenACC
57/// specification notes that a visible default clause is the nearest default
58/// clause appearing on the compute construct or a lexically containing data
59/// construct.
60std::optional<ClauseDefaultValue> getDefaultAttr(mlir::Operation *op);
61
62/// Get the type category of an OpenACC variable.
63mlir::acc::VariableTypeCategory getTypeCategory(mlir::Value var);
64
65/// Attempts to extract the variable name from a value by walking through
66/// view-like operations until an `acc.var_name` attribute, the name of a data
67/// clause operation, or the symbol a global is addressed through is found.
68/// Returns empty string if no name is found.
69std::string getVariableName(mlir::Value v);
70
71/// Returns a placeholder string for use as an acc.var_name attribute value when
72/// the actual variable name is not yet known at the point of IR construction.
73/// The placeholder is meant to be replaced with the real name at a later
74/// lowering stage.
75/// For example, recipe init regions may attach this to ops at recipe-generation
76/// time, and ACCRecipeMaterialization will subsequently replace the placeholder
77/// with the actual variable name on all marked ops after inlining the recipe
78/// into the compute construct.
79llvm::StringLiteral getVarNamePlaceholder();
80
81/// Get the recipe name for a given recipe kind and type.
82/// Returns an empty string if not possible to generate a recipe name.
83std::string getRecipeName(mlir::acc::RecipeKind kind, mlir::Type type);
84
85// Get the base entity from partial entity access. This is used for getting
86// the base `struct` from an operation that only accesses a field or the
87// base `array` from an operation that only accesses a subarray.
88mlir::Value getBaseEntity(mlir::Value val);
89
90/// Check if a symbol use is valid for use in an OpenACC region.
91/// This includes looking for various attributes such as `acc.routine_info`
92/// and `acc.declare` attributes.
93/// \param user The operation using the symbol
94/// \param symbol The symbol reference being used
95/// \param definingOpPtr Optional output parameter to receive the defining op
96/// \return true if the symbol use is valid, false otherwise
97bool isValidSymbolUse(mlir::Operation *user, mlir::SymbolRefAttr symbol,
98 mlir::Operation **definingOpPtr = nullptr);
99
100/// Check if a value represents device data.
101/// This checks if the value represents device data via the
102/// MappableType, PointerLikeType, and GlobalVariableOpInterface interfaces,
103/// and whether the defining operation carries `acc.declare` with the deviceptr
104/// clause.
105/// \param val The value to check
106/// \param symbolTables Optional cache of symbol tables used to resolve global
107/// symbols. Callers that query many values should pass one: without it
108/// every lookup scans the whole module.
109/// \return true if the value is device data, false otherwise
111 mlir::Value val, mlir::SymbolTableCollection *symbolTables = nullptr);
112
113/// Check if a value is backed by memory that is residing in the current device,
114/// and therefore requires no runtime mapping or attach.
115///
116/// This is stricter than isDeviceAccessibleValue: isDeviceAccessibleValue
117/// answers device accessibility (whether the current device can reach the
118/// storage, regardless of where it physically resides), whereas this answers
119/// device residence (whether the storage physically lives in device memory).
120/// Storage that is accessible but physically shared with the host may migrate
121/// on demand, so it is not in device memory: it must still be mapped so the
122/// runtime can attach rather than be treated as already resident.
123/// \param val The value to check
124/// \param symbolTables Optional cache of symbol tables used to resolve global
125/// symbols (see isDeviceAccessibleValue).
126/// \return true if the value is in device memory, false otherwise
127bool isInDeviceMemoryValue(mlir::Value val,
128 mlir::SymbolTableCollection *symbolTables = nullptr);
129
130/// Check if a value use is valid in an OpenACC region.
131/// This is true if:
132/// - The value is produced by an ACC data entry operation
133/// - The value is device data
134/// - The value is only used by private clauses in the region
135/// \param val The value to check
136/// \param region The OpenACC region
137/// \param symbolTables Optional cache of symbol tables used to resolve global
138/// symbols (see isDeviceAccessibleValue).
139/// \return true if the value use is valid, false otherwise
140bool isValidValueUse(mlir::Value val, mlir::Region &region,
141 mlir::SymbolTableCollection *symbolTables = nullptr);
142
143/// Collects all data clauses that dominate the compute construct.
144/// This includes data clauses from:
145/// - The compute construct itself
146/// - Enclosing data constructs
147/// - Applicable declare directives (those that dominate and post-dominate)
148/// This is used to determine if a variable is already covered by an existing
149/// data clause.
150/// \param computeConstructOp The compute construct operation
151/// \param domInfo Dominance information
152/// \param postDomInfo Post-dominance information
153/// \return Vector of data clause values that dominate the compute construct
154llvm::SmallVector<mlir::Value>
155getDominatingDataClauses(mlir::Operation *computeConstructOp,
156 mlir::DominanceInfo &domInfo,
157 mlir::PostDominanceInfo &postDomInfo);
158
159/// Returns true if `op` is in a branch that does not execute on the target.
160/// `deviceTypes` lists the `acc_device_t` values for which `acc.on_device` is
161/// true. That branch is the `then` of a constant `acc.on_device` outside the
162/// list, or the `else` of one in the list. A non-constant operand is ignored.
163/// An empty list returns false.
164bool isInOffTargetBranch(mlir::Operation *op,
165 llvm::ArrayRef<int64_t> deviceTypes);
166
167/// Emit an OpenACC remark with lazy message generation.
168///
169/// The messageFn is only invoked if remarks are enabled, allowing callers
170/// to avoid constructing expensive messages when remarks are disabled.
171///
172/// \param op The operation to emit the remark for.
173/// \param messageFn A callable that returns the remark message.
174/// \param category Optional category for the remark. Defaults to "openacc".
175/// \return An in-flight remark object that can be used to append
176/// additional information to the remark.
177remark::detail::InFlightRemark
178emitRemark(mlir::Operation *op, const std::function<std::string()> &messageFn,
179 llvm::StringRef category = "openacc");
180
181/// Emit an OpenACC remark for the given operation with the given message.
182///
183/// \param op The operation to emit the remark for.
184/// \param message The remark message.
185/// \param category Optional category for the remark. Defaults to "openacc".
186/// \return An in-flight remark object that can be used to append
187/// additional information to the remark.
188inline remark::detail::InFlightRemark
189emitRemark(mlir::Operation *op, const llvm::Twine &message,
190 llvm::StringRef category = "openacc") {
191 return emitRemark(
192 op, std::function<std::string()>([msg = message.str()]() { return msg; }),
193 category);
194}
195
196/// Follow `arith.index_cast` and `arith.index_castui` to the value being cast.
198 while (mlir::isa_and_nonnull<arith::IndexCastOp, arith::IndexCastUIOp>(
199 value.getDefiningOp()))
200 value = value.getDefiningOp()->getOperand(0);
201 return value;
202}
203
204/// Return true when every gang, worker, and vector size on `op` is the
205/// constant 1.
206template <typename ComputeOpT>
207bool isGangWorkerVectorAllOne(ComputeOpT op) {
208 auto numGangs = op.getNumGangsValues();
209 if (numGangs.empty())
210 return false;
211 for (mlir::Value gangSize : numGangs) {
212 if (!mlir::isConstantIntValue(stripIndexCasts(gangSize), 1))
213 return false;
214 }
215 mlir::Value numWorkers = op.getNumWorkersValue();
216 if (!numWorkers)
217 return false;
218 mlir::Value vectorLength = op.getVectorLengthValue();
219 if (!vectorLength)
220 return false;
221 return mlir::isConstantIntValue(stripIndexCasts(numWorkers), 1) &&
223}
224} // namespace acc
225} // namespace mlir
226
227#endif // MLIR_DIALECT_OPENACC_OPENACCUTILS_H_
A class for computing basic dominance information.
Definition Dominance.h:143
Operation is the basic unit of execution within MLIR.
Definition Operation.h:87
Value getOperand(unsigned idx)
Definition Operation.h:377
A class for computing basic postdominance information.
Definition Dominance.h:207
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Definition Value.h:96
Operation * getDefiningOp() const
If this value is the result of an operation, return the operation that defines it.
Definition Value.cpp:18
mlir::acc::VariableTypeCategory getTypeCategory(mlir::Value var)
Get the type category of an OpenACC variable.
mlir::BlockArgument getACCBlockArgForOperand(mlir::OpOperand &operand)
If operand is a launch or ins operand of an acc.compute_region, returns the body block argument it is...
std::string getVariableName(mlir::Value v)
Attempts to extract the variable name from a value by walking through view-like operations until an a...
bool isValidSymbolUse(mlir::Operation *user, mlir::SymbolRefAttr symbol, mlir::Operation **definingOpPtr=nullptr)
Check if a symbol use is valid for use in an OpenACC region.
mlir::Value getACCOperandForBlockArg(mlir::Value v)
If v is not a block argument of an acc.compute_region body, returns nullptr.
mlir::Operation * getACCDataClauseOpForBlockArg(mlir::Value v)
If v is not a block argument of an acc.compute_region body, returns nullptr.
mlir::Value stripIndexCasts(mlir::Value value)
Follow arith.index_cast and arith.index_castui to the value being cast.
std::optional< ClauseDefaultValue > getDefaultAttr(mlir::Operation *op)
Looks for an OpenACC default attribute on the current operation op or in a parent operation which enc...
bool isOnlyUsedByReductionClauses(mlir::Value val, mlir::Region &region)
Returns true if this value is only used by acc.reduction operations in the region.
bool isGangWorkerVectorAllOne(ComputeOpT op)
Return true when every gang, worker, and vector size on op is the constant 1.
mlir::Operation * getEnclosingComputeOp(mlir::Region &region)
Used to obtain the enclosing compute construct operation that contains the provided region.
bool isValidValueUse(mlir::Value val, mlir::Region &region, mlir::SymbolTableCollection *symbolTables=nullptr)
Check if a value use is valid in an OpenACC region.
llvm::StringLiteral getVarNamePlaceholder()
Returns a placeholder string for use as an acc.var_name attribute value when the actual variable name...
llvm::SmallVector< mlir::Value > getDominatingDataClauses(mlir::Operation *computeConstructOp, mlir::DominanceInfo &domInfo, mlir::PostDominanceInfo &postDomInfo)
Collects all data clauses that dominate the compute construct.
bool isInDeviceMemoryValue(mlir::Value val, mlir::SymbolTableCollection *symbolTables=nullptr)
Check if a value is backed by memory that is residing in the current device, and therefore requires n...
std::string getRecipeName(mlir::acc::RecipeKind kind, mlir::Type type)
Get the recipe name for a given recipe kind and type.
remark::detail::InFlightRemark emitRemark(mlir::Operation *op, const std::function< std::string()> &messageFn, llvm::StringRef category="openacc")
Emit an OpenACC remark with lazy message generation.
bool isDeviceAccessibleValue(mlir::Value val, mlir::SymbolTableCollection *symbolTables=nullptr)
Check if a value represents device data.
bool isInOffTargetBranch(mlir::Operation *op, llvm::ArrayRef< int64_t > deviceTypes)
Returns true if op is in a branch that does not execute on the target.
mlir::Value getBaseEntity(mlir::Value val)
bool isOnlyUsedByPrivateClauses(mlir::Value val, mlir::Region &region)
Returns true if this value is only used by acc.private operations in the region.
Include the generated interface declarations.
bool isConstantIntValue(OpFoldResult ofr, int64_t value)
Return true if ofr is constant integer equal to value.