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// }
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#include "llvm/ADT/SmallVectorExtras.h"
202
207#include "mlir/IR/Builders.h"
208#include "mlir/IR/BuiltinOps.h"
209#include "mlir/IR/Dominance.h"
210#include "mlir/IR/Operation.h"
211#include "mlir/IR/Value.h"
215#include "llvm/ADT/STLExtras.h"
216#include "llvm/ADT/SmallVector.h"
217#include "llvm/ADT/TypeSwitch.h"
218#include "llvm/Support/ErrorHandling.h"
219#include <type_traits>
220
221namespace mlir {
222namespace acc {
223#define GEN_PASS_DEF_ACCIMPLICITDATA
224#include "mlir/Dialect/OpenACC/Transforms/Passes.h.inc"
225} // namespace acc
226} // namespace mlir
227
228#define DEBUG_TYPE "acc-implicit-data"
229
230using namespace mlir;
231
232namespace {
233
234class ACCImplicitData : public acc::impl::ACCImplicitDataBase<ACCImplicitData> {
235public:
236 using acc::impl::ACCImplicitDataBase<ACCImplicitData>::ACCImplicitDataBase;
237
238 void runOnOperation() override;
239
240private:
241 /// Looks through the `dominatingDataClauses` to find the original data clause
242 /// op for an alias. Returns nullptr if no original data clause op is found.
243 template <typename OpT>
244 Operation *getOriginalDataClauseOpForAlias(
245 Value var, OpBuilder &builder, OpT computeConstructOp,
246 const SmallVector<Value> &dominatingDataClauses);
247
248 /// Generates the appropriate `acc.copyin`, `acc.present`,`acc.firstprivate`,
249 /// etc. data clause op for a candidate variable.
250 template <typename OpT>
251 Operation *generateDataClauseOpForCandidate(
252 Value var, ModuleOp &module, OpBuilder &builder, OpT computeConstructOp,
253 const SmallVector<Value> &dominatingDataClauses,
254 const std::optional<acc::ClauseDefaultValue> &defaultClause);
255
256 /// Generates the implicit data ops for a compute construct.
257 template <typename OpT>
258 void
259 generateImplicitDataOps(ModuleOp &module, OpT computeConstructOp,
260 std::optional<acc::ClauseDefaultValue> &defaultClause,
261 acc::OpenACCSupport &accSupport);
262
263 /// Generates a private recipe for a variable.
264 acc::PrivateRecipeOp generatePrivateRecipe(ModuleOp &module, Value var,
265 Location loc, OpBuilder &builder,
266 acc::OpenACCSupport &accSupport);
267
268 /// Generates a firstprivate recipe for a variable.
269 acc::FirstprivateRecipeOp
270 generateFirstprivateRecipe(ModuleOp &module, Value var, Location loc,
271 OpBuilder &builder,
272 acc::OpenACCSupport &accSupport);
273
274 /// Generates recipes for a list of variables.
275 void generateRecipes(ModuleOp &module, OpBuilder &builder,
276 Operation *computeConstructOp,
277 const SmallVector<Value> &newOperands);
278};
279
280/// Determines if a variable is a candidate for implicit data mapping.
281/// Returns true if the variable is a candidate, false otherwise.
282static bool isCandidateForImplicitData(Value val, Region &accRegion,
283 acc::OpenACCSupport &accSupport) {
284 // Ensure the variable is an allowed type for data clause.
285 if (!acc::isPointerLikeType(val.getType()) &&
287 return false;
288
289 // If this is already coming from a data clause, we do not need to generate
290 // another.
291 if (isa_and_nonnull<ACC_DATA_ENTRY_OPS>(val.getDefiningOp()))
292 return false;
293
294 // Device data is a candidate - it will get a deviceptr clause.
295 if (acc::isDeviceValue(val))
296 return true;
297
298 // If it is otherwise valid, skip it.
299 if (accSupport.isValidValueUse(val, accRegion))
300 return false;
301
302 return true;
303}
304
305template <typename OpT>
306Operation *ACCImplicitData::getOriginalDataClauseOpForAlias(
307 Value var, OpBuilder &builder, OpT computeConstructOp,
308 const SmallVector<Value> &dominatingDataClauses) {
309 auto &aliasAnalysis = this->getAnalysis<AliasAnalysis>();
310 for (auto dataClause : dominatingDataClauses) {
311 if (auto *dataClauseOp = dataClause.getDefiningOp()) {
312 // Only accept clauses that guarantee that the alias is present.
313 if (isa<acc::CopyinOp, acc::CreateOp, acc::PresentOp, acc::NoCreateOp,
314 acc::DevicePtrOp>(dataClauseOp))
315 if (aliasAnalysis.alias(acc::getVar(dataClauseOp), var).isMust())
316 return dataClauseOp;
317 }
318 }
319 return nullptr;
320}
321
322// Generates bounds for variables that have unknown dimensions
323static void fillInBoundsForUnknownDimensions(Operation *dataClauseOp,
324 OpBuilder &builder) {
325
326 if (!acc::getBounds(dataClauseOp).empty())
327 // If bounds are already present, do not overwrite them.
328 return;
329
330 // For types that have unknown dimensions, attempt to generate bounds by
331 // relying on MappableType being able to extract it from the IR.
332 auto var = acc::getVar(dataClauseOp);
333 auto type = var.getType();
334 if (auto mappableTy = dyn_cast<acc::MappableType>(type)) {
335 if (mappableTy.hasUnknownDimensions()) {
336 TypeSwitch<Operation *>(dataClauseOp)
337 .Case<ACC_DATA_ENTRY_OPS, ACC_DATA_EXIT_OPS>([&](auto dataClauseOp) {
338 if (std::is_same_v<decltype(dataClauseOp), acc::DevicePtrOp>)
339 return;
340 OpBuilder::InsertionGuard guard(builder);
341 builder.setInsertionPoint(dataClauseOp);
342 auto bounds = mappableTy.generateAccBounds(var, builder);
343 if (!bounds.empty())
344 dataClauseOp.getBoundsMutable().assign(bounds);
345 });
346 }
347 }
348}
349
350acc::PrivateRecipeOp
351ACCImplicitData::generatePrivateRecipe(ModuleOp &module, Value var,
352 Location loc, OpBuilder &builder,
353 acc::OpenACCSupport &accSupport) {
354 auto type = var.getType();
355 std::string recipeName =
356 accSupport.getRecipeName(acc::RecipeKind::private_recipe, type, var);
357
358 // Check if recipe already exists
359 auto existingRecipe = module.lookupSymbol<acc::PrivateRecipeOp>(recipeName);
360 if (existingRecipe)
361 return existingRecipe;
362
363 // Set insertion point to module body in a scoped way
364 OpBuilder::InsertionGuard guard(builder);
365 builder.setInsertionPointToStart(module.getBody());
366
367 auto recipe =
368 acc::PrivateRecipeOp::createAndPopulate(builder, loc, recipeName, type);
369 if (!recipe.has_value())
370 return accSupport.emitNYI(loc, "implicit private"), nullptr;
371 return recipe.value();
372}
373
374acc::FirstprivateRecipeOp
375ACCImplicitData::generateFirstprivateRecipe(ModuleOp &module, Value var,
376 Location loc, OpBuilder &builder,
377 acc::OpenACCSupport &accSupport) {
378 auto type = var.getType();
379 std::string recipeName =
380 accSupport.getRecipeName(acc::RecipeKind::firstprivate_recipe, type, var);
381
382 // Check if recipe already exists
383 auto existingRecipe =
384 module.lookupSymbol<acc::FirstprivateRecipeOp>(recipeName);
385 if (existingRecipe)
386 return existingRecipe;
387
388 // Set insertion point to module body in a scoped way
389 OpBuilder::InsertionGuard guard(builder);
390 builder.setInsertionPointToStart(module.getBody());
391
392 auto recipe = acc::FirstprivateRecipeOp::createAndPopulate(builder, loc,
393 recipeName, type);
394 if (!recipe.has_value())
395 return accSupport.emitNYI(loc, "implicit firstprivate"), nullptr;
396 return recipe.value();
397}
398
399void ACCImplicitData::generateRecipes(ModuleOp &module, OpBuilder &builder,
400 Operation *computeConstructOp,
401 const SmallVector<Value> &newOperands) {
402 auto &accSupport = this->getAnalysis<acc::OpenACCSupport>();
403 for (auto var : newOperands) {
404 auto loc{var.getLoc()};
405 if (auto privateOp = var.getDefiningOp<acc::PrivateOp>()) {
406 auto recipe = generatePrivateRecipe(
407 module, acc::getVar(var.getDefiningOp()), loc, builder, accSupport);
408 if (recipe)
409 privateOp.setRecipeAttr(
410 SymbolRefAttr::get(module->getContext(), recipe.getSymName()));
411 } else if (auto firstprivateOp = var.getDefiningOp<acc::FirstprivateOp>()) {
412 auto recipe = generateFirstprivateRecipe(
413 module, acc::getVar(var.getDefiningOp()), loc, builder, accSupport);
414 if (recipe)
415 firstprivateOp.setRecipeAttr(SymbolRefAttr::get(
416 module->getContext(), recipe.getSymName().str()));
417 } else {
418 accSupport.emitNYI(var.getLoc(), "implicit reduction");
419 }
420 }
421}
422
423// Generates the data entry data op clause so that it adheres to OpenACC
424// rules as follows (line numbers and specification from OpenACC 3.4):
425// 1388 An aggregate variable will be treated as if it appears either:
426// 1389 - In a present clause if there is a default(present) clause visible at
427// the compute construct.
428// 1391 - In a copy clause otherwise.
429// 1392 A scalar variable will be treated as if it appears either:
430// 1393 - In a copy clause if the compute construct is a kernels construct.
431// 1394 - In a firstprivate clause otherwise.
432template <typename OpT>
433Operation *ACCImplicitData::generateDataClauseOpForCandidate(
434 Value var, ModuleOp &module, OpBuilder &builder, OpT computeConstructOp,
435 const SmallVector<Value> &dominatingDataClauses,
436 const std::optional<acc::ClauseDefaultValue> &defaultClause) {
437 auto &accSupport = this->getAnalysis<acc::OpenACCSupport>();
438 acc::VariableTypeCategory typeCategory =
439 acc::VariableTypeCategory::uncategorized;
440 if (auto mappableTy = dyn_cast<acc::MappableType>(var.getType())) {
441 typeCategory = mappableTy.getTypeCategory(var);
442 } else if (auto pointerLikeTy =
443 dyn_cast<acc::PointerLikeType>(var.getType())) {
444 typeCategory = pointerLikeTy.getPointeeTypeCategory(
446 pointerLikeTy.getElementType());
447 }
448
449 bool isScalar =
450 acc::bitEnumContainsAny(typeCategory, acc::VariableTypeCategory::scalar);
451 bool isAnyAggregate = acc::bitEnumContainsAny(
452 typeCategory, acc::VariableTypeCategory::aggregate);
453 Location loc = computeConstructOp->getLoc();
454
455 Operation *op = nullptr;
456 op = getOriginalDataClauseOpForAlias(var, builder, computeConstructOp,
457 dominatingDataClauses);
458 if (op) {
459 if (isa<acc::NoCreateOp>(op))
460 return acc::NoCreateOp::create(builder, loc, var,
461 /*structured=*/true, /*implicit=*/true,
462 accSupport.getVariableName(var),
463 acc::getBounds(op));
464
465 if (isa<acc::DevicePtrOp>(op))
466 return acc::DevicePtrOp::create(builder, loc, var,
467 /*structured=*/true, /*implicit=*/true,
468 accSupport.getVariableName(var),
469 acc::getBounds(op));
470
471 // The original data clause op is a PresentOp, CopyinOp, or CreateOp,
472 // hence guaranteed to be present.
473 return acc::PresentOp::create(builder, loc, var,
474 /*structured=*/true, /*implicit=*/true,
475 accSupport.getVariableName(var),
476 acc::getBounds(op));
477 }
478
479 if (acc::isDeviceValue(var)) {
480 // If the variable is device data, use deviceptr clause.
481 return acc::DevicePtrOp::create(builder, loc, var,
482 /*structured=*/true, /*implicit=*/true,
483 accSupport.getVariableName(var));
484 }
485
486 if (isScalar) {
487 if (enableImplicitReductionCopy &&
489 computeConstructOp->getRegion(0))) {
490 auto copyinOp =
491 acc::CopyinOp::create(builder, loc, var,
492 /*structured=*/true, /*implicit=*/true,
493 accSupport.getVariableName(var));
494 copyinOp.setDataClause(acc::DataClause::acc_reduction);
495 return copyinOp.getOperation();
496 }
497 if constexpr (std::is_same_v<OpT, acc::KernelsOp> ||
498 std::is_same_v<OpT, acc::KernelEnvironmentOp>) {
499 // Scalars are implicit copyin in kernels construct.
500 // We also do the same for acc.kernel_environment because semantics
501 // of user variable mappings should be applied while ACC construct exists
502 // and at this point we should only be dealing with unmapped variables
503 // that were made live-in by the compiler.
504 // TODO: This may be revisited.
505 auto copyinOp =
506 acc::CopyinOp::create(builder, loc, var,
507 /*structured=*/true, /*implicit=*/true,
508 accSupport.getVariableName(var));
509 copyinOp.setDataClause(acc::DataClause::acc_copy);
510 return copyinOp.getOperation();
511 } else {
512 // Scalars are implicit firstprivate in parallel and serial construct.
513 return acc::FirstprivateOp::create(builder, loc, var,
514 /*structured=*/true, /*implicit=*/true,
515 accSupport.getVariableName(var));
516 }
517 } else if (isAnyAggregate) {
518 Operation *newDataOp = nullptr;
519
520 // When default(present) is true, the implicit behavior is present.
521 if (defaultClause.has_value() &&
522 defaultClause.value() == acc::ClauseDefaultValue::Present) {
523 newDataOp = acc::PresentOp::create(builder, loc, var,
524 /*structured=*/true, /*implicit=*/true,
525 accSupport.getVariableName(var));
527 builder.getUnitAttr());
528 } else {
529 auto copyinOp =
530 acc::CopyinOp::create(builder, loc, var,
531 /*structured=*/true, /*implicit=*/true,
532 accSupport.getVariableName(var));
533 copyinOp.setDataClause(acc::DataClause::acc_copy);
534 newDataOp = copyinOp.getOperation();
535 }
536
537 return newDataOp;
538 } else {
539 // This is not a fatal error - for example when the element type is
540 // pointer type (aka we have a pointer of pointer), it is potentially a
541 // deep copy scenario which is not being handled here.
542 // Other types need to be canonicalized. Thus just log unhandled cases.
543 LLVM_DEBUG(llvm::dbgs()
544 << "Unhandled case for implicit data mapping " << var << "\n");
545 }
546 return nullptr;
547}
548
549// Ensures that result values from the acc data clause ops are used inside the
550// acc region. ie:
551// acc.kernels {
552// use %val
553// }
554// =>
555// %dev = acc.dataop %val
556// acc.kernels {
557// use %dev
558// }
559static void legalizeValuesInRegion(Region &accRegion,
560 SmallVector<Value> &newPrivateOperands,
561 SmallVector<Value> &newDataClauseOperands) {
562 for (Value dataClause :
563 llvm::concat<Value>(newDataClauseOperands, newPrivateOperands)) {
564 Value var = acc::getVar(dataClause.getDefiningOp());
565 replaceAllUsesInRegionWith(var, dataClause, accRegion);
566 }
567}
568
569// Adds the private operands to the compute construct operation.
570template <typename OpT>
571static void addNewPrivateOperands(OpT &accOp,
572 const SmallVector<Value> &privateOperands) {
573 if (privateOperands.empty())
574 return;
575
576 for (auto priv : privateOperands) {
577 if (isa<acc::PrivateOp>(priv.getDefiningOp())) {
578 accOp.getPrivateOperandsMutable().append(priv);
579 } else if (isa<acc::FirstprivateOp>(priv.getDefiningOp())) {
580 accOp.getFirstprivateOperandsMutable().append(priv);
581 } else {
582 llvm_unreachable("unhandled reduction operand");
583 }
584 }
585}
586
587static Operation *findDataExitOp(Operation *dataEntryOp) {
588 auto res = acc::getAccVar(dataEntryOp);
589 for (auto *user : res.getUsers())
590 if (isa<ACC_DATA_EXIT_OPS>(user))
591 return user;
592 return nullptr;
593}
594
595// Generates matching data exit operation as described in the acc dialect
596// for how data clauses are decomposed:
597// https://mlir.llvm.org/docs/Dialects/OpenACCDialect/#operation-categories
598// Key ones used here:
599// * acc {construct} copy -> acc.copyin (before region) + acc.copyout (after
600// region)
601// * acc {construct} present -> acc.present (before region) + acc.delete
602// (after region)
603static void
604generateDataExitOperations(OpBuilder &builder, Operation *accOp,
605 const SmallVector<Value> &newDataClauseOperands,
606 const SmallVector<Value> &sortedDataClauseOperands) {
607 builder.setInsertionPointAfter(accOp);
608 Value lastDataClause = nullptr;
609 for (auto dataEntry : llvm::reverse(sortedDataClauseOperands)) {
610 if (llvm::find(newDataClauseOperands, dataEntry) ==
611 newDataClauseOperands.end()) {
612 // If this is not a new data clause operand, we should not generate an
613 // exit operation for it.
614 lastDataClause = dataEntry;
615 continue;
616 }
617 if (lastDataClause)
618 if (auto *dataExitOp = findDataExitOp(lastDataClause.getDefiningOp()))
619 builder.setInsertionPointAfter(dataExitOp);
620 Operation *dataEntryOp = dataEntry.getDefiningOp();
621 if (isa<acc::CopyinOp>(dataEntryOp)) {
622 auto copyoutOp = acc::CopyoutOp::create(
623 builder, dataEntryOp->getLoc(), dataEntry, acc::getVar(dataEntryOp),
624 /*structured=*/true, /*implicit=*/true,
625 acc::getVarName(dataEntryOp).value(), acc::getBounds(dataEntryOp));
626 copyoutOp.setDataClause(acc::DataClause::acc_copy);
627 } else if (isa<acc::PresentOp, acc::NoCreateOp>(dataEntryOp)) {
628 auto deleteOp = acc::DeleteOp::create(
629 builder, dataEntryOp->getLoc(), dataEntry,
630 /*structured=*/true, /*implicit=*/true,
631 acc::getVarName(dataEntryOp).value(), acc::getBounds(dataEntryOp));
632 deleteOp.setDataClause(acc::getDataClause(dataEntryOp).value());
633 } else if (isa<acc::DevicePtrOp>(dataEntryOp)) {
634 // Do nothing.
635 } else {
636 llvm_unreachable("unhandled data exit");
637 }
638 lastDataClause = dataEntry;
639 }
640}
641
642/// Returns all base references of a value in order.
643/// So for example, if we have a reference to a struct field like
644/// s.f1.f2.f3, this will return <s, s.f1, s.f1.f2, s.f1.f2.f3>.
645/// Any intermediate casts/view-like operations are included in the
646/// chain as well.
647static SmallVector<Value> getBaseRefsChain(Value val) {
648 SmallVector<Value> baseRefs;
649 baseRefs.push_back(val);
650 while (true) {
651 Value prevVal = val;
652
653 val = acc::getBaseEntity(val);
654 if (val != baseRefs.front())
655 baseRefs.insert(baseRefs.begin(), val);
656
657 // If this is a view-like operation, it is effectively another
658 // view of the same entity so we should add it to the chain also.
659 if (auto viewLikeOp = val.getDefiningOp<ViewLikeOpInterface>()) {
660 val = viewLikeOp.getViewSource();
661 baseRefs.insert(baseRefs.begin(), val);
662 }
663
664 // Continue loop if we made any progress
665 if (val == prevVal)
666 break;
667 }
668
669 return baseRefs;
670}
671
672static void insertInSortedOrder(SmallVector<Value> &sortedDataClauseOperands,
673 Operation *newClause) {
674 auto *insertPos =
675 std::find_if(sortedDataClauseOperands.begin(),
676 sortedDataClauseOperands.end(), [&](Value dataClauseVal) {
677 // Get the base refs for the current clause we are looking
678 // at.
679 auto var = acc::getVar(dataClauseVal.getDefiningOp());
680 auto baseRefs = getBaseRefsChain(var);
681
682 // If the newClause is of a base ref of an existing clause,
683 // we should insert it right before the current clause.
684 // Thus return true to stop iteration when this is the
685 // case.
686 return std::find(baseRefs.begin(), baseRefs.end(),
687 acc::getVar(newClause)) != baseRefs.end();
688 });
689
690 if (insertPos != sortedDataClauseOperands.end()) {
691 newClause->moveBefore(insertPos->getDefiningOp());
692 sortedDataClauseOperands.insert(insertPos, acc::getAccVar(newClause));
693 } else {
694 sortedDataClauseOperands.push_back(acc::getAccVar(newClause));
695 }
696}
697
698template <typename OpT>
699void ACCImplicitData::generateImplicitDataOps(
700 ModuleOp &module, OpT computeConstructOp,
701 std::optional<acc::ClauseDefaultValue> &defaultClause,
702 acc::OpenACCSupport &accSupport) {
703 // Implicit data attributes are only applied if "[t]here is no default(none)
704 // clause visible at the compute construct."
705 if (defaultClause.has_value() &&
706 defaultClause.value() == acc::ClauseDefaultValue::None)
707 return;
708 assert(!defaultClause.has_value() ||
709 defaultClause.value() == acc::ClauseDefaultValue::Present);
710
711 // 1) Collect live-in values.
712 Region &accRegion = computeConstructOp->getRegion(0);
713 SetVector<Value> liveInValues;
714 getUsedValuesDefinedAbove(accRegion, liveInValues);
715
716 // 2) Run the filtering to find relevant pointers that need copied.
717 auto isCandidate{[&](Value val) -> bool {
718 return isCandidateForImplicitData(val, accRegion, accSupport);
719 }};
720 auto candidateVars(llvm::filter_to_vector(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:102
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:350
This class helps build Operations.
Definition Builders.h:209
void setInsertionPointToStart(Block *block)
Sets the insertion point to the start of the specified block.
Definition Builders.h:433
void setInsertionPoint(Block *block, Block::iterator insertPoint)
Set the insertion point to the specified location.
Definition Builders.h:400
void setInsertionPointAfter(Operation *op)
Sets the insertion point to the node after the specified operation, which will cause subsequent inser...
Definition Builders.h:414
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:58
#define ACC_DATA_ENTRY_OPS
Definition OpenACC.h:46
#define ACC_DATA_EXIT_OPS
Definition OpenACC.h:54
static constexpr StringLiteral getFromDefaultClauseAttrName()
Definition OpenACC.h:200
mlir::Value getAccVar(mlir::Operation *accDataClauseOp)
Used to obtain the accVar from a data clause operation.
Definition OpenACC.cpp:5191
mlir::Value getVar(mlir::Operation *accDataClauseOp)
Used to obtain the var from a data clause operation.
Definition OpenACC.cpp:5160
std::optional< mlir::acc::DataClause > getDataClause(mlir::Operation *accDataEntryOp)
Used to obtain the dataClause from a data entry operation.
Definition OpenACC.cpp:5264
bool isPointerLikeType(mlir::Type type)
Used to check whether the provided type implements the PointerLikeType interface.
Definition OpenACC.h:161
mlir::SmallVector< mlir::Value > getBounds(mlir::Operation *accDataClauseOp)
Used to obtain bounds from an acc data clause operation.
Definition OpenACC.cpp:5209
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:5253
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:167
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:123
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:136