MLIR 22.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// }
150//
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)
170//
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 (accSupport.isValidValueUse(val, accRegion))
289 return false;
290
291 // If this is already coming from a data clause, we do not need to generate
292 // another.
293 if (isa_and_nonnull<ACC_DATA_ENTRY_OPS>(val.getDefiningOp()))
294 return false;
295
296 // If this is only used by private clauses, it is not a real live-in.
297 if (acc::isOnlyUsedByPrivateClauses(val, accRegion))
298 return false;
299
300 return true;
301}
302
303template <typename OpT>
304Operation *ACCImplicitData::getOriginalDataClauseOpForAlias(
305 Value var, OpBuilder &builder, OpT computeConstructOp,
306 const SmallVector<Value> &dominatingDataClauses) {
307 auto &aliasAnalysis = this->getAnalysis<AliasAnalysis>();
308 for (auto dataClause : dominatingDataClauses) {
309 if (auto *dataClauseOp = dataClause.getDefiningOp()) {
310 // Only accept clauses that guarantee that the alias is present.
311 if (isa<acc::CopyinOp, acc::CreateOp, acc::PresentOp, acc::NoCreateOp,
312 acc::DevicePtrOp>(dataClauseOp))
313 if (aliasAnalysis.alias(acc::getVar(dataClauseOp), var).isMust())
314 return dataClauseOp;
315 }
316 }
317 return nullptr;
318}
319
320// Generates bounds for variables that have unknown dimensions
321static void fillInBoundsForUnknownDimensions(Operation *dataClauseOp,
322 OpBuilder &builder) {
323
324 if (!acc::getBounds(dataClauseOp).empty())
325 // If bounds are already present, do not overwrite them.
326 return;
327
328 // For types that have unknown dimensions, attempt to generate bounds by
329 // relying on MappableType being able to extract it from the IR.
330 auto var = acc::getVar(dataClauseOp);
331 auto type = var.getType();
332 if (auto mappableTy = dyn_cast<acc::MappableType>(type)) {
333 if (mappableTy.hasUnknownDimensions()) {
334 TypeSwitch<Operation *>(dataClauseOp)
335 .Case<ACC_DATA_ENTRY_OPS, ACC_DATA_EXIT_OPS>([&](auto dataClauseOp) {
336 if (std::is_same_v<decltype(dataClauseOp), acc::DevicePtrOp>)
337 return;
338 OpBuilder::InsertionGuard guard(builder);
339 builder.setInsertionPoint(dataClauseOp);
340 auto bounds = mappableTy.generateAccBounds(var, builder);
341 if (!bounds.empty())
342 dataClauseOp.getBoundsMutable().assign(bounds);
343 });
344 }
345 }
346}
347
348acc::PrivateRecipeOp
349ACCImplicitData::generatePrivateRecipe(ModuleOp &module, Value var,
350 Location loc, OpBuilder &builder,
351 acc::OpenACCSupport &accSupport) {
352 auto type = var.getType();
353 std::string recipeName =
354 accSupport.getRecipeName(acc::RecipeKind::private_recipe, type, var);
355
356 // Check if recipe already exists
357 auto existingRecipe = module.lookupSymbol<acc::PrivateRecipeOp>(recipeName);
358 if (existingRecipe)
359 return existingRecipe;
360
361 // Set insertion point to module body in a scoped way
362 OpBuilder::InsertionGuard guard(builder);
363 builder.setInsertionPointToStart(module.getBody());
364
365 auto recipe =
366 acc::PrivateRecipeOp::createAndPopulate(builder, loc, recipeName, type);
367 if (!recipe.has_value())
368 return accSupport.emitNYI(loc, "implicit private"), nullptr;
369 return recipe.value();
370}
371
372acc::FirstprivateRecipeOp
373ACCImplicitData::generateFirstprivateRecipe(ModuleOp &module, Value var,
374 Location loc, OpBuilder &builder,
375 acc::OpenACCSupport &accSupport) {
376 auto type = var.getType();
377 std::string recipeName =
378 accSupport.getRecipeName(acc::RecipeKind::firstprivate_recipe, type, var);
379
380 // Check if recipe already exists
381 auto existingRecipe =
382 module.lookupSymbol<acc::FirstprivateRecipeOp>(recipeName);
383 if (existingRecipe)
384 return existingRecipe;
385
386 // Set insertion point to module body in a scoped way
387 OpBuilder::InsertionGuard guard(builder);
388 builder.setInsertionPointToStart(module.getBody());
389
390 auto recipe = acc::FirstprivateRecipeOp::createAndPopulate(builder, loc,
391 recipeName, type);
392 if (!recipe.has_value())
393 return accSupport.emitNYI(loc, "implicit firstprivate"), nullptr;
394 return recipe.value();
395}
396
397void ACCImplicitData::generateRecipes(ModuleOp &module, OpBuilder &builder,
398 Operation *computeConstructOp,
399 const SmallVector<Value> &newOperands) {
400 auto &accSupport = this->getAnalysis<acc::OpenACCSupport>();
401 for (auto var : newOperands) {
402 auto loc{var.getLoc()};
403 if (auto privateOp = dyn_cast<acc::PrivateOp>(var.getDefiningOp())) {
404 auto recipe = generatePrivateRecipe(
405 module, acc::getVar(var.getDefiningOp()), loc, builder, accSupport);
406 if (recipe)
407 privateOp.setRecipeAttr(
408 SymbolRefAttr::get(module->getContext(), recipe.getSymName()));
409 } else if (auto firstprivateOp =
410 dyn_cast<acc::FirstprivateOp>(var.getDefiningOp())) {
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 } else if (isScalar) {
477 if (enableImplicitReductionCopy &&
479 computeConstructOp->getRegion(0))) {
480 auto copyinOp =
481 acc::CopyinOp::create(builder, loc, var,
482 /*structured=*/true, /*implicit=*/true,
483 accSupport.getVariableName(var));
484 copyinOp.setDataClause(acc::DataClause::acc_reduction);
485 return copyinOp.getOperation();
486 }
487 if constexpr (std::is_same_v<OpT, acc::KernelsOp> ||
488 std::is_same_v<OpT, acc::KernelEnvironmentOp>) {
489 // Scalars are implicit copyin in kernels construct.
490 // We also do the same for acc.kernel_environment because semantics
491 // of user variable mappings should be applied while ACC construct exists
492 // and at this point we should only be dealing with unmapped variables
493 // that were made live-in by the compiler.
494 // TODO: This may be revisited.
495 auto copyinOp =
496 acc::CopyinOp::create(builder, loc, var,
497 /*structured=*/true, /*implicit=*/true,
498 accSupport.getVariableName(var));
499 copyinOp.setDataClause(acc::DataClause::acc_copy);
500 return copyinOp.getOperation();
501 } else {
502 // Scalars are implicit firstprivate in parallel and serial construct.
503 return acc::FirstprivateOp::create(builder, loc, var,
504 /*structured=*/true, /*implicit=*/true,
505 accSupport.getVariableName(var));
506 }
507 } else if (isAnyAggregate) {
508 Operation *newDataOp = nullptr;
509
510 // When default(present) is true, the implicit behavior is present.
511 if (defaultClause.has_value() &&
512 defaultClause.value() == acc::ClauseDefaultValue::Present) {
513 newDataOp = acc::PresentOp::create(builder, loc, var,
514 /*structured=*/true, /*implicit=*/true,
515 accSupport.getVariableName(var));
517 builder.getUnitAttr());
518 } else {
519 auto copyinOp =
520 acc::CopyinOp::create(builder, loc, var,
521 /*structured=*/true, /*implicit=*/true,
522 accSupport.getVariableName(var));
523 copyinOp.setDataClause(acc::DataClause::acc_copy);
524 newDataOp = copyinOp.getOperation();
525 }
526
527 return newDataOp;
528 } else {
529 // This is not a fatal error - for example when the element type is
530 // pointer type (aka we have a pointer of pointer), it is potentially a
531 // deep copy scenario which is not being handled here.
532 // Other types need to be canonicalized. Thus just log unhandled cases.
533 LLVM_DEBUG(llvm::dbgs()
534 << "Unhandled case for implicit data mapping " << var << "\n");
535 }
536 return nullptr;
537}
538
539// Ensures that result values from the acc data clause ops are used inside the
540// acc region. ie:
541// acc.kernels {
542// use %val
543// }
544// =>
545// %dev = acc.dataop %val
546// acc.kernels {
547// use %dev
548// }
549static void legalizeValuesInRegion(Region &accRegion,
550 SmallVector<Value> &newPrivateOperands,
551 SmallVector<Value> &newDataClauseOperands) {
552 for (Value dataClause :
553 llvm::concat<Value>(newDataClauseOperands, newPrivateOperands)) {
554 Value var = acc::getVar(dataClause.getDefiningOp());
555 replaceAllUsesInRegionWith(var, dataClause, accRegion);
556 }
557}
558
559// Adds the private operands to the compute construct operation.
560template <typename OpT>
561static void addNewPrivateOperands(OpT &accOp,
562 const SmallVector<Value> &privateOperands) {
563 if (privateOperands.empty())
564 return;
565
566 for (auto priv : privateOperands) {
567 if (isa<acc::PrivateOp>(priv.getDefiningOp())) {
568 accOp.getPrivateOperandsMutable().append(priv);
569 } else if (isa<acc::FirstprivateOp>(priv.getDefiningOp())) {
570 accOp.getFirstprivateOperandsMutable().append(priv);
571 } else {
572 llvm_unreachable("unhandled reduction operand");
573 }
574 }
575}
576
577static Operation *findDataExitOp(Operation *dataEntryOp) {
578 auto res = acc::getAccVar(dataEntryOp);
579 for (auto *user : res.getUsers())
580 if (isa<ACC_DATA_EXIT_OPS>(user))
581 return user;
582 return nullptr;
583}
584
585// Generates matching data exit operation as described in the acc dialect
586// for how data clauses are decomposed:
587// https://mlir.llvm.org/docs/Dialects/OpenACCDialect/#operation-categories
588// Key ones used here:
589// * acc {construct} copy -> acc.copyin (before region) + acc.copyout (after
590// region)
591// * acc {construct} present -> acc.present (before region) + acc.delete
592// (after region)
593static void
594generateDataExitOperations(OpBuilder &builder, Operation *accOp,
595 const SmallVector<Value> &newDataClauseOperands,
596 const SmallVector<Value> &sortedDataClauseOperands) {
597 builder.setInsertionPointAfter(accOp);
598 Value lastDataClause = nullptr;
599 for (auto dataEntry : llvm::reverse(sortedDataClauseOperands)) {
600 if (llvm::find(newDataClauseOperands, dataEntry) ==
601 newDataClauseOperands.end()) {
602 // If this is not a new data clause operand, we should not generate an
603 // exit operation for it.
604 lastDataClause = dataEntry;
605 continue;
606 }
607 if (lastDataClause)
608 if (auto *dataExitOp = findDataExitOp(lastDataClause.getDefiningOp()))
609 builder.setInsertionPointAfter(dataExitOp);
610 Operation *dataEntryOp = dataEntry.getDefiningOp();
611 if (isa<acc::CopyinOp>(dataEntryOp)) {
612 auto copyoutOp = acc::CopyoutOp::create(
613 builder, dataEntryOp->getLoc(), dataEntry, acc::getVar(dataEntryOp),
614 /*structured=*/true, /*implicit=*/true,
615 acc::getVarName(dataEntryOp).value(), acc::getBounds(dataEntryOp));
616 copyoutOp.setDataClause(acc::DataClause::acc_copy);
617 } else if (isa<acc::PresentOp, acc::NoCreateOp>(dataEntryOp)) {
618 auto deleteOp = acc::DeleteOp::create(
619 builder, dataEntryOp->getLoc(), dataEntry,
620 /*structured=*/true, /*implicit=*/true,
621 acc::getVarName(dataEntryOp).value(), acc::getBounds(dataEntryOp));
622 deleteOp.setDataClause(acc::getDataClause(dataEntryOp).value());
623 } else if (isa<acc::DevicePtrOp>(dataEntryOp)) {
624 // Do nothing.
625 } else {
626 llvm_unreachable("unhandled data exit");
627 }
628 lastDataClause = dataEntry;
629 }
630}
631
632/// Returns all base references of a value in order.
633/// So for example, if we have a reference to a struct field like
634/// s.f1.f2.f3, this will return <s, s.f1, s.f1.f2, s.f1.f2.f3>.
635/// Any intermediate casts/view-like operations are included in the
636/// chain as well.
637static SmallVector<Value> getBaseRefsChain(Value val) {
638 SmallVector<Value> baseRefs;
639 baseRefs.push_back(val);
640 while (true) {
641 Value prevVal = val;
642
643 val = acc::getBaseEntity(val);
644 if (val != baseRefs.front())
645 baseRefs.insert(baseRefs.begin(), val);
646
647 // If this is a view-like operation, it is effectively another
648 // view of the same entity so we should add it to the chain also.
649 if (auto viewLikeOp = val.getDefiningOp<ViewLikeOpInterface>()) {
650 val = viewLikeOp.getViewSource();
651 baseRefs.insert(baseRefs.begin(), val);
652 }
653
654 // Continue loop if we made any progress
655 if (val == prevVal)
656 break;
657 }
658
659 return baseRefs;
660}
661
662static void insertInSortedOrder(SmallVector<Value> &sortedDataClauseOperands,
663 Operation *newClause) {
664 auto *insertPos =
665 std::find_if(sortedDataClauseOperands.begin(),
666 sortedDataClauseOperands.end(), [&](Value dataClauseVal) {
667 // Get the base refs for the current clause we are looking
668 // at.
669 auto var = acc::getVar(dataClauseVal.getDefiningOp());
670 auto baseRefs = getBaseRefsChain(var);
671
672 // If the newClause is of a base ref of an existing clause,
673 // we should insert it right before the current clause.
674 // Thus return true to stop iteration when this is the
675 // case.
676 return std::find(baseRefs.begin(), baseRefs.end(),
677 acc::getVar(newClause)) != baseRefs.end();
678 });
679
680 if (insertPos != sortedDataClauseOperands.end()) {
681 newClause->moveBefore(insertPos->getDefiningOp());
682 sortedDataClauseOperands.insert(insertPos, acc::getAccVar(newClause));
683 } else {
684 sortedDataClauseOperands.push_back(acc::getAccVar(newClause));
685 }
686}
687
688template <typename OpT>
689void ACCImplicitData::generateImplicitDataOps(
690 ModuleOp &module, OpT computeConstructOp,
691 std::optional<acc::ClauseDefaultValue> &defaultClause,
692 acc::OpenACCSupport &accSupport) {
693 // Implicit data attributes are only applied if "[t]here is no default(none)
694 // clause visible at the compute construct."
695 if (defaultClause.has_value() &&
696 defaultClause.value() == acc::ClauseDefaultValue::None)
697 return;
698 assert(!defaultClause.has_value() ||
699 defaultClause.value() == acc::ClauseDefaultValue::Present);
700
701 // 1) Collect live-in values.
702 Region &accRegion = computeConstructOp->getRegion(0);
703 SetVector<Value> liveInValues;
704 getUsedValuesDefinedAbove(accRegion, liveInValues);
705
706 // 2) Run the filtering to find relevant pointers that need copied.
707 auto isCandidate{[&](Value val) -> bool {
708 return isCandidateForImplicitData(val, accRegion, accSupport);
709 }};
710 auto candidateVars(
711 llvm::to_vector(llvm::make_filter_range(liveInValues, isCandidate)));
712 if (candidateVars.empty())
713 return;
714
715 // 3) Generate data clauses for the variables.
716 SmallVector<Value> newPrivateOperands;
717 SmallVector<Value> newDataClauseOperands;
718 OpBuilder builder(computeConstructOp);
719 if (!candidateVars.empty()) {
720 LLVM_DEBUG(llvm::dbgs() << "== Generating clauses for ==\n"
721 << computeConstructOp << "\n");
722 }
723 auto &domInfo = this->getAnalysis<DominanceInfo>();
724 auto &postDomInfo = this->getAnalysis<PostDominanceInfo>();
725 auto dominatingDataClauses =
726 acc::getDominatingDataClauses(computeConstructOp, domInfo, postDomInfo);
727 for (auto var : candidateVars) {
728 auto newDataClauseOp = generateDataClauseOpForCandidate(
729 var, module, builder, computeConstructOp, dominatingDataClauses,
730 defaultClause);
731 fillInBoundsForUnknownDimensions(newDataClauseOp, builder);
732 LLVM_DEBUG(llvm::dbgs() << "Generated data clause for " << var << ":\n"
733 << "\t" << *newDataClauseOp << "\n");
734 if (isa_and_nonnull<acc::PrivateOp, acc::FirstprivateOp, acc::ReductionOp>(
735 newDataClauseOp)) {
736 newPrivateOperands.push_back(acc::getAccVar(newDataClauseOp));
737 } else if (isa_and_nonnull<ACC_DATA_CLAUSE_OPS>(newDataClauseOp)) {
738 newDataClauseOperands.push_back(acc::getAccVar(newDataClauseOp));
739 dominatingDataClauses.push_back(acc::getAccVar(newDataClauseOp));
740 }
741 }
742
743 // 4) Legalize values in region (aka the uses in the region are the result
744 // of the data clause ops)
745 legalizeValuesInRegion(accRegion, newPrivateOperands, newDataClauseOperands);
746
747 // 5) Generate private recipes which are required for properly attaching
748 // private operands.
749 if constexpr (!std::is_same_v<OpT, acc::KernelsOp> &&
750 !std::is_same_v<OpT, acc::KernelEnvironmentOp>)
751 generateRecipes(module, builder, computeConstructOp, newPrivateOperands);
752
753 // 6) Figure out insertion order for the new data clause operands.
754 SmallVector<Value> sortedDataClauseOperands(
755 computeConstructOp.getDataClauseOperands());
756 for (auto newClause : newDataClauseOperands)
757 insertInSortedOrder(sortedDataClauseOperands, newClause.getDefiningOp());
758
759 // 7) Generate the data exit operations.
760 generateDataExitOperations(builder, computeConstructOp, newDataClauseOperands,
761 sortedDataClauseOperands);
762 // 8) Add all of the new operands to the compute construct op.
763 if constexpr (!std::is_same_v<OpT, acc::KernelsOp> &&
764 !std::is_same_v<OpT, acc::KernelEnvironmentOp>)
765 addNewPrivateOperands(computeConstructOp, newPrivateOperands);
766 computeConstructOp.getDataClauseOperandsMutable().assign(
767 sortedDataClauseOperands);
768}
769
770void ACCImplicitData::runOnOperation() {
771 ModuleOp module = this->getOperation();
772
773 acc::OpenACCSupport &accSupport = getAnalysis<acc::OpenACCSupport>();
774
775 module.walk([&](Operation *op) {
776 if (isa<ACC_COMPUTE_CONSTRUCT_OPS, acc::KernelEnvironmentOp>(op)) {
777 assert(op->getNumRegions() == 1 && "must have 1 region");
778
779 auto defaultClause = acc::getDefaultAttr(op);
781 .Case<ACC_COMPUTE_CONSTRUCT_OPS, acc::KernelEnvironmentOp>(
782 [&](auto op) {
783 generateImplicitDataOps(module, op, defaultClause, accSupport);
784 })
785 .Default([&](Operation *) {});
786 }
787 });
788}
789
790} // namespace
#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
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.
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:4835
mlir::Value getVar(mlir::Operation *accDataClauseOp)
Used to obtain the var from a data clause operation.
Definition OpenACC.cpp:4804
std::optional< mlir::acc::DataClause > getDataClause(mlir::Operation *accDataEntryOp)
Used to obtain the dataClause from a data entry operation.
Definition OpenACC.cpp:4908
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:4853
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:4897
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
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.
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