MLIR 23.0.0git
ACCImplicitData.cpp
Go to the documentation of this file.
1//===- ACCImplicitData.cpp ------------------------------------------------===//
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// This pass implements the OpenACC specification for "Variables with
10// Implicitly Determined Data Attributes" (OpenACC 3.4 spec, section 2.6.2).
11//
12// Overview:
13// ---------
14// The pass automatically generates data clause operations for variables used
15// within OpenACC compute constructs (parallel, kernels, serial) that do not
16// already have explicit data clauses. The semantics follow these rules:
17//
18// 1. If there is a default(none) clause visible, no implicit data actions
19// apply.
20//
21// 2. An aggregate variable (arrays, derived types, etc.) will be treated as:
22// - In a present clause when default(present) is visible.
23// - In a copy clause otherwise.
24//
25// 3. A scalar variable will be treated as if it appears in:
26// - A copy clause if the compute construct is a kernels construct.
27// - A firstprivate clause otherwise (parallel, serial).
28//
29// Requirements:
30// -------------
31// To use this pass in a pipeline, the following requirements must be met:
32//
33// 1. Type Interface Implementation: Variables from the dialect being used
34// must implement one or both of the following MLIR interfaces:
35// `acc::MappableType` and/or `acc::PointerLikeType`
36//
37// These interfaces provide the necessary methods for the pass to:
38// - Determine variable type categories (scalar vs. aggregate)
39// - Generate appropriate bounds information
40// - Generate privatization recipes
41//
42// 2. Operation Interface Implementation: Operations that access partial
43// entities or create views should implement the following MLIR
44// interfaces: `acc::PartialEntityAccess` and/or
45// `mlir::ViewLikeOpInterface`
46//
47// These interfaces are used for proper data clause ordering, ensuring
48// that base entities are mapped before derived entities (e.g., a
49// struct is mapped before its fields, an array is mapped before
50// subarray views).
51//
52// 3. Analysis Registration (Optional): If custom behavior is needed for
53// variable name extraction or alias analysis, the dialect should
54// pre-register the `acc::OpenACCSupport` and `mlir::AliasAnalysis` analyses.
55//
56// If not registered, default behavior will be used.
57//
58// Implementation Details:
59// -----------------------
60// The pass performs the following operations:
61//
62// 1. Finds candidate variables which are live-in to the compute region and
63// are not already in a data clause or private clause.
64//
65// 2. Generates both data "entry" and "exit" clause operations that match
66// the intended action depending on variable type:
67// - copy -> acc.copyin (entry) + acc.copyout (exit)
68// - present -> acc.present (entry) + acc.delete (exit)
69// - firstprivate -> acc.firstprivate (entry only, no exit)
70//
71// 3. Ensures that default clause is taken into consideration by looking
72// through current construct and parent constructs to find the "visible
73// default clause".
74//
75// 4. Fixes up SSA value links so that uses in the acc region reference the
76// result of the newly created data clause operations.
77//
78// 5. When generating implicit data clause operations, it also adds variable
79// name information and marks them with the implicit flag.
80//
81// 6. Recipes are generated by calling the appropriate entrypoints in the
82// MappableType and PointerLikeType interfaces.
83//
84// 7. AliasAnalysis is used to determine if a variable is already covered by
85// an existing data clause (e.g., an interior pointer covered by its parent).
86//
87// Examples:
88// ---------
89//
90// Example 1: Scalar in parallel construct (implicit firstprivate)
91//
92// Before:
93// func.func @test() {
94// %scalar = memref.alloca() {acc.var_name = "x"} : memref<f32>
95// acc.parallel {
96// %val = memref.load %scalar[] : memref<f32>
97// acc.yield
98// }
99// }
100//
101// After:
102// func.func @test() {
103// %scalar = memref.alloca() {acc.var_name = "x"} : memref<f32>
104// %firstpriv = acc.firstprivate varPtr(%scalar : memref<f32>)
105// -> memref<f32> {implicit = true, name = "x"}
106// acc.parallel firstprivate(@recipe -> %firstpriv : memref<f32>) {
107// %val = memref.load %firstpriv[] : memref<f32>
108// acc.yield
109// }
110// }
111//
112// Example 2: Scalar in kernels construct (implicit copy)
113//
114// Before:
115// func.func @test() {
116// %scalar = memref.alloca() {acc.var_name = "n"} : memref<i32>
117// acc.kernels {
118// %val = memref.load %scalar[] : memref<i32>
119// acc.terminator
120// }
121// }
122//
123// After:
124// func.func @test() {
125// %scalar = memref.alloca() {acc.var_name = "n"} : memref<i32>
126// %copyin = acc.copyin varPtr(%scalar : memref<i32>) -> memref<i32>
127// {dataClause = #acc<data_clause acc_copy>,
128// implicit = true, name = "n"}
129// acc.kernels dataOperands(%copyin : memref<i32>) {
130// %val = memref.load %copyin[] : memref<i32>
131// acc.terminator
132// }
133// acc.copyout accPtr(%copyin : memref<i32>)
134// to varPtr(%scalar : memref<i32>)
135// {dataClause = #acc<data_clause acc_copy>,
136// implicit = true, name = "n"}
137// }
138//
139// Example 3: Array (aggregate) in parallel (implicit copy)
140//
141// Before:
142// func.func @test() {
143// %array = memref.alloca() {acc.var_name = "arr"} : memref<100xf32>
144// acc.parallel {
145// %c0 = arith.constant 0 : index
146// %val = memref.load %array[%c0] : memref<100xf32>
147// acc.yield
148// }
149// }
151// After:
152// func.func @test() {
153// %array = memref.alloca() {acc.var_name = "arr"} : memref<100xf32>
154// %copyin = acc.copyin varPtr(%array : memref<100xf32>)
155// -> memref<100xf32>
156// {dataClause = #acc<data_clause acc_copy>,
157// implicit = true, name = "arr"}
158// acc.parallel dataOperands(%copyin : memref<100xf32>) {
159// %c0 = arith.constant 0 : index
160// %val = memref.load %copyin[%c0] : memref<100xf32>
161// acc.yield
162// }
163// acc.copyout accPtr(%copyin : memref<100xf32>)
164// to varPtr(%array : memref<100xf32>)
165// {dataClause = #acc<data_clause acc_copy>,
166// implicit = true, name = "arr"}
167// }
168//
169// Example 4: Array with default(present)
171// Before:
172// func.func @test() {
173// %array = memref.alloca() {acc.var_name = "arr"} : memref<100xf32>
174// acc.parallel {
175// %c0 = arith.constant 0 : index
176// %val = memref.load %array[%c0] : memref<100xf32>
177// acc.yield
178// } attributes {defaultAttr = #acc<defaultvalue present>}
179// }
180//
181// After:
182// func.func @test() {
183// %array = memref.alloca() {acc.var_name = "arr"} : memref<100xf32>
184// %present = acc.present varPtr(%array : memref<100xf32>)
185// -> memref<100xf32>
186// {implicit = true, name = "arr"}
187// acc.parallel dataOperands(%present : memref<100xf32>)
188// attributes {defaultAttr = #acc<defaultvalue present>} {
189// %c0 = arith.constant 0 : index
190// %val = memref.load %present[%c0] : memref<100xf32>
191// acc.yield
192// }
193// acc.delete accPtr(%present : memref<100xf32>)
194// {dataClause = #acc<data_clause acc_present>,
195// implicit = true, name = "arr"}
196// }
197//
198//===----------------------------------------------------------------------===//
199
201
206#include "mlir/IR/Builders.h"
207#include "mlir/IR/BuiltinOps.h"
208#include "mlir/IR/Dominance.h"
209#include "mlir/IR/Operation.h"
210#include "mlir/IR/Value.h"
214#include "llvm/ADT/STLExtras.h"
215#include "llvm/ADT/SmallVector.h"
216#include "llvm/ADT/TypeSwitch.h"
217#include "llvm/Support/ErrorHandling.h"
218#include <type_traits>
219
220namespace mlir {
221namespace acc {
222#define GEN_PASS_DEF_ACCIMPLICITDATA
223#include "mlir/Dialect/OpenACC/Transforms/Passes.h.inc"
224} // namespace acc
225} // namespace mlir
226
227#define DEBUG_TYPE "acc-implicit-data"
228
229using namespace mlir;
230
231namespace {
232
233class ACCImplicitData : public acc::impl::ACCImplicitDataBase<ACCImplicitData> {
234public:
235 using acc::impl::ACCImplicitDataBase<ACCImplicitData>::ACCImplicitDataBase;
236
237 void runOnOperation() override;
238
239private:
240 /// Looks through the `dominatingDataClauses` to find the original data clause
241 /// op for an alias. Returns nullptr if no original data clause op is found.
242 template <typename OpT>
243 Operation *getOriginalDataClauseOpForAlias(
244 Value var, OpBuilder &builder, OpT computeConstructOp,
245 const SmallVector<Value> &dominatingDataClauses);
246
247 /// Generates the appropriate `acc.copyin`, `acc.present`,`acc.firstprivate`,
248 /// etc. data clause op for a candidate variable.
249 template <typename OpT>
250 Operation *generateDataClauseOpForCandidate(
251 Value var, ModuleOp &module, OpBuilder &builder, OpT computeConstructOp,
252 const SmallVector<Value> &dominatingDataClauses,
253 const std::optional<acc::ClauseDefaultValue> &defaultClause);
254
255 /// Generates the implicit data ops for a compute construct.
256 template <typename OpT>
257 void
258 generateImplicitDataOps(ModuleOp &module, OpT computeConstructOp,
259 std::optional<acc::ClauseDefaultValue> &defaultClause,
260 acc::OpenACCSupport &accSupport);
261
262 /// Generates a private recipe for a variable.
263 acc::PrivateRecipeOp generatePrivateRecipe(ModuleOp &module, Value var,
264 Location loc, OpBuilder &builder,
265 acc::OpenACCSupport &accSupport);
266
267 /// Generates a firstprivate recipe for a variable.
268 acc::FirstprivateRecipeOp
269 generateFirstprivateRecipe(ModuleOp &module, Value var, Location loc,
270 OpBuilder &builder,
271 acc::OpenACCSupport &accSupport);
272
273 /// Generates recipes for a list of variables.
274 void generateRecipes(ModuleOp &module, OpBuilder &builder,
275 Operation *computeConstructOp,
276 const SmallVector<Value> &newOperands);
277};
278
279/// Determines if a variable is a candidate for implicit data mapping.
280/// Returns true if the variable is a candidate, false otherwise.
281static bool isCandidateForImplicitData(Value val, Region &accRegion,
282 acc::OpenACCSupport &accSupport) {
283 // Ensure the variable is an allowed type for data clause.
284 if (!acc::isPointerLikeType(val.getType()) &&
286 return false;
287
288 // If this is already coming from a data clause, we do not need to generate
289 // another.
290 if (isa_and_nonnull<ACC_DATA_ENTRY_OPS>(val.getDefiningOp()))
291 return false;
292
293 // Device data is a candidate - it will get a deviceptr clause.
294 if (acc::isDeviceValue(val))
295 return true;
296
297 // If it is otherwise valid, skip it.
298 if (accSupport.isValidValueUse(val, accRegion))
299 return false;
300
301 return true;
302}
303
304template <typename OpT>
305Operation *ACCImplicitData::getOriginalDataClauseOpForAlias(
306 Value var, OpBuilder &builder, OpT computeConstructOp,
307 const SmallVector<Value> &dominatingDataClauses) {
308 auto &aliasAnalysis = this->getAnalysis<AliasAnalysis>();
309 for (auto dataClause : dominatingDataClauses) {
310 if (auto *dataClauseOp = dataClause.getDefiningOp()) {
311 // Only accept clauses that guarantee that the alias is present.
312 if (isa<acc::CopyinOp, acc::CreateOp, acc::PresentOp, acc::NoCreateOp,
313 acc::DevicePtrOp>(dataClauseOp))
314 if (aliasAnalysis.alias(acc::getVar(dataClauseOp), var).isMust())
315 return dataClauseOp;
316 }
317 }
318 return nullptr;
319}
320
321// Generates bounds for variables that have unknown dimensions
322static void fillInBoundsForUnknownDimensions(Operation *dataClauseOp,
323 OpBuilder &builder) {
324
325 if (!acc::getBounds(dataClauseOp).empty())
326 // If bounds are already present, do not overwrite them.
327 return;
328
329 // For types that have unknown dimensions, attempt to generate bounds by
330 // relying on MappableType being able to extract it from the IR.
331 auto var = acc::getVar(dataClauseOp);
332 auto type = var.getType();
333 if (auto mappableTy = dyn_cast<acc::MappableType>(type)) {
334 if (mappableTy.hasUnknownDimensions()) {
335 TypeSwitch<Operation *>(dataClauseOp)
336 .Case<ACC_DATA_ENTRY_OPS, ACC_DATA_EXIT_OPS>([&](auto dataClauseOp) {
337 if (std::is_same_v<decltype(dataClauseOp), acc::DevicePtrOp>)
338 return;
339 OpBuilder::InsertionGuard guard(builder);
340 builder.setInsertionPoint(dataClauseOp);
341 auto bounds = mappableTy.generateAccBounds(var, builder);
342 if (!bounds.empty())
343 dataClauseOp.getBoundsMutable().assign(bounds);
344 });
345 }
346 }
347}
348
349acc::PrivateRecipeOp
350ACCImplicitData::generatePrivateRecipe(ModuleOp &module, Value var,
351 Location loc, OpBuilder &builder,
352 acc::OpenACCSupport &accSupport) {
353 auto type = var.getType();
354 std::string recipeName =
355 accSupport.getRecipeName(acc::RecipeKind::private_recipe, type, var);
356
357 // Check if recipe already exists
358 auto existingRecipe = module.lookupSymbol<acc::PrivateRecipeOp>(recipeName);
359 if (existingRecipe)
360 return existingRecipe;
361
362 // Set insertion point to module body in a scoped way
363 OpBuilder::InsertionGuard guard(builder);
364 builder.setInsertionPointToStart(module.getBody());
365
366 auto recipe =
367 acc::PrivateRecipeOp::createAndPopulate(builder, loc, recipeName, type);
368 if (!recipe.has_value())
369 return accSupport.emitNYI(loc, "implicit private"), nullptr;
370 return recipe.value();
371}
372
373acc::FirstprivateRecipeOp
374ACCImplicitData::generateFirstprivateRecipe(ModuleOp &module, Value var,
375 Location loc, OpBuilder &builder,
376 acc::OpenACCSupport &accSupport) {
377 auto type = var.getType();
378 std::string recipeName =
379 accSupport.getRecipeName(acc::RecipeKind::firstprivate_recipe, type, var);
380
381 // Check if recipe already exists
382 auto existingRecipe =
383 module.lookupSymbol<acc::FirstprivateRecipeOp>(recipeName);
384 if (existingRecipe)
385 return existingRecipe;
386
387 // Set insertion point to module body in a scoped way
388 OpBuilder::InsertionGuard guard(builder);
389 builder.setInsertionPointToStart(module.getBody());
390
391 auto recipe = acc::FirstprivateRecipeOp::createAndPopulate(builder, loc,
392 recipeName, type);
393 if (!recipe.has_value())
394 return accSupport.emitNYI(loc, "implicit firstprivate"), nullptr;
395 return recipe.value();
396}
397
398void ACCImplicitData::generateRecipes(ModuleOp &module, OpBuilder &builder,
399 Operation *computeConstructOp,
400 const SmallVector<Value> &newOperands) {
401 auto &accSupport = this->getAnalysis<acc::OpenACCSupport>();
402 for (auto var : newOperands) {
403 auto loc{var.getLoc()};
404 if (auto privateOp = var.getDefiningOp<acc::PrivateOp>()) {
405 auto recipe = generatePrivateRecipe(
406 module, acc::getVar(var.getDefiningOp()), loc, builder, accSupport);
407 if (recipe)
408 privateOp.setRecipeAttr(
409 SymbolRefAttr::get(module->getContext(), recipe.getSymName()));
410 } else if (auto firstprivateOp = var.getDefiningOp<acc::FirstprivateOp>()) {
411 auto recipe = generateFirstprivateRecipe(
412 module, acc::getVar(var.getDefiningOp()), loc, builder, accSupport);
413 if (recipe)
414 firstprivateOp.setRecipeAttr(SymbolRefAttr::get(
415 module->getContext(), recipe.getSymName().str()));
416 } else {
417 accSupport.emitNYI(var.getLoc(), "implicit reduction");
418 }
419 }
420}
421
422// Generates the data entry data op clause so that it adheres to OpenACC
423// rules as follows (line numbers and specification from OpenACC 3.4):
424// 1388 An aggregate variable will be treated as if it appears either:
425// 1389 - In a present clause if there is a default(present) clause visible at
426// the compute construct.
427// 1391 - In a copy clause otherwise.
428// 1392 A scalar variable will be treated as if it appears either:
429// 1393 - In a copy clause if the compute construct is a kernels construct.
430// 1394 - In a firstprivate clause otherwise.
431template <typename OpT>
432Operation *ACCImplicitData::generateDataClauseOpForCandidate(
433 Value var, ModuleOp &module, OpBuilder &builder, OpT computeConstructOp,
434 const SmallVector<Value> &dominatingDataClauses,
435 const std::optional<acc::ClauseDefaultValue> &defaultClause) {
436 auto &accSupport = this->getAnalysis<acc::OpenACCSupport>();
437 acc::VariableTypeCategory typeCategory =
438 acc::VariableTypeCategory::uncategorized;
439 if (auto mappableTy = dyn_cast<acc::MappableType>(var.getType())) {
440 typeCategory = mappableTy.getTypeCategory(var);
441 } else if (auto pointerLikeTy =
442 dyn_cast<acc::PointerLikeType>(var.getType())) {
443 typeCategory = pointerLikeTy.getPointeeTypeCategory(
445 pointerLikeTy.getElementType());
446 }
447
448 bool isScalar =
449 acc::bitEnumContainsAny(typeCategory, acc::VariableTypeCategory::scalar);
450 bool isAnyAggregate = acc::bitEnumContainsAny(
451 typeCategory, acc::VariableTypeCategory::aggregate);
452 Location loc = computeConstructOp->getLoc();
453
454 Operation *op = nullptr;
455 op = getOriginalDataClauseOpForAlias(var, builder, computeConstructOp,
456 dominatingDataClauses);
457 if (op) {
458 if (isa<acc::NoCreateOp>(op))
459 return acc::NoCreateOp::create(builder, loc, var,
460 /*structured=*/true, /*implicit=*/true,
461 accSupport.getVariableName(var),
462 acc::getBounds(op));
463
464 if (isa<acc::DevicePtrOp>(op))
465 return acc::DevicePtrOp::create(builder, loc, var,
466 /*structured=*/true, /*implicit=*/true,
467 accSupport.getVariableName(var),
468 acc::getBounds(op));
469
470 // The original data clause op is a PresentOp, CopyinOp, or CreateOp,
471 // hence guaranteed to be present.
472 return acc::PresentOp::create(builder, loc, var,
473 /*structured=*/true, /*implicit=*/true,
474 accSupport.getVariableName(var),
475 acc::getBounds(op));
476 }
477
478 if (acc::isDeviceValue(var)) {
479 // If the variable is device data, use deviceptr clause.
480 return acc::DevicePtrOp::create(builder, loc, var,
481 /*structured=*/true, /*implicit=*/true,
482 accSupport.getVariableName(var));
483 }
484
485 if (isScalar) {
486 if (enableImplicitReductionCopy &&
488 computeConstructOp->getRegion(0))) {
489 auto copyinOp =
490 acc::CopyinOp::create(builder, loc, var,
491 /*structured=*/true, /*implicit=*/true,
492 accSupport.getVariableName(var));
493 copyinOp.setDataClause(acc::DataClause::acc_reduction);
494 return copyinOp.getOperation();
495 }
496 if constexpr (std::is_same_v<OpT, acc::KernelsOp> ||
497 std::is_same_v<OpT, acc::KernelEnvironmentOp>) {
498 // Scalars are implicit copyin in kernels construct.
499 // We also do the same for acc.kernel_environment because semantics
500 // of user variable mappings should be applied while ACC construct exists
501 // and at this point we should only be dealing with unmapped variables
502 // that were made live-in by the compiler.
503 // TODO: This may be revisited.
504 auto copyinOp =
505 acc::CopyinOp::create(builder, loc, var,
506 /*structured=*/true, /*implicit=*/true,
507 accSupport.getVariableName(var));
508 copyinOp.setDataClause(acc::DataClause::acc_copy);
509 return copyinOp.getOperation();
510 } else {
511 // Scalars are implicit firstprivate in parallel and serial construct.
512 return acc::FirstprivateOp::create(builder, loc, var,
513 /*structured=*/true, /*implicit=*/true,
514 accSupport.getVariableName(var));
515 }
516 } else if (isAnyAggregate) {
517 Operation *newDataOp = nullptr;
518
519 // When default(present) is true, the implicit behavior is present.
520 if (defaultClause.has_value() &&
521 defaultClause.value() == acc::ClauseDefaultValue::Present) {
522 newDataOp = acc::PresentOp::create(builder, loc, var,
523 /*structured=*/true, /*implicit=*/true,
524 accSupport.getVariableName(var));
526 builder.getUnitAttr());
527 } else {
528 auto copyinOp =
529 acc::CopyinOp::create(builder, loc, var,
530 /*structured=*/true, /*implicit=*/true,
531 accSupport.getVariableName(var));
532 copyinOp.setDataClause(acc::DataClause::acc_copy);
533 newDataOp = copyinOp.getOperation();
534 }
535
536 return newDataOp;
537 } else {
538 // This is not a fatal error - for example when the element type is
539 // pointer type (aka we have a pointer of pointer), it is potentially a
540 // deep copy scenario which is not being handled here.
541 // Other types need to be canonicalized. Thus just log unhandled cases.
542 LLVM_DEBUG(llvm::dbgs()
543 << "Unhandled case for implicit data mapping " << var << "\n");
544 }
545 return nullptr;
546}
547
548// Ensures that result values from the acc data clause ops are used inside the
549// acc region. ie:
550// acc.kernels {
551// use %val
552// }
553// =>
554// %dev = acc.dataop %val
555// acc.kernels {
556// use %dev
557// }
558static void legalizeValuesInRegion(Region &accRegion,
559 SmallVector<Value> &newPrivateOperands,
560 SmallVector<Value> &newDataClauseOperands) {
561 for (Value dataClause :
562 llvm::concat<Value>(newDataClauseOperands, newPrivateOperands)) {
563 Value var = acc::getVar(dataClause.getDefiningOp());
564 replaceAllUsesInRegionWith(var, dataClause, accRegion);
565 }
566}
567
568// Adds the private operands to the compute construct operation.
569template <typename OpT>
570static void addNewPrivateOperands(OpT &accOp,
571 const SmallVector<Value> &privateOperands) {
572 if (privateOperands.empty())
573 return;
574
575 for (auto priv : privateOperands) {
576 if (isa<acc::PrivateOp>(priv.getDefiningOp())) {
577 accOp.getPrivateOperandsMutable().append(priv);
578 } else if (isa<acc::FirstprivateOp>(priv.getDefiningOp())) {
579 accOp.getFirstprivateOperandsMutable().append(priv);
580 } else {
581 llvm_unreachable("unhandled reduction operand");
582 }
583 }
584}
585
586static Operation *findDataExitOp(Operation *dataEntryOp) {
587 auto res = acc::getAccVar(dataEntryOp);
588 for (auto *user : res.getUsers())
589 if (isa<ACC_DATA_EXIT_OPS>(user))
590 return user;
591 return nullptr;
592}
593
594// Generates matching data exit operation as described in the acc dialect
595// for how data clauses are decomposed:
596// https://mlir.llvm.org/docs/Dialects/OpenACCDialect/#operation-categories
597// Key ones used here:
598// * acc {construct} copy -> acc.copyin (before region) + acc.copyout (after
599// region)
600// * acc {construct} present -> acc.present (before region) + acc.delete
601// (after region)
602static void
603generateDataExitOperations(OpBuilder &builder, Operation *accOp,
604 const SmallVector<Value> &newDataClauseOperands,
605 const SmallVector<Value> &sortedDataClauseOperands) {
606 builder.setInsertionPointAfter(accOp);
607 Value lastDataClause = nullptr;
608 for (auto dataEntry : llvm::reverse(sortedDataClauseOperands)) {
609 if (llvm::find(newDataClauseOperands, dataEntry) ==
610 newDataClauseOperands.end()) {
611 // If this is not a new data clause operand, we should not generate an
612 // exit operation for it.
613 lastDataClause = dataEntry;
614 continue;
615 }
616 if (lastDataClause)
617 if (auto *dataExitOp = findDataExitOp(lastDataClause.getDefiningOp()))
618 builder.setInsertionPointAfter(dataExitOp);
619 Operation *dataEntryOp = dataEntry.getDefiningOp();
620 if (isa<acc::CopyinOp>(dataEntryOp)) {
621 auto copyoutOp = acc::CopyoutOp::create(
622 builder, dataEntryOp->getLoc(), dataEntry, acc::getVar(dataEntryOp),
623 /*structured=*/true, /*implicit=*/true,
624 acc::getVarName(dataEntryOp).value(), acc::getBounds(dataEntryOp));
625 copyoutOp.setDataClause(acc::DataClause::acc_copy);
626 } else if (isa<acc::PresentOp, acc::NoCreateOp>(dataEntryOp)) {
627 auto deleteOp = acc::DeleteOp::create(
628 builder, dataEntryOp->getLoc(), dataEntry,
629 /*structured=*/true, /*implicit=*/true,
630 acc::getVarName(dataEntryOp).value(), acc::getBounds(dataEntryOp));
631 deleteOp.setDataClause(acc::getDataClause(dataEntryOp).value());
632 } else if (isa<acc::DevicePtrOp>(dataEntryOp)) {
633 // Do nothing.
634 } else {
635 llvm_unreachable("unhandled data exit");
636 }
637 lastDataClause = dataEntry;
638 }
639}
640
641/// Returns all base references of a value in order.
642/// So for example, if we have a reference to a struct field like
643/// s.f1.f2.f3, this will return <s, s.f1, s.f1.f2, s.f1.f2.f3>.
644/// Any intermediate casts/view-like operations are included in the
645/// chain as well.
646static SmallVector<Value> getBaseRefsChain(Value val) {
647 SmallVector<Value> baseRefs;
648 baseRefs.push_back(val);
649 while (true) {
650 Value prevVal = val;
651
652 val = acc::getBaseEntity(val);
653 if (val != baseRefs.front())
654 baseRefs.insert(baseRefs.begin(), val);
655
656 // If this is a view-like operation, it is effectively another
657 // view of the same entity so we should add it to the chain also.
658 if (auto viewLikeOp = val.getDefiningOp<ViewLikeOpInterface>()) {
659 val = viewLikeOp.getViewSource();
660 baseRefs.insert(baseRefs.begin(), val);
661 }
662
663 // Continue loop if we made any progress
664 if (val == prevVal)
665 break;
666 }
667
668 return baseRefs;
669}
670
671static void insertInSortedOrder(SmallVector<Value> &sortedDataClauseOperands,
672 Operation *newClause) {
673 auto *insertPos =
674 std::find_if(sortedDataClauseOperands.begin(),
675 sortedDataClauseOperands.end(), [&](Value dataClauseVal) {
676 // Get the base refs for the current clause we are looking
677 // at.
678 auto var = acc::getVar(dataClauseVal.getDefiningOp());
679 auto baseRefs = getBaseRefsChain(var);
680
681 // If the newClause is of a base ref of an existing clause,
682 // we should insert it right before the current clause.
683 // Thus return true to stop iteration when this is the
684 // case.
685 return std::find(baseRefs.begin(), baseRefs.end(),
686 acc::getVar(newClause)) != baseRefs.end();
687 });
688
689 if (insertPos != sortedDataClauseOperands.end()) {
690 newClause->moveBefore(insertPos->getDefiningOp());
691 sortedDataClauseOperands.insert(insertPos, acc::getAccVar(newClause));
692 } else {
693 sortedDataClauseOperands.push_back(acc::getAccVar(newClause));
694 }
695}
696
697template <typename OpT>
698void ACCImplicitData::generateImplicitDataOps(
699 ModuleOp &module, OpT computeConstructOp,
700 std::optional<acc::ClauseDefaultValue> &defaultClause,
701 acc::OpenACCSupport &accSupport) {
702 // Implicit data attributes are only applied if "[t]here is no default(none)
703 // clause visible at the compute construct."
704 if (defaultClause.has_value() &&
705 defaultClause.value() == acc::ClauseDefaultValue::None)
706 return;
707 assert(!defaultClause.has_value() ||
708 defaultClause.value() == acc::ClauseDefaultValue::Present);
709
710 // 1) Collect live-in values.
711 Region &accRegion = computeConstructOp->getRegion(0);
712 SetVector<Value> liveInValues;
713 getUsedValuesDefinedAbove(accRegion, liveInValues);
714
715 // 2) Run the filtering to find relevant pointers that need copied.
716 auto isCandidate{[&](Value val) -> bool {
717 return isCandidateForImplicitData(val, accRegion, accSupport);
718 }};
719 auto candidateVars(
720 llvm::to_vector(llvm::make_filter_range(liveInValues, isCandidate)));
721 if (candidateVars.empty())
722 return;
723
724 // 3) Generate data clauses for the variables.
725 SmallVector<Value> newPrivateOperands;
726 SmallVector<Value> newDataClauseOperands;
727 OpBuilder builder(computeConstructOp);
728 if (!candidateVars.empty()) {
729 LLVM_DEBUG(llvm::dbgs() << "== Generating clauses for ==\n"
730 << computeConstructOp << "\n");
731 }
732 auto &domInfo = this->getAnalysis<DominanceInfo>();
733 auto &postDomInfo = this->getAnalysis<PostDominanceInfo>();
734 auto dominatingDataClauses =
735 acc::getDominatingDataClauses(computeConstructOp, domInfo, postDomInfo);
736 for (auto var : candidateVars) {
737 auto newDataClauseOp = generateDataClauseOpForCandidate(
738 var, module, builder, computeConstructOp, dominatingDataClauses,
739 defaultClause);
740 fillInBoundsForUnknownDimensions(newDataClauseOp, builder);
741 LLVM_DEBUG(llvm::dbgs() << "Generated data clause for " << var << ":\n"
742 << "\t" << *newDataClauseOp << "\n");
743 if (isa_and_nonnull<acc::PrivateOp, acc::FirstprivateOp, acc::ReductionOp>(
744 newDataClauseOp)) {
745 newPrivateOperands.push_back(acc::getAccVar(newDataClauseOp));
746 } else if (isa_and_nonnull<ACC_DATA_CLAUSE_OPS>(newDataClauseOp)) {
747 newDataClauseOperands.push_back(acc::getAccVar(newDataClauseOp));
748 dominatingDataClauses.push_back(acc::getAccVar(newDataClauseOp));
749 }
750 }
751
752 // 4) Legalize values in region (aka the uses in the region are the result
753 // of the data clause ops)
754 legalizeValuesInRegion(accRegion, newPrivateOperands, newDataClauseOperands);
755
756 // 5) Generate private recipes which are required for properly attaching
757 // private operands.
758 if constexpr (!std::is_same_v<OpT, acc::KernelsOp> &&
759 !std::is_same_v<OpT, acc::KernelEnvironmentOp>)
760 generateRecipes(module, builder, computeConstructOp, newPrivateOperands);
761
762 // 6) Figure out insertion order for the new data clause operands.
763 SmallVector<Value> sortedDataClauseOperands(
764 computeConstructOp.getDataClauseOperands());
765 for (auto newClause : newDataClauseOperands)
766 insertInSortedOrder(sortedDataClauseOperands, newClause.getDefiningOp());
767
768 // 7) Generate the data exit operations.
769 generateDataExitOperations(builder, computeConstructOp, newDataClauseOperands,
770 sortedDataClauseOperands);
771 // 8) Add all of the new operands to the compute construct op.
772 if constexpr (!std::is_same_v<OpT, acc::KernelsOp> &&
773 !std::is_same_v<OpT, acc::KernelEnvironmentOp>)
774 addNewPrivateOperands(computeConstructOp, newPrivateOperands);
775 computeConstructOp.getDataClauseOperandsMutable().assign(
776 sortedDataClauseOperands);
777}
778
779void ACCImplicitData::runOnOperation() {
780 ModuleOp module = this->getOperation();
781
782 acc::OpenACCSupport &accSupport = getAnalysis<acc::OpenACCSupport>();
783
784 module.walk([&](Operation *op) {
785 if (isa<ACC_COMPUTE_CONSTRUCT_OPS, acc::KernelEnvironmentOp>(op)) {
786 assert(op->getNumRegions() == 1 && "must have 1 region");
787
788 auto defaultClause = acc::getDefaultAttr(op);
790 .Case<ACC_COMPUTE_CONSTRUCT_OPS, acc::KernelEnvironmentOp>(
791 [&](auto op) {
792 generateImplicitDataOps(module, op, defaultClause, accSupport);
793 })
794 .Default([&](Operation *) {});
795 }
796 });
797}
798
799} // namespace
UnitAttr getUnitAttr()
Definition Builders.cpp:98
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
Definition Location.h:76
RAII guard to reset the insertion point of the builder when destroyed.
Definition Builders.h:348
This class helps build Operations.
Definition Builders.h:207
void setInsertionPointToStart(Block *block)
Sets the insertion point to the start of the specified block.
Definition Builders.h:431
void setInsertionPoint(Block *block, Block::iterator insertPoint)
Set the insertion point to the specified location.
Definition Builders.h:398
void setInsertionPointAfter(Operation *op)
Sets the insertion point to the node after the specified operation, which will cause subsequent inser...
Definition Builders.h:412
Operation is the basic unit of execution within MLIR.
Definition Operation.h:88
Location getLoc()
The source location the operation was defined or derived from.
Definition Operation.h:223
void setAttr(StringAttr name, Attribute value)
If the an attribute exists with the specified name, change it to the new value.
Definition Operation.h:582
void moveBefore(Operation *existingOp)
Unlink this operation from its current block and insert it right before existingOp which may be in th...
This class contains a list of basic blocks and a link to the parent operation it is attached to.
Definition Region.h:26
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Definition Value.h:96
Type getType() const
Return the type of this value.
Definition Value.h:105
Location getLoc() const
Return the location of this value.
Definition Value.cpp:24
Operation * getDefiningOp() const
If this value is the result of an operation, return the operation that defines it.
Definition Value.cpp:18
InFlightDiagnostic emitNYI(Location loc, const Twine &message)
Report a case that is not yet supported by the implementation.
bool isValidValueUse(Value v, Region &region)
Check if a value use is legal in an OpenACC region.
std::string getVariableName(Value v)
Get the variable name for a given value.
std::string getRecipeName(RecipeKind kind, Type type, Value var)
Get the recipe name for a given type and value.
#define ACC_COMPUTE_CONSTRUCT_OPS
Definition OpenACC.h:57
#define ACC_DATA_ENTRY_OPS
Definition OpenACC.h:45
#define ACC_DATA_EXIT_OPS
Definition OpenACC.h:53
static constexpr StringLiteral getFromDefaultClauseAttrName()
Definition OpenACC.h:199
mlir::Value getAccVar(mlir::Operation *accDataClauseOp)
Used to obtain the accVar from a data clause operation.
Definition OpenACC.cpp:4923
mlir::Value getVar(mlir::Operation *accDataClauseOp)
Used to obtain the var from a data clause operation.
Definition OpenACC.cpp:4892
std::optional< mlir::acc::DataClause > getDataClause(mlir::Operation *accDataEntryOp)
Used to obtain the dataClause from a data entry operation.
Definition OpenACC.cpp:4996
bool isPointerLikeType(mlir::Type type)
Used to check whether the provided type implements the PointerLikeType interface.
Definition OpenACC.h:160
mlir::SmallVector< mlir::Value > getBounds(mlir::Operation *accDataClauseOp)
Used to obtain bounds from an acc data clause operation.
Definition OpenACC.cpp:4941
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.
std::optional< llvm::StringRef > getVarName(mlir::Operation *accOp)
Used to obtain the name from an acc operation.
Definition OpenACC.cpp:4985
llvm::SmallVector< mlir::Value > getDominatingDataClauses(mlir::Operation *computeConstructOp, mlir::DominanceInfo &domInfo, mlir::PostDominanceInfo &postDomInfo)
Collects all data clauses that dominate the compute construct.
bool isMappableType(mlir::Type type)
Used to check whether the provided type implements the MappableType interface.
Definition OpenACC.h:166
bool isDeviceValue(mlir::Value val)
Check if a value represents device data.
mlir::Value getBaseEntity(mlir::Value val)
Include the generated interface declarations.
void replaceAllUsesInRegionWith(Value orig, Value replacement, Region &region)
Replace all uses of orig within the given region with replacement.
llvm::SetVector< T, Vector, Set, N > SetVector
Definition LLVM.h:131
std::conditional_t< std::is_same_v< Ty, mlir::Type >, mlir::Value, detail::TypedValue< Ty > > TypedValue
If Ty is mlir::Type this will select Value instead of having a wrapper around it.
Definition Value.h:497
void getUsedValuesDefinedAbove(Region &region, Region &limit, SetVector< Value > &values)
Fill values with a list of values defined at the ancestors of the limit region and used within region...
llvm::TypeSwitch< T, ResultT > TypeSwitch
Definition LLVM.h:144