MLIR 24.0.0git
OpenMPToLLVMIRTranslation.cpp
Go to the documentation of this file.
1//===- OpenMPToLLVMIRTranslation.cpp - Translate OpenMP dialect to LLVM IR-===//
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 file implements a translation between the MLIR OpenMP dialect and LLVM
10// IR.
11//
12//===----------------------------------------------------------------------===//
21#include "mlir/IR/Operation.h"
23#include "mlir/Support/LLVM.h"
26
27#include "llvm/ADT/ArrayRef.h"
28#include "llvm/ADT/SmallVector.h"
29#include "llvm/ADT/TypeSwitch.h"
30#include "llvm/Frontend/OpenMP/OMPConstants.h"
31#include "llvm/Frontend/OpenMP/OMPIRBuilder.h"
32#include "llvm/IR/Constants.h"
33#include "llvm/IR/DebugInfoMetadata.h"
34#include "llvm/IR/DerivedTypes.h"
35#include "llvm/IR/IRBuilder.h"
36#include "llvm/IR/MDBuilder.h"
37#include "llvm/IR/ReplaceConstant.h"
38#include "llvm/Support/AMDGPUAddrSpace.h"
39#include "llvm/Support/CommandLine.h"
40#include "llvm/Support/FileSystem.h"
41#include "llvm/Support/MathExtras.h"
42#include "llvm/Support/NVPTXAddrSpace.h"
43#include "llvm/Support/SaveAndRestore.h"
44#include "llvm/Support/VirtualFileSystem.h"
45#include "llvm/TargetParser/Triple.h"
46#include "llvm/Transforms/Utils/ModuleUtils.h"
47
48#include <cstdint>
49#include <iterator>
50#include <numeric>
51#include <optional>
52#include <utility>
53
54using namespace mlir;
55
57getPrivateDataAddress(llvm::IRBuilderBase &builder,
58 LLVM::ModuleTranslation &moduleTranslation,
59 omp::PrivateClauseOp privatizer, llvm::Value *var);
60
61namespace {
62/// Stores the option value so the OpenMP-to-LLVM IR translation can read it
63/// outside registerOpenMPTranslationCLOptions(). The local cl::opt avoids a
64/// global constructor in MLIR and writes to this variable through cl::location.
65/// Without registration, false keeps Virtual enabled for eligible loops.
66static bool disableVirtualCollapse = false;
67
68static llvm::omp::ScheduleKind
69convertToScheduleKind(std::optional<omp::ClauseScheduleKind> schedKind) {
70 if (!schedKind.has_value())
71 return llvm::omp::OMP_SCHEDULE_Default;
72 switch (schedKind.value()) {
73 case omp::ClauseScheduleKind::Static:
74 return llvm::omp::OMP_SCHEDULE_Static;
75 case omp::ClauseScheduleKind::Dynamic:
76 return llvm::omp::OMP_SCHEDULE_Dynamic;
77 case omp::ClauseScheduleKind::Guided:
78 return llvm::omp::OMP_SCHEDULE_Guided;
79 case omp::ClauseScheduleKind::Auto:
80 return llvm::omp::OMP_SCHEDULE_Auto;
81 case omp::ClauseScheduleKind::Runtime:
82 return llvm::omp::OMP_SCHEDULE_Runtime;
83 case omp::ClauseScheduleKind::Distribute:
84 return llvm::omp::OMP_SCHEDULE_Distribute;
85 }
86 llvm_unreachable("unhandled schedule clause argument");
87}
88
89/// ModuleTranslation stack frame for OpenMP operations. This keeps track of the
90/// blocks in which allocas are emitted.
91class OpenMPAllocStackFrame
92 : public StateStackFrameBase<OpenMPAllocStackFrame> {
93public:
95
96 explicit OpenMPAllocStackFrame(
97 llvm::BasicBlock *allocBlock,
98 llvm::ArrayRef<llvm::BasicBlock *> deallocBlocks)
99 : allocBlock(allocBlock), deallocBlocks(deallocBlocks) {}
100 llvm::BasicBlock *allocBlock;
101 llvm::SmallVector<llvm::BasicBlock *> deallocBlocks;
102};
103
104/// Stack frame to hold a \see llvm::CanonicalLoopInfo representing the
105/// collapsed canonical loop information corresponding to an \c omp.loop_nest
106/// operation.
107class OpenMPLoopInfoStackFrame
108 : public StateStackFrameBase<OpenMPLoopInfoStackFrame> {
109public:
110 MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(OpenMPLoopInfoStackFrame)
111 llvm::CanonicalLoopInfo *loopInfo = nullptr;
112};
113
114/// OpenMP state that lives as long as the module translation: the
115/// OpenMPIRBuilder associated with the LLVM module being constructed and the
116/// not yet consumed canonical loop handles.
117class OpenMPTranslationState : public LLVM::ModuleTranslation::Extension {
118public:
120
121 explicit OpenMPTranslationState(llvm::Module &module) : ompBuilder(module) {
122 // Flags represented as top-level OpenMP dialect attributes are set in
123 // `OpenMPDialectLLVMIRTranslationInterface::amendOperation()`. Here we set
124 // the default configuration.
125 llvm::OpenMPIRBuilderConfig config(
126 /* IsTargetDevice = */ false, /* IsGPU = */ false,
127 /* OpenMPOffloadMandatory = */ false,
128 /* HasRequiresReverseOffload = */ false,
129 /* HasRequiresUnifiedAddress = */ false,
130 /* HasRequiresUnifiedSharedMemory = */ false,
131 /* HasRequiresDynamicAllocators = */ false);
132 config.setDefaultTargetAS(module.getDataLayout().getProgramAddressSpace());
133 config.setRuntimeCC(module.getTargetTriple().isSPIRV()
134 ? llvm::CallingConv::SPIR_FUNC
135 : llvm::CallingConv::C);
136 ompBuilder.setConfig(std::move(config));
137 ompBuilder.initialize();
138 }
139
140 ~OpenMPTranslationState() override {
141 if (!ompBuilder.isFinalized())
142 ompBuilder.finalize();
143 }
144
145 LogicalResult finalize() override {
146 ompBuilder.finalize();
147 return success();
148 }
149
150 /// Builder for LLVM IR generation of OpenMP constructs.
151 llvm::OpenMPIRBuilder ompBuilder;
152
153 /// List of not yet consumed MLIR loop handles (represented by an omp.new_cli
154 /// operation which creates a value of type CanonicalLoopInfoType) and their
155 /// LLVM-IR representation as CanonicalLoopInfo which is managed by the
156 /// OpenMPIRBuilder.
158};
159} // namespace
160
161static OpenMPTranslationState &
163 return moduleTranslation.getOrCreateExtension<OpenMPTranslationState>(
164 *moduleTranslation.getLLVMModule());
165}
166
167/// Returns the OpenMP IR builder associated with the LLVM IR module being
168/// constructed.
169static llvm::OpenMPIRBuilder *
171 return &getOpenMPState(moduleTranslation).ompBuilder;
172}
173
174/// Find the LLVM-IR loop that represents an MLIR loop.
175static llvm::CanonicalLoopInfo *
177 auto cli = mlir.getDefiningOp<omp::NewCliOp>();
178 llvm::CanonicalLoopInfo *result =
179 getOpenMPState(moduleTranslation).loopMapping.lookup(cli);
180 assert(result && "attempt to get non-existing loop");
181 return result;
182}
183
184/// Mark an OpenMP loop as having been consumed.
185static void invalidateOmpLoop(LLVM::ModuleTranslation &moduleTranslation,
186 Value mlir) {
187 auto cli = mlir.getDefiningOp<omp::NewCliOp>();
188 getOpenMPState(moduleTranslation).loopMapping.erase(cli);
189}
190
191/// Map an MLIR OpenMP dialect CanonicalLoopInfo to its lowered LLVM-IR
192/// OpenMPIRBuilder CanonicalLoopInfo.
193static void mapOmpLoop(LLVM::ModuleTranslation &moduleTranslation, Value mlir,
194 llvm::CanonicalLoopInfo *llvm) {
195 assert(llvm && "argument must be non-null");
196 auto cli = mlir.getDefiningOp<omp::NewCliOp>();
197 llvm::CanonicalLoopInfo *&cur =
198 getOpenMPState(moduleTranslation).loopMapping[cli];
199 assert(cur == nullptr && "attempting to map a loop that is already mapped");
200 cur = llvm;
201}
202
203namespace {
204/// Custom error class to signal translation errors that don't need reporting,
205/// since encountering them will have already triggered relevant error messages.
206///
207/// Its purpose is to serve as the glue between MLIR failures represented as
208/// \see LogicalResult instances and \see llvm::Error instances used to
209/// propagate errors through the \see llvm::OpenMPIRBuilder. Generally, when an
210/// error of the first type is raised, a message is emitted directly (the \see
211/// LogicalResult itself does not hold any information). If we need to forward
212/// this error condition as an \see llvm::Error while avoiding triggering some
213/// redundant error reporting later on, we need a custom \see llvm::ErrorInfo
214/// class to just signal this situation has happened.
215///
216/// For example, this class should be used to trigger errors from within
217/// callbacks passed to the \see OpenMPIRBuilder when they were triggered by the
218/// translation of their own regions. This unclutters the error log from
219/// redundant messages.
220class PreviouslyReportedError
221 : public llvm::ErrorInfo<PreviouslyReportedError> {
222public:
223 void log(raw_ostream &) const override {
224 // Do not log anything.
225 }
226
227 std::error_code convertToErrorCode() const override {
228 llvm_unreachable(
229 "PreviouslyReportedError doesn't support ECError conversion");
230 }
231
232 // Used by ErrorInfo::classID.
233 static char ID;
234};
235
236char PreviouslyReportedError::ID = 0;
237
238/*
239 * Custom class for processing linear clause for omp.wsloop
240 * and omp.simd. Linear clause translation requires setup,
241 * initialization, update, and finalization at varying
242 * basic blocks in the IR. This class helps maintain
243 * internal state to allow consistent translation in
244 * each of these stages.
245 */
246
247class LinearClauseProcessor {
248
249private:
250 SmallVector<llvm::Type *> linearVarTypes;
251 SmallVector<llvm::Value *> linearSteps;
252 // The `linear` privatizer, original and private copy of each linear var.
253 SmallVector<omp::PrivateClauseOp> linearPrivatizers;
254 SmallVector<llvm::Value *> linearOrigVars;
255 SmallVector<llvm::Value *> linearPrivateVars;
256 // The value of each linear var on entry to the loop.
257 SmallVector<llvm::Value *> linearStartVals;
258 llvm::BasicBlock *linearFinalizationBB;
259 llvm::BasicBlock *linearExitBB;
260 llvm::BasicBlock *linearLastIterExitBB;
261 std::optional<size_t> linearLoopIVIndex;
262
263 // Address of the value of linear var `index` held by `var`.
264 llvm::Expected<llvm::Value *>
265 getAddress(llvm::IRBuilderBase &builder,
266 LLVM::ModuleTranslation &moduleTranslation, size_t index,
267 llvm::Value *var) {
268 return getPrivateDataAddress(builder, moduleTranslation,
269 linearPrivatizers[index], var);
270 }
271
272 // Copy the current value of each linear var back to the original.
273 llvm::Error storeLinearVars(llvm::IRBuilderBase &builder,
274 LLVM::ModuleTranslation &moduleTranslation) {
275 for (size_t index = 0; index < linearOrigVars.size(); index++) {
276 llvm::Expected<llvm::Value *> from = getAddress(
277 builder, moduleTranslation, index, linearPrivateVars[index]);
278 if (!from)
279 return from.takeError();
280 llvm::LoadInst *linearVarTemp =
281 builder.CreateLoad(linearVarTypes[index], *from);
282 llvm::Expected<llvm::Value *> to =
283 getAddress(builder, moduleTranslation, index, linearOrigVars[index]);
284 if (!to)
285 return to.takeError();
286 builder.CreateStore(linearVarTemp, *to);
287 }
288 return llvm::Error::success();
289 }
290
291public:
292 // Register type for the linear variables
293 void registerType(LLVM::ModuleTranslation &moduleTranslation,
294 mlir::Attribute &ty) {
295 linearVarTypes.push_back(moduleTranslation.convertType(
296 mlir::cast<mlir::TypeAttr>(ty).getValue()));
297 }
298
299 // Register a linear var, allocating space for its start value at `allocaIP`
300 void createLinearVar(llvm::IRBuilderBase &builder,
301 const llvm::OpenMPIRBuilder::InsertPointTy &allocaIP,
302 omp::PrivateClauseOp privatizer, llvm::Value *origVar,
303 llvm::Value *privateVar, int idx) {
304 llvm::IRBuilderBase::InsertPointGuard guard(builder);
305 builder.SetInsertPoint(allocaIP.getNodeParent()->getTerminator());
306 linearStartVals.push_back(
307 builder.CreateAlloca(linearVarTypes[idx], nullptr, ".linear_var"));
308 linearPrivatizers.push_back(privatizer);
309 linearOrigVars.push_back(origVar);
310 linearPrivateVars.push_back(privateVar);
311 }
312
313 // Initialize linear step
314 inline void initLinearStep(LLVM::ModuleTranslation &moduleTranslation,
315 mlir::Value &linearStep) {
316 linearSteps.push_back(moduleTranslation.lookupValue(linearStep));
317 }
318
319 // Emit IR for initialization of linear variables
320 llvm::Error initLinearVar(llvm::IRBuilderBase &builder,
321 LLVM::ModuleTranslation &moduleTranslation,
322 llvm::BasicBlock *loopPreHeader) {
323 builder.SetInsertPoint(loopPreHeader->getTerminator());
324 for (size_t index = 0; index < linearOrigVars.size(); index++) {
325 llvm::Expected<llvm::Value *> orig =
326 getAddress(builder, moduleTranslation, index, linearOrigVars[index]);
327 if (!orig)
328 return orig.takeError();
329 llvm::LoadInst *linearVarLoad =
330 builder.CreateLoad(linearVarTypes[index], *orig);
331 builder.CreateStore(linearVarLoad, linearStartVals[index]);
332 }
333 return llvm::Error::success();
334 }
335
336 // Find linear iteration variable and save it for later updates
337 LogicalResult initLinearIV(omp::SimdOp simdOp) {
338 auto loopOp = cast<omp::LoopNestOp>(simdOp.getWrappedLoop());
339 // NOTE iteration variables can only be linear in non-nested loops.
340 if (loopOp.getIVs().size() != 1)
341 return success();
342 // Currently, frontends using `omp.simd` always generate a store from the
343 // `omp.loop_nest`'s IV to the corresponding iteration variable, possibly
344 // through the data address of its private copy.
345 //
346 // TODO Add an attribute to `omp.loop_nest` that explicitly lists the
347 // variables that correspond to the loop induction variables.
348 MutableArrayRef<BlockArgument> linearArgs =
349 cast<omp::BlockArgOpenMPOpInterface>(*simdOp).getLinearBlockArgs();
350 SmallVector<Value> ivValues{loopOp.getIVs().front()};
351 for (Operation *user : loopOp.getIVs().front().getUsers())
352 if (isa<LLVM::SExtOp, LLVM::ZExtOp, LLVM::TruncOp>(user))
353 ivValues.push_back(user->getResult(0));
354
355 for (Value ivValue : ivValues) {
356 for (Operation *user : ivValue.getUsers()) {
357 auto storeOp = dyn_cast<LLVM::StoreOp>(user);
358 if (!storeOp || storeOp.getValue() != ivValue)
359 continue;
360 // Look through loads, GEPs and copies of a private copy, e.g. of a
361 // descriptor, to find the linear block argument the IV is stored to.
362 Value addr = storeOp.getAddr();
363 while (true) {
364 Operation *def = addr.getDefiningOp();
365 if (auto load = dyn_cast_if_present<LLVM::LoadOp>(def)) {
366 addr = load.getAddr();
367 } else if (auto gep = dyn_cast_if_present<LLVM::GEPOp>(def)) {
368 addr = gep.getBase();
369 } else {
370 auto copy = llvm::find_if(addr.getUsers(), [&](Operation *user) {
371 auto memcpy = dyn_cast<LLVM::MemcpyOp>(user);
372 return memcpy && memcpy.getDst() == addr &&
373 llvm::is_contained(linearArgs, memcpy.getSrc());
374 });
375 if (copy == addr.getUsers().end())
376 break;
377 addr = cast<LLVM::MemcpyOp>(*copy).getSrc();
378 }
379 }
380 auto *it = llvm::find(linearArgs, addr);
381 if (it == linearArgs.end())
382 continue;
383 size_t index = std::distance(linearArgs.begin(), it);
384 if (linearLoopIVIndex && *linearLoopIVIndex != index)
385 return simdOp.emitError(
386 "Could not determine the linear variable associated with the "
387 "loop nest induction variable");
388 linearLoopIVIndex = index;
389 }
390 }
391 return success();
392 }
393
394 // Emit IR for updating Linear variables
395 llvm::Error updateLinearVar(llvm::IRBuilderBase &builder,
396 LLVM::ModuleTranslation &moduleTranslation,
397 llvm::BasicBlock *loopBody,
398 llvm::Value *loopInductionVar) {
399 builder.SetInsertPoint(loopBody->getTerminator());
400 for (size_t index = 0; index < linearStartVals.size(); index++) {
401 llvm::Type *linearVarType = linearVarTypes[index];
402 llvm::Value *iv = loopInductionVar;
403 llvm::Value *step = linearSteps[index];
404 llvm::Expected<llvm::Value *> result = getAddress(
405 builder, moduleTranslation, index, linearPrivateVars[index]);
406 if (!result)
407 return result.takeError();
408
409 if (!iv->getType()->isIntegerTy())
410 llvm_unreachable("OpenMP loop induction variable must be an integer "
411 "type");
412
413 if (linearVarType->isIntegerTy()) {
414 // Integer path: normalize all arithmetic to linearVarType
415 iv = builder.CreateSExtOrTrunc(iv, linearVarType);
416 step = builder.CreateSExtOrTrunc(step, linearVarType);
417
418 llvm::LoadInst *linearVarStart =
419 builder.CreateLoad(linearVarType, linearStartVals[index]);
420 llvm::Value *mulInst = builder.CreateMul(iv, step);
421 llvm::Value *addInst = builder.CreateAdd(linearVarStart, mulInst);
422 builder.CreateStore(addInst, *result);
423 } else if (linearVarType->isFloatingPointTy()) {
424 // Float path: perform multiply in integer, then convert to float
425 step = builder.CreateSExtOrTrunc(step, iv->getType());
426 llvm::Value *mulInst = builder.CreateMul(iv, step);
427
428 llvm::LoadInst *linearVarStart =
429 builder.CreateLoad(linearVarType, linearStartVals[index]);
430 llvm::Value *mulFp = builder.CreateSIToFP(mulInst, linearVarType);
431 llvm::Value *addInst = builder.CreateFAdd(linearVarStart, mulFp);
432 builder.CreateStore(addInst, *result);
433 } else {
434 llvm_unreachable(
435 "Linear variable must be of integer or floating-point type");
436 }
437 }
438 return llvm::Error::success();
439 }
440
441 // Emit IR for updating linear iteration variables on loop exit
442 llvm::Error updateLinearIV(llvm::IRBuilderBase &builder,
443 LLVM::ModuleTranslation &moduleTranslation) {
444 if (!linearLoopIVIndex)
445 return llvm::Error::success();
446 size_t index = *linearLoopIVIndex;
447
448 // Add one more step to the linear iteration variable
449 llvm::Type *varType = linearVarTypes[index];
450 if (!varType->isIntegerTy())
451 llvm_unreachable("Linear iteration variable must be of integer type");
452 llvm::Expected<llvm::Value *> var =
453 getAddress(builder, moduleTranslation, index, linearPrivateVars[index]);
454 if (!var)
455 return var.takeError();
456 llvm::Value *step = builder.CreateSExtOrTrunc(linearSteps[index], varType);
457 llvm::Value *val = builder.CreateLoad(varType, *var);
458 llvm::Value *addInst = builder.CreateAdd(val, step);
459 builder.CreateStore(addInst, *var);
460 return llvm::Error::success();
461 }
462
463 // Linear variable finalization is conditional on the last logical iteration.
464 // Create BB splits to manage the same.
465 void splitLinearFiniBB(llvm::IRBuilderBase &builder,
466 llvm::BasicBlock *loopExit) {
467 linearFinalizationBB = loopExit->splitBasicBlock(
468 loopExit->getTerminator(), "omp_loop.linear_finalization");
469 linearExitBB = linearFinalizationBB->splitBasicBlock(
470 linearFinalizationBB->getTerminator(), "omp_loop.linear_exit");
471 linearLastIterExitBB = linearFinalizationBB->splitBasicBlock(
472 linearFinalizationBB->getTerminator(), "omp_loop.linear_lastiter_exit");
473 }
474
475 // Finalize the linear vars
476 llvm::OpenMPIRBuilder::InsertPointOrErrorTy
477 finalizeLinearVar(llvm::IRBuilderBase &builder,
478 LLVM::ModuleTranslation &moduleTranslation,
479 llvm::Value *lastIter) {
480 // Emit condition to check whether last logical iteration is being executed
481 builder.SetInsertPoint(linearFinalizationBB->getTerminator());
482 llvm::Value *loopLastIterLoad = builder.CreateLoad(
483 llvm::Type::getInt32Ty(builder.getContext()), lastIter);
484 llvm::Value *isLast =
485 builder.CreateCmp(llvm::CmpInst::ICMP_NE, loopLastIterLoad,
486 llvm::ConstantInt::get(
487 llvm::Type::getInt32Ty(builder.getContext()), 0));
488 // Store the linear variable values to original variables.
489 builder.SetInsertPoint(linearLastIterExitBB->getTerminator());
490 if (llvm::Error err = storeLinearVars(builder, moduleTranslation))
491 return std::move(err);
492
493 // Create conditional branch such that the linear variable
494 // values are stored to original variables only at the
495 // last logical iteration
496 builder.SetInsertPoint(linearFinalizationBB->getTerminator());
497 builder.CreateCondBr(isLast, linearLastIterExitBB, linearExitBB);
498 linearFinalizationBB->getTerminator()->eraseFromParent();
499 // Emit barrier
500 builder.SetInsertPoint(linearExitBB->getTerminator());
501 return getOpenMPBuilder(moduleTranslation)
502 ->createBarrier(builder, llvm::omp::OMPD_barrier);
503 }
504
505 // Emit stores for linear variables. Useful in case of SIMD
506 // construct.
507 llvm::Error
508 emitStoresForLinearVar(llvm::IRBuilderBase &builder,
509 LLVM::ModuleTranslation &moduleTranslation) {
510 return storeLinearVars(builder, moduleTranslation);
511 }
512};
513} // namespace
514
515/// Looks up from the operation from and returns the PrivateClauseOp with
516/// name symbolName
517static omp::PrivateClauseOp findPrivatizer(Operation *from,
518 SymbolRefAttr symbolName) {
519 omp::PrivateClauseOp privatizer =
521 symbolName);
522 assert(privatizer && "privatizer not found in the symbol table");
523 return privatizer;
524}
525
526/// Check whether translation to LLVM IR for the given operation is currently
527/// supported. If not, descriptive diagnostics will be emitted to let users know
528/// this is a not-yet-implemented feature.
529///
530/// \returns success if no unimplemented features are needed to translate the
531/// given operation.
532static LogicalResult checkImplementationStatus(Operation &op) {
533 auto todo = [&op](StringRef clauseName) {
534 return op.emitError() << "not yet implemented: Unhandled clause "
535 << clauseName << " in " << op.getName()
536 << " operation";
537 };
538
539 auto checkAllocate = [&todo](auto op, LogicalResult &result) {
540 if (!op.getAllocateVars().empty() || !op.getAllocatorVars().empty())
541 result = todo("allocate");
542 };
543 auto checkBare = [&todo](auto op, LogicalResult &result) {
544 if (op.getKernelType() == omp::TargetExecMode::bare)
545 result = todo("ompx_bare");
546 };
547 auto checkDepend = [&todo](auto op, LogicalResult &result) {
548 if (!op.getDependVars().empty() || op.getDependKinds() ||
549 !op.getDependIterated().empty() || op.getDependIteratedKinds())
550 result = todo("depend");
551 };
552 auto checkHint = [](auto op, LogicalResult &) {
553 if (op.getHint())
554 op.emitWarning("hint clause discarded");
555 };
556 auto checkInReduction = [&todo](auto op, LogicalResult &result) {
557 if (isa<omp::TargetOp, omp::TaskOp, omp::TaskloopContextOp>(
558 op.getOperation())) {
559 if (auto byrefAttr = op.getInReductionByref()) {
560 for (bool isByRef : *byrefAttr) {
561 if (isByRef) {
562 result = todo("in_reduction with byref modifier");
563 return;
564 }
565 }
566 }
567 if (isa<omp::TargetOp>(op.getOperation())) {
568 if (auto inReductionSyms = op.getInReductionSyms()) {
569 for (auto sym :
570 (*inReductionSyms).template getAsRange<SymbolRefAttr>()) {
571 auto decl =
573 op, sym);
574 assert(decl &&
575 "symbol resolution should be guaranteed by the op verifier");
576 if (decl.getInitializerRegion().front().getNumArguments() != 1) {
577 result = todo("in_reduction with two-argument initializer");
578 return;
579 }
580 if (!decl.getCleanupRegion().empty()) {
581 result = todo("in_reduction with cleanup region");
582 return;
583 }
584 }
585 }
586 }
587 } else if (!op.getInReductionVars().empty() || op.getInReductionByref() ||
588 op.getInReductionSyms()) {
589 result = todo("in_reduction");
590 }
591 };
592 auto checkNowait = [&todo](auto op, LogicalResult &result) {
593 if (op.getNowait())
594 result = todo("nowait");
595 };
596 auto checkOrder = [&todo](auto op, LogicalResult &result) {
597 if (op.getOrder() || op.getOrderMod())
598 result = todo("order");
599 };
600 auto checkPrivate = [&todo](auto op, LogicalResult &result) {
601 if (!op.getPrivateVars().empty() || op.getPrivateSyms())
602 result = todo("privatization");
603 };
604 auto checkReduction = [&todo](auto op, LogicalResult &result) {
605 if (isa<omp::TeamsOp>(op))
606 if (!op.getReductionVars().empty() || op.getReductionByref() ||
607 op.getReductionSyms())
608 result = todo("reduction");
609 for (unsigned i = 0, e = op.getNumReductionVars(); i != e; ++i) {
610 omp::ReductionModifier mod = op.getReductionModifier(i);
611 if (mod == omp::ReductionModifier::defaultmod)
612 continue;
613 // Task modifiers are supported only on parallel and worksharing
614 // constructs, and only for non-byref reduction variables.
615 bool taskModifierSupported =
616 mod == omp::ReductionModifier::task &&
617 isa<omp::ParallelOp, omp::WsloopOp, omp::SectionsOp>(op);
618 if (!taskModifierSupported) {
619 result = todo("reduction with modifier");
620 } else if (auto byref = op.getReductionByref()) {
621 if ((*byref)[i])
622 result = todo("task reduction modifier with by-ref reduction");
623 }
624 }
625 };
626 auto checkTaskReductionByref = [&todo](auto op, LogicalResult &result) {
627 if (auto byrefAttr = op.getTaskReductionByref())
628 for (bool isByRef : *byrefAttr)
629 if (isByRef) {
630 result = todo("task_reduction with byref modifier");
631 return;
632 }
633 };
634 auto checkReductionByref = [&todo](auto op, LogicalResult &result) {
635 if (auto byrefAttr = op.getReductionByref())
636 for (bool isByRef : *byrefAttr)
637 if (isByRef) {
638 result = todo("reduction with byref modifier");
639 return;
640 }
641 };
642 auto checkNumTeams = [&todo](auto op, LogicalResult &result) {
643 if (op.hasNumTeamsMultiDim())
644 result = todo("num_teams with multi-dimensional values");
645 };
646 auto checkNumThreads = [&todo](auto op, LogicalResult &result) {
647 if (op.hasNumThreadsMultiDim())
648 result = todo("num_threads with multi-dimensional values");
649 };
650
651 auto checkThreadLimit = [&todo](auto op, LogicalResult &result) {
652 if (op.hasThreadLimitMultiDim())
653 result = todo("thread_limit with multi-dimensional values");
654 };
655 auto checkMap = [&todo](auto op, LogicalResult &result) {
656 if (!op.getMapIterated().empty())
657 result = todo("map/motion clause with iterator modifier");
658 };
659
660 auto checkDynGroupprivate = [&todo](auto op, LogicalResult &result) {
661 if (op.getDynGroupprivateSize())
662 result = todo("dyn_groupprivate");
663 };
664
665 // `declare_mapper.info` supports a single-dimension iterator whose region
666 // (which may itself span several blocks) yields one member-free omp.map.info
667 // for a locator described by var_ptr + bounds. Descriptor-indirect
668 // (var_ptr_ptr) locators aren't handled yet. Anything else falls back to the
669 // generic (not yet implemented) diagnostic above.
670 auto checkDeclareMapperMap = [&todo](omp::DeclareMapperInfoOp op,
671 LogicalResult &result) {
672 for (Value iterVal : op.getMapIterated()) {
673 auto itersOp = iterVal.getDefiningOp<omp::IteratorOp>();
674 bool supported = itersOp && itersOp.getLoopLowerBounds().size() == 1;
675 if (supported) {
676 omp::YieldOp yieldOp = itersOp.getYieldOp();
677 supported = yieldOp && yieldOp.getResults().size() == 1;
678 if (supported) {
679 auto mapInfoOp =
680 yieldOp.getResults()[0].getDefiningOp<omp::MapInfoOp>();
681 supported =
682 mapInfoOp && !mapInfoOp.getVarPtrPtr() &&
683 mapInfoOp.getMembers().empty() &&
684 mapInfoOp.getMapCaptureType() == omp::VariableCaptureKind::ByRef;
685 }
686 }
687 if (!supported) {
688 result = todo("map/motion clause with iterator modifier");
689 return;
690 }
691 }
692 };
693
694 LogicalResult result = success();
696 .Case([&](omp::DistributeOp op) {
697 checkAllocate(op, result);
698 checkOrder(op, result);
699 })
700 .Case([&](omp::SectionsOp op) {
701 checkAllocate(op, result);
702 checkPrivate(op, result);
703 checkReduction(op, result);
704 })
705 .Case([&](omp::ScopeOp op) { checkReduction(op, result); })
706 .Case([&](omp::SingleOp op) {
707 checkAllocate(op, result);
708 checkPrivate(op, result);
709 })
710 .Case([&](omp::TeamsOp op) {
711 checkAllocate(op, result);
712 checkPrivate(op, result);
713 checkNumTeams(op, result);
714 checkThreadLimit(op, result);
715 checkDynGroupprivate(op, result);
716 })
717 .Case([&](omp::TaskOp op) {
718 checkAllocate(op, result);
719 checkInReduction(op, result);
720 })
721 .Case([&](omp::TaskgroupOp op) {
722 checkAllocate(op, result);
723 checkTaskReductionByref(op, result);
724 })
725 .Case([&](omp::DispatchOp op) {
726 // OpenMP 5.1 dispatch creates an explicit task; nowait controls whether
727 // it is included. Diagnose unsupported asynchronous tasking before 5.2,
728 // where the nowait property has no effect on dispatch.
730 op->getParentOfType<ModuleOp>(), /*fallback=*/51);
731 if (version < 52)
732 checkNowait(op, result);
733 })
734 .Case([&](omp::TaskloopContextOp op) {
735 checkAllocate(op, result);
736 checkInReduction(op, result);
737 checkReduction(op, result);
738 checkReductionByref(op, result);
739 })
740 .Case([&](omp::WsloopOp op) {
741 checkAllocate(op, result);
742 checkOrder(op, result);
743 checkReduction(op, result);
744 })
745 .Case([&](omp::ParallelOp op) {
746 checkReduction(op, result);
747 checkNumThreads(op, result);
748 })
749 .Case([&](omp::SimdOp op) { checkReduction(op, result); })
750 .Case<omp::AtomicReadOp, omp::AtomicWriteOp, omp::AtomicUpdateOp,
751 omp::AtomicCaptureOp>([&](auto op) { checkHint(op, result); })
752 .Case([&](omp::AtomicCompareOp op) {
753 checkHint(op, result);
754 Region &region = op.getRegion();
755 if (region.empty())
756 return;
757 mlir::Type argType = region.front().getArgument(0).getType();
758 auto structTy = dyn_cast<LLVM::LLVMStructType>(argType);
759 if (!structTy)
760 return;
761 DataLayout dl = DataLayout(op->getParentOfType<ModuleOp>());
762 unsigned totalBits = dl.getTypeSizeInBits(structTy);
763 if (totalBits > 128)
764 result = todo("compare for complex types wider than 128 bits");
765 })
766 .Case<omp::TargetEnterDataOp, omp::TargetExitDataOp>([&](auto op) {
767 checkDepend(op, result);
768 checkMap(op, result);
769 })
770 .Case([&](omp::TargetUpdateOp op) {
771 checkDepend(op, result);
772 checkMap(op, result);
773 })
774 .Case([&](omp::TargetOp op) {
775 checkAllocate(op, result);
776 checkBare(op, result);
777 checkInReduction(op, result);
778 checkMap(op, result);
779 checkThreadLimit(op, result);
780 })
781 .Case([&](omp::TargetDataOp op) { checkMap(op, result); })
782 .Case([&](omp::DeclareMapperInfoOp op) {
783 checkDeclareMapperMap(op, result);
784 })
785 .Default([](Operation &) {
786 // Assume all clauses for an operation can be translated unless they are
787 // checked above.
788 });
789 return result;
790}
791
792static LogicalResult handleError(llvm::Error error, Operation &op) {
793 LogicalResult result = success();
794 if (error) {
795 llvm::handleAllErrors(
796 std::move(error),
797 [&](const PreviouslyReportedError &) { result = failure(); },
798 [&](const llvm::ErrorInfoBase &err) {
799 result = op.emitError(err.message());
800 });
801 }
802 return result;
803}
804
805template <typename T>
806static LogicalResult handleError(llvm::Expected<T> &result, Operation &op) {
807 if (!result)
808 return handleError(result.takeError(), op);
809
810 return success();
811}
812
813/// Find the insertion point for allocas given the current insertion point for
814/// normal operations in the builder.
815static llvm::OpenMPIRBuilder::InsertPointTy findAllocInsertPoints(
816 llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation,
817 llvm::SmallVectorImpl<llvm::BasicBlock *> *deallocBlocks = nullptr) {
818 // If there is an allocation insertion point on stack, i.e. we are in a nested
819 // operation and a specific point was provided by some surrounding operation,
820 // use it.
821 llvm::OpenMPIRBuilder::InsertPointTy allocInsertPoint;
822 llvm::ArrayRef<llvm::BasicBlock *> deallocInsertPoints;
823 WalkResult walkResult = moduleTranslation.stackWalk<OpenMPAllocStackFrame>(
824 [&](OpenMPAllocStackFrame &frame) {
825 allocInsertPoint = frame.allocBlock->getFirstInsertionPt();
826 deallocInsertPoints = frame.deallocBlocks;
827 return WalkResult::interrupt();
828 });
829 // In cases with multiple levels of outlining, the tree walk might find an
830 // insertion point that is inside the original function while the builder
831 // insertion point is inside the outlined function. We need to make sure that
832 // we do not use it in those cases.
833 if (walkResult.wasInterrupted() &&
834 allocInsertPoint.getNodeParent()->getParent() ==
835 builder.GetInsertBlock()->getParent()) {
836 if (deallocBlocks)
837 deallocBlocks->insert(deallocBlocks->end(), deallocInsertPoints.begin(),
838 deallocInsertPoints.end());
839 return allocInsertPoint;
840 }
841
842 // Otherwise, insert to the entry block of the surrounding function.
843 // If the current IRBuilder InsertPoint is the function's entry, it cannot
844 // also be used for alloca insertion which would result in insertion order
845 // confusion. Create a new BasicBlock for the Builder and use the entry block
846 // for the allocs.
847 // TODO: Create a dedicated alloca BasicBlock at function creation such that
848 // we do not need to move the current InsertPoint here.
849 if (builder.GetInsertBlock() ==
850 &builder.GetInsertBlock()->getParent()->getEntryBlock()) {
851 assert(builder.GetInsertPoint() == builder.GetInsertBlock()->end() &&
852 "Assuming end of basic block");
853 llvm::BasicBlock *entryBB = llvm::BasicBlock::Create(
854 builder.getContext(), "entry", builder.GetInsertBlock()->getParent(),
855 builder.GetInsertBlock()->getNextNode());
856 builder.CreateBr(entryBB);
857 builder.SetInsertPoint(entryBB);
858 }
859
860 // Collect exit blocks, which is where explicit deallocations should happen in
861 // this case.
862 if (deallocBlocks) {
863 for (llvm::BasicBlock &block : *builder.GetInsertBlock()->getParent()) {
864 // TODO: This currently results in no blocks being added to the list when
865 // all exit blocks of the enclosing function have not been lowered before
866 // this is reached.
867 llvm::Instruction *terminator = block.getTerminatorOrNull();
868 if (isa_and_present<llvm::ReturnInst>(terminator))
869 deallocBlocks->emplace_back(&block);
870 }
871 }
872
873 llvm::BasicBlock &funcEntryBlock =
874 builder.GetInsertBlock()->getParent()->getEntryBlock();
875 return funcEntryBlock.getFirstInsertionPt();
876}
877
878/// Find the loop information structure for the loop nest being translated. It
879/// will return a `null` value unless called from the translation function for
880/// a loop wrapper operation after successfully translating its body.
881static llvm::CanonicalLoopInfo *
883 llvm::CanonicalLoopInfo *loopInfo = nullptr;
884 moduleTranslation.stackWalk<OpenMPLoopInfoStackFrame>(
885 [&](OpenMPLoopInfoStackFrame &frame) {
886 loopInfo = frame.loopInfo;
887 return WalkResult::interrupt();
888 });
889 return loopInfo;
890}
891
892/// Converts the given region that appears within an OpenMP dialect operation to
893/// LLVM IR, creating a branch from the `sourceBlock` to the entry block of the
894/// region, and a branch from any block with an successor-less OpenMP terminator
895/// to `continuationBlock`. Populates `continuationBlockPHIs` with the PHI nodes
896/// of the continuation block if provided.
898 Region &region, StringRef blockName, llvm::IRBuilderBase &builder,
899 LLVM::ModuleTranslation &moduleTranslation,
900 SmallVectorImpl<llvm::PHINode *> *continuationBlockPHIs = nullptr) {
901 bool isLoopWrapper = isa<omp::LoopWrapperInterface>(region.getParentOp());
902
903 llvm::BasicBlock *continuationBlock =
904 splitBB(builder, true, "omp.region.cont");
905 llvm::BasicBlock *sourceBlock = builder.GetInsertBlock();
906
907 llvm::LLVMContext &llvmContext = builder.getContext();
908 for (Block &bb : region) {
909 llvm::BasicBlock *llvmBB = llvm::BasicBlock::Create(
910 llvmContext, blockName, builder.GetInsertBlock()->getParent(),
911 continuationBlock);
912 moduleTranslation.mapBlock(&bb, llvmBB);
913 }
914
915 llvm::Instruction *sourceTerminator = sourceBlock->getTerminator();
916
917 // Terminators (namely YieldOp) may be forwarding values to the region that
918 // need to be available in the continuation block. Collect the types of these
919 // operands in preparation of creating PHI nodes. This is skipped for loop
920 // wrapper operations, for which we know in advance they have no terminators.
921 SmallVector<llvm::Type *> continuationBlockPHITypes;
922 unsigned numYields = 0;
923
924 if (!isLoopWrapper) {
925 bool operandsProcessed = false;
926 for (Block &bb : region.getBlocks()) {
927 if (omp::YieldOp yield = dyn_cast<omp::YieldOp>(bb.getTerminator())) {
928 if (!operandsProcessed) {
929 for (unsigned i = 0, e = yield->getNumOperands(); i < e; ++i) {
930 continuationBlockPHITypes.push_back(
931 moduleTranslation.convertType(yield->getOperand(i).getType()));
932 }
933 operandsProcessed = true;
934 } else {
935 assert(continuationBlockPHITypes.size() == yield->getNumOperands() &&
936 "mismatching number of values yielded from the region");
937 for (unsigned i = 0, e = yield->getNumOperands(); i < e; ++i) {
938 llvm::Type *operandType =
939 moduleTranslation.convertType(yield->getOperand(i).getType());
940 (void)operandType;
941 assert(continuationBlockPHITypes[i] == operandType &&
942 "values of mismatching types yielded from the region");
943 }
944 }
945 numYields++;
946 }
947 }
948 }
949
950 // Insert PHI nodes in the continuation block for any values forwarded by the
951 // terminators in this region.
952 if (!continuationBlockPHITypes.empty())
953 assert(
954 continuationBlockPHIs &&
955 "expected continuation block PHIs if converted regions yield values");
956 if (continuationBlockPHIs) {
957 llvm::IRBuilderBase::InsertPointGuard guard(builder);
958 continuationBlockPHIs->reserve(continuationBlockPHITypes.size());
959 builder.SetInsertPoint(continuationBlock->begin());
960 for (llvm::Type *ty : continuationBlockPHITypes)
961 continuationBlockPHIs->push_back(builder.CreatePHI(ty, numYields));
962 }
963
964 // Convert blocks one by one in topological order to ensure
965 // defs are converted before uses.
967 for (Block *bb : blocks) {
968 llvm::BasicBlock *llvmBB = moduleTranslation.lookupBlock(bb);
969 // Retarget the branch of the entry block to the entry block of the
970 // converted region (regions are single-entry).
971 if (bb->isEntryBlock()) {
972 assert(sourceTerminator->getNumSuccessors() == 1 &&
973 "provided entry block has multiple successors");
974 assert(sourceTerminator->getSuccessor(0) == continuationBlock &&
975 "ContinuationBlock is not the successor of the entry block");
976 sourceTerminator->setSuccessor(0, llvmBB);
977 }
978
979 llvm::IRBuilderBase::InsertPointGuard guard(builder);
980 if (failed(
981 moduleTranslation.convertBlock(*bb, bb->isEntryBlock(), builder)))
982 return llvm::make_error<PreviouslyReportedError>();
983
984 // Create a direct branch here for loop wrappers to prevent their lack of a
985 // terminator from causing a crash below.
986 if (isLoopWrapper) {
987 builder.CreateBr(continuationBlock);
988 continue;
989 }
990
991 // Special handling for `omp.yield` and `omp.terminator` (we may have more
992 // than one): they return the control to the parent OpenMP dialect operation
993 // so replace them with the branch to the continuation block. We handle this
994 // here to avoid relying inter-function communication through the
995 // ModuleTranslation class to set up the correct insertion point. This is
996 // also consistent with MLIR's idiom of handling special region terminators
997 // in the same code that handles the region-owning operation.
998 Operation *terminator = bb->getTerminator();
999 if (isa<omp::TerminatorOp, omp::YieldOp>(terminator)) {
1000 builder.CreateBr(continuationBlock);
1001
1002 for (unsigned i = 0, e = terminator->getNumOperands(); i < e; ++i)
1003 (*continuationBlockPHIs)[i]->addIncoming(
1004 moduleTranslation.lookupValue(terminator->getOperand(i)), llvmBB);
1005 }
1006 }
1007 // After all blocks have been traversed and values mapped, connect the PHI
1008 // nodes to the results of preceding blocks.
1009 LLVM::detail::connectPHINodes(region, moduleTranslation);
1010
1011 // Remove the blocks and values defined in this region from the mapping since
1012 // they are not visible outside of this region. This allows the same region to
1013 // be converted several times, that is cloned, without clashes, and slightly
1014 // speeds up the lookups.
1015 moduleTranslation.forgetMapping(region);
1016
1017 return continuationBlock;
1018}
1019
1020/// Convert ProcBindKind from MLIR-generated enum to LLVM enum.
1021static llvm::omp::ProcBindKind getProcBindKind(omp::ClauseProcBindKind kind) {
1022 switch (kind) {
1023 case omp::ClauseProcBindKind::Close:
1024 return llvm::omp::ProcBindKind::OMP_PROC_BIND_close;
1025 case omp::ClauseProcBindKind::Master:
1026 return llvm::omp::ProcBindKind::OMP_PROC_BIND_master;
1027 case omp::ClauseProcBindKind::Primary:
1028 return llvm::omp::ProcBindKind::OMP_PROC_BIND_primary;
1029 case omp::ClauseProcBindKind::Spread:
1030 return llvm::omp::ProcBindKind::OMP_PROC_BIND_spread;
1031 }
1032 llvm_unreachable("Unknown ClauseProcBindKind kind");
1033}
1034
1035/// Convert 'dispatch' operation into LLVM IR.
1036static LogicalResult
1037convertOmpDispatch(Operation &opInst, llvm::IRBuilderBase &builder,
1038 LLVM::ModuleTranslation &moduleTranslation) {
1039 auto dispatchOp = cast<omp::DispatchOp>(opInst);
1040
1041 if (failed(checkImplementationStatus(opInst)))
1042 return failure();
1043
1044 auto &region = dispatchOp.getRegion();
1045 auto result = convertOmpOpRegions(region, "omp.dispatch.region", builder,
1046 moduleTranslation);
1047 if (!result)
1048 return handleError(result.takeError(), opInst);
1049 builder.SetInsertPoint(*result);
1050 return success();
1051}
1052
1053/// Converts an OpenMP 'masked' operation into LLVM IR using OpenMPIRBuilder.
1054static LogicalResult
1055convertOmpMasked(Operation &opInst, llvm::IRBuilderBase &builder,
1056 LLVM::ModuleTranslation &moduleTranslation) {
1057 auto maskedOp = cast<omp::MaskedOp>(opInst);
1058 using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy;
1059
1060 if (failed(checkImplementationStatus(opInst)))
1061 return failure();
1062
1063 auto bodyGenCB = [&](InsertPointTy allocaIP, InsertPointTy codeGenIP,
1064 llvm::ArrayRef<llvm::BasicBlock *> deallocBlocks) {
1065 // MaskedOp has only one region associated with it.
1066 auto &region = maskedOp.getRegion();
1067 builder.restoreIP(codeGenIP);
1068 return convertOmpOpRegions(region, "omp.masked.region", builder,
1069 moduleTranslation)
1070 .takeError();
1071 };
1072
1073 // TODO: Perform finalization actions for variables. This has to be
1074 // called for variables which have destructors/finalizers.
1075 auto finiCB = [&](InsertPointTy codeGenIP) { return llvm::Error::success(); };
1076
1077 llvm::Value *filterVal = nullptr;
1078 if (auto filterVar = maskedOp.getFilteredThreadId()) {
1079 filterVal = moduleTranslation.lookupValue(filterVar);
1080 } else {
1081 llvm::LLVMContext &llvmContext = builder.getContext();
1082 filterVal =
1083 llvm::ConstantInt::get(llvm::Type::getInt32Ty(llvmContext), /*V=*/0);
1084 }
1085 assert(filterVal != nullptr);
1086 llvm::OpenMPIRBuilder::LocationDescription ompLoc(builder);
1087 llvm::OpenMPIRBuilder::InsertPointOrErrorTy afterIP =
1088 getOpenMPBuilder(moduleTranslation)
1089 ->createMasked(ompLoc, bodyGenCB, finiCB, filterVal);
1090
1091 if (failed(handleError(afterIP, opInst)))
1092 return failure();
1093
1094 builder.restoreIP(*afterIP);
1095 return success();
1096}
1097
1098/// Converts an OpenMP 'master' operation into LLVM IR using OpenMPIRBuilder.
1099static LogicalResult
1100convertOmpMaster(Operation &opInst, llvm::IRBuilderBase &builder,
1101 LLVM::ModuleTranslation &moduleTranslation) {
1102 using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy;
1103 auto masterOp = cast<omp::MasterOp>(opInst);
1104
1105 if (failed(checkImplementationStatus(opInst)))
1106 return failure();
1107
1108 auto bodyGenCB = [&](InsertPointTy allocaIP, InsertPointTy codeGenIP,
1109 llvm::ArrayRef<llvm::BasicBlock *> deallocBlocks) {
1110 // MasterOp has only one region associated with it.
1111 auto &region = masterOp.getRegion();
1112 builder.restoreIP(codeGenIP);
1113 return convertOmpOpRegions(region, "omp.master.region", builder,
1114 moduleTranslation)
1115 .takeError();
1116 };
1117
1118 // TODO: Perform finalization actions for variables. This has to be
1119 // called for variables which have destructors/finalizers.
1120 auto finiCB = [&](InsertPointTy codeGenIP) { return llvm::Error::success(); };
1121
1122 llvm::OpenMPIRBuilder::LocationDescription ompLoc(builder);
1123 llvm::OpenMPIRBuilder::InsertPointOrErrorTy afterIP =
1124 getOpenMPBuilder(moduleTranslation)
1125 ->createMaster(ompLoc, bodyGenCB, finiCB);
1126
1127 if (failed(handleError(afterIP, opInst)))
1128 return failure();
1129
1130 builder.restoreIP(*afterIP);
1131 return success();
1132}
1133
1134/// Converts an OpenMP 'critical' operation into LLVM IR using OpenMPIRBuilder.
1135static LogicalResult
1136convertOmpCritical(Operation &opInst, llvm::IRBuilderBase &builder,
1137 LLVM::ModuleTranslation &moduleTranslation) {
1138 using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy;
1139 auto criticalOp = cast<omp::CriticalOp>(opInst);
1140
1141 if (failed(checkImplementationStatus(opInst)))
1142 return failure();
1143
1144 auto bodyGenCB = [&](InsertPointTy allocaIP, InsertPointTy codeGenIP,
1145 llvm::ArrayRef<llvm::BasicBlock *> deallocBlocks) {
1146 // CriticalOp has only one region associated with it.
1147 auto &region = cast<omp::CriticalOp>(opInst).getRegion();
1148 builder.restoreIP(codeGenIP);
1149 return convertOmpOpRegions(region, "omp.critical.region", builder,
1150 moduleTranslation)
1151 .takeError();
1152 };
1153
1154 // TODO: Perform finalization actions for variables. This has to be
1155 // called for variables which have destructors/finalizers.
1156 auto finiCB = [&](InsertPointTy codeGenIP) { return llvm::Error::success(); };
1157
1158 llvm::OpenMPIRBuilder::LocationDescription ompLoc(builder);
1159 llvm::LLVMContext &llvmContext = moduleTranslation.getLLVMContext();
1160 llvm::Constant *hint = nullptr;
1161
1162 // If it has a name, it probably has a hint too.
1163 if (criticalOp.getNameAttr()) {
1164 // The verifiers in OpenMP Dialect guarentee that all the pointers are
1165 // non-null
1166 auto symbolRef = cast<SymbolRefAttr>(criticalOp.getNameAttr());
1167 auto criticalDeclareOp =
1169 symbolRef);
1170 hint =
1171 llvm::ConstantInt::get(llvm::Type::getInt32Ty(llvmContext),
1172 static_cast<int>(criticalDeclareOp.getHint()));
1173 }
1174 llvm::OpenMPIRBuilder::InsertPointOrErrorTy afterIP =
1175 getOpenMPBuilder(moduleTranslation)
1176 ->createCritical(ompLoc, bodyGenCB, finiCB,
1177 criticalOp.getName().value_or(""), hint);
1178
1179 if (failed(handleError(afterIP, opInst)))
1180 return failure();
1181
1182 builder.restoreIP(*afterIP);
1183 return success();
1184}
1185
1186namespace {
1187/// A util to collect info needed to convert delayed privatizers from MLIR to
1188/// LLVM.
1189struct PrivateVarsInfo {
1190 /// Per-variable data for a single delayed privatizer.
1191 struct VarInfo {
1192 BlockArgument blockArg;
1193 mlir::Value mlirVar;
1194 omp::PrivateClauseOp privatizer;
1195 llvm::Value *llvmVar = nullptr;
1196 };
1197
1198 struct AllocatorInfo {
1199 llvm::Value *allocatedPtr;
1200 llvm::Value *allocator;
1201 };
1202
1203 template <typename OP>
1204 PrivateVarsInfo(OP op) {
1205 MutableArrayRef<BlockArgument> blockArgs =
1206 cast<omp::BlockArgOpenMPOpInterface>(*op).getPrivateBlockArgs();
1207 SmallVector<omp::PrivateClauseOp> privatizers;
1208
1209 collectPrivatizationDecls<OP>(op, op.getPrivateSyms(), privatizers);
1210 collectPrivatizationInfo(blockArgs, op.getPrivateVars(), privatizers);
1211 numPrivateVars = vars.size();
1212 }
1213
1214 /// Adds the linear variables of `op`, which are privatized by their
1215 /// `linear` privatizers, after the private variables.
1216 template <typename OP>
1217 void addLinearVars(OP op) {
1218 MutableArrayRef<BlockArgument> blockArgs =
1219 cast<omp::BlockArgOpenMPOpInterface>(*op).getLinearBlockArgs();
1220 SmallVector<omp::PrivateClauseOp> privatizers;
1221
1222 collectPrivatizationDecls<OP>(op, op.getLinearSyms(), privatizers);
1223 collectPrivatizationInfo(blockArgs, op.getLinearVars(), privatizers);
1224 }
1225
1226 /// Number of private variables before the linear ones.
1227 size_t numPrivateVars = 0;
1228 SmallVector<VarInfo> vars;
1229 llvm::DenseMap<Value, llvm::Value *> convertedAllocators;
1230 SmallVector<AllocatorInfo> allocatorPrivates;
1231
1232 SmallVector<llvm::Value *> getLlvmVars() const {
1233 return llvm::map_to_vector(vars,
1234 [](const VarInfo &v) { return v.llvmVar; });
1235 }
1236
1237private:
1238 /// Adds the provided privatization information to `vars`.
1239 void collectPrivatizationInfo(
1240 MutableArrayRef<BlockArgument> blockArgs, OperandRange privateVars,
1241 const SmallVectorImpl<omp::PrivateClauseOp> &privatizers) {
1242 vars.reserve(vars.size() + blockArgs.size());
1243 for (auto [blockArg, mlirVar, privatizer] :
1244 llvm::zip_equal(blockArgs, privateVars, privatizers))
1245 vars.push_back({blockArg, mlirVar, privatizer});
1246 }
1247
1248 /// Populates `privatizers` with privatization declarations the provided
1249 /// `symsAttr` points to.
1250 template <class OP>
1251 void collectPrivatizationDecls(
1252 OP op, std::optional<ArrayAttr> symsAttr,
1253 SmallVectorImpl<omp::PrivateClauseOp> &privatizers) {
1254 if (!symsAttr)
1255 return;
1256
1257 privatizers.reserve(privatizers.size() + symsAttr->size());
1258 llvm::transform(
1259 symsAttr->getAsRange<SymbolRefAttr>(), std::back_inserter(privatizers),
1260 [&](SymbolRefAttr symbolRef) { return findPrivatizer(op, symbolRef); });
1261 }
1262};
1263} // namespace
1264
1265/// Populates `reductions` with reduction declarations used in the given op.
1266template <typename T>
1267static void
1270 std::optional<ArrayAttr> attr = op.getReductionSyms();
1271 if (!attr)
1272 return;
1273
1274 reductions.reserve(reductions.size() + op.getNumReductionVars());
1275 for (auto symbolRef : attr->getAsRange<SymbolRefAttr>()) {
1276 reductions.push_back(
1278 op, symbolRef));
1279 }
1280}
1281
1282/// Look up and validate the declare_reduction ops referenced by a
1283/// reduction-like clause on the omp.taskloop.context translation path. Only
1284/// the non-byref, single-init-arg, no-cleanup form is supported in this
1285/// initial cut; richer shapes are rejected here with a diagnostic. \p syms
1286/// is the clause's symbol list (e.g. `getReductionSyms()` or
1287/// `getInReductionSyms()`), \p opName is the textual op name used in
1288/// diagnostics, and \p clauseName distinguishes "reduction" from
1289/// "in_reduction" in those diagnostics.
1291 Operation *contextOp, std::optional<ArrayAttr> syms, StringRef opName,
1292 StringRef clauseName, SmallVectorImpl<omp::DeclareReductionOp> &out) {
1293 if (!syms)
1294 return success();
1295 out.reserve(out.size() + syms->size());
1296 for (auto sym : syms->getAsRange<SymbolRefAttr>()) {
1298 contextOp, sym);
1299 if (!decl)
1300 return contextOp->emitError()
1301 << "failed to resolve " << clauseName
1302 << " declare_reduction symbol " << sym.getRootReference() << " in "
1303 << opName;
1304 if (decl.getInitializerRegion().front().getNumArguments() != 1)
1305 return contextOp->emitError()
1306 << "not yet implemented: " << clauseName
1307 << " with two-argument initializer in " << opName;
1308 if (!decl.getCleanupRegion().empty())
1309 return contextOp->emitError() << "not yet implemented: " << clauseName
1310 << " with cleanup region in " << opName;
1311 if (decl.getReductionRegion().empty())
1312 return contextOp->emitError()
1313 << clauseName << " declare_reduction is missing a combiner region";
1314 out.push_back(decl);
1315 }
1316 return success();
1317}
1318
1319/// Translates the blocks contained in the given region and appends them to at
1320/// the current insertion point of `builder`. The operations of the entry block
1321/// are appended to the current insertion block. If set, `continuationBlockArgs`
1322/// is populated with translated values that correspond to the values
1323/// omp.yield'ed from the region.
1324static LogicalResult inlineConvertOmpRegions(
1325 Region &region, StringRef blockName, llvm::IRBuilderBase &builder,
1326 LLVM::ModuleTranslation &moduleTranslation,
1327 SmallVectorImpl<llvm::Value *> *continuationBlockArgs = nullptr) {
1328 if (region.empty())
1329 return success();
1330
1331 // Special case for single-block regions that don't create additional blocks:
1332 // insert operations without creating additional blocks.
1333 if (region.hasOneBlock()) {
1334 llvm::BasicBlock *insertBlock = builder.GetInsertBlock();
1335 llvm::Instruction *potentialTerminator =
1336 insertBlock->empty() ? nullptr : &insertBlock->back();
1337
1338 if (potentialTerminator && potentialTerminator->isTerminator()) {
1339 assert(builder.GetInsertPoint() == potentialTerminator->getIterator() &&
1340 "Insertion point should be the terminator");
1341 potentialTerminator->removeFromParent();
1342 // Reset insertion point to the end of the block.
1343 builder.SetInsertPoint(insertBlock);
1344 }
1345 moduleTranslation.mapBlock(&region.front(), insertBlock);
1346
1347 // convertBlock leaves the location of the region's last op current. Restore
1348 // the caller's, as convertOmpOpRegions does for every block it converts.
1349 llvm::DebugLoc loc = builder.getCurrentDebugLocation();
1350 if (failed(moduleTranslation.convertBlock(
1351 region.front(), /*ignoreArguments=*/true, builder)))
1352 return failure();
1353 builder.SetCurrentDebugLocation(loc);
1354
1355 // The continuation arguments are simply the translated terminator operands.
1356 if (continuationBlockArgs)
1357 llvm::append_range(
1358 *continuationBlockArgs,
1359 moduleTranslation.lookupValues(region.front().back().getOperands()));
1360
1361 // Drop the mapping that is no longer necessary so that the same region can
1362 // be processed multiple times.
1363 moduleTranslation.forgetMapping(region);
1364
1365 if (potentialTerminator && potentialTerminator->isTerminator()) {
1366 llvm::BasicBlock *block = builder.GetInsertBlock();
1367 if (block->empty()) {
1368 // this can happen for really simple reduction init regions e.g.
1369 // %0 = llvm.mlir.constant(0 : i32) : i32
1370 // omp.yield(%0 : i32)
1371 // because the llvm.mlir.constant (MLIR op) isn't converted into any
1372 // llvm op
1373 potentialTerminator->insertInto(block, block->begin());
1374 } else {
1375 potentialTerminator->insertAfter(&block->back());
1376 }
1377 }
1378
1379 return success();
1380 }
1381
1383 llvm::Expected<llvm::BasicBlock *> continuationBlock =
1384 convertOmpOpRegions(region, blockName, builder, moduleTranslation, &phis);
1385
1386 if (failed(handleError(continuationBlock, *region.getParentOp())))
1387 return failure();
1388
1389 if (continuationBlockArgs)
1390 llvm::append_range(*continuationBlockArgs, phis);
1391 builder.SetInsertPoint((*continuationBlock)->getFirstInsertionPt());
1392 return success();
1393}
1394
1395namespace {
1396/// Owning equivalents of OpenMPIRBuilder::(Atomic)ReductionGen that are used to
1397/// store lambdas with capture.
1398using OwningReductionGen =
1399 std::function<llvm::OpenMPIRBuilder::InsertPointOrErrorTy(
1400 llvm::OpenMPIRBuilder::InsertPointTy, llvm::Value *, llvm::Value *,
1401 llvm::Value *&)>;
1402using OwningAtomicReductionGen =
1403 std::function<llvm::OpenMPIRBuilder::InsertPointOrErrorTy(
1404 llvm::OpenMPIRBuilder::InsertPointTy, llvm::Type *, llvm::Value *,
1405 llvm::Value *)>;
1406using OwningDataPtrPtrReductionGen =
1407 std::function<llvm::OpenMPIRBuilder::InsertPointOrErrorTy(
1408 llvm::OpenMPIRBuilder::InsertPointTy, llvm::Value *, llvm::Value *&)>;
1409} // namespace
1410
1411/// Create an OpenMPIRBuilder-compatible reduction generator for the given
1412/// reduction declaration. The generator uses `builder` but ignores its
1413/// insertion point.
1414static OwningReductionGen
1415makeReductionGen(omp::DeclareReductionOp decl, llvm::IRBuilderBase &builder,
1416 LLVM::ModuleTranslation &moduleTranslation) {
1417 // The lambda is mutable because we need access to non-const methods of decl
1418 // (which aren't actually mutating it), and we must capture decl by-value to
1419 // avoid the dangling reference after the parent function returns.
1420 OwningReductionGen gen =
1421 [&, decl](llvm::OpenMPIRBuilder::InsertPointTy insertPoint,
1422 llvm::Value *lhs, llvm::Value *rhs,
1423 llvm::Value *&result) mutable
1424 -> llvm::OpenMPIRBuilder::InsertPointOrErrorTy {
1425 moduleTranslation.mapValue(decl.getReductionLhsArg(), lhs);
1426 moduleTranslation.mapValue(decl.getReductionRhsArg(), rhs);
1427 builder.restoreIP(insertPoint);
1429 if (failed(inlineConvertOmpRegions(decl.getReductionRegion(),
1430 "omp.reduction.nonatomic.body", builder,
1431 moduleTranslation, &phis)))
1432 return llvm::createStringError(
1433 "failed to inline `combiner` region of `omp.declare_reduction`");
1434 result = llvm::getSingleElement(phis);
1435 return builder.saveIP();
1436 };
1437 return gen;
1438}
1439
1440/// Create an OpenMPIRBuilder-compatible atomic reduction generator for the
1441/// given reduction declaration. The generator uses `builder` but ignores its
1442/// insertion point. Returns null if there is no atomic region available in the
1443/// reduction declaration.
1444static OwningAtomicReductionGen
1445makeAtomicReductionGen(omp::DeclareReductionOp decl,
1446 llvm::IRBuilderBase &builder,
1447 LLVM::ModuleTranslation &moduleTranslation) {
1448 if (decl.getAtomicReductionRegion().empty())
1449 return OwningAtomicReductionGen();
1450
1451 // The lambda is mutable because we need access to non-const methods of decl
1452 // (which aren't actually mutating it), and we must capture decl by-value to
1453 // avoid the dangling reference after the parent function returns.
1454 OwningAtomicReductionGen atomicGen =
1455 [&, decl](llvm::OpenMPIRBuilder::InsertPointTy insertPoint, llvm::Type *,
1456 llvm::Value *lhs, llvm::Value *rhs) mutable
1457 -> llvm::OpenMPIRBuilder::InsertPointOrErrorTy {
1458 moduleTranslation.mapValue(decl.getAtomicReductionLhsArg(), lhs);
1459 moduleTranslation.mapValue(decl.getAtomicReductionRhsArg(), rhs);
1460 builder.restoreIP(insertPoint);
1462 if (failed(inlineConvertOmpRegions(decl.getAtomicReductionRegion(),
1463 "omp.reduction.atomic.body", builder,
1464 moduleTranslation, &phis)))
1465 return llvm::createStringError(
1466 "failed to inline `atomic` region of `omp.declare_reduction`");
1467 assert(phis.empty());
1468 return builder.saveIP();
1469 };
1470 return atomicGen;
1471}
1472
1473/// Create an OpenMPIRBuilder-compatible `data_ptr_ptr` reduction generator for
1474/// the given reduction declaration. The generator uses `builder` but ignores
1475/// its insertion point. Returns null if there is no `data_ptr_ptr` region
1476/// available in the reduction declaration.
1477static OwningDataPtrPtrReductionGen
1478makeRefDataPtrGen(omp::DeclareReductionOp decl, llvm::IRBuilderBase &builder,
1479 LLVM::ModuleTranslation &moduleTranslation, bool isByRef) {
1480 if (!isByRef || decl.getDataPtrPtrRegion().empty())
1481 return OwningDataPtrPtrReductionGen();
1482
1483 OwningDataPtrPtrReductionGen refDataPtrGen =
1484 [&, decl](llvm::OpenMPIRBuilder::InsertPointTy insertPoint,
1485 llvm::Value *byRefVal, llvm::Value *&result) mutable
1486 -> llvm::OpenMPIRBuilder::InsertPointOrErrorTy {
1487 moduleTranslation.mapValue(decl.getDataPtrPtrRegionArg(), byRefVal);
1488 builder.restoreIP(insertPoint);
1490 if (failed(inlineConvertOmpRegions(decl.getDataPtrPtrRegion(),
1491 "omp.data_ptr_ptr.body", builder,
1492 moduleTranslation, &phis)))
1493 return llvm::createStringError(
1494 "failed to inline `data_ptr_ptr` region of `omp.declare_reduction`");
1495 result = llvm::getSingleElement(phis);
1496 return builder.saveIP();
1497 };
1498
1499 return refDataPtrGen;
1500}
1501
1502/// Converts an OpenMP 'ordered' operation into LLVM IR using OpenMPIRBuilder.
1503static LogicalResult
1504convertOmpOrdered(Operation &opInst, llvm::IRBuilderBase &builder,
1505 LLVM::ModuleTranslation &moduleTranslation) {
1506 auto orderedOp = cast<omp::OrderedOp>(opInst);
1507
1508 if (failed(checkImplementationStatus(opInst)))
1509 return failure();
1510
1511 omp::ClauseDepend dependType = *orderedOp.getDoacrossDependType();
1512 bool isDependSource = dependType == omp::ClauseDepend::dependsource;
1513 unsigned numLoops = *orderedOp.getDoacrossNumLoops();
1514 SmallVector<llvm::Value *> vecValues =
1515 moduleTranslation.lookupValues(orderedOp.getDoacrossDependVars());
1516
1517 size_t indexVecValues = 0;
1518 while (indexVecValues < vecValues.size()) {
1519 SmallVector<llvm::Value *> storeValues;
1520 storeValues.reserve(numLoops);
1521 for (unsigned i = 0; i < numLoops; i++) {
1522 storeValues.push_back(vecValues[indexVecValues]);
1523 indexVecValues++;
1524 }
1525 llvm::OpenMPIRBuilder::InsertPointTy allocaIP =
1526 findAllocInsertPoints(builder, moduleTranslation);
1527 llvm::OpenMPIRBuilder::LocationDescription ompLoc(builder);
1528 builder.restoreIP(getOpenMPBuilder(moduleTranslation)
1529 ->createOrderedDepend(ompLoc, allocaIP, numLoops,
1530 storeValues, ".cnt.addr",
1531 isDependSource));
1532 }
1533 return success();
1534}
1535
1536/// Converts an OpenMP 'ordered_region' operation into LLVM IR using
1537/// OpenMPIRBuilder.
1538static LogicalResult
1539convertOmpOrderedRegion(Operation &opInst, llvm::IRBuilderBase &builder,
1540 LLVM::ModuleTranslation &moduleTranslation) {
1541 using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy;
1542 auto orderedRegionOp = cast<omp::OrderedRegionOp>(opInst);
1543
1544 if (failed(checkImplementationStatus(opInst)))
1545 return failure();
1546
1547 auto bodyGenCB = [&](InsertPointTy allocaIP, InsertPointTy codeGenIP,
1548 llvm::ArrayRef<llvm::BasicBlock *> deallocBlocks) {
1549 // OrderedOp has only one region associated with it.
1550 auto &region = cast<omp::OrderedRegionOp>(opInst).getRegion();
1551 builder.restoreIP(codeGenIP);
1552 return convertOmpOpRegions(region, "omp.ordered.region", builder,
1553 moduleTranslation)
1554 .takeError();
1555 };
1556
1557 // TODO: Perform finalization actions for variables. This has to be
1558 // called for variables which have destructors/finalizers.
1559 auto finiCB = [&](InsertPointTy codeGenIP) { return llvm::Error::success(); };
1560
1561 llvm::OpenMPIRBuilder::LocationDescription ompLoc(builder);
1562 llvm::OpenMPIRBuilder::InsertPointOrErrorTy afterIP =
1563 getOpenMPBuilder(moduleTranslation)
1564 ->createOrderedThreadsSimd(ompLoc, bodyGenCB, finiCB,
1565 !orderedRegionOp.getParLevelSimd());
1566
1567 if (failed(handleError(afterIP, opInst)))
1568 return failure();
1569
1570 builder.restoreIP(*afterIP);
1571 return success();
1572}
1573
1574namespace {
1575/// A util to collect info needed to translate the reductions of an OpenMP
1576/// construct from MLIR to LLVM. Mirrors `PrivateVarsInfo` for delayed
1577/// privatizers.
1578struct ReductionVarsInfo {
1579 /// Per-variable data for a single reduction.
1580 struct VarInfo {
1581 BlockArgument blockArg;
1582 mlir::Value mlirVar;
1583 omp::DeclareReductionOp decl;
1584 bool byRef;
1585 llvm::Value *privateVar = nullptr;
1586 llvm::Value *storage = nullptr;
1587 };
1588
1589 /// Contains the arguments for an LLVM store operation.
1590 struct DeferredStore {
1591 DeferredStore(llvm::Value *value, llvm::Value *address)
1592 : value(value), address(address) {}
1593
1594 llvm::Value *value;
1595 llvm::Value *address;
1596 };
1597
1598 template <typename OP>
1599 ReductionVarsInfo(OP op) {
1600 MutableArrayRef<BlockArgument> blockArgs =
1601 cast<omp::BlockArgOpenMPOpInterface>(*op).getReductionBlockArgs();
1602 SmallVector<omp::DeclareReductionOp> decls;
1603 collectReductionDecls(op, decls);
1604 std::optional<ArrayRef<bool>> attr = op.getReductionByref();
1605 ArrayRef<bool> byRefs = attr ? *attr : ArrayRef<bool>();
1606
1607 vars.reserve(blockArgs.size());
1608 for (auto [blockArg, mlirVar, decl, byRef] :
1609 llvm::zip_equal(blockArgs, op.getReductionVars(), decls, byRefs))
1610 vars.push_back({blockArg, mlirVar, decl, byRef});
1611 }
1612
1613 SmallVector<VarInfo> vars;
1614 /// Stores deferred until after all allocas (see `allocReductionVars`).
1615 SmallVector<DeferredStore> deferredStores;
1616
1617 size_t size() const { return vars.size(); }
1618
1619 SmallVector<omp::DeclareReductionOp> getReductionDecls() const {
1620 return llvm::map_to_vector(vars, [](const VarInfo &v) { return v.decl; });
1621 }
1622 SmallVector<llvm::Value *> getPrivateReductionVariables() const {
1623 return llvm::map_to_vector(vars,
1624 [](const VarInfo &v) { return v.privateVar; });
1625 }
1626 SmallVector<bool> getIsByRef() const {
1627 return llvm::map_to_vector(vars, [](const VarInfo &v) { return v.byRef; });
1628 }
1629};
1630} // namespace
1631
1632/// Allocate space for privatized reduction variables.
1633/// `deferredStores` contains information to create store operations which needs
1634/// to be inserted after all allocas
1635static LogicalResult
1636allocReductionVars(Operation &op, llvm::IRBuilderBase &builder,
1637 LLVM::ModuleTranslation &moduleTranslation,
1638 const llvm::OpenMPIRBuilder::InsertPointTy &allocaIP,
1639 ReductionVarsInfo &redInfo) {
1640 llvm::IRBuilderBase::InsertPointGuard guard(builder);
1641 builder.SetInsertPoint(allocaIP.getNodeParent()->getTerminator());
1642
1643 llvm::OpenMPIRBuilder *ompBuilder = getOpenMPBuilder(moduleTranslation);
1644 bool useDeviceSharedMem = omp::opInSharedDeviceContext(op);
1645
1646 // delay creating stores until after all allocas
1647 redInfo.deferredStores.reserve(redInfo.size());
1648
1649 for (ReductionVarsInfo::VarInfo &var : redInfo.vars) {
1650 Region &allocRegion = var.decl.getAllocRegion();
1651 if (var.byRef) {
1652 if (allocRegion.empty())
1653 continue;
1654
1656 if (failed(inlineConvertOmpRegions(allocRegion, "omp.reduction.alloc",
1657 builder, moduleTranslation, &phis)))
1658 return op.emitError(
1659 "failed to inline `alloc` region of `omp.declare_reduction`");
1660
1661 assert(phis.size() == 1 && "expected one allocation to be yielded");
1662 builder.SetInsertPoint(allocaIP.getNodeParent()->getTerminator());
1663
1664 // Allocate reduction variable (which is a pointer to the real reduction
1665 // variable allocated in the inlined region)
1666 llvm::Type *ptrTy = builder.getPtrTy();
1667 llvm::Type *varTy = moduleTranslation.convertType(var.decl.getType());
1668 llvm::Value *llvmVar;
1669 if (useDeviceSharedMem) {
1670 llvmVar = ompBuilder->createOMPAllocShared(builder, varTy);
1671 } else {
1672 llvmVar = builder.CreateAlloca(varTy);
1673 llvmVar = builder.CreatePointerBitCastOrAddrSpaceCast(llvmVar, ptrTy);
1674 }
1675
1676 llvm::Value *castPhi =
1677 builder.CreatePointerBitCastOrAddrSpaceCast(phis[0], ptrTy);
1678
1679 redInfo.deferredStores.emplace_back(castPhi, llvmVar);
1680
1681 var.privateVar = llvmVar;
1682 moduleTranslation.mapValue(var.blockArg, castPhi);
1683 var.storage = castPhi;
1684 } else {
1685 assert(allocRegion.empty() &&
1686 "allocaction is implicit for by-val reduction");
1687
1688 llvm::Type *ptrTy = builder.getPtrTy();
1689 llvm::Type *varTy = moduleTranslation.convertType(var.decl.getType());
1690 llvm::Value *llvmVar;
1691 if (useDeviceSharedMem) {
1692 llvmVar = ompBuilder->createOMPAllocShared(builder, varTy);
1693 } else {
1694 llvmVar = builder.CreateAlloca(varTy);
1695 llvmVar = builder.CreatePointerBitCastOrAddrSpaceCast(llvmVar, ptrTy);
1696 }
1697
1698 var.privateVar = llvmVar;
1699 moduleTranslation.mapValue(var.blockArg, llvmVar);
1700 var.storage = llvmVar;
1701 }
1702 }
1703
1704 return success();
1705}
1706
1707/// Map input arguments to reduction initialization region
1708static void
1710 llvm::IRBuilderBase &builder,
1711 const ReductionVarsInfo::VarInfo &redVarInfo) {
1712 // map input argument to the initialization region
1713 omp::DeclareReductionOp reduction = redVarInfo.decl;
1714 Region &initializerRegion = reduction.getInitializerRegion();
1715 Block &entry = initializerRegion.front();
1716
1717 mlir::Value mlirSource = redVarInfo.mlirVar;
1718 llvm::Value *llvmSource = moduleTranslation.lookupValue(mlirSource);
1719 llvm::Value *origVal = llvmSource;
1720 // If a non-pointer value is expected, load the value from the source pointer.
1721 if (!isa<LLVM::LLVMPointerType>(
1722 reduction.getInitializerMoldArg().getType()) &&
1723 isa<LLVM::LLVMPointerType>(mlirSource.getType())) {
1724 origVal =
1725 builder.CreateLoad(moduleTranslation.convertType(
1726 reduction.getInitializerMoldArg().getType()),
1727 llvmSource, "omp_orig");
1728 }
1729 moduleTranslation.mapValue(reduction.getInitializerMoldArg(), origVal);
1730
1731 if (entry.getNumArguments() > 1)
1732 moduleTranslation.mapValue(reduction.getInitializerAllocArg(),
1733 redVarInfo.storage);
1734}
1735
1736static void
1737setInsertPointForPossiblyEmptyBlock(llvm::IRBuilderBase &builder,
1738 llvm::BasicBlock *block = nullptr) {
1739 if (block == nullptr)
1740 block = builder.GetInsertBlock();
1741
1742 if (!block->hasTerminator())
1743 builder.SetInsertPoint(block);
1744 else
1745 builder.SetInsertPoint(block->getTerminator());
1746}
1747
1748/// Inline reductions' `init` regions. This functions assumes that the
1749/// `builder`'s insertion point is where the user wants the `init` regions to be
1750/// inlined; i.e. it does not try to find a proper insertion location for the
1751/// `init` regions. It also leaves the `builder's insertions point in a state
1752/// where the user can continue the code-gen directly afterwards.
1753static LogicalResult
1754initReductionVars(Operation &op, llvm::IRBuilderBase &builder,
1755 LLVM::ModuleTranslation &moduleTranslation,
1756 llvm::BasicBlock *latestAllocaBlock,
1757 ReductionVarsInfo &redInfo) {
1758 if (redInfo.size() == 0)
1759 return success();
1760
1761 llvm::OpenMPIRBuilder *ompBuilder = getOpenMPBuilder(moduleTranslation);
1762 bool useDeviceSharedMem = omp::opInSharedDeviceContext(op);
1763
1764 llvm::BasicBlock *initBlock = splitBB(builder, true, "omp.reduction.init");
1765 SmallVector<llvm::Value *> byRefVars(redInfo.size());
1766 {
1767 llvm::IRBuilderBase::InsertPointGuard guard(builder);
1768 auto allocaIP = latestAllocaBlock->getTerminator()->getIterator();
1769 builder.restoreIP(allocaIP);
1770
1771 for (auto [var, byRefVar] : llvm::zip_equal(redInfo.vars, byRefVars)) {
1772 if (var.byRef) {
1773 if (!var.decl.getAllocRegion().empty())
1774 continue;
1775
1776 // TODO: remove after all users of by-ref are updated to use the alloc
1777 // region: Allocate reduction variable (which is a pointer to the real
1778 // reduciton variable allocated in the inlined region)
1779 llvm::Type *varTy = moduleTranslation.convertType(var.decl.getType());
1780 if (useDeviceSharedMem)
1781 byRefVar = ompBuilder->createOMPAllocShared(builder, varTy);
1782 else
1783 byRefVar = builder.CreateAlloca(varTy);
1784 }
1785 }
1786 }
1787
1788 setInsertPointForPossiblyEmptyBlock(builder, initBlock);
1789
1790 // store result of the alloc region to the allocated pointer to the real
1791 // reduction variable
1792 for (auto [data, addr] : redInfo.deferredStores)
1793 builder.CreateStore(data, addr);
1794
1795 // Before the loop, store the initial values of reductions into reduction
1796 // variables. Although this could be done after allocas, we don't want to mess
1797 // up with the alloca insertion point.
1798 for (auto [var, byRefVar] : llvm::zip_equal(redInfo.vars, byRefVars)) {
1800
1801 // map block argument to initializer region
1802 mapInitializationArgs(moduleTranslation, builder, var);
1803
1804 // TODO In some cases (specially on the GPU), the init regions may
1805 // contains stack alloctaions. If the region is inlined in a loop, this is
1806 // problematic. Instead of just inlining the region, handle allocations by
1807 // hoisting fixed length allocations to the function entry and using
1808 // stacksave and restore for variable length ones.
1809 if (failed(inlineConvertOmpRegions(var.decl.getInitializerRegion(),
1810 "omp.reduction.neutral", builder,
1811 moduleTranslation, &phis)))
1812 return failure();
1813
1814 assert(phis.size() == 1 && "expected one value to be yielded from the "
1815 "reduction neutral element declaration region");
1816
1818
1819 if (var.byRef) {
1820 if (!var.decl.getAllocRegion().empty())
1821 // done in allocReductionVars
1822 continue;
1823
1824 // TODO: this path can be removed once all users of by-ref are updated to
1825 // use an alloc region
1826
1827 // Store the result of the inlined region to the allocated reduction var
1828 // ptr
1829 builder.CreateStore(phis[0], byRefVar);
1830 var.privateVar = byRefVar;
1831
1832 moduleTranslation.mapValue(var.blockArg, phis[0]);
1833 var.storage = phis[0];
1834 } else {
1835 // for by-ref case the store is inside of the reduction region
1836 builder.CreateStore(phis[0], var.privateVar);
1837 // the rest was handled in allocByValReductionVars
1838 }
1839
1840 // forget the mapping for the initializer region because we might need a
1841 // different mapping if this reduction declaration is re-used for a
1842 // different variable
1843 moduleTranslation.forgetMapping(var.decl.getInitializerRegion());
1844 }
1845
1846 return success();
1847}
1848
1849/// Collect reduction info
1850static void collectReductionInfo(
1851 llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation,
1852 ReductionVarsInfo &redInfo,
1853 SmallVectorImpl<OwningReductionGen> &owningReductionGens,
1854 SmallVectorImpl<OwningAtomicReductionGen> &owningAtomicReductionGens,
1855 SmallVector<OwningDataPtrPtrReductionGen> &owningDataPtrPtrReductionGens,
1857 unsigned numReductions = redInfo.size();
1858
1859 for (ReductionVarsInfo::VarInfo &var : redInfo.vars) {
1860 owningReductionGens.push_back(
1861 makeReductionGen(var.decl, builder, moduleTranslation));
1862 owningAtomicReductionGens.push_back(
1863 makeAtomicReductionGen(var.decl, builder, moduleTranslation));
1864 owningDataPtrPtrReductionGens.push_back(
1865 makeRefDataPtrGen(var.decl, builder, moduleTranslation, var.byRef));
1866 }
1867
1868 // Collect the reduction information.
1869 reductionInfos.reserve(numReductions);
1870 for (auto [var, redGen, atomicRedGen, dataPtrPtrRedGen] : llvm::zip_equal(
1871 redInfo.vars, owningReductionGens, owningAtomicReductionGens,
1872 owningDataPtrPtrReductionGens)) {
1873 llvm::OpenMPIRBuilder::ReductionGenAtomicCBTy atomicGen = nullptr;
1874 if (atomicRedGen)
1875 atomicGen = atomicRedGen;
1876 llvm::Value *variable = moduleTranslation.lookupValue(var.mlirVar);
1877 mlir::Type allocatedType;
1878 var.decl.getAllocRegion().walk([&](mlir::Operation *op) {
1879 if (auto alloca = mlir::dyn_cast<LLVM::AllocaOp>(op)) {
1880 allocatedType = alloca.getElemType();
1882 }
1883
1885 });
1886
1887 reductionInfos.push_back(
1888 {moduleTranslation.convertType(var.decl.getType()), variable,
1889 var.privateVar,
1890 /*EvaluationKind=*/llvm::OpenMPIRBuilder::EvalKind::Scalar, redGen,
1891 /*ReductionGenClang=*/nullptr, atomicGen, dataPtrPtrRedGen,
1892 allocatedType ? moduleTranslation.convertType(allocatedType) : nullptr,
1893 var.decl.getByrefElementType()
1894 ? moduleTranslation.convertType(*var.decl.getByrefElementType())
1895 : nullptr});
1896 }
1897}
1898
1899/// handling of DeclareReductionOp's cleanup region
1900static LogicalResult
1902 llvm::ArrayRef<llvm::Value *> privateVariables,
1903 LLVM::ModuleTranslation &moduleTranslation,
1904 llvm::IRBuilderBase &builder, StringRef regionName,
1905 bool shouldLoadCleanupRegionArg = true) {
1906 for (auto [i, cleanupRegion] : llvm::enumerate(cleanupRegions)) {
1907 if (cleanupRegion->empty())
1908 continue;
1909
1910 // map the argument to the cleanup region
1911 Block &entry = cleanupRegion->front();
1912
1913 llvm::Instruction *potentialTerminator =
1914 builder.GetInsertBlock()->empty() ? nullptr
1915 : &builder.GetInsertBlock()->back();
1916 if (potentialTerminator && potentialTerminator->isTerminator())
1917 builder.SetInsertPoint(potentialTerminator);
1918 llvm::Value *privateVarValue =
1919 shouldLoadCleanupRegionArg
1920 ? builder.CreateLoad(
1921 moduleTranslation.convertType(entry.getArgument(0).getType()),
1922 privateVariables[i])
1923 : privateVariables[i];
1924
1925 moduleTranslation.mapValue(entry.getArgument(0), privateVarValue);
1926
1927 if (failed(inlineConvertOmpRegions(*cleanupRegion, regionName, builder,
1928 moduleTranslation)))
1929 return failure();
1930
1931 // clear block argument mapping in case it needs to be re-created with a
1932 // different source for another use of the same reduction decl
1933 moduleTranslation.forgetMapping(*cleanupRegion);
1934 }
1935 return success();
1936}
1937
1938// TODO: not used by ParallelOp
1939static LogicalResult
1940createReductionsAndCleanup(Operation &op, llvm::IRBuilderBase &builder,
1941 LLVM::ModuleTranslation &moduleTranslation,
1942 llvm::OpenMPIRBuilder::InsertPointTy &allocaIP,
1943 ReductionVarsInfo &redInfo, bool isNowait = false,
1944 bool isTeamsReduction = false) {
1945 // Process the reductions if required.
1946 if (redInfo.size() == 0)
1947 return success();
1948
1949 SmallVector<OwningReductionGen> owningReductionGens;
1950 SmallVector<OwningAtomicReductionGen> owningAtomicReductionGens;
1951 SmallVector<OwningDataPtrPtrReductionGen> owningReductionGenRefDataPtrGens;
1953
1954 llvm::OpenMPIRBuilder *ompBuilder = getOpenMPBuilder(moduleTranslation);
1955
1956 // Create the reduction generators. We need to own them here because
1957 // ReductionInfo only accepts references to the generators.
1958 collectReductionInfo(builder, moduleTranslation, redInfo, owningReductionGens,
1959 owningAtomicReductionGens,
1960 owningReductionGenRefDataPtrGens, reductionInfos);
1961
1962 // The call to createReductions below expects the block to have a
1963 // terminator. Create an unreachable instruction to serve as terminator
1964 // and remove it later.
1965 llvm::UnreachableInst *tempTerminator = builder.CreateUnreachable();
1966 builder.SetInsertPoint(tempTerminator);
1967 llvm::DebugLoc reductionLoc = builder.getCurrentDebugLocation();
1968 llvm::OpenMPIRBuilder::InsertPointOrErrorTy contInsertPoint =
1969 ompBuilder->createReductions(builder, allocaIP, reductionInfos,
1970 redInfo.getIsByRef(), isNowait,
1971 isTeamsReduction);
1972
1973 if (failed(handleError(contInsertPoint, op)))
1974 return failure();
1975
1976 if (!contInsertPoint->isValid())
1977 return op.emitOpError() << "failed to convert reductions";
1978
1979 llvm::OpenMPIRBuilder::InsertPointTy afterIP = *contInsertPoint;
1980 if (!isTeamsReduction && !isNowait) {
1981 llvm::OpenMPIRBuilder::InsertPointOrErrorTy barrierIP =
1982 ompBuilder->createBarrier({*contInsertPoint, reductionLoc},
1983 llvm::omp::OMPD_for);
1984
1985 if (failed(handleError(barrierIP, op)))
1986 return failure();
1987 afterIP = *barrierIP;
1988 }
1989
1990 tempTerminator->eraseFromParent();
1991 builder.restoreIP(afterIP);
1992
1993 // after the construct, deallocate private reduction variables
1994 SmallVector<Region *> reductionRegions;
1995 llvm::transform(redInfo.vars, std::back_inserter(reductionRegions),
1996 [](ReductionVarsInfo::VarInfo &var) {
1997 return &var.decl.getCleanupRegion();
1998 });
1999 LogicalResult result = inlineOmpRegionCleanup(
2000 reductionRegions, redInfo.getPrivateReductionVariables(),
2001 moduleTranslation, builder, "omp.reduction.cleanup");
2002
2003 bool useDeviceSharedMem = omp::opInSharedDeviceContext(op);
2004 if (useDeviceSharedMem) {
2005 for (ReductionVarsInfo::VarInfo &var : redInfo.vars)
2006 ompBuilder->createOMPFreeShared(
2007 builder, var.privateVar,
2008 moduleTranslation.convertType(var.decl.getType()));
2009 }
2010
2011 return result;
2012}
2013
2014// TODO: not used by omp.parallel
2015static LogicalResult
2016allocAndInitializeReductionVars(Operation &op, llvm::IRBuilderBase &builder,
2017 LLVM::ModuleTranslation &moduleTranslation,
2018 llvm::OpenMPIRBuilder::InsertPointTy &allocaIP,
2019 ReductionVarsInfo &redInfo) {
2020 if (redInfo.size() == 0)
2021 return success();
2022
2023 if (failed(allocReductionVars(op, builder, moduleTranslation, allocaIP,
2024 redInfo)))
2025 return failure();
2026
2027 return initReductionVars(op, builder, moduleTranslation,
2028 allocaIP.getNodeParent(), redInfo);
2029}
2030
2031/// Return the llvm::Value * corresponding to the `privateVar` that
2032/// is being privatized. It isn't always as simple as looking up
2033/// moduleTranslation with privateVar. For instance, in case of
2034/// an allocatable, the descriptor for the allocatable is privatized.
2035/// This descriptor is mapped using an MapInfoOp. So, this function
2036/// will return a pointer to the llvm::Value corresponding to the
2037/// block argument for the mapped descriptor.
2038static llvm::Value *
2039findAssociatedValue(Value privateVar, llvm::IRBuilderBase &builder,
2040 LLVM::ModuleTranslation &moduleTranslation,
2041 llvm::DenseMap<Value, Value> *mappedPrivateVars = nullptr) {
2042 if (mappedPrivateVars == nullptr || !mappedPrivateVars->contains(privateVar))
2043 return moduleTranslation.lookupValue(privateVar);
2044
2045 Value blockArg = (*mappedPrivateVars)[privateVar];
2046 Type privVarType = privateVar.getType();
2047 Type blockArgType = blockArg.getType();
2048 assert(isa<LLVM::LLVMPointerType>(blockArgType) &&
2049 "A block argument corresponding to a mapped var should have "
2050 "!llvm.ptr type");
2051
2052 if (privVarType == blockArgType)
2053 return moduleTranslation.lookupValue(blockArg);
2054
2055 // This typically happens when the privatized type is lowered from
2056 // boxchar<KIND> and gets lowered to !llvm.struct<(ptr, i64)>. That is the
2057 // struct/pair is passed by value. But, mapped values are passed only as
2058 // pointers, so before we privatize, we must load the pointer.
2059 if (!isa<LLVM::LLVMPointerType>(privVarType))
2060 return builder.CreateLoad(moduleTranslation.convertType(privVarType),
2061 moduleTranslation.lookupValue(blockArg));
2062
2063 return moduleTranslation.lookupValue(privateVar);
2064}
2065
2066// Privatizer region arguments may be by-value even when the available LLVM
2067// value is storage for that value, e.g. lowered Fortran boxchar descriptors in
2068// task context structs. Materialize the value expected by the region argument
2069// while preserving the existing pointer mapping for pointer arguments.
2070static llvm::Value *
2071materializeRegionArgValue(llvm::IRBuilderBase &builder,
2072 LLVM::ModuleTranslation &moduleTranslation,
2073 BlockArgument regionArg, llvm::Value *value) {
2074 if (!regionArg)
2075 return value;
2076
2077 llvm::Type *regionArgType =
2078 moduleTranslation.convertType(regionArg.getType());
2079 if (regionArgType->isPointerTy() || !value->getType()->isPointerTy())
2080 return value;
2081
2082 return builder.CreateLoad(regionArgType, value);
2083}
2084
2085/// Returns the address of the data in `var`, via the `data_address` region.
2087getPrivateDataAddress(llvm::IRBuilderBase &builder,
2088 LLVM::ModuleTranslation &moduleTranslation,
2089 omp::PrivateClauseOp privatizer, llvm::Value *var) {
2090 Region &region = privatizer.getDataAddressRegion();
2091 if (region.empty())
2092 return var;
2093
2094 BlockArgument arg = privatizer.getDataAddressArg();
2095 moduleTranslation.mapValue(
2096 arg, materializeRegionArgValue(builder, moduleTranslation, arg, var));
2098 if (failed(inlineConvertOmpRegions(region, "omp.private.data_address",
2099 builder, moduleTranslation, &address)))
2100 return llvm::make_error<PreviouslyReportedError>();
2102 return address.front();
2103}
2104
2105/// Initialize a single (first)private variable. You probably want to use
2106/// allocateAndInitPrivateVars instead of this.
2107/// This returns the private variable which has been initialized. This
2108/// variable should be mapped before constructing the body of the Op.
2110initPrivateVar(llvm::IRBuilderBase &builder,
2111 LLVM::ModuleTranslation &moduleTranslation,
2112 omp::PrivateClauseOp &privDecl, llvm::Value *nonPrivateVar,
2113 BlockArgument &blockArg, llvm::Value *llvmPrivateVar,
2114 llvm::BasicBlock *privInitBlock,
2115 llvm::DenseMap<Value, Value> *mappedPrivateVars = nullptr) {
2116 Region &initRegion = privDecl.getInitRegion();
2117 if (initRegion.empty())
2118 return llvmPrivateVar;
2119
2120 assert(nonPrivateVar);
2121 moduleTranslation.mapValue(privDecl.getInitMoldArg(), nonPrivateVar);
2122 moduleTranslation.mapValue(privDecl.getInitPrivateArg(), llvmPrivateVar);
2123
2124 // in-place convert the private initialization region
2126 if (failed(inlineConvertOmpRegions(initRegion, "omp.private.init", builder,
2127 moduleTranslation, &phis)))
2128 return llvm::createStringError(
2129 "failed to inline `init` region of `omp.private`");
2130
2131 assert(phis.size() == 1 && "expected one allocation to be yielded");
2132
2133 // clear init region block argument mapping in case it needs to be
2134 // re-created with a different source for another use of the same
2135 // reduction decl
2136 moduleTranslation.forgetMapping(initRegion);
2137
2138 // Prefer the value yielded from the init region to the allocated private
2139 // variable in case the region is operating on arguments by-value (e.g.
2140 // Fortran character boxes).
2141 return phis[0];
2142}
2143
2144/// Version of initPrivateVar which looks up the nonPrivateVar from mlirPrivVar.
2146 llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation,
2147 omp::PrivateClauseOp &privDecl, Value mlirPrivVar, BlockArgument &blockArg,
2148 llvm::Value *llvmPrivateVar, llvm::BasicBlock *privInitBlock,
2149 llvm::DenseMap<Value, Value> *mappedPrivateVars = nullptr) {
2150 return initPrivateVar(
2151 builder, moduleTranslation, privDecl,
2152 findAssociatedValue(mlirPrivVar, builder, moduleTranslation,
2153 mappedPrivateVars),
2154 blockArg, llvmPrivateVar, privInitBlock, mappedPrivateVars);
2155}
2156
2157static llvm::Error
2158initPrivateVars(llvm::IRBuilderBase &builder,
2159 LLVM::ModuleTranslation &moduleTranslation,
2160 PrivateVarsInfo &privateVarsInfo,
2161 llvm::DenseMap<Value, Value> *mappedPrivateVars = nullptr) {
2162 if (privateVarsInfo.vars.empty())
2163 return llvm::Error::success();
2164
2165 llvm::BasicBlock *privInitBlock = splitBB(builder, true, "omp.private.init");
2166 setInsertPointForPossiblyEmptyBlock(builder, privInitBlock);
2167
2168 for (PrivateVarsInfo::VarInfo &var : privateVarsInfo.vars) {
2170 builder, moduleTranslation, var.privatizer, var.mlirVar, var.blockArg,
2171 var.llvmVar, privInitBlock, mappedPrivateVars);
2172
2173 if (!privVarOrErr)
2174 return privVarOrErr.takeError();
2175
2176 var.llvmVar = privVarOrErr.get();
2177 moduleTranslation.mapValue(var.blockArg, var.llvmVar);
2178
2180 }
2181
2182 return llvm::Error::success();
2183}
2184
2185static LogicalResult
2187 llvm::IRBuilderBase &builder,
2188 LLVM::ModuleTranslation &moduleTranslation,
2189 PrivateVarsInfo &privateVarsInfo) {
2190 for (Value allocatorVar : allocatorVars) {
2191 if (privateVarsInfo.convertedAllocators.contains(allocatorVar))
2192 continue;
2193
2194 llvm::Value *allocator = moduleTranslation.lookupValue(allocatorVar);
2195 if (!allocator)
2196 return op.emitError("failed to translate OpenMP allocator operand");
2197 if (allocator->getType()->isIntegerTy())
2198 allocator = builder.CreateIntToPtr(allocator, builder.getPtrTy());
2199 else if (allocator->getType()->isPointerTy())
2200 allocator = builder.CreatePointerBitCastOrAddrSpaceCast(
2201 allocator, builder.getPtrTy());
2202 else
2203 return op.emitError(
2204 "OpenMP allocator operand must have integer or pointer type");
2205
2206 privateVarsInfo.convertedAllocators.try_emplace(allocatorVar, allocator);
2207 }
2208 return success();
2209}
2210
2211/// Allocate and initialize delayed private variables. Returns the basic block
2212/// which comes after all of these allocations. llvm::Value * for each of these
2213/// private variables are populated in llvmPrivateVars.
2214template <typename T>
2216 T op, llvm::IRBuilderBase &builder,
2217 LLVM::ModuleTranslation &moduleTranslation,
2218 PrivateVarsInfo &privateVarsInfo,
2219 llvm::OpenMPIRBuilder::InsertPointTy &allocaIP,
2220 llvm::DenseMap<Value, Value> *mappedPrivateVars = nullptr,
2221 std::optional<llvm::OpenMPIRBuilder::InsertPointTy> allocatorIP =
2222 std::nullopt) {
2223 // Allocate private vars
2224 // Save blocks before splits since allocaIP/allocatorIP iterators may follow
2225 // spliced instructions to the new block.
2226 llvm::BasicBlock *allocaBB = allocaIP.getNodeParent();
2227 llvm::Instruction *allocaTerminator = allocaBB->getTerminator();
2228 splitBB(allocaTerminator->getIterator(), true,
2229 allocaTerminator->getDebugLoc(), "omp.region.after_alloca");
2230 // Update the allocaTerminator since the alloca block was split above.
2231 allocaTerminator = allocaBB->getTerminator();
2232 // The new terminator is an uncondition branch created by the splitBB above.
2233 assert(allocaTerminator->getNumSuccessors() == 1 &&
2234 "This is an unconditional branch created by splitBB");
2235 allocaIP = allocaTerminator->getIterator();
2236
2237 llvm::Instruction *allocatorTerminator = nullptr;
2238 llvm::BasicBlock *afterAllocatorAllocations = nullptr;
2239 if (allocatorIP) {
2240 llvm::BasicBlock *allocatorBB = allocatorIP->getNodeParent();
2241 allocatorTerminator = allocatorBB->getTerminator();
2242 afterAllocatorAllocations = splitBB(
2243 allocatorTerminator->getIterator(), true,
2244 allocatorTerminator->getDebugLoc(), "omp.region.after_allocate");
2245 allocatorTerminator = allocatorBB->getTerminator();
2246 assert(allocatorTerminator->getNumSuccessors() == 1 &&
2247 "This is an unconditional branch created by splitBB");
2248 }
2249
2250 std::optional<llvm::IRBuilderBase::InsertPointGuard> guard;
2251 if (!allocatorIP)
2252 guard.emplace(builder);
2253 builder.SetInsertPoint(allocaTerminator);
2254
2255 llvm::DataLayout dataLayout = builder.getDataLayout();
2256 llvm::BasicBlock *afterAllocas = allocaTerminator->getSuccessor(0);
2257
2258 llvm::OpenMPIRBuilder *ompBuilder = getOpenMPBuilder(moduleTranslation);
2259 bool mightUseDeviceSharedMem = omp::opInSharedDeviceContext(*op);
2260 unsigned int allocaAS =
2261 moduleTranslation.getLLVMModule()->getDataLayout().getAllocaAddrSpace();
2262 unsigned int defaultAS = moduleTranslation.getLLVMModule()
2263 ->getDataLayout()
2264 .getProgramAddressSpace();
2265
2266 SmallVector<int64_t> allocateItemForPrivate(privateVarsInfo.vars.size(), -1);
2267 ValueRange allocatorVars;
2268 DenseI64ArrayAttr allocateAlignments;
2269 if constexpr (std::is_same_v<T, omp::ParallelOp> ||
2270 std::is_same_v<T, omp::ScopeOp>) {
2271 allocatorVars = op.getAllocatorVars();
2272 allocateAlignments = op.getAllocateAlignmentsAttr();
2273 if (auto privateIndices = op.getAllocatePrivateIndicesAttr())
2274 for (auto [allocateIndex, privateIndex] :
2275 llvm::enumerate(privateIndices.asArrayRef()))
2276 allocateItemForPrivate[privateIndex] = allocateIndex;
2277 }
2278
2279 for (auto [privateIndex, var] : llvm::enumerate(privateVarsInfo.vars)) {
2280 llvm::Type *llvmAllocType =
2281 moduleTranslation.convertType(var.privatizer.getType());
2282 llvm::Value *llvmPrivateVar = nullptr;
2283 int64_t allocateIndex = allocateItemForPrivate[privateIndex];
2284 builder.SetInsertPoint(allocateIndex >= 0 && allocatorTerminator
2285 ? allocatorTerminator
2286 : allocaTerminator);
2287 if (allocateIndex >= 0) {
2288 if (ompBuilder->Config.isTargetDevice() ||
2289 op->template getParentOfType<omp::TargetOp>())
2290 return llvm::createStringError(
2291 "allocate clause in an OpenMP device context is not supported");
2292 if (!llvmAllocType->isSized())
2293 return llvm::createStringError(
2294 "allocate clause private type must have a fixed size");
2295 llvm::TypeSize size = dataLayout.getTypeAllocSize(llvmAllocType);
2296 if (size.isScalable())
2297 return llvm::createStringError(
2298 "allocate clause private type must have a fixed size");
2299 llvm::IntegerType *sizeTy =
2300 moduleTranslation.getLLVMModule()->getDataLayout().getIntPtrType(
2301 moduleTranslation.getLLVMModule()->getContext());
2302 if (!llvm::isUIntN(sizeTy->getBitWidth(), size.getFixedValue()))
2303 return llvm::createStringError(
2304 "OpenMP allocation size cannot be represented by the target size "
2305 "type");
2306 llvm::Value *sizeValue =
2307 llvm::ConstantInt::get(sizeTy, size.getFixedValue());
2308
2309 Value allocatorVar = allocatorVars[allocateIndex];
2310 auto allocator = privateVarsInfo.convertedAllocators.find(allocatorVar);
2311 if (allocator == privateVarsInfo.convertedAllocators.end())
2312 return llvm::createStringError(
2313 "failed to find converted OpenMP allocator operand");
2314 llvm::OpenMPIRBuilder::LocationDescription ompLoc(builder);
2315 int64_t alignment =
2316 allocateAlignments ? allocateAlignments[allocateIndex] : 0;
2317 if (alignment != 0) {
2318 // The allocation must be aligned to at least the maximum of the
2319 // requested alignment and the alignment the base language requires
2320 // for the type being allocated.
2321 uint64_t alignmentValue = std::max<uint64_t>(
2322 static_cast<uint64_t>(alignment),
2323 dataLayout.getABITypeAlign(llvmAllocType).value());
2324 if (!llvm::isUIntN(sizeTy->getBitWidth(), alignmentValue))
2325 return llvm::createStringError(
2326 "OpenMP allocation alignment cannot be represented by the "
2327 "target size type");
2328 llvmPrivateVar = ompBuilder->createOMPAlignedAlloc(
2329 ompLoc, llvm::ConstantInt::get(sizeTy, alignmentValue), sizeValue,
2330 allocator->second, "omp.private.alloc");
2331 } else {
2332 llvmPrivateVar = ompBuilder->createOMPAlloc(
2333 ompLoc, sizeValue, allocator->second, "omp.private.alloc");
2334 }
2335 if (!llvmPrivateVar)
2336 return llvm::createStringError(
2337 "failed to create OpenMP private allocation");
2338 privateVarsInfo.allocatorPrivates.push_back(
2339 {llvmPrivateVar, allocator->second});
2340 } else if (mightUseDeviceSharedMem &&
2341 omp::allocaUsesRequireSharedMem(var.blockArg)) {
2342 llvmPrivateVar = ompBuilder->createOMPAllocShared(builder, llvmAllocType);
2343 } else {
2344 llvmPrivateVar = builder.CreateAlloca(
2345 llvmAllocType, /*ArraySize=*/nullptr, "omp.private.alloc");
2346 if (allocaAS != defaultAS)
2347 llvmPrivateVar = builder.CreateAddrSpaceCast(
2348 llvmPrivateVar, builder.getPtrTy(defaultAS));
2349 }
2350
2351 var.llvmVar = llvmPrivateVar;
2352 }
2353
2354 return afterAllocatorAllocations ? afterAllocatorAllocations : afterAllocas;
2355}
2356
2357/// A compiler-generated barrier is unsafe when only part of the current team
2358/// can reach it. This cannot always be determined statically (e.g. across a
2359/// function call), but the enclosing OpenMP constructs can rule it out.
2361 for (mlir::Operation *parent = op; parent != nullptr;
2362 parent = parent->getParentOp()) {
2363 // An inner parallel construct creates a new team, even when it is nested
2364 // inside a construct that only some threads of the outer team encounter.
2365 if (mlir::isa<omp::ParallelOp>(parent))
2366 return true;
2367
2368 if (mlir::isa<omp::SingleOp, omp::CriticalOp, omp::MaskedOp, omp::MasterOp,
2369 omp::SectionOp>(parent))
2370 return false;
2371 }
2372 return true;
2373}
2374
2375static LogicalResult
2376emitPrivatizationBarrier(mlir::Operation *op, llvm::IRBuilderBase &builder,
2377 LLVM::ModuleTranslation &moduleTranslation) {
2378 if (!opMightBeSafeForBarriers(op))
2379 return success();
2380
2381 llvm::OpenMPIRBuilder *ompBuilder = getOpenMPBuilder(moduleTranslation);
2382 llvm::OpenMPIRBuilder::InsertPointOrErrorTy res =
2383 ompBuilder->createBarrier(builder, llvm::omp::OMPD_barrier);
2384 return handleError(res, *op);
2385}
2386
2387/// Applies the firstprivate copy region for each variable, pairing the mold
2388/// values with the private allocations and privatizer declarations from
2389/// `privateVarsInfo`, and emits a barrier if requested.
2390///
2391/// `moldVars` and `llvmPrivateVars` are optional overrides that, if empty,
2392/// are read directly from `privateVarsInfo`. `mappedPrivateVars` is only
2393/// consulted while materializing mold values from `privateVarsInfo` (i.e. empty
2394/// `moldVars`).
2395static LogicalResult
2396completePrivateVars(mlir::Operation *op, llvm::IRBuilderBase &builder,
2397 LLVM::ModuleTranslation &moduleTranslation,
2398 const PrivateVarsInfo &privateVarsInfo, bool insertBarrier,
2399 ArrayRef<llvm::Value *> moldVars = {},
2400 ArrayRef<llvm::Value *> llvmPrivateVars = {},
2401 DenseMap<Value, Value> *mappedPrivateVars = nullptr) {
2402 assert((moldVars.empty() || moldVars.size() == privateVarsInfo.vars.size()) &&
2403 "expected one mold value per variable when provided");
2404 assert((llvmPrivateVars.empty() ||
2405 llvmPrivateVars.size() == privateVarsInfo.vars.size()) &&
2406 "expected one private allocation per variable when provided");
2407
2408 // Apply copy region for firstprivate.
2409 bool needsFirstprivate = llvm::any_of(
2410 privateVarsInfo.vars, [](const PrivateVarsInfo::VarInfo &var) {
2411 // Copy the op handle so the non-const accessor can be called.
2412 omp::PrivateClauseOp privOp = var.privatizer;
2413 return privOp.getDataSharingType() ==
2414 omp::DataSharingClauseType::FirstPrivate;
2415 });
2416
2417 if (!needsFirstprivate)
2418 return insertBarrier
2419 ? emitPrivatizationBarrier(op, builder, moduleTranslation)
2420 : success();
2421
2422 // Materialize the mold values from the MLIR variables when the caller didn't
2423 // supply explicit locations.
2424 SmallVector<llvm::Value *> materializedMoldVars;
2425 if (moldVars.empty()) {
2426 materializedMoldVars.reserve(privateVarsInfo.vars.size());
2427 for (const PrivateVarsInfo::VarInfo &var : privateVarsInfo.vars) {
2428 // map copyRegion rhs arg
2429 llvm::Value *moldVar = findAssociatedValue(
2430 var.mlirVar, builder, moduleTranslation, mappedPrivateVars);
2431 assert(moldVar);
2432 materializedMoldVars.push_back(moldVar);
2433 }
2434 moldVars = materializedMoldVars;
2435 }
2436
2437 llvm::BasicBlock *copyBlock =
2438 splitBB(builder, /*CreateBranch=*/true, "omp.private.copy");
2439 setInsertPointForPossiblyEmptyBlock(builder, copyBlock);
2440
2441 unsigned varIdx = 0;
2442 for (auto [var, moldVar] : llvm::zip_equal(privateVarsInfo.vars, moldVars)) {
2443 // The private allocation defaults to the one tracked in `privateVarsInfo`,
2444 // unless the caller overrode it with an explicit location.
2445 llvm::Value *llvmVar =
2446 llvmPrivateVars.empty() ? var.llvmVar : llvmPrivateVars[varIdx];
2447 ++varIdx;
2448
2449 omp::PrivateClauseOp decl = var.privatizer;
2450 if (decl.getDataSharingType() != omp::DataSharingClauseType::FirstPrivate)
2451 continue;
2452
2453 // copyRegion implements `lhs = rhs`
2454 Region &copyRegion = decl.getCopyRegion();
2455
2456 llvm::Value *copyMoldVar = materializeRegionArgValue(
2457 builder, moduleTranslation, decl.getCopyMoldArg(), moldVar);
2458 llvm::Value *copyPrivateVar = materializeRegionArgValue(
2459 builder, moduleTranslation, decl.getCopyPrivateArg(), llvmVar);
2460
2461 moduleTranslation.mapValue(decl.getCopyMoldArg(), copyMoldVar);
2462
2463 // map copyRegion lhs arg
2464 moduleTranslation.mapValue(decl.getCopyPrivateArg(), copyPrivateVar);
2465
2466 // in-place convert copy region
2467 if (failed(inlineConvertOmpRegions(copyRegion, "omp.private.copy", builder,
2468 moduleTranslation)))
2469 return decl.emitError("failed to inline `copy` region of `omp.private`");
2470
2472
2473 // ignore unused value yielded from copy region
2474
2475 // clear copy region block argument mapping in case it needs to be
2476 // re-created with different sources for reuse of the same reduction
2477 // decl
2478 moduleTranslation.forgetMapping(copyRegion);
2479 }
2480
2481 return insertBarrier
2482 ? emitPrivatizationBarrier(op, builder, moduleTranslation)
2483 : success();
2484}
2485
2486template <typename T>
2487static LogicalResult
2488cleanupPrivateVars(T op, llvm::IRBuilderBase &builder,
2489 LLVM::ModuleTranslation &moduleTranslation, Location loc,
2490 PrivateVarsInfo &privateVarsInfo) {
2491 // private variable deallocation
2492 SmallVector<Region *> privateCleanupRegions;
2493 llvm::transform(privateVarsInfo.vars,
2494 std::back_inserter(privateCleanupRegions),
2495 [](PrivateVarsInfo::VarInfo &var) {
2496 return &var.privatizer.getDeallocRegion();
2497 });
2498
2499 SmallVector<llvm::Value *> llvmPrivVars = privateVarsInfo.getLlvmVars();
2500 if (failed(inlineOmpRegionCleanup(privateCleanupRegions, llvmPrivVars,
2501 moduleTranslation, builder,
2502 "omp.private.dealloc",
2503 /*shouldLoadCleanupRegionArg=*/false)))
2504 return mlir::emitError(loc, "failed to inline `dealloc` region of an "
2505 "`omp.private` op in");
2507
2508 llvm::OpenMPIRBuilder *ompBuilder = getOpenMPBuilder(moduleTranslation);
2509 bool mightUseDeviceSharedMem = omp::opInSharedDeviceContext(*op);
2510 for (PrivateVarsInfo::VarInfo &var : privateVarsInfo.vars) {
2511 if (mightUseDeviceSharedMem &&
2512 omp::allocaUsesRequireSharedMem(var.blockArg)) {
2513 ompBuilder->createOMPFreeShared(
2514 builder, var.llvmVar,
2515 moduleTranslation.convertType(var.privatizer.getType()));
2516 }
2517 }
2518
2519 llvm::OpenMPIRBuilder::LocationDescription ompLoc(builder);
2520 for (const PrivateVarsInfo::AllocatorInfo &allocation :
2521 llvm::reverse(privateVarsInfo.allocatorPrivates))
2522 ompBuilder->createOMPFree(ompLoc, allocation.allocatedPtr,
2523 allocation.allocator);
2524
2525 return success();
2526}
2527
2528/// Returns true if the construct contains omp.cancel or omp.cancellation_point
2530 // omp.cancel and omp.cancellation_point must be "closely nested" so they will
2531 // be visible and not inside of function calls. This is enforced by the
2532 // verifier.
2533 return op
2534 ->walk([](Operation *child) {
2535 if (mlir::isa<omp::CancelOp, omp::CancellationPointOp>(child))
2536 return WalkResult::interrupt();
2537 return WalkResult::advance();
2538 })
2539 .wasInterrupted();
2540}
2541
2542// Forward declarations for the task-reduction helpers defined alongside the
2543// omp.taskgroup lowering further down in this file. These are shared by the
2544// `reduction(task, ...)` modifier lowering on the parallel/worksharing
2545// constructs and by the omp.taskgroup / omp.taskloop.context task_reduction
2546// lowering. When \p isModifier is set, `__kmpc_taskred_modifier_init` is
2547// emitted (opening a task-reduction scope) instead of `__kmpc_taskred_init`,
2548// with \p isWorksharing selecting the runtime `is_ws` argument.
2549static llvm::Value *emitTaskReductionInitCall(
2551 ArrayRef<llvm::Value *> origPtrs, StringRef helperNamePrefix,
2552 llvm::IRBuilderBase &builder, llvm::OpenMPIRBuilder::InsertPointTy allocaIP,
2553 LLVM::ModuleTranslation &moduleTranslation, bool isModifier = false,
2554 bool isWorksharing = false);
2555static void
2556emitTaskReductionModifierFini(bool isWorksharing, llvm::IRBuilderBase &builder,
2557 LLVM::ModuleTranslation &moduleTranslation);
2558
2559/// Register only the task-modified items. All items still participate in the
2560/// enclosing construct's ordinary reduction combination and cleanup.
2561template <typename OpTy>
2563 OpTy op, ArrayRef<omp::DeclareReductionOp> reductionDecls,
2564 ArrayRef<llvm::Value *> privateReductionVariables,
2565 llvm::IRBuilderBase &builder, llvm::OpenMPIRBuilder::InsertPointTy allocaIP,
2566 LLVM::ModuleTranslation &moduleTranslation, bool isWorksharing) {
2568 SmallVector<llvm::Value *> taskVariables;
2569 for (unsigned i = 0, e = op.getNumReductionVars(); i != e; ++i) {
2570 if (op.getReductionModifier(i) != omp::ReductionModifier::task)
2571 continue;
2572 taskDecls.push_back(reductionDecls[i]);
2573 taskVariables.push_back(privateReductionVariables[i]);
2574 }
2576 taskDecls, taskVariables, "__omp_taskred_mod_", builder, allocaIP,
2577 moduleTranslation, /*isModifier=*/true, isWorksharing);
2578}
2579
2580static LogicalResult
2581convertOmpSections(Operation &opInst, llvm::IRBuilderBase &builder,
2582 LLVM::ModuleTranslation &moduleTranslation) {
2583 using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy;
2584 using StorableBodyGenCallbackTy =
2585 llvm::OpenMPIRBuilder::StorableBodyGenCallbackTy;
2586
2587 auto sectionsOp = cast<omp::SectionsOp>(opInst);
2588
2589 if (failed(checkImplementationStatus(opInst)))
2590 return failure();
2591
2592 ReductionVarsInfo redInfo(sectionsOp);
2593 llvm::OpenMPIRBuilder::InsertPointTy allocaIP =
2594 findAllocInsertPoints(builder, moduleTranslation);
2595
2597 *sectionsOp, builder, moduleTranslation, allocaIP, redInfo)))
2598 return failure();
2599
2600 bool isTaskReductionMod =
2601 sectionsOp.hasReductionModifier(omp::ReductionModifier::task);
2602
2604
2605 for (Operation &op : *sectionsOp.getRegion().begin()) {
2606 auto sectionOp = dyn_cast<omp::SectionOp>(op);
2607 if (!sectionOp) // omp.terminator
2608 continue;
2609
2610 Region &region = sectionOp.getRegion();
2611 auto sectionCB = [&sectionsOp, &region, &builder, &moduleTranslation](
2612 InsertPointTy allocaIP, InsertPointTy codeGenIP,
2613 ArrayRef<llvm::BasicBlock *> deallocBlocks) {
2614 builder.restoreIP(codeGenIP);
2615
2616 // map the omp.section reduction block argument to the omp.sections block
2617 // arguments
2618 // TODO: this assumes that the only block arguments are reduction
2619 // variables
2620 assert(region.getNumArguments() ==
2621 sectionsOp.getRegion().getNumArguments());
2622 for (auto [sectionsArg, sectionArg] : llvm::zip_equal(
2623 sectionsOp.getRegion().getArguments(), region.getArguments())) {
2624 llvm::Value *llvmVal = moduleTranslation.lookupValue(sectionsArg);
2625 assert(llvmVal);
2626 moduleTranslation.mapValue(sectionArg, llvmVal);
2627 }
2628
2629 return convertOmpOpRegions(region, "omp.section.region", builder,
2630 moduleTranslation)
2631 .takeError();
2632 };
2633 sectionCBs.push_back(sectionCB);
2634 }
2635
2636 // Empty sections still require an implicit barrier unless nowait is present.
2637 if (sectionCBs.empty()) {
2638 if (!sectionsOp.getNowait()) {
2639 auto afterIP = getOpenMPBuilder(moduleTranslation)
2640 ->createBarrier(builder, llvm::omp::OMPD_sections);
2641 if (failed(handleError(afterIP, opInst)))
2642 return failure();
2643 builder.restoreIP(*afterIP);
2644 }
2645 return success();
2646 }
2647
2648 // For `reduction(task, ...)` open a task-reduction scope for the worksharing
2649 // region. Participating explicit tasks accumulate into the per-thread private
2650 // copies, which the worksharing reduction then combines across threads. This
2651 // is emitted only after the empty-sections early return above, so it stays
2652 // balanced with the matching fini emitted after the sections region.
2653 if (isTaskReductionMod &&
2655 sectionsOp, redInfo.getReductionDecls(),
2656 redInfo.getPrivateReductionVariables(), builder, allocaIP,
2657 moduleTranslation, /*isWorksharing=*/true))
2658 return sectionsOp.emitError(
2659 "failed to emit task reduction modifier initialization");
2660
2661 assert(isa<omp::SectionOp>(*sectionsOp.getRegion().op_begin()));
2662
2663 // TODO: Perform appropriate actions according to the data-sharing
2664 // attribute (shared, private, firstprivate, ...) of variables.
2665 // Currently defaults to shared.
2666 auto privCB = [&](InsertPointTy, InsertPointTy codeGenIP, llvm::Value &,
2667 llvm::Value &vPtr, llvm::Value *&replacementValue)
2668 -> llvm::OpenMPIRBuilder::InsertPointOrErrorTy {
2669 replacementValue = &vPtr;
2670 return codeGenIP;
2671 };
2672
2673 // TODO: Perform finalization actions for variables. This has to be
2674 // called for variables which have destructors/finalizers.
2675 auto finiCB = [&](InsertPointTy codeGenIP) { return llvm::Error::success(); };
2676
2677 allocaIP = findAllocInsertPoints(builder, moduleTranslation);
2678 bool isCancellable = constructIsCancellable(sectionsOp);
2679 llvm::OpenMPIRBuilder::LocationDescription ompLoc(builder);
2680 llvm::OpenMPIRBuilder::InsertPointOrErrorTy afterIP =
2681 getOpenMPBuilder(moduleTranslation)
2682 ->createSections(ompLoc, allocaIP, sectionCBs, privCB, finiCB,
2683 isCancellable, sectionsOp.getNowait());
2684
2685 if (failed(handleError(afterIP, opInst)))
2686 return failure();
2687
2688 builder.restoreIP(*afterIP);
2689
2690 // Close the task-reduction scope before combining the worksharing copies.
2691 if (isTaskReductionMod)
2692 emitTaskReductionModifierFini(/*isWorksharing=*/true, builder,
2693 moduleTranslation);
2694
2695 // Process the reductions if required.
2696 return createReductionsAndCleanup(*sectionsOp, builder, moduleTranslation,
2697 allocaIP, redInfo, sectionsOp.getNowait());
2698}
2699
2700/// Converts an OpenMP scope construct into LLVM IR.
2701static LogicalResult
2702convertOmpScope(omp::ScopeOp &scopeOp, llvm::IRBuilderBase &builder,
2703 LLVM::ModuleTranslation &moduleTranslation) {
2704 using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy;
2705 llvm::OpenMPIRBuilder *ompBuilder = getOpenMPBuilder(moduleTranslation);
2706
2707 if (failed(checkImplementationStatus(*scopeOp)))
2708 return failure();
2709
2710 PrivateVarsInfo privateVarsInfo(scopeOp);
2711 if (failed(convertAllocatorVars(*scopeOp, scopeOp.getAllocatorVars(), builder,
2712 moduleTranslation, privateVarsInfo)))
2713 return failure();
2714
2715 ReductionVarsInfo reductionInfo(scopeOp);
2716 InsertPointTy privateAllocaIP =
2717 findAllocInsertPoints(builder, moduleTranslation);
2718
2719 if (scopeOp.getAllocateVars().empty()) {
2721 scopeOp, builder, moduleTranslation, privateVarsInfo, privateAllocaIP);
2722 if (failed(handleError(afterAllocas, *scopeOp)))
2723 return failure();
2724 }
2725
2726 if (failed(allocAndInitializeReductionVars(*scopeOp, builder,
2727 moduleTranslation, privateAllocaIP,
2728 reductionInfo)))
2729 return failure();
2730
2731 auto bodyCB =
2732 [&](InsertPointTy allocaIP, InsertPointTy codeGenIP,
2733 llvm::ArrayRef<llvm::BasicBlock *> deallocBlocks) -> llvm::Error {
2734 if (!scopeOp.getAllocateVars().empty()) {
2735 // Runtime storage must be allocated on each dynamic Scope entry. Ordinary
2736 // private allocas still use the enclosing alloca insertion point.
2738 scopeOp, builder, moduleTranslation, privateVarsInfo, privateAllocaIP,
2739 /*mappedPrivateVars=*/nullptr, codeGenIP);
2740 if (handleError(afterAllocas, *scopeOp).failed())
2741 return llvm::make_error<PreviouslyReportedError>();
2742 builder.SetInsertPoint(afterAllocas.get()->getTerminator());
2743 } else {
2744 builder.restoreIP(codeGenIP);
2745 }
2746
2747 if (handleError(
2748 initPrivateVars(builder, moduleTranslation, privateVarsInfo),
2749 *scopeOp)
2750 .failed())
2751 return llvm::make_error<PreviouslyReportedError>();
2752
2753 if (failed(completePrivateVars(scopeOp, builder, moduleTranslation,
2754 privateVarsInfo,
2755 scopeOp.getPrivateNeedsBarrier())))
2756 return llvm::make_error<PreviouslyReportedError>();
2757
2758 return convertOmpOpRegions(scopeOp.getRegion(), "omp.scope.region", builder,
2759 moduleTranslation)
2760 .takeError();
2761 };
2762
2763 auto finiCB = [&](InsertPointTy codeGenIP) -> llvm::Error {
2764 InsertPointTy oldIP = builder.saveIP();
2765 builder.restoreIP(codeGenIP);
2766 if (failed(cleanupPrivateVars(scopeOp, builder, moduleTranslation,
2767 scopeOp.getLoc(), privateVarsInfo)))
2768 return llvm::make_error<PreviouslyReportedError>();
2769 builder.restoreIP(oldIP);
2770 return llvm::Error::success();
2771 };
2772
2773 llvm::OpenMPIRBuilder::LocationDescription ompLoc(builder);
2774 llvm::OpenMPIRBuilder::InsertPointOrErrorTy afterIP =
2775 ompBuilder->createScope(ompLoc, bodyCB, finiCB, scopeOp.getNowait());
2776
2777 if (failed(handleError(afterIP, *scopeOp)))
2778 return failure();
2779
2780 builder.restoreIP(*afterIP);
2781
2782 // Process the reductions if required.
2783 return createReductionsAndCleanup(*scopeOp, builder, moduleTranslation,
2784 privateAllocaIP, reductionInfo,
2785 scopeOp.getNowait(),
2786 /*isTeamsReduction=*/false);
2787}
2788
2789/// Converts an OpenMP single construct into LLVM IR using OpenMPIRBuilder.
2790static LogicalResult
2791convertOmpSingle(omp::SingleOp &singleOp, llvm::IRBuilderBase &builder,
2792 LLVM::ModuleTranslation &moduleTranslation) {
2793 using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy;
2794 llvm::OpenMPIRBuilder::LocationDescription ompLoc(builder);
2795
2796 if (failed(checkImplementationStatus(*singleOp)))
2797 return failure();
2798
2799 auto bodyCB = [&](InsertPointTy allocaIP, InsertPointTy codegenIP,
2800 llvm::ArrayRef<llvm::BasicBlock *> deallocBlocks) {
2801 builder.restoreIP(codegenIP);
2802 return convertOmpOpRegions(singleOp.getRegion(), "omp.single.region",
2803 builder, moduleTranslation)
2804 .takeError();
2805 };
2806 auto finiCB = [&](InsertPointTy codeGenIP) { return llvm::Error::success(); };
2807
2808 // Handle copyprivate
2809 Operation::operand_range cpVars = singleOp.getCopyprivateVars();
2810 std::optional<ArrayAttr> cpFuncs = singleOp.getCopyprivateSyms();
2813 for (size_t i = 0, e = cpVars.size(); i < e; ++i) {
2814 llvmCPVars.push_back(moduleTranslation.lookupValue(cpVars[i]));
2816 singleOp, cast<SymbolRefAttr>((*cpFuncs)[i]));
2817 llvmCPFuncs.push_back(
2818 moduleTranslation.lookupFunction(llvmFuncOp.getName()));
2819 }
2820
2821 llvm::OpenMPIRBuilder::InsertPointOrErrorTy afterIP =
2822 getOpenMPBuilder(moduleTranslation)
2823 ->createSingle(ompLoc, bodyCB, finiCB, singleOp.getNowait(),
2824 llvmCPVars, llvmCPFuncs);
2825
2826 if (failed(handleError(afterIP, *singleOp)))
2827 return failure();
2828
2829 builder.restoreIP(*afterIP);
2830 return success();
2831}
2832
2833static omp::DistributeOp
2835 // Early return if we found more than one distribute op or if we can't find
2836 // any distribute op in the teams region.
2837 omp::DistributeOp distOp;
2838 WalkResult walk = teamsOp.getRegion().walk([&](omp::DistributeOp op) {
2839 if (distOp)
2840 return WalkResult::interrupt();
2841 distOp = op;
2842 return WalkResult::skip();
2843 });
2844 if (walk.wasInterrupted() || !distOp)
2845 return {};
2846
2847 auto iface =
2848 llvm::cast<mlir::omp::BlockArgOpenMPOpInterface>(teamsOp.getOperation());
2849 // Check that all uses of the reduction block arg has the same distribute op
2850 // parent.
2852 for (auto ra : iface.getReductionBlockArgs())
2853 for (auto &use : ra.getUses()) {
2854 auto *useOp = use.getOwner();
2855 // Ignore debug uses.
2856 if (mlir::isa<LLVM::DbgDeclareOp, LLVM::DbgValueOp>(useOp)) {
2857 debugUses.push_back(useOp);
2858 continue;
2859 }
2860 if (!distOp->isProperAncestor(useOp))
2861 return {};
2862 }
2863
2864 // If we are going to use distribute reduction then remove any debug uses of
2865 // the reduction parameters in teamsOp. Otherwise they will be left without
2866 // any mapped value in moduleTranslation and will eventually error out.
2867 for (auto *use : debugUses)
2868 use->erase();
2869 return distOp;
2870}
2871
2872// Convert an OpenMP Teams construct to LLVM IR using OpenMPIRBuilder
2873static LogicalResult
2874convertOmpTeams(omp::TeamsOp op, llvm::IRBuilderBase &builder,
2875 LLVM::ModuleTranslation &moduleTranslation) {
2876 using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy;
2877 if (failed(checkImplementationStatus(*op)))
2878 return failure();
2879
2880 std::optional<ReductionVarsInfo> teamsRedInfo;
2881 llvm::OpenMPIRBuilder::InsertPointTy allocaIP =
2882 findAllocInsertPoints(builder, moduleTranslation);
2883
2884 // Only do teams reduction if there is no distribute op that captures the
2885 // reduction instead.
2887 teamsRedInfo.emplace(op);
2888
2889 if (failed(allocAndInitializeReductionVars(*op, builder, moduleTranslation,
2890 allocaIP, *teamsRedInfo)))
2891 return failure();
2892 }
2893
2894 auto bodyCB = [&](InsertPointTy allocaIP, InsertPointTy codegenIP,
2895 llvm::ArrayRef<llvm::BasicBlock *> deallocBlocks) {
2897 moduleTranslation, allocaIP.getNodeParent(), deallocBlocks);
2898 builder.restoreIP(codegenIP);
2899 return convertOmpOpRegions(op.getRegion(), "omp.teams.region", builder,
2900 moduleTranslation)
2901 .takeError();
2902 };
2903
2904 llvm::Value *numTeamsLower = nullptr;
2905 if (Value numTeamsLowerVar = op.getNumTeamsLower())
2906 numTeamsLower = moduleTranslation.lookupValue(numTeamsLowerVar);
2907
2908 llvm::Value *numTeamsUpper = nullptr;
2909 if (!op.getNumTeamsUpperVars().empty())
2910 numTeamsUpper = moduleTranslation.lookupValue(op.getNumTeams(0));
2911
2912 llvm::Value *threadLimit = nullptr;
2913 if (!op.getThreadLimitVars().empty())
2914 threadLimit = moduleTranslation.lookupValue(op.getThreadLimit(0));
2915
2916 llvm::Value *ifExpr = nullptr;
2917 if (Value ifVar = op.getIfExpr())
2918 ifExpr = moduleTranslation.lookupValue(ifVar);
2919
2920 llvm::OpenMPIRBuilder::LocationDescription ompLoc(builder);
2921 llvm::OpenMPIRBuilder::InsertPointOrErrorTy afterIP =
2922 getOpenMPBuilder(moduleTranslation)
2923 ->createTeams(ompLoc, bodyCB, numTeamsLower, numTeamsUpper,
2924 threadLimit, ifExpr);
2925
2926 if (failed(handleError(afterIP, *op)))
2927 return failure();
2928
2929 builder.restoreIP(*afterIP);
2930 if (teamsRedInfo) {
2931 // Process the reductions if required.
2932 return createReductionsAndCleanup(*op, builder, moduleTranslation, allocaIP,
2933 *teamsRedInfo,
2934 /*isNoWait=*/false,
2935 /*isTeamsReduction=*/true);
2936 }
2937 return success();
2938}
2939
2940static llvm::omp::RTLDependenceKindTy
2941convertDependKind(mlir::omp::ClauseTaskDepend kind) {
2942 switch (kind) {
2943 case mlir::omp::ClauseTaskDepend::taskdependin:
2944 return llvm::omp::RTLDependenceKindTy::DepIn;
2945 // The OpenMP runtime requires that the codegen for 'depend' clause for
2946 // 'out' dependency kind must be the same as codegen for 'depend' clause
2947 // with 'inout' dependency.
2948 case mlir::omp::ClauseTaskDepend::taskdependout:
2949 case mlir::omp::ClauseTaskDepend::taskdependinout:
2950 return llvm::omp::RTLDependenceKindTy::DepInOut;
2951 case mlir::omp::ClauseTaskDepend::taskdependmutexinoutset:
2952 return llvm::omp::RTLDependenceKindTy::DepMutexInOutSet;
2953 case mlir::omp::ClauseTaskDepend::taskdependinoutset:
2954 return llvm::omp::RTLDependenceKindTy::DepInOutSet;
2955 }
2956 llvm_unreachable("unhandled depend kind");
2957}
2958
2960 std::optional<ArrayAttr> dependKinds, OperandRange dependVars,
2961 LLVM::ModuleTranslation &moduleTranslation,
2963 if (dependVars.empty())
2964 return;
2965 for (auto dep : llvm::zip(dependVars, dependKinds->getValue())) {
2966 auto kind =
2967 cast<mlir::omp::ClauseTaskDependAttr>(std::get<1>(dep)).getValue();
2968 llvm::omp::RTLDependenceKindTy type = convertDependKind(kind);
2969 llvm::Value *depVal = moduleTranslation.lookupValue(std::get<0>(dep));
2970 llvm::OpenMPIRBuilder::DependData dd(type, depVal->getType(), depVal);
2971 dds.emplace_back(dd);
2972 }
2973}
2974
2975/// Shared implementation of a callback which adds a termiator for the new block
2976/// created for the branch taken when an openmp construct is cancelled. The
2977/// terminator is saved in \p cancelTerminators. This callback is invoked only
2978/// if there is cancellation inside of the taskgroup body.
2979/// The terminator will need to be fixed to branch to the correct block to
2980/// cleanup the construct.
2982 SmallVectorImpl<llvm::UncondBrInst *> &cancelTerminators,
2983 llvm::IRBuilderBase &llvmBuilder, llvm::OpenMPIRBuilder &ompBuilder,
2984 mlir::Operation *op, llvm::omp::Directive cancelDirective) {
2985 auto finiCB = [&](llvm::OpenMPIRBuilder::InsertPointTy ip) -> llvm::Error {
2986 llvm::IRBuilderBase::InsertPointGuard guard(llvmBuilder);
2987
2988 // ip is currently in the block branched to if cancellation occurred.
2989 // We need to create a branch to terminate that block.
2990 llvmBuilder.restoreIP(ip);
2991
2992 // We must still clean up the construct after cancelling it, so we need to
2993 // branch to the block that finalizes the taskgroup.
2994 // That block has not been created yet so use this block as a dummy for now
2995 // and fix this after creating the operation.
2996 cancelTerminators.push_back(llvmBuilder.CreateBr(ip.getNodeParent()));
2997 return llvm::Error::success();
2998 };
2999 // We have to add the cleanup to the OpenMPIRBuilder before the body gets
3000 // created in case the body contains omp.cancel (which will then expect to be
3001 // able to find this cleanup callback).
3002 ompBuilder.pushFinalizationCB(
3003 {finiCB, cancelDirective, constructIsCancellable(op)});
3004}
3005
3006/// If we cancelled the construct, we should branch to the finalization block of
3007/// that construct. OMPIRBuilder structures the CFG such that the cleanup block
3008/// is immediately before the continuation block. Now this finalization has
3009/// been created we can fix the branch.
3010static void
3012 llvm::OpenMPIRBuilder &ompBuilder,
3013 llvm::BasicBlock *afterBB) {
3014 ompBuilder.popFinalizationCB();
3015 llvm::BasicBlock *constructFini = afterBB->getSinglePredecessor();
3016 for (llvm::UncondBrInst *cancelBranch : cancelTerminators)
3017 cancelBranch->setSuccessor(constructFini);
3018}
3019
3020namespace {
3021/// TaskContextStructManager takes care of creating and freeing a structure
3022/// containing information needed by the task body to execute.
3023class TaskContextStructManager {
3024public:
3025 TaskContextStructManager(llvm::IRBuilderBase &builder,
3026 LLVM::ModuleTranslation &moduleTranslation,
3027 const PrivateVarsInfo &privateVarsInfo)
3028 : builder{builder}, moduleTranslation{moduleTranslation},
3029 privateVarsInfo{privateVarsInfo} {}
3030
3031 /// Creates a heap allocated struct containing space for each private
3032 /// variable. Invariant: privateVarTypes, privateVarsInfo.vars, and the
3033 /// elements of the structure should all have the same order (although
3034 /// privatizers which do not read from the mold argument are skipped).
3035 void generateTaskContextStruct();
3036
3037 /// Create GEPs to access each member of the structure representing a private
3038 /// variable, adding them to llvmPrivateVars. Null values are added where
3039 /// private decls were skipped so that the ordering continues to match the
3040 /// private decls.
3041 void createGEPsToPrivateVars();
3042
3043 /// Given the address of the structure, return a GEP for each private variable
3044 /// in the structure. Null values are added where private decls were skipped
3045 /// so that the ordering continues to match the private decls.
3046 /// Must be called after generateTaskContextStruct().
3047 SmallVector<llvm::Value *>
3048 createGEPsToPrivateVars(llvm::Value *altStructPtr) const;
3049
3050 /// De-allocate the task context structure.
3051 void freeStructPtr();
3052
3053 MutableArrayRef<llvm::Value *> getLLVMPrivateVarGEPs() {
3054 return llvmPrivateVarGEPs;
3055 }
3056
3057 llvm::Value *getStructPtr() { return structPtr; }
3058
3059private:
3060 llvm::IRBuilderBase &builder;
3061 LLVM::ModuleTranslation &moduleTranslation;
3062 const PrivateVarsInfo &privateVarsInfo;
3063
3064 /// The type of each member of the structure, in order.
3065 SmallVector<llvm::Type *> privateVarTypes;
3066
3067 /// LLVM values for each private variable, or null if that private variable is
3068 /// not included in the task context structure
3069 SmallVector<llvm::Value *> llvmPrivateVarGEPs;
3070
3071 /// A pointer to the structure containing context for this task.
3072 llvm::Value *structPtr = nullptr;
3073 /// The type of the structure
3074 llvm::Type *structTy = nullptr;
3075};
3076
3077/// IteratorInfo extracts and prepares loop bounds information from an
3078/// mlir::omp::IteratorOp for lowering to LLVM IR.
3079///
3080/// It computes the per-dimension trip counts and the total linearized trip
3081/// count as i64. Bounds and steps keep their declared type so that the
3082/// physical induction variables can be reconstructed in that type inside the
3083/// loop body.
3084class IteratorInfo {
3085private:
3086 llvm::SmallVector<llvm::Value *> lowerBounds;
3087 llvm::SmallVector<llvm::Value *> upperBounds;
3088 llvm::SmallVector<llvm::Value *> steps;
3089 llvm::SmallVector<llvm::Value *> trips;
3090 unsigned dims;
3091 llvm::Value *totalTrips;
3092
3093public:
3094 IteratorInfo(mlir::omp::IteratorOp itersOp,
3095 mlir::LLVM::ModuleTranslation &moduleTranslation,
3096 llvm::IRBuilderBase &builder) {
3097 dims = itersOp.getLoopLowerBounds().size();
3098 lowerBounds.resize(dims);
3099 upperBounds.resize(dims);
3100 steps.resize(dims);
3101 trips.resize(dims);
3102
3103 for (unsigned d = 0; d < dims; ++d) {
3104 llvm::Value *lb =
3105 moduleTranslation.lookupValue(itersOp.getLoopLowerBounds()[d]);
3106 llvm::Value *ub =
3107 moduleTranslation.lookupValue(itersOp.getLoopUpperBounds()[d]);
3108 llvm::Value *st =
3109 moduleTranslation.lookupValue(itersOp.getLoopSteps()[d]);
3110 assert(lb && ub && st &&
3111 "Expect lowerBounds, upperBounds, and steps in IteratorOp");
3112 assert(lb->getType() == ub->getType() && lb->getType() == st->getType() &&
3113 "Expect matching iterator range types");
3114 assert((!llvm::isa<llvm::ConstantInt>(st) ||
3115 !llvm::cast<llvm::ConstantInt>(st)->isZero()) &&
3116 "Expect non-zero step in IteratorOp");
3117
3118 lowerBounds[d] = lb;
3119 upperBounds[d] = ub;
3120 steps[d] = st;
3121
3122 // Use a direction-aware count so an empty range contributes no entries.
3123 // Widen by one bit so the span between the bounds cannot overflow.
3124 llvm::Type *countTy =
3125 builder.getIntNTy(lb->getType()->getIntegerBitWidth() + 1);
3126 llvm::Value *start = builder.CreateSExt(lb, countTy);
3127 llvm::Value *stop = builder.CreateSExt(ub, countTy);
3128 llvm::Value *step = builder.CreateSExt(st, countTy);
3129 llvm::Value *count =
3130 getOpenMPBuilder(moduleTranslation)
3131 ->calculateCanonicalLoopTripCount(
3132 builder, start, stop, step,
3133 /*IsSigned=*/true, itersOp.getLoopInclusive(), "iterator");
3134 trips[d] = builder.CreateZExtOrTrunc(count, builder.getInt64Ty());
3135 }
3136
3137 totalTrips = llvm::ConstantInt::get(builder.getInt64Ty(), 1);
3138 for (unsigned d = 0; d < dims; ++d)
3139 totalTrips = builder.CreateMul(totalTrips, trips[d]);
3140 }
3141
3142 unsigned getDims() const { return dims; }
3143 llvm::ArrayRef<llvm::Value *> getLowerBounds() const { return lowerBounds; }
3144 llvm::ArrayRef<llvm::Value *> getUpperBounds() const { return upperBounds; }
3145 llvm::ArrayRef<llvm::Value *> getSteps() const { return steps; }
3146 llvm::ArrayRef<llvm::Value *> getTrips() const { return trips; }
3147 llvm::Value *getTotalTrips() const { return totalTrips; }
3148};
3149} // namespace
3150
3151void TaskContextStructManager::generateTaskContextStruct() {
3152 if (privateVarsInfo.vars.empty())
3153 return;
3154 privateVarTypes.reserve(privateVarsInfo.vars.size());
3155
3156 for (const PrivateVarsInfo::VarInfo &var : privateVarsInfo.vars) {
3157 omp::PrivateClauseOp privOp = var.privatizer;
3158 // Skip private variables which can safely be allocated and initialised
3159 // inside of the task
3160 if (!privOp.readsFromMold())
3161 continue;
3162 Type mlirType = privOp.getType();
3163 privateVarTypes.push_back(moduleTranslation.convertType(mlirType));
3164 }
3165
3166 if (privateVarTypes.empty())
3167 return;
3168
3169 structTy = llvm::StructType::get(moduleTranslation.getLLVMContext(),
3170 privateVarTypes);
3171
3172 llvm::DataLayout dataLayout = builder.getDataLayout();
3173 llvm::Type *intPtrTy = builder.getIntPtrTy(dataLayout);
3174 llvm::Value *allocSize =
3175 builder.CreateTypeSize(intPtrTy, dataLayout.getTypeAllocSize(structTy));
3176
3177 // Heap allocate the structure
3178 structPtr = builder.CreateMalloc(intPtrTy, allocSize,
3179 /*ArraySize=*/nullptr, /*MallocF=*/nullptr,
3180 "omp.task.context_ptr");
3181}
3182
3183SmallVector<llvm::Value *> TaskContextStructManager::createGEPsToPrivateVars(
3184 llvm::Value *altStructPtr) const {
3185 SmallVector<llvm::Value *> ret;
3186
3187 // Create GEPs for each struct member
3188 ret.reserve(privateVarsInfo.vars.size());
3189 llvm::Value *zero = builder.getInt32(0);
3190 unsigned i = 0;
3191 for (const PrivateVarsInfo::VarInfo &var : privateVarsInfo.vars) {
3192 omp::PrivateClauseOp privDecl = var.privatizer;
3193 if (!privDecl.readsFromMold()) {
3194 // Handle this inside of the task so we don't pass unnessecary vars in
3195 ret.push_back(nullptr);
3196 continue;
3197 }
3198 llvm::Value *iVal = builder.getInt32(i);
3199 llvm::Value *gep = builder.CreateGEP(structTy, altStructPtr, {zero, iVal});
3200 ret.push_back(gep);
3201 i += 1;
3202 }
3203 return ret;
3204}
3205
3206void TaskContextStructManager::createGEPsToPrivateVars() {
3207 if (!structPtr)
3208 assert(privateVarTypes.empty());
3209 // Still need to run createGEPsToPrivateVars to populate llvmPrivateVarGEPs
3210 // with null values for skipped private decls
3211
3212 llvmPrivateVarGEPs = createGEPsToPrivateVars(structPtr);
3213}
3214
3215void TaskContextStructManager::freeStructPtr() {
3216 if (!structPtr)
3217 return;
3218
3219 llvm::IRBuilderBase::InsertPointGuard guard{builder};
3220 // Ensure we don't put the call to free() after the terminator
3221 builder.SetInsertPoint(builder.GetInsertBlock()->getTerminator());
3222 builder.CreateFree(structPtr);
3223}
3224
3225static void storeAffinityEntry(llvm::IRBuilderBase &builder,
3226 llvm::OpenMPIRBuilder &ompBuilder,
3227 llvm::Value *affinityList, llvm::Value *index,
3228 llvm::Value *addr, llvm::Value *len) {
3229 llvm::StructType *kmpTaskAffinityInfoTy =
3230 ompBuilder.getKmpTaskAffinityInfoTy();
3231 llvm::Value *entry = builder.CreateInBoundsGEP(
3232 kmpTaskAffinityInfoTy, affinityList, index, "omp.affinity.entry");
3233
3234 addr = builder.CreatePtrToInt(addr, kmpTaskAffinityInfoTy->getElementType(0));
3235 len = builder.CreateIntCast(len, kmpTaskAffinityInfoTy->getElementType(1),
3236 /*isSigned=*/false);
3237 llvm::Value *flags = builder.getInt32(0);
3238
3239 builder.CreateStore(addr,
3240 builder.CreateStructGEP(kmpTaskAffinityInfoTy, entry, 0));
3241 builder.CreateStore(len,
3242 builder.CreateStructGEP(kmpTaskAffinityInfoTy, entry, 1));
3243 builder.CreateStore(flags,
3244 builder.CreateStructGEP(kmpTaskAffinityInfoTy, entry, 2));
3245}
3246
3248 llvm::IRBuilderBase &builder,
3249 LLVM::ModuleTranslation &moduleTranslation,
3250 llvm::Value *affinityList) {
3251 for (auto [i, affinityVar] : llvm::enumerate(affinityVars)) {
3252 auto entryOp = affinityVar.getDefiningOp<mlir::omp::AffinityEntryOp>();
3253 assert(entryOp && "affinity item must be omp.affinity_entry");
3254
3255 llvm::Value *addr = moduleTranslation.lookupValue(entryOp.getAddr());
3256 llvm::Value *len = moduleTranslation.lookupValue(entryOp.getLen());
3257 assert(addr && len && "expect affinity addr and len to be non-null");
3258 storeAffinityEntry(builder, *getOpenMPBuilder(moduleTranslation),
3259 affinityList, builder.getInt64(i), addr, len);
3260 }
3261}
3262
3263static mlir::LogicalResult convertIteratorRegion(
3264 llvm::Value *linearIV, IteratorInfo &iterInfo, mlir::Region &iteratorRegion,
3265 llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation) {
3266 mlir::Block &entryBlock = iteratorRegion.front();
3267 llvm::Value *tmp = linearIV;
3268 for (int d = (int)iterInfo.getDims() - 1; d >= 0; --d) {
3269 llvm::Value *trip = iterInfo.getTrips()[d];
3270 llvm::Value *zero = llvm::ConstantInt::get(trip->getType(), 0);
3271 llvm::Value *one = llvm::ConstantInt::get(trip->getType(), 1);
3272 // A zero trip count makes the linearized loop empty. Use one in its
3273 // unreachable IV decoder so the generated IR contains no division by zero.
3274 llvm::Value *divisor =
3275 builder.CreateSelect(builder.CreateICmpEQ(trip, zero), one, trip);
3276 // idx_d = tmp % divisor_d
3277 llvm::Value *idx = builder.CreateURem(tmp, divisor);
3278 // tmp = tmp / divisor_d
3279 tmp = builder.CreateUDiv(tmp, divisor);
3280
3281 // physIV_d = lb_d + idx_d * step_d
3282 idx =
3283 builder.CreateZExtOrTrunc(idx, iterInfo.getLowerBounds()[d]->getType());
3284 llvm::Value *physIV = builder.CreateAdd(
3285 iterInfo.getLowerBounds()[d],
3286 builder.CreateMul(idx, iterInfo.getSteps()[d]), "omp.it.phys_iv");
3287
3288 moduleTranslation.mapValue(entryBlock.getArgument(d), physIV);
3289 }
3290
3291 // Translate the iterator region into the loop body.
3292 if (iteratorRegion.hasOneBlock()) {
3293 moduleTranslation.mapBlock(&entryBlock, builder.GetInsertBlock());
3294 return moduleTranslation.convertBlock(entryBlock, /*ignoreArguments=*/true,
3295 builder);
3296 }
3297
3298 // Unlike convertOmpOpRegions, do not forward the yielded value through a PHI:
3299 // it may have no LLVM type (e.g. `!omp.affinity_entry_ty`). The unique
3300 // `omp.yield` block is the continuation's only predecessor, so callers can
3301 // look up the yielded value directly.
3302 llvm::BasicBlock *continuation =
3303 splitBB(builder, true, "omp.iterator.region.cont");
3304 llvm::Instruction *sourceBranch = builder.GetInsertBlock()->getTerminator();
3305 for (mlir::Block &block : iteratorRegion)
3306 moduleTranslation.mapBlock(
3307 &block,
3308 llvm::BasicBlock::Create(builder.getContext(), "omp.iterator.region",
3309 continuation->getParent(), continuation));
3310 sourceBranch->setSuccessor(0, moduleTranslation.lookupBlock(&entryBlock));
3311
3312 for (mlir::Block *block : getBlocksSortedByDominance(iteratorRegion)) {
3313 llvm::IRBuilderBase::InsertPointGuard guard(builder);
3314 if (failed(moduleTranslation.convertBlock(*block, block->isEntryBlock(),
3315 builder)))
3316 return mlir::failure();
3317 if (isa<omp::YieldOp>(block->getTerminator()))
3318 builder.CreateBr(continuation);
3319 }
3320 LLVM::detail::connectPHINodes(iteratorRegion, moduleTranslation);
3321
3322 builder.SetInsertPoint(continuation);
3323 return mlir::success();
3324}
3325
3327 llvm::function_ref<void(llvm::Value *linearIV, mlir::omp::YieldOp yield)>;
3328
3329static mlir::LogicalResult
3330fillIteratorLoop(mlir::omp::IteratorOp itersOp, llvm::IRBuilderBase &builder,
3331 mlir::LLVM::ModuleTranslation &moduleTranslation,
3332 IteratorInfo &iterInfo, llvm::StringRef loopName,
3333 IteratorStoreEntryTy genStoreEntry) {
3334 mlir::Region &itersRegion = itersOp.getRegion();
3335
3336 llvm::OpenMPIRBuilder::LocationDescription loc(builder);
3337
3338 auto bodyGen = [&](llvm::OpenMPIRBuilder::InsertPointTy bodyIP,
3339 llvm::Value *linearIV) -> llvm::Error {
3340 llvm::IRBuilderBase::InsertPointGuard guard(builder);
3341 builder.restoreIP(bodyIP);
3342
3343 if (failed(convertIteratorRegion(linearIV, iterInfo, itersRegion, builder,
3344 moduleTranslation))) {
3345 return llvm::make_error<llvm::StringError>(
3346 "failed to convert iterator region", llvm::inconvertibleErrorCode());
3347 }
3348
3349 mlir::omp::YieldOp yield = itersOp.getYieldOp();
3350 assert(yield && yield.getResults().size() == 1 &&
3351 "expect omp.yield in iterator region to have one result");
3352
3353 genStoreEntry(linearIV, yield);
3354
3355 // Iterator-region block/value mappings are temporary for this conversion,
3356 // clear them to avoid stale entries in ModuleTranslation.
3357 moduleTranslation.forgetMapping(itersRegion);
3358
3359 return llvm::Error::success();
3360 };
3361
3362 llvm::OpenMPIRBuilder::InsertPointOrErrorTy afterIP =
3363 getOpenMPBuilder(moduleTranslation)
3364 ->createIteratorLoop(loc, iterInfo.getTotalTrips(), bodyGen,
3365 loopName);
3366 if (failed(handleError(afterIP, *itersOp)))
3367 return failure();
3368
3369 builder.restoreIP(*afterIP);
3370
3371 return mlir::success();
3372}
3373
3374static mlir::LogicalResult
3375buildAffinityData(mlir::omp::TaskOp &taskOp, llvm::IRBuilderBase &builder,
3376 mlir::LLVM::ModuleTranslation &moduleTranslation,
3377 llvm::OpenMPIRBuilder::AffinityData &ad) {
3378
3379 if (taskOp.getAffinityVars().empty() && taskOp.getIterated().empty()) {
3380 ad.Count = nullptr;
3381 ad.Info = nullptr;
3382 return mlir::success();
3383 }
3384
3386 llvm::StructType *kmpTaskAffinityInfoTy =
3387 getOpenMPBuilder(moduleTranslation)->getKmpTaskAffinityInfoTy();
3388
3389 auto allocateAffinityList = [&](llvm::Value *count) -> llvm::Value * {
3390 llvm::IRBuilderBase::InsertPointGuard guard(builder);
3391 if (llvm::isa<llvm::Constant>(count) || llvm::isa<llvm::Argument>(count))
3392 builder.restoreIP(findAllocInsertPoints(builder, moduleTranslation));
3393 return builder.CreateAlloca(kmpTaskAffinityInfoTy, count,
3394 "omp.affinity_list");
3395 };
3396
3397 auto createAffinity =
3398 [&](llvm::Value *count,
3399 llvm::Value *info) -> llvm::OpenMPIRBuilder::AffinityData {
3400 llvm::OpenMPIRBuilder::AffinityData ad{};
3401 ad.Count = builder.CreateTrunc(count, builder.getInt32Ty());
3402 ad.Info =
3403 builder.CreatePointerBitCastOrAddrSpaceCast(info, builder.getPtrTy(0));
3404 return ad;
3405 };
3406
3407 if (!taskOp.getAffinityVars().empty()) {
3408 llvm::Value *count = llvm::ConstantInt::get(
3409 builder.getInt64Ty(), taskOp.getAffinityVars().size());
3410 llvm::Value *list = allocateAffinityList(count);
3411 fillAffinityLocators(taskOp.getAffinityVars(), builder, moduleTranslation,
3412 list);
3413 ads.emplace_back(createAffinity(count, list));
3414 }
3415
3416 if (!taskOp.getIterated().empty()) {
3417 for (auto [i, iter] : llvm::enumerate(taskOp.getIterated())) {
3418 auto itersOp = iter.getDefiningOp<omp::IteratorOp>();
3419 assert(itersOp && "iterated value must be defined by omp.iterator");
3420 IteratorInfo iterInfo(itersOp, moduleTranslation, builder);
3421 llvm::Value *affList = allocateAffinityList(iterInfo.getTotalTrips());
3422 if (failed(fillIteratorLoop(
3423 itersOp, builder, moduleTranslation, iterInfo, "iterator",
3424 [&](llvm::Value *linearIV, mlir::omp::YieldOp yield) {
3425 auto entryOp = yield.getResults()[0]
3426 .getDefiningOp<mlir::omp::AffinityEntryOp>();
3427 assert(entryOp && "expect yield produce an affinity entry");
3428 llvm::Value *addr =
3429 moduleTranslation.lookupValue(entryOp.getAddr());
3430 llvm::Value *len =
3431 moduleTranslation.lookupValue(entryOp.getLen());
3432 storeAffinityEntry(builder,
3433 *getOpenMPBuilder(moduleTranslation),
3434 affList, linearIV, addr, len);
3435 })))
3436 return llvm::failure();
3437 ads.emplace_back(createAffinity(iterInfo.getTotalTrips(), affList));
3438 }
3439 }
3440
3441 llvm::Value *totalAffinityCount = builder.getInt32(0);
3442 for (const auto &affinity : ads)
3443 totalAffinityCount = builder.CreateAdd(
3444 totalAffinityCount,
3445 builder.CreateIntCast(affinity.Count, builder.getInt32Ty(),
3446 /*isSigned=*/false));
3447
3448 llvm::Value *affinityInfo = ads.front().Info;
3449 if (ads.size() > 1) {
3450 llvm::StructType *kmpTaskAffinityInfoTy =
3451 getOpenMPBuilder(moduleTranslation)->getKmpTaskAffinityInfoTy();
3452 llvm::Value *affinityInfoElemSize = builder.getInt64(
3453 moduleTranslation.getLLVMModule()->getDataLayout().getTypeAllocSize(
3454 kmpTaskAffinityInfoTy));
3455
3456 llvm::Value *packedAffinityInfo = allocateAffinityList(totalAffinityCount);
3457 llvm::Value *packedAffinityInfoOffset = builder.getInt32(0);
3458 for (const auto &affinity : ads) {
3459 llvm::Value *affinityCount = builder.CreateIntCast(
3460 affinity.Count, builder.getInt32Ty(), /*isSigned=*/false);
3461 llvm::Value *affinityCountInt64 = builder.CreateIntCast(
3462 affinityCount, builder.getInt64Ty(), /*isSigned=*/false);
3463 llvm::Value *affinityInfoSize =
3464 builder.CreateMul(affinityCountInt64, affinityInfoElemSize);
3465
3466 llvm::Value *packedAffinityInfoIndex = builder.CreateIntCast(
3467 packedAffinityInfoOffset, kmpTaskAffinityInfoTy->getElementType(0),
3468 /*isSigned=*/false);
3469 packedAffinityInfoIndex = builder.CreateInBoundsGEP(
3470 kmpTaskAffinityInfoTy, packedAffinityInfo, packedAffinityInfoIndex);
3471
3472 builder.CreateMemCpy(
3473 packedAffinityInfoIndex, llvm::Align(1),
3474 builder.CreatePointerBitCastOrAddrSpaceCast(
3475 affinity.Info, builder.getPtrTy(packedAffinityInfoIndex->getType()
3476 ->getPointerAddressSpace())),
3477 llvm::Align(1), affinityInfoSize);
3478
3479 packedAffinityInfoOffset =
3480 builder.CreateAdd(packedAffinityInfoOffset, affinityCount);
3481 }
3482
3483 affinityInfo = packedAffinityInfo;
3484 }
3485
3486 ad.Count = totalAffinityCount;
3487 ad.Info = affinityInfo;
3488
3489 return mlir::success();
3490}
3491
3492// Allocates a single kmp_dep_info array sized to hold both locator
3493// (non-iterated) and iterated entries, fills the locator entries first, then
3494// runs an iterator loop for each iterator modifier object.
3495static mlir::LogicalResult
3496buildDependData(OperandRange dependVars, std::optional<ArrayAttr> dependKinds,
3497 OperandRange dependIterated,
3498 std::optional<ArrayAttr> dependIteratedKinds,
3499 llvm::IRBuilderBase &builder,
3500 mlir::LLVM::ModuleTranslation &moduleTranslation,
3501 llvm::OpenMPIRBuilder::DependenciesInfo &taskDeps) {
3502 if (dependIterated.empty()) {
3503 buildDependDataLocator(dependKinds, dependVars, moduleTranslation,
3504 taskDeps.Deps);
3505 return mlir::success();
3506 }
3507
3508 llvm::OpenMPIRBuilder &ompBuilder = *getOpenMPBuilder(moduleTranslation);
3509 llvm::Type *dependInfoTy = ompBuilder.DependInfo;
3510 unsigned numLocator = dependVars.size();
3511
3512 // Compute total count: locator deps + sum of iterator trip counts.
3513 llvm::Value *totalCount =
3514 llvm::ConstantInt::get(builder.getInt64Ty(), numLocator);
3515
3517 for (auto iter : dependIterated) {
3518 auto itersOp = iter.getDefiningOp<mlir::omp::IteratorOp>();
3519 assert(itersOp && "depend_iterated value must be defined by omp.iterator");
3520 iterInfos.emplace_back(itersOp, moduleTranslation, builder);
3521 totalCount =
3522 builder.CreateAdd(totalCount, iterInfos.back().getTotalTrips());
3523 }
3524
3525 // Heap-allocate the kmp_depend_info array so we don't risk
3526 // dynamic-sized alloca outside the entry block (e.g. inside loops).
3527 llvm::DataLayout dataLayout = builder.getDataLayout();
3528 llvm::Value *allocSize = builder.CreateTypeSize(
3529 ompBuilder.SizeTy, dataLayout.getTypeAllocSize(dependInfoTy));
3530 llvm::Value *depArray =
3531 builder.CreateMalloc(ompBuilder.SizeTy, allocSize, totalCount,
3532 /*MallocF=*/nullptr, ".dep.arr.addr");
3533
3534 // Fill non-iterated entries at indices [0, numLocator).
3535 if (numLocator > 0) {
3537 buildDependDataLocator(dependKinds, dependVars, moduleTranslation, dds);
3538 for (auto [i, dd] : llvm::enumerate(dds)) {
3539 llvm::Value *idx = llvm::ConstantInt::get(builder.getInt64Ty(), i);
3540 llvm::Value *entry =
3541 builder.CreateInBoundsGEP(dependInfoTy, depArray, idx);
3542 ompBuilder.emitTaskDependency(builder, entry, dd);
3543 }
3544 }
3545
3546 // Fill iterated entries starting at index numLocator.
3547 llvm::Value *offset =
3548 llvm::ConstantInt::get(builder.getInt64Ty(), numLocator);
3549 for (auto [i, iterInfo] : llvm::enumerate(iterInfos)) {
3550 auto kindAttr = cast<mlir::omp::ClauseTaskDependAttr>(
3551 dependIteratedKinds->getValue()[i]);
3552 llvm::omp::RTLDependenceKindTy rtlKind =
3553 convertDependKind(kindAttr.getValue());
3554
3555 auto itersOp = dependIterated[i].getDefiningOp<mlir::omp::IteratorOp>();
3556 if (failed(fillIteratorLoop(
3557 itersOp, builder, moduleTranslation, iterInfo, "dep_iterator",
3558 [&](llvm::Value *linearIV, mlir::omp::YieldOp yield) {
3559 llvm::Value *addr =
3560 moduleTranslation.lookupValue(yield.getResults()[0]);
3561 llvm::Value *idx = builder.CreateAdd(offset, linearIV);
3562 llvm::Value *entry =
3563 builder.CreateInBoundsGEP(dependInfoTy, depArray, idx);
3564 ompBuilder.emitTaskDependency(
3565 builder, entry,
3566 llvm::OpenMPIRBuilder::DependData{rtlKind, addr->getType(),
3567 addr});
3568 })))
3569 return mlir::failure();
3570
3571 // Advance offset by the trip count of this iterator.
3572 offset = builder.CreateAdd(offset, iterInfo.getTotalTrips());
3573 }
3574
3575 taskDeps.DepArray = depArray;
3576 taskDeps.NumDeps = builder.CreateTrunc(totalCount, builder.getInt32Ty());
3577 return mlir::success();
3578}
3579
3580/// Converts an OpenMP task construct into LLVM IR using OpenMPIRBuilder.
3581static LogicalResult
3582convertOmpTaskOp(omp::TaskOp taskOp, llvm::IRBuilderBase &builder,
3583 LLVM::ModuleTranslation &moduleTranslation) {
3584 using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy;
3585 if (failed(checkImplementationStatus(*taskOp)))
3586 return failure();
3587
3588 PrivateVarsInfo privateVarsInfo(taskOp);
3589 TaskContextStructManager taskStructMgr{builder, moduleTranslation,
3590 privateVarsInfo};
3591
3592 // Allocate and copy private variables before creating the task. This avoids
3593 // accessing invalid memory if (after this scope ends) the private variables
3594 // are initialized from host variables or if the variables are copied into
3595 // from host variables (firstprivate). The insertion point is just before
3596 // where the code for creating and scheduling the task will go. That puts this
3597 // code outside of the outlined task region, which is what we want because
3598 // this way the initialization and copy regions are executed immediately while
3599 // the host variable data are still live.
3601 InsertPointTy allocaIP =
3602 findAllocInsertPoints(builder, moduleTranslation, &deallocBlocks);
3603
3604 // Not using splitBB() because that requires the current block to have a
3605 // terminator.
3606 assert(builder.GetInsertPoint() == builder.GetInsertBlock()->end());
3607 llvm::BasicBlock *taskStartBlock = llvm::BasicBlock::Create(
3608 builder.getContext(), "omp.task.start",
3609 /*Parent=*/builder.GetInsertBlock()->getParent());
3610 llvm::Instruction *branchToTaskStartBlock = builder.CreateBr(taskStartBlock);
3611 builder.SetInsertPoint(branchToTaskStartBlock);
3612
3613 // Now do this again to make the initialization and copy blocks
3614 llvm::BasicBlock *copyBlock =
3615 splitBB(builder, /*CreateBranch=*/true, "omp.private.copy");
3616 llvm::BasicBlock *initBlock =
3617 splitBB(builder, /*CreateBranch=*/true, "omp.private.init");
3618
3619 // Now the control flow graph should look like
3620 // starter_block:
3621 // <---- where we started when convertOmpTaskOp was called
3622 // br %omp.private.init
3623 // omp.private.init:
3624 // br %omp.private.copy
3625 // omp.private.copy:
3626 // br %omp.task.start
3627 // omp.task.start:
3628 // <---- where we want the insertion point to be when we call createTask()
3629
3630 // Save the alloca insertion point on ModuleTranslation stack for use in
3631 // nested regions.
3633 moduleTranslation, allocaIP.getNodeParent(), deallocBlocks);
3634
3635 // Allocate and initialize private variables
3636 builder.SetInsertPoint(initBlock->getTerminator());
3637
3638 // Create task variable structure
3639 taskStructMgr.generateTaskContextStruct();
3640 // GEPs so that we can initialize the variables. Don't use these GEPs inside
3641 // of the body otherwise it will be the GEP not the struct which is fowarded
3642 // to the outlined function. GEPs forwarded in this way are passed in a
3643 // stack-allocated (by OpenMPIRBuilder) structure which is not safe for tasks
3644 // which may not be executed until after the current stack frame goes out of
3645 // scope.
3646 taskStructMgr.createGEPsToPrivateVars();
3647
3648 for (auto [var, llvmPrivateVarAlloc] : llvm::zip_equal(
3649 privateVarsInfo.vars, taskStructMgr.getLLVMPrivateVarGEPs())) {
3650 // To be handled inside the task.
3651 if (!var.privatizer.readsFromMold())
3652 continue;
3653 assert(llvmPrivateVarAlloc &&
3654 "reads from mold so shouldn't have been skipped");
3655
3656 llvm::Expected<llvm::Value *> privateVarOrErr =
3657 initPrivateVar(builder, moduleTranslation, var.privatizer, var.mlirVar,
3658 var.blockArg, llvmPrivateVarAlloc, initBlock);
3659 if (!privateVarOrErr)
3660 return handleError(privateVarOrErr, *taskOp.getOperation());
3661
3663
3664 // TODO: this is a bit of a hack for Fortran character boxes.
3665 // Character boxes are passed by value into the init region and then the
3666 // initialized character box is yielded by value. Here we need to store the
3667 // yielded value into the private allocation, and load the private
3668 // allocation to match the type expected by region block arguments.
3669 [[maybe_unused]] llvm::Value *llvmPrivateVar = llvmPrivateVarAlloc;
3670 if ((privateVarOrErr.get() != llvmPrivateVarAlloc) &&
3671 !mlir::isa<LLVM::LLVMPointerType>(var.blockArg.getType())) {
3672 builder.CreateStore(privateVarOrErr.get(), llvmPrivateVarAlloc);
3673 // Load it so we have the value pointed to by the GEP
3674 llvmPrivateVar = builder.CreateLoad(privateVarOrErr.get()->getType(),
3675 llvmPrivateVarAlloc);
3676 }
3677 assert(llvmPrivateVar->getType() ==
3678 moduleTranslation.convertType(var.blockArg.getType()));
3679
3680 // Mapping blockArg -> llvmPrivateVarAlloc is done inside the body callback
3681 // so that OpenMPIRBuilder doesn't try to pass each GEP address through a
3682 // stack allocated structure.
3683 }
3684
3685 // firstprivate copy region
3686 setInsertPointForPossiblyEmptyBlock(builder, copyBlock);
3687 if (failed(completePrivateVars(
3688 taskOp, builder, moduleTranslation, privateVarsInfo,
3689 taskOp.getPrivateNeedsBarrier(),
3690 /*moldVars=*/{}, taskStructMgr.getLLVMPrivateVarGEPs())))
3691 return llvm::failure();
3692
3693 llvm::OpenMPIRBuilder::AffinityData ad;
3694 if (failed(buildAffinityData(taskOp, builder, moduleTranslation, ad)))
3695 return llvm::failure();
3696
3697 // Resolve and validate in_reduction declarations. Byref in_reduction has
3698 // already been rejected by checkImplementationStatus; the helper rejects the
3699 // remaining richer declare_reduction shapes (two-argument initializer,
3700 // cleanup region, missing combiner). This is pure MLIR symbol-table work and
3701 // emits no IR. The matching task_reduction descriptor is registered by an
3702 // enclosing taskgroup; here we only look the per-task storage up at runtime.
3705 taskOp.getOperation(), taskOp.getInReductionSyms(), "omp.task",
3706 "in_reduction", inRedDecls)))
3707 return failure();
3708 SmallVector<llvm::Value *> inRedOrigPtrs;
3709 inRedOrigPtrs.reserve(inRedDecls.size());
3710 for (Value v : taskOp.getInReductionVars())
3711 inRedOrigPtrs.push_back(moduleTranslation.lookupValue(v));
3712
3713 // Set up for call to createTask()
3714 builder.SetInsertPoint(taskStartBlock);
3715
3716 auto bodyCB =
3717 [&](InsertPointTy allocaIP, InsertPointTy codegenIP,
3718 llvm::ArrayRef<llvm::BasicBlock *> deallocBlocks) -> llvm::Error {
3719 // Save the alloca insertion point on ModuleTranslation stack for use in
3720 // nested regions.
3722 moduleTranslation, allocaIP.getNodeParent(), deallocBlocks);
3723
3724 // translate the body of the task:
3725 builder.restoreIP(codegenIP);
3726
3727 llvm::BasicBlock *privInitBlock = nullptr;
3728 for (PrivateVarsInfo::VarInfo &var : privateVarsInfo.vars) {
3729 // This is handled before the task executes
3730 if (var.privatizer.readsFromMold())
3731 continue;
3732
3733 llvm::IRBuilderBase::InsertPointGuard guard(builder);
3734 llvm::Type *llvmAllocType =
3735 moduleTranslation.convertType(var.privatizer.getType());
3736 builder.SetInsertPoint(allocaIP.getNodeParent()->getTerminator());
3737 llvm::Value *llvmPrivateVar = builder.CreateAlloca(
3738 llvmAllocType, /*ArraySize=*/nullptr, "omp.private.alloc");
3739
3741 builder, moduleTranslation, var.privatizer, var.mlirVar, var.blockArg,
3742 llvmPrivateVar, privInitBlock);
3743 if (!privateVarOrError)
3744 return privateVarOrError.takeError();
3745 moduleTranslation.mapValue(var.blockArg, privateVarOrError.get());
3746 var.llvmVar = privateVarOrError.get();
3747 }
3748
3749 taskStructMgr.createGEPsToPrivateVars();
3750 for (auto [i, llvmPrivVar] :
3751 llvm::enumerate(taskStructMgr.getLLVMPrivateVarGEPs())) {
3752 if (!llvmPrivVar) {
3753 assert(privateVarsInfo.vars[i].llvmVar &&
3754 "This is added in the loop above");
3755 continue;
3756 }
3757 privateVarsInfo.vars[i].llvmVar = llvmPrivVar;
3758 }
3759
3760 // Find and map the addresses of each variable within the task context
3761 // structure
3762 for (PrivateVarsInfo::VarInfo &var : privateVarsInfo.vars) {
3763 // This was handled above.
3764 if (!var.privatizer.readsFromMold())
3765 continue;
3766 // Fix broken pass-by-value case for Fortran character boxes
3767 if (!mlir::isa<LLVM::LLVMPointerType>(var.blockArg.getType())) {
3768 var.llvmVar = builder.CreateLoad(
3769 moduleTranslation.convertType(var.blockArg.getType()), var.llvmVar);
3770 }
3771 assert(var.llvmVar->getType() ==
3772 moduleTranslation.convertType(var.blockArg.getType()));
3773 moduleTranslation.mapValue(var.blockArg, var.llvmVar);
3774 }
3775
3776 // Map in_reduction block arguments to the per-task private storage returned
3777 // by __kmpc_task_reduction_get_th_data. This call must be emitted inside
3778 // the to-be-outlined task body so that it returns the *executing* thread's
3779 // gtid (not the encountering thread's). The descriptor is NULL: the runtime
3780 // walks up enclosing taskgroups to find the matching task_reduction
3781 // registration for `origPtr`. The original pointers are auto-captured into
3782 // the task shareds aggregate by CodeExtractor during
3783 // OpenMPIRBuilder::finalize.
3784 if (!inRedDecls.empty()) {
3785 auto iface = cast<omp::BlockArgOpenMPOpInterface>(taskOp.getOperation());
3786 llvm::OpenMPIRBuilder &ompB = *getOpenMPBuilder(moduleTranslation);
3787 llvm::Module *m = moduleTranslation.getLLVMModule();
3788 llvm::LLVMContext &llvmCtx = m->getContext();
3789 llvm::OpenMPIRBuilder::LocationDescription bodyLoc(builder);
3790 uint32_t srcLocSize;
3791 llvm::Constant *srcLocStr =
3792 ompB.getOrCreateSrcLocStr(bodyLoc, srcLocSize);
3793 llvm::Value *bodyIdent = ompB.getOrCreateIdent(srcLocStr, srcLocSize);
3794 // Align OpenMPIRBuilder's internal IRBuilder with `builder` so the gtid
3795 // call lands inside the to-be-outlined task body.
3796 ompB.updateToLocation(bodyLoc);
3797 llvm::Value *bodyGtid = ompB.getOrCreateThreadID(bodyIdent);
3798 llvm::FunctionCallee getThData = ompB.getOrCreateRuntimeFunction(
3799 *m, llvm::omp::OMPRTL___kmpc_task_reduction_get_th_data);
3800 llvm::Type *ptrTy = llvm::PointerType::getUnqual(llvmCtx);
3801 llvm::Value *nullDesc = llvm::ConstantPointerNull::get(ptrTy);
3802 ArrayRef<BlockArgument> inRedBlockArgs = iface.getInReductionBlockArgs();
3803 for (auto [blockArg, origPtr] :
3804 llvm::zip_equal(inRedBlockArgs, inRedOrigPtrs)) {
3805 // __kmpc_task_reduction_get_th_data takes and returns a generic,
3806 // default-address-space `ptr`. Normalize a non-default-address-space
3807 // original pointer to the generic address space before the call, and
3808 // cast the returned private pointer back to the block argument's
3809 // address space when it differs (mirrors the taskloop reduction
3810 // remapping in convertOmpTaskloopContextOp).
3811 llvm::Value *lookupPtr = origPtr;
3812 if (auto *origPtrTy =
3813 llvm::dyn_cast<llvm::PointerType>(lookupPtr->getType());
3814 origPtrTy && origPtrTy->getAddressSpace() != 0)
3815 lookupPtr = builder.CreateAddrSpaceCast(lookupPtr, ptrTy);
3816 llvm::Value *priv = ompB.createRuntimeFunctionCall(
3817 getThData, {bodyGtid, nullDesc, lookupPtr}, "omp.inred.priv");
3818 if (auto *argPtrTy = llvm::dyn_cast<llvm::PointerType>(
3819 moduleTranslation.convertType(blockArg.getType()));
3820 argPtrTy && argPtrTy->getAddressSpace() != 0)
3821 priv = builder.CreateAddrSpaceCast(priv, argPtrTy);
3822 moduleTranslation.mapValue(blockArg, priv);
3823 }
3824 }
3825
3826 auto continuationBlockOrError = convertOmpOpRegions(
3827 taskOp.getRegion(), "omp.task.region", builder, moduleTranslation);
3828 if (failed(handleError(continuationBlockOrError, *taskOp)))
3829 return llvm::make_error<PreviouslyReportedError>();
3830
3831 builder.SetInsertPoint(continuationBlockOrError.get()->getTerminator());
3832
3833 if (failed(cleanupPrivateVars(taskOp, builder, moduleTranslation,
3834 taskOp.getLoc(), privateVarsInfo)))
3835 return llvm::make_error<PreviouslyReportedError>();
3836
3837 // Free heap allocated task context structure at the end of the task.
3838 taskStructMgr.freeStructPtr();
3839
3840 return llvm::Error::success();
3841 };
3842
3843 llvm::OpenMPIRBuilder &ompBuilder = *getOpenMPBuilder(moduleTranslation);
3844 SmallVector<llvm::UncondBrInst *> cancelTerminators;
3845 // The directive to match here is OMPD_taskgroup because it is the taskgroup
3846 // which is canceled. This is handled here because it is the task's cleanup
3847 // block which should be branched to.
3848 pushCancelFinalizationCB(cancelTerminators, builder, ompBuilder, taskOp,
3849 llvm::omp::Directive::OMPD_taskgroup);
3850
3851 llvm::OpenMPIRBuilder::DependenciesInfo dependencies;
3852 if (failed(buildDependData(taskOp.getDependVars(), taskOp.getDependKinds(),
3853 taskOp.getDependIterated(),
3854 taskOp.getDependIteratedKinds(), builder,
3855 moduleTranslation, dependencies)))
3856 return failure();
3857
3858 llvm::OpenMPIRBuilder::LocationDescription ompLoc(builder);
3859 llvm::OpenMPIRBuilder::InsertPointOrErrorTy afterIP =
3860 getOpenMPBuilder(moduleTranslation)
3861 ->createTask(ompLoc, allocaIP, deallocBlocks, bodyCB,
3862 !taskOp.getUntied(),
3863 moduleTranslation.lookupValue(taskOp.getFinal()),
3864 moduleTranslation.lookupValue(taskOp.getIfExpr()),
3865 dependencies, ad, taskOp.getMergeable(),
3866 moduleTranslation.lookupValue(taskOp.getEventHandle()),
3867 moduleTranslation.lookupValue(taskOp.getPriority()),
3868 taskOp.getThreadset() == omp::ThreadsetPolicy::omp_pool);
3869
3870 if (failed(handleError(afterIP, *taskOp)))
3871 return failure();
3872
3873 // Set the correct branch target for task cancellation
3874 popCancelFinalizationCB(cancelTerminators, ompBuilder,
3875 afterIP->getNodeParent());
3876
3877 builder.restoreIP(*afterIP);
3878
3879 if (dependencies.DepArray)
3880 builder.CreateFree(dependencies.DepArray);
3881
3882 return success();
3883}
3884
3885/// The correct entry point is convertOmpTaskloopContextOp. This gets called
3886/// whilst lowering the body of the taskloop context (i.e. the task function).
3887static LogicalResult
3888convertOmpTaskloopWrapperOp(omp::TaskloopWrapperOp loopWrapperOp,
3889 llvm::IRBuilderBase &builder,
3890 LLVM::ModuleTranslation &moduleTranslation) {
3891 mlir::Operation &opInst = *loopWrapperOp.getOperation();
3892 if (failed(checkImplementationStatus(opInst)))
3893 return failure();
3894
3895 // Recurse into the loop body.
3896 auto continuationBlockOrError = convertOmpOpRegions(
3897 loopWrapperOp.getRegion(), "omp.taskloop.wrapper.region", builder,
3898 moduleTranslation);
3899
3900 if (failed(handleError(continuationBlockOrError, opInst)))
3901 return failure();
3902
3903 builder.SetInsertPoint(continuationBlockOrError.get());
3904 return success();
3905}
3906
3907/// Look up the given value in the mapping, and if it's not there, translate its
3908/// defining operation at the current builder insertion point. Only pure,
3909/// regionless operations are supported because the same operation will later be
3910/// translated again when the taskloop body itself is lowered.
3911static llvm::Expected<llvm::Value *>
3913 LLVM::ModuleTranslation &moduleTranslation,
3914 llvm::IRBuilderBase &builder) {
3915 if (llvm::Value *mapped = moduleTranslation.lookupValue(value))
3916 return mapped;
3917
3918 Operation *defOp = value.getDefiningOp();
3919 if (!defOp)
3920 return llvm::make_error<llvm::StringError>(
3921 "value is a block argument and is not mapped",
3922 llvm::inconvertibleErrorCode());
3923 if (defOp->getNumRegions() != 0 || !isPure(defOp))
3924 return llvm::make_error<llvm::StringError>(
3925 "unsupported op defining taskloop loop bound",
3926 llvm::inconvertibleErrorCode());
3927
3928 SmallVector<Value> mappingsToRemove;
3929 mappingsToRemove.reserve(defOp->getNumOperands() + defOp->getNumResults());
3930 for (Value operand : defOp->getOperands()) {
3931 if (moduleTranslation.lookupValue(operand))
3932 continue;
3933
3934 llvm::Expected<llvm::Value *> operandOrError =
3935 lookupOrTranslatePureValue(operand, moduleTranslation, builder);
3936 if (!operandOrError)
3937 return operandOrError.takeError();
3938 moduleTranslation.mapValue(operand, *operandOrError);
3939 mappingsToRemove.push_back(operand);
3940 }
3941
3942 if (failed(moduleTranslation.convertOperation(*defOp, builder)))
3943 return llvm::make_error<llvm::StringError>(
3944 "failed to convert op defining taskloop loop bound",
3945 llvm::inconvertibleErrorCode());
3946
3947 llvm::Value *result = moduleTranslation.lookupValue(value);
3948 assert(result && "expected conversion of loop bound op to produce a value");
3949
3950 for (Value resultValue : defOp->getResults()) {
3951 if (moduleTranslation.lookupValue(resultValue))
3952 mappingsToRemove.push_back(resultValue);
3953 }
3954 for (Value mappedValue : mappingsToRemove)
3955 moduleTranslation.forgetMapping(mappedValue);
3956
3957 return result;
3958}
3959
3960static llvm::Error
3961computeTaskloopBounds(omp::LoopNestOp loopOp, llvm::IRBuilderBase &builder,
3962 LLVM::ModuleTranslation &moduleTranslation,
3963 llvm::Value *&lbVal, llvm::Value *&ubVal,
3964 llvm::Value *&stepVal) {
3965 Operation::operand_range lowerBounds = loopOp.getLoopLowerBounds();
3966 Operation::operand_range upperBounds = loopOp.getLoopUpperBounds();
3967 Operation::operand_range steps = loopOp.getLoopSteps();
3968
3969 llvm::Expected<llvm::Value *> firstLbOrErr =
3970 lookupOrTranslatePureValue(lowerBounds[0], moduleTranslation, builder);
3971 if (!firstLbOrErr)
3972 return firstLbOrErr.takeError();
3973
3974 llvm::Type *boundType = (*firstLbOrErr)->getType();
3975 ubVal = builder.getIntN(boundType->getIntegerBitWidth(), 1);
3976 if (loopOp.getCollapseNumLoops() > 1) {
3977 // In cases where Collapse is used with Taskloop, the upper bound of the
3978 // iteration space needs to be recalculated to cater for the collapsed loop.
3979 // The Collapsed Loop UpperBound is the product of all collapsed
3980 // loop's tripcount.
3981 // The LowerBound for collapsed loops is always 1. When the loops are
3982 // collapsed, it will reset the bounds and introduce processing to ensure
3983 // the index's are presented as expected. As this happens after creating
3984 // Taskloop, these bounds need predicting. Example:
3985 // !$omp taskloop collapse(2)
3986 // do i = 1, 10
3987 // do j = 1, 5
3988 // ..
3989 // end do
3990 // end do
3991 // This loop above has a total of 50 iterations, so the lb will be 1, and
3992 // the ub will be 50. collapseLoops in OMPIRBuilder then handles ensuring
3993 // that i and j are properly presented when used in the loop.
3994 for (uint64_t i = 0; i < loopOp.getCollapseNumLoops(); i++) {
3996 i == 0 ? std::move(firstLbOrErr)
3997 : lookupOrTranslatePureValue(lowerBounds[i], moduleTranslation,
3998 builder);
3999 if (!lbOrErr)
4000 return lbOrErr.takeError();
4002 upperBounds[i], moduleTranslation, builder);
4003 if (!ubOrErr)
4004 return ubOrErr.takeError();
4006 lookupOrTranslatePureValue(steps[i], moduleTranslation, builder);
4007 if (!stepOrErr)
4008 return stepOrErr.takeError();
4009
4010 llvm::Value *loopLb = *lbOrErr;
4011 llvm::Value *loopUb = *ubOrErr;
4012 llvm::Value *loopStep = *stepOrErr;
4013 // In some cases, such as where the ub is less than the lb so the loop
4014 // steps down, the calculation for the loopTripCount is swapped. To ensure
4015 // the correct value is found, calculate both UB - LB and LB - UB then
4016 // select which value to use depending on how the loop has been
4017 // configured.
4018 llvm::Value *loopLbMinusOne = builder.CreateSub(
4019 loopLb, builder.getIntN(boundType->getIntegerBitWidth(), 1));
4020 llvm::Value *loopUbMinusOne = builder.CreateSub(
4021 loopUb, builder.getIntN(boundType->getIntegerBitWidth(), 1));
4022 llvm::Value *boundsCmp = builder.CreateICmpSLT(loopLb, loopUb);
4023 llvm::Value *ubMinusLb = builder.CreateSub(loopUb, loopLbMinusOne);
4024 llvm::Value *lbMinusUb = builder.CreateSub(loopLb, loopUbMinusOne);
4025 llvm::Value *loopTripCount =
4026 builder.CreateSelect(boundsCmp, ubMinusLb, lbMinusUb);
4027 loopTripCount = builder.CreateBinaryIntrinsic(
4028 llvm::Intrinsic::abs, loopTripCount, builder.getFalse());
4029 // For loops that have a step value not equal to 1, we need to adjust the
4030 // trip count to ensure the correct number of iterations for the loop is
4031 // captured.
4032 llvm::Value *loopTripCountDivStep =
4033 builder.CreateSDiv(loopTripCount, loopStep);
4034 loopTripCountDivStep = builder.CreateBinaryIntrinsic(
4035 llvm::Intrinsic::abs, loopTripCountDivStep, builder.getFalse());
4036 llvm::Value *loopTripCountRem =
4037 builder.CreateSRem(loopTripCount, loopStep);
4038 loopTripCountRem = builder.CreateBinaryIntrinsic(
4039 llvm::Intrinsic::abs, loopTripCountRem, builder.getFalse());
4040 llvm::Value *needsRoundUp = builder.CreateICmpNE(
4041 loopTripCountRem,
4042 builder.getIntN(loopTripCountRem->getType()->getIntegerBitWidth(),
4043 0));
4044 loopTripCount =
4045 builder.CreateAdd(loopTripCountDivStep,
4046 builder.CreateZExtOrTrunc(
4047 needsRoundUp, loopTripCountDivStep->getType()));
4048 ubVal = builder.CreateMul(ubVal, loopTripCount);
4049 }
4050 lbVal = builder.getIntN(boundType->getIntegerBitWidth(), 1);
4051 stepVal = builder.getIntN(boundType->getIntegerBitWidth(), 1);
4052 } else {
4054 lookupOrTranslatePureValue(upperBounds[0], moduleTranslation, builder);
4055 if (!ubOrErr)
4056 return ubOrErr.takeError();
4058 lookupOrTranslatePureValue(steps[0], moduleTranslation, builder);
4059 if (!stepOrErr)
4060 return stepOrErr.takeError();
4061 lbVal = *firstLbOrErr;
4062 ubVal = *ubOrErr;
4063 stepVal = *stepOrErr;
4064 }
4065
4066 assert(lbVal != nullptr && "Expected value for lbVal");
4067 assert(ubVal != nullptr && "Expected value for ubVal");
4068 assert(stepVal != nullptr && "Expected value for stepVal");
4069 return llvm::Error::success();
4070}
4071
4072// Converts an OpenMP taskloop construct into LLVM IR using OpenMPIRBuilder.
4073static LogicalResult
4074convertOmpTaskloopContextOp(omp::TaskloopContextOp contextOp,
4075 llvm::IRBuilderBase &builder,
4076 LLVM::ModuleTranslation &moduleTranslation) {
4077 using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy;
4078 mlir::Operation &opInst = *contextOp.getOperation();
4079 omp::TaskloopWrapperOp loopWrapperOp = contextOp.getLoopOp();
4080 if (failed(checkImplementationStatus(opInst)))
4081 return failure();
4082
4083 // It stores the pointer of allocated firstprivate copies,
4084 // which can be used later for freeing the allocated space.
4085 SmallVector<llvm::Value *> llvmFirstPrivateVars;
4086 PrivateVarsInfo privateVarsInfo(contextOp);
4087 TaskContextStructManager taskStructMgr{builder, moduleTranslation,
4088 privateVarsInfo};
4089
4091 llvm::OpenMPIRBuilder::InsertPointTy allocaIP =
4092 findAllocInsertPoints(builder, moduleTranslation, &deallocBlocks);
4093
4094 assert(builder.GetInsertPoint() == builder.GetInsertBlock()->end());
4095 llvm::BasicBlock *taskloopStartBlock = llvm::BasicBlock::Create(
4096 builder.getContext(), "omp.taskloop.wrapper.start",
4097 /*Parent=*/builder.GetInsertBlock()->getParent());
4098 llvm::Instruction *branchToTaskloopStartBlock =
4099 builder.CreateBr(taskloopStartBlock);
4100 builder.SetInsertPoint(branchToTaskloopStartBlock);
4101
4102 llvm::BasicBlock *copyBlock =
4103 splitBB(builder, /*CreateBranch=*/true, "omp.private.copy");
4104 llvm::BasicBlock *initBlock =
4105 splitBB(builder, /*CreateBranch=*/true, "omp.private.init");
4106
4108 moduleTranslation, allocaIP.getNodeParent(), deallocBlocks);
4109
4110 // Allocate and initialize private variables
4111 builder.SetInsertPoint(initBlock->getTerminator());
4112
4113 // TODO: don't allocate if the loop has zero iterations.
4114 taskStructMgr.generateTaskContextStruct();
4115 taskStructMgr.createGEPsToPrivateVars();
4116
4117 llvmFirstPrivateVars.resize(privateVarsInfo.vars.size());
4118
4119 for (auto [i, zip] : llvm::enumerate(llvm::zip_equal(
4120 privateVarsInfo.vars, taskStructMgr.getLLVMPrivateVarGEPs()))) {
4121 auto &[var, llvmPrivateVarAlloc] = zip;
4122 // To be handled inside the taskloop.
4123 if (!var.privatizer.readsFromMold())
4124 continue;
4125 assert(llvmPrivateVarAlloc &&
4126 "reads from mold so shouldn't have been skipped");
4127
4128 llvm::Expected<llvm::Value *> privateVarOrErr =
4129 initPrivateVar(builder, moduleTranslation, var.privatizer, var.mlirVar,
4130 var.blockArg, llvmPrivateVarAlloc, initBlock);
4131 if (!privateVarOrErr)
4132 return handleError(privateVarOrErr, *contextOp.getOperation());
4133
4134 llvmFirstPrivateVars[i] = privateVarOrErr.get();
4135
4136 llvm::IRBuilderBase::InsertPointGuard guard(builder);
4137 builder.SetInsertPoint(builder.GetInsertBlock()->getTerminator());
4138
4139 [[maybe_unused]] llvm::Value *llvmPrivateVar = llvmPrivateVarAlloc;
4140 if ((privateVarOrErr.get() != llvmPrivateVarAlloc) &&
4141 !mlir::isa<LLVM::LLVMPointerType>(var.blockArg.getType())) {
4142 builder.CreateStore(privateVarOrErr.get(), llvmPrivateVarAlloc);
4143 // Load it so we have the value pointed to by the GEP
4144 llvmPrivateVar = builder.CreateLoad(privateVarOrErr.get()->getType(),
4145 llvmPrivateVarAlloc);
4146 }
4147 assert(llvmPrivateVar->getType() ==
4148 moduleTranslation.convertType(var.blockArg.getType()));
4149 }
4150
4151 // firstprivate copy region
4152 setInsertPointForPossiblyEmptyBlock(builder, copyBlock);
4153 if (failed(completePrivateVars(
4154 contextOp, builder, moduleTranslation, privateVarsInfo,
4155 contextOp.getPrivateNeedsBarrier(),
4156 /*moldVars=*/{}, taskStructMgr.getLLVMPrivateVarGEPs())))
4157 return llvm::failure();
4158
4159 // Resolve and validate reduction / in_reduction declarations up front.
4160 // This is pure MLIR symbol-table work and does not emit IR, so do it
4161 // before moving the builder to the taskloop start block. Richer
4162 // declare_reduction shapes (byref) have been rejected already by
4163 // checkImplementationStatus; the rest (two-argument initializer, cleanup
4164 // region, missing combiner) are rejected by the helper.
4167 contextOp.getOperation(), contextOp.getReductionSyms(),
4168 "omp.taskloop.context", "reduction", redDecls)))
4169 return failure();
4172 contextOp.getOperation(), contextOp.getInReductionSyms(),
4173 "omp.taskloop.context", "in_reduction", inRedDecls)))
4174 return failure();
4175
4176 // The op verifier rejects nogroup + reduction, so no check is needed here.
4177
4178 SmallVector<llvm::Value *> redOrigPtrs;
4179 redOrigPtrs.reserve(redDecls.size());
4180 for (Value v : contextOp.getReductionVars())
4181 redOrigPtrs.push_back(moduleTranslation.lookupValue(v));
4182 SmallVector<llvm::Value *> inRedOrigPtrs;
4183 inRedOrigPtrs.reserve(inRedDecls.size());
4184 for (Value v : contextOp.getInReductionVars())
4185 inRedOrigPtrs.push_back(moduleTranslation.lookupValue(v));
4186
4187 // Set up insertion point for emitting the implicit-taskgroup reduction
4188 // setup (if any) and for the subsequent call to createTaskloop().
4189 builder.SetInsertPoint(taskloopStartBlock);
4190
4191 llvm::OpenMPIRBuilder &ompBuilderRef = *getOpenMPBuilder(moduleTranslation);
4192 llvm::Module *module = moduleTranslation.getLLVMModule();
4193
4194 // If we have task_reduction items, we must emit our own implicit
4195 // __kmpc_taskgroup so that the descriptor returned by __kmpc_taskred_init
4196 // is associated with that taskgroup. We then force NoGroup=true so that
4197 // OpenMPIRBuilder::createTaskloop does not emit a second taskgroup.
4198 bool implicitTaskgroup = !redDecls.empty();
4199 llvm::Value *redDesc = nullptr;
4200 if (implicitTaskgroup) {
4201 llvm::OpenMPIRBuilder::LocationDescription redLoc(builder);
4202 uint32_t srcLocSize;
4203 llvm::Constant *srcLocStr =
4204 ompBuilderRef.getOrCreateSrcLocStr(redLoc, srcLocSize);
4205 llvm::Value *ident = ompBuilderRef.getOrCreateIdent(srcLocStr, srcLocSize);
4206 // Align OpenMPIRBuilder's internal IRBuilder with `builder` so the
4207 // gtid call lands at our insertion point.
4208 ompBuilderRef.updateToLocation(redLoc);
4209 llvm::Value *outerGtid = ompBuilderRef.getOrCreateThreadID(ident);
4210 llvm::FunctionCallee taskgroupFn = ompBuilderRef.getOrCreateRuntimeFunction(
4211 *module, llvm::omp::OMPRTL___kmpc_taskgroup);
4212 ompBuilderRef.createRuntimeFunctionCall(taskgroupFn, {ident, outerGtid});
4213
4214 redDesc = emitTaskReductionInitCall(redDecls, redOrigPtrs,
4215 "__omp_taskloop_taskred_", builder,
4216 allocaIP, moduleTranslation);
4217 if (!redDesc)
4218 return failure();
4219 }
4220
4221 auto loopOp = cast<omp::LoopNestOp>(loopWrapperOp.getWrappedLoop());
4222 llvm::Value *lbVal = nullptr;
4223 llvm::Value *ubVal = nullptr;
4224 llvm::Value *stepVal = nullptr;
4225 if (llvm::Error err = computeTaskloopBounds(
4226 loopOp, builder, moduleTranslation, lbVal, ubVal, stepVal))
4227 return handleError(std::move(err), opInst);
4228
4229 auto bodyCB =
4230 [&](InsertPointTy allocaIP, InsertPointTy codegenIP,
4231 llvm::ArrayRef<llvm::BasicBlock *> deallocBlocks) -> llvm::Error {
4232 // Save the alloca insertion point on ModuleTranslation stack for use in
4233 // nested regions.
4235 moduleTranslation, allocaIP.getNodeParent(), deallocBlocks);
4236
4237 // translate the body of the taskloop:
4238 builder.restoreIP(codegenIP);
4239
4240 llvm::BasicBlock *privInitBlock = nullptr;
4241 for (PrivateVarsInfo::VarInfo &var : privateVarsInfo.vars) {
4242 // This is handled before the task executes
4243 if (var.privatizer.readsFromMold())
4244 continue;
4245
4246 llvm::IRBuilderBase::InsertPointGuard guard(builder);
4247 llvm::Type *llvmAllocType =
4248 moduleTranslation.convertType(var.privatizer.getType());
4249 builder.SetInsertPoint(allocaIP.getNodeParent()->getTerminator());
4250 llvm::Value *llvmPrivateVar = builder.CreateAlloca(
4251 llvmAllocType, /*ArraySize=*/nullptr, "omp.private.alloc");
4252
4254 builder, moduleTranslation, var.privatizer, var.mlirVar, var.blockArg,
4255 llvmPrivateVar, privInitBlock);
4256 if (!privateVarOrError)
4257 return privateVarOrError.takeError();
4258 moduleTranslation.mapValue(var.blockArg, privateVarOrError.get());
4259 var.llvmVar = privateVarOrError.get();
4260 }
4261
4262 taskStructMgr.createGEPsToPrivateVars();
4263 for (auto [i, llvmPrivVar] :
4264 llvm::enumerate(taskStructMgr.getLLVMPrivateVarGEPs())) {
4265 if (!llvmPrivVar) {
4266 assert(privateVarsInfo.vars[i].llvmVar &&
4267 "This is added in the loop above");
4268 continue;
4269 }
4270 privateVarsInfo.vars[i].llvmVar = llvmPrivVar;
4271 }
4272
4273 // Find and map the addresses of each variable within the taskloop context
4274 // structure
4275 for (PrivateVarsInfo::VarInfo &var : privateVarsInfo.vars) {
4276 // This was handled above.
4277 if (!var.privatizer.readsFromMold())
4278 continue;
4279 // Fix broken pass-by-value case for Fortran character boxes
4280 if (!mlir::isa<LLVM::LLVMPointerType>(var.blockArg.getType())) {
4281 var.llvmVar = builder.CreateLoad(
4282 moduleTranslation.convertType(var.blockArg.getType()), var.llvmVar);
4283 }
4284 assert(var.llvmVar->getType() ==
4285 moduleTranslation.convertType(var.blockArg.getType()));
4286 moduleTranslation.mapValue(var.blockArg, var.llvmVar);
4287 }
4288
4289 // Map reduction and in_reduction block arguments to the per-task private
4290 // storage returned by __kmpc_task_reduction_get_th_data. This call must
4291 // be emitted inside the to-be-outlined task body so that it returns the
4292 // *executing* thread's gtid (not the encountering thread's). The
4293 // taskgroup descriptor `redDesc` is computed in the outer scope and is
4294 // auto-captured into the task shareds aggregate by CodeExtractor during
4295 // OpenMPIRBuilder::finalize. For in_reduction the descriptor is NULL:
4296 // the runtime walks up enclosing taskgroups to find the matching
4297 // task_reduction registration for `origPtr`.
4298 if (!redDecls.empty() || !inRedDecls.empty()) {
4299 auto iface =
4300 cast<omp::BlockArgOpenMPOpInterface>(contextOp.getOperation());
4301 llvm::OpenMPIRBuilder &ompB = *getOpenMPBuilder(moduleTranslation);
4302 llvm::Module *m = moduleTranslation.getLLVMModule();
4303 llvm::LLVMContext &llvmCtx = m->getContext();
4304 llvm::OpenMPIRBuilder::LocationDescription bodyLoc(builder);
4305 uint32_t srcLocSize;
4306 llvm::Constant *srcLocStr =
4307 ompB.getOrCreateSrcLocStr(bodyLoc, srcLocSize);
4308 llvm::Value *bodyIdent = ompB.getOrCreateIdent(srcLocStr, srcLocSize);
4309 // Align OpenMPIRBuilder's internal IRBuilder with `builder` so the
4310 // gtid call lands inside the to-be-outlined task body.
4311 ompB.updateToLocation(bodyLoc);
4312 llvm::Value *bodyGtid = ompB.getOrCreateThreadID(bodyIdent);
4313 llvm::FunctionCallee getThData = ompB.getOrCreateRuntimeFunction(
4314 *m, llvm::omp::OMPRTL___kmpc_task_reduction_get_th_data);
4315 llvm::Type *ptrTy = llvm::PointerType::getUnqual(llvmCtx);
4316
4317 // Emit one __kmpc_task_reduction_get_th_data lookup for a reduction /
4318 // in_reduction item and map its block argument to the per-task private
4319 // storage the runtime returns. The runtime entry point takes (and
4320 // returns) a generic, default-address-space `ptr`, so normalize a
4321 // non-default-address-space original pointer to the generic address
4322 // space before the call (mirroring the descriptor setup in
4323 // emitTaskReductionInitCall), and cast the returned private pointer back
4324 // to the block argument's address space when that differs.
4325 auto remapReductionArg = [&](BlockArgument blockArg, llvm::Value *desc,
4326 llvm::Value *origPtr,
4327 const llvm::Twine &name) {
4328 if (auto *origPtrTy =
4329 llvm::dyn_cast<llvm::PointerType>(origPtr->getType());
4330 origPtrTy && origPtrTy->getAddressSpace() != 0)
4331 origPtr = builder.CreateAddrSpaceCast(origPtr, ptrTy);
4332 llvm::Value *priv = ompB.createRuntimeFunctionCall(
4333 getThData, {bodyGtid, desc, origPtr}, name);
4334 if (auto *argPtrTy = llvm::dyn_cast<llvm::PointerType>(
4335 moduleTranslation.convertType(blockArg.getType()));
4336 argPtrTy && argPtrTy->getAddressSpace() != 0)
4337 priv = builder.CreateAddrSpaceCast(priv, argPtrTy);
4338 moduleTranslation.mapValue(blockArg, priv);
4339 };
4340
4341 ArrayRef<BlockArgument> redBlockArgs = iface.getReductionBlockArgs();
4342 for (auto [blockArg, origPtr] :
4343 llvm::zip_equal(redBlockArgs, redOrigPtrs))
4344 remapReductionArg(blockArg, redDesc, origPtr, "omp.taskred.priv");
4345 ArrayRef<BlockArgument> inRedBlockArgs = iface.getInReductionBlockArgs();
4346 llvm::Value *nullDesc = llvm::ConstantPointerNull::get(ptrTy);
4347 for (auto [blockArg, origPtr] :
4348 llvm::zip_equal(inRedBlockArgs, inRedOrigPtrs))
4349 remapReductionArg(blockArg, nullDesc, origPtr, "omp.inred.priv");
4350 }
4351
4352 // Lower the contents of the taskloop context region: this is the body of
4353 // the generated task, not the loop.
4354 auto continuationBlockOrError = convertOmpOpRegions(
4355 contextOp.getRegion(), "omp.taskloop.context.region", builder,
4356 moduleTranslation);
4357
4358 if (failed(handleError(continuationBlockOrError, opInst)))
4359 return llvm::make_error<PreviouslyReportedError>();
4360
4361 builder.SetInsertPoint(continuationBlockOrError.get()->getTerminator());
4362
4363 // This is freeing the private variables as mapped inside of the task: these
4364 // will be per-task private copies possibly after task duplication. This is
4365 // handled transparently by how these are passed to the structure passed
4366 // into the outlined function. When the task is duplicated, that structure
4367 // is duplicated too.
4368 if (failed(cleanupPrivateVars(contextOp, builder, moduleTranslation,
4369 contextOp.getLoc(), privateVarsInfo)))
4370 return llvm::make_error<PreviouslyReportedError>();
4371 // Similarly, the task context structure freed inside the task is the
4372 // per-task copy after task duplication.
4373 taskStructMgr.freeStructPtr();
4374
4375 return llvm::Error::success();
4376 };
4377
4378 // Taskloop divides into an appropriate number of tasks by repeatedly
4379 // duplicating the original task. Each time this is done, the task context
4380 // structure must be duplicated too.
4381 auto taskDupCB = [&](InsertPointTy allocaIP, InsertPointTy codegenIP,
4382 llvm::Value *destPtr, llvm::Value *srcPtr)
4384 llvm::IRBuilderBase::InsertPointGuard guard(builder);
4385 builder.restoreIP(codegenIP);
4386
4387 llvm::Type *ptrTy =
4388 builder.getPtrTy(srcPtr->getType()->getPointerAddressSpace());
4389 llvm::Value *src =
4390 builder.CreateLoad(ptrTy, srcPtr, "omp.taskloop.context.src");
4391
4392 TaskContextStructManager &srcStructMgr = taskStructMgr;
4393 TaskContextStructManager destStructMgr(builder, moduleTranslation,
4394 privateVarsInfo);
4395 destStructMgr.generateTaskContextStruct();
4396 llvm::Value *dest = destStructMgr.getStructPtr();
4397 dest->setName("omp.taskloop.context.dest");
4398 builder.CreateStore(dest, destPtr);
4399
4401 srcStructMgr.createGEPsToPrivateVars(src);
4403 destStructMgr.createGEPsToPrivateVars(dest);
4404
4405 // Inline init regions.
4406 for (auto [var, mold, llvmPrivateVarAlloc] :
4407 llvm::zip_equal(privateVarsInfo.vars, srcGEPs, destGEPs)) {
4408 // To be handled inside task body.
4409 if (!var.privatizer.readsFromMold())
4410 continue;
4411 assert(llvmPrivateVarAlloc &&
4412 "reads from mold so shouldn't have been skipped");
4413
4414 llvm::Value *moldArg = materializeRegionArgValue(
4415 builder, moduleTranslation, var.privatizer.getInitMoldArg(), mold);
4417 builder, moduleTranslation, var.privatizer, moldArg, var.blockArg,
4418 llvmPrivateVarAlloc, builder.GetInsertBlock());
4419 if (!privateVarOrErr)
4420 return privateVarOrErr.takeError();
4421
4423
4424 // TODO: this is a bit of a hack for Fortran character boxes.
4425 // Character boxes are passed by value into the init region and then the
4426 // initialized character box is yielded by value. Here we need to store
4427 // the yielded value into the private allocation, and load the private
4428 // allocation to match the type expected by region block arguments.
4429 [[maybe_unused]] llvm::Value *llvmPrivateVar = llvmPrivateVarAlloc;
4430 if ((privateVarOrErr.get() != llvmPrivateVarAlloc) &&
4431 !mlir::isa<LLVM::LLVMPointerType>(var.blockArg.getType())) {
4432 builder.CreateStore(privateVarOrErr.get(), llvmPrivateVarAlloc);
4433 // Load it so we have the value pointed to by the GEP
4434 llvmPrivateVar = builder.CreateLoad(privateVarOrErr.get()->getType(),
4435 llvmPrivateVarAlloc);
4436 }
4437 assert(llvmPrivateVar->getType() ==
4438 moduleTranslation.convertType(var.blockArg.getType()));
4439
4440 // Mapping blockArg -> llvmPrivateVarAlloc is done inside the body
4441 // callback so that OpenMPIRBuilder doesn't try to pass each GEP address
4442 // through a stack allocated structure.
4443 }
4444
4445 if (failed(completePrivateVars(contextOp.getOperation(), builder,
4446 moduleTranslation, privateVarsInfo,
4447 contextOp.getPrivateNeedsBarrier(), srcGEPs,
4448 destGEPs)))
4449 return llvm::make_error<PreviouslyReportedError>();
4450
4451 return builder.saveIP();
4452 };
4453
4454 auto loopInfo = [&]() -> llvm::Expected<llvm::CanonicalLoopInfo *> {
4455 llvm::CanonicalLoopInfo *loopInfo = findCurrentLoopInfo(moduleTranslation);
4456 return loopInfo;
4457 };
4458
4459 llvm::Value *ifCond = nullptr;
4460 llvm::Value *grainsize = nullptr;
4461 int sched = 0; // default
4462 mlir::Value grainsizeVal = contextOp.getGrainsize();
4463 mlir::Value numTasksVal = contextOp.getNumTasks();
4464 if (Value ifVar = contextOp.getIfExpr())
4465 ifCond = moduleTranslation.lookupValue(ifVar);
4466 if (grainsizeVal) {
4467 grainsize = moduleTranslation.lookupValue(grainsizeVal);
4468 sched = 1; // grainsize
4469 } else if (numTasksVal) {
4470 grainsize = moduleTranslation.lookupValue(numTasksVal);
4471 sched = 2; // num_tasks
4472 }
4473
4474 llvm::OpenMPIRBuilder::TaskDupCallbackTy taskDupOrNull = nullptr;
4475 if (taskStructMgr.getStructPtr())
4476 taskDupOrNull = taskDupCB;
4477
4478 llvm::OpenMPIRBuilder &ompBuilder = *getOpenMPBuilder(moduleTranslation);
4479 SmallVector<llvm::UncondBrInst *> cancelTerminators;
4480 // The directive to match here is OMPD_taskgroup because it is the
4481 // taskgroup which is canceled. This is handled here because it is the
4482 // task's cleanup block which should be branched to. It doesn't depend upon
4483 // nogroup because even in that case the taskloop might still be inside an
4484 // explicit taskgroup.
4485 pushCancelFinalizationCB(cancelTerminators, builder, ompBuilder, contextOp,
4486 llvm::omp::Directive::OMPD_taskgroup);
4487
4488 llvm::OpenMPIRBuilder::LocationDescription ompLoc(builder);
4489 bool effectiveNoGroup = contextOp.getNogroup() || implicitTaskgroup;
4490 llvm::OpenMPIRBuilder::InsertPointOrErrorTy afterIP =
4491 getOpenMPBuilder(moduleTranslation)
4492 ->createTaskloop(
4493 ompLoc, allocaIP, deallocBlocks, bodyCB, loopInfo, lbVal, ubVal,
4494 stepVal, contextOp.getUntied(), ifCond, grainsize,
4495 effectiveNoGroup, sched,
4496 moduleTranslation.lookupValue(contextOp.getFinal()),
4497 contextOp.getMergeable(),
4498 moduleTranslation.lookupValue(contextOp.getPriority()),
4499 loopOp.getCollapseNumLoops(), taskDupOrNull,
4500 taskStructMgr.getStructPtr(),
4501 contextOp.getThreadset() == omp::ThreadsetPolicy::omp_pool);
4502
4503 if (failed(handleError(afterIP, opInst)))
4504 return failure();
4505
4506 popCancelFinalizationCB(cancelTerminators, ompBuilder,
4507 afterIP->getNodeParent());
4508
4509 builder.restoreIP(*afterIP);
4510
4511 // Close the implicit taskgroup we opened for task_reduction. The end call
4512 // must execute on the encountering thread, so use the outer-scope gtid.
4513 if (implicitTaskgroup) {
4514 llvm::OpenMPIRBuilder::LocationDescription endLoc(builder);
4515 uint32_t srcLocSize;
4516 llvm::Constant *srcLocStr =
4517 ompBuilder.getOrCreateSrcLocStr(endLoc, srcLocSize);
4518 llvm::Value *ident = ompBuilder.getOrCreateIdent(srcLocStr, srcLocSize);
4519 // Align OpenMPIRBuilder's internal IRBuilder with `builder` so the
4520 // gtid call lands at our insertion point.
4521 ompBuilder.updateToLocation(endLoc);
4522 llvm::Value *outerGtid = ompBuilder.getOrCreateThreadID(ident);
4523 llvm::FunctionCallee endTgFn = ompBuilder.getOrCreateRuntimeFunction(
4524 *moduleTranslation.getLLVMModule(),
4525 llvm::omp::OMPRTL___kmpc_end_taskgroup);
4526 ompBuilder.createRuntimeFunctionCall(endTgFn, {ident, outerGtid});
4527 }
4528 return success();
4529}
4530
4531/// Build an outlined init helper for a task_reduction declare_reduction op.
4532/// Signature: void(ptr %priv, ptr %orig). For non-byref reductions, the init
4533/// region's mold argument is mapped following the same rule as the regular
4534/// reduction path (`mapInitializationArgs`): a non-pointer mold loads the
4535/// value from %orig, while a pointer-typed mold receives %orig directly. The
4536/// yielded value is stored into %priv.
4537static llvm::Function *
4538emitTaskReductionInitFn(omp::DeclareReductionOp decl, StringRef baseName,
4539 LLVM::ModuleTranslation &moduleTranslation) {
4540 llvm::Module *llvmModule = moduleTranslation.getLLVMModule();
4541 llvm::LLVMContext &ctx = llvmModule->getContext();
4542 llvm::Type *voidTy = llvm::Type::getVoidTy(ctx);
4543 llvm::Type *ptrTy = llvm::PointerType::getUnqual(ctx);
4544 llvm::FunctionType *fty =
4545 llvm::FunctionType::get(voidTy, {ptrTy, ptrTy}, false);
4546 llvm::Function *fn =
4547 llvm::Function::Create(fty, llvm::GlobalValue::InternalLinkage,
4548 baseName + ".red.init", llvmModule);
4549 fn->setDoesNotRecurse();
4550 fn->getArg(0)->setName("priv");
4551 fn->getArg(1)->setName("orig");
4552
4553 llvm::BasicBlock *entry = llvm::BasicBlock::Create(ctx, "entry", fn);
4554 llvm::IRBuilder<> b(entry);
4555
4556 // Map the initializer's mold argument the same way the regular reduction
4557 // path does in `mapInitializationArgs`: only load the original value when a
4558 // non-pointer mold is expected. For a pointer-typed mold the storage pointer
4559 // (%orig) is passed through directly, so a mold-yielding initializer lowers
4560 // to `store ptr %orig, ptr %priv` rather than emitting a spurious load.
4561 Value moldArg = decl.getInitializerMoldArg();
4562 llvm::Value *origVal = fn->getArg(1);
4563 if (!isa<LLVM::LLVMPointerType>(moldArg.getType()))
4564 origVal = b.CreateLoad(moduleTranslation.convertType(moldArg.getType()),
4565 fn->getArg(1), "omp.orig");
4566 moduleTranslation.mapValue(moldArg, origVal);
4568 if (failed(inlineConvertOmpRegions(decl.getInitializerRegion(),
4569 "omp.taskred.init", b, moduleTranslation,
4570 &phis))) {
4571 fn->eraseFromParent();
4572 return nullptr;
4573 }
4574 assert(phis.size() == 1 &&
4575 "expected one value yielded from reduction initializer");
4576 b.CreateStore(phis[0], fn->getArg(0));
4577 b.CreateRetVoid();
4578
4579 moduleTranslation.forgetMapping(decl.getInitializerRegion());
4580 return fn;
4581}
4582
4583/// Build an outlined combiner helper for a task_reduction declare_reduction op.
4584/// Signature: void(ptr %lhs, ptr %rhs). For non-byref reductions, the values
4585/// at *%lhs and *%rhs are loaded, fed into the combiner region, and the
4586/// yielded scalar is stored back into *%lhs.
4587static llvm::Function *
4588emitTaskReductionCombFn(omp::DeclareReductionOp decl, StringRef baseName,
4589 LLVM::ModuleTranslation &moduleTranslation) {
4590 llvm::Module *llvmModule = moduleTranslation.getLLVMModule();
4591 llvm::LLVMContext &ctx = llvmModule->getContext();
4592 llvm::Type *voidTy = llvm::Type::getVoidTy(ctx);
4593 llvm::Type *ptrTy = llvm::PointerType::getUnqual(ctx);
4594 llvm::FunctionType *fty =
4595 llvm::FunctionType::get(voidTy, {ptrTy, ptrTy}, false);
4596 llvm::Function *fn =
4597 llvm::Function::Create(fty, llvm::GlobalValue::InternalLinkage,
4598 baseName + ".red.comb", llvmModule);
4599 fn->setDoesNotRecurse();
4600 fn->getArg(0)->setName("lhs");
4601 fn->getArg(1)->setName("rhs");
4602
4603 llvm::BasicBlock *entry = llvm::BasicBlock::Create(ctx, "entry", fn);
4604 llvm::IRBuilder<> b(entry);
4605
4606 llvm::Type *elemTy = moduleTranslation.convertType(decl.getType());
4607 Block &combBlock = decl.getReductionRegion().front();
4608 assert(combBlock.getNumArguments() == 2 &&
4609 "expected two arguments in declare_reduction combiner");
4610 llvm::Value *lhsVal = b.CreateLoad(elemTy, fn->getArg(0), "omp.lhs");
4611 llvm::Value *rhsVal = b.CreateLoad(elemTy, fn->getArg(1), "omp.rhs");
4612 moduleTranslation.mapValue(combBlock.getArgument(0), lhsVal);
4613 moduleTranslation.mapValue(combBlock.getArgument(1), rhsVal);
4614
4616 if (failed(inlineConvertOmpRegions(decl.getReductionRegion(),
4617 "omp.taskred.comb", b, moduleTranslation,
4618 &phis))) {
4619 fn->eraseFromParent();
4620 return nullptr;
4621 }
4622 assert(phis.size() == 1 &&
4623 "expected one value yielded from reduction combiner");
4624 b.CreateStore(phis[0], fn->getArg(0));
4625 b.CreateRetVoid();
4626
4627 moduleTranslation.forgetMapping(decl.getReductionRegion());
4628 return fn;
4629}
4630
4631/// Emit the per-taskgroup task_reduction descriptor array and the
4632/// `__kmpc_taskred_init` runtime call. \p origPtrs holds the LLVM values for
4633/// the original (shared) variables, one per declaration in \p redDecls.
4634/// `builder` must be set to the point at which the descriptor stores and the
4635/// init call should be emitted; the descriptor array itself is allocated at
4636/// \p allocaIP. \p helperNamePrefix is used to disambiguate the generated
4637/// init/combiner helper symbol names between taskgroup and taskloop callers.
4638///
4639/// When \p isModifier is false, emits `__kmpc_taskred_init` and returns the
4640/// `ptr` value it produces (the taskgroup reduction handle). When \p isModifier
4641/// is true, emits `__kmpc_taskred_modifier_init` instead to open a
4642/// task-reduction scope for a parallel or worksharing construct, passing
4643/// \p isWorksharing as the runtime `is_ws` argument. Returns null on failure.
4644///
4645/// Only the non-byref form is handled here. Byref reductions have already
4646/// been rejected by `checkImplementationStatus`.
4647static llvm::Value *emitTaskReductionInitCall(
4649 ArrayRef<llvm::Value *> origPtrs, StringRef helperNamePrefix,
4650 llvm::IRBuilderBase &builder, llvm::OpenMPIRBuilder::InsertPointTy allocaIP,
4651 LLVM::ModuleTranslation &moduleTranslation, bool isModifier,
4652 bool isWorksharing) {
4653 assert(redDecls.size() == origPtrs.size() &&
4654 "expected one orig pointer per reduction decl");
4655 llvm::OpenMPIRBuilder *ompBuilder = getOpenMPBuilder(moduleTranslation);
4656 llvm::Module *llvmModule = moduleTranslation.getLLVMModule();
4657 llvm::LLVMContext &ctx = llvmModule->getContext();
4658 const llvm::DataLayout &dl = llvmModule->getDataLayout();
4659
4660 llvm::Type *ptrTy = llvm::PointerType::getUnqual(ctx);
4661 llvm::Type *i32Ty = llvm::Type::getInt32Ty(ctx);
4662 llvm::Type *sizeTy =
4663 llvm::Type::getIntNTy(ctx, dl.getPointerSizeInBits(/*AddrSpace=*/0));
4664
4665 // Identified `kmp_taskred_input_t` struct, matching the layout used by
4666 // Clang's CGOpenMPRuntime::emitTaskReductionInit.
4667 llvm::StructType *redInputTy =
4668 llvm::StructType::getTypeByName(ctx, "kmp_taskred_input_t");
4669 if (!redInputTy)
4670 redInputTy = llvm::StructType::create(
4671 ctx, {ptrTy, ptrTy, sizeTy, ptrTy, ptrTy, ptrTy, i32Ty},
4672 "kmp_taskred_input_t");
4673
4674 unsigned n = redDecls.size();
4675 llvm::ArrayType *arrTy = llvm::ArrayType::get(redInputTy, n);
4676
4677 // Allocate the descriptor array in the enclosing function's alloca block.
4678 llvm::AllocaInst *arrAlloca;
4679 {
4680 llvm::IRBuilderBase::InsertPointGuard guard(builder);
4681 builder.restoreIP(allocaIP);
4682 arrAlloca =
4683 builder.CreateAlloca(arrTy, /*ArraySize=*/nullptr, ".taskred.input");
4684 }
4685
4686 // Fill each descriptor entry at the current builder insertion point.
4687 llvm::Value *zero = builder.getInt32(0);
4688 for (unsigned i = 0; i < n; ++i) {
4689 omp::DeclareReductionOp decl = redDecls[i];
4690 llvm::Value *orig = origPtrs[i];
4691 if (auto *origPtrTy = llvm::dyn_cast<llvm::PointerType>(orig->getType());
4692 origPtrTy && origPtrTy->getAddressSpace() != 0)
4693 orig = builder.CreateAddrSpaceCast(orig, ptrTy);
4694 llvm::Type *elemTy = moduleTranslation.convertType(decl.getType());
4695 uint64_t size = dl.getTypeAllocSize(elemTy).getFixedValue();
4696
4697 std::string baseName =
4698 (llvm::Twine(helperNamePrefix) + decl.getSymName()).str();
4699 llvm::Function *initFn =
4700 emitTaskReductionInitFn(decl, baseName, moduleTranslation);
4701 llvm::Function *combFn =
4702 emitTaskReductionCombFn(decl, baseName, moduleTranslation);
4703 if (!initFn || !combFn)
4704 return nullptr;
4705 llvm::Value *elemPtr = builder.CreateInBoundsGEP(
4706 arrTy, arrAlloca, {zero, builder.getInt32(i)}, ".taskred.elem");
4707 auto storeField = [&](unsigned fieldIdx, llvm::Value *val) {
4708 llvm::Value *fieldPtr =
4709 builder.CreateStructGEP(redInputTy, elemPtr, fieldIdx);
4710 builder.CreateStore(val, fieldPtr);
4711 };
4712 storeField(0, orig); // reduce_shar
4713 storeField(1, orig); // reduce_orig
4714 storeField(2, llvm::ConstantInt::get(sizeTy, size)); // reduce_size
4715 storeField(3, initFn); // reduce_init
4716 storeField(4, llvm::ConstantPointerNull::get(ptrTy)); // reduce_fini
4717 storeField(5, combFn); // reduce_comb
4718 storeField(6, llvm::ConstantInt::get(i32Ty, 0)); // flags
4719 }
4720
4721 // Emit the runtime call that registers the task reduction data.
4722 llvm::OpenMPIRBuilder::LocationDescription ompLoc(builder);
4723 uint32_t srcLocSize;
4724 llvm::Constant *srcLocStr =
4725 ompBuilder->getOrCreateSrcLocStr(ompLoc, srcLocSize);
4726 llvm::Value *ident = ompBuilder->getOrCreateIdent(srcLocStr, srcLocSize);
4727 ompBuilder->updateToLocation(ompLoc);
4728 llvm::Value *gtid = ompBuilder->getOrCreateThreadID(ident);
4729 if (isModifier) {
4730 // __kmpc_taskred_modifier_init(loc, gtid, is_ws, num, &arr) opens a
4731 // task-reduction scope for the enclosing parallel/worksharing region.
4732 llvm::FunctionCallee modInit = ompBuilder->getOrCreateRuntimeFunction(
4733 *llvmModule, llvm::omp::OMPRTL___kmpc_taskred_modifier_init);
4734 return ompBuilder->createRuntimeFunctionCall(
4735 modInit,
4736 {ident, gtid, builder.getInt32(isWorksharing ? 1 : 0),
4737 builder.getInt32(n), arrAlloca},
4738 ".taskred.desc");
4739 }
4740 // __kmpc_taskred_init(gtid, num, &arr).
4741 llvm::FunctionCallee taskredInit = ompBuilder->getOrCreateRuntimeFunction(
4742 *llvmModule, llvm::omp::OMPRTL___kmpc_taskred_init);
4743 return ompBuilder->createRuntimeFunctionCall(
4744 taskredInit, {gtid, builder.getInt32(n), arrAlloca}, ".taskred.desc");
4745}
4746
4747/// Emits `__kmpc_task_reduction_modifier_fini(loc, gtid, is_ws)` at the current
4748/// builder insertion point, closing the task-reduction scope opened by the
4749/// `task` reduction modifier on a parallel or worksharing construct.
4750static void
4751emitTaskReductionModifierFini(bool isWorksharing, llvm::IRBuilderBase &builder,
4752 LLVM::ModuleTranslation &moduleTranslation) {
4753 llvm::OpenMPIRBuilder *ompBuilder = getOpenMPBuilder(moduleTranslation);
4754 llvm::Module *llvmModule = moduleTranslation.getLLVMModule();
4755 llvm::OpenMPIRBuilder::LocationDescription ompLoc(builder);
4756 uint32_t srcLocSize;
4757 llvm::Constant *srcLocStr =
4758 ompBuilder->getOrCreateSrcLocStr(ompLoc, srcLocSize);
4759 llvm::Value *ident = ompBuilder->getOrCreateIdent(srcLocStr, srcLocSize);
4760 ompBuilder->updateToLocation(ompLoc);
4761 llvm::Value *gtid = ompBuilder->getOrCreateThreadID(ident);
4762 llvm::FunctionCallee fini = ompBuilder->getOrCreateRuntimeFunction(
4763 *llvmModule, llvm::omp::OMPRTL___kmpc_task_reduction_modifier_fini);
4764 ompBuilder->createRuntimeFunctionCall(
4765 fini, {ident, gtid, builder.getInt32(isWorksharing ? 1 : 0)});
4766}
4767
4768/// Converts an OpenMP taskgroup construct into LLVM IR using OpenMPIRBuilder.
4769static LogicalResult
4770convertOmpTaskgroupOp(omp::TaskgroupOp tgOp, llvm::IRBuilderBase &builder,
4771 LLVM::ModuleTranslation &moduleTranslation) {
4772 using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy;
4773 if (failed(checkImplementationStatus(*tgOp)))
4774 return failure();
4775
4776 // Resolve and validate task_reduction declarations up front. We only handle
4777 // declare_reduction ops shaped like a non-byref scalar reduction in this
4778 // first cut; richer shapes (two-argument initializer, cleanup region,
4779 // missing combiner) require additional infrastructure.
4781 if (auto syms = tgOp.getTaskReductionSyms()) {
4782 redDecls.reserve(syms->size());
4783 for (auto sym : syms->getAsRange<SymbolRefAttr>()) {
4785 tgOp, sym);
4786 if (!decl)
4787 return tgOp.emitError()
4788 << "failed to resolve task_reduction declare_reduction symbol "
4789 << sym.getRootReference() << " in omp.taskgroup";
4790 if (decl.getInitializerRegion().front().getNumArguments() != 1)
4791 return tgOp.emitError("not yet implemented: task_reduction with "
4792 "two-argument initializer in omp.taskgroup");
4793 if (!decl.getCleanupRegion().empty())
4794 return tgOp.emitError("not yet implemented: task_reduction with "
4795 "cleanup region in omp.taskgroup");
4796 if (decl.getReductionRegion().empty())
4797 return tgOp.emitError("task_reduction declare_reduction is missing a "
4798 "combiner region");
4799 redDecls.push_back(decl);
4800 }
4801 }
4802
4803 auto bodyCB =
4804 [&](InsertPointTy allocaIP, InsertPointTy codegenIP,
4805 llvm::ArrayRef<llvm::BasicBlock *> deallocBlocks) -> llvm::Error {
4806 builder.restoreIP(codegenIP);
4807
4808 if (!redDecls.empty()) {
4810 origPtrs.reserve(redDecls.size());
4811 for (Value v : tgOp.getTaskReductionVars())
4812 origPtrs.push_back(moduleTranslation.lookupValue(v));
4813 if (!emitTaskReductionInitCall(redDecls, origPtrs, "__omp_taskred_",
4814 builder, allocaIP, moduleTranslation))
4815 return llvm::createStringError(
4816 llvm::inconvertibleErrorCode(),
4817 "failed to emit task_reduction initialization for omp.taskgroup");
4818 }
4819
4820 // Inside the taskgroup body, each task_reduction block argument refers to
4821 // the same shared/original storage that the runtime now knows about via
4822 // the descriptor array. Inner tasks that declare in_reduction look up
4823 // per-task private copies through the runtime; the taskgroup body itself
4824 // uses the original variable.
4825 for (auto [i, blockArg] :
4826 llvm::enumerate(tgOp.getRegion().getArguments())) {
4827 llvm::Value *orig =
4828 moduleTranslation.lookupValue(tgOp.getTaskReductionVars()[i]);
4829 moduleTranslation.mapValue(blockArg, orig);
4830 }
4831
4832 return convertOmpOpRegions(tgOp.getRegion(), "omp.taskgroup.region",
4833 builder, moduleTranslation)
4834 .takeError();
4835 };
4836
4838 InsertPointTy allocaIP =
4839 findAllocInsertPoints(builder, moduleTranslation, &deallocBlocks);
4840 llvm::OpenMPIRBuilder::LocationDescription ompLoc(builder);
4841 llvm::OpenMPIRBuilder::InsertPointOrErrorTy afterIP =
4842 getOpenMPBuilder(moduleTranslation)
4843 ->createTaskgroup(ompLoc, allocaIP, deallocBlocks, bodyCB);
4844
4845 if (failed(handleError(afterIP, *tgOp)))
4846 return failure();
4847
4848 builder.restoreIP(*afterIP);
4849 return success();
4850}
4851
4852static LogicalResult
4853convertOmpInteropInitOp(omp::InteropInitOp initOp, llvm::IRBuilderBase &builder,
4854 LLVM::ModuleTranslation &moduleTranslation) {
4855 if (!initOp.getDependVars().empty() || initOp.getDependKinds() ||
4856 !initOp.getDependIterated().empty() || initOp.getDependIteratedKinds())
4857 return initOp.emitError()
4858 << "not yet implemented: Unhandled clause depend in "
4859 << omp::InteropInitOp::getOperationName() << " operation";
4860
4861 llvm::OpenMPIRBuilder *ompBuilder = getOpenMPBuilder(moduleTranslation);
4862 llvm::Value *interopVar =
4863 moduleTranslation.lookupValue(initOp.getInteropVar());
4864 llvm::Value *device = initOp.getDevice()
4865 ? moduleTranslation.lookupValue(initOp.getDevice())
4866 : nullptr;
4867
4868 // TODO: Handle depend clauses when supported.
4869 llvm::Value *numDeps = llvm::ConstantInt::get(builder.getInt32Ty(), 0);
4870 llvm::Value *depArray = llvm::ConstantPointerNull::get(builder.getPtrTy());
4871 bool hasNowait = initOp.getNowait();
4872
4873 // A single `init` clause may list both `target` and `targetsync`, but the
4874 // runtime init call takes a single interop-type. Collapse the set to one
4875 // value, matching Clang: if `target` is present use Target, otherwise
4876 // TargetSync. The offload runtime object model supports only one type per
4877 // object; representing both would require a runtime change.
4878 bool hasTarget = false, hasTargetSync = false;
4879 for (mlir::Attribute typeAttr : initOp.getInteropTypes()) {
4880 switch (cast<omp::InteropTypeAttr>(typeAttr).getValue()) {
4881 case omp::InteropType::target:
4882 hasTarget = true;
4883 break;
4884 case omp::InteropType::targetsync:
4885 hasTargetSync = true;
4886 break;
4887 }
4888 }
4889 llvm::omp::OMPInteropType interopType =
4890 (!hasTarget && hasTargetSync) ? llvm::omp::OMPInteropType::TargetSync
4891 : llvm::omp::OMPInteropType::Target;
4892 ompBuilder->createOMPInteropInit(builder, interopVar, interopType, device,
4893 numDeps, depArray, hasNowait);
4894 return success();
4895}
4896
4897static LogicalResult
4898convertOmpInteropDestroyOp(omp::InteropDestroyOp destroyOp,
4899 llvm::IRBuilderBase &builder,
4900 LLVM::ModuleTranslation &moduleTranslation) {
4901 if (!destroyOp.getDependVars().empty() || destroyOp.getDependKinds() ||
4902 !destroyOp.getDependIterated().empty() ||
4903 destroyOp.getDependIteratedKinds())
4904 return destroyOp.emitError()
4905 << "not yet implemented: Unhandled clause depend in "
4906 << omp::InteropDestroyOp::getOperationName() << " operation";
4907
4908 llvm::OpenMPIRBuilder *ompBuilder = getOpenMPBuilder(moduleTranslation);
4909 llvm::Value *interopVar =
4910 moduleTranslation.lookupValue(destroyOp.getInteropVar());
4911 llvm::Value *device =
4912 destroyOp.getDevice()
4913 ? moduleTranslation.lookupValue(destroyOp.getDevice())
4914 : nullptr;
4915
4916 llvm::Value *numDeps = llvm::ConstantInt::get(builder.getInt32Ty(), 0);
4917 llvm::Value *depArray = llvm::ConstantPointerNull::get(builder.getPtrTy());
4918 bool hasNowait = destroyOp.getNowait();
4919
4920 ompBuilder->createOMPInteropDestroy(builder, interopVar, device, numDeps,
4921 depArray, hasNowait);
4922 return success();
4923}
4924
4925static LogicalResult
4926convertOmpInteropUseOp(omp::InteropUseOp useOp, llvm::IRBuilderBase &builder,
4927 LLVM::ModuleTranslation &moduleTranslation) {
4928 if (!useOp.getDependVars().empty() || useOp.getDependKinds() ||
4929 !useOp.getDependIterated().empty() || useOp.getDependIteratedKinds())
4930 return useOp.emitError()
4931 << "not yet implemented: Unhandled clause depend in "
4932 << omp::InteropUseOp::getOperationName() << " operation";
4933
4934 llvm::OpenMPIRBuilder *ompBuilder = getOpenMPBuilder(moduleTranslation);
4935 llvm::Value *interopVar =
4936 moduleTranslation.lookupValue(useOp.getInteropVar());
4937 llvm::Value *device = useOp.getDevice()
4938 ? moduleTranslation.lookupValue(useOp.getDevice())
4939 : nullptr;
4940
4941 llvm::Value *numDeps = llvm::ConstantInt::get(builder.getInt32Ty(), 0);
4942 llvm::Value *depArray = llvm::ConstantPointerNull::get(builder.getPtrTy());
4943 bool hasNowait = useOp.getNowait();
4944
4945 ompBuilder->createOMPInteropUse(builder, interopVar, device, numDeps,
4946 depArray, hasNowait);
4947 return success();
4948}
4949
4950static LogicalResult
4951convertOmpTaskwaitOp(omp::TaskwaitOp twOp, llvm::IRBuilderBase &builder,
4952 LLVM::ModuleTranslation &moduleTranslation) {
4953 if (failed(checkImplementationStatus(*twOp)))
4954 return failure();
4955
4956 llvm::OpenMPIRBuilder::DependenciesInfo dds;
4957 if (failed(buildDependData(
4958 twOp.getDependVars(), twOp.getDependKinds(), twOp.getDependIterated(),
4959 twOp.getDependIteratedKinds(), builder, moduleTranslation, dds))) {
4960 return failure();
4961 }
4962
4963 getOpenMPBuilder(moduleTranslation)
4964 ->createTaskwait(builder, dds, twOp.getNowait());
4965 if (dds.DepArray) {
4966 builder.CreateFree(dds.DepArray);
4967 }
4968
4969 return success();
4970}
4971
4972/// Converts an OpenMP workshare loop into LLVM IR using OpenMPIRBuilder.
4973static LogicalResult
4974convertOmpWsloop(Operation &opInst, llvm::IRBuilderBase &builder,
4975 LLVM::ModuleTranslation &moduleTranslation) {
4976 llvm::OpenMPIRBuilder *ompBuilder = getOpenMPBuilder(moduleTranslation);
4977 auto wsloopOp = cast<omp::WsloopOp>(opInst);
4978 if (failed(checkImplementationStatus(opInst)))
4979 return failure();
4980
4981 auto loopOp = cast<omp::LoopNestOp>(wsloopOp.getWrappedLoop());
4982
4983 // Static is the default.
4984 auto schedule =
4985 wsloopOp.getScheduleKind().value_or(omp::ClauseScheduleKind::Static);
4986
4987 // Find the loop configuration.
4988 llvm::Value *step = moduleTranslation.lookupValue(loopOp.getLoopSteps()[0]);
4989 llvm::Type *ivType = step->getType();
4990 llvm::Value *chunk = nullptr;
4991 if (wsloopOp.getScheduleChunk()) {
4992 llvm::Value *chunkVar =
4993 moduleTranslation.lookupValue(wsloopOp.getScheduleChunk());
4994 chunk = builder.CreateSExtOrTrunc(chunkVar, ivType);
4995 }
4996
4997 omp::DistributeOp distributeOp = nullptr;
4998 llvm::Value *distScheduleChunk = nullptr;
4999 bool hasDistSchedule = false;
5000 if (llvm::isa_and_present<omp::DistributeOp>(opInst.getParentOp())) {
5001 distributeOp = cast<omp::DistributeOp>(opInst.getParentOp());
5002 hasDistSchedule = distributeOp.getDistScheduleStatic();
5003 if (distributeOp.getDistScheduleChunkSize()) {
5004 llvm::Value *chunkVar = moduleTranslation.lookupValue(
5005 distributeOp.getDistScheduleChunkSize());
5006 distScheduleChunk = builder.CreateSExtOrTrunc(chunkVar, ivType);
5007 }
5008 }
5009
5010 PrivateVarsInfo privateVarsInfo(wsloopOp);
5011 privateVarsInfo.addLinearVars(wsloopOp);
5012 ReductionVarsInfo reductionInfo(wsloopOp);
5013
5014 llvm::OpenMPIRBuilder::InsertPointTy allocaIP =
5015 findAllocInsertPoints(builder, moduleTranslation);
5016
5017 llvm::BasicBlock *allocaBlock = allocaIP.getNodeParent();
5019 wsloopOp, builder, moduleTranslation, privateVarsInfo, allocaIP);
5020 if (handleError(afterAllocas, opInst).failed())
5021 return failure();
5022
5023 if (failed(allocReductionVars(*wsloopOp, builder, moduleTranslation, allocaIP,
5024 reductionInfo)))
5025 return failure();
5026
5027 if (handleError(initPrivateVars(builder, moduleTranslation, privateVarsInfo),
5028 opInst)
5029 .failed())
5030 return failure();
5031
5032 if (failed(completePrivateVars(wsloopOp, builder, moduleTranslation,
5033 privateVarsInfo,
5034 wsloopOp.getPrivateNeedsBarrier())))
5035 return failure();
5036
5037 assert(afterAllocas.get()->getSinglePredecessor());
5038 if (failed(initReductionVars(*wsloopOp, builder, moduleTranslation,
5039 afterAllocas.get()->getSinglePredecessor(),
5040 reductionInfo)))
5041 return failure();
5042
5043 // For `reduction(task, ...)` open a task-reduction scope for the worksharing
5044 // loop. Participating explicit tasks accumulate into the per-thread private
5045 // copies, which the worksharing reduction then combines across threads.
5046 bool isTaskReductionMod =
5047 wsloopOp.hasReductionModifier(omp::ReductionModifier::task);
5048 if (isTaskReductionMod &&
5050 wsloopOp, reductionInfo.getReductionDecls(),
5051 reductionInfo.getPrivateReductionVariables(), builder, allocaIP,
5052 moduleTranslation, /*isWorksharing=*/true))
5053 return wsloopOp.emitError(
5054 "failed to emit task reduction modifier initialization");
5055
5056 // TODO: Handle doacross loops when the ordered clause has a parameter.
5057 bool isOrdered = wsloopOp.getOrdered().has_value();
5058 std::optional<omp::ScheduleModifier> scheduleMod = wsloopOp.getScheduleMod();
5059 bool isSimd = wsloopOp.getScheduleSimd();
5060 bool loopNeedsBarrier = !wsloopOp.getNowait();
5061
5062 // The only legal way for the direct parent to be omp.distribute is that this
5063 // represents 'distribute parallel do'. Otherwise, this is a regular
5064 // worksharing loop.
5065 llvm::omp::WorksharingLoopType workshareLoopType =
5066 llvm::isa_and_present<omp::DistributeOp>(opInst.getParentOp())
5067 ? llvm::omp::WorksharingLoopType::DistributeForStaticLoop
5068 : llvm::omp::WorksharingLoopType::ForStaticLoop;
5069
5070 SmallVector<llvm::UncondBrInst *> cancelTerminators;
5071 pushCancelFinalizationCB(cancelTerminators, builder, *ompBuilder, wsloopOp,
5072 llvm::omp::Directive::OMPD_for);
5073
5074 llvm::OpenMPIRBuilder::LocationDescription ompLoc(builder);
5075
5076 // Initialize linear variables and linear step
5077 LinearClauseProcessor linearClauseProcessor;
5078
5079 if (!wsloopOp.getLinearVars().empty()) {
5080 auto linearVarTypes = wsloopOp.getLinearVarTypes().value();
5081 for (mlir::Attribute linearVarType : linearVarTypes)
5082 linearClauseProcessor.registerType(moduleTranslation, linearVarType);
5083
5084 for (auto [idx, linearVar] : llvm::enumerate(wsloopOp.getLinearVars())) {
5085 size_t privIdx = privateVarsInfo.numPrivateVars + idx;
5086 linearClauseProcessor.createLinearVar(
5087 builder, allocaIP, privateVarsInfo.vars[privIdx].privatizer,
5088 moduleTranslation.lookupValue(linearVar),
5089 privateVarsInfo.vars[privIdx].llvmVar, idx);
5090 }
5091 for (mlir::Value linearStep : wsloopOp.getLinearStepVars())
5092 linearClauseProcessor.initLinearStep(moduleTranslation, linearStep);
5093 }
5094
5096 wsloopOp.getRegion(), "omp.wsloop.region", builder, moduleTranslation);
5097
5098 if (failed(handleError(regionBlock, opInst)))
5099 return failure();
5100
5101 llvm::CanonicalLoopInfo *loopInfo = findCurrentLoopInfo(moduleTranslation);
5102
5103 // Emit Initialization and Update IR for linear variables
5104 if (!wsloopOp.getLinearVars().empty()) {
5105 if (failed(handleError(
5106 linearClauseProcessor.initLinearVar(builder, moduleTranslation,
5107 loopInfo->getPreheader()),
5108 opInst)))
5109 return failure();
5110 llvm::OpenMPIRBuilder::InsertPointOrErrorTy afterBarrierIP =
5111 getOpenMPBuilder(moduleTranslation)
5112 ->createBarrier(builder, llvm::omp::OMPD_barrier);
5113 if (failed(handleError(afterBarrierIP, *loopOp)))
5114 return failure();
5115 builder.restoreIP(*afterBarrierIP);
5116 if (failed(handleError(linearClauseProcessor.updateLinearVar(
5117 builder, moduleTranslation, loopInfo->getBody(),
5118 loopInfo->getIndVar()),
5119 opInst)))
5120 return failure();
5121 linearClauseProcessor.splitLinearFiniBB(builder, loopInfo->getExit());
5122 }
5123
5124 builder.SetInsertPoint((*regionBlock)->begin());
5125
5126 // Check if we can generate no-loop kernel
5127 bool noLoopMode = false;
5128 omp::TargetOp targetOp = wsloopOp->getParentOfType<mlir::omp::TargetOp>();
5129 if (targetOp &&
5130 targetOp.getKernelType() == omp::TargetExecMode::spmd_no_loop) {
5131 Operation *targetCapturedOp =
5132 cast<omp::ComposableOpInterface>(*targetOp).findCapturedOp();
5133 // We need this check because, without it, noLoopMode would be set to true
5134 // for every omp.wsloop nested inside a no-loop SPMD target region, even if
5135 // that loop is not the top-level SPMD one.
5136 if (loopOp == targetCapturedOp)
5137 noLoopMode = true;
5138 }
5139
5140 // Nested regions can move the instruction referenced by allocaIP.
5141 allocaIP = allocaBlock->getFirstInsertionPt();
5142 llvm::OpenMPIRBuilder::InsertPointOrErrorTy wsloopIP =
5143 ompBuilder->applyWorkshareLoop(
5144 ompLoc.DL, loopInfo, allocaIP, loopNeedsBarrier,
5145 convertToScheduleKind(schedule), chunk, isSimd,
5146 scheduleMod == omp::ScheduleModifier::monotonic,
5147 scheduleMod == omp::ScheduleModifier::nonmonotonic, isOrdered,
5148 workshareLoopType, noLoopMode, hasDistSchedule, distScheduleChunk,
5149 !wsloopOp.getLinearVars().empty());
5150
5151 if (failed(handleError(wsloopIP, opInst)))
5152 return failure();
5153
5154 // Save the continuation block before linear var finalization, which may
5155 // invalidate the wsloopIP iterator.
5156 llvm::BasicBlock *wsloopContinuationBB = wsloopIP->getNodeParent();
5157
5158 // Emit finalization and in-place rewrites for linear vars.
5159 if (!wsloopOp.getLinearVars().empty()) {
5160 llvm::OpenMPIRBuilder::InsertPointTy oldIP = builder.saveIP();
5161 assert(loopInfo->getLastIter() &&
5162 "`lastiter` in CanonicalLoopInfo is nullptr");
5163 llvm::OpenMPIRBuilder::InsertPointOrErrorTy afterBarrierIP =
5164 linearClauseProcessor.finalizeLinearVar(builder, moduleTranslation,
5165 loopInfo->getLastIter());
5166 if (failed(handleError(afterBarrierIP, *loopOp)))
5167 return failure();
5168
5169 builder.restoreIP(oldIP);
5170 }
5171
5172 // Set the correct branch target for task cancellation
5173 popCancelFinalizationCB(cancelTerminators, *ompBuilder, wsloopContinuationBB);
5174
5175 // Close the task-reduction scope before the worksharing reduction combine.
5176 if (isTaskReductionMod)
5177 emitTaskReductionModifierFini(/*isWorksharing=*/true, builder,
5178 moduleTranslation);
5179
5180 // Process the reductions if required.
5181 if (failed(createReductionsAndCleanup(*wsloopOp, builder, moduleTranslation,
5182 allocaIP, reductionInfo,
5183 wsloopOp.getNowait(),
5184 /*isTeamsReduction=*/false)))
5185 return failure();
5186
5187 return cleanupPrivateVars(wsloopOp, builder, moduleTranslation,
5188 wsloopOp.getLoc(), privateVarsInfo);
5189}
5190
5191/// Converts the OpenMP parallel operation to LLVM IR.
5192static LogicalResult
5193convertOmpParallel(omp::ParallelOp opInst, llvm::IRBuilderBase &builder,
5194 LLVM::ModuleTranslation &moduleTranslation) {
5195 using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy;
5196 llvm::OpenMPIRBuilder *ompBuilder = getOpenMPBuilder(moduleTranslation);
5197 bool isCancellable = constructIsCancellable(opInst);
5198
5199 if (failed(checkImplementationStatus(*opInst)))
5200 return failure();
5201
5202 PrivateVarsInfo privateVarsInfo(opInst);
5203 if (failed(convertAllocatorVars(*opInst, opInst.getAllocatorVars(), builder,
5204 moduleTranslation, privateVarsInfo)))
5205 return failure();
5206
5207 // Gather reduction info.
5208 ReductionVarsInfo reductionInfo(opInst);
5209
5210 // Only open a task-reduction scope when the `task` modifier is present and
5211 // there are reduction variables to combine; otherwise the matching fini in
5212 // the reduction-combine path (guarded by getNumReductionVars() > 0) would be
5213 // skipped, leaving the modifier init unbalanced.
5214 bool isTaskReductionMod =
5215 opInst.hasReductionModifier(omp::ReductionModifier::task);
5216
5217 auto bodyGenCB =
5218 [&](InsertPointTy allocaIP, InsertPointTy codeGenIP,
5219 llvm::ArrayRef<llvm::BasicBlock *> deallocBlocks) -> llvm::Error {
5221 opInst, builder, moduleTranslation, privateVarsInfo, allocaIP);
5222 if (handleError(afterAllocas, *opInst).failed())
5223 return llvm::make_error<PreviouslyReportedError>();
5224
5225 // Allocate reduction vars
5226 allocaIP = allocaIP.getNodeParent()->getTerminator()->getIterator();
5227
5228 if (failed(allocReductionVars(*opInst, builder, moduleTranslation, allocaIP,
5229 reductionInfo)))
5230 return llvm::make_error<PreviouslyReportedError>();
5231
5232 assert(afterAllocas.get()->getSinglePredecessor());
5233 builder.restoreIP(codeGenIP);
5234
5235 if (handleError(
5236 initPrivateVars(builder, moduleTranslation, privateVarsInfo),
5237 *opInst)
5238 .failed())
5239 return llvm::make_error<PreviouslyReportedError>();
5240
5241 if (failed(completePrivateVars(opInst, builder, moduleTranslation,
5242 privateVarsInfo,
5243 opInst.getPrivateNeedsBarrier())))
5244 return llvm::make_error<PreviouslyReportedError>();
5245
5246 if (failed(initReductionVars(*opInst, builder, moduleTranslation,
5247 afterAllocas.get()->getSinglePredecessor(),
5248 reductionInfo)))
5249 return llvm::make_error<PreviouslyReportedError>();
5250
5251 // For `reduction(task, ...)` open a task-reduction scope so participating
5252 // explicit tasks accumulate into the per-thread private copies; the
5253 // parallel reduction then combines those copies across the team.
5254 if (isTaskReductionMod &&
5256 opInst, reductionInfo.getReductionDecls(),
5257 reductionInfo.getPrivateReductionVariables(), builder, allocaIP,
5258 moduleTranslation, /*isWorksharing=*/false))
5259 return llvm::createStringError(
5260 "failed to emit task reduction modifier initialization");
5261
5262 // Save the alloca insertion point on ModuleTranslation stack for use in
5263 // nested regions.
5265 moduleTranslation, allocaIP.getNodeParent(), deallocBlocks);
5266
5267 // ParallelOp has only one region associated with it.
5269 opInst.getRegion(), "omp.par.region", builder, moduleTranslation);
5270 if (!regionBlock)
5271 return regionBlock.takeError();
5272
5273 // Process the reductions if required.
5274 if (opInst.getNumReductionVars() > 0) {
5275 // Collect reduction info
5276 SmallVector<OwningReductionGen> owningReductionGens;
5277 SmallVector<OwningAtomicReductionGen> owningAtomicReductionGens;
5279 owningReductionGenRefDataPtrGens;
5281 collectReductionInfo(builder, moduleTranslation, reductionInfo,
5282 owningReductionGens, owningAtomicReductionGens,
5283 owningReductionGenRefDataPtrGens, reductionInfos);
5284
5285 // Move to region cont block
5286 builder.SetInsertPoint((*regionBlock)->getTerminator());
5287
5288 // Close the task-reduction scope before the per-thread reduction
5289 // contributions are combined across the team.
5290 if (isTaskReductionMod)
5291 emitTaskReductionModifierFini(/*isWorksharing=*/false, builder,
5292 moduleTranslation);
5293
5294 // Generate reductions from info
5295 llvm::UnreachableInst *tempTerminator = builder.CreateUnreachable();
5296 builder.SetInsertPoint(tempTerminator);
5297
5298 llvm::OpenMPIRBuilder::InsertPointOrErrorTy contInsertPoint =
5299 ompBuilder->createReductions(builder, allocaIP, reductionInfos,
5300 reductionInfo.getIsByRef(),
5301 /*IsNoWait=*/false,
5302 /*IsTeamsReduction=*/false);
5303 if (!contInsertPoint)
5304 return contInsertPoint.takeError();
5305
5306 if (!contInsertPoint->isValid())
5307 return llvm::make_error<PreviouslyReportedError>();
5308
5309 tempTerminator->eraseFromParent();
5310 builder.restoreIP(*contInsertPoint);
5311 }
5312
5313 return llvm::Error::success();
5314 };
5315
5316 auto privCB = [](InsertPointTy allocaIP, InsertPointTy codeGenIP,
5317 llvm::Value &, llvm::Value &val, llvm::Value *&replVal) {
5318 // tell OpenMPIRBuilder not to do anything. We handled Privatisation in
5319 // bodyGenCB.
5320 replVal = &val;
5321 return codeGenIP;
5322 };
5323
5324 // TODO: Perform finalization actions for variables. This has to be
5325 // called for variables which have destructors/finalizers.
5326 auto finiCB = [&](InsertPointTy codeGenIP) -> llvm::Error {
5327 InsertPointTy oldIP = builder.saveIP();
5328 builder.restoreIP(codeGenIP);
5329
5330 // if the reduction has a cleanup region, inline it here to finalize the
5331 // reduction variables
5332 SmallVector<Region *> reductionCleanupRegions;
5333 llvm::transform(reductionInfo.vars,
5334 std::back_inserter(reductionCleanupRegions),
5335 [](ReductionVarsInfo::VarInfo &var) {
5336 return &var.decl.getCleanupRegion();
5337 });
5338 if (failed(inlineOmpRegionCleanup(
5339 reductionCleanupRegions,
5340 reductionInfo.getPrivateReductionVariables(), moduleTranslation,
5341 builder, "omp.reduction.cleanup")))
5342 return llvm::createStringError(
5343 "failed to inline `cleanup` region of `omp.declare_reduction`");
5344
5345 if (failed(cleanupPrivateVars(opInst, builder, moduleTranslation,
5346 opInst.getLoc(), privateVarsInfo)))
5347 return llvm::make_error<PreviouslyReportedError>();
5348
5349 // If we could be performing cancellation, add the cancellation barrier on
5350 // the way out of the outlined region.
5351 if (isCancellable) {
5352 auto IPOrErr = ompBuilder->createBarrier(
5353 llvm::OpenMPIRBuilder::LocationDescription(builder),
5354 llvm::omp::Directive::OMPD_unknown,
5355 /* ForceSimpleCall */ false,
5356 /* CheckCancelFlag */ false);
5357 if (!IPOrErr)
5358 return IPOrErr.takeError();
5359 }
5360
5361 builder.restoreIP(oldIP);
5362 return llvm::Error::success();
5363 };
5364
5365 llvm::Value *ifCond = nullptr;
5366 if (auto ifVar = opInst.getIfExpr())
5367 ifCond = moduleTranslation.lookupValue(ifVar);
5368 llvm::Value *numThreads = nullptr;
5369 if (!opInst.getNumThreadsVars().empty())
5370 numThreads = moduleTranslation.lookupValue(opInst.getNumThreads(0));
5371 auto pbKind = llvm::omp::OMP_PROC_BIND_default;
5372 if (auto bind = opInst.getProcBindKind())
5373 pbKind = getProcBindKind(*bind);
5374
5376 llvm::OpenMPIRBuilder::InsertPointTy allocaIP =
5377 findAllocInsertPoints(builder, moduleTranslation, &deallocBlocks);
5378 llvm::OpenMPIRBuilder::LocationDescription ompLoc(builder);
5379
5380 llvm::OpenMPIRBuilder::InsertPointOrErrorTy afterIP =
5381 ompBuilder->createParallel(ompLoc, allocaIP, deallocBlocks, bodyGenCB,
5382 privCB, finiCB, ifCond, numThreads, pbKind,
5383 isCancellable);
5384
5385 if (failed(handleError(afterIP, *opInst)))
5386 return failure();
5387
5388 builder.restoreIP(*afterIP);
5389 return success();
5390}
5391
5392/// Convert Order attribute to llvm::omp::OrderKind.
5393static llvm::omp::OrderKind
5394convertOrderKind(std::optional<omp::ClauseOrderKind> o) {
5395 if (!o)
5396 return llvm::omp::OrderKind::OMP_ORDER_unknown;
5397 switch (*o) {
5398 case omp::ClauseOrderKind::Concurrent:
5399 return llvm::omp::OrderKind::OMP_ORDER_concurrent;
5400 }
5401 llvm_unreachable("Unknown ClauseOrderKind kind");
5402}
5403
5404/// Converts an OpenMP simd loop into LLVM IR using OpenMPIRBuilder.
5405static LogicalResult
5406convertOmpSimd(Operation &opInst, llvm::IRBuilderBase &builder,
5407 LLVM::ModuleTranslation &moduleTranslation) {
5408 llvm::OpenMPIRBuilder *ompBuilder = getOpenMPBuilder(moduleTranslation);
5409 auto simdOp = cast<omp::SimdOp>(opInst);
5410
5411 if (failed(checkImplementationStatus(opInst)))
5412 return failure();
5413
5414 PrivateVarsInfo privateVarsInfo(simdOp);
5415 privateVarsInfo.addLinearVars(simdOp);
5416 ReductionVarsInfo reductionInfo(simdOp);
5417
5418 llvm::OpenMPIRBuilder::InsertPointTy allocaIP =
5419 findAllocInsertPoints(builder, moduleTranslation);
5420
5422 simdOp, builder, moduleTranslation, privateVarsInfo, allocaIP);
5423 if (handleError(afterAllocas, opInst).failed())
5424 return failure();
5425
5426 if (failed(allocReductionVars(*simdOp, builder, moduleTranslation, allocaIP,
5427 reductionInfo)))
5428 return failure();
5429
5430 if (handleError(initPrivateVars(builder, moduleTranslation, privateVarsInfo),
5431 opInst)
5432 .failed())
5433 return failure();
5434
5435 // No call to completePrivateVars because SIMD does not allow FIRSTPRIVATE and
5436 // is not a worksharing construct, so a privatization barrier here could
5437 // deadlock.
5438
5439 // Initialize linear variables and linear step
5440 LinearClauseProcessor linearClauseProcessor;
5441 if (linearClauseProcessor.initLinearIV(simdOp).failed())
5442 return failure();
5443
5444 if (!simdOp.getLinearVars().empty()) {
5445 auto linearVarTypes = simdOp.getLinearVarTypes().value();
5446 for (mlir::Attribute linearVarType : linearVarTypes)
5447 linearClauseProcessor.registerType(moduleTranslation, linearVarType);
5448 for (auto [idx, linearVar] : llvm::enumerate(simdOp.getLinearVars())) {
5449 size_t privIdx = privateVarsInfo.numPrivateVars + idx;
5450 linearClauseProcessor.createLinearVar(
5451 builder, allocaIP, privateVarsInfo.vars[privIdx].privatizer,
5452 moduleTranslation.lookupValue(linearVar),
5453 privateVarsInfo.vars[privIdx].llvmVar, idx);
5454 }
5455 for (mlir::Value linearStep : simdOp.getLinearStepVars())
5456 linearClauseProcessor.initLinearStep(moduleTranslation, linearStep);
5457 }
5458
5459 assert(afterAllocas.get()->getSinglePredecessor());
5460 if (failed(initReductionVars(*simdOp, builder, moduleTranslation,
5461 afterAllocas.get()->getSinglePredecessor(),
5462 reductionInfo)))
5463 return failure();
5464
5465 llvm::ConstantInt *simdlen = nullptr;
5466 if (std::optional<uint64_t> simdlenVar = simdOp.getSimdlen())
5467 simdlen = builder.getInt64(simdlenVar.value());
5468
5469 llvm::ConstantInt *safelen = nullptr;
5470 if (std::optional<uint64_t> safelenVar = simdOp.getSafelen())
5471 safelen = builder.getInt64(safelenVar.value());
5472
5474 llvm::omp::OrderKind order = convertOrderKind(simdOp.getOrder());
5475
5476 llvm::BasicBlock *sourceBlock = builder.GetInsertBlock();
5477 std::optional<ArrayAttr> alignmentValues = simdOp.getAlignments();
5478 mlir::OperandRange operands = simdOp.getAlignedVars();
5479 for (size_t i = 0; i < operands.size(); ++i) {
5480 llvm::Value *alignment = nullptr;
5481 llvm::Value *llvmVal = moduleTranslation.lookupValue(operands[i]);
5482 llvm::Type *ty = llvmVal->getType();
5483
5484 auto intAttr = cast<IntegerAttr>((*alignmentValues)[i]);
5485 alignment = builder.getInt64(intAttr.getInt());
5486 assert(ty->isPointerTy() && "Invalid type for aligned variable");
5487 assert(alignment && "Invalid alignment value");
5488
5489 // Check if the alignment value is not a power of 2. If so, skip emitting
5490 // alignment.
5491 if (!intAttr.getValue().isPowerOf2())
5492 continue;
5493
5494 auto curInsert = builder.saveIP();
5495 builder.SetInsertPoint(sourceBlock);
5496 llvmVal = builder.CreateLoad(ty, llvmVal);
5497 builder.restoreIP(curInsert);
5498 alignedVars[llvmVal] = alignment;
5499 }
5500
5502 simdOp.getRegion(), "omp.simd.region", builder, moduleTranslation);
5503
5504 if (failed(handleError(regionBlock, opInst)))
5505 return failure();
5506
5507 llvm::CanonicalLoopInfo *loopInfo = findCurrentLoopInfo(moduleTranslation);
5508 // Emit Initialization for linear variables
5509 if (simdOp.getLinearVars().size()) {
5510 if (failed(handleError(
5511 linearClauseProcessor.initLinearVar(builder, moduleTranslation,
5512 loopInfo->getPreheader()),
5513 opInst)))
5514 return failure();
5515
5516 if (failed(handleError(linearClauseProcessor.updateLinearVar(
5517 builder, moduleTranslation, loopInfo->getBody(),
5518 loopInfo->getIndVar()),
5519 opInst)))
5520 return failure();
5521 }
5522 builder.SetInsertPoint((*regionBlock)->begin());
5523
5524 ompBuilder->applySimd(loopInfo, alignedVars,
5525 simdOp.getIfExpr()
5526 ? moduleTranslation.lookupValue(simdOp.getIfExpr())
5527 : nullptr,
5528 order, simdlen, safelen);
5529
5530 if (failed(handleError(
5531 linearClauseProcessor.updateLinearIV(builder, moduleTranslation),
5532 opInst)))
5533 return failure();
5534 if (failed(handleError(linearClauseProcessor.emitStoresForLinearVar(
5535 builder, moduleTranslation),
5536 opInst)))
5537 return failure();
5538
5539 // We now need to reduce the per-simd-lane reduction variable into the
5540 // original variable. This works a bit differently to other reductions (e.g.
5541 // wsloop) because we don't need to call into the OpenMP runtime to handle
5542 // threads: everything happened in this one thread.
5543 for (auto [i, var] : llvm::enumerate(reductionInfo.vars)) {
5544 OwningReductionGen gen =
5545 makeReductionGen(var.decl, builder, moduleTranslation);
5546 llvm::Value *originalVariable = moduleTranslation.lookupValue(var.mlirVar);
5547 llvm::Type *reductionType =
5548 moduleTranslation.convertType(var.decl.getType());
5549
5550 // We have one less load for by-ref case because that load is now inside of
5551 // the reduction region.
5552 llvm::Value *redValue = originalVariable;
5553 if (!var.byRef)
5554 redValue =
5555 builder.CreateLoad(reductionType, redValue, "red.value." + Twine(i));
5556 llvm::Value *privateRedValue = builder.CreateLoad(
5557 reductionType, var.privateVar, "red.private.value." + Twine(i));
5558 llvm::Value *reduced;
5559
5560 auto res = gen(builder.saveIP(), redValue, privateRedValue, reduced);
5561 if (failed(handleError(res, opInst)))
5562 return failure();
5563 builder.restoreIP(res.get());
5564
5565 // For by-ref case, the store is inside of the reduction region.
5566 if (!var.byRef)
5567 builder.CreateStore(reduced, originalVariable);
5568 }
5569
5570 // After the construct, deallocate private reduction variables.
5571 SmallVector<Region *> reductionRegions;
5572 llvm::transform(reductionInfo.vars, std::back_inserter(reductionRegions),
5573 [](ReductionVarsInfo::VarInfo &var) {
5574 return &var.decl.getCleanupRegion();
5575 });
5576 if (failed(inlineOmpRegionCleanup(
5577 reductionRegions, reductionInfo.getPrivateReductionVariables(),
5578 moduleTranslation, builder, "omp.reduction.cleanup")))
5579 return failure();
5580
5581 return cleanupPrivateVars(simdOp, builder, moduleTranslation, simdOp.getLoc(),
5582 privateVarsInfo);
5583}
5584
5585/// Select Virtual only for two host worksharing loops.
5586static llvm::OpenMPIRBuilder::CollapseIVMapping
5587selectCollapseIVMapping(omp::LoopNestOp loopOp, bool isTargetDevice) {
5588 using Mapping = llvm::OpenMPIRBuilder::CollapseIVMapping;
5589 if (isTargetDevice || loopOp.getCollapseNumLoops() != 2 ||
5590 disableVirtualCollapse)
5591 return Mapping::DivMod;
5592 auto wsloop = dyn_cast<omp::WsloopOp>(loopOp->getParentOp());
5593 if (!wsloop || isa<omp::LoopWrapperInterface>(wsloop->getParentOp()) ||
5594 wsloop.getScheduleKind().value_or(omp::ClauseScheduleKind::Static) !=
5595 omp::ClauseScheduleKind::Static ||
5596 wsloop.getScheduleChunk() || wsloop.getOrdered().has_value() ||
5597 !wsloop.getLinearVars().empty())
5598 return Mapping::DivMod;
5599 return Mapping::Virtual;
5600}
5601
5602/// Converts an OpenMP loop nest into LLVM IR using OpenMPIRBuilder.
5603static LogicalResult
5604convertOmpLoopNest(Operation &opInst, llvm::IRBuilderBase &builder,
5605 LLVM::ModuleTranslation &moduleTranslation) {
5606 llvm::OpenMPIRBuilder *ompBuilder = getOpenMPBuilder(moduleTranslation);
5607 auto loopOp = cast<omp::LoopNestOp>(opInst);
5608
5609 if (failed(checkImplementationStatus(opInst)))
5610 return failure();
5611
5612 // Set up the source location value for OpenMP runtime.
5613 llvm::OpenMPIRBuilder::LocationDescription ompLoc(builder);
5614
5615 // Generator of the canonical loop body.
5618 auto bodyGen = [&](llvm::OpenMPIRBuilder::InsertPointTy ip,
5619 llvm::Value *iv) -> llvm::Error {
5620 // Make sure further conversions know about the induction variable.
5621 moduleTranslation.mapValue(
5622 loopOp.getRegion().front().getArgument(loopInfos.size()), iv);
5623
5624 // Capture the body insertion point for use in nested loops. BodyIP of the
5625 // CanonicalLoopInfo always points to the beginning of the entry block of
5626 // the body.
5627 bodyInsertPoints.push_back(ip);
5628
5629 if (loopInfos.size() != loopOp.getNumLoops() - 1)
5630 return llvm::Error::success();
5631
5632 // Convert the body of the loop.
5633 builder.restoreIP(ip);
5635 loopOp.getRegion(), "omp.loop_nest.region", builder, moduleTranslation);
5636 if (!regionBlock)
5637 return regionBlock.takeError();
5638
5639 builder.SetInsertPoint((*regionBlock)->begin());
5640 return llvm::Error::success();
5641 };
5642
5643 // Delegate actual loop construction to the OpenMP IRBuilder.
5644 // TODO: this currently assumes omp.loop_nest is semantically similar to SCF
5645 // loop, i.e. it has a positive step, uses signed integer semantics.
5646 // Reconsider this code when the nested loop operation clearly supports more
5647 // cases.
5648 for (unsigned i = 0, e = loopOp.getNumLoops(); i < e; ++i) {
5649 llvm::Value *lowerBound =
5650 moduleTranslation.lookupValue(loopOp.getLoopLowerBounds()[i]);
5651 llvm::Value *upperBound =
5652 moduleTranslation.lookupValue(loopOp.getLoopUpperBounds()[i]);
5653 llvm::Value *step = moduleTranslation.lookupValue(loopOp.getLoopSteps()[i]);
5654
5655 // Make sure loop trip count are emitted in the preheader of the outermost
5656 // loop at the latest so that they are all available for the new collapsed
5657 // loop will be created below.
5658 llvm::OpenMPIRBuilder::LocationDescription loc = ompLoc;
5659 llvm::OpenMPIRBuilder::InsertPointTy computeIP = ompLoc.IP;
5660 if (i != 0) {
5661 loc = llvm::OpenMPIRBuilder::LocationDescription(bodyInsertPoints.back(),
5662 ompLoc.DL);
5663 computeIP = loopInfos.front()->getPreheaderIP();
5664 }
5665
5667 ompBuilder->createCanonicalLoop(
5668 loc, bodyGen, lowerBound, upperBound, step,
5669 /*IsSigned=*/true, loopOp.getLoopInclusive(), computeIP);
5670
5671 if (failed(handleError(loopResult, *loopOp)))
5672 return failure();
5673
5674 loopInfos.push_back(*loopResult);
5675 }
5676
5677 llvm::OpenMPIRBuilder::InsertPointTy afterIP =
5678 loopInfos.front()->getAfterIP();
5679
5680 // Do tiling.
5681 if (const auto &tiles = loopOp.getTileSizes()) {
5682 llvm::Type *ivType = loopInfos.front()->getIndVarType();
5684
5685 for (auto tile : tiles.value()) {
5686 llvm::Value *tileVal = llvm::ConstantInt::get(ivType, tile);
5687 tileSizes.push_back(tileVal);
5688 }
5689
5690 std::vector<llvm::CanonicalLoopInfo *> newLoops =
5691 ompBuilder->tileLoops(ompLoc.DL, loopInfos, tileSizes);
5692
5693 // Update afterIP to get the correct insertion point after
5694 // tiling.
5695 llvm::BasicBlock *afterBB = newLoops.front()->getAfter();
5696 llvm::BasicBlock *afterAfterBB = afterBB->getSingleSuccessor();
5697 afterIP = afterAfterBB->begin();
5698
5699 // Update the loop infos.
5700 loopInfos.clear();
5701 for (const auto &newLoop : newLoops)
5702 loopInfos.push_back(newLoop);
5703 } // Tiling done.
5704
5705 // Do collapse.
5706 const auto &numCollapse = loopOp.getCollapseNumLoops();
5708 loopInfos.begin(), loopInfos.begin() + (numCollapse));
5709
5710 llvm::SaveAndRestore<llvm::OpenMPIRBuilder::CollapseIVMapping> mappingGuard(
5711 ompBuilder->Config.CollapseMapping,
5712 selectCollapseIVMapping(loopOp, ompBuilder->Config.isTargetDevice()));
5713 auto newTopLoopInfo =
5714 ompBuilder->collapseLoops(ompLoc.DL, collapseLoopInfos, {});
5715
5716 assert(newTopLoopInfo && "New top loop information is missing");
5717 moduleTranslation.stackWalk<OpenMPLoopInfoStackFrame>(
5718 [&](OpenMPLoopInfoStackFrame &frame) {
5719 frame.loopInfo = newTopLoopInfo;
5720 return WalkResult::interrupt();
5721 });
5722
5723 // Continue building IR after the loop. Note that the LoopInfo returned by
5724 // `collapseLoops` points inside the outermost loop and is intended for
5725 // potential further loop transformations. Use the insertion point stored
5726 // before collapsing loops instead.
5727 builder.restoreIP(afterIP);
5728 return success();
5729}
5730
5731/// Convert an omp.canonical_loop to LLVM-IR
5732static LogicalResult
5733convertOmpCanonicalLoopOp(omp::CanonicalLoopOp op, llvm::IRBuilderBase &builder,
5734 LLVM::ModuleTranslation &moduleTranslation) {
5735 llvm::OpenMPIRBuilder *ompBuilder = getOpenMPBuilder(moduleTranslation);
5736
5737 llvm::OpenMPIRBuilder::LocationDescription loopLoc(builder);
5738 Value loopIV = op.getInductionVar();
5739 Value loopTC = op.getTripCount();
5740
5741 llvm::Value *llvmTC = moduleTranslation.lookupValue(loopTC);
5742
5744 ompBuilder->createCanonicalLoop(
5745 loopLoc,
5746 [&](llvm::OpenMPIRBuilder::InsertPointTy ip, llvm::Value *llvmIV) {
5747 // Register the mapping of MLIR induction variable to LLVM-IR
5748 // induction variable
5749 moduleTranslation.mapValue(loopIV, llvmIV);
5750
5751 builder.restoreIP(ip);
5753 convertOmpOpRegions(op.getRegion(), "omp.loop.region", builder,
5754 moduleTranslation);
5755
5756 return bodyGenStatus.takeError();
5757 },
5758 llvmTC, "omp.loop");
5759 if (!llvmOrError)
5760 return op.emitError(llvm::toString(llvmOrError.takeError()));
5761
5762 llvm::CanonicalLoopInfo *llvmCLI = *llvmOrError;
5763 llvm::IRBuilderBase::InsertPoint afterIP = llvmCLI->getAfterIP();
5764 builder.restoreIP(afterIP);
5765
5766 // Register the mapping of MLIR loop to LLVM-IR OpenMPIRBuilder loop
5767 if (Value cli = op.getCli())
5768 mapOmpLoop(moduleTranslation, cli, llvmCLI);
5769
5770 return success();
5771}
5772
5773/// Apply a `#pragma omp unroll` / "!$omp unroll" transformation using the
5774/// OpenMPIRBuilder.
5775static LogicalResult
5776applyUnrollHeuristic(omp::UnrollHeuristicOp op, llvm::IRBuilderBase &builder,
5777 LLVM::ModuleTranslation &moduleTranslation) {
5778 llvm::OpenMPIRBuilder *ompBuilder = getOpenMPBuilder(moduleTranslation);
5779
5780 Value applyee = op.getApplyee();
5781 assert(applyee && "Loop to apply unrolling on required");
5782
5783 llvm::CanonicalLoopInfo *consBuilderCLI =
5784 lookupOMPLoop(moduleTranslation, applyee);
5785 llvm::OpenMPIRBuilder::LocationDescription loc(builder);
5786 ompBuilder->unrollLoopHeuristic(loc.DL, consBuilderCLI);
5787
5788 invalidateOmpLoop(moduleTranslation, applyee);
5789 return success();
5790}
5791
5792/// Apply a `#pragma omp unroll full` / `!$omp unroll full` transformation
5793/// using the OpenMPIRBuilder.
5794static LogicalResult
5795applyUnrollFull(omp::UnrollFullOp op, llvm::IRBuilderBase &builder,
5796 LLVM::ModuleTranslation &moduleTranslation) {
5797 llvm::OpenMPIRBuilder *ompBuilder = getOpenMPBuilder(moduleTranslation);
5798
5799 Value applyee = op.getApplyee();
5800 assert(applyee && "Loop to apply unrolling on required");
5801
5802 llvm::CanonicalLoopInfo *consBuilderCLI =
5803 lookupOMPLoop(moduleTranslation, applyee);
5804 llvm::OpenMPIRBuilder::LocationDescription loc(builder);
5805 ompBuilder->unrollLoopFull(loc.DL, consBuilderCLI);
5806
5807 invalidateOmpLoop(moduleTranslation, applyee);
5808 return success();
5809}
5810
5811/// Apply a `#pragma omp unroll partial` / `!$omp unroll partial`
5812/// transformation using the OpenMPIRBuilder.
5813static LogicalResult
5814applyUnrollPartial(omp::UnrollPartialOp op, llvm::IRBuilderBase &builder,
5815 LLVM::ModuleTranslation &moduleTranslation) {
5816 llvm::OpenMPIRBuilder *ompBuilder = getOpenMPBuilder(moduleTranslation);
5817
5818 Value applyee = op.getApplyee();
5819 assert(applyee && "Loop to apply unrolling on required");
5820
5821 llvm::CanonicalLoopInfo *consBuilderCLI =
5822 lookupOMPLoop(moduleTranslation, applyee);
5823 llvm::OpenMPIRBuilder::LocationDescription loc(builder);
5824
5825 // No generatee is supported yet, so the unrolled loop's CanonicalLoopInfo is
5826 // not requested and unrolling is deferred to LLVM's LoopUnroll pass.
5827 int32_t factor = static_cast<int32_t>(op.getUnrollFactor());
5828 ompBuilder->unrollLoopPartial(loc.DL, consBuilderCLI, factor,
5829 /*UnrolledCLI=*/nullptr);
5830
5831 invalidateOmpLoop(moduleTranslation, applyee);
5832 return success();
5833}
5834
5835/// Apply a `#pragma omp tile` / `!$omp tile` transformation using the
5836/// OpenMPIRBuilder.
5837static LogicalResult applyTile(omp::TileOp op, llvm::IRBuilderBase &builder,
5838 LLVM::ModuleTranslation &moduleTranslation) {
5839 llvm::OpenMPIRBuilder *ompBuilder = getOpenMPBuilder(moduleTranslation);
5840 llvm::OpenMPIRBuilder::LocationDescription loc(builder);
5841
5843 SmallVector<llvm::Value *> translatedSizes;
5844
5845 for (Value size : op.getSizes()) {
5846 llvm::Value *translatedSize = moduleTranslation.lookupValue(size);
5847 assert(translatedSize &&
5848 "sizes clause arguments must already be translated");
5849 translatedSizes.push_back(translatedSize);
5850 }
5851
5852 for (Value applyee : op.getApplyees()) {
5853 llvm::CanonicalLoopInfo *consBuilderCLI =
5854 lookupOMPLoop(moduleTranslation, applyee);
5855 assert(applyee && "Canonical loop must already been translated");
5856 translatedLoops.push_back(consBuilderCLI);
5857 }
5858
5859 auto generatedLoops =
5860 ompBuilder->tileLoops(loc.DL, translatedLoops, translatedSizes);
5861 if (!op.getGeneratees().empty()) {
5862 for (auto [mlirLoop, genLoop] :
5863 zip_equal(op.getGeneratees(), generatedLoops))
5864 mapOmpLoop(moduleTranslation, mlirLoop, genLoop);
5865 }
5866
5867 // CLIs can only be consumed once
5868 for (Value applyee : op.getApplyees())
5869 invalidateOmpLoop(moduleTranslation, applyee);
5870
5871 return success();
5872}
5873
5874/// Apply a `#pragma omp fuse` / `!$omp fuse` transformation using the
5875/// OpenMPIRBuilder.
5876static LogicalResult applyFuse(omp::FuseOp op, llvm::IRBuilderBase &builder,
5877 LLVM::ModuleTranslation &moduleTranslation) {
5878 llvm::OpenMPIRBuilder *ompBuilder = getOpenMPBuilder(moduleTranslation);
5879 llvm::OpenMPIRBuilder::LocationDescription loc(builder);
5880
5881 // Select what CLIs are going to be fused
5882 SmallVector<llvm::CanonicalLoopInfo *> beforeFuse, toFuse, afterFuse;
5883 for (size_t i = 0; i < op.getApplyees().size(); i++) {
5884 Value applyee = op.getApplyees()[i];
5885 llvm::CanonicalLoopInfo *consBuilderCLI =
5886 lookupOMPLoop(moduleTranslation, applyee);
5887 assert(applyee && "Canonical loop must already been translated");
5888 if (op.getFirst().has_value() && i < op.getFirst().value() - 1)
5889 beforeFuse.push_back(consBuilderCLI);
5890 else if (op.getCount().has_value() &&
5891 i >= op.getFirst().value() + op.getCount().value() - 1)
5892 afterFuse.push_back(consBuilderCLI);
5893 else
5894 toFuse.push_back(consBuilderCLI);
5895 }
5896 assert(
5897 (op.getGeneratees().empty() ||
5898 beforeFuse.size() + afterFuse.size() + 1 == op.getGeneratees().size()) &&
5899 "Wrong number of generatees");
5900
5901 // do the fuse
5902 auto generatedLoop = ompBuilder->fuseLoops(loc.DL, toFuse);
5903 if (!op.getGeneratees().empty()) {
5904 size_t i = 0;
5905 for (; i < beforeFuse.size(); i++)
5906 mapOmpLoop(moduleTranslation, op.getGeneratees()[i], beforeFuse[i]);
5907 mapOmpLoop(moduleTranslation, op.getGeneratees()[i++], generatedLoop);
5908 for (; i < afterFuse.size(); i++)
5909 mapOmpLoop(moduleTranslation, op.getGeneratees()[i], afterFuse[i]);
5910 }
5911
5912 // CLIs can only be consumed once
5913 for (Value applyee : op.getApplyees())
5914 invalidateOmpLoop(moduleTranslation, applyee);
5915
5916 return success();
5917}
5918
5919/// Convert an Atomic Ordering attribute to llvm::AtomicOrdering.
5920static llvm::AtomicOrdering
5921convertAtomicOrdering(std::optional<omp::ClauseMemoryOrderKind> ao) {
5922 if (!ao)
5923 return llvm::AtomicOrdering::Monotonic; // Default Memory Ordering
5924
5925 switch (*ao) {
5926 case omp::ClauseMemoryOrderKind::Seq_cst:
5927 return llvm::AtomicOrdering::SequentiallyConsistent;
5928 case omp::ClauseMemoryOrderKind::Acq_rel:
5929 return llvm::AtomicOrdering::AcquireRelease;
5930 case omp::ClauseMemoryOrderKind::Acquire:
5931 return llvm::AtomicOrdering::Acquire;
5932 case omp::ClauseMemoryOrderKind::Release:
5933 return llvm::AtomicOrdering::Release;
5934 case omp::ClauseMemoryOrderKind::Relaxed:
5935 return llvm::AtomicOrdering::Monotonic;
5936 }
5937 llvm_unreachable("Unknown ClauseMemoryOrderKind kind");
5938}
5939
5940/// Compute the cmpxchg failure ordering for an atomic compare op: use the
5941/// `fail` clause ordering when present (the verifier guarantees it is a valid
5942/// cmpxchg failure ordering), otherwise the strongest failure ordering derived
5943/// from the success ordering (which matches the OpenMPIRBuilder default).
5944static llvm::AtomicOrdering
5945getAtomicCompareFailureOrdering(omp::AtomicCompareOp atomicCompareOp,
5946 llvm::AtomicOrdering atomicOrdering) {
5947 if (atomicCompareOp.getFailMemoryOrder())
5948 return convertAtomicOrdering(atomicCompareOp.getFailMemoryOrder());
5949 return llvm::AtomicCmpXchgInst::getStrongestFailureOrdering(atomicOrdering);
5950}
5951
5952/// Convert omp.atomic.read operation to LLVM IR.
5953static LogicalResult
5954convertOmpAtomicRead(Operation &opInst, llvm::IRBuilderBase &builder,
5955 LLVM::ModuleTranslation &moduleTranslation) {
5956 auto readOp = cast<omp::AtomicReadOp>(opInst);
5957 if (failed(checkImplementationStatus(opInst)))
5958 return failure();
5959
5960 llvm::OpenMPIRBuilder *ompBuilder = getOpenMPBuilder(moduleTranslation);
5961 llvm::OpenMPIRBuilder::InsertPointTy allocaIP =
5962 findAllocInsertPoints(builder, moduleTranslation);
5963
5964 llvm::OpenMPIRBuilder::LocationDescription ompLoc(builder);
5965
5966 llvm::AtomicOrdering AO = convertAtomicOrdering(readOp.getMemoryOrder());
5967 llvm::Value *x = moduleTranslation.lookupValue(readOp.getX());
5968 llvm::Value *v = moduleTranslation.lookupValue(readOp.getV());
5969
5970 llvm::Type *elementType =
5971 moduleTranslation.convertType(readOp.getElementType());
5972
5973 llvm::OpenMPIRBuilder::AtomicOpValue V = {v, elementType, false, false};
5974 llvm::OpenMPIRBuilder::AtomicOpValue X = {x, elementType, false, false};
5975 builder.restoreIP(ompBuilder->createAtomicRead(ompLoc, X, V, AO, allocaIP));
5976 return success();
5977}
5978
5979/// Converts an omp.atomic.write operation to LLVM IR.
5980static LogicalResult
5981convertOmpAtomicWrite(Operation &opInst, llvm::IRBuilderBase &builder,
5982 LLVM::ModuleTranslation &moduleTranslation) {
5983 auto writeOp = cast<omp::AtomicWriteOp>(opInst);
5984 if (failed(checkImplementationStatus(opInst)))
5985 return failure();
5986
5987 llvm::OpenMPIRBuilder *ompBuilder = getOpenMPBuilder(moduleTranslation);
5988 llvm::OpenMPIRBuilder::InsertPointTy allocaIP =
5989 findAllocInsertPoints(builder, moduleTranslation);
5990
5991 llvm::OpenMPIRBuilder::LocationDescription ompLoc(builder);
5992 llvm::AtomicOrdering ao = convertAtomicOrdering(writeOp.getMemoryOrder());
5993 llvm::Value *expr = moduleTranslation.lookupValue(writeOp.getExpr());
5994 llvm::Value *dest = moduleTranslation.lookupValue(writeOp.getX());
5995 llvm::Type *ty = moduleTranslation.convertType(writeOp.getExpr().getType());
5996 llvm::OpenMPIRBuilder::AtomicOpValue x = {dest, ty, /*isSigned=*/false,
5997 /*isVolatile=*/false};
5998 builder.restoreIP(
5999 ompBuilder->createAtomicWrite(ompLoc, x, expr, ao, allocaIP));
6000 return success();
6001}
6002
6003/// Converts an LLVM dialect binary operation to the corresponding enum value
6004/// for `atomicrmw` supported binary operation.
6005static llvm::AtomicRMWInst::BinOp convertBinOpToAtomic(Operation &op) {
6007 .Case([&](LLVM::AddOp) { return llvm::AtomicRMWInst::BinOp::Add; })
6008 .Case([&](LLVM::SubOp) { return llvm::AtomicRMWInst::BinOp::Sub; })
6009 .Case([&](LLVM::AndOp) { return llvm::AtomicRMWInst::BinOp::And; })
6010 .Case([&](LLVM::OrOp) { return llvm::AtomicRMWInst::BinOp::Or; })
6011 .Case([&](LLVM::XOrOp) { return llvm::AtomicRMWInst::BinOp::Xor; })
6012 .Case([&](LLVM::SMaxOp) { return llvm::AtomicRMWInst::BinOp::Max; })
6013 .Case([&](LLVM::SMinOp) { return llvm::AtomicRMWInst::BinOp::Min; })
6014 .Case([&](LLVM::UMaxOp) { return llvm::AtomicRMWInst::BinOp::UMax; })
6015 .Case([&](LLVM::UMinOp) { return llvm::AtomicRMWInst::BinOp::UMin; })
6016 .Case([&](LLVM::FAddOp) { return llvm::AtomicRMWInst::BinOp::FAdd; })
6017 .Case([&](LLVM::FSubOp) { return llvm::AtomicRMWInst::BinOp::FSub; })
6018 .Case([&](LLVM::MaxNumOp) { return llvm::AtomicRMWInst::BinOp::FMax; })
6019 .Case([&](LLVM::MinNumOp) { return llvm::AtomicRMWInst::BinOp::FMin; })
6020 .Case(
6021 [&](LLVM::MaximumOp) { return llvm::AtomicRMWInst::BinOp::FMaximum; })
6022 .Case(
6023 [&](LLVM::MinimumOp) { return llvm::AtomicRMWInst::BinOp::FMinimum; })
6024 .Default(llvm::AtomicRMWInst::BinOp::BAD_BINOP);
6025}
6026
6027static llvm::omp::AtomicControl
6028extractAtomicControlFlags(omp::AtomicUpdateOp atomicUpdateOp) {
6029 llvm::omp::AtomicControl ac;
6030 ac.IgnoreDenormalMode = false;
6031 ac.FineGrainedMemory = false;
6032 ac.RemoteMemory = false;
6033 if (atomicUpdateOp && atomicUpdateOp.getAtomicControlAttr()) {
6034 mlir::omp::AtomicControlAttr atomicControlAttr =
6035 atomicUpdateOp.getAtomicControlAttr();
6036 ac.IgnoreDenormalMode = atomicControlAttr.getIgnoreDenormalMode();
6037 ac.FineGrainedMemory = atomicControlAttr.getFineGrainedMemory();
6038 ac.RemoteMemory = atomicControlAttr.getRemoteMemory();
6039 }
6040 return ac;
6041}
6042
6043/// Converts an OpenMP atomic update operation using OpenMPIRBuilder.
6044static LogicalResult
6045convertOmpAtomicUpdate(omp::AtomicUpdateOp &opInst,
6046 llvm::IRBuilderBase &builder,
6047 LLVM::ModuleTranslation &moduleTranslation) {
6048 llvm::OpenMPIRBuilder *ompBuilder = getOpenMPBuilder(moduleTranslation);
6049 if (failed(checkImplementationStatus(*opInst)))
6050 return failure();
6051
6052 // Convert values and types.
6053 auto &innerOpList = opInst.getRegion().front().getOperations();
6054 bool isXBinopExpr{false};
6055 llvm::AtomicRMWInst::BinOp binop;
6056 mlir::Value mlirExpr;
6057 llvm::Value *llvmExpr = nullptr;
6058 llvm::Value *llvmX = nullptr;
6059 llvm::Type *llvmXElementType = nullptr;
6060 if (innerOpList.size() == 2) {
6061 // The two operations here are the update and the terminator.
6062 // Since we can identify the update operation, there is a possibility
6063 // that we can generate the atomicrmw instruction.
6064 mlir::Operation &innerOp = *opInst.getRegion().front().begin();
6065 if (!llvm::is_contained(innerOp.getOperands(),
6066 opInst.getRegion().getArgument(0))) {
6067 return opInst.emitError("no atomic update operation with region argument"
6068 " as operand found inside atomic.update region");
6069 }
6070 binop = convertBinOpToAtomic(innerOp);
6071 isXBinopExpr = innerOp.getOperand(0) == opInst.getRegion().getArgument(0);
6072 mlirExpr = (isXBinopExpr ? innerOp.getOperand(1) : innerOp.getOperand(0));
6073 llvmExpr = moduleTranslation.lookupValue(mlirExpr);
6074 } else {
6075 // Since the update region includes more than one operation
6076 // we will resort to generating a cmpxchg loop.
6077 binop = llvm::AtomicRMWInst::BinOp::BAD_BINOP;
6078 }
6079 llvmX = moduleTranslation.lookupValue(opInst.getX());
6080 llvmXElementType = moduleTranslation.convertType(
6081 opInst.getRegion().getArgument(0).getType());
6082 llvm::OpenMPIRBuilder::AtomicOpValue llvmAtomicX = {llvmX, llvmXElementType,
6083 /*isSigned=*/false,
6084 /*isVolatile=*/false};
6085
6086 llvm::AtomicOrdering atomicOrdering =
6087 convertAtomicOrdering(opInst.getMemoryOrder());
6088
6089 // Generate update code.
6090 auto updateFn =
6091 [&opInst, &moduleTranslation](
6092 llvm::Value *atomicx,
6093 llvm::IRBuilder<> &builder) -> llvm::Expected<llvm::Value *> {
6094 Block &bb = *opInst.getRegion().begin();
6095 moduleTranslation.mapValue(*opInst.getRegion().args_begin(), atomicx);
6096 moduleTranslation.mapBlock(&bb, builder.GetInsertBlock());
6097 if (failed(moduleTranslation.convertBlock(bb, true, builder)))
6098 return llvm::make_error<PreviouslyReportedError>();
6099
6100 omp::YieldOp yieldop = dyn_cast<omp::YieldOp>(bb.getTerminator());
6101 assert(yieldop && yieldop.getResults().size() == 1 &&
6102 "terminator must be omp.yield op and it must have exactly one "
6103 "argument");
6104 return moduleTranslation.lookupValue(yieldop.getResults()[0]);
6105 };
6106
6107 llvm::omp::AtomicControl atomicControl = extractAtomicControlFlags(opInst);
6108 // Handle ambiguous alloca, if any.
6109 auto allocaIP = findAllocInsertPoints(builder, moduleTranslation);
6110 llvm::OpenMPIRBuilder::LocationDescription ompLoc(builder);
6111 llvm::OpenMPIRBuilder::InsertPointOrErrorTy afterIP =
6112 ompBuilder->createAtomicUpdate(ompLoc, allocaIP, llvmAtomicX, llvmExpr,
6113 atomicOrdering, binop, updateFn,
6114 isXBinopExpr, atomicControl);
6115
6116 if (failed(handleError(afterIP, *opInst)))
6117 return failure();
6118
6119 builder.restoreIP(*afterIP);
6120 return success();
6121}
6122
6123/// Helper to extract the OMPAtomicCompareOp from an integer comparison
6124/// predicate. Returns std::nullopt for unsupported predicates.
6125static std::optional<llvm::omp::OMPAtomicCompareOp>
6126convertICmpPredicateToAtomicCompareOp(LLVM::ICmpPredicate predicate) {
6127 switch (predicate) {
6128 case LLVM::ICmpPredicate::eq:
6129 return llvm::omp::OMPAtomicCompareOp::EQ;
6130 case LLVM::ICmpPredicate::slt:
6131 case LLVM::ICmpPredicate::ult:
6132 return llvm::omp::OMPAtomicCompareOp::MIN;
6133 case LLVM::ICmpPredicate::sgt:
6134 case LLVM::ICmpPredicate::ugt:
6135 return llvm::omp::OMPAtomicCompareOp::MAX;
6136 default:
6137 return std::nullopt;
6138 }
6139}
6140
6141/// Helper to extract the OMPAtomicCompareOp from a floating-point comparison
6142/// predicate. Returns std::nullopt for unsupported predicates.
6143static std::optional<llvm::omp::OMPAtomicCompareOp>
6144convertFCmpPredicateToAtomicCompareOp(LLVM::FCmpPredicate predicate) {
6145 switch (predicate) {
6146 case LLVM::FCmpPredicate::oeq:
6147 case LLVM::FCmpPredicate::ueq:
6148 return llvm::omp::OMPAtomicCompareOp::EQ;
6149 case LLVM::FCmpPredicate::olt:
6150 case LLVM::FCmpPredicate::ult:
6151 return llvm::omp::OMPAtomicCompareOp::MIN;
6152 case LLVM::FCmpPredicate::ogt:
6153 case LLVM::FCmpPredicate::ugt:
6154 return llvm::omp::OMPAtomicCompareOp::MAX;
6155 default:
6156 return std::nullopt;
6157 }
6158}
6159
6160/// Result of matching the decomposed complex equality pattern inside an atomic
6161/// compare region.
6163 bool isComplex = false;
6164 bool isNE = false; // `or` of the field compares => NE (unsupported).
6165 mlir::Value eAggregate; // The complex expected value (`e`).
6166 bool isXBinopExpr = false; // True if x is the first fcmp operand.
6167};
6168
6169/// Detect a decomposed complex equality comparison in an atomic compare region:
6170/// %re_x = llvm.extractvalue %xval[0]
6171/// %re_e = llvm.extractvalue %eStruct[0]
6172/// %cmp_re = llvm.fcmp "oeq" %re_x, %re_e
6173/// %im_x = llvm.extractvalue %xval[1]
6174/// %im_e = llvm.extractvalue %eStruct[1]
6175/// %cmp_im = llvm.fcmp "oeq" %im_x, %im_e
6176/// %cmp = llvm.and %cmp_re, %cmp_im (llvm.or would be NE)
6177/// It is recognised by an and/or whose operands are both fcmps operating on
6178/// extractvalues, one chain rooted at the block argument (x) and the other at
6179/// the expected complex value (e).
6182 auto traceToAggregate = [](mlir::Value v) -> mlir::Value {
6183 if (auto extractOp = v.getDefiningOp<LLVM::ExtractValueOp>())
6184 return extractOp.getContainer();
6185 return nullptr;
6186 };
6187 for (Operation &op : block.getOperations()) {
6188 if (!isa<LLVM::AndOp, LLVM::OrOp>(op))
6189 continue;
6190 auto lhsFcmp = op.getOperand(0).getDefiningOp<LLVM::FCmpOp>();
6191 auto rhsFcmp = op.getOperand(1).getDefiningOp<LLVM::FCmpOp>();
6192 if (!lhsFcmp || !rhsFcmp)
6193 continue;
6194 mlir::Value lhsAgg0 = traceToAggregate(lhsFcmp.getOperand(0));
6195 mlir::Value lhsAgg1 = traceToAggregate(lhsFcmp.getOperand(1));
6196 bool lhsXIsOp0 = (lhsAgg0 == block.getArgument(0));
6197 bool lhsXIsOp1 = (lhsAgg1 == block.getArgument(0));
6198 if (!lhsXIsOp0 && !lhsXIsOp1)
6199 continue;
6200 mlir::Value eAggregate = lhsXIsOp0 ? lhsAgg1 : lhsAgg0;
6201 if (!eAggregate)
6202 continue;
6203 result.isComplex = true;
6204 result.isNE = isa<LLVM::OrOp>(op);
6205 result.eAggregate = eAggregate;
6206 result.isXBinopExpr = lhsXIsOp0;
6207 break;
6208 }
6209 return result;
6210}
6211
6212/// Emit an IEEE-754-correct `cmpxchg` for a complex (struct-typed) atomic
6213/// compare with `fcmp oeq`. The old value of X is returned (as the complex
6214/// struct type) in \p oldComplex and the success flag (i1) in \p cmpOk.
6215/// \p failOrdering is the memory ordering used when the compare-exchange does
6216/// not store; it must be a valid cmpxchg failure ordering.
6217static void emitComplexAtomicCmpXchg(llvm::IRBuilderBase &builder,
6218 llvm::Value *llvmX, llvm::Type *complexTy,
6219 llvm::Value *eVal, llvm::Value *dVal,
6220 llvm::AtomicOrdering atomicOrdering,
6221 llvm::AtomicOrdering failOrdering,
6222 bool isWeak, llvm::Value *&oldComplex,
6223 llvm::Value *&cmpOk) {
6224 const llvm::DataLayout &DL = builder.getDataLayout();
6225 unsigned totalBits = DL.getTypeStoreSizeInBits(complexTy).getFixedValue();
6226 llvm::IntegerType *intTy =
6227 llvm::IntegerType::get(builder.getContext(), totalBits);
6228 llvm::Align complexAlign = DL.getABITypeAlign(complexTy);
6229 llvm::Align intAlign = DL.getABITypeAlign(intTy);
6230 llvm::Align maxAlign = std::max(complexAlign, intAlign);
6231
6232 // Spill D to obtain its integer bit pattern for the swap value.
6233 llvm::AllocaInst *dAlloca =
6234 builder.CreateAlloca(complexTy, nullptr, "cmplx.d");
6235 dAlloca->setAlignment(maxAlign);
6236 builder.CreateAlignedStore(dVal, dAlloca, maxAlign);
6237 llvm::Value *dInt =
6238 builder.CreateAlignedLoad(intTy, dAlloca, maxAlign, "cmplx.d.int");
6239
6240 // Load X atomically and reinterpret as complex. Use the failure ordering: on
6241 // a failed component comparison we branch around the cmpxchg, so this load is
6242 // the only memory op on that path.
6243 llvm::LoadInst *xCurr =
6244 builder.CreateAlignedLoad(intTy, llvmX, maxAlign, "cmplx.x.load");
6245 xCurr->setAtomic(failOrdering);
6246 llvm::AllocaInst *xAlloca =
6247 builder.CreateAlloca(complexTy, nullptr, "cmplx.x");
6248 xAlloca->setAlignment(maxAlign);
6249 builder.CreateAlignedStore(xCurr, xAlloca, maxAlign);
6250 llvm::Value *xStruct =
6251 builder.CreateAlignedLoad(complexTy, xAlloca, maxAlign, "cmplx.x.val");
6252
6253 // Component-wise IEEE-754 equality: `fcmp oeq` yields false for NaN (so a
6254 // NaN component correctly makes the compare fail) and true for +0.0 vs -0.0
6255 // (so a zero-sign difference does not spuriously fail the compare).
6256 llvm::Value *reX = builder.CreateExtractValue(xStruct, 0);
6257 llvm::Value *imX = builder.CreateExtractValue(xStruct, 1);
6258 llvm::Value *reE = builder.CreateExtractValue(eVal, 0);
6259 llvm::Value *imE = builder.CreateExtractValue(eVal, 1);
6260 llvm::Value *reEq = builder.CreateFCmpOEQ(reX, reE, "cmplx.re.eq");
6261 llvm::Value *imEq = builder.CreateFCmpOEQ(imX, imE, "cmplx.im.eq");
6262 llvm::Value *fpEqual = builder.CreateAnd(reEq, imEq, "cmplx.eq");
6263
6264 // When the components compare equal, attempt the swap using X's own loaded
6265 // bit pattern as the comparand; otherwise the compare fails and X is left
6266 // unchanged (the captured old value is the value just loaded).
6267 llvm::BasicBlock *curBB = builder.GetInsertBlock();
6268 llvm::Function *fn = curBB->getParent();
6269 llvm::BasicBlock *swapBB =
6270 llvm::BasicBlock::Create(builder.getContext(), "cmplx.atomic.swap", fn);
6271 llvm::BasicBlock *exitBB =
6272 llvm::BasicBlock::Create(builder.getContext(), "cmplx.atomic.exit", fn);
6273 builder.CreateCondBr(fpEqual, swapBB, exitBB);
6274
6275 builder.SetInsertPoint(swapBB);
6276 llvm::AtomicCmpXchgInst *cmpXchg = builder.CreateAtomicCmpXchg(
6277 llvmX, xCurr, dInt, maxAlign, atomicOrdering, failOrdering);
6278 cmpXchg->setWeak(isWeak);
6279 llvm::Value *oldSwap = builder.CreateExtractValue(cmpXchg, 0);
6280 llvm::Value *okSwap = builder.CreateExtractValue(cmpXchg, 1);
6281 builder.CreateBr(exitBB);
6282
6283 // Merge the swap and no-swap paths.
6284 builder.SetInsertPoint(exitBB);
6285 llvm::PHINode *oldIntPHI = builder.CreatePHI(intTy, 2, "cmplx.old.int");
6286 oldIntPHI->addIncoming(oldSwap, swapBB);
6287 oldIntPHI->addIncoming(xCurr, curBB);
6288 llvm::PHINode *okPHI = builder.CreatePHI(builder.getInt1Ty(), 2, "cmplx.ok");
6289 okPHI->addIncoming(okSwap, swapBB);
6290 okPHI->addIncoming(builder.getFalse(), curBB);
6291
6292 // Reinterpret the old integer value as the complex struct via memory.
6293 llvm::AllocaInst *oldAlloca =
6294 builder.CreateAlloca(complexTy, nullptr, "cmplx.old");
6295 oldAlloca->setAlignment(maxAlign);
6296 builder.CreateAlignedStore(oldIntPHI, oldAlloca, maxAlign);
6297 oldComplex = builder.CreateAlignedLoad(complexTy, oldAlloca, maxAlign,
6298 "cmplx.old.val");
6299 cmpOk = okPHI;
6300}
6301
6302/// Holds the extracted comparison pattern information from an atomic compare
6303/// region.
6305 llvm::omp::OMPAtomicCompareOp compareOp = llvm::omp::OMPAtomicCompareOp::EQ;
6306 llvm::Value *eVal = nullptr;
6307 llvm::Value *dVal = nullptr;
6308 bool isXBinopExpr = false;
6309 bool isSigned = false;
6310};
6311/// Extract comparison predicate, expected value (e), desired value (d), and
6312/// related flags from an atomic compare region block by scanning for
6313/// icmp/fcmp/select/min/max operations.
6314static LogicalResult extractAtomicComparePattern(
6315 Block &block,
6316 llvm::function_ref<llvm::Value *(mlir::Value)> materializeValue,
6317 omp::AtomicCompareOp atomicCompareOp, AtomicComparePatternInfo &info) {
6318 // Complex equality is a decomposed per-field pattern (extractvalue + fcmp +
6319 // and) rather than a single scalar compare. Detect it first so the scalar
6320 // icmp/fcmp handling below does not mistake a real/imaginary field for the
6321 // whole expected value.
6323 cplx.isComplex) {
6324 if (cplx.isNE)
6325 return atomicCompareOp.emitError(
6326 "unsupported comparison predicate (NE) for complex atomic compare");
6327 info.compareOp = llvm::omp::OMPAtomicCompareOp::EQ;
6328 info.isXBinopExpr = cplx.isXBinopExpr;
6329 info.eVal = materializeValue(cplx.eAggregate);
6330 for (Operation &op : block.getOperations()) {
6331 if (auto selectOp = dyn_cast<LLVM::SelectOp>(op)) {
6332 info.dVal = materializeValue(selectOp.getTrueValue());
6333 break;
6334 }
6335 }
6336 return success();
6337 }
6338
6339 for (Operation &op : block.getOperations()) {
6340 // Pre-filter: skip icmps that don't involve the block argument
6341 // (e.g., truthiness extractions from logical-to-integer conversion).
6342 if (auto icmpOp = dyn_cast<LLVM::ICmpOp>(op);
6343 icmpOp && icmpOp.getOperand(0) != block.getArgument(0) &&
6344 icmpOp.getOperand(1) != block.getArgument(0))
6345 continue;
6346
6347 LogicalResult result =
6349 .Case<LLVM::ICmpOp>([&](LLVM::ICmpOp icmpOp) -> LogicalResult {
6350 auto maybeOp =
6351 convertICmpPredicateToAtomicCompareOp(icmpOp.getPredicate());
6352 if (!maybeOp)
6353 return atomicCompareOp.emitError(
6354 "unsupported comparison predicate in atomic compare");
6355 info.compareOp = *maybeOp;
6356 LLVM::ICmpPredicate pred = icmpOp.getPredicate();
6357 info.isSigned = (pred == LLVM::ICmpPredicate::slt ||
6358 pred == LLVM::ICmpPredicate::sgt ||
6359 pred == LLVM::ICmpPredicate::sle ||
6360 pred == LLVM::ICmpPredicate::sge);
6361 info.isXBinopExpr =
6362 (icmpOp.getOperand(0) == block.getArgument(0));
6363 mlir::Value eOperand = info.isXBinopExpr ? icmpOp.getOperand(1)
6364 : icmpOp.getOperand(0);
6365 info.eVal = materializeValue(eOperand);
6366 return success();
6367 })
6368 .Case<LLVM::FCmpOp>([&](LLVM::FCmpOp fcmpOp) -> LogicalResult {
6369 auto maybeOp =
6370 convertFCmpPredicateToAtomicCompareOp(fcmpOp.getPredicate());
6371 if (!maybeOp)
6372 return atomicCompareOp.emitError(
6373 "unsupported comparison predicate in atomic compare");
6374 info.compareOp = *maybeOp;
6375 info.isXBinopExpr =
6376 (fcmpOp.getOperand(0) == block.getArgument(0));
6377 mlir::Value eOperand = info.isXBinopExpr ? fcmpOp.getOperand(1)
6378 : fcmpOp.getOperand(0);
6379 info.eVal = materializeValue(eOperand);
6380 return success();
6381 })
6382 .Case<LLVM::SelectOp>([&](LLVM::SelectOp selectOp) {
6383 if (!info.dVal)
6384 info.dVal = materializeValue(selectOp.getTrueValue());
6385 return success();
6386 })
6387 .Case<mlir::arith::MaxSIOp, mlir::arith::MinSIOp,
6388 mlir::arith::MaxUIOp, mlir::arith::MinUIOp,
6389 mlir::arith::MaximumFOp, mlir::arith::MinimumFOp,
6390 LLVM::SMaxOp, LLVM::SMinOp, LLVM::UMaxOp, LLVM::UMinOp,
6391 LLVM::MaxNumOp, LLVM::MinNumOp>([&](Operation *) {
6392 // Canonicalized min/max ops (arith or LLVM intrinsic form).
6393 // max(x,e) came from slt/ult/olt -> OMPAtomicCompareOp::MIN
6394 // min(x,e) came from sgt/ugt/ogt -> OMPAtomicCompareOp::MAX
6395 // (OMPIRBuilder inverts: MIN->atomicrmw max, MAX->atomicrmw min)
6396 bool isMax = isa<mlir::arith::MaxSIOp, mlir::arith::MaxUIOp,
6397 mlir::arith::MaximumFOp, LLVM::SMaxOp,
6398 LLVM::UMaxOp, LLVM::MaxNumOp>(op);
6399 info.compareOp = isMax ? llvm::omp::OMPAtomicCompareOp::MIN
6400 : llvm::omp::OMPAtomicCompareOp::MAX;
6401 info.isSigned = isa<mlir::arith::MaxSIOp, mlir::arith::MinSIOp,
6402 LLVM::SMaxOp, LLVM::SMinOp>(op);
6403 info.isXBinopExpr = (op.getOperand(0) == block.getArgument(0));
6404 mlir::Value eOperand =
6405 info.isXBinopExpr ? op.getOperand(1) : op.getOperand(0);
6406 info.eVal = materializeValue(eOperand);
6407 info.dVal = info.eVal;
6408 return success();
6409 })
6410 .Default([](Operation *) { return success(); });
6411
6412 if (failed(result))
6413 return result;
6414 }
6415 return success();
6416}
6417
6418static LogicalResult
6419convertOmpAtomicCapture(omp::AtomicCaptureOp atomicCaptureOp,
6420 llvm::IRBuilderBase &builder,
6421 LLVM::ModuleTranslation &moduleTranslation) {
6422 llvm::OpenMPIRBuilder *ompBuilder = getOpenMPBuilder(moduleTranslation);
6423 if (failed(checkImplementationStatus(*atomicCaptureOp)))
6424 return failure();
6425
6426 omp::AtomicUpdateOp atomicUpdateOp = atomicCaptureOp.getAtomicUpdateOp();
6427 omp::AtomicWriteOp atomicWriteOp = atomicCaptureOp.getAtomicWriteOp();
6428 omp::AtomicCompareOp atomicCompareOp = atomicCaptureOp.getAtomicCompareOp();
6429
6430 // If the capture contains an atomic.compare, delegate to
6431 // createAtomicCompare with the capture variable (V) set.
6432 if (atomicCompareOp) {
6433 omp::AtomicReadOp atomicReadOp = atomicCaptureOp.getAtomicReadOp();
6434 assert(atomicReadOp && "expected atomic.read in capture+compare");
6435
6436 Region &region = atomicCompareOp.getRegion();
6437 Block &block = region.front();
6438
6439 llvm::Type *llvmXElementType =
6440 moduleTranslation.convertType(block.getArgument(0).getType());
6441 llvm::Value *llvmX = moduleTranslation.lookupValue(atomicCompareOp.getX());
6442 llvm::Value *llvmV = moduleTranslation.lookupValue(atomicReadOp.getV());
6443
6444 bool isSigned = false;
6445 llvm::OpenMPIRBuilder::AtomicOpValue llvmAtomicX = {
6446 llvmX, llvmXElementType, isSigned, /*IsVolatile=*/false};
6447 llvm::OpenMPIRBuilder::AtomicOpValue llvmAtomicV = {
6448 llvmV, llvmXElementType, /*isSigned=*/false, /*IsVolatile=*/false};
6449 llvm::OpenMPIRBuilder::AtomicOpValue llvmAtomicR = {nullptr, nullptr, false,
6450 false};
6451
6452 llvm::AtomicOrdering atomicOrdering =
6453 convertAtomicOrdering(atomicCaptureOp.getMemoryOrder());
6454
6455 // Pre-translate non-pattern operations inside the compare region.
6456 auto isAtomicComparePatternOp = [](Operation &op) {
6457 return llvm::isa<LLVM::ICmpOp, LLVM::FCmpOp, LLVM::SelectOp, LLVM::AndOp,
6458 LLVM::OrOp, LLVM::SMaxOp, LLVM::SMinOp, LLVM::UMaxOp,
6459 LLVM::UMinOp, LLVM::MaxNumOp, LLVM::MinNumOp,
6460 mlir::arith::MaxSIOp, mlir::arith::MinSIOp,
6461 mlir::arith::MaxUIOp, mlir::arith::MinUIOp,
6462 mlir::arith::MaximumFOp, mlir::arith::MinimumFOp>(op);
6463 };
6464 for (Operation &op : block.without_terminator()) {
6465 if (isAtomicComparePatternOp(op))
6466 continue;
6467 bool allOperandsMapped =
6468 llvm::all_of(op.getOperands(), [&](mlir::Value v) {
6469 return moduleTranslation.lookupValue(v) != nullptr;
6470 });
6471 if (!allOperandsMapped)
6472 continue;
6473 if (failed(moduleTranslation.convertOperation(op, builder)))
6474 return atomicCompareOp.emitError(
6475 "failed to translate operation inside atomic compare region");
6476 }
6477
6478 auto materializeValue = [&](mlir::Value val) -> llvm::Value * {
6479 if (llvm::Value *existing = moduleTranslation.lookupValue(val))
6480 return existing;
6481 if (auto loadOp = val.getDefiningOp<LLVM::LoadOp>()) {
6482 if (loadOp->getParentRegion() == &region) {
6483 llvm::Value *loadAddr =
6484 moduleTranslation.lookupValue(loadOp.getAddr());
6485 if (!loadAddr)
6486 return nullptr;
6487 llvm::Type *loadType =
6488 moduleTranslation.convertType(loadOp.getResult().getType());
6489 return builder.CreateLoad(loadType, loadAddr);
6490 }
6491 }
6492 return nullptr;
6493 };
6494
6495 // Extract comparison predicate, eVal, and dVal from the region.
6496 AtomicComparePatternInfo patternInfo;
6497 if (failed(extractAtomicComparePattern(block, materializeValue,
6498 atomicCompareOp, patternInfo)))
6499 return failure();
6500
6501 llvm::omp::OMPAtomicCompareOp compareOp = patternInfo.compareOp;
6502 llvm::Value *eVal = patternInfo.eVal;
6503 llvm::Value *dVal = patternInfo.dVal;
6504 bool isXBinopExpr = patternInfo.isXBinopExpr;
6505 isSigned = patternInfo.isSigned;
6506
6507 if (!eVal)
6508 return atomicCompareOp.emitError(
6509 "failed to extract expected value (e) from atomic compare region");
6510 if (!dVal) {
6511 auto yieldOp = cast<omp::YieldOp>(block.getTerminator());
6512 if (yieldOp.getResults().empty())
6513 return atomicCompareOp.emitError(
6514 "failed to extract desired value (d) from atomic compare region");
6515 dVal = materializeValue(yieldOp.getResults()[0]);
6516 }
6517
6518 llvmAtomicX.IsSigned = isSigned;
6519
6520 llvm::OpenMPIRBuilder::LocationDescription ompLoc(builder);
6521 bool isReadFirst = isa<omp::AtomicReadOp>(atomicCaptureOp.getFirstOp());
6522 bool isPostfixCapture = !isReadFirst;
6523 bool isFailOnly = atomicCaptureOp.getFailOnly();
6524
6525 // Complex equality capture: x is struct-typed, which the OMPIRBuilder
6526 // cannot handle, so emit an IEEE-754-correct cmpxchg (as in the non-capture
6527 // complex path) and reconstruct the captured value from its result. The
6528 // helper compares components with `fcmp oeq` so `-0.0 == +0.0` and `NaN`
6529 // are handled as in the scalar float path. Complex only supports the ==
6530 // comparison.
6531 if (llvmXElementType->isStructTy()) {
6532 llvm::Value *oldComplex = nullptr;
6533 llvm::Value *cmpOk = nullptr;
6534 llvm::AtomicOrdering failOrdering =
6535 getAtomicCompareFailureOrdering(atomicCompareOp, atomicOrdering);
6536 emitComplexAtomicCmpXchg(builder, llvmX, llvmXElementType, eVal, dVal,
6537 atomicOrdering, failOrdering,
6538 atomicCompareOp.getWeak(), oldComplex, cmpOk);
6539
6540 if (isFailOnly) {
6541 // v is written only when the compare fails (cmpOk == false).
6542 llvm::Value *cmpFailed = builder.CreateNot(cmpOk);
6543 llvm::BasicBlock *curBB = builder.GetInsertBlock();
6544 llvm::Function *fn = curBB->getParent();
6545 llvm::BasicBlock *contBB = llvm::BasicBlock::Create(
6546 builder.getContext(), "omp.atomic.cont", fn);
6547 llvm::BasicBlock *exitBB = llvm::BasicBlock::Create(
6548 builder.getContext(), "omp.atomic.exit", fn);
6549 builder.CreateCondBr(cmpFailed, contBB, exitBB);
6550 builder.SetInsertPoint(contBB);
6551 builder.CreateStore(oldComplex, llvmAtomicV.Var,
6552 llvmAtomicV.IsVolatile);
6553 builder.CreateBr(exitBB);
6554 builder.SetInsertPoint(exitBB);
6555 } else if (isPostfixCapture) {
6556 // v gets the new value of x: d on success, old x otherwise.
6557 llvm::Value *newComplex = builder.CreateSelect(cmpOk, dVal, oldComplex);
6558 builder.CreateStore(newComplex, llvmAtomicV.Var,
6559 llvmAtomicV.IsVolatile);
6560 } else {
6561 // Prefix: v gets the old value of x.
6562 builder.CreateStore(oldComplex, llvmAtomicV.Var,
6563 llvmAtomicV.IsVolatile);
6564 }
6565
6566 return success();
6567 }
6568
6569 // Min/max (<, >) comparisons lower to an atomicrmw. The OMPIRBuilder has no
6570 // notion of a failed compare for an atomicrmw, so the fail-only capture
6571 // form (v written only when the compare fails) has no valid mapping and is
6572 // Min/max (<, >) comparisons lower to an atomicrmw. The OMPIRBuilder has no
6573 // notion of a failed compare for an atomicrmw (it asserts on IsFailOnly),
6574 // so for min/max the fail-only capture is reconstructed manually below.
6575 bool isMinMax = compareOp != llvm::omp::OMPAtomicCompareOp::EQ;
6576
6577 llvm::OpenMPIRBuilder::AtomicOpValue llvmAtomicVForCall = llvmAtomicV;
6578 // Capture into V is reconstructed manually below for:
6579 // * postfix capture (v gets the new value of x): equality from the
6580 // cmpxchg result, min/max from the atomicrmw result;
6581 // * min/max fail-only capture (the OMPIRBuilder cannot express it).
6582 // Bypass V in the OMPIRBuilder for those cases so it does not also emit its
6583 // own (for min/max, incorrect or unsupported) capture store.
6584 bool minMaxManualCapture = isMinMax && (isPostfixCapture || isFailOnly);
6585 bool eqPostfixManualCapture = !isMinMax && isPostfixCapture && !isFailOnly;
6586 if (minMaxManualCapture || eqPostfixManualCapture)
6587 llvmAtomicVForCall = {nullptr, nullptr, false, false};
6588
6589 // The OMPIRBuilder only understands IsFailOnly for the equality (cmpxchg)
6590 // path; for min/max it would assert. Min/max fail-only is handled here.
6591 bool builderFailOnly = isFailOnly && !isMinMax;
6592
6593 // IsPostfixUpdate selects which value the OMPIRBuilder captures into V:
6594 // * min/max prefix and equality prefix: a direct store of the old value
6595 // (IsPostfixUpdate=true).
6596 // * equality fail-only: a conditional store (IsPostfixUpdate=false).
6597 // Manually-reconstructed captures bypass V above.
6598 bool isPostfixUpdate = !builderFailOnly;
6599
6600 bool isWeak = atomicCompareOp.getWeak();
6601 bool savedHandleFPNegZero = ompBuilder->setHandleFPNegZero(true);
6602 llvm::AtomicOrdering failureOrdering =
6603 getAtomicCompareFailureOrdering(atomicCompareOp, atomicOrdering);
6604 llvm::OpenMPIRBuilder::InsertPointOrErrorTy afterIP =
6605 ompBuilder->createAtomicCompare(
6606 ompLoc, llvmAtomicX, llvmAtomicVForCall, llvmAtomicR, eVal, dVal,
6607 atomicOrdering, compareOp, isXBinopExpr, isPostfixUpdate,
6608 builderFailOnly, failureOrdering, isWeak);
6609 ompBuilder->setHandleFPNegZero(savedHandleFPNegZero);
6610
6611 if (failed(handleError(afterIP, *atomicCaptureOp)))
6612 return failure();
6613
6614 builder.restoreIP(*afterIP);
6615
6616 // Min/max capture is reconstructed from the atomicrmw the OMPIRBuilder
6617 // emits (its result is the old value of x). V was bypassed above.
6618 // * postfix: v gets the new value min/max(old, e);
6619 // * fail-only: v gets the old value, but only when the compare failed
6620 // (i.e. the atomicrmw did not change x).
6621 // (Prefix min/max captures the old value directly through V, so nothing
6622 // extra is needed there.)
6623 if (isMinMax && (isPostfixCapture || isFailOnly)) {
6624 llvm::BasicBlock *curBB = builder.GetInsertBlock();
6625 llvm::AtomicRMWInst *rmw = nullptr;
6626 for (auto &inst : llvm::reverse(*curBB)) {
6627 if (auto *r = dyn_cast<llvm::AtomicRMWInst>(&inst)) {
6628 rmw = r;
6629 break;
6630 }
6631 }
6632 assert(rmw && "expected atomicrmw for min/max compare capture");
6633 llvm::Value *oldVal = rmw;
6634 llvm::Value *rhs = rmw->getValOperand();
6635
6636 if (isFailOnly) {
6637 // The compare "failed" (the else branch runs) exactly when the
6638 // atomicrmw did not change x. Recompute the original update condition
6639 // on the old value and negate it. v is stored only in that case.
6640 llvm::CmpInst::Predicate updatePred;
6641 switch (rmw->getOperation()) {
6642 case llvm::AtomicRMWInst::Min:
6643 updatePred = llvm::CmpInst::ICMP_SGT;
6644 break;
6645 case llvm::AtomicRMWInst::Max:
6646 updatePred = llvm::CmpInst::ICMP_SLT;
6647 break;
6648 case llvm::AtomicRMWInst::UMin:
6649 updatePred = llvm::CmpInst::ICMP_UGT;
6650 break;
6651 case llvm::AtomicRMWInst::UMax:
6652 updatePred = llvm::CmpInst::ICMP_ULT;
6653 break;
6654 case llvm::AtomicRMWInst::FMin:
6655 updatePred = llvm::CmpInst::FCMP_OGT;
6656 break;
6657 case llvm::AtomicRMWInst::FMax:
6658 updatePred = llvm::CmpInst::FCMP_OLT;
6659 break;
6660 default:
6661 llvm_unreachable(
6662 "unexpected atomicrmw op for min/max compare capture");
6663 }
6664 llvm::Value *updated = builder.CreateCmp(updatePred, oldVal, rhs);
6665 llvm::Value *failed = builder.CreateNot(updated);
6666 llvm::Function *fn = curBB->getParent();
6667 llvm::BasicBlock *contBB = llvm::BasicBlock::Create(
6668 builder.getContext(), "omp.atomic.cont", fn);
6669 llvm::BasicBlock *exitBB = llvm::BasicBlock::Create(
6670 builder.getContext(), "omp.atomic.exit", fn);
6671 builder.CreateCondBr(failed, contBB, exitBB);
6672 builder.SetInsertPoint(contBB);
6673 builder.CreateStore(oldVal, llvmAtomicV.Var, llvmAtomicV.IsVolatile);
6674 builder.CreateBr(exitBB);
6675 builder.SetInsertPoint(exitBB);
6676 } else {
6677 llvm::Intrinsic::ID id;
6678 switch (rmw->getOperation()) {
6679 case llvm::AtomicRMWInst::Min:
6680 id = llvm::Intrinsic::smin;
6681 break;
6682 case llvm::AtomicRMWInst::Max:
6683 id = llvm::Intrinsic::smax;
6684 break;
6685 case llvm::AtomicRMWInst::UMin:
6686 id = llvm::Intrinsic::umin;
6687 break;
6688 case llvm::AtomicRMWInst::UMax:
6689 id = llvm::Intrinsic::umax;
6690 break;
6691 case llvm::AtomicRMWInst::FMin:
6692 id = llvm::Intrinsic::minnum;
6693 break;
6694 case llvm::AtomicRMWInst::FMax:
6695 id = llvm::Intrinsic::maxnum;
6696 break;
6697 default:
6698 llvm_unreachable(
6699 "unexpected atomicrmw op for min/max compare capture");
6700 }
6701 llvm::Value *newVal = builder.CreateBinaryIntrinsic(id, oldVal, rhs);
6702 builder.CreateStore(newVal, llvmAtomicV.Var, llvmAtomicV.IsVolatile);
6703 }
6704 }
6705
6706 // Equality postfix: v = select(success, D, old) — reconstructs the new
6707 // value of x from the cmpxchg result.
6708 if (!isMinMax && isPostfixCapture && !isFailOnly) {
6709 llvm::BasicBlock *curBB = builder.GetInsertBlock();
6710 llvm::Value *oldVal = nullptr;
6711 llvm::Value *successVal = nullptr;
6712
6713 // Integer path (and non-HandleFPNegZero FP path): a single cmpxchg
6714 // lives in the current block.
6715 for (auto &inst : llvm::reverse(*curBB)) {
6716 if (isa<llvm::AtomicCmpXchgInst>(&inst)) {
6717 oldVal = builder.CreateExtractValue(&inst, /*Idxs=*/0);
6718 successVal = builder.CreateExtractValue(&inst, /*Idxs=*/1);
6719 break;
6720 }
6721 }
6722
6723 // FP HandleFPNegZero path: the OMPIRBuilder emits a multi-block
6724 // structure (NaN / ±0.0 handling) with cmpxchg in predecessor
6725 // blocks. Results are merged via PHI nodes in the current (exit)
6726 // block: an i1 PHI for success and a bitcast of an integer PHI
6727 // for the old FP value.
6728 if (!oldVal) {
6729 for (auto &inst : *curBB) {
6730 auto *phi = dyn_cast<llvm::PHINode>(&inst);
6731 if (!phi)
6732 break;
6733 if (phi->getType()->isIntegerTy(1))
6734 successVal = phi;
6735 }
6736 for (auto &inst : *curBB) {
6737 if (auto *bc = dyn_cast<llvm::BitCastInst>(&inst)) {
6738 oldVal = bc;
6739 break;
6740 }
6741 }
6742 }
6743
6744 assert(oldVal && "expected cmpxchg or PHI+bitcast for compare capture");
6745 assert(successVal && "expected success flag for compare capture");
6746 llvm::Value *newVal = builder.CreateSelect(successVal, dVal, oldVal);
6747 builder.CreateStore(newVal, llvmAtomicV.Var, llvmAtomicV.IsVolatile);
6748 }
6749
6750 return success();
6751 }
6752
6753 mlir::Value mlirExpr;
6754 bool isXBinopExpr = false, isPostfixUpdate = false;
6755 llvm::AtomicRMWInst::BinOp binop = llvm::AtomicRMWInst::BinOp::BAD_BINOP;
6756
6757 assert((atomicUpdateOp || atomicWriteOp) &&
6758 "internal op must be an atomic.update or atomic.write op");
6759
6760 if (atomicWriteOp) {
6761 isPostfixUpdate = true;
6762 mlirExpr = atomicWriteOp.getExpr();
6763 } else {
6764 isPostfixUpdate = atomicCaptureOp.getSecondOp() ==
6765 atomicCaptureOp.getAtomicUpdateOp().getOperation();
6766 auto &innerOpList = atomicUpdateOp.getRegion().front().getOperations();
6767 // Find the binary update operation that uses the region argument
6768 // and get the expression to update
6769 if (innerOpList.size() == 2) {
6770 mlir::Operation &innerOp = *atomicUpdateOp.getRegion().front().begin();
6771 if (!llvm::is_contained(innerOp.getOperands(),
6772 atomicUpdateOp.getRegion().getArgument(0))) {
6773 return atomicUpdateOp.emitError(
6774 "no atomic update operation with region argument"
6775 " as operand found inside atomic.update region");
6776 }
6777 binop = convertBinOpToAtomic(innerOp);
6778 isXBinopExpr =
6779 innerOp.getOperand(0) == atomicUpdateOp.getRegion().getArgument(0);
6780 mlirExpr = (isXBinopExpr ? innerOp.getOperand(1) : innerOp.getOperand(0));
6781 } else {
6782 binop = llvm::AtomicRMWInst::BinOp::BAD_BINOP;
6783 }
6784 }
6785
6786 llvm::Value *llvmExpr = moduleTranslation.lookupValue(mlirExpr);
6787 llvm::Value *llvmX =
6788 moduleTranslation.lookupValue(atomicCaptureOp.getAtomicReadOp().getX());
6789 llvm::Value *llvmV =
6790 moduleTranslation.lookupValue(atomicCaptureOp.getAtomicReadOp().getV());
6791 llvm::Type *llvmXElementType = moduleTranslation.convertType(
6792 atomicCaptureOp.getAtomicReadOp().getElementType());
6793 llvm::OpenMPIRBuilder::AtomicOpValue llvmAtomicX = {llvmX, llvmXElementType,
6794 /*isSigned=*/false,
6795 /*isVolatile=*/false};
6796 llvm::OpenMPIRBuilder::AtomicOpValue llvmAtomicV = {llvmV, llvmXElementType,
6797 /*isSigned=*/false,
6798 /*isVolatile=*/false};
6799
6800 llvm::AtomicOrdering atomicOrdering =
6801 convertAtomicOrdering(atomicCaptureOp.getMemoryOrder());
6802
6803 auto updateFn =
6804 [&](llvm::Value *atomicx,
6805 llvm::IRBuilder<> &builder) -> llvm::Expected<llvm::Value *> {
6806 if (atomicWriteOp)
6807 return moduleTranslation.lookupValue(atomicWriteOp.getExpr());
6808 Block &bb = *atomicUpdateOp.getRegion().begin();
6809 moduleTranslation.mapValue(*atomicUpdateOp.getRegion().args_begin(),
6810 atomicx);
6811 moduleTranslation.mapBlock(&bb, builder.GetInsertBlock());
6812 if (failed(moduleTranslation.convertBlock(bb, true, builder)))
6813 return llvm::make_error<PreviouslyReportedError>();
6814
6815 omp::YieldOp yieldop = dyn_cast<omp::YieldOp>(bb.getTerminator());
6816 assert(yieldop && yieldop.getResults().size() == 1 &&
6817 "terminator must be omp.yield op and it must have exactly one "
6818 "argument");
6819 return moduleTranslation.lookupValue(yieldop.getResults()[0]);
6820 };
6821
6822 llvm::omp::AtomicControl atomicControl =
6823 extractAtomicControlFlags(atomicUpdateOp);
6824 // Handle ambiguous alloca, if any.
6825 auto allocaIP = findAllocInsertPoints(builder, moduleTranslation);
6826 llvm::OpenMPIRBuilder::LocationDescription ompLoc(builder);
6827 llvm::OpenMPIRBuilder::InsertPointOrErrorTy afterIP =
6828 ompBuilder->createAtomicCapture(
6829 ompLoc, allocaIP, llvmAtomicX, llvmAtomicV, llvmExpr, atomicOrdering,
6830 binop, updateFn, atomicUpdateOp, isPostfixUpdate, isXBinopExpr,
6831 atomicControl);
6832
6833 if (failed(handleError(afterIP, *atomicCaptureOp)))
6834 return failure();
6835
6836 builder.restoreIP(*afterIP);
6837 return success();
6838}
6839
6840/// Converts an omp.atomic.compare operation to LLVM IR.
6841///
6842/// if (x == e) x = d
6843/// The region contains a comparison + select pattern:
6844/// ^bb0(%xval: T):
6845/// %cmp = llvm.icmp/fcmp <pred> %xval, %e : T
6846/// %sel = llvm.select %cmp, %d, %xval : i1, T
6847/// omp.yield(%sel : T)
6848///
6849/// From MLIR extract:
6850/// 1) comparison operator
6851/// 2) expected value (e)
6852/// 3) desired value (d)
6853/// These are passed to OpenMPIRBuilder::createAtomicCompare which generates
6854/// the actual cmpxchg / atomicrmw instruction.
6855///
6856static LogicalResult
6857convertOmpAtomicCompare(omp::AtomicCompareOp atomicCompareOp,
6858 llvm::IRBuilderBase &builder,
6859 LLVM::ModuleTranslation &moduleTranslation) {
6860 llvm::OpenMPIRBuilder *ompBuilder = getOpenMPBuilder(moduleTranslation);
6861 if (failed(checkImplementationStatus(*atomicCompareOp)))
6862 return failure();
6863
6864 Region &region = atomicCompareOp.getRegion();
6865 Block &block = region.front();
6866
6867 // Determine element type from the region block argument
6868 llvm::Type *llvmXElementType =
6869 moduleTranslation.convertType(block.getArgument(0).getType());
6870 if (!llvmXElementType)
6871 return atomicCompareOp.emitError(
6872 "unable to determine element type for atomic compare");
6873
6874 llvm::Value *llvmX = moduleTranslation.lookupValue(atomicCompareOp.getX());
6875
6876 // IsSigned is determined from the comparison predicate in the region.
6877 // Signed ICmp predicates (slt/sgt) set this to true; unsigned (ult/ugt)
6878 // leave it false. For EQ and float comparisons, signedness is irrelevant.
6879 bool isSigned = false;
6880 llvm::OpenMPIRBuilder::AtomicOpValue llvmAtomicX = {llvmX, llvmXElementType,
6881 isSigned,
6882 /*IsVolatile=*/false};
6883
6884 llvm::AtomicOrdering atomicOrdering =
6885 convertAtomicOrdering(atomicCompareOp.getMemoryOrder());
6886
6887 auto isAtomicComparePatternOp = [](Operation &op) {
6888 return llvm::isa<LLVM::ICmpOp, LLVM::FCmpOp, LLVM::SelectOp, LLVM::AndOp,
6889 LLVM::OrOp, LLVM::SMaxOp, LLVM::SMinOp, LLVM::UMaxOp,
6890 LLVM::UMinOp, LLVM::MaxNumOp, LLVM::MinNumOp,
6891 mlir::arith::MaxSIOp, mlir::arith::MinSIOp,
6892 mlir::arith::MaxUIOp, mlir::arith::MinUIOp,
6893 mlir::arith::MaximumFOp, mlir::arith::MinimumFOp>(op);
6894 };
6895
6896 // Pre-translate operations inside the region that compute e and d (e.g.,
6897 // GEP, loads for dereferencing Fortran pointers) but are not part of the
6898 // atomic compare-and-swap pattern (icmp/fcmp, select, and/or).
6899 //
6900 // 1) Validity: The OpenMP spec requires e and d to be evaluated before the
6901 // atomic operation, so emitting their computation here is correct.
6902 // 2) Memory effects: These ops only depend on values defined outside the
6903 // region. They cannot observe the block argument (%xval), which is the
6904 // value loaded atomically by cmpxchg and does not exist yet.
6905 // 3) Invariant enforcement: The `allOperandsMapped` check below skips any
6906 // op whose operands include the unmapped block argument, guaranteeing
6907 // only region-external-dependent ops are pre-translated.
6908 for (Operation &op : block.without_terminator()) {
6909 // Skip operations that form the atomic compare pattern — these are
6910 // not emitted as individual instructions but are analyzed below to
6911 // extract the comparison predicate, expected value (e), and desired
6912 // value (d) for generating a single cmpxchg/atomicrmw.
6913 if (isAtomicComparePatternOp(op))
6914 continue;
6915
6916 // Avoid translating ops that depend on the unmapped block argument.
6917 bool allOperandsMapped = llvm::all_of(op.getOperands(), [&](mlir::Value v) {
6918 return moduleTranslation.lookupValue(v) != nullptr;
6919 });
6920 if (!allOperandsMapped)
6921 continue;
6922
6923 if (failed(moduleTranslation.convertOperation(op, builder)))
6924 return atomicCompareOp.emitError(
6925 "failed to translate operation inside atomic compare region");
6926 }
6927
6928 // Look up a value that may have been pre-translated or defined outside the
6929 // region.
6930 auto materializeValue = [&](mlir::Value val) -> llvm::Value * {
6931 // Check if the value is already mapped (pre-translated or defined outside).
6932 if (llvm::Value *existing = moduleTranslation.lookupValue(val))
6933 return existing;
6934 // Fallback for a single LoadOp whose address is mapped but whose result
6935 // was not pre-translated.
6936 if (auto loadOp = val.getDefiningOp<LLVM::LoadOp>()) {
6937 if (loadOp->getParentRegion() == &region) {
6938 llvm::Value *loadAddr = moduleTranslation.lookupValue(loadOp.getAddr());
6939 if (!loadAddr)
6940 return nullptr;
6941 llvm::Type *loadType =
6942 moduleTranslation.convertType(loadOp.getResult().getType());
6943 return builder.CreateLoad(loadType, loadAddr);
6944 }
6945 }
6946 return nullptr;
6947 };
6948
6949 // Walk the region to extract comparison predicate, eVal, and dVal.
6950 // if (x == eVal) x = dVal
6951 llvm::omp::OMPAtomicCompareOp compareOp = llvm::omp::OMPAtomicCompareOp::EQ;
6952 llvm::Value *eVal = nullptr;
6953 llvm::Value *dVal = nullptr;
6954 bool isXBinopExpr = false;
6955
6956 // Check for a decomposed complex comparison pattern (extractvalue + fcmp +
6957 // and/or of the real/imaginary fields).
6959 bool isComplexPattern = cplx.isComplex;
6960 if (isComplexPattern) {
6961 if (cplx.isNE)
6962 // OrOp corresponds to NE, which is not a valid atomic compare op.
6963 return atomicCompareOp.emitError(
6964 "unsupported comparison predicate (NE) for complex atomic compare");
6965 compareOp = llvm::omp::OMPAtomicCompareOp::EQ;
6966 isXBinopExpr = cplx.isXBinopExpr;
6967 eVal = materializeValue(cplx.eAggregate);
6968 }
6969
6970 if (isComplexPattern) {
6971 // dVal from SelectOp or YieldOp.
6972 for (Operation &op : block.getOperations()) {
6973 if (auto selectOp = dyn_cast<LLVM::SelectOp>(op)) {
6974 dVal = materializeValue(selectOp.getTrueValue());
6975 break;
6976 }
6977 }
6978 if (!dVal) {
6979 auto yieldOp = cast<omp::YieldOp>(block.getTerminator());
6980 if (yieldOp.getResults().empty())
6981 return atomicCompareOp.emitError(
6982 "failed to extract desired value (d) from atomic compare region");
6983 dVal = materializeValue(yieldOp.getResults()[0]);
6984 }
6985
6986 llvm::Value *oldComplex = nullptr;
6987 llvm::Value *cmpOk = nullptr;
6988 llvm::AtomicOrdering failOrdering =
6989 getAtomicCompareFailureOrdering(atomicCompareOp, atomicOrdering);
6990 emitComplexAtomicCmpXchg(builder, llvmX, llvmXElementType, eVal, dVal,
6991 atomicOrdering, failOrdering,
6992 atomicCompareOp.getWeak(), oldComplex, cmpOk);
6993 (void)oldComplex;
6994 (void)cmpOk;
6995
6996 return success();
6997 } else {
6998 AtomicComparePatternInfo patternInfo;
6999 if (failed(extractAtomicComparePattern(block, materializeValue,
7000 atomicCompareOp, patternInfo)))
7001 return failure();
7002 compareOp = patternInfo.compareOp;
7003 eVal = patternInfo.eVal;
7004 dVal = patternInfo.dVal;
7005 isXBinopExpr = patternInfo.isXBinopExpr;
7006 isSigned = patternInfo.isSigned;
7007 }
7008
7009 if (!eVal)
7010 return atomicCompareOp.emitError(
7011 "failed to extract expected value (e) from atomic compare region");
7012 if (!dVal) {
7013 // Fall back to the yield operand.
7014 auto yieldOp = cast<omp::YieldOp>(block.getTerminator());
7015 if (yieldOp.getResults().empty())
7016 return atomicCompareOp.emitError(
7017 "failed to extract desired value (d) from atomic compare region");
7018 dVal = materializeValue(yieldOp.getResults()[0]);
7019 }
7020
7021 llvmAtomicX.IsSigned = isSigned;
7022
7023 llvm::OpenMPIRBuilder::AtomicOpValue vOpVal = {nullptr, nullptr, false,
7024 false};
7025 llvm::OpenMPIRBuilder::AtomicOpValue rOpVal = {nullptr, nullptr, false,
7026 false};
7027 llvm::OpenMPIRBuilder::LocationDescription ompLoc(builder);
7028
7029 bool isWeak = atomicCompareOp.getWeak();
7030
7031 bool savedHandleFPNegZero = ompBuilder->setHandleFPNegZero(true);
7032 llvm::AtomicOrdering failureOrdering =
7033 getAtomicCompareFailureOrdering(atomicCompareOp, atomicOrdering);
7034 llvm::OpenMPIRBuilder::InsertPointOrErrorTy afterIP =
7035 ompBuilder->createAtomicCompare(
7036 ompLoc, llvmAtomicX, vOpVal, rOpVal, eVal, dVal, atomicOrdering,
7037 compareOp, isXBinopExpr, /*IsPostfixUpdate=*/false,
7038 /*IsFailOnly=*/false, failureOrdering, isWeak);
7039 ompBuilder->setHandleFPNegZero(savedHandleFPNegZero);
7040
7041 if (failed(handleError(afterIP, *atomicCompareOp)))
7042 return failure();
7043
7044 builder.restoreIP(*afterIP);
7045 return success();
7046}
7047
7048static llvm::omp::Directive convertCancellationConstructType(
7049 omp::ClauseCancellationConstructType directive) {
7050 switch (directive) {
7051 case omp::ClauseCancellationConstructType::Loop:
7052 return llvm::omp::Directive::OMPD_for;
7053 case omp::ClauseCancellationConstructType::Parallel:
7054 return llvm::omp::Directive::OMPD_parallel;
7055 case omp::ClauseCancellationConstructType::Sections:
7056 return llvm::omp::Directive::OMPD_sections;
7057 case omp::ClauseCancellationConstructType::Taskgroup:
7058 return llvm::omp::Directive::OMPD_taskgroup;
7059 }
7060 llvm_unreachable("Unhandled cancellation construct type");
7061}
7062
7063static LogicalResult
7064convertOmpCancel(omp::CancelOp op, llvm::IRBuilderBase &builder,
7065 LLVM::ModuleTranslation &moduleTranslation) {
7066 if (failed(checkImplementationStatus(*op.getOperation())))
7067 return failure();
7068
7069 llvm::OpenMPIRBuilder::LocationDescription ompLoc(builder);
7070 llvm::OpenMPIRBuilder *ompBuilder = getOpenMPBuilder(moduleTranslation);
7071
7072 llvm::Value *ifCond = nullptr;
7073 if (Value ifVar = op.getIfExpr())
7074 ifCond = moduleTranslation.lookupValue(ifVar);
7075
7076 llvm::omp::Directive cancelledDirective =
7077 convertCancellationConstructType(op.getCancelDirective());
7078
7079 llvm::OpenMPIRBuilder::InsertPointOrErrorTy afterIP =
7080 ompBuilder->createCancel(ompLoc, ifCond, cancelledDirective);
7081
7082 if (failed(handleError(afterIP, *op.getOperation())))
7083 return failure();
7084
7085 builder.restoreIP(afterIP.get());
7086
7087 return success();
7088}
7089
7090static LogicalResult
7091convertOmpCancellationPoint(omp::CancellationPointOp op,
7092 llvm::IRBuilderBase &builder,
7093 LLVM::ModuleTranslation &moduleTranslation) {
7094 if (failed(checkImplementationStatus(*op.getOperation())))
7095 return failure();
7096
7097 llvm::OpenMPIRBuilder::LocationDescription ompLoc(builder);
7098 llvm::OpenMPIRBuilder *ompBuilder = getOpenMPBuilder(moduleTranslation);
7099
7100 llvm::omp::Directive cancelledDirective =
7101 convertCancellationConstructType(op.getCancelDirective());
7102
7103 llvm::OpenMPIRBuilder::InsertPointOrErrorTy afterIP =
7104 ompBuilder->createCancellationPoint(ompLoc, cancelledDirective);
7105
7106 if (failed(handleError(afterIP, *op.getOperation())))
7107 return failure();
7108
7109 builder.restoreIP(afterIP.get());
7110
7111 return success();
7112}
7113
7114/// Converts an OpenMP Threadprivate operation into LLVM IR using
7115/// OpenMPIRBuilder.
7116static LogicalResult
7117convertOmpThreadprivate(Operation &opInst, llvm::IRBuilderBase &builder,
7118 LLVM::ModuleTranslation &moduleTranslation) {
7119 llvm::OpenMPIRBuilder::LocationDescription ompLoc(builder);
7120 llvm::OpenMPIRBuilder *ompBuilder = getOpenMPBuilder(moduleTranslation);
7121 auto threadprivateOp = cast<omp::ThreadprivateOp>(opInst);
7122
7123 if (failed(checkImplementationStatus(opInst)))
7124 return failure();
7125
7126 Value symAddr = threadprivateOp.getSymAddr();
7127 auto *symOp = symAddr.getDefiningOp();
7128
7129 if (auto asCast = dyn_cast<LLVM::AddrSpaceCastOp>(symOp))
7130 symOp = asCast.getOperand().getDefiningOp();
7131
7132 if (!isa<LLVM::AddressOfOp>(symOp))
7133 return opInst.emitError("Addressing symbol not found");
7134 LLVM::AddressOfOp addressOfOp = dyn_cast<LLVM::AddressOfOp>(symOp);
7135
7136 LLVM::GlobalOp global =
7137 addressOfOp.getGlobal(moduleTranslation.symbolTable());
7138 llvm::GlobalValue *globalValue = moduleTranslation.lookupGlobal(global);
7139 llvm::Type *type = globalValue->getValueType();
7140 llvm::TypeSize typeSize = builder.getDataLayout().getTypeStoreSize(type);
7141 llvm::ConstantInt *size = builder.getInt64(typeSize.getFixedValue());
7142 llvm::Value *callInst = ompBuilder->createCachedThreadPrivate(
7143 ompLoc, globalValue, size, global.getSymName() + ".cache");
7144 moduleTranslation.mapValue(opInst.getResult(0), callInst);
7145
7146 return success();
7147}
7148
7149static llvm::OffloadEntriesInfoManager::OMPTargetDeviceClauseKind
7150convertToDeviceClauseKind(mlir::omp::DeclareTargetDeviceType deviceClause) {
7151 switch (deviceClause) {
7152 case mlir::omp::DeclareTargetDeviceType::host:
7153 return llvm::OffloadEntriesInfoManager::OMPTargetDeviceClauseHost;
7154 break;
7155 case mlir::omp::DeclareTargetDeviceType::nohost:
7156 return llvm::OffloadEntriesInfoManager::OMPTargetDeviceClauseNoHost;
7157 break;
7158 case mlir::omp::DeclareTargetDeviceType::any:
7159 return llvm::OffloadEntriesInfoManager::OMPTargetDeviceClauseAny;
7160 break;
7161 }
7162 llvm_unreachable("unhandled device clause");
7163}
7164
7165static llvm::OffloadEntriesInfoManager::OMPTargetGlobalVarEntryKind
7167 mlir::omp::DeclareTargetCaptureClause captureClause) {
7168 switch (captureClause) {
7169 case mlir::omp::DeclareTargetCaptureClause::to:
7170 return llvm::OffloadEntriesInfoManager::OMPTargetGlobalVarEntryTo;
7171 case mlir::omp::DeclareTargetCaptureClause::link:
7172 return llvm::OffloadEntriesInfoManager::OMPTargetGlobalVarEntryLink;
7173 case mlir::omp::DeclareTargetCaptureClause::enter:
7174 return llvm::OffloadEntriesInfoManager::OMPTargetGlobalVarEntryEnter;
7175 case mlir::omp::DeclareTargetCaptureClause::none:
7176 return llvm::OffloadEntriesInfoManager::OMPTargetGlobalVarEntryNone;
7177 }
7178 llvm_unreachable("unhandled capture clause");
7179}
7180
7182 Operation *op = value.getDefiningOp();
7183 if (auto addrCast = dyn_cast_if_present<LLVM::AddrSpaceCastOp>(op))
7184 op = addrCast->getOperand(0).getDefiningOp();
7185 if (auto addressOfOp = dyn_cast_if_present<LLVM::AddressOfOp>(op)) {
7186 auto modOp = addressOfOp->getParentOfType<mlir::ModuleOp>();
7187 return modOp.lookupSymbol(addressOfOp.getGlobalName());
7188 }
7189 return nullptr;
7190}
7191
7193 while (Operation *op = value.getDefiningOp()) {
7194 if (auto addrCast = dyn_cast_if_present<LLVM::AddrSpaceCastOp>(op))
7195 value = addrCast.getOperand();
7196 // Traces through hlfir.declare, fir.declare to reach the base address and
7197 // use for type lookup.
7198 else if (op->getName().getIdentifier() &&
7199 (op->getName().getIdentifier().str() == "hlfir.declare" ||
7200 op->getName().getIdentifier().str() == "fir.declare")) {
7201 if (op->getNumOperands() > 0)
7202 value = op->getOperand(0);
7203 else
7204 break;
7205 } else {
7206 break;
7207 }
7208 }
7209 return value;
7210}
7211
7212// Determine the LLVM type whose storage size should be allocated for an
7213// OpenMP allocate directive list item. Opaque pointers lose element type, so
7214// trace through declare wrappers to the underlying global or stack allocation.
7215static llvm::Type *
7217 LLVM::ModuleTranslation &moduleTranslation) {
7218 llvm::Type *llvmVarTy = moduleTranslation.convertType(var.getType());
7219 if (!llvmVarTy->isPointerTy())
7220 return llvmVarTy;
7221
7222 if (Operation *globalOp = getGlobalOpFromValue(baseVar))
7223 if (auto gop = dyn_cast<LLVM::GlobalOp>(globalOp))
7224 return moduleTranslation.convertType(gop.getGlobalType());
7225
7226 if (auto allocaOp =
7227 dyn_cast_if_present<LLVM::AllocaOp>(baseVar.getDefiningOp()))
7228 return moduleTranslation.convertType(allocaOp.getElemType());
7229
7230 if (llvm::Value *baseLlvm = moduleTranslation.lookupValue(baseVar))
7231 if (auto *allocaInst = dyn_cast<llvm::AllocaInst>(baseLlvm))
7232 return allocaInst->getAllocatedType();
7233
7234 return llvmVarTy;
7235}
7236
7237// For dynamically-sized stack allocations, compute the allocation size from
7238// the alloca's element count at runtime.
7239static std::optional<llvm::Value *> getDynamicAllocatedSize(
7240 Value var, Value baseVar, LLVM::ModuleTranslation &moduleTranslation,
7241 llvm::IRBuilderBase &builder, const llvm::DataLayout &dataLayout) {
7242 if (auto allocaOp =
7243 dyn_cast_if_present<LLVM::AllocaOp>(baseVar.getDefiningOp())) {
7244 if (Value arraySize = allocaOp.getArraySize()) {
7245 llvm::Type *elemTy =
7246 moduleTranslation.convertType(allocaOp.getElemType());
7247 llvm::Value *numElems = moduleTranslation.lookupValue(arraySize);
7248 if (!numElems->getType()->isIntegerTy(64))
7249 numElems = builder.CreateZExt(numElems, builder.getInt64Ty());
7250 uint64_t elemSize = dataLayout.getTypeAllocSize(elemTy).getFixedValue();
7251 return builder.CreateMul(numElems, builder.getInt64(elemSize));
7252 }
7253 }
7254 if (llvm::Value *baseLlvm = moduleTranslation.lookupValue(baseVar)) {
7255 if (auto *allocaInst = dyn_cast<llvm::AllocaInst>(baseLlvm)) {
7256 if (allocaInst->isArrayAllocation() &&
7257 !llvm::isa<llvm::ArrayType>(allocaInst->getAllocatedType())) {
7258 uint64_t elemSize =
7259 dataLayout.getTypeAllocSize(allocaInst->getAllocatedType())
7260 .getFixedValue();
7261 return builder.CreateMul(allocaInst->getArraySize(),
7262 builder.getInt64(elemSize));
7263 }
7264 }
7265 }
7266 return std::nullopt;
7267}
7268
7269static llvm::SmallString<64>
7270getDeclareTargetRefPtrSuffix(LLVM::GlobalOp globalOp,
7271 llvm::OpenMPIRBuilder &ompBuilder,
7272 llvm::vfs::FileSystem &vfs) {
7273 llvm::SmallString<64> suffix;
7274 llvm::raw_svector_ostream os(suffix);
7275 if (globalOp.getVisibility() == mlir::SymbolTable::Visibility::Private) {
7276 auto loc = globalOp->getLoc()->findInstanceOf<FileLineColLoc>();
7277 auto fileInfoCallBack = [&loc]() {
7278 return std::pair<std::string, uint64_t>(
7279 llvm::StringRef(loc.getFilename()), loc.getLine());
7280 };
7281
7282 os << llvm::format(
7283 "_%x",
7284 ompBuilder.getTargetEntryUniqueInfo(fileInfoCallBack, vfs).FileID);
7285 }
7286 os << "_decl_tgt_ref_ptr";
7287
7288 return suffix;
7289}
7290
7291static bool isDeclareTargetLink(Value value) {
7292 if (auto declareTargetGlobal =
7293 dyn_cast_if_present<omp::DeclareTargetInterface>(
7294 getGlobalOpFromValue(value))) {
7295 omp::DeclareTargetAttr declareTargetAttr =
7296 declareTargetGlobal.getDeclareTarget();
7297 if (declareTargetAttr && declareTargetAttr.getCaptureClause() ==
7298 omp::DeclareTargetCaptureClause::link)
7299 return true;
7300 }
7301 return false;
7302}
7303
7304static bool isDeclareTargetTo(Value value) {
7305 if (auto declareTargetGlobal =
7306 dyn_cast_if_present<omp::DeclareTargetInterface>(
7307 getGlobalOpFromValue(value))) {
7308 omp::DeclareTargetAttr declareTargetAttr =
7309 declareTargetGlobal.getDeclareTarget();
7310 if (declareTargetAttr && (declareTargetAttr.getCaptureClause() ==
7311 omp::DeclareTargetCaptureClause::to ||
7312 declareTargetAttr.getCaptureClause() ==
7313 omp::DeclareTargetCaptureClause::enter))
7314 return true;
7315 }
7316 return false;
7317}
7318
7319// Returns the reference pointer generated by the lowering of the declare
7320// target operation in cases where the link clause is used or the to clause is
7321// used in USM mode.
7322static llvm::Value *
7324 LLVM::ModuleTranslation &moduleTranslation) {
7325 llvm::OpenMPIRBuilder *ompBuilder = getOpenMPBuilder(moduleTranslation);
7326 if (auto gOp =
7327 dyn_cast_or_null<LLVM::GlobalOp>(getGlobalOpFromValue(value))) {
7328 // In this case, we must utilise the reference pointer generated by
7329 // the declare target operation, similar to Clang
7330 if (isDeclareTargetLink(value) ||
7331 (isDeclareTargetTo(value) &&
7332 ompBuilder->Config.hasRequiresUnifiedSharedMemory())) {
7334 gOp, *ompBuilder, moduleTranslation.getFileSystem());
7335
7336 if (gOp.getSymName().contains(suffix))
7337 return moduleTranslation.getLLVMModule()->getNamedValue(
7338 gOp.getSymName());
7339
7340 return moduleTranslation.getLLVMModule()->getNamedValue(
7341 (gOp.getSymName().str() + suffix.str()).str());
7342 }
7343 }
7344 return nullptr;
7345}
7346
7347namespace {
7348// Append customMappers information to existing MapInfosTy
7349struct MapInfosTy : llvm::OpenMPIRBuilder::MapInfosTy {
7350 SmallVector<Operation *, 4> Mappers;
7351
7352 /// Append arrays in \a CurInfo.
7353 void append(MapInfosTy &curInfo) {
7354 Mappers.append(curInfo.Mappers.begin(), curInfo.Mappers.end());
7355 llvm::OpenMPIRBuilder::MapInfosTy::append(curInfo);
7356 }
7357};
7358// A small helper structure to contain data gathered
7359// for map lowering and coalese it into one area and
7360// avoiding extra computations such as searches in the
7361// llvm module for lowered mapped variables or checking
7362// if something is declare target (and retrieving the
7363// value) more than neccessary.
7364struct MapInfoData : MapInfosTy {
7365 llvm::SmallVector<bool, 4> IsDeclareTarget;
7366 llvm::SmallVector<bool, 4> IsAMember;
7367 // Identify if mapping was added by mapClause or use_device clauses.
7368 llvm::SmallVector<bool, 4> IsAMapping;
7369 llvm::SmallVector<mlir::Operation *, 4> MapClause;
7370 llvm::SmallVector<llvm::Value *, 4> OriginalValue;
7371 // Stripped off array/pointer to get the underlying
7372 // element type
7373 llvm::SmallVector<llvm::Type *, 4> BaseType;
7374
7375 /// Append arrays in \a CurInfo.
7376 void append(MapInfoData &CurInfo) {
7377 IsDeclareTarget.append(CurInfo.IsDeclareTarget.begin(),
7378 CurInfo.IsDeclareTarget.end());
7379 MapClause.append(CurInfo.MapClause.begin(), CurInfo.MapClause.end());
7380 OriginalValue.append(CurInfo.OriginalValue.begin(),
7381 CurInfo.OriginalValue.end());
7382 BaseType.append(CurInfo.BaseType.begin(), CurInfo.BaseType.end());
7383 MapInfosTy::append(CurInfo);
7384 }
7385};
7386
7387enum class TargetDirectiveEnumTy : uint32_t {
7388 None = 0,
7389 Target = 1,
7390 TargetData = 2,
7391 TargetEnterData = 3,
7392 TargetExitData = 4,
7393 TargetUpdate = 5
7394};
7395
7396static TargetDirectiveEnumTy getTargetDirectiveEnumTyFromOp(Operation *op) {
7397 return llvm::TypeSwitch<Operation *, TargetDirectiveEnumTy>(op)
7398 .Case([](omp::TargetDataOp) { return TargetDirectiveEnumTy::TargetData; })
7399 .Case([](omp::TargetEnterDataOp) {
7400 return TargetDirectiveEnumTy::TargetEnterData;
7401 })
7402 .Case([&](omp::TargetExitDataOp) {
7403 return TargetDirectiveEnumTy::TargetExitData;
7404 })
7405 .Case([&](omp::TargetUpdateOp) {
7406 return TargetDirectiveEnumTy::TargetUpdate;
7407 })
7408 .Case([&](omp::TargetOp) { return TargetDirectiveEnumTy::Target; })
7409 .Default([&](Operation *op) { return TargetDirectiveEnumTy::None; });
7410}
7411} // namespace
7412
7413static uint64_t getArrayElementSizeInBits(LLVM::LLVMArrayType arrTy,
7414 DataLayout &dl) {
7415 if (auto nestedArrTy = llvm::dyn_cast_if_present<LLVM::LLVMArrayType>(
7416 arrTy.getElementType()))
7417 return getArrayElementSizeInBits(nestedArrTy, dl);
7418 return dl.getTypeSizeInBits(arrTy.getElementType());
7419}
7420
7421// The intent is to verify if the mapped data being passed is a
7422// pointer -> pointee that requires special handling in certain cases,
7423// e.g. applying the OMP_MAP_PTR_AND_OBJ map type.
7424//
7425// There may be a better way to verify this, but unfortunately with
7426// opaque pointers we lose the ability to easily check if something is
7427// a pointer whilst maintaining access to the underlying type.
7428static bool checkIfPointerMap(omp::MapInfoOp mapOp) {
7429 // If we have a varPtrPtr field assigned then the underlying type is a pointer
7430 if (mapOp.getVarPtrPtr())
7431 return true;
7432
7433 // If the map data is declare target with a link clause, then it's represented
7434 // as a pointer when we lower it to LLVM-IR even if at the MLIR level it has
7435 // no relation to pointers.
7436 if (isDeclareTargetLink(mapOp.getVarPtr()))
7437 return true;
7438
7439 return false;
7440}
7441
7442// A privatizeable attach map is a pointer/descriptor that is privatized and
7443// passed directly as a kernel argument (target_param) rather than undergoing
7444// the standard attach/parent mapping. These are handled specially in a couple
7445// of places in map lowering.
7446static bool isPrivatizeableAttachMap(omp::ClauseMapFlags mapType) {
7447 return bitEnumContainsAll(mapType, omp::ClauseMapFlags::priv |
7448 omp::ClauseMapFlags::target_param |
7449 omp::ClauseMapFlags::attach);
7450}
7451
7452// This function calculates the size to be offloaded for a specified type, given
7453// its associated map clause (which can contain bounds information which affects
7454// the total size), this size is calculated based on the underlying element type
7455// e.g. given a 1-D array of ints, we will calculate the size from the integer
7456// type * number of elements in the array. This size can be used in other
7457// calculations but is ultimately used as an argument to the OpenMP runtimes
7458// kernel argument structure which is generated through the combinedInfo data
7459// structures.
7460// This function is somewhat equivalent to Clang's getExprTypeSize inside of
7461// CGOpenMPRuntime.cpp.
7462static llvm::Value *getSizeInBytes(DataLayout &dl, const mlir::Type &type,
7463 Operation *clauseOp,
7464 llvm::Value *basePointer,
7465 llvm::Type *baseType,
7466 llvm::IRBuilderBase &builder,
7467 LLVM::ModuleTranslation &moduleTranslation) {
7468 if (auto memberClause =
7469 mlir::dyn_cast_if_present<mlir::omp::MapInfoOp>(clauseOp)) {
7470 // This calculates the size to transfer based on bounds and the underlying
7471 // element type, provided bounds have been specified (Fortran
7472 // pointers/allocatables/target and arrays that have sections specified fall
7473 // into this as well)
7474 if (!memberClause.getBounds().empty()) {
7475 llvm::Value *elementCount = builder.getInt64(1);
7476 for (auto bounds : memberClause.getBounds()) {
7477 if (auto boundOp = mlir::dyn_cast_if_present<mlir::omp::MapBoundsOp>(
7478 bounds.getDefiningOp())) {
7479 // The below calculation for the size to be mapped calculated from the
7480 // map.info's bounds is: (elemCount * [UB - LB] + 1), later we
7481 // multiply by the underlying element types byte size to get the full
7482 // size to be offloaded based on the bounds
7483 elementCount = builder.CreateMul(
7484 elementCount,
7485 builder.CreateAdd(
7486 builder.CreateSub(
7487 moduleTranslation.lookupValue(boundOp.getUpperBound()),
7488 moduleTranslation.lookupValue(boundOp.getLowerBound())),
7489 builder.getInt64(1)));
7490 }
7491 }
7492
7493 // utilising getTypeSizeInBits instead of getTypeSize as getTypeSize gives
7494 // the size in inconsistent byte or bit format.
7495 uint64_t underlyingTypeSzInBits = dl.getTypeSizeInBits(type);
7496 if (auto arrTy = llvm::dyn_cast_if_present<LLVM::LLVMArrayType>(type))
7497 underlyingTypeSzInBits = getArrayElementSizeInBits(arrTy, dl);
7498
7499 // The size in bytes x number of elements, the sizeInBytes stored is
7500 // the underyling types size, e.g. if ptr<i32>, it'll be the i32's
7501 // size, so we do some on the fly runtime math to get the size in
7502 // bytes from the extent (ub - lb) * sizeInBytes. NOTE: This may need
7503 // some adjustment for members with more complex types.
7504 llvm::Value *sizeCalc = builder.CreateMul(
7505 elementCount, builder.getInt64(underlyingTypeSzInBits / 8),
7506 "element_count");
7507
7508 // This is a part of a "complicated" bit of size calculation logic that is
7509 // in place to handle a couple of scenarios, one specific to Fortran and
7510 // the other a more general OpenMP issue. The other piece of the
7511 // calculation can be found as the final size calculation within the
7512 // processIndividualMap function. Ideally we would move it here, but due
7513 // to the complexity of calculating the final base address of some
7514 // constructs (required for a nullary check), it's left as the final step.
7515 // So, in the below 2 cases, the nullary check is in processIndividualMap
7516 // and the size equality check is here. The cases this modifications help
7517 // cover are:
7518 //
7519 // 1) If an argument has a null base pointer, then the size must be set to
7520 // 0 to avoid the runtime exploding/complaining about an illegal
7521 // pointer map. The size returning non-zero is feasible in certain
7522 // cases if for example someone has specified there own bounds/range.
7523 // 2) We wish to support a very specific OpenMP Fortran edge-case where a
7524 // size zero array can be legally presence checked and found to be on
7525 // device when it has been mapped. In these rare occasions the
7526 // allocatable/pointer will have a size of 1 allocated for the
7527 // underlying data, but this wall not be represented within the size of
7528 // the descriptor, so we get a non-nullary pointer and a size of 0,
7529 // allowing us to specify a size of 1 in these cases registering it on
7530 // the device mapping table as present.
7531 //
7532 // The default fall through case is just returning the size calculation
7533 // above, if we are not nullary and the size we calculate is non-zero,
7534 // which is basically any pointer type that is allocated in someway
7535 // (providing you are not running on a rare system that allows malloc's of
7536 // size 0 with whatever caveats that may come with).
7537 //
7538 // Later in the nullary check in processIndividualMap it just devolves to
7539 // selecting a size of 0 if we are nullary, if we are not, we will return
7540 // either 1 or the calculated size, depending on the outcome of this
7541 // select.
7542 if (checkIfPointerMap(memberClause)) {
7543 return builder.CreateSelect(
7544 builder.CreateICmpEQ(sizeCalc, builder.getInt64(0)),
7545 builder.getInt64(1), sizeCalc);
7546 }
7547
7548 return sizeCalc;
7549 }
7550 }
7551
7552 return builder.getInt64(dl.getTypeSizeInBits(type) / 8);
7553}
7554
7555// Convert the MLIR map flag set to the runtime map flag set for embedding
7556// in LLVM-IR. This is important as the two bit-flag lists do not correspond
7557// 1-to-1 as there's flags the runtime doesn't care about and vice versa.
7558// Certain flags are discarded here such as RefPtee and co.
7559static llvm::omp::OpenMPOffloadMappingFlags
7560convertClauseMapFlags(omp::ClauseMapFlags mlirFlags) {
7561 const bool hasExplicitMap =
7562 (mlirFlags & ~omp::ClauseMapFlags::is_device_ptr) !=
7563 omp::ClauseMapFlags::none;
7564
7565 llvm::omp::OpenMPOffloadMappingFlags mapType =
7566 llvm::omp::OpenMPOffloadMappingFlags::OMP_MAP_NONE;
7567
7568 if (bitEnumContainsAll(mlirFlags, omp::ClauseMapFlags::to))
7569 mapType |= llvm::omp::OpenMPOffloadMappingFlags::OMP_MAP_TO;
7570
7571 if (bitEnumContainsAll(mlirFlags, omp::ClauseMapFlags::from))
7572 mapType |= llvm::omp::OpenMPOffloadMappingFlags::OMP_MAP_FROM;
7573
7574 if (bitEnumContainsAll(mlirFlags, omp::ClauseMapFlags::always))
7575 mapType |= llvm::omp::OpenMPOffloadMappingFlags::OMP_MAP_ALWAYS;
7576
7577 if (bitEnumContainsAll(mlirFlags, omp::ClauseMapFlags::del))
7578 mapType |= llvm::omp::OpenMPOffloadMappingFlags::OMP_MAP_DELETE;
7579
7580 if (bitEnumContainsAll(mlirFlags, omp::ClauseMapFlags::return_param))
7581 mapType |= llvm::omp::OpenMPOffloadMappingFlags::OMP_MAP_RETURN_PARAM;
7582
7583 if (bitEnumContainsAll(mlirFlags, omp::ClauseMapFlags::priv))
7584 mapType |= llvm::omp::OpenMPOffloadMappingFlags::OMP_MAP_PRIVATE;
7585
7586 if (bitEnumContainsAll(mlirFlags, omp::ClauseMapFlags::literal))
7587 mapType |= llvm::omp::OpenMPOffloadMappingFlags::OMP_MAP_LITERAL;
7588
7589 if (bitEnumContainsAll(mlirFlags, omp::ClauseMapFlags::implicit))
7590 mapType |= llvm::omp::OpenMPOffloadMappingFlags::OMP_MAP_IMPLICIT;
7591
7592 if (bitEnumContainsAll(mlirFlags, omp::ClauseMapFlags::close))
7593 mapType |= llvm::omp::OpenMPOffloadMappingFlags::OMP_MAP_CLOSE;
7594
7595 if (bitEnumContainsAll(mlirFlags, omp::ClauseMapFlags::present))
7596 mapType |= llvm::omp::OpenMPOffloadMappingFlags::OMP_MAP_PRESENT;
7597
7598 if (bitEnumContainsAll(mlirFlags, omp::ClauseMapFlags::ompx_hold))
7599 mapType |= llvm::omp::OpenMPOffloadMappingFlags::OMP_MAP_OMPX_HOLD;
7600
7601 if (bitEnumContainsAll(mlirFlags, omp::ClauseMapFlags::attach))
7602 mapType |= llvm::omp::OpenMPOffloadMappingFlags::OMP_MAP_ATTACH;
7603
7604 if (bitEnumContainsAll(mlirFlags, omp::ClauseMapFlags::target_param))
7605 mapType |= llvm::omp::OpenMPOffloadMappingFlags::OMP_MAP_TARGET_PARAM;
7606
7607 if (bitEnumContainsAll(mlirFlags, omp::ClauseMapFlags::is_device_ptr)) {
7608 mapType |= llvm::omp::OpenMPOffloadMappingFlags::OMP_MAP_TARGET_PARAM;
7609 if (!hasExplicitMap)
7610 mapType |= llvm::omp::OpenMPOffloadMappingFlags::OMP_MAP_LITERAL;
7611 }
7612
7613 return mapType;
7614}
7615
7616static StringRef getMapClauseName(omp::MapInfoOp mapOp) {
7617 if (StringAttr name = mapOp.getNameAttr())
7618 return name.getValue();
7619 return {};
7620}
7621
7623 MapInfoData &mapData, SmallVectorImpl<Value> &mapVars,
7624 LLVM::ModuleTranslation &moduleTranslation, DataLayout &dl,
7625 llvm::IRBuilderBase &builder, ArrayRef<Value> useDevPtrOperands = {},
7626 ArrayRef<Value> useDevAddrOperands = {},
7627 ArrayRef<Value> hasDevAddrOperands = {}) {
7628
7629 auto checkRefPtrOrPteeMapWithAttach = [](omp::ClauseMapFlags mapType) {
7630 bool hasRefType =
7631 bitEnumContainsAll(mapType, omp::ClauseMapFlags::ref_ptr) ||
7632 bitEnumContainsAll(mapType, omp::ClauseMapFlags::ref_ptee);
7633 return hasRefType &&
7634 bitEnumContainsAll(mapType, omp::ClauseMapFlags::attach);
7635 };
7636
7637 auto checkIsAMember = [](const auto &mapVars, auto mapOp) {
7638 // Check if this is a member mapping and correctly assign that it is, if
7639 // it is a member of a larger object.
7640 // TODO: Need better handling of members, and distinguishing of members
7641 // that are implicitly allocated on device vs explicitly passed in as
7642 // arguments.
7643 // TODO: May require some further additions to support nested record
7644 // types, i.e. member maps that can have member maps.
7645 for (Value mapValue : mapVars) {
7646 auto map = cast<omp::MapInfoOp>(mapValue.getDefiningOp());
7647 for (auto member : map.getMembers())
7648 if (member == mapOp)
7649 return true;
7650 }
7651 return false;
7652 };
7653
7654 // Process MapOperands
7655 for (Value mapValue : mapVars) {
7656 auto mapOp = cast<omp::MapInfoOp>(mapValue.getDefiningOp());
7657 bool isAttachStyleMap =
7658 checkRefPtrOrPteeMapWithAttach(mapOp.getMapType()) ||
7659 isPrivatizeableAttachMap(mapOp.getMapType());
7660 Value offloadPtr = (mapOp.getVarPtrPtr() && !isAttachStyleMap)
7661 ? mapOp.getVarPtrPtr()
7662 : mapOp.getVarPtr();
7663 mapData.OriginalValue.push_back(moduleTranslation.lookupValue(offloadPtr));
7664 mapData.Pointers.push_back(
7665 isAttachStyleMap ? moduleTranslation.lookupValue(mapOp.getVarPtrPtr())
7666 : mapData.OriginalValue.back());
7667
7668 if (llvm::Value *refPtr =
7669 getRefPtrIfDeclareTarget(offloadPtr, moduleTranslation)) {
7670 mapData.IsDeclareTarget.push_back(true);
7671 mapData.BasePointers.push_back(refPtr);
7672 } else if (isDeclareTargetTo(offloadPtr)) {
7673 mapData.IsDeclareTarget.push_back(true);
7674 mapData.BasePointers.push_back(mapData.OriginalValue.back());
7675 } else { // regular mapped variable
7676 mapData.IsDeclareTarget.push_back(false);
7677 mapData.BasePointers.push_back(mapData.OriginalValue.back());
7678 }
7679
7680 // In every situation we currently have if we have a varPtrPtr present
7681 // we wish to utilise it's type for the base type, main cases are
7682 // currently Fortran descriptor base address maps and attach maps.
7683 mapData.BaseType.push_back(moduleTranslation.convertType(
7684 mapOp.getVarPtrPtr() ? mapOp.getVarPtrPtrType().value()
7685 : mapOp.getVarPtrType()));
7686
7687 // For the attach map cases, it's a little odd, as we effectively have to
7688 // utilise the base address (including all bounds offsets) for the pointer
7689 // field, the pointer address for the base address field, and the pointer
7690 // not the data (base addresses) size. So we end up with a mix of base
7691 // types and sizes we wish to insert here.
7692 mlir::Type sizeType = (isAttachStyleMap || !mapOp.getVarPtrPtr())
7693 ? mapOp.getVarPtrType()
7694 : mapOp.getVarPtrPtrType().value();
7695 mapData.Sizes.push_back(getSizeInBytes(
7696 dl, sizeType, isAttachStyleMap ? nullptr : mapOp,
7697 mapData.Pointers.back(), moduleTranslation.convertType(sizeType),
7698 builder, moduleTranslation));
7699 mapData.MapClause.push_back(mapOp.getOperation());
7700 mapData.Types.push_back(convertClauseMapFlags(mapOp.getMapType()));
7701 // TODO: set HasAttachPtr from Flang for pointee-storage entries.
7702 mapData.HasAttachPtr.push_back(false);
7703 mapData.Names.push_back(LLVM::createMappingInformation(
7704 mapOp.getLoc(), *getOpenMPBuilder(moduleTranslation),
7705 getMapClauseName(mapOp)));
7706 mapData.DevicePointers.push_back(llvm::OpenMPIRBuilder::DeviceInfoTy::None);
7707 if (mapOp.getMapperId())
7708 mapData.Mappers.push_back(
7710 mapOp, mapOp.getMapperIdAttr()));
7711 else
7712 mapData.Mappers.push_back(nullptr);
7713 mapData.IsAMapping.push_back(true);
7714 mapData.IsAMember.push_back(checkIsAMember(mapVars, mapOp));
7715 }
7716
7717 auto findMapInfo = [&mapData](llvm::Value *val,
7718 llvm::OpenMPIRBuilder::DeviceInfoTy devInfoTy,
7719 size_t memberCount) {
7720 unsigned index = 0;
7721 bool found = false;
7722 for (llvm::Value *basePtr : mapData.OriginalValue) {
7723 auto mapOp = cast<omp::MapInfoOp>(mapData.MapClause[index]);
7724 // TODO: Currently we define an equivalent mapping as
7725 // the same base pointer and an equivalent member count, but
7726 // that is a loose definition. We may have to extend to check
7727 // for other fields (varPtrPtr/individual members being mapped).
7728 // Note: Attach maps are not the same as a normal data transfer
7729 // they specify to the runtime to perform an attach map and they
7730 // (at least at the moment) are never something we would aim to
7731 // return in a use_dev_* clause, so they are skipped in terms of
7732 // duplicate maps.
7733 bool isAttachMap =
7734 (mapData.Types[index] &
7735 llvm::omp::OpenMPOffloadMappingFlags::OMP_MAP_ATTACH) ==
7736 llvm::omp::OpenMPOffloadMappingFlags::OMP_MAP_ATTACH;
7737 if (!isAttachMap && basePtr == val && mapData.IsAMapping[index] &&
7738 memberCount == mapOp.getMembers().size()) {
7739 found = true;
7740 mapData.Types[index] |=
7741 llvm::omp::OpenMPOffloadMappingFlags::OMP_MAP_RETURN_PARAM;
7742 mapData.DevicePointers[index] = devInfoTy;
7743 }
7744 index++;
7745 }
7746 return found;
7747 };
7748
7749 // Process useDevPtr(Addr)Operands
7750 auto addDevInfos = [&](const llvm::ArrayRef<Value> &useDevOperands,
7751 llvm::OpenMPIRBuilder::DeviceInfoTy devInfoTy) {
7752 for (Value mapValue : useDevOperands) {
7753 auto mapOp = cast<omp::MapInfoOp>(mapValue.getDefiningOp());
7754 Value offloadPtr =
7755 mapOp.getVarPtrPtr() ? mapOp.getVarPtrPtr() : mapOp.getVarPtr();
7756 llvm::Value *origValue = moduleTranslation.lookupValue(offloadPtr);
7757
7758 // Check if map info is already present for this entry.
7759 if (!findMapInfo(origValue, devInfoTy, mapOp.getMembers().size())) {
7760 mapData.OriginalValue.push_back(origValue);
7761 mapData.Pointers.push_back(mapData.OriginalValue.back());
7762 mapData.IsDeclareTarget.push_back(false);
7763 mapData.BasePointers.push_back(mapData.OriginalValue.back());
7764 mlir::Type baseTy = mapOp.getVarPtrPtr()
7765 ? mapOp.getVarPtrPtrType().value()
7766 : mapOp.getVarPtrType();
7767 mapData.BaseType.push_back(moduleTranslation.convertType(baseTy));
7768 mapData.Sizes.push_back(builder.getInt64(0));
7769 mapData.MapClause.push_back(mapOp.getOperation());
7770 mapData.Types.push_back(
7771 llvm::omp::OpenMPOffloadMappingFlags::OMP_MAP_RETURN_PARAM);
7772 // TODO: set HasAttachPtr from Flang for pointee-storage entries.
7773 mapData.HasAttachPtr.push_back(false);
7774 mapData.Names.push_back(LLVM::createMappingInformation(
7775 mapOp.getLoc(), *getOpenMPBuilder(moduleTranslation),
7776 getMapClauseName(mapOp)));
7777 mapData.DevicePointers.push_back(devInfoTy);
7778 mapData.Mappers.push_back(nullptr);
7779 mapData.IsAMapping.push_back(false);
7780 mapData.IsAMember.push_back(checkIsAMember(useDevOperands, mapOp));
7781 }
7782 }
7783 };
7784
7785 addDevInfos(useDevAddrOperands, llvm::OpenMPIRBuilder::DeviceInfoTy::Address);
7786 addDevInfos(useDevPtrOperands, llvm::OpenMPIRBuilder::DeviceInfoTy::Pointer);
7787
7788 for (Value mapValue : hasDevAddrOperands) {
7789 auto mapOp = cast<omp::MapInfoOp>(mapValue.getDefiningOp());
7790 Value offloadPtr =
7791 mapOp.getVarPtrPtr() ? mapOp.getVarPtrPtr() : mapOp.getVarPtr();
7792 llvm::Value *origValue = moduleTranslation.lookupValue(offloadPtr);
7793 auto mapType = convertClauseMapFlags(mapOp.getMapType());
7794 auto mapTypeAlways = llvm::omp::OpenMPOffloadMappingFlags::OMP_MAP_ALWAYS;
7795 bool isDevicePtr =
7796 (mapOp.getMapType() & omp::ClauseMapFlags::is_device_ptr) !=
7797 omp::ClauseMapFlags::none;
7798
7799 mapData.OriginalValue.push_back(origValue);
7800 mapData.BasePointers.push_back(origValue);
7801 mapData.Pointers.push_back(origValue);
7802 mapData.IsDeclareTarget.push_back(false);
7803
7804 mlir::Type baseTy = mapOp.getVarPtrPtr() ? mapOp.getVarPtrPtrType().value()
7805 : mapOp.getVarPtrType();
7806 mapData.BaseType.push_back(moduleTranslation.convertType(baseTy));
7807 mapData.Sizes.push_back(builder.getInt64(dl.getTypeSize(baseTy)));
7808
7809 mapData.MapClause.push_back(mapOp.getOperation());
7810 if (llvm::to_underlying(mapType & mapTypeAlways)) {
7811 // Descriptors are mapped with the ALWAYS flag, since they can get
7812 // rematerialized, so the address of the decriptor for a given object
7813 // may change from one place to another.
7814 mapData.Types.push_back(mapType);
7815 // TODO: set HasAttachPtr from Flang for pointee-storage entries.
7816 mapData.HasAttachPtr.push_back(false);
7817 // Technically it's possible for a non-descriptor mapping to have
7818 // both has-device-addr and ALWAYS, so lookup the mapper in case it
7819 // exists.
7820 if (mapOp.getMapperId()) {
7821 mapData.Mappers.push_back(
7823 mapOp, mapOp.getMapperIdAttr()));
7824 } else {
7825 mapData.Mappers.push_back(nullptr);
7826 }
7827 } else {
7828 // For is_device_ptr we need the map type to propagate so the runtime
7829 // can materialize the device-side copy of the pointer container.
7830 mapData.Types.push_back(
7831 isDevicePtr ? mapType
7832 : llvm::omp::OpenMPOffloadMappingFlags::OMP_MAP_LITERAL);
7833 // TODO: set HasAttachPtr from Flang for pointee-storage entries.
7834 mapData.HasAttachPtr.push_back(false);
7835 mapData.Mappers.push_back(nullptr);
7836 }
7837 mapData.Names.push_back(LLVM::createMappingInformation(
7838 mapOp.getLoc(), *getOpenMPBuilder(moduleTranslation),
7839 getMapClauseName(mapOp)));
7840 mapData.DevicePointers.push_back(
7841 isDevicePtr ? llvm::OpenMPIRBuilder::DeviceInfoTy::Pointer
7842 : llvm::OpenMPIRBuilder::DeviceInfoTy::Address);
7843 mapData.IsAMapping.push_back(false);
7844 mapData.IsAMember.push_back(checkIsAMember(hasDevAddrOperands, mapOp));
7845 }
7846}
7847
7848static int getMapDataMemberIdx(MapInfoData &mapData, omp::MapInfoOp memberOp) {
7849 auto *res = llvm::find(mapData.MapClause, memberOp);
7850 assert(res != mapData.MapClause.end() &&
7851 "MapInfoOp for member not found in MapData, cannot return index");
7852 return std::distance(mapData.MapClause.begin(), res);
7853}
7854
7856 omp::MapInfoOp mapInfo, bool first = true) {
7857 ArrayAttr indexAttr = mapInfo.getMembersIndexAttr();
7858 llvm::SmallVector<size_t> occludedChildren;
7859 llvm::sort(
7860 indices.begin(), indices.end(), [&](const size_t a, const size_t b) {
7861 // Bail early if we are asked to look at the same index. If we do not
7862 // bail early, we can end up mistakenly adding indices to
7863 // occludedChildren. This can occur with some types of libc++ hardening.
7864 if (a == b)
7865 return false;
7866
7867 auto memberIndicesA = cast<ArrayAttr>(indexAttr[a]);
7868 auto memberIndicesB = cast<ArrayAttr>(indexAttr[b]);
7869
7870 for (auto it : llvm::zip(memberIndicesA, memberIndicesB)) {
7871 int64_t aIndex = mlir::cast<IntegerAttr>(std::get<0>(it)).getInt();
7872 int64_t bIndex = mlir::cast<IntegerAttr>(std::get<1>(it)).getInt();
7873
7874 if (aIndex == bIndex)
7875 continue;
7876
7877 if (aIndex < bIndex)
7878 return first;
7879
7880 if (aIndex > bIndex)
7881 return !first;
7882 }
7883
7884 // Iterated up until the end of the smallest member and
7885 // they were found to be equal up to that point, so select
7886 // the member with the lowest index count, so the "parent"
7887 bool memberAParent = memberIndicesA.size() < memberIndicesB.size();
7888 if (memberAParent)
7889 occludedChildren.push_back(b);
7890 else
7891 occludedChildren.push_back(a);
7892 return memberAParent;
7893 });
7894
7895 for (auto v : occludedChildren)
7896 indices.erase(std::remove(indices.begin(), indices.end(), v),
7897 indices.end());
7898}
7899
7900static omp::MapInfoOp getFirstOrLastMappedMemberPtr(omp::MapInfoOp mapInfo,
7901 bool first) {
7902 ArrayAttr indexAttr = mapInfo.getMembersIndexAttr();
7903 // Only 1 member has been mapped, we can return it.
7904 if (indexAttr.size() == 1)
7905 return cast<omp::MapInfoOp>(mapInfo.getMembers()[0].getDefiningOp());
7906 llvm::SmallVector<size_t> indices(indexAttr.size());
7907 std::iota(indices.begin(), indices.end(), 0);
7908 sortMapIndices(indices, mapInfo, first);
7909 return llvm::cast<omp::MapInfoOp>(
7910 mapInfo.getMembers()[indices.front()].getDefiningOp());
7911}
7912
7913/// This function calculates the array/pointer offset for map data provided
7914/// with bounds operations, e.g. when provided something like the following:
7915///
7916/// Fortran
7917/// map(tofrom: array(2:5, 3:2))
7918///
7919/// We must calculate the initial pointer offset to pass across, this function
7920/// performs this using bounds.
7921///
7922/// TODO/WARNING: This only supports Fortran's column major indexing currently
7923/// as is noted in the note below and comments in the function, we must extend
7924/// this function when we add a C++ frontend.
7925/// NOTE: which while specified in row-major order it currently needs to be
7926/// flipped for Fortran's column order array allocation and access (as
7927/// opposed to C++'s row-major, hence the backwards processing where order is
7928/// important). This is likely important to keep in mind for the future when
7929/// we incorporate a C++ frontend, both frontends will need to agree on the
7930/// ordering of generated bounds operations (one may have to flip them) to
7931/// make the below lowering frontend agnostic. The offload size
7932/// calcualtion may also have to be adjusted for C++.
7933static std::vector<llvm::Value *>
7935 llvm::IRBuilderBase &builder, bool isArrayTy,
7936 OperandRange bounds, bool &isByteOffset) {
7937 std::vector<llvm::Value *> idx;
7938 isByteOffset = false;
7939 // There's no bounds to calculate an offset from, we can safely
7940 // ignore and return no indices.
7941 if (bounds.empty())
7942 return idx;
7943
7944 // If we have an array type, then we have its type so can treat it as a
7945 // normal GEP instruction where the bounds operations are simply indexes
7946 // into the array. We currently do reverse order of the bounds, which
7947 // I believe leans more towards Fortran's column-major in memory.
7948 if (isArrayTy) {
7949 idx.push_back(builder.getInt64(0));
7950 for (int i = bounds.size() - 1; i >= 0; --i) {
7951 if (auto boundOp = dyn_cast_if_present<omp::MapBoundsOp>(
7952 bounds[i].getDefiningOp())) {
7953 idx.push_back(moduleTranslation.lookupValue(boundOp.getLowerBound()));
7954 }
7955 }
7956 } else {
7957 // Check if Fortran descriptors provide strides in bytes
7958 llvm::Value *offset = builder.getInt64(0);
7959 for (Value bound : bounds) {
7960 auto boundOp =
7961 dyn_cast_if_present<omp::MapBoundsOp>(bound.getDefiningOp());
7962 if (!boundOp || !boundOp.getStride())
7963 continue;
7964 // Fortran descriptors provide strides in bytes; when that's the case the
7965 // accumulated offset is a byte offset and must be consumed with a byte
7966 // (i8) GEP at the call site to avoid double-scaling by the element size.
7967 isByteOffset = boundOp.getStrideInBytes();
7968 }
7969 if (isByteOffset) {
7970 for (Value bound : bounds) {
7971 auto boundOp =
7972 dyn_cast_if_present<omp::MapBoundsOp>(bound.getDefiningOp());
7973 if (!boundOp || !boundOp.getStride())
7974 continue;
7975 // If we do not have an array type, but we have bounds, then we're
7976 // dealing with a pointer that's being treated like an array
7977 // and we have the underlying type e.g. an i32, or f64 etc,
7978 // e.g. a fortran descriptor base address (pointer pointing to
7979 // the actual data) and we know that the offset stride is expressed
7980 // in bytes, so we must calculate the offset to the first mapped
7981 // element as a single linear index into that data.
7982 //
7983 // Each bound carries the stride between consecutive elements along its
7984 // dimension, so the linear offset to the section's origin is:
7985 //
7986 // offset += lower_bound[d] * stride[d]
7987 llvm::Value *lb =
7988 moduleTranslation.lookupValue(boundOp.getLowerBound());
7989 llvm::Value *stride =
7990 moduleTranslation.lookupValue(boundOp.getStride());
7991 offset = builder.CreateAdd(offset, builder.CreateMul(lb, stride));
7992 }
7993 idx.push_back(offset);
7994 } else {
7995 for (int i = bounds.size() - 1; i >= 0; --i) {
7996 if (auto boundOp = dyn_cast_if_present<omp::MapBoundsOp>(
7997 bounds[i].getDefiningOp())) {
7998 // If the stride in bytes is unknown, so we must calculate the
7999 // offset using a single index which the following loop attempts to
8000 // compute using the standard column-major algorithm e.g for a 3D
8001 // array:
8002 //
8003 // ((((c_idx * b_len) + b_idx) * a_len) + a_idx)
8004 //
8005 // It is of note that it's doing column-major rather than row-major at
8006 // the moment, but having a way for the frontend to indicate which
8007 // major format to use or standardizing/canonicalizing the order of
8008 // the bounds to compute the offset may be useful in the future when
8009 // there's other frontends with different formats.
8010 if (i == ((int)bounds.size() - 1))
8011 idx.emplace_back(
8012 moduleTranslation.lookupValue(boundOp.getLowerBound()));
8013 else
8014 idx.back() = builder.CreateAdd(
8015 builder.CreateMul(idx.back(), moduleTranslation.lookupValue(
8016 boundOp.getExtent())),
8017 moduleTranslation.lookupValue(boundOp.getLowerBound()));
8018 }
8019 }
8020 }
8021 }
8022
8023 return idx;
8024}
8025
8027 llvm::transform(values, std::back_inserter(ints), [](Attribute value) {
8028 return cast<IntegerAttr>(value).getInt();
8029 });
8030}
8031
8032// Gathers members that are overlapping in the parent, excluding members that
8033// themselves overlap, keeping the top-most (closest to parents level) map.
8034static void
8036 omp::MapInfoOp parentOp) {
8037 // No members mapped, no overlaps.
8038 if (parentOp.getMembers().empty())
8039 return;
8040
8041 // Single member, we can insert and return early.
8042 if (parentOp.getMembers().size() == 1) {
8043 overlapMapDataIdxs.push_back(0);
8044 return;
8045 }
8046
8047 ArrayAttr indexAttr = parentOp.getMembersIndexAttr();
8048 size_t numMembers = indexAttr.size();
8049
8050 // Pre-convert all member indices to integer arrays for efficient comparison.
8051 llvm::SmallVector<llvm::SmallVector<int64_t>> memberIndices(numMembers);
8052 for (auto [i, indicesAttr] : llvm::enumerate(indexAttr))
8053 getAsIntegers(cast<ArrayAttr>(indicesAttr), memberIndices[i]);
8054
8055 // For each member, check if it's superseded by another (shorter prefix)
8056 // member. If member j's indices are a prefix of member i's indices, then
8057 // i is a child of j and should be skipped. e.g. if member [0] is mapped,
8058 // we skip members [0,1], [0,2], etc.
8059 llvm::SmallDenseSet<size_t> skipIndices;
8060 for (size_t i = 0; i < numMembers; ++i) {
8061 const auto &iIndices = memberIndices[i];
8062 for (size_t j = 0; j < numMembers; ++j) {
8063 if (i == j)
8064 continue;
8065 const auto &jIndices = memberIndices[j];
8066 // If j's indices are a strict prefix of i's indices, skip i
8067 if (jIndices.size() < iIndices.size() &&
8068 std::equal(jIndices.begin(), jIndices.end(), iIndices.begin())) {
8069 skipIndices.insert(i);
8070 break; // No need to check other potential parents
8071 }
8072 }
8073 }
8074
8075 // Collect indices of members that are not superseded by a parent.
8076 for (size_t i = 0; i < numMembers; ++i)
8077 if (!skipIndices.contains(i))
8078 overlapMapDataIdxs.push_back(i);
8079}
8080
8081/// Describe a bounded update as a set of contiguous pieces. Bounds follow the
8082/// dialect's normalized fastest-to-slowest varying order, which matches
8083/// Fortran's column-major dimension order. Frontends for row-major languages
8084/// such as C/C++ must normalize their source dimensions to this order.
8085/// OpenMPIRBuilder reverses the vectors when emitting the runtime descriptor,
8086/// which uses byte offsets and strides with the slowest varying dimension
8087/// first.
8089 llvm::IRBuilderBase &builder,
8090 MapInfoData &mapData, size_t mapDataIdx,
8091 MapInfosTy &combinedInfo) {
8092 auto mapOp = cast<omp::MapInfoOp>(mapData.MapClause[mapDataIdx]);
8093 if (mapOp.getBounds().empty() || mapOp.getMapperId() ||
8094 mapOp->getParentOfType<omp::DeclareMapperOp>() ||
8095 bitEnumContainsAll(mapOp.getMapType(), omp::ClauseMapFlags::attach))
8096 return;
8097
8098 llvm::Type *elementType = mapData.BaseType[mapDataIdx];
8099 // Bounds extents may be absent, and a scalar subscript has extent one.
8100 // Preserve the full source shape: for a(4,5), a(2,:) still needs a
8101 // second-dimension stride of four elements.
8102 SmallVector<uint64_t> arrayExtents;
8103 while (auto *arrayType = dyn_cast<llvm::ArrayType>(elementType)) {
8104 arrayExtents.push_back(arrayType->getNumElements());
8105 elementType = arrayType->getElementType();
8106 }
8107 llvm::Value *elementSize = builder.getInt64(
8108 builder.GetInsertBlock()->getModule()->getDataLayout().getTypeAllocSize(
8109 elementType));
8110
8111 // Include a byte dimension so that a non-unit descriptor stride in the
8112 // innermost array dimension still transfers one element at a time.
8113 llvm::OpenMPIRBuilder::MapValuesArrayTy offsets{builder.getInt64(0)};
8114 llvm::OpenMPIRBuilder::MapValuesArrayTy counts{elementSize};
8115 llvm::OpenMPIRBuilder::MapValuesArrayTy strides{builder.getInt64(1)};
8116 llvm::Value *sourceStride = elementSize;
8117 llvm::Value *contiguousSize = elementSize;
8118 // Unknown descriptor strides conservatively use a descriptor. The runtime
8119 // merges contiguous dimensions from their actual values.
8120 bool isContiguous = true;
8121 for (auto [dim, bound] : llvm::enumerate(mapOp.getBounds())) {
8122 auto bounds = cast<omp::MapBoundsOp>(bound.getDefiningOp());
8123 auto getInt64 = [&](Value value) {
8124 return builder.CreateSExtOrTrunc(moduleTranslation.lookupValue(value),
8125 builder.getInt64Ty());
8126 };
8127 llvm::Value *lower = bounds.getLowerBound()
8128 ? getInt64(bounds.getLowerBound())
8129 : builder.getInt64(0);
8130 llvm::Value *count = builder.CreateAdd(
8131 builder.CreateSub(getInt64(bounds.getUpperBound()), lower),
8132 builder.getInt64(1));
8133 count =
8134 builder.CreateSelect(builder.CreateICmpSGT(count, builder.getInt64(0)),
8135 count, builder.getInt64(0));
8136 llvm::Value *stride = sourceStride;
8137 if (bounds.getStrideInBytes() && bounds.getStride())
8138 stride = getInt64(bounds.getStride());
8139 else if (arrayExtents.empty() && bounds.getStride())
8140 stride = builder.CreateMul(getInt64(bounds.getStride()), elementSize);
8141 offsets.push_back(builder.CreateMul(lower, stride));
8142 counts.push_back(count);
8143 strides.push_back(stride);
8144 isContiguous &= stride == contiguousSize;
8145 contiguousSize = builder.CreateMul(contiguousSize, count);
8146
8147 // Static array types carry the full source shape, including dimensions
8148 // selected with scalar subscripts. Otherwise the frontend supplies the
8149 // physical stride in elements (or descriptor bytes) for every dimension.
8150 if (dim < arrayExtents.size())
8151 sourceStride = builder.CreateMul(
8152 sourceStride,
8153 builder.getInt64(arrayExtents[arrayExtents.size() - dim - 1]));
8154 else if (bounds.getExtent())
8155 sourceStride =
8156 builder.CreateMul(sourceStride, getInt64(bounds.getExtent()));
8157 }
8158 if (isContiguous)
8159 return;
8160
8161 llvm::Value *base = mapData.OriginalValue[mapDataIdx];
8162 if (mapOp.getVarPtrPtr())
8163 base = builder.CreateLoad(builder.getPtrTy(), base);
8164 // Absent optional arrays and unallocated descriptors must not issue
8165 // transfers, including sections with explicit nonempty bounds.
8166 counts[1] = builder.CreateSelect(builder.CreateIsNull(base),
8167 builder.getInt64(0), counts[1]);
8168 // The descriptor offsets already locate the first selected element. The
8169 // runtime needs the pointee base, not the descriptor or a section address.
8170 combinedInfo.BasePointers.back() = base;
8171 combinedInfo.Types.back() |=
8172 llvm::omp::OpenMPOffloadMappingFlags::OMP_MAP_NON_CONTIG;
8173 auto &nonContig = combinedInfo.NonContigInfo;
8174 nonContig.IsNonContiguous = true;
8175 nonContig.Dims.resize(combinedInfo.Types.size(), 1);
8176 nonContig.Dims.back() = counts.size();
8177 nonContig.Offsets.push_back(std::move(offsets));
8178 nonContig.Counts.push_back(std::move(counts));
8179 nonContig.Strides.push_back(std::move(strides));
8180}
8181
8182/// This function handles the insertion of a single item of map data from
8183/// MapInfoData into the OMPIRBuilder's MapInfo list. Utilising this function
8184/// means the map being inserted can be treated as a non-parent map entity,
8185/// if the memberOfFlag is set then the map being inserted is treated as
8186/// a member map of a larger entity. The insertion into the MapInfo list of
8187/// the OMPIRBuilder can vary based on a number of factors, such as if it's
8188/// a ref_ptr or ref_ptee map, if it's a member of a record, what construct
8189/// the map belongs to and the various map type bit flags that are set for
8190/// the map.
8192 LLVM::ModuleTranslation &moduleTranslation, llvm::IRBuilderBase &builder,
8193 llvm::OpenMPIRBuilder &ompBuilder, MapInfoData &mapData, size_t mapDataIdx,
8194 MapInfosTy &combinedInfo, TargetDirectiveEnumTy targetDirective,
8195 llvm::omp::OpenMPOffloadMappingFlags memberOfFlag =
8196 llvm::omp::OpenMPOffloadMappingFlags::OMP_MAP_NONE,
8197 bool isTargetParam = true, int mapDataParentIdx = -1) {
8198 auto mapFlag = mapData.Types[mapDataIdx];
8199 auto mapInfoOp = llvm::cast<omp::MapInfoOp>(mapData.MapClause[mapDataIdx]);
8200
8201 bool isPtrTy = checkIfPointerMap(mapInfoOp);
8202 bool isAttachMap = ((convertClauseMapFlags(mapInfoOp.getMapType()) &
8203 llvm::omp::OpenMPOffloadMappingFlags::OMP_MAP_ATTACH) ==
8204 llvm::omp::OpenMPOffloadMappingFlags::OMP_MAP_ATTACH);
8205
8206 // Declare target variables are not passed to the kernel, and for the moment
8207 // attach maps are not passed to the kernel. However, it is possible to create
8208 // attach maps that transfer data and thus can be kernel arguments, but our
8209 // existing frontend does not do this.
8210 if (isTargetParam &&
8211 (targetDirective == TargetDirectiveEnumTy::Target &&
8212 !mapData.IsDeclareTarget[mapDataIdx]) &&
8213 !isAttachMap)
8214 mapFlag |= llvm::omp::OpenMPOffloadMappingFlags::OMP_MAP_TARGET_PARAM;
8215
8216 if (mapInfoOp.getMapCaptureType() == omp::VariableCaptureKind::ByCopy &&
8217 !isPtrTy)
8218 mapFlag |= llvm::omp::OpenMPOffloadMappingFlags::OMP_MAP_LITERAL;
8219
8220 // If we have a pointer and it's part of a MEMBER_OF mapping we do not apply
8221 // MEMBER_OF, as the runtime currently has a work-around that utilises
8222 // MEMBER_OF to prevent reference updating in certain scenarios instead of
8223 // target_param. However, this causes a noticeable issue in cases where we
8224 // map some data (Fortran descriptor primarily at the moment), alter it on
8225 // the host, and then expect it to not be updated in a subsequent implicit map
8226 // (such as an implicit map on a target).
8227 if (memberOfFlag != llvm::omp::OpenMPOffloadMappingFlags::OMP_MAP_NONE) {
8228 if (!isPtrTy && !isAttachMap)
8229 ompBuilder.setCorrectMemberOfFlag(mapFlag, memberOfFlag);
8230
8231 // The return parameter should be the over-riding parent in cases where we
8232 // have a return parameter that is echoed to all members, the main case of
8233 // this currently is with fortran descriptors. It may need more finessing
8234 // for C/C++ in the future or descriptors that are members of derived
8235 // types.
8236 mapFlag &= ~llvm::omp::OpenMPOffloadMappingFlags::OMP_MAP_RETURN_PARAM;
8237 }
8238
8239 // We apply MAP_PTR_AND_OBJ when within a declare mapper object as it enforces
8240 // MEMBER_OF mappings on maps that are passed the initial nesting depth, which
8241 // includes pointed to data and attach members, both of which are technically
8242 // not part of the main object. This has the side effect of causing early
8243 // map-backs in certain cases where an implicit declare mapper has been
8244 // emitted for a target region. Applying MAP_PTR_AND_OBJ in these situations
8245 // circumvents this.
8246 if (isPtrTy && !isAttachMap && mapData.IsDeclareTarget[mapDataIdx])
8247 mapFlag |= llvm::omp::OpenMPOffloadMappingFlags::OMP_MAP_PTR_AND_OBJ;
8248
8249 // if we're provided a mapDataParentIdx, then the data being mapped is
8250 // part of a larger object (in a parent <-> member mapping) and in this
8251 // case our BasePointer should be the parent. Except in the edge case
8252 // where we are mapping pointee data, where we try staying close to
8253 // what Clang currently does and utilise the regular base pointer of the
8254 // data.
8255 bool isRefPtee =
8256 !bitEnumContainsAll(mapInfoOp.getMapType(),
8257 omp::ClauseMapFlags::ref_ptr) &&
8258 bitEnumContainsAll(mapInfoOp.getMapType(), omp::ClauseMapFlags::ref_ptee);
8259 bool isRefPtrPtee = bitEnumContainsAll(mapInfoOp.getMapType(),
8260 omp::ClauseMapFlags::ref_ptr |
8261 omp::ClauseMapFlags::ref_ptee);
8262
8263 if (!mapInfoOp->getParentOfType<omp::DeclareMapperOp>() &&
8264 mapDataParentIdx >= 0 && !(isRefPtee || (isRefPtrPtee && isPtrTy))) {
8265 combinedInfo.BasePointers.emplace_back(
8266 mapData.BasePointers[mapDataParentIdx]);
8267 } else {
8268 combinedInfo.BasePointers.emplace_back(mapData.BasePointers[mapDataIdx]);
8269 }
8270
8271 combinedInfo.Pointers.emplace_back(mapData.Pointers[mapDataIdx]);
8272 combinedInfo.DevicePointers.emplace_back(
8273 memberOfFlag != llvm::omp::OpenMPOffloadMappingFlags::OMP_MAP_NONE
8274 ? llvm::OpenMPIRBuilder::DeviceInfoTy::None
8275 : mapData.DevicePointers[mapDataIdx]);
8276 combinedInfo.Mappers.emplace_back(mapData.Mappers[mapDataIdx]);
8277 combinedInfo.Names.emplace_back(mapData.Names[mapDataIdx]);
8278 combinedInfo.Types.emplace_back(mapFlag);
8279 // TODO: set HasAttachPtr from Flang for pointee-storage entries.
8280 combinedInfo.HasAttachPtr.emplace_back(false);
8281 // A privatized attach map needs storage for the pointer or descriptor even
8282 // when its pointee is null. Its size describes that storage, not the pointee,
8283 // and is needed by the runtime for corresponding-pointer-initialization.
8284 combinedInfo.Sizes.emplace_back(
8285 isPtrTy && !isPrivatizeableAttachMap(mapInfoOp.getMapType())
8286 ? builder.CreateSelect(
8287 builder.CreateIsNull(mapData.Pointers[mapDataIdx]),
8288 builder.getInt64(0), mapData.Sizes[mapDataIdx])
8289 : mapData.Sizes[mapDataIdx]);
8290 if (targetDirective == TargetDirectiveEnumTy::TargetUpdate)
8291 addNonContiguousUpdate(moduleTranslation, builder, mapData, mapDataIdx,
8292 combinedInfo);
8293}
8294
8295// This creates two insertions into the MapInfosTy data structure for the
8296// "parent" of a set of members, (usually a container e.g.
8297// class/structure/derived type) when subsequent members have also been
8298// explicitly mapped on the same map clause. Certain types, such as Fortran
8299// descriptors are mapped like this as well, however, the members are
8300// implicit as far as a user is concerned, but we must explicitly map them
8301// internally.
8302//
8303// This function also returns the memberOfFlag for this particular parent,
8304// which is utilised in subsequent member mappings (by modifying there map type
8305// with it) to indicate that a member is part of this parent and should be
8306// treated by the runtime as such. Important to achieve the correct mapping.
8307//
8308// This function borrows a lot from Clang's emitCombinedEntry function
8309// inside of CGOpenMPRuntime.cpp
8311 LLVM::ModuleTranslation &moduleTranslation, llvm::IRBuilderBase &builder,
8312 llvm::OpenMPIRBuilder &ompBuilder, DataLayout &dl, MapInfosTy &combinedInfo,
8313 MapInfoData &mapData, uint64_t mapDataIndex,
8314 llvm::omp::OpenMPOffloadMappingFlags memberOfFlag,
8315 TargetDirectiveEnumTy targetDirective) {
8316 using MapFlags = llvm::omp::OpenMPOffloadMappingFlags;
8317 assert(!ompBuilder.Config.isTargetDevice() &&
8318 "function only supported for host device codegen");
8319 auto parentClause =
8320 llvm::cast<omp::MapInfoOp>(mapData.MapClause[mapDataIndex]);
8321 auto *parentMapper = mapData.Mappers[mapDataIndex];
8322
8323 // Map the first segment of the parent. If a user-defined mapper is attached,
8324 // include the parent's to/from-style bits (and common modifiers) in this
8325 // base entry so the mapper receives correct copy semantics via its 'type'
8326 // parameter. Also keep TARGET_PARAM when required for kernel arguments.
8327 MapFlags baseFlag = (targetDirective == TargetDirectiveEnumTy::Target &&
8328 !mapData.IsDeclareTarget[mapDataIndex])
8329 ? MapFlags::OMP_MAP_TARGET_PARAM
8330 : MapFlags::OMP_MAP_NONE;
8331
8332 if (parentMapper) {
8333 // Preserve relevant map-type bits from the parent clause. These include
8334 // the copy direction (TO/FROM), as well as commonly used modifiers that
8335 // should be visible to the mapper for correct behaviour.
8336 MapFlags parentFlags = mapData.Types[mapDataIndex];
8337 MapFlags preserve = MapFlags::OMP_MAP_TO | MapFlags::OMP_MAP_FROM |
8338 MapFlags::OMP_MAP_ALWAYS | MapFlags::OMP_MAP_CLOSE |
8339 MapFlags::OMP_MAP_PRESENT |
8340 MapFlags::OMP_MAP_OMPX_HOLD |
8341 MapFlags::OMP_MAP_IMPLICIT;
8342 baseFlag |= (parentFlags & preserve);
8343 } else {
8344 MapFlags parentFlags = mapData.Types[mapDataIndex];
8345 MapFlags preserve = MapFlags::OMP_MAP_TO | MapFlags::OMP_MAP_FROM |
8346 MapFlags::OMP_MAP_PRESENT |
8347 MapFlags::OMP_MAP_RETURN_PARAM |
8348 MapFlags::OMP_MAP_IMPLICIT;
8349 baseFlag |= (parentFlags & preserve);
8350 }
8351
8352 combinedInfo.Types.emplace_back(baseFlag);
8353 // TODO: set HasAttachPtr from Flang for pointee-storage entries.
8354 combinedInfo.HasAttachPtr.emplace_back(false);
8355 combinedInfo.DevicePointers.emplace_back(
8356 mapData.DevicePointers[mapDataIndex]);
8357 // Only attach the mapper to the base entry when we are mapping the whole
8358 // parent. Combined/segment entries must not carry a mapper; otherwise the
8359 // mapper can be invoked with a partial size, which is undefined behaviour.
8360 combinedInfo.Mappers.emplace_back(
8361 parentMapper && !parentClause.getPartialMap() ? parentMapper : nullptr);
8362 combinedInfo.Names.emplace_back(LLVM::createMappingInformation(
8363 mapData.MapClause[mapDataIndex]->getLoc(), ompBuilder,
8364 getMapClauseName(cast<omp::MapInfoOp>(mapData.MapClause[mapDataIndex]))));
8365 combinedInfo.BasePointers.emplace_back(mapData.BasePointers[mapDataIndex]);
8366
8367 // Calculate size of the parent object being mapped based on the
8368 // addresses at runtime, highAddr - lowAddr = size. This of course
8369 // doesn't factor in allocated data like pointers, hence the further
8370 // processing of members specified by users, or in the case of
8371 // Fortran pointers and allocatables, the mapping of the pointed to
8372 // data by the descriptor (which itself, is a structure containing
8373 // runtime information on the dynamically allocated data).
8374 llvm::Value *lowAddr, *highAddr;
8375 if (!parentClause.getPartialMap()) {
8376 lowAddr = builder.CreatePointerCast(mapData.Pointers[mapDataIndex],
8377 builder.getPtrTy());
8378 highAddr = builder.CreatePointerCast(
8379 builder.CreateConstGEP1_32(mapData.BaseType[mapDataIndex],
8380 mapData.Pointers[mapDataIndex], 1),
8381 builder.getPtrTy());
8382 combinedInfo.Pointers.emplace_back(mapData.Pointers[mapDataIndex]);
8383 } else {
8384 auto mapOp = dyn_cast<omp::MapInfoOp>(mapData.MapClause[mapDataIndex]);
8385 int firstMemberIdx = getMapDataMemberIdx(
8386 mapData, getFirstOrLastMappedMemberPtr(mapOp, true));
8387 lowAddr = builder.CreatePointerCast(mapData.BasePointers[firstMemberIdx],
8388 builder.getPtrTy());
8389
8390 int lastMemberIdx = getMapDataMemberIdx(
8391 mapData, getFirstOrLastMappedMemberPtr(mapOp, false));
8392 auto lastMemberMapInfo =
8393 cast<omp::MapInfoOp>(mapData.MapClause[lastMemberIdx]);
8394
8395 // NOTE: Currently, for RefPtee the BaseType is set to the varPtrPtr field,
8396 // which is the pointer datas type and not the member within the structure
8397 // that it's part of, so we have to make sure we use the member type in this
8398 // case when calculating the parents size offsets.
8399 // TODO: May be good to extend MapInfoData to support tracking of both
8400 // VarPtr/VarPtrPtr BaseType's to better distinguish what's being used more
8401 // consistently.
8402 bool isRefPteeMap = bitEnumContainsAll(lastMemberMapInfo.getMapType(),
8403 omp::ClauseMapFlags::ref_ptee) &&
8404 !bitEnumContainsAll(lastMemberMapInfo.getMapType(),
8405 omp::ClauseMapFlags::ref_ptr);
8406 llvm::Type *castType = mapData.BaseType[lastMemberIdx];
8407 if (isRefPteeMap)
8408 castType =
8409 moduleTranslation.convertType(lastMemberMapInfo.getVarPtrType());
8410 highAddr = builder.CreatePointerCast(
8411 builder.CreateGEP(castType, mapData.BasePointers[lastMemberIdx],
8412 builder.getInt64(1)),
8413 builder.getPtrTy());
8414 combinedInfo.Pointers.emplace_back(mapData.BasePointers[firstMemberIdx]);
8415 }
8416
8417 llvm::Value *size = builder.CreateIntCast(
8418 builder.CreatePtrDiff(builder.getInt8Ty(), highAddr, lowAddr),
8419 builder.getInt64Ty(),
8420 /*isSigned=*/false);
8421 combinedInfo.Sizes.push_back(size);
8422
8423 // This creates the initial MEMBER_OF mapping that consists of
8424 // the parent/top level container (same as above effectively, except
8425 // with a fixed initial compile time size and separate maptype which
8426 // indicates the true mape type (tofrom etc.). This parent mapping is
8427 // only relevant if the structure in its totality is being mapped,
8428 // otherwise the above suffices.
8429 if (!parentClause.getPartialMap()) {
8430 // TODO: This will need to be expanded to include the whole host of logic
8431 // for the map flags that Clang currently supports (e.g. it should do some
8432 // further case specific flag modifications). For the moment, it handles
8433 // what we support as expected.
8434 MapFlags mapFlag = mapData.Types[mapDataIndex];
8435 bool hasMapClose = (MapFlags(mapFlag) & MapFlags::OMP_MAP_CLOSE) ==
8436 MapFlags::OMP_MAP_CLOSE;
8437 ompBuilder.setCorrectMemberOfFlag(mapFlag, memberOfFlag);
8438
8439 llvm::SmallVector<size_t> overlapIdxs;
8440 // Find all of the members that "overlap", i.e. occlude other members that
8441 // were mapped alongside the parent, e.g. member [0], occludes [0,1] and
8442 // [0,2], but not [1,0].
8443 getOverlappedMembers(overlapIdxs, parentClause);
8444
8445 // When we only have one overlap we skip the case that tries to segment the
8446 // mapping as best it can without creating holes, as the calculation is more
8447 // likely to have more overhead than anything we gain from mapping a smaller
8448 // chunk of data. This can be seen in cases where we are mapping Fortran
8449 // descriptors which are a special case of record type mapping.
8450 //
8451 // The cases for close and update are unique edge cases where the segmenting
8452 // does not play well with the runtime currently.
8453 if (targetDirective == TargetDirectiveEnumTy::TargetUpdate || hasMapClose ||
8454 overlapIdxs.size() == 1) {
8455 combinedInfo.Types.emplace_back(mapFlag);
8456 // TODO: set HasAttachPtr from Flang for pointee-storage entries.
8457 combinedInfo.HasAttachPtr.emplace_back(false);
8458 combinedInfo.DevicePointers.emplace_back(
8459 mapData.DevicePointers[mapDataIndex]);
8460 combinedInfo.Names.emplace_back(LLVM::createMappingInformation(
8461 mapData.MapClause[mapDataIndex]->getLoc(), ompBuilder,
8463 cast<omp::MapInfoOp>(mapData.MapClause[mapDataIndex]))));
8464 combinedInfo.BasePointers.emplace_back(
8465 mapData.BasePointers[mapDataIndex]);
8466 combinedInfo.Pointers.emplace_back(mapData.Pointers[mapDataIndex]);
8467 combinedInfo.Sizes.emplace_back(mapData.Sizes[mapDataIndex]);
8468 combinedInfo.Mappers.emplace_back(nullptr);
8469 } else {
8470 // We need to make sure the overlapped members are sorted in order of
8471 // lowest address to highest address.
8472 sortMapIndices(overlapIdxs, parentClause);
8473
8474 lowAddr = builder.CreatePointerCast(mapData.Pointers[mapDataIndex],
8475 builder.getPtrTy());
8476 highAddr = builder.CreatePointerCast(
8477 builder.CreateConstGEP1_32(mapData.BaseType[mapDataIndex],
8478 mapData.Pointers[mapDataIndex], 1),
8479 builder.getPtrTy());
8480
8481 // Currently, the return parameter should be the over-riding parent in
8482 // cases where we have a return parameter that is echoed to all members,
8483 // the main case of this currently is with fortran descriptors. It may
8484 // need more finessing for C/C++ in the future or descriptors that are
8485 // members of derived types.
8486 mapFlag &= ~llvm::omp::OpenMPOffloadMappingFlags::OMP_MAP_RETURN_PARAM;
8487
8488 // TODO: We may want to skip arrays/array sections in this as Clang does.
8489 // It appears to be an optimisation rather than a necessity though,
8490 // but this requires further investigation. However, we would have to make
8491 // sure to not exclude maps with bounds that ARE pointers, as these are
8492 // processed as separate components, i.e. pointer + data.
8493 for (auto v : overlapIdxs) {
8494 auto mapDataOverlapIdx = getMapDataMemberIdx(
8495 mapData,
8496 cast<omp::MapInfoOp>(parentClause.getMembers()[v].getDefiningOp()));
8497 auto isPtrMap = checkIfPointerMap(
8498 llvm::cast<omp::MapInfoOp>(mapData.MapClause[mapDataOverlapIdx]));
8499 combinedInfo.Types.emplace_back(mapFlag);
8500 // TODO: set HasAttachPtr from Flang for pointee-storage entries.
8501 combinedInfo.HasAttachPtr.emplace_back(false);
8502 combinedInfo.DevicePointers.emplace_back(
8503 llvm::OpenMPIRBuilder::DeviceInfoTy::None);
8504 combinedInfo.Names.emplace_back(LLVM::createMappingInformation(
8505 mapData.MapClause[mapDataIndex]->getLoc(), ompBuilder,
8507 cast<omp::MapInfoOp>(mapData.MapClause[mapDataIndex]))));
8508 combinedInfo.BasePointers.emplace_back(
8509 mapData.BasePointers[mapDataIndex]);
8510 combinedInfo.Mappers.emplace_back(nullptr);
8511 combinedInfo.Pointers.emplace_back(lowAddr);
8512 auto sizeCalc = builder.CreateIntCast(
8513 builder.CreatePtrDiff(builder.getInt8Ty(),
8514 mapData.OriginalValue[mapDataOverlapIdx],
8515 lowAddr),
8516 builder.getInt64Ty(), /*isSigned=*/true);
8517 // In certain cases, we'll generate a size of 0 if we're not careful
8518 // (e.g. if lowAddr happens to be the first member), which isn't
8519 // correct, even if the runtimes is sometimes fine with it so, in these
8520 // scenarios we select the types size instead.
8521 llvm::DataLayout dataLayout = builder.getDataLayout();
8522 auto sizeSel = builder.CreateSelect(
8523 builder.CreateICmpNE(builder.getInt64(0), sizeCalc), sizeCalc,
8524 isPtrMap ? builder.getInt64(dataLayout.getPointerSize())
8525 : mapData.Sizes[mapDataOverlapIdx]);
8526 combinedInfo.Sizes.emplace_back(sizeSel);
8527 lowAddr = builder.CreateConstGEP1_32(
8528 isPtrMap ? builder.getPtrTy() : mapData.BaseType[mapDataOverlapIdx],
8529 mapData.BasePointers[mapDataOverlapIdx], 1);
8530 }
8531
8532 combinedInfo.Types.emplace_back(mapFlag);
8533 // TODO: set HasAttachPtr from Flang for pointee-storage entries.
8534 combinedInfo.HasAttachPtr.emplace_back(false);
8535 combinedInfo.DevicePointers.emplace_back(
8536 llvm::OpenMPIRBuilder::DeviceInfoTy::None);
8537 combinedInfo.Names.emplace_back(LLVM::createMappingInformation(
8538 mapData.MapClause[mapDataIndex]->getLoc(), ompBuilder,
8540 cast<omp::MapInfoOp>(mapData.MapClause[mapDataIndex]))));
8541 combinedInfo.BasePointers.emplace_back(
8542 mapData.BasePointers[mapDataIndex]);
8543 combinedInfo.Mappers.emplace_back(nullptr);
8544 combinedInfo.Pointers.emplace_back(lowAddr);
8545 combinedInfo.Sizes.emplace_back(builder.CreateIntCast(
8546 builder.CreatePtrDiff(builder.getInt8Ty(), highAddr, lowAddr),
8547 builder.getInt64Ty(), true));
8548 }
8549 }
8550}
8551
8553 llvm::IRBuilderBase &builder,
8554 llvm::OpenMPIRBuilder &ompBuilder,
8555 DataLayout &dl, MapInfosTy &combinedInfo,
8556 MapInfoData &mapData, uint64_t mapDataIndex,
8557 TargetDirectiveEnumTy targetDirective) {
8558 assert(!ompBuilder.Config.isTargetDevice() &&
8559 "function only supported for host device codegen");
8560
8561 auto parentClause =
8562 llvm::cast<omp::MapInfoOp>(mapData.MapClause[mapDataIndex]);
8563
8564 // If we have a partial map (no parent referenced in the map clauses of the
8565 // directive, only members) and only a single member, we do not need to bind
8566 // the map of the member to the parent, we can pass the member separately.
8567 if (parentClause.getMembers().size() == 1 && parentClause.getPartialMap()) {
8568 auto memberClause = llvm::cast<omp::MapInfoOp>(
8569 parentClause.getMembers()[0].getDefiningOp());
8570 int memberDataIdx = getMapDataMemberIdx(mapData, memberClause);
8571 // Note: Clang treats arrays with explicit bounds that fall into this
8572 // category as a parent with map case, however, it seems this isn't a
8573 // requirement, and processing them as an individual map is fine. So,
8574 // we will handle them as individual maps for the moment, as it's
8575 // difficult for us to check this as we always require bounds to be
8576 // specified currently and it's also marginally more optimal (single
8577 // map rather than two). The difference may come from the fact that
8578 // Clang maps array without bounds as pointers (which we do not
8579 // currently do), whereas we treat them as arrays in all cases
8580 // currently.
8582 moduleTranslation, builder, ompBuilder, mapData, memberDataIdx,
8583 combinedInfo, targetDirective,
8584 /*MemberOfFlag=*/llvm::omp::OpenMPOffloadMappingFlags::OMP_MAP_NONE,
8585 /*isTargetParam=*/true, mapDataIndex);
8586 return;
8587 }
8588
8589 auto collectMapInfoIdxs =
8590 [&](llvm::SmallVectorImpl<int64_t> &mapsAndInfoIdx) {
8591 auto parentClause =
8592 llvm::cast<omp::MapInfoOp>(mapData.MapClause[mapDataIndex]);
8593 mapsAndInfoIdx.push_back(getMapDataMemberIdx(mapData, parentClause));
8594 for (auto member : parentClause.getMembers())
8595 mapsAndInfoIdx.push_back(getMapDataMemberIdx(
8596 mapData, llvm::cast<omp::MapInfoOp>(member.getDefiningOp())));
8597 };
8598
8599 llvm::SmallVector<int64_t> mapInfoIdx;
8600 collectMapInfoIdxs(mapInfoIdx);
8601
8602 llvm::omp::OpenMPOffloadMappingFlags memberOfFlag =
8603 ompBuilder.getMemberOfFlag(combinedInfo.Types.size());
8604
8605 // The first index is the parent map, the rest are its members. The parent
8606 // normally undergoes the standard parent-with-members mapping, contributing
8607 // the MEMBER_OF flag that binds each member to it. The one exception is a
8608 // privatizeable attach map (a privatized pointer/descriptor passed directly
8609 // as a kernel argument): here the parent is emitted as an individual map
8610 // instead, for the time being, as it's used only in pointer/allocatable to
8611 // array cases for the moment. This only ever applies to the parent, so it is
8612 // checked once here rather than inside the loop below.
8613 bool parentIsPrivatizeableAttach =
8614 isPrivatizeableAttachMap(parentClause.getMapType());
8615 for (auto [i, idx] : llvm::enumerate(mapInfoIdx)) {
8616 bool emitParentMap = i == 0 && !parentIsPrivatizeableAttach;
8617 if (emitParentMap) {
8618 mapParentWithMembers(moduleTranslation, builder, ompBuilder, dl,
8619 combinedInfo, mapData, idx, memberOfFlag,
8620 targetDirective);
8621 } else {
8623 moduleTranslation, builder, ompBuilder, mapData, idx, combinedInfo,
8624 targetDirective,
8625 parentIsPrivatizeableAttach
8626 ? llvm::omp::OpenMPOffloadMappingFlags::OMP_MAP_NONE
8627 : memberOfFlag,
8628 /*isTargetParam=*/false, mapDataIndex);
8629 }
8630 }
8631}
8632
8633// This is a variation on Clang's GenerateOpenMPCapturedVars, which
8634// generates different operation (e.g. load/store) combinations for
8635// arguments to the kernel, based on map capture kinds which are then
8636// utilised in the combinedInfo in place of the original Map value.
8637static void
8638createAlteredByCaptureMap(MapInfoData &mapData,
8639 LLVM::ModuleTranslation &moduleTranslation,
8640 llvm::IRBuilderBase &builder) {
8641 assert(!getOpenMPBuilder(moduleTranslation)->Config.isTargetDevice() &&
8642 "function only supported for host device codegen");
8643 for (size_t i = 0; i < mapData.MapClause.size(); ++i) {
8644 auto mapOp = cast<omp::MapInfoOp>(mapData.MapClause[i]);
8645 bool isAttachMap =
8646 ((convertClauseMapFlags(mapOp.getMapType()) &
8647 llvm::omp::OpenMPOffloadMappingFlags::OMP_MAP_ATTACH) ==
8648 llvm::omp::OpenMPOffloadMappingFlags::OMP_MAP_ATTACH);
8649
8650 // If it's declare target, skip it, it's handled separately. However, if
8651 // it's declare target, and an attach map, we want to calculate the exact
8652 // address offset so that we attach correctly.
8653 if (!mapData.IsDeclareTarget[i] ||
8654 (mapData.IsDeclareTarget[i] && isAttachMap)) {
8655 omp::VariableCaptureKind captureKind = mapOp.getMapCaptureType();
8656 bool isPtrTy = checkIfPointerMap(mapOp);
8657
8658 // Currently handles array sectioning lowerbound case, but more
8659 // logic may be required in the future. Clang invokes EmitLValue,
8660 // which has specialised logic for special Clang types such as user
8661 // defines, so it is possible we will have to extend this for
8662 // structures or other complex types. As the general idea is that this
8663 // function mimics some of the logic from Clang that we require for
8664 // kernel argument passing from host -> device.
8665 switch (captureKind) {
8666 case omp::VariableCaptureKind::ByRef: {
8667 llvm::Value *newV = mapData.Pointers[i];
8668 bool isByteOffset = false;
8669 std::vector<llvm::Value *> offsetIdx = calculateBoundsOffset(
8670 moduleTranslation, builder, mapData.BaseType[i]->isArrayTy(),
8671 mapOp.getBounds(), isByteOffset);
8672 if (isPtrTy)
8673 newV = builder.CreateLoad(builder.getPtrTy(), newV);
8674
8675 if (!offsetIdx.empty())
8676 newV = builder.CreateInBoundsGEP(isByteOffset ? builder.getInt8Ty()
8677 : mapData.BaseType[i],
8678 newV, offsetIdx, "array_offset");
8679 mapData.Pointers[i] = newV;
8680 } break;
8681 case omp::VariableCaptureKind::ByCopy: {
8682 llvm::Type *type = mapData.BaseType[i];
8683 llvm::Value *newV;
8684 if (mapData.Pointers[i]->getType()->isPointerTy())
8685 newV = builder.CreateLoad(type, mapData.Pointers[i]);
8686 else
8687 newV = mapData.Pointers[i];
8688
8689 if (!isPtrTy) {
8690 auto curInsert = builder.saveIP();
8691 llvm::DebugLoc DbgLoc = builder.getCurrentDebugLocation();
8692 builder.restoreIP(findAllocInsertPoints(builder, moduleTranslation));
8693 auto *memTempAlloc =
8694 builder.CreateAlloca(builder.getPtrTy(), nullptr, ".casted");
8695 builder.SetCurrentDebugLocation(DbgLoc);
8696 builder.restoreIP(curInsert);
8697
8698 builder.CreateStore(newV, memTempAlloc);
8699 newV = builder.CreateLoad(builder.getPtrTy(), memTempAlloc);
8700 }
8701
8702 mapData.Pointers[i] = newV;
8703 mapData.BasePointers[i] = newV;
8704 } break;
8705 case omp::VariableCaptureKind::This:
8706 case omp::VariableCaptureKind::VLAType:
8707 mapData.MapClause[i]->emitOpError("Unhandled capture kind");
8708 break;
8709 }
8710 }
8711 }
8712}
8713
8714// Generate all map related information and fill the combinedInfo.
8715static void genMapInfos(llvm::IRBuilderBase &builder,
8716 LLVM::ModuleTranslation &moduleTranslation,
8717 DataLayout &dl, MapInfosTy &combinedInfo,
8718 MapInfoData &mapData,
8719 TargetDirectiveEnumTy targetDirective) {
8720 assert(!getOpenMPBuilder(moduleTranslation)->Config.isTargetDevice() &&
8721 "function only supported for host device codegen");
8722 // We wish to modify some of the methods in which arguments are
8723 // passed based on their capture type by the target region, this can
8724 // involve generating new loads and stores, which changes the
8725 // MLIR value to LLVM value mapping, however, we only wish to do this
8726 // locally for the current function/target and also avoid altering
8727 // ModuleTranslation, so we remap the base pointer or pointer stored
8728 // in the map infos corresponding MapInfoData, which is later accessed
8729 // by genMapInfos and createTarget to help generate the kernel and
8730 // kernel arg structure. It primarily becomes relevant in cases like
8731 // bycopy, or byref range'd arrays. In the default case, we simply
8732 // pass thee pointer byref as both basePointer and pointer.
8733 createAlteredByCaptureMap(mapData, moduleTranslation, builder);
8734
8735 llvm::OpenMPIRBuilder *ompBuilder = getOpenMPBuilder(moduleTranslation);
8736
8737 // We operate under the assumption that all vectors that are
8738 // required in MapInfoData are of equal lengths (either filled with
8739 // default constructed data or appropiate information) so we can
8740 // utilise the size from any component of MapInfoData, if we can't
8741 // something is missing from the initial MapInfoData construction.
8742 for (size_t i = 0; i < mapData.MapClause.size(); ++i) {
8743 if (mapData.IsAMember[i])
8744 continue;
8745
8746 auto mapInfoOp = dyn_cast<omp::MapInfoOp>(mapData.MapClause[i]);
8747 if (!mapInfoOp.getMembers().empty()) {
8748 processMapWithMembersOf(moduleTranslation, builder, *ompBuilder, dl,
8749 combinedInfo, mapData, i, targetDirective);
8750 continue;
8751 }
8752
8753 processIndividualMap(moduleTranslation, builder, *ompBuilder, mapData, i,
8754 combinedInfo, targetDirective);
8755 }
8756 if (!combinedInfo.NonContigInfo.Dims.empty())
8757 combinedInfo.NonContigInfo.Dims.resize(combinedInfo.Types.size(), 1);
8758}
8759
8760static llvm::Expected<llvm::Function *>
8761emitUserDefinedMapper(Operation *declMapperOp, llvm::IRBuilderBase &builder,
8762 LLVM::ModuleTranslation &moduleTranslation,
8763 llvm::StringRef mapperFuncName,
8764 TargetDirectiveEnumTy targetDirective);
8765
8766static llvm::Expected<llvm::Function *>
8767getOrCreateUserDefinedMapperFunc(Operation *op, llvm::IRBuilderBase &builder,
8768 LLVM::ModuleTranslation &moduleTranslation,
8769 TargetDirectiveEnumTy targetDirective) {
8770 assert(!getOpenMPBuilder(moduleTranslation)->Config.isTargetDevice() &&
8771 "function only supported for host device codegen");
8772 auto declMapperOp = cast<omp::DeclareMapperOp>(op);
8773 std::string mapperFuncName =
8774 getOpenMPBuilder(moduleTranslation)
8775 ->createPlatformSpecificName(
8776 {"omp_mapper", declMapperOp.getSymName()});
8777
8778 if (auto *lookupFunc = moduleTranslation.lookupFunction(mapperFuncName))
8779 return lookupFunc;
8780
8781 // Recursive types can cause re-entrant mapper emission. The mapper function
8782 // is created by OpenMPIRBuilder before the callbacks run, so it may already
8783 // exist in the LLVM module even though it is not yet registered in the
8784 // ModuleTranslation mapping table. Reuse and register it to break the
8785 // recursion.
8786 if (llvm::Function *existingFunc =
8787 moduleTranslation.getLLVMModule()->getFunction(mapperFuncName)) {
8788 moduleTranslation.mapFunction(mapperFuncName, existingFunc);
8789 return existingFunc;
8790 }
8791
8792 return emitUserDefinedMapper(declMapperOp, builder, moduleTranslation,
8793 mapperFuncName, targetDirective);
8794}
8795
8796/// The mapper body (and any iterator regions in it) is emitted inside the
8797/// mapper's per-element loop, so temporaries Flang allocates in the mapper
8798/// region (e.g. the storage for an iterator variable) would be allocated once
8799/// per element and grow the stack with every iteration. Move constant-size
8800/// allocas to the function's entry block, where a frontend would place them.
8801static void hoistMapperAllocasToEntry(llvm::Function &mapperFn) {
8802 llvm::BasicBlock &entry = mapperFn.getEntryBlock();
8804 for (llvm::BasicBlock &bb : llvm::drop_begin(mapperFn))
8805 for (llvm::Instruction &inst : bb)
8806 if (auto *alloca = dyn_cast<llvm::AllocaInst>(&inst))
8807 if (isa<llvm::ConstantInt>(alloca->getArraySize()))
8808 toHoist.push_back(alloca);
8809 for (llvm::AllocaInst *alloca : toHoist)
8810 alloca->moveBefore(entry.getFirstNonPHIOrAlloca());
8811}
8812
8813static llvm::Expected<llvm::Function *>
8814emitUserDefinedMapper(Operation *op, llvm::IRBuilderBase &builder,
8815 LLVM::ModuleTranslation &moduleTranslation,
8816 llvm::StringRef mapperFuncName,
8817 TargetDirectiveEnumTy targetDirective) {
8818 assert(!getOpenMPBuilder(moduleTranslation)->Config.isTargetDevice() &&
8819 "function only supported for host device codegen");
8820 auto declMapperOp = cast<omp::DeclareMapperOp>(op);
8821 auto declMapperInfoOp = declMapperOp.getDeclareMapperInfo();
8822 if (failed(checkImplementationStatus(*declMapperInfoOp)))
8823 return llvm::make_error<PreviouslyReportedError>();
8824
8825 DataLayout dl = DataLayout(declMapperOp->getParentOfType<ModuleOp>());
8826 llvm::OpenMPIRBuilder *ompBuilder = getOpenMPBuilder(moduleTranslation);
8827 llvm::Type *varType = moduleTranslation.convertType(declMapperOp.getType());
8828 SmallVector<Value> mapVars = declMapperInfoOp.getMapVars();
8829
8830 using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy;
8831
8832 // Fill up the arrays with all the mapped variables.
8833 MapInfosTy combinedInfo;
8834 auto genMapInfoCB =
8835 [&](InsertPointTy codeGenIP, llvm::Value *ptrPHI,
8836 llvm::Value *unused2) -> llvm::OpenMPIRBuilder::MapInfosOrErrorTy {
8837 builder.restoreIP(codeGenIP);
8838 moduleTranslation.mapValue(declMapperOp.getSymVal(), ptrPHI);
8839 moduleTranslation.mapBlock(&declMapperOp.getRegion().front(),
8840 builder.GetInsertBlock());
8841 if (failed(moduleTranslation.convertBlock(declMapperOp.getRegion().front(),
8842 /*ignoreArguments=*/true,
8843 builder)))
8844 return llvm::make_error<PreviouslyReportedError>();
8845 MapInfoData mapData;
8846 collectMapDataFromMapOperands(mapData, mapVars, moduleTranslation, dl,
8847 builder);
8848
8849 // Components produced by an `iterator` modifier on the mapper's own map
8850 // clause: their count is only known at runtime, so they are recorded as
8851 // dynamic segments and pushed one at a time (via
8852 // __tgt_push_mapper_component) from a generated loop, mirroring how the
8853 // depend/affinity clauses already handle iterator-produced entries. Each
8854 // per-iteration locator keeps its array base in var_ptr with bounds
8855 // selecting the mapped element, the same shape as an ordinary
8856 // array-section map, so the existing calculateBoundsOffset helper
8857 // computes its address.
8858 //
8859 // Like statically-known members (see processMapWithMembersOf), the
8860 // iterated elements are grouped under a component for the mapper variable
8861 // via MEMBER_OF, so the runtime treats them as sub-ranges of one
8862 // allocation rather than independent objects. If the mapper also maps the
8863 // variable itself that component is reused. Otherwise a storage-only
8864 // parent is synthesized that, like the parent of explicit members, spans
8865 // exactly the elements the iterators expand to: its begin/end are the
8866 // runtime min/max over all iterations, so it never extends a mapping of
8867 // the component the user may have made separately, and it is skipped
8868 // altogether when every iterator has a zero trip count (an empty iterator
8869 // acts as if the list item were omitted). The parent must precede every
8870 // other component: the runtime maps components in order and rejects a
8871 // later one that extends an earlier mapping.
8872 struct IteratedEntryInfo {
8873 mlir::omp::IteratorOp itersOp;
8874 mlir::omp::MapInfoOp mapInfoOp;
8875 llvm::Type *baseLLVMTy;
8876 llvm::Value *elemSizeVal;
8877 IteratorInfo iterInfo;
8878 };
8880 for (mlir::Value iterVal : declMapperInfoOp.getMapIterated()) {
8881 auto itersOp = iterVal.getDefiningOp<mlir::omp::IteratorOp>();
8882 assert(itersOp && "map_iterated value must be defined by omp.iterator");
8883 // Lowering the locator's indices (e.g. involving LEN_TRIM) can
8884 // introduce control flow inside the iterator, so its `omp.yield` is
8885 // not necessarily in the region's first block.
8886 mlir::omp::YieldOp yieldOp = itersOp.getYieldOp();
8887 assert(yieldOp && "expected exactly one omp.yield in the iterator body");
8888 auto mapInfoOp =
8889 yieldOp.getResults()[0].getDefiningOp<mlir::omp::MapInfoOp>();
8890 assert(mapInfoOp && "expected an omp.map.info in the map_iterated body");
8891
8892 mlir::Type varPtrMlirTy = mapInfoOp.getVarPtrType();
8893 // Byte size of one element of the locator's innermost dimension; the
8894 // bounds supply the (runtime) element count per iteration.
8895 uint64_t elemSizeInBits = dl.getTypeSizeInBits(varPtrMlirTy);
8896 if (auto arrTy = mlir::dyn_cast<mlir::LLVM::LLVMArrayType>(varPtrMlirTy))
8897 elemSizeInBits = getArrayElementSizeInBits(arrTy, dl);
8898 iteratedEntries.push_back(
8899 {itersOp, mapInfoOp, moduleTranslation.convertType(varPtrMlirTy),
8900 builder.getInt64(elemSizeInBits / 8),
8901 IteratorInfo(itersOp, moduleTranslation, builder)});
8902 }
8903
8904 // Emits the (base, begin, size) of the entry for one iteration, given the
8905 // loop's linear induction variable. `info` is taken by value: it holds
8906 // the lb/ub/step/trip llvm::Value*s looked up while `declMapperOp`'s
8907 // region mapping was still valid, and this may run later (from within
8908 // OpenMPIRBuilder::emitUserDefinedMapper), after that mapping has been
8909 // dropped via forgetMapping.
8910 auto genIteratedEntry = [&moduleTranslation](IteratedEntryInfo info,
8911 llvm::IRBuilderBase &b,
8912 llvm::Value *linearIV)
8914 if (failed(convertIteratorRegion(linearIV, info.iterInfo,
8915 info.itersOp.getRegion(), b,
8916 moduleTranslation)))
8917 return llvm::make_error<PreviouslyReportedError>();
8918 llvm::Value *base =
8919 moduleTranslation.lookupValue(info.mapInfoOp.getVarPtr());
8920 bool isByteOffset = false;
8921 std::vector<llvm::Value *> offsetIdx = calculateBoundsOffset(
8922 moduleTranslation, b, info.baseLLVMTy->isArrayTy(),
8923 info.mapInfoOp.getBounds(), isByteOffset);
8924 llvm::Value *addr = base;
8925 if (!offsetIdx.empty())
8926 addr = b.CreateInBoundsGEP(
8927 isByteOffset ? b.getInt8Ty() : info.baseLLVMTy, base, offsetIdx);
8928 // Size = product over dimensions of (ub - lb + 1), times the element
8929 // size, the same calculation getSizeInBytes does for static entries.
8930 llvm::Value *elementCount = b.getInt64(1);
8931 for (mlir::Value bound : info.mapInfoOp.getBounds()) {
8932 auto boundOp = bound.getDefiningOp<mlir::omp::MapBoundsOp>();
8933 if (!boundOp)
8934 continue;
8935 llvm::Value *lb =
8936 moduleTranslation.lookupValue(boundOp.getLowerBound());
8937 llvm::Value *ub =
8938 moduleTranslation.lookupValue(boundOp.getUpperBound());
8939 elementCount = b.CreateMul(
8940 elementCount, b.CreateAdd(b.CreateSub(ub, lb), b.getInt64(1)));
8941 }
8942 llvm::Value *size = b.CreateMul(elementCount, info.elemSizeVal);
8943 moduleTranslation.forgetMapping(info.itersOp.getRegion());
8944 // The array base is the component's base pointer, as for a
8945 // statically-known member; MEMBER_OF ties it to the parent entry.
8946 return llvm::SmallVector<llvm::Value *, 3>{base, addr, size};
8947 };
8948
8949 bool hasIterated = !iteratedEntries.empty();
8950 std::optional<unsigned> iteratedParentIdx;
8951 // Span of the iterated elements, computed when the mapper does not map
8952 // the variable whole; null otherwise.
8953 llvm::Value *anyTrips = nullptr;
8954 llvm::Value *spanBegin = nullptr;
8955 llvm::Value *spanEnd = nullptr;
8956 bool hasStaticParent = false;
8957 if (hasIterated) {
8958 bool mapsWholeVariable = false;
8959 for (Value mapVar : mapVars) {
8960 auto mapOp = cast<omp::MapInfoOp>(mapVar.getDefiningOp());
8961 if (mapOp.getVarPtr() != declMapperOp.getSymVal())
8962 continue;
8963 // A partial map with a single member is emitted as an individual map
8964 // of that member (see processMapWithMembersOf), so there is no parent
8965 // component to attach the iterated elements to.
8966 if (mapOp.getPartialMap() && mapOp.getMembers().size() == 1)
8967 continue;
8968 hasStaticParent = true;
8969 if (!mapOp.getPartialMap() && mapOp.getBounds().empty())
8970 mapsWholeVariable = true;
8971 }
8972 if (!mapsWholeVariable) {
8973 // Span of all iterated elements as [spanBegin, spanEnd) integers,
8974 // meaningful only when anyTrips. A pre-pass loop over each segment's
8975 // iterations (the same ones the mapper pushes later) accumulates the
8976 // min begin / max end in two slots; createIteratorLoop carries no
8977 // loop state, so memory is used rather than PHIs. The allocas end
8978 // up in the entry block via hoistMapperAllocasToEntry.
8979 llvm::Type *i64Ty = builder.getInt64Ty();
8980 anyTrips = builder.getFalse();
8981 spanBegin = builder.getInt64(0);
8982 spanEnd = builder.getInt64(0);
8983 llvm::Value *beginSlot =
8984 builder.CreateAlloca(i64Ty, nullptr, "omp.iterparent.begin");
8985 llvm::Value *endSlot =
8986 builder.CreateAlloca(i64Ty, nullptr, "omp.iterparent.end");
8987 for (IteratedEntryInfo &info : iteratedEntries) {
8988 llvm::Value *trips = info.iterInfo.getTotalTrips();
8989 llvm::Value *hasTrips =
8990 builder.CreateICmpNE(trips, builder.getInt64(0));
8991 builder.CreateStore(builder.getInt64(~0ULL), beginSlot);
8992 builder.CreateStore(builder.getInt64(0), endSlot);
8993 auto spanBodyGen = [&](InsertPointTy bodyIP,
8994 llvm::Value *linearIV) -> llvm::Error {
8995 builder.restoreIP(bodyIP);
8997 genIteratedEntry(info, builder, linearIV);
8998 if (!entryOrErr)
8999 return entryOrErr.takeError();
9000 llvm::Value *begin =
9001 builder.CreatePtrToInt((*entryOrErr)[1], i64Ty);
9002 llvm::Value *end = builder.CreateAdd(begin, (*entryOrErr)[2]);
9003 builder.CreateStore(builder.CreateBinaryIntrinsic(
9004 llvm::Intrinsic::umin,
9005 builder.CreateLoad(i64Ty, beginSlot),
9006 begin),
9007 beginSlot);
9008 builder.CreateStore(builder.CreateBinaryIntrinsic(
9009 llvm::Intrinsic::umax,
9010 builder.CreateLoad(i64Ty, endSlot), end),
9011 endSlot);
9012 return llvm::Error::success();
9013 };
9014 llvm::OpenMPIRBuilder::InsertPointOrErrorTy afterIP =
9015 ompBuilder->createIteratorLoop(
9016 llvm::OpenMPIRBuilder::LocationDescription(builder), trips,
9017 spanBodyGen, "mapper.iterspan");
9018 if (!afterIP)
9019 return afterIP.takeError();
9020 builder.restoreIP(*afterIP);
9021 llvm::Value *segBegin = builder.CreateLoad(i64Ty, beginSlot);
9022 llvm::Value *segEnd = builder.CreateLoad(i64Ty, endSlot);
9023 // Fold this segment into the overall span unless it is empty.
9024 llvm::Value *mergedBegin = builder.CreateSelect(
9025 anyTrips,
9026 builder.CreateBinaryIntrinsic(llvm::Intrinsic::umin, spanBegin,
9027 segBegin),
9028 segBegin);
9029 llvm::Value *mergedEnd =
9030 builder.CreateSelect(anyTrips,
9031 builder.CreateBinaryIntrinsic(
9032 llvm::Intrinsic::umax, spanEnd, segEnd),
9033 segEnd);
9034 spanBegin = builder.CreateSelect(hasTrips, mergedBegin, spanBegin);
9035 spanEnd = builder.CreateSelect(hasTrips, mergedEnd, spanEnd);
9036 anyTrips = builder.CreateOr(anyTrips, hasTrips);
9037 }
9038 // The pre-pass loops split the block emitUserDefinedMapper was
9039 // emitting into; move its builder to the continuation as well.
9040 ompBuilder->Builder.restoreIP(builder.saveIP());
9041
9042 if (!hasStaticParent) {
9043 // No map clause covers the variable, so synthesize a storage-only
9044 // parent for the span, pushed only when there are elements.
9045 iteratedParentIdx = 0;
9046 combinedInfo.BasePointers.push_back(ptrPHI);
9047 combinedInfo.Pointers.push_back(
9048 builder.CreateIntToPtr(spanBegin, builder.getPtrTy()));
9049 combinedInfo.Sizes.push_back(builder.CreateSub(spanEnd, spanBegin));
9050 combinedInfo.Types.push_back(
9051 llvm::omp::OpenMPOffloadMappingFlags::OMP_MAP_NONE);
9052 combinedInfo.HasAttachPtr.push_back(false);
9053 combinedInfo.DevicePointers.push_back(
9054 llvm::OpenMPIRBuilder::DeviceInfoTy::None);
9055 combinedInfo.Mappers.push_back(nullptr);
9056 combinedInfo.Names.push_back(LLVM::createMappingInformation(
9057 declMapperOp.getLoc(), *ompBuilder, declMapperOp.getSymName()));
9058 combinedInfo.LeadingParentCond = anyTrips;
9059 }
9060 }
9061 }
9062
9063 genMapInfos(builder, moduleTranslation, dl, combinedInfo, mapData,
9064 targetDirective);
9065
9066 llvm::omp::OpenMPOffloadMappingFlags iteratedMemberOf =
9067 llvm::omp::OpenMPOffloadMappingFlags::OMP_MAP_NONE;
9068 if (hasIterated) {
9069 if (!iteratedParentIdx) {
9070 // The component genMapInfos emitted for the variable: the whole
9071 // variable, or the partial parent of its statically mapped members.
9072 // Members also have the variable as base, but carry MEMBER_OF.
9073 for (unsigned i = 0; i < combinedInfo.BasePointers.size(); ++i) {
9074 if (combinedInfo.BasePointers[i] == ptrPHI &&
9075 (combinedInfo.Types[i] &
9076 llvm::omp::OpenMPOffloadMappingFlags::OMP_MAP_MEMBER_OF) ==
9077 llvm::omp::OpenMPOffloadMappingFlags::OMP_MAP_NONE) {
9078 iteratedParentIdx = i;
9079 break;
9080 }
9081 }
9082 }
9083 assert(iteratedParentIdx && "no parent component for iterated entries");
9084 if (iteratedParentIdx && spanBegin && hasStaticParent) {
9085 // The partial parent spans only the static members. The runtime
9086 // rejects a later entry that extends an earlier one, so rather than
9087 // adding a second parent, widen this one to also cover the iterated
9088 // elements (when there are any).
9089 unsigned idx = *iteratedParentIdx;
9090 llvm::Type *i64Ty = builder.getInt64Ty();
9091 llvm::Value *parentBegin =
9092 builder.CreatePtrToInt(combinedInfo.Pointers[idx], i64Ty);
9093 llvm::Value *parentEnd =
9094 builder.CreateAdd(parentBegin, combinedInfo.Sizes[idx]);
9095 llvm::Value *newBegin = builder.CreateSelect(
9096 anyTrips,
9097 builder.CreateBinaryIntrinsic(llvm::Intrinsic::umin, parentBegin,
9098 spanBegin),
9099 parentBegin, "omp.iterparent.begin.merged");
9100 llvm::Value *newEnd =
9101 builder.CreateSelect(anyTrips,
9102 builder.CreateBinaryIntrinsic(
9103 llvm::Intrinsic::umax, parentEnd, spanEnd),
9104 parentEnd, "omp.iterparent.end.merged");
9105 combinedInfo.Pointers[idx] =
9106 builder.CreateIntToPtr(newBegin, builder.getPtrTy());
9107 combinedInfo.Sizes[idx] = builder.CreateSub(newEnd, newBegin);
9108 }
9109 if (iteratedParentIdx)
9110 iteratedMemberOf = ompBuilder->getMemberOfFlag(*iteratedParentIdx);
9111 }
9112
9113 for (IteratedEntryInfo &info : iteratedEntries) {
9114 llvm::omp::OpenMPOffloadMappingFlags mapType =
9115 convertClauseMapFlags(info.mapInfoOp.getMapType());
9116 ompBuilder->setCorrectMemberOfFlag(mapType, iteratedMemberOf);
9117 bool hasAttachPtr =
9118 (mapType & llvm::omp::OpenMPOffloadMappingFlags::OMP_MAP_ATTACH) !=
9119 llvm::omp::OpenMPOffloadMappingFlags::OMP_MAP_NONE;
9120
9121 combinedInfo.DynamicSegments.push_back(MapInfosTy::DynamicSegment{
9122 info.iterInfo.getTotalTrips(), {}, mapType, hasAttachPtr});
9123 MapInfosTy::DynamicSegment &seg = combinedInfo.DynamicSegments.back();
9124 seg.GenEntry = [genIteratedEntry, info](llvm::IRBuilderBase &b,
9125 llvm::Value *linearIV) {
9126 return genIteratedEntry(info, b, linearIV);
9127 };
9128
9129 if (info.mapInfoOp.getMapperId()) {
9130 auto childMapperOp =
9132 info.mapInfoOp, info.mapInfoOp.getMapperIdAttr());
9133 // Emitting the child mapper for the first time leaves builder's
9134 // insertion point inside the child function; restore it so that
9135 // later iterator segments are emitted into this (the parent)
9136 // mapper function instead.
9137 llvm::IRBuilderBase::InsertPointGuard childMapperIPGuard(builder);
9138 llvm::Expected<llvm::Function *> childMapperFn =
9140 childMapperOp, builder, moduleTranslation, targetDirective);
9141 if (!childMapperFn)
9142 return childMapperFn.takeError();
9143 seg.ChildMapperFn = *childMapperFn;
9144 }
9145 }
9146
9147 return combinedInfo;
9148 };
9149
9150 auto customMapperCB = [&](unsigned i) -> llvm::Expected<llvm::Function *> {
9151 if (!combinedInfo.Mappers[i])
9152 return nullptr;
9153 return getOrCreateUserDefinedMapperFunc(combinedInfo.Mappers[i], builder,
9154 moduleTranslation, targetDirective);
9155 };
9156
9157 llvm::Expected<llvm::Function *> newFn = ompBuilder->emitUserDefinedMapper(
9158 genMapInfoCB, varType, mapperFuncName, customMapperCB,
9159 /*PreserveMemberOfFlags=*/true, /*PropagatePresentToPointeeStorage=*/true,
9160 /*PropagatePresentToNonPointeeStorage=*/true);
9161 // Only now that emitUserDefinedMapper has fully finished (including running
9162 // any iterator-produced DynamicSegment::GenEntry callbacks, which look up
9163 // values defined in declMapperOp's region) is it safe to drop the mapping,
9164 // so that the same region can be processed multiple times.
9165 moduleTranslation.forgetMapping(declMapperOp.getRegion());
9166 if (!newFn)
9167 return newFn.takeError();
9169 if ([[maybe_unused]] llvm::Function *mappedFunc =
9170 moduleTranslation.lookupFunction(mapperFuncName)) {
9171 assert(mappedFunc == *newFn &&
9172 "mapper function mapping disagrees with emitted function");
9173 } else {
9174 moduleTranslation.mapFunction(mapperFuncName, *newFn);
9175 }
9176 return *newFn;
9177}
9178
9179static llvm::Value *getSourceLocIdentFromOp(llvm::IRBuilderBase &builder,
9180 llvm::OpenMPIRBuilder &ompBuilder,
9181 Operation *op) {
9182 auto fileLoc = op->getLoc()->findInstanceOf<FileLineColLoc>();
9183 if (!fileLoc)
9184 return nullptr;
9185 uint32_t strSize;
9186 llvm::Function *parentFn = builder.GetInsertBlock()->getParent();
9187 llvm::StringRef fnName = parentFn ? parentFn->getName() : "";
9188 llvm::Constant *srcStr = LLVM::createSourceLocStrFromLocation(
9189 fileLoc, ompBuilder, fnName, strSize);
9190 return ompBuilder.getOrCreateIdent(srcStr, strSize);
9191}
9192
9193static LogicalResult
9194convertOmpTargetData(Operation *op, llvm::IRBuilderBase &builder,
9195 LLVM::ModuleTranslation &moduleTranslation) {
9196 llvm::Value *ifCond = nullptr;
9197 llvm::Value *deviceID = builder.getInt64(llvm::omp::OMP_DEVICEID_UNDEF);
9198 SmallVector<Value> mapVars;
9199 SmallVector<Value> useDevicePtrVars;
9200 SmallVector<Value> useDeviceAddrVars;
9201 llvm::omp::RuntimeFunction RTLFn;
9202 DataLayout DL = DataLayout(op->getParentOfType<ModuleOp>());
9203 TargetDirectiveEnumTy targetDirective = getTargetDirectiveEnumTyFromOp(op);
9204
9205 llvm::OpenMPIRBuilder *ompBuilder = getOpenMPBuilder(moduleTranslation);
9206 llvm::OpenMPIRBuilder::TargetDataInfo info(
9207 /*RequiresDevicePointerInfo=*/true,
9208 /*SeparateBeginEndCalls=*/true);
9209
9210 if (ompBuilder->Config.isTargetDevice())
9211 return op->emitOpError() << "not allowed in a target device";
9212
9213 bool isOffloadEntry = !ompBuilder->Config.TargetTriples.empty();
9214
9215 auto getDeviceID = [&](mlir::Value dev) -> llvm::Value * {
9216 llvm::Value *v = moduleTranslation.lookupValue(dev);
9217 return builder.CreateIntCast(v, builder.getInt64Ty(), /*isSigned=*/true);
9218 };
9219
9220 LogicalResult result =
9222 .Case([&](omp::TargetDataOp dataOp) {
9223 if (failed(checkImplementationStatus(*dataOp)))
9224 return failure();
9225
9226 if (auto ifVar = dataOp.getIfExpr())
9227 ifCond = moduleTranslation.lookupValue(ifVar);
9228
9229 if (mlir::Value devId = dataOp.getDevice())
9230 deviceID = getDeviceID(devId);
9231
9232 mapVars = dataOp.getMapVars();
9233 useDevicePtrVars = dataOp.getUseDevicePtrVars();
9234 useDeviceAddrVars = dataOp.getUseDeviceAddrVars();
9235 return success();
9236 })
9237 .Case([&](omp::TargetEnterDataOp enterDataOp) -> LogicalResult {
9238 if (failed(checkImplementationStatus(*enterDataOp)))
9239 return failure();
9240
9241 if (auto ifVar = enterDataOp.getIfExpr())
9242 ifCond = moduleTranslation.lookupValue(ifVar);
9243
9244 if (mlir::Value devId = enterDataOp.getDevice())
9245 deviceID = getDeviceID(devId);
9246
9247 RTLFn =
9248 enterDataOp.getNowait()
9249 ? llvm::omp::OMPRTL___tgt_target_data_begin_nowait_mapper
9250 : llvm::omp::OMPRTL___tgt_target_data_begin_mapper;
9251 mapVars = enterDataOp.getMapVars();
9252 info.HasNoWait = enterDataOp.getNowait();
9253 return success();
9254 })
9255 .Case([&](omp::TargetExitDataOp exitDataOp) -> LogicalResult {
9256 if (failed(checkImplementationStatus(*exitDataOp)))
9257 return failure();
9258
9259 if (auto ifVar = exitDataOp.getIfExpr())
9260 ifCond = moduleTranslation.lookupValue(ifVar);
9261
9262 if (mlir::Value devId = exitDataOp.getDevice())
9263 deviceID = getDeviceID(devId);
9264
9265 RTLFn = exitDataOp.getNowait()
9266 ? llvm::omp::OMPRTL___tgt_target_data_end_nowait_mapper
9267 : llvm::omp::OMPRTL___tgt_target_data_end_mapper;
9268 mapVars = exitDataOp.getMapVars();
9269 info.HasNoWait = exitDataOp.getNowait();
9270 return success();
9271 })
9272 .Case([&](omp::TargetUpdateOp updateDataOp) -> LogicalResult {
9273 if (failed(checkImplementationStatus(*updateDataOp)))
9274 return failure();
9275
9276 if (auto ifVar = updateDataOp.getIfExpr())
9277 ifCond = moduleTranslation.lookupValue(ifVar);
9278
9279 if (mlir::Value devId = updateDataOp.getDevice())
9280 deviceID = getDeviceID(devId);
9281
9282 RTLFn =
9283 updateDataOp.getNowait()
9284 ? llvm::omp::OMPRTL___tgt_target_data_update_nowait_mapper
9285 : llvm::omp::OMPRTL___tgt_target_data_update_mapper;
9286 mapVars = updateDataOp.getMapVars();
9287 info.HasNoWait = updateDataOp.getNowait();
9288 return success();
9289 })
9290 .DefaultUnreachable("unexpected operation");
9291
9292 if (failed(result))
9293 return failure();
9294 // Pretend we have IF(false) if we're not doing offload.
9295 if (!isOffloadEntry)
9296 ifCond = builder.getFalse();
9297
9298 using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy;
9299 MapInfoData mapData;
9300 collectMapDataFromMapOperands(mapData, mapVars, moduleTranslation, DL,
9301 builder, useDevicePtrVars, useDeviceAddrVars);
9302
9303 // Fill up the arrays with all the mapped variables.
9304 MapInfosTy combinedInfo;
9305 auto genMapInfoCB = [&](InsertPointTy codeGenIP) -> MapInfosTy & {
9306 builder.restoreIP(codeGenIP);
9307 genMapInfos(builder, moduleTranslation, DL, combinedInfo, mapData,
9308 targetDirective);
9309 return combinedInfo;
9310 };
9311
9312 // Define a lambda to apply mappings between use_device_addr and
9313 // use_device_ptr base pointers, and their associated block arguments.
9314 auto mapUseDevice =
9315 [&moduleTranslation](
9316 llvm::OpenMPIRBuilder::DeviceInfoTy type,
9318 llvm::SmallVectorImpl<Value> &useDeviceVars, MapInfoData &mapInfoData,
9319 llvm::function_ref<llvm::Value *(llvm::Value *)> mapper = nullptr) {
9320 for (auto [arg, useDevVar] :
9321 llvm::zip_equal(blockArgs, useDeviceVars)) {
9322
9323 auto getMapBasePtr = [](omp::MapInfoOp mapInfoOp) {
9324 return mapInfoOp.getVarPtrPtr() ? mapInfoOp.getVarPtrPtr()
9325 : mapInfoOp.getVarPtr();
9326 };
9327
9328 auto useDevMap = cast<omp::MapInfoOp>(useDevVar.getDefiningOp());
9329 for (auto [mapClause, devicePointer, basePointer] : llvm::zip_equal(
9330 mapInfoData.MapClause, mapInfoData.DevicePointers,
9331 mapInfoData.BasePointers)) {
9332 auto mapOp = cast<omp::MapInfoOp>(mapClause);
9333 if (getMapBasePtr(mapOp) != getMapBasePtr(useDevMap) ||
9334 devicePointer != type)
9335 continue;
9336
9337 if (llvm::Value *devPtrInfoMap =
9338 mapper ? mapper(basePointer) : basePointer) {
9339 moduleTranslation.mapValue(arg, devPtrInfoMap);
9340 break;
9341 }
9342 }
9343 }
9344 };
9345
9346 using BodyGenTy = llvm::OpenMPIRBuilder::BodyGenTy;
9347 auto bodyGenCB = [&](InsertPointTy codeGenIP, BodyGenTy bodyGenType)
9348 -> llvm::OpenMPIRBuilder::InsertPointOrErrorTy {
9349 // We must always restoreIP regardless of doing anything the caller
9350 // does not restore it, leading to incorrect (no) branch generation.
9351 builder.restoreIP(codeGenIP);
9352 assert(isa<omp::TargetDataOp>(op) &&
9353 "BodyGen requested for non TargetDataOp");
9354 auto blockArgIface = cast<omp::BlockArgOpenMPOpInterface>(op);
9355 Region &region = cast<omp::TargetDataOp>(op).getRegion();
9356 switch (bodyGenType) {
9357 case BodyGenTy::Priv:
9358 // Check if any device ptr/addr info is available
9359 if (!info.DevicePtrInfoMap.empty()) {
9360 mapUseDevice(llvm::OpenMPIRBuilder::DeviceInfoTy::Address,
9361 blockArgIface.getUseDeviceAddrBlockArgs(),
9362 useDeviceAddrVars, mapData,
9363 [&](llvm::Value *basePointer) -> llvm::Value * {
9364 if (!info.DevicePtrInfoMap[basePointer].second)
9365 return nullptr;
9366 return builder.CreateLoad(
9367 builder.getPtrTy(),
9368 info.DevicePtrInfoMap[basePointer].second);
9369 });
9370 mapUseDevice(llvm::OpenMPIRBuilder::DeviceInfoTy::Pointer,
9371 blockArgIface.getUseDevicePtrBlockArgs(), useDevicePtrVars,
9372 mapData, [&](llvm::Value *basePointer) {
9373 return info.DevicePtrInfoMap[basePointer].second;
9374 });
9375
9376 if (failed(inlineConvertOmpRegions(region, "omp.data.region", builder,
9377 moduleTranslation)))
9378 return llvm::make_error<PreviouslyReportedError>();
9379 }
9380 break;
9381 case BodyGenTy::DupNoPriv:
9382 if (info.DevicePtrInfoMap.empty()) {
9383 // For host device we still need to do the mapping for codegen,
9384 // otherwise it may try to lookup a missing value.
9385 mapUseDevice(llvm::OpenMPIRBuilder::DeviceInfoTy::Address,
9386 blockArgIface.getUseDeviceAddrBlockArgs(),
9387 useDeviceAddrVars, mapData);
9388 mapUseDevice(llvm::OpenMPIRBuilder::DeviceInfoTy::Pointer,
9389 blockArgIface.getUseDevicePtrBlockArgs(), useDevicePtrVars,
9390 mapData);
9391 }
9392 break;
9393 case BodyGenTy::NoPriv:
9394 // If device info is available then region has already been generated
9395 if (info.DevicePtrInfoMap.empty()) {
9396 if (failed(inlineConvertOmpRegions(region, "omp.data.region", builder,
9397 moduleTranslation)))
9398 return llvm::make_error<PreviouslyReportedError>();
9399 }
9400 break;
9401 }
9402 return builder.saveIP();
9403 };
9404
9405 auto customMapperCB =
9406 [&](unsigned int i) -> llvm::Expected<llvm::Function *> {
9407 if (!combinedInfo.Mappers[i])
9408 return nullptr;
9409 info.HasMapper = true;
9410 return getOrCreateUserDefinedMapperFunc(combinedInfo.Mappers[i], builder,
9411 moduleTranslation, targetDirective);
9412 };
9413
9414 llvm::OpenMPIRBuilder::LocationDescription ompLoc(builder);
9416 llvm::OpenMPIRBuilder::InsertPointTy allocaIP =
9417 findAllocInsertPoints(builder, moduleTranslation, &deallocBlocks);
9418
9419 // Pass the region's source location to the runtime, taken from the op's own
9420 // location; only offloading entries emit the mapper calls that consume it.
9421 // No need to also guard on !isTargetDevice here: this function bails out
9422 // earlier for the target device, so isOffloadEntry alone is sufficient.
9423 llvm::Value *srcLocOverride =
9424 isOffloadEntry ? getSourceLocIdentFromOp(builder, *ompBuilder, op)
9425 : nullptr;
9426
9427 llvm::OpenMPIRBuilder::InsertPointOrErrorTy afterIP = [&]() {
9428 if (isa<omp::TargetDataOp>(op))
9429 return ompBuilder->createTargetData(
9430 ompLoc, allocaIP, builder.saveIP(), deallocBlocks, deviceID, ifCond,
9431 info, genMapInfoCB, customMapperCB,
9432 /*MapperFunc=*/nullptr, bodyGenCB,
9433 /*DeviceAddrCB=*/nullptr, srcLocOverride);
9434 return ompBuilder->createTargetData(
9435 ompLoc, allocaIP, builder.saveIP(), deallocBlocks, deviceID, ifCond,
9436 info, genMapInfoCB, customMapperCB, &RTLFn,
9437 /*BodyGenCB=*/nullptr,
9438 /*DeviceAddrCB=*/nullptr, srcLocOverride);
9439 }();
9440
9441 if (failed(handleError(afterIP, *op)))
9442 return failure();
9443
9444 builder.restoreIP(*afterIP);
9445 return success();
9446}
9447
9448static LogicalResult
9449convertOmpDistribute(Operation &opInst, llvm::IRBuilderBase &builder,
9450 LLVM::ModuleTranslation &moduleTranslation) {
9451 llvm::OpenMPIRBuilder *ompBuilder = getOpenMPBuilder(moduleTranslation);
9452 auto distributeOp = cast<omp::DistributeOp>(opInst);
9453 if (failed(checkImplementationStatus(opInst)))
9454 return failure();
9455
9456 /// Process teams op reduction in distribute if the reduction is contained in
9457 /// this specific distribute op.
9458 omp::TeamsOp teamsOp = opInst.getParentOfType<omp::TeamsOp>();
9459 std::optional<ReductionVarsInfo> distributeRedInfo;
9460 if (teamsOp &&
9461 getDistributeCapturingTeamsReduction(teamsOp) == distributeOp) {
9462 distributeRedInfo.emplace(teamsOp);
9463 llvm::OpenMPIRBuilder::InsertPointTy allocaIP =
9464 findAllocInsertPoints(builder, moduleTranslation);
9465
9466 if (failed(allocAndInitializeReductionVars(*teamsOp, builder,
9467 moduleTranslation, allocaIP,
9468 *distributeRedInfo)))
9469 return failure();
9470 }
9471
9472 using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy;
9473 auto bodyGenCB =
9474 [&](InsertPointTy allocaIP, InsertPointTy codeGenIP,
9475 llvm::ArrayRef<llvm::BasicBlock *> deallocBlocks) -> llvm::Error {
9476 llvm::BasicBlock *allocaBlock = allocaIP.getNodeParent();
9477 // DistributeOp has only one region associated with it.
9478 builder.restoreIP(codeGenIP);
9479 PrivateVarsInfo privVarsInfo(distributeOp);
9480
9482 distributeOp, builder, moduleTranslation, privVarsInfo, allocaIP);
9483 if (handleError(afterAllocas, opInst).failed())
9484 return llvm::make_error<PreviouslyReportedError>();
9485
9486 // Save the alloca insertion point on ModuleTranslation stack for use in
9487 // nested regions. This must be after allocatePrivateVars, which splits
9488 // the alloca block and updates allocaIP.
9490 moduleTranslation, allocaIP.getNodeParent(), deallocBlocks);
9491
9492 if (handleError(initPrivateVars(builder, moduleTranslation, privVarsInfo),
9493 opInst)
9494 .failed())
9495 return llvm::make_error<PreviouslyReportedError>();
9496
9497 if (failed(completePrivateVars(distributeOp, builder, moduleTranslation,
9498 privVarsInfo,
9499 distributeOp.getPrivateNeedsBarrier())))
9500 return llvm::make_error<PreviouslyReportedError>();
9501
9502 llvm::OpenMPIRBuilder *ompBuilder = getOpenMPBuilder(moduleTranslation);
9503 llvm::OpenMPIRBuilder::LocationDescription ompLoc(builder);
9505 convertOmpOpRegions(distributeOp.getRegion(), "omp.distribute.region",
9506 builder, moduleTranslation);
9507 if (!regionBlock)
9508 return regionBlock.takeError();
9509 builder.SetInsertPoint((*regionBlock)->begin());
9510
9511 // Skip applying a workshare loop below when translating 'distribute
9512 // parallel do' (it's been already handled by this point while translating
9513 // the nested omp.wsloop).
9514 if (!isa_and_present<omp::WsloopOp>(distributeOp.getNestedWrapper())) {
9515 // TODO: Add support for clauses which are valid for DISTRIBUTE
9516 // constructs. Static schedule is the default.
9517 bool hasDistSchedule = distributeOp.getDistScheduleStatic();
9518 auto schedule = hasDistSchedule ? omp::ClauseScheduleKind::Distribute
9519 : omp::ClauseScheduleKind::Static;
9520 // dist_schedule clauses are ordered - otherise this should be false
9521 bool isOrdered = hasDistSchedule;
9522 std::optional<omp::ScheduleModifier> scheduleMod;
9523 bool isSimd = false;
9524 llvm::omp::WorksharingLoopType workshareLoopType =
9525 llvm::omp::WorksharingLoopType::DistributeStaticLoop;
9526 bool loopNeedsBarrier = false;
9527 llvm::Value *chunk = moduleTranslation.lookupValue(
9528 distributeOp.getDistScheduleChunkSize());
9529 llvm::CanonicalLoopInfo *loopInfo =
9530 findCurrentLoopInfo(moduleTranslation);
9531 // Nested regions can move the instruction referenced by allocaIP.
9532 allocaIP = allocaBlock->getFirstInsertionPt();
9533 llvm::OpenMPIRBuilder::InsertPointOrErrorTy wsloopIP =
9534 ompBuilder->applyWorkshareLoop(
9535 ompLoc.DL, loopInfo, allocaIP, loopNeedsBarrier,
9536 convertToScheduleKind(schedule), chunk, isSimd,
9537 scheduleMod == omp::ScheduleModifier::monotonic,
9538 scheduleMod == omp::ScheduleModifier::nonmonotonic, isOrdered,
9539 workshareLoopType, false, hasDistSchedule, chunk);
9540
9541 if (!wsloopIP)
9542 return wsloopIP.takeError();
9543 }
9544 if (failed(cleanupPrivateVars(distributeOp, builder, moduleTranslation,
9545 distributeOp.getLoc(), privVarsInfo)))
9546 return llvm::make_error<PreviouslyReportedError>();
9547
9548 return llvm::Error::success();
9549 };
9550
9552 llvm::OpenMPIRBuilder::InsertPointTy allocaIP =
9553 findAllocInsertPoints(builder, moduleTranslation, &deallocBlocks);
9554 llvm::OpenMPIRBuilder::LocationDescription ompLoc(builder);
9555 llvm::OpenMPIRBuilder::InsertPointOrErrorTy afterIP =
9556 ompBuilder->createDistribute(ompLoc, allocaIP, deallocBlocks, bodyGenCB);
9557
9558 if (failed(handleError(afterIP, opInst)))
9559 return failure();
9560
9561 builder.restoreIP(*afterIP);
9562
9563 if (distributeRedInfo) {
9564 // Process the reductions if required.
9565 return createReductionsAndCleanup(*teamsOp, builder, moduleTranslation,
9566 allocaIP, *distributeRedInfo,
9567 /*isNoWait=*/false,
9568 /*isTeamsReduction=*/true);
9569 }
9570 return success();
9571}
9572
9573/// Lowers the FlagsAttr which is applied to the module when offloading. This
9574/// attribute contains OpenMP RTL globals that can be passed as flags to the
9575/// frontend, otherwise they are set to default
9576static LogicalResult
9577convertFlagsAttr(Operation *op, mlir::omp::FlagsAttr attribute,
9578 LLVM::ModuleTranslation &moduleTranslation) {
9579 auto offloadMod = dyn_cast<omp::OffloadModuleInterface>(op);
9580 if (!offloadMod)
9581 return op->emitOpError() << "omp flags attached to non offload module op";
9582
9583 llvm::OpenMPIRBuilder *ompBuilder = getOpenMPBuilder(moduleTranslation);
9584
9585 if (offloadMod.getIsTargetDevice())
9586 ompBuilder->M.addModuleFlag(llvm::Module::Max, "openmp-device",
9587 attribute.getOpenmpDeviceVersion());
9588
9589 // The flags below are only intended to be emitted for GPU offload targets.
9590 if (!offloadMod.getIsGPU())
9591 return success();
9592
9593 if (attribute.getNoGpuLib())
9594 return success();
9595
9596 ompBuilder->createGlobalFlag(attribute.getDebugKind(),
9597 "__omp_rtl_debug_kind");
9598 ompBuilder->createGlobalFlag(attribute.getAssumeTeamsOversubscription(),
9599 "__omp_rtl_assume_teams_oversubscription");
9600 ompBuilder->createGlobalFlag(attribute.getAssumeThreadsOversubscription(),
9601 "__omp_rtl_assume_threads_oversubscription");
9602 ompBuilder->createGlobalFlag(attribute.getAssumeNoThreadState(),
9603 "__omp_rtl_assume_no_thread_state");
9604 ompBuilder->createGlobalFlag(attribute.getAssumeNoNestedParallelism(),
9605 "__omp_rtl_assume_no_nested_parallelism");
9606 return success();
9607}
9608
9609static void getTargetEntryUniqueInfo(llvm::TargetRegionEntryInfo &targetInfo,
9610 omp::TargetOp targetOp,
9611 llvm::OpenMPIRBuilder &ompBuilder,
9612 llvm::vfs::FileSystem &vfs,
9613 llvm::StringRef parentName = "") {
9614 auto fileLoc = targetOp.getLoc()->findInstanceOf<FileLineColLoc>();
9615 assert(fileLoc && "No file found from location");
9616
9617 auto fileInfoCallBack = [&fileLoc]() {
9618 return std::pair<std::string, uint64_t>(
9619 llvm::StringRef(fileLoc.getFilename()), fileLoc.getLine());
9620 };
9621
9622 targetInfo =
9623 ompBuilder.getTargetEntryUniqueInfo(fileInfoCallBack, vfs, parentName);
9624}
9625
9626// The createDeviceArgumentAccessor function generates
9627// instructions for retrieving (acessing) kernel
9628// arguments inside of the device kernel for use by
9629// the kernel. This enables different semantics such as
9630// the creation of temporary copies of data allowing
9631// semantics like read-only/no host write back kernel
9632// arguments.
9633//
9634// This currently implements a very light version of Clang's
9635// EmitParmDecl's handling of direct argument handling as well
9636// as a portion of the argument access generation based on
9637// capture types found at the end of emitOutlinedFunctionPrologue
9638// in Clang. The indirect path handling of EmitParmDecl's may be
9639// required for future work, but a direct 1-to-1 copy doesn't seem
9640// possible as the logic is rather scattered throughout Clang's
9641// lowering and perhaps we wish to deviate slightly.
9642//
9643// \param mapData - A container containing vectors of information
9644// corresponding to the input argument, which should have a
9645// corresponding entry in the MapInfoData containers
9646// OrigialValue's.
9647// \param arg - This is the generated kernel function argument that
9648// corresponds to the passed in input argument. We generated different
9649// accesses of this Argument, based on capture type and other Input
9650// related information.
9651// \param input - This is the host side value that will be passed to
9652// the kernel i.e. the kernel input, we rewrite all uses of this within
9653// the kernel (as we generate the kernel body based on the target's region
9654// which maintians references to the original input) to the retVal argument
9655// apon exit of this function inside of the OMPIRBuilder. This interlinks
9656// the kernel argument to future uses of it in the function providing
9657// appropriate "glue" instructions inbetween.
9658// \param retVal - This is the value that all uses of input inside of the
9659// kernel will be re-written to, the goal of this function is to generate
9660// an appropriate location for the kernel argument to be accessed from,
9661// e.g. ByRef will result in a temporary allocation location and then
9662// a store of the kernel argument into this allocated memory which
9663// will then be loaded from, ByCopy will use the allocated memory
9664// directly.
9665static llvm::IRBuilderBase::InsertPoint createDeviceArgumentAccessor(
9666 omp::TargetOp targetOp, MapInfoData &mapData, llvm::Argument &arg,
9667 llvm::Value *input, llvm::Value *&retVal, llvm::IRBuilderBase &builder,
9668 llvm::OpenMPIRBuilder &ompBuilder,
9669 LLVM::ModuleTranslation &moduleTranslation,
9670 llvm::IRBuilderBase::InsertPoint allocaIP,
9671 llvm::IRBuilderBase::InsertPoint codeGenIP,
9673 assert(ompBuilder.Config.isTargetDevice() &&
9674 "function only supported for target device codegen");
9675 builder.restoreIP(allocaIP);
9676
9677 omp::VariableCaptureKind capture = omp::VariableCaptureKind::ByRef;
9678 LLVM::TypeToLLVMIRTranslator typeToLLVMIRTranslator(
9679 ompBuilder.M.getContext());
9680 unsigned alignmentValue = 0;
9681 BlockArgument mlirArg;
9683 cast<omp::BlockArgOpenMPOpInterface>(*targetOp).getBlockArgsPairs(
9684 blockArgsPairs);
9685 // Find the associated MapInfoData entry for the current input
9686 for (size_t i = 0; i < mapData.MapClause.size(); ++i) {
9687 if (mapData.OriginalValue[i] == input) {
9688 auto mapOp = cast<omp::MapInfoOp>(mapData.MapClause[i]);
9689 capture = mapOp.getMapCaptureType();
9690 // Get information of alignment of mapped object
9691 alignmentValue = typeToLLVMIRTranslator.getPreferredAlignment(
9692 mapOp.getVarPtrType(), ompBuilder.M.getDataLayout());
9693
9694 // Find the corresponding entry block argument, which can be associated to
9695 // a map, use_device* or has_device* clause.
9696 for (auto &[val, arg] : blockArgsPairs) {
9697 if (mapOp.getResult() == val) {
9698 mlirArg = arg;
9699 break;
9700 }
9701 }
9702 assert(mlirArg && "expected to find entry block argument for map clause");
9703 break;
9704 }
9705 }
9706
9707 unsigned int allocaAS = ompBuilder.M.getDataLayout().getAllocaAddrSpace();
9708 unsigned int defaultAS =
9709 ompBuilder.M.getDataLayout().getProgramAddressSpace();
9710
9711 // Create the allocation for the argument.
9712 llvm::Value *v = nullptr;
9713 if (omp::opInSharedDeviceContext(*targetOp) &&
9715 // Use the beginning of the codeGenIP rather than the usual allocation point
9716 // for shared memory allocations because otherwise these would be done prior
9717 // to the target initialization call. Also, the exit block (where the
9718 // deallocation is placed) is only executed if the initialization call
9719 // succeeds.
9720 builder.SetInsertPoint(codeGenIP.getNodeParent()->getFirstInsertionPt());
9721 v = ompBuilder.createOMPAllocShared(builder, arg.getType());
9722
9723 // Create deallocations in all provided deallocation points and then restore
9724 // the insertion point to right after the new allocations.
9725 llvm::IRBuilderBase::InsertPointGuard guard(builder);
9726 for (auto deallocIP : deallocIPs) {
9727 builder.SetInsertPoint(deallocIP);
9728 ompBuilder.createOMPFreeShared(builder, v, arg.getType());
9729 }
9730 } else {
9731 // Use the current point, which was previously set to allocaIP.
9732 v = builder.CreateAlloca(arg.getType(), allocaAS);
9733
9734 if (allocaAS != defaultAS && arg.getType()->isPointerTy())
9735 v = builder.CreateAddrSpaceCast(v, builder.getPtrTy(defaultAS));
9736 }
9737
9738 builder.CreateStore(&arg, v);
9739
9740 builder.restoreIP(codeGenIP);
9741
9742 switch (capture) {
9743 case omp::VariableCaptureKind::ByCopy: {
9744 retVal = v;
9745 break;
9746 }
9747 case omp::VariableCaptureKind::ByRef: {
9748 llvm::LoadInst *loadInst = builder.CreateAlignedLoad(
9749 v->getType(), v,
9750 ompBuilder.M.getDataLayout().getPrefTypeAlign(v->getType()));
9751 // CreateAlignedLoad function creates similar LLVM IR:
9752 // %res = load ptr, ptr %input, align 8
9753 // This LLVM IR does not contain information about alignment
9754 // of the loaded value. We need to add !align metadata to unblock
9755 // optimizer. The existence of the !align metadata on the instruction
9756 // tells the optimizer that the value loaded is known to be aligned to
9757 // a boundary specified by the integer value in the metadata node.
9758 // Example:
9759 // %res = load ptr, ptr %input, align 8, !align !align_md_node
9760 // ^ ^
9761 // | |
9762 // alignment of %input address |
9763 // |
9764 // alignment of %res object
9765 if (v->getType()->isPointerTy() && alignmentValue) {
9766 llvm::MDBuilder MDB(builder.getContext());
9767 loadInst->setMetadata(
9768 llvm::LLVMContext::MD_align,
9769 llvm::MDNode::get(builder.getContext(),
9770 MDB.createConstant(llvm::ConstantInt::get(
9771 llvm::Type::getInt64Ty(builder.getContext()),
9772 alignmentValue))));
9773 }
9774 retVal = loadInst;
9775
9776 break;
9777 }
9778 case omp::VariableCaptureKind::This:
9779 case omp::VariableCaptureKind::VLAType:
9780 // TODO: Consider returning error to use standard reporting for
9781 // unimplemented features.
9782 assert(false && "Currently unsupported capture kind");
9783 break;
9784 }
9785
9786 return builder.saveIP();
9787}
9788
9789/// Follow uses of `host_eval`-defined block arguments of the given `omp.target`
9790/// operation and populate output variables with their corresponding host value
9791/// (i.e. operand evaluated outside of the target region), based on their uses
9792/// inside of the target region.
9793///
9794/// Loop bounds and steps are only optionally populated, if output vectors are
9795/// provided.
9796static void
9797extractHostEvalClauses(omp::TargetOp targetOp, Value &numThreads,
9798 Value &numTeamsLower, Value &numTeamsUpper,
9799 Value &threadLimit,
9800 llvm::SmallVectorImpl<Value> *lowerBounds = nullptr,
9801 llvm::SmallVectorImpl<Value> *upperBounds = nullptr,
9802 llvm::SmallVectorImpl<Value> *steps = nullptr) {
9803 auto blockArgIface = llvm::cast<omp::BlockArgOpenMPOpInterface>(*targetOp);
9804 for (auto item : llvm::zip_equal(targetOp.getHostEvalVars(),
9805 blockArgIface.getHostEvalBlockArgs())) {
9806 Value hostEvalVar = std::get<0>(item), blockArg = std::get<1>(item);
9807
9808 for (Operation *user : blockArg.getUsers()) {
9810 .Case([&](omp::TeamsOp teamsOp) {
9811 if (teamsOp.getNumTeamsLower() == blockArg)
9812 numTeamsLower = hostEvalVar;
9813 else if (llvm::is_contained(teamsOp.getNumTeamsUpperVars(),
9814 blockArg))
9815 numTeamsUpper = hostEvalVar;
9816 else if (!teamsOp.getThreadLimitVars().empty() &&
9817 teamsOp.getThreadLimit(0) == blockArg)
9818 threadLimit = hostEvalVar;
9819 else
9820 llvm_unreachable("unsupported host_eval use");
9821 })
9822 .Case([&](omp::ParallelOp parallelOp) {
9823 if (!parallelOp.getNumThreadsVars().empty() &&
9824 parallelOp.getNumThreads(0) == blockArg)
9825 numThreads = hostEvalVar;
9826 else
9827 llvm_unreachable("unsupported host_eval use");
9828 })
9829 .Case([&](omp::LoopNestOp loopOp) {
9830 auto processBounds =
9831 [&](OperandRange opBounds,
9832 llvm::SmallVectorImpl<Value> *outBounds) -> bool {
9833 bool found = false;
9834 for (auto [i, lb] : llvm::enumerate(opBounds)) {
9835 if (lb == blockArg) {
9836 found = true;
9837 if (outBounds)
9838 (*outBounds)[i] = hostEvalVar;
9839 }
9840 }
9841 return found;
9842 };
9843 bool found =
9844 processBounds(loopOp.getLoopLowerBounds(), lowerBounds);
9845 found = processBounds(loopOp.getLoopUpperBounds(), upperBounds) ||
9846 found;
9847 found = processBounds(loopOp.getLoopSteps(), steps) || found;
9848 (void)found;
9849 assert(found && "unsupported host_eval use");
9850 })
9851 .DefaultUnreachable("unsupported host_eval use");
9852 }
9853 }
9854}
9855
9856/// If \p op is of the given type parameter, return it casted to that type.
9857/// Otherwise, if its immediate parent operation (or some other higher-level
9858/// parent, if \p immediateParent is false) is of that type, return that parent
9859/// casted to the given type.
9860///
9861/// If \p op is \c null or neither it or its parent(s) are of the specified
9862/// type, return a \c null operation.
9863template <typename OpTy>
9864static OpTy castOrGetParentOfType(Operation *op, bool immediateParent = false) {
9865 if (!op)
9866 return OpTy();
9867
9868 if (OpTy casted = dyn_cast<OpTy>(op))
9869 return casted;
9870
9871 if (immediateParent)
9872 return dyn_cast_if_present<OpTy>(op->getParentOp());
9873
9874 return op->getParentOfType<OpTy>();
9875}
9876
9877/// If the given \p value is defined by an \c llvm.mlir.constant operation and
9878/// it is of an integer type, return its value.
9879static std::optional<int64_t> extractConstInteger(Value value) {
9880 if (!value)
9881 return std::nullopt;
9882
9883 if (auto constOp = value.getDefiningOp<LLVM::ConstantOp>())
9884 if (auto constAttr = dyn_cast<IntegerAttr>(constOp.getValue()))
9885 return constAttr.getInt();
9886
9887 return std::nullopt;
9888}
9889
9890static uint64_t getTypeByteSize(mlir::Type type, const DataLayout &dl) {
9891 uint64_t sizeInBits = dl.getTypeSizeInBits(type);
9892 uint64_t sizeInBytes = sizeInBits / 8;
9893 return sizeInBytes;
9894}
9895
9896template <typename OpTy>
9897static uint64_t getReductionDataSize(OpTy &op) {
9898 if (op.getNumReductionVars() > 0) {
9900 collectReductionDecls(op, reductions);
9901
9903 members.reserve(reductions.size());
9904 for (omp::DeclareReductionOp &red : reductions) {
9905 // For by-ref reductions, use the actual element type rather than the
9906 // pointer type so that the buffer size matches the access pattern in
9907 // the copy/reduce callbacks generated by OMPIRBuilder.
9908 if (red.getByrefElementType())
9909 members.push_back(*red.getByrefElementType());
9910 else
9911 members.push_back(red.getType());
9912 }
9913 Operation *opp = op.getOperation();
9914 auto structType = mlir::LLVM::LLVMStructType::getLiteral(
9915 opp->getContext(), members, /*isPacked=*/false);
9916 DataLayout dl = DataLayout(opp->getParentOfType<ModuleOp>());
9917 return getTypeByteSize(structType, dl);
9918 }
9919 return 0;
9920}
9921
9922/// Populate default `MinTeams`, `MaxTeams` and `MaxThreads` to their default
9923/// values as stated by the corresponding clauses, if constant.
9924///
9925/// These default values must be set before the creation of the outlined LLVM
9926/// function for the target region, so that they can be used to initialize the
9927/// corresponding global `ConfigurationEnvironmentTy` structure.
9928static void
9929initTargetDefaultAttrs(omp::TargetOp targetOp, Operation *capturedOp,
9930 llvm::OpenMPIRBuilder::TargetKernelDefaultAttrs &attrs,
9931 bool isTargetDevice, bool isGPU) {
9932 // TODO: Handle constant 'if' clauses.
9933
9934 Value numThreads, numTeamsLower, numTeamsUpper, threadLimit;
9935 if (!isTargetDevice) {
9936 extractHostEvalClauses(targetOp, numThreads, numTeamsLower, numTeamsUpper,
9937 threadLimit);
9938 } else {
9939 // In the target device, values for these clauses are not passed as
9940 // host_eval, but instead evaluated prior to entry to the region. This
9941 // ensures values are mapped and available inside of the target region.
9942 if (auto teamsOp = castOrGetParentOfType<omp::TeamsOp>(capturedOp)) {
9943 numTeamsLower = teamsOp.getNumTeamsLower();
9944 // Handle num_teams upper bounds (only first value for now)
9945 if (!teamsOp.getNumTeamsUpperVars().empty())
9946 numTeamsUpper = teamsOp.getNumTeams(0);
9947 if (!teamsOp.getThreadLimitVars().empty())
9948 threadLimit = teamsOp.getThreadLimit(0);
9949 }
9950
9951 if (auto parallelOp = castOrGetParentOfType<omp::ParallelOp>(capturedOp)) {
9952 if (!parallelOp.getNumThreadsVars().empty())
9953 numThreads = parallelOp.getNumThreads(0);
9954 }
9955 }
9956
9957 // Handle clauses impacting the number of teams.
9958
9959 int32_t minTeamsVal = 1, maxTeamsVal = -1;
9960 if (castOrGetParentOfType<omp::TeamsOp>(capturedOp)) {
9961 // TODO: Use `hostNumTeamsLower` to initialize `minTeamsVal`. For now,
9962 // match clang and set min and max to the same value.
9963 if (numTeamsUpper) {
9964 if (auto val = extractConstInteger(numTeamsUpper))
9965 minTeamsVal = maxTeamsVal = *val;
9966 } else {
9967 minTeamsVal = maxTeamsVal = 0;
9968 }
9969 } else if (castOrGetParentOfType<omp::ParallelOp>(capturedOp,
9970 /*immediateParent=*/true) ||
9972 /*immediateParent=*/true)) {
9973 minTeamsVal = maxTeamsVal = 1;
9974 } else {
9975 minTeamsVal = maxTeamsVal = -1;
9976 }
9977
9978 // Handle clauses impacting the number of threads.
9979
9980 auto setMaxValueFromClause = [](Value clauseValue, int32_t &result) {
9981 if (!clauseValue)
9982 return;
9983
9984 if (auto val = extractConstInteger(clauseValue))
9985 result = *val;
9986
9987 // Found an applicable clause, so it's not undefined. Mark as unknown
9988 // because it's not constant.
9989 if (result < 0)
9990 result = 0;
9991 };
9992
9993 // Extract 'thread_limit' clause from 'target' and 'teams' directives.
9994 int32_t targetThreadLimitVal = -1, teamsThreadLimitVal = -1;
9995 if (!targetOp.getThreadLimitVars().empty())
9996 setMaxValueFromClause(targetOp.getThreadLimit(0), targetThreadLimitVal);
9997 setMaxValueFromClause(threadLimit, teamsThreadLimitVal);
9998
9999 // Extract 'max_threads' clause from 'parallel' or set to 1 if it's SIMD.
10000 int32_t maxThreadsVal = -1;
10002 setMaxValueFromClause(numThreads, maxThreadsVal);
10003 else if (castOrGetParentOfType<omp::SimdOp>(capturedOp,
10004 /*immediateParent=*/true))
10005 maxThreadsVal = 1;
10006
10007 // For max values, < 0 means unset, == 0 means set but unknown. Select the
10008 // minimum value between 'max_threads' and 'thread_limit' clauses that were
10009 // set.
10010 int32_t combinedMaxThreadsVal = targetThreadLimitVal;
10011 if (combinedMaxThreadsVal < 0 ||
10012 (teamsThreadLimitVal >= 0 && teamsThreadLimitVal < combinedMaxThreadsVal))
10013 combinedMaxThreadsVal = teamsThreadLimitVal;
10014
10015 if (combinedMaxThreadsVal < 0 ||
10016 (maxThreadsVal >= 0 && maxThreadsVal < combinedMaxThreadsVal))
10017 combinedMaxThreadsVal = maxThreadsVal;
10018
10019 int32_t reductionDataSize = 0;
10020 if (isGPU && capturedOp) {
10021 if (auto teamsOp = castOrGetParentOfType<omp::TeamsOp>(capturedOp))
10022 reductionDataSize = getReductionDataSize(teamsOp);
10023 }
10024
10025 // Update kernel bounds structure for the `OpenMPIRBuilder` to use.
10026 // Use the kernel_type attribute set by the frontend instead of analyzing IR.
10027 omp::TargetExecMode execMode = targetOp.getKernelType();
10028 switch (execMode) {
10029 case omp::TargetExecMode::bare:
10030 attrs.ExecFlags = llvm::omp::OMP_TGT_EXEC_MODE_BARE;
10031 break;
10032 case omp::TargetExecMode::generic:
10033 attrs.ExecFlags = llvm::omp::OMP_TGT_EXEC_MODE_GENERIC;
10034 break;
10035 case omp::TargetExecMode::spmd:
10036 attrs.ExecFlags = llvm::omp::OMP_TGT_EXEC_MODE_SPMD;
10037 break;
10038 case omp::TargetExecMode::spmd_no_loop:
10039 attrs.ExecFlags = llvm::omp::OMP_TGT_EXEC_MODE_SPMD_NO_LOOP;
10040 break;
10041 }
10042 attrs.MinTeams.front() = minTeamsVal;
10043 attrs.MaxTeams.front() = maxTeamsVal;
10044 attrs.MinThreads.front() = 1;
10045 attrs.MaxThreads.front() = combinedMaxThreadsVal;
10046 attrs.ReductionDataSize = reductionDataSize;
10047}
10048
10049/// Gather LLVM runtime values for all clauses evaluated in the host that are
10050/// passed to the kernel invocation.
10051///
10052/// This function must be called only when compiling for the host. Also, it will
10053/// only provide correct results if it's called after the body of \c targetOp
10054/// has been fully generated.
10055static void
10056initTargetRuntimeAttrs(llvm::IRBuilderBase &builder,
10057 LLVM::ModuleTranslation &moduleTranslation,
10058 omp::TargetOp targetOp, Operation *capturedOp,
10059 llvm::OpenMPIRBuilder::TargetKernelRuntimeAttrs &attrs) {
10060 omp::LoopNestOp loopOp = castOrGetParentOfType<omp::LoopNestOp>(capturedOp);
10061 unsigned numLoops = loopOp ? loopOp.getNumLoops() : 0;
10062
10063 Value numThreads, numTeamsLower, numTeamsUpper, teamsThreadLimit;
10064 llvm::SmallVector<Value> lowerBounds(numLoops), upperBounds(numLoops),
10065 steps(numLoops);
10066 extractHostEvalClauses(targetOp, numThreads, numTeamsLower, numTeamsUpper,
10067 teamsThreadLimit, &lowerBounds, &upperBounds, &steps);
10068
10069 // TODO: Handle constant 'if' clauses.
10070 if (!targetOp.getThreadLimitVars().empty()) {
10071 Value targetThreadLimit = targetOp.getThreadLimit(0);
10072 attrs.TargetThreadLimit.front() =
10073 moduleTranslation.lookupValue(targetThreadLimit);
10074 }
10075
10076 // The __kmpc_push_num_teams_51 function expects int32 as the arguments. So,
10077 // truncate or sign extend lower and upper num_teams bounds as well as
10078 // thread_limit to match int32 ABI requirements for the OpenMP runtime.
10079 if (numTeamsLower)
10080 attrs.MinTeams.front() = builder.CreateSExtOrTrunc(
10081 moduleTranslation.lookupValue(numTeamsLower), builder.getInt32Ty());
10082
10083 if (numTeamsUpper)
10084 attrs.MaxTeams.front() = builder.CreateSExtOrTrunc(
10085 moduleTranslation.lookupValue(numTeamsUpper), builder.getInt32Ty());
10086
10087 if (teamsThreadLimit)
10088 attrs.TeamsThreadLimit.front() = builder.CreateSExtOrTrunc(
10089 moduleTranslation.lookupValue(teamsThreadLimit), builder.getInt32Ty());
10090
10091 if (numThreads)
10092 attrs.MaxThreads.front() = moduleTranslation.lookupValue(numThreads);
10093
10094 if (targetOp.hasHostEvalTripCount()) {
10095 llvm::OpenMPIRBuilder *ompBuilder = getOpenMPBuilder(moduleTranslation);
10096 attrs.LoopTripCount = nullptr;
10097
10098 // To calculate the trip count, we multiply together the trip counts of
10099 // every collapsed canonical loop. We don't need to create the loop nests
10100 // here, since we're only interested in the trip count.
10101 for (auto [loopLower, loopUpper, loopStep] :
10102 llvm::zip_equal(lowerBounds, upperBounds, steps)) {
10103 llvm::Value *lowerBound = moduleTranslation.lookupValue(loopLower);
10104 llvm::Value *upperBound = moduleTranslation.lookupValue(loopUpper);
10105 llvm::Value *step = moduleTranslation.lookupValue(loopStep);
10106
10107 if (!lowerBound || !upperBound || !step) {
10108 attrs.LoopTripCount = nullptr;
10109 break;
10110 }
10111
10112 llvm::OpenMPIRBuilder::LocationDescription loc(builder);
10113 llvm::Value *tripCount = ompBuilder->calculateCanonicalLoopTripCount(
10114 loc, lowerBound, upperBound, step, /*IsSigned=*/true,
10115 loopOp.getLoopInclusive());
10116
10117 if (!attrs.LoopTripCount) {
10118 attrs.LoopTripCount = tripCount;
10119 continue;
10120 }
10121
10122 // TODO: Enable UndefinedSanitizer to diagnose an overflow here.
10123 attrs.LoopTripCount = builder.CreateMul(attrs.LoopTripCount, tripCount,
10124 {}, /*HasNUW=*/true);
10125 }
10126 }
10127
10128 attrs.DeviceID = builder.getInt64(llvm::omp::OMP_DEVICEID_UNDEF);
10129 if (mlir::Value devId = targetOp.getDevice()) {
10130 attrs.DeviceID = moduleTranslation.lookupValue(devId);
10131 attrs.DeviceID =
10132 builder.CreateSExtOrTrunc(attrs.DeviceID, builder.getInt64Ty());
10133 }
10134}
10135
10136static llvm::omp::OMPDynGroupprivateFallbackType
10137getDynGroupprivateFallbackType(omp::FallbackModifierAttr fallbackAttr) {
10138 omp::FallbackModifier fb = fallbackAttr ? fallbackAttr.getValue()
10139 : omp::FallbackModifier::default_mem;
10140 switch (fb) {
10141 case omp::FallbackModifier::abort:
10142 return llvm::omp::OMPDynGroupprivateFallbackType::Abort;
10143 case omp::FallbackModifier::null:
10144 return llvm::omp::OMPDynGroupprivateFallbackType::Null;
10145 case omp::FallbackModifier::default_mem:
10146 return llvm::omp::OMPDynGroupprivateFallbackType::DefaultMem;
10147 }
10148
10149 llvm_unreachable("unexpected dyn_groupprivate fallback type");
10150}
10151
10152static LogicalResult
10153convertOmpTarget(Operation &opInst, llvm::IRBuilderBase &builder,
10154 LLVM::ModuleTranslation &moduleTranslation) {
10155 auto targetOp = cast<omp::TargetOp>(opInst);
10156
10157 // The current debug location already has the DISubprogram for the outlined
10158 // function that will be created for the target op. We save it here so that
10159 // we can set it on the outlined function.
10160 llvm::DebugLoc outlinedFnLoc = builder.getCurrentDebugLocation();
10161 if (failed(checkImplementationStatus(opInst)))
10162 return failure();
10163
10164 // During the handling of target op, we will generate instructions in the
10165 // parent function like call to the oulined function or branch to a new
10166 // BasicBlock. We set the debug location here to parent function so that those
10167 // get the correct debug locations. For outlined functions, the normal MLIR op
10168 // conversion will automatically pick the correct location.
10169 llvm::BasicBlock *parentBB = builder.GetInsertBlock();
10170 assert(parentBB && "No insert block is set for the builder");
10171 llvm::Function *parentLLVMFn = parentBB->getParent();
10172 assert(parentLLVMFn && "Parent Function must be valid");
10173 if (llvm::DISubprogram *SP = parentLLVMFn->getSubprogram())
10174 builder.SetCurrentDebugLocation(llvm::DILocation::get(
10175 parentLLVMFn->getContext(), outlinedFnLoc.getLine(),
10176 outlinedFnLoc.getCol(), SP, outlinedFnLoc.getInlinedAt()));
10177
10178 // OMPIRBuilder emits runtime calls into the outlined function before bodyCB
10179 // below gets a chance to attach the subprogram to it, so it needs the
10180 // outlined function's location handed to it separately. Only pass it under
10181 // the same condition that decides whether the subprogram is attached at all:
10182 // a location may not be attached to an instruction in a function that has no
10183 // subprogram.
10184 llvm::DebugLoc outlinedFnDbgLoc;
10185 if (outlinedFnLoc && parentLLVMFn->getSubprogram())
10186 outlinedFnDbgLoc = outlinedFnLoc;
10187
10188 llvm::OpenMPIRBuilder *ompBuilder = getOpenMPBuilder(moduleTranslation);
10189 bool isTargetDevice = ompBuilder->Config.isTargetDevice();
10190 bool isGPU = ompBuilder->Config.isGPU();
10191
10192 auto parentFn = opInst.getParentOfType<LLVM::LLVMFuncOp>();
10193 auto argIface = cast<omp::BlockArgOpenMPOpInterface>(opInst);
10194 auto &targetRegion = targetOp.getRegion();
10195 // Holds the private vars that have been mapped along with the block
10196 // argument that corresponds to the MapInfoOp corresponding to the private
10197 // var in question. So, for instance:
10198 //
10199 // %10 = omp.map.info var_ptr(%6#0 : !fir.ref<!fir.box<!fir.heap<i32>>>, ..)
10200 // omp.target map_entries(%10 -> %arg0) private(@box.privatizer %6#0-> %arg1)
10201 //
10202 // Then, %10 has been created so that the descriptor can be used by the
10203 // privatizer @box.privatizer on the device side. Here we'd record {%6#0,
10204 // %arg0} in the mappedPrivateVars map.
10205 llvm::DenseMap<Value, Value> mappedPrivateVars;
10206 DataLayout dl = DataLayout(opInst.getParentOfType<ModuleOp>());
10207 SmallVector<Value> mapVars = targetOp.getMapVars();
10208 SmallVector<Value> hdaVars = targetOp.getHasDeviceAddrVars();
10209 ArrayRef<BlockArgument> mapBlockArgs = argIface.getMapBlockArgs();
10210 ArrayRef<BlockArgument> hdaBlockArgs = argIface.getHasDeviceAddrBlockArgs();
10211 llvm::Function *llvmOutlinedFn = nullptr;
10212 TargetDirectiveEnumTy targetDirective =
10213 getTargetDirectiveEnumTyFromOp(&opInst);
10214
10215 // TODO: It can also be false if a compile-time constant `false` IF clause is
10216 // specified.
10217 bool isOffloadEntry =
10218 isTargetDevice || !ompBuilder->Config.TargetTriples.empty();
10219
10220 // Resolve in_reduction clauses on omp.target for the host. From the target
10221 // device's perspective an in_reduction list item behaves as a regular
10222 // map(tofrom) variable, so no special handling is needed there; only the
10223 // host redirects the mapped value to the per-task reduction-private storage
10224 // returned by __kmpc_task_reduction_get_th_data (emitted inside the
10225 // to-be-outlined target task body). This applies to both offloading and
10226 // non-offloading host modules.
10227 //
10228 // The target body has no dedicated in_reduction block argument: each
10229 // in_reduction variable is accessed through its map_entries block argument.
10230 // So each in_reduction variable must also be captured by a matching
10231 // map_entries entry (guaranteed by the verifier); without one the outlined
10232 // body would reference a value defined in the host function. Record, for each
10233 // in_reduction variable, the position of that map entry so the corresponding
10234 // map block argument can be redirected inside the body. The in_reduction
10235 // operand itself is used as the `orig` argument of the runtime lookup.
10236 SmallVector<llvm::Value *> inRedOrigPtrs;
10237 SmallVector<unsigned> inRedMapArgIdx;
10238 if (!targetOp.getInReductionVars().empty() && !isTargetDevice) {
10239 inRedOrigPtrs.reserve(targetOp.getInReductionVars().size());
10240 inRedMapArgIdx.reserve(targetOp.getInReductionVars().size());
10241 for (Value v : targetOp.getInReductionVars()) {
10242 // Select the map_entries entry that captures this in_reduction operand.
10243 // The verifier guarantees at least one match exists; more than one
10244 // matching entry is a lowering ambiguity (the redirect cannot pick which
10245 // map argument to rebind).
10246 std::optional<unsigned> matchIdx;
10247 for (auto [idx, mapV] : llvm::enumerate(targetOp.getMapVars())) {
10248 auto mapInfo = mapV.getDefiningOp<omp::MapInfoOp>();
10249 if (v != mapInfo.getVarPtr())
10250 continue;
10251 if (matchIdx)
10252 return targetOp.emitError()
10253 << "in_reduction variable on omp.target has multiple matching "
10254 "map_entries entries; the redirect target is ambiguous";
10255 matchIdx = idx;
10256 }
10257 // The verifier requires a capturing map entry for every in_reduction
10258 // operand, so a match must exist here.
10259 assert(matchIdx &&
10260 "TargetOp verifier guarantees a matching map_entries entry for "
10261 "each in_reduction variable");
10262 inRedMapArgIdx.push_back(*matchIdx);
10263 // The runtime `orig` pointer is the in_reduction operand itself, the
10264 // reduction variable the enclosing taskgroup registered.
10265 inRedOrigPtrs.push_back(moduleTranslation.lookupValue(v));
10266 }
10267 }
10268
10269 // For some private variables, the MapsForPrivatizedVariablesPass
10270 // creates MapInfoOp instances. Go through the private variables and
10271 // the mapped variables so that during codegeneration we are able
10272 // to quickly look up the corresponding map variable, if any for each
10273 // private variable.
10274 if (!targetOp.getPrivateVars().empty() && !targetOp.getMapVars().empty()) {
10275 OperandRange privateVars = targetOp.getPrivateVars();
10276 std::optional<ArrayAttr> privateSyms = targetOp.getPrivateSyms();
10277 std::optional<DenseI64ArrayAttr> privateMapIndices =
10278 targetOp.getPrivateMapsAttr();
10279
10280 for (auto [privVarIdx, privVarSymPair] :
10281 llvm::enumerate(llvm::zip_equal(privateVars, *privateSyms))) {
10282 auto privVar = std::get<0>(privVarSymPair);
10283 auto privSym = std::get<1>(privVarSymPair);
10284
10285 SymbolRefAttr privatizerName = llvm::cast<SymbolRefAttr>(privSym);
10286 omp::PrivateClauseOp privatizer =
10287 findPrivatizer(targetOp, privatizerName);
10288
10289 if (!privatizer.needsMap())
10290 continue;
10291
10292 mlir::Value mappedValue =
10293 targetOp.getMappedValueForPrivateVar(privVarIdx);
10294 assert(mappedValue && "Expected to find mapped value for a privatized "
10295 "variable that needs mapping");
10296
10297 // The MapInfoOp defining the map var isn't really needed later.
10298 // So, we don't store it in any datastructure. Instead, we just
10299 // do some sanity checks on it right now.
10300 auto mapInfoOp = mappedValue.getDefiningOp<omp::MapInfoOp>();
10301 [[maybe_unused]] Type varType = mapInfoOp.getVarPtrType();
10302
10303 // Check #1: Check that the type of the private variable matches
10304 // the type of the variable being mapped.
10305 if (!isa<LLVM::LLVMPointerType>(privVar.getType()))
10306 assert(
10307 varType == privVar.getType() &&
10308 "Type of private var doesn't match the type of the mapped value");
10309
10310 // Ok, only 1 sanity check for now.
10311 // Record the block argument corresponding to this mapvar.
10312 mappedPrivateVars.insert(
10313 {privVar,
10314 targetRegion.getArgument(argIface.getMapBlockArgsStart() +
10315 (*privateMapIndices)[privVarIdx])});
10316 }
10317 }
10318
10319 using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy;
10320 auto bodyCB = [&](InsertPointTy allocaIP, InsertPointTy codeGenIP,
10321 ArrayRef<llvm::BasicBlock *> deallocBlocks)
10322 -> llvm::OpenMPIRBuilder::InsertPointOrErrorTy {
10323 llvm::IRBuilderBase::InsertPointGuard guard(builder);
10324 builder.SetCurrentDebugLocation(llvm::DebugLoc());
10325 // Forward target-cpu and target-features function attributes from the
10326 // original function to the new outlined function.
10327 llvm::Function *llvmParentFn =
10328 moduleTranslation.lookupFunction(parentFn.getName());
10329 llvmOutlinedFn = codeGenIP.getNodeParent()->getParent();
10330 assert(llvmParentFn && llvmOutlinedFn &&
10331 "Both parent and outlined functions must exist at this point");
10332
10333 if (outlinedFnLoc && llvmParentFn->getSubprogram())
10334 llvmOutlinedFn->setSubprogram(outlinedFnLoc->getScope()->getSubprogram());
10335
10336 if (auto attr = llvmParentFn->getFnAttribute("target-cpu");
10337 attr.isStringAttribute())
10338 llvmOutlinedFn->addFnAttr(attr);
10339
10340 if (auto attr = llvmParentFn->getFnAttribute("target-features");
10341 attr.isStringAttribute())
10342 llvmOutlinedFn->addFnAttr(attr);
10343
10344 for (auto [idx, arg] : llvm::enumerate(mapBlockArgs)) {
10345 // in_reduction list items on omp.target are accessed through their
10346 // map_entries block argument, which is redirected below to the per-task
10347 // reduction-private storage returned by the runtime. Skip the default
10348 // host-value mapping for those block arguments so the write-once
10349 // mapValue mapping is free to be set to the private pointer.
10350 if (llvm::is_contained(inRedMapArgIdx, idx))
10351 continue;
10352 auto mapInfoOp = cast<omp::MapInfoOp>(mapVars[idx].getDefiningOp());
10353 llvm::Value *mapOpValue =
10354 moduleTranslation.lookupValue(mapInfoOp.getVarPtr());
10355 moduleTranslation.mapValue(arg, mapOpValue);
10356 }
10357 for (auto [arg, mapOp] : llvm::zip_equal(hdaBlockArgs, hdaVars)) {
10358 auto mapInfoOp = cast<omp::MapInfoOp>(mapOp.getDefiningOp());
10359 llvm::Value *mapOpValue =
10360 moduleTranslation.lookupValue(mapInfoOp.getVarPtr());
10361 moduleTranslation.mapValue(arg, mapOpValue);
10362 }
10363
10364 // Do privatization after moduleTranslation has already recorded
10365 // mapped values.
10366 PrivateVarsInfo privateVarsInfo(targetOp);
10367
10369 allocatePrivateVars(targetOp, builder, moduleTranslation,
10370 privateVarsInfo, allocaIP, &mappedPrivateVars);
10371
10372 if (failed(handleError(afterAllocas, *targetOp)))
10373 return llvm::make_error<PreviouslyReportedError>();
10374
10375 builder.restoreIP(codeGenIP);
10376 if (handleError(initPrivateVars(builder, moduleTranslation, privateVarsInfo,
10377 &mappedPrivateVars),
10378 *targetOp)
10379 .failed())
10380 return llvm::make_error<PreviouslyReportedError>();
10381
10382 if (failed(completePrivateVars(
10383 targetOp, builder, moduleTranslation, privateVarsInfo,
10384 targetOp.getPrivateNeedsBarrier(), /*moldVars=*/{},
10385 /*llvmPrivateVars=*/{}, &mappedPrivateVars)))
10386 return llvm::make_error<PreviouslyReportedError>();
10387
10388 // The target body accesses each in_reduction variable through its
10389 // map_entries block argument. Redirect that block argument to the per-task
10390 // private storage returned by __kmpc_task_reduction_get_th_data so the body
10391 // accumulates into the reduction-private copy rather than the mapped
10392 // original. The lookup must run inside the target task body so the gtid
10393 // corresponds to the executing thread. The descriptor argument is NULL: the
10394 // runtime walks enclosing taskgroups to locate the matching task_reduction
10395 // registration for `origPtr`. Mirrors the in_reduction handling on
10396 // omp.taskloop.context.
10397 if (!inRedOrigPtrs.empty()) {
10398 // Collect, per item, the type the private pointer must have (the map
10399 // block argument's type), and, through the callback, rebind the map block
10400 // argument that stands in for each in_reduction list item to the per-task
10401 // reduction-private storage the runtime returns.
10402 SmallVector<llvm::Type *> inRedResultPtrTys;
10403 inRedResultPtrTys.reserve(inRedMapArgIdx.size());
10404 for (unsigned mapArgIdx : inRedMapArgIdx)
10405 inRedResultPtrTys.push_back(
10406 moduleTranslation.convertType(mapBlockArgs[mapArgIdx].getType()));
10407
10408 llvm::OpenMPIRBuilder::LocationDescription bodyLoc(builder);
10409 llvm::OpenMPIRBuilder::InsertPointTy redIP =
10410 ompBuilder->createTargetInReduction(
10411 bodyLoc, inRedOrigPtrs, inRedResultPtrTys,
10412 [&](unsigned idx, llvm::Value *priv) {
10413 moduleTranslation.mapValue(mapBlockArgs[inRedMapArgIdx[idx]],
10414 priv);
10415 });
10416 builder.restoreIP(redIP);
10417 }
10418
10420 moduleTranslation, allocaIP.getNodeParent(), deallocBlocks);
10422 targetRegion, "omp.target", builder, moduleTranslation);
10423
10424 if (failed(handleError(exitBlock, *targetOp)))
10425 return llvm::make_error<PreviouslyReportedError>();
10426
10427 builder.SetInsertPoint(exitBlock.get()->getTerminator());
10428
10429 if (failed(cleanupPrivateVars(targetOp, builder, moduleTranslation,
10430 targetOp.getLoc(), privateVarsInfo)))
10431 return llvm::make_error<PreviouslyReportedError>();
10432
10433 return builder.saveIP();
10434 };
10435
10436 StringRef parentName = parentFn.getName();
10437
10438 llvm::TargetRegionEntryInfo entryInfo;
10439
10440 getTargetEntryUniqueInfo(entryInfo, targetOp,
10441 *getOpenMPBuilder(moduleTranslation),
10442 moduleTranslation.getFileSystem(), parentName);
10443
10444 MapInfoData mapData;
10445 collectMapDataFromMapOperands(mapData, mapVars, moduleTranslation, dl,
10446 builder, /*useDevPtrOperands=*/{},
10447 /*useDevAddrOperands=*/{}, hdaVars);
10448
10449 MapInfosTy combinedInfos;
10450 auto genMapInfoCB =
10451 [&](llvm::OpenMPIRBuilder::InsertPointTy codeGenIP) -> MapInfosTy & {
10452 builder.restoreIP(codeGenIP);
10453 genMapInfos(builder, moduleTranslation, dl, combinedInfos, mapData,
10454 targetDirective);
10455
10456 // Append a null entry for the implicit dyn_ptr argument so the argument
10457 // count sent to the runtime already includes it.
10458 auto *nullPtr = llvm::Constant::getNullValue(builder.getPtrTy());
10459 combinedInfos.BasePointers.push_back(nullPtr);
10460 combinedInfos.Pointers.push_back(nullPtr);
10461 combinedInfos.DevicePointers.push_back(
10462 llvm::OpenMPIRBuilder::DeviceInfoTy::None);
10463 combinedInfos.Sizes.push_back(builder.getInt64(0));
10464 combinedInfos.Types.push_back(
10465 llvm::omp::OpenMPOffloadMappingFlags::OMP_MAP_TARGET_PARAM |
10466 llvm::omp::OpenMPOffloadMappingFlags::OMP_MAP_LITERAL);
10467 // TODO: set HasAttachPtr from Flang for pointee-storage entries.
10468 combinedInfos.HasAttachPtr.push_back(false);
10469 if (!combinedInfos.Names.empty())
10470 combinedInfos.Names.push_back(nullPtr);
10471 combinedInfos.Mappers.push_back(nullptr);
10472
10473 return combinedInfos;
10474 };
10475
10476 auto argAccessorCB = [&](llvm::Argument &arg, llvm::Value *input,
10477 llvm::Value *&retVal, InsertPointTy allocaIP,
10478 InsertPointTy codeGenIP,
10480 -> llvm::OpenMPIRBuilder::InsertPointOrErrorTy {
10481 llvm::IRBuilderBase::InsertPointGuard guard(builder);
10482 builder.SetCurrentDebugLocation(llvm::DebugLoc());
10483 // We just return the unaltered argument for the host function
10484 // for now, some alterations may be required in the future to
10485 // keep host fallback functions working identically to the device
10486 // version (e.g. pass ByCopy values should be treated as such on
10487 // host and device, currently not always the case)
10488 if (!isTargetDevice) {
10489 retVal = cast<llvm::Value>(&arg);
10490 return codeGenIP;
10491 }
10492
10493 return createDeviceArgumentAccessor(targetOp, mapData, arg, input, retVal,
10494 builder, *ompBuilder, moduleTranslation,
10495 allocaIP, codeGenIP, deallocIPs);
10496 };
10497
10498 llvm::OpenMPIRBuilder::TargetKernelRuntimeAttrs runtimeAttrs;
10499 llvm::OpenMPIRBuilder::TargetKernelDefaultAttrs defaultAttrs;
10500 Operation *targetCapturedOp =
10501 cast<omp::ComposableOpInterface>(*targetOp).findCapturedOp();
10502 initTargetDefaultAttrs(targetOp, targetCapturedOp, defaultAttrs,
10503 isTargetDevice, isGPU);
10504
10505 // Collect host-evaluated values needed to properly launch the kernel from the
10506 // host.
10507 if (!isTargetDevice)
10508 initTargetRuntimeAttrs(builder, moduleTranslation, targetOp,
10509 targetCapturedOp, runtimeAttrs);
10510
10511 // Pass host-evaluated values as parameters to the kernel / host fallback,
10512 // except if they are constants. In any case, map the MLIR block argument to
10513 // the corresponding LLVM values.
10515 SmallVector<Value> hostEvalVars = targetOp.getHostEvalVars();
10516 ArrayRef<BlockArgument> hostEvalBlockArgs = argIface.getHostEvalBlockArgs();
10517 for (auto [arg, var] : llvm::zip_equal(hostEvalBlockArgs, hostEvalVars)) {
10518 llvm::Value *value = moduleTranslation.lookupValue(var);
10519 moduleTranslation.mapValue(arg, value);
10520
10521 if (!llvm::isa<llvm::Constant>(value))
10522 kernelInput.push_back(value);
10523 }
10524
10525 for (size_t i = 0, e = mapData.OriginalValue.size(); i != e; ++i) {
10526 // 1) Declare target arguments are not passed to kernels as arguments.
10527 // 2) Attach maps are not passed in as arguments to kernels, except for
10528 // private attach maps used for corresponding-pointer initialization.
10529 // 3) Children of record objects are not passed in as arguments.
10530 // TODO: We currently do not handle cases where a member is explicitly
10531 // passed in as an argument, this will likley need to be handled in
10532 // the near future, rather than using IsAMember, it may be better to
10533 // test if the relevant BlockArg is used within the target region and
10534 // then use that as a basis for exclusion in the kernel inputs.
10535 using MapFlags = llvm::omp::OpenMPOffloadMappingFlags;
10536 bool isAttachMap = (mapData.Types[i] & MapFlags::OMP_MAP_ATTACH) ==
10537 MapFlags::OMP_MAP_ATTACH;
10538 bool isPrivateTargetParam =
10539 (mapData.Types[i] &
10540 (MapFlags::OMP_MAP_PRIVATE | MapFlags::OMP_MAP_TARGET_PARAM)) ==
10541 (MapFlags::OMP_MAP_PRIVATE | MapFlags::OMP_MAP_TARGET_PARAM);
10542
10543 if (!mapData.IsDeclareTarget[i] && !mapData.IsAMember[i] &&
10544 (!isAttachMap || (isAttachMap && isPrivateTargetParam)))
10545 kernelInput.push_back(mapData.OriginalValue[i]);
10546 }
10547
10549 llvm::OpenMPIRBuilder::InsertPointTy allocaIP =
10550 findAllocInsertPoints(builder, moduleTranslation, &deallocBlocks);
10551
10552 llvm::OpenMPIRBuilder::DependenciesInfo dds;
10553 if (failed(buildDependData(
10554 targetOp.getDependVars(), targetOp.getDependKinds(),
10555 targetOp.getDependIterated(), targetOp.getDependIteratedKinds(),
10556 builder, moduleTranslation, dds)))
10557 return failure();
10558
10559 llvm::OpenMPIRBuilder::LocationDescription ompLoc(builder);
10560
10561 llvm::OpenMPIRBuilder::TargetDataInfo info(
10562 /*RequiresDevicePointerInfo=*/false,
10563 /*SeparateBeginEndCalls=*/true);
10564
10565 auto customMapperCB =
10566 [&](unsigned int i) -> llvm::Expected<llvm::Function *> {
10567 if (!combinedInfos.Mappers[i])
10568 return nullptr;
10569 info.HasMapper = true;
10570 return getOrCreateUserDefinedMapperFunc(combinedInfos.Mappers[i], builder,
10571 moduleTranslation, targetDirective);
10572 };
10573
10574 llvm::Value *ifCond = nullptr;
10575 if (Value targetIfCond = targetOp.getIfExpr())
10576 ifCond = moduleTranslation.lookupValue(targetIfCond);
10577
10578 Value dynGroupPrivateSize = targetOp.getDynGroupprivateSize();
10579 llvm::Value *dynSizeVal = nullptr;
10580 if (dynGroupPrivateSize) {
10581 dynSizeVal = moduleTranslation.lookupValue(dynGroupPrivateSize);
10582 dynSizeVal = builder.CreateIntCast(dynSizeVal, builder.getInt32Ty(),
10583 /*isSigned=*/false);
10584 }
10585
10586 llvm::omp::OMPDynGroupprivateFallbackType fallbackType =
10587 getDynGroupprivateFallbackType(targetOp.getDynGroupprivateFallbackAttr());
10588
10589 // Pass the target region's source location to the runtime, taken from the
10590 // op's own location. Restricted to the host offload path that actually emits
10591 // the kernel launch, to avoid creating an unused identifier on the device.
10592 llvm::Value *rtLocOverride =
10593 (!isTargetDevice && isOffloadEntry)
10594 ? getSourceLocIdentFromOp(builder, *ompBuilder, targetOp)
10595 : nullptr;
10596
10597 llvm::OpenMPIRBuilder::InsertPointOrErrorTy afterIP =
10598 getOpenMPBuilder(moduleTranslation)
10599 ->createTarget(ompLoc, isOffloadEntry, allocaIP, builder.saveIP(),
10600 deallocBlocks, info, entryInfo, defaultAttrs,
10601 runtimeAttrs, ifCond, kernelInput, genMapInfoCB,
10602 bodyCB, argAccessorCB, customMapperCB, dds,
10603 targetOp.getNowait(), dynSizeVal, fallbackType,
10604 outlinedFnDbgLoc, rtLocOverride);
10605
10606 if (failed(handleError(afterIP, opInst)))
10607 return failure();
10608
10609 builder.restoreIP(*afterIP);
10610
10611 if (dds.DepArray)
10612 builder.CreateFree(dds.DepArray);
10613
10614 return success();
10615}
10616
10617static LogicalResult
10618convertDeclareTargetAttr(Operation *op, mlir::omp::DeclareTargetAttr attribute,
10619 llvm::OpenMPIRBuilder *ompBuilder,
10620 LLVM::ModuleTranslation &moduleTranslation) {
10621 // Amend omp.declare_target by deleting the IR of the outlined functions
10622 // created for target regions. They cannot be filtered out from MLIR earlier
10623 // because the omp.target operation inside must be translated to LLVM, but
10624 // the wrapper functions themselves must not remain at the end of the
10625 // process. We know that functions where omp.declare_target does not match
10626 // omp.is_target_device at this stage can only be wrapper functions because
10627 // those that aren't are removed earlier as an MLIR transformation pass.
10628 if (FunctionOpInterface funcOp = dyn_cast<FunctionOpInterface>(op)) {
10629 if (auto offloadMod = dyn_cast<omp::OffloadModuleInterface>(
10630 op->getParentOfType<ModuleOp>().getOperation())) {
10631 if (!offloadMod.getIsTargetDevice())
10632 return success();
10633
10634 omp::DeclareTargetDeviceType declareType = attribute.getDeviceType();
10635
10636 if (declareType == omp::DeclareTargetDeviceType::host) {
10637 llvm::Function *llvmFunc =
10638 moduleTranslation.lookupFunction(funcOp.getName());
10639 llvmFunc->dropAllReferences();
10640 llvmFunc->eraseFromParent();
10641
10642 // Invalidate the builder's current insertion point, as it now points to
10643 // a deleted block.
10644 ompBuilder->Builder.ClearInsertionPoint();
10645 ompBuilder->Builder.SetCurrentDebugLocation(llvm::DebugLoc());
10646 } else if (llvm::Function *llvmFunc =
10647 moduleTranslation.lookupFunction(funcOp.getName())) {
10648 // Device-side declare target functions are externally visible by
10649 // default so they can be referenced from other device translation
10650 // units. That also prevents the offload LTO from internalizing and
10651 // deleting them when they end up unused in the final device image.
10652 // Such dead functions can still reference internal LDS and trigger
10653 // spurious "local memory global used by non-kernel function" backend
10654 // warnings. Marking them hidden keeps the symbol usable within the
10655 // device image's linkage unit while letting LTO drop it when nothing
10656 // references it; symbols that must stay reachable (e.g. via an offload
10657 // entry that takes their address) are kept alive by that reference.
10658 if (!llvmFunc->isDeclaration() && llvmFunc->hasExternalLinkage() &&
10659 llvmFunc->getVisibility() == llvm::GlobalValue::DefaultVisibility)
10660 llvmFunc->setVisibility(llvm::GlobalValue::HiddenVisibility);
10661 }
10662 }
10663 return success();
10664 }
10665
10666 if (LLVM::GlobalOp gOp = dyn_cast<LLVM::GlobalOp>(op)) {
10667 llvm::Module *llvmModule = moduleTranslation.getLLVMModule();
10668 if (auto *gVal = llvmModule->getNamedValue(gOp.getSymName())) {
10669 auto *gVar = cast<llvm::GlobalVariable>(gVal);
10670 llvm::OpenMPIRBuilder *ompBuilder = getOpenMPBuilder(moduleTranslation);
10671 bool isDeclaration = gOp.isDeclaration();
10672 bool isExternallyVisible =
10673 gOp.getVisibility() != mlir::SymbolTable::Visibility::Private;
10674 auto loc = op->getLoc()->findInstanceOf<FileLineColLoc>();
10675 llvm::StringRef mangledName = gOp.getSymName();
10676 mlir::omp::DeclareTargetCaptureClause captureClause =
10677 attribute.getCaptureClause();
10678 auto captureClauseKind = convertToCaptureClauseKind(captureClause);
10679 auto deviceClause = convertToDeviceClauseKind(attribute.getDeviceType());
10680 llvm::StringRef entryMangledName = mangledName;
10681 llvm::Constant *entryAddr = llvm::cast<llvm::Constant>(gVal);
10682 std::function<llvm::GlobalValue::LinkageTypes()> variableLinkage;
10683 llvm::SmallString<128> entryNameStorage;
10684 bool requiresUSM = ompBuilder->Config.hasRequiresUnifiedSharedMemory();
10685 bool isToOrEnter =
10686 captureClause == omp::DeclareTargetCaptureClause::to ||
10687 captureClause == omp::DeclareTargetCaptureClause::enter;
10688 bool isHostOnly =
10689 attribute.getDeviceType() == omp::DeclareTargetDeviceType::host;
10690
10691 // A to/enter declare-target variable needs a device-resident,
10692 // name-resolvable copy and a host offloading entry. A local-linkage
10693 // global provides neither, so we promote it to external.
10694 if (isToOrEnter && !isHostOnly && !requiresUSM &&
10695 gVar->hasLocalLinkage()) {
10696 gVar->setLinkage(llvm::GlobalValue::ExternalLinkage);
10697 isExternallyVisible = true;
10698
10699 // Clear the stale dso_local flag so it is referenced like a
10700 // module-scope declare target global.
10701 if (ompBuilder->Config.isTargetDevice())
10702 gVar->setDSOLocal(false);
10703 }
10704
10705 if (isToOrEnter &&
10706 deviceClause ==
10707 llvm::OffloadEntriesInfoManager::OMPTargetDeviceClauseAny &&
10708 !requiresUSM && !isDeclaration &&
10709 (gVal->hasLocalLinkage() || gVal->hasHiddenVisibility())) {
10710 // Keep the original symbol as-is for target code, but create a visible
10711 // alias for the offload entry so libomptarget can associate the host
10712 // global with the actual device global.
10713 entryNameStorage = (mangledName + llvm::Twine("_decl_tgt_entry")).str();
10714 entryMangledName = entryNameStorage;
10715 if (llvm::GlobalValue *existing =
10716 llvmModule->getNamedValue(entryMangledName)) {
10717 entryAddr = llvm::cast<llvm::Constant>(existing);
10718 } else {
10719 entryAddr = llvm::GlobalAlias::create(
10720 gVal->getValueType(), gVal->getAddressSpace(),
10721 llvm::GlobalValue::WeakAnyLinkage, entryMangledName, entryAddr,
10722 llvmModule);
10723 llvm::cast<llvm::GlobalAlias>(entryAddr)->setVisibility(
10724 llvm::GlobalValue::DefaultVisibility);
10725 }
10726 variableLinkage = [] { return llvm::GlobalValue::WeakAnyLinkage; };
10727 }
10728 // unused for MLIR at the moment, required in Clang for book
10729 // keeping
10730 std::vector<llvm::GlobalVariable *> generatedRefs;
10731
10732 std::vector<llvm::Triple> targetTriple;
10733 auto targetTripleAttr = dyn_cast_or_null<mlir::StringAttr>(
10734 op->getParentOfType<mlir::ModuleOp>()->getDiscardableAttr(
10735 LLVM::LLVMDialect::getTargetTripleAttrName()));
10736 if (targetTripleAttr)
10737 targetTriple.emplace_back(targetTripleAttr.data());
10738
10739 auto fileInfoCallBack = [&loc]() {
10740 std::string filename = "";
10741 std::uint64_t lineNo = 0;
10742
10743 if (loc) {
10744 filename = loc.getFilename().str();
10745 lineNo = loc.getLine();
10746 }
10747
10748 return std::pair<std::string, std::uint64_t>(llvm::StringRef(filename),
10749 lineNo);
10750 };
10751
10752 llvm::vfs::FileSystem &vfs = moduleTranslation.getFileSystem();
10753 ompBuilder->registerTargetGlobalVariable(
10754 captureClauseKind, deviceClause, isDeclaration, isExternallyVisible,
10755 ompBuilder->getTargetEntryUniqueInfo(fileInfoCallBack, vfs),
10756 entryMangledName, generatedRefs, /*OpenMPSimd*/ false, targetTriple,
10757 /*GlobalInitializer*/ nullptr, variableLinkage, gVal->getType(),
10758 entryAddr);
10759
10760 if (ompBuilder->Config.isTargetDevice() &&
10761 (captureClause == omp::DeclareTargetCaptureClause::link ||
10762 requiresUSM)) {
10763 // For USM and link we generate a global reference pointer in the
10764 // default address space (e.g address space 0), as opposed to the
10765 // globals original type and address space.
10766 llvm::Type *ptrTy = llvm::PointerType::get(llvmModule->getContext(), 0);
10767 llvm::Constant *refPtr = ompBuilder->getAddrOfDeclareTargetVar(
10768 captureClauseKind, deviceClause, isDeclaration, isExternallyVisible,
10769 ompBuilder->getTargetEntryUniqueInfo(fileInfoCallBack, vfs),
10770 mangledName, generatedRefs, /*OpenMPSimd*/ false, targetTriple,
10771 ptrTy, /*GlobalInitializer*/ nullptr,
10772 /*VariableLinkage*/ nullptr);
10773
10774 // For indirectly-accessed global pointers, we rely on "internal"
10775 // linkage to optimize out the unneeded full-variable storage later,
10776 // since we can't prevent the LLVM dialect from generating globals
10777 // without also breaking target lowering. However, We can only do
10778 // this for definiions, as global variable declarations must have
10779 // external or weak linkage.
10780 if (refPtr) {
10781 if (!gVar->isDeclaration())
10782 gVar->setLinkage(llvm::GlobalValue::InternalLinkage);
10783
10784 // Register the (original global, reference pointer) pair so that the
10785 // OpenMPIRBuilder can rewrite uses of the original global during
10786 // finalization.
10787 if (auto *newGV =
10788 dyn_cast<llvm::GlobalValue>(refPtr->stripPointerCasts()))
10789 ompBuilder->registerDeclareTargetGlobalReplacement(gVal, newGV);
10790 }
10791 }
10792
10793 // Mark 'device_type(host) enter(...)' variables as external in the device
10794 // since they're not supposed to have their own copy. This will cause
10795 // linker errors if accesses are attempted from the target device.
10796 if (ompBuilder->Config.isTargetDevice() && isHostOnly && isToOrEnter) {
10797 gVar->setLinkage(llvm::GlobalValue::ExternalLinkage);
10798 gVar->setInitializer(nullptr);
10799 }
10800 }
10801 }
10802
10803 return success();
10804}
10805
10806namespace {
10807
10808/// Implementation of the dialect interface that converts operations belonging
10809/// to the OpenMP dialect to LLVM IR.
10810class OpenMPDialectLLVMIRTranslationInterface
10811 : public LLVMTranslationDialectInterface {
10812public:
10813 using LLVMTranslationDialectInterface::LLVMTranslationDialectInterface;
10814
10815 /// Translates the given operation to LLVM IR using the provided IR builder
10816 /// and saving the state in `moduleTranslation`.
10817 LogicalResult
10818 convertOperation(Operation *op, llvm::IRBuilderBase &builder,
10819 LLVM::ModuleTranslation &moduleTranslation) const final;
10820
10821 /// Given an OpenMP MLIR attribute, create the corresponding LLVM-IR,
10822 /// runtime calls, or operation amendments
10823 LogicalResult
10824 amendOperation(Operation *op, ArrayRef<llvm::Instruction *> instructions,
10825 NamedAttribute attribute,
10826 LLVM::ModuleTranslation &moduleTranslation) const final;
10827
10828 /// Records the LLVM alloc pointer produced for an OMP ALLOCATE variable so
10829 /// that the paired omp.allocate_free op can generate the matching
10830 /// __kmpc_free call.
10831 void registerAllocatedPtr(Value var, llvm::Value *ptr) const {
10832 ompAllocatedPtrs[var] = ptr;
10833 }
10834
10835 /// Returns the LLVM alloc pointer previously registered for var, or
10836 /// nullptr if no allocation was recorded.
10837 llvm::Value *lookupAllocatedPtr(Value var) const {
10838 auto it = ompAllocatedPtrs.find(var);
10839 return it != ompAllocatedPtrs.end() ? it->second : nullptr;
10840 }
10841
10842private:
10843 /// Maps each MLIR variable value that appeared in an omp.allocate_dir op to
10844 /// the LLVM pointer returned by the corresponding __kmpc_alloc call. The
10845 /// paired omp.allocate_free op looks up these pointers to emit __kmpc_free.
10846 mutable DenseMap<Value, llvm::Value *> ompAllocatedPtrs;
10847};
10848
10849} // namespace
10850
10851LogicalResult OpenMPDialectLLVMIRTranslationInterface::amendOperation(
10852 Operation *op, ArrayRef<llvm::Instruction *> instructions,
10853 NamedAttribute attribute,
10854 LLVM::ModuleTranslation &moduleTranslation) const {
10855 return llvm::StringSwitch<llvm::function_ref<LogicalResult(Attribute)>>(
10856 attribute.getName())
10857 .Case("omp.is_target_device",
10858 [&](Attribute attr) {
10859 if (auto deviceAttr = dyn_cast<BoolAttr>(attr)) {
10860 llvm::OpenMPIRBuilderConfig &config =
10861 getOpenMPBuilder(moduleTranslation)->Config;
10862 config.setIsTargetDevice(deviceAttr.getValue());
10863 return success();
10864 }
10865 return failure();
10866 })
10867 .Case("omp.is_gpu",
10868 [&](Attribute attr) {
10869 if (auto gpuAttr = dyn_cast<BoolAttr>(attr)) {
10870 llvm::OpenMPIRBuilderConfig &config =
10871 getOpenMPBuilder(moduleTranslation)->Config;
10872 config.setIsGPU(gpuAttr.getValue());
10873 return success();
10874 }
10875 return failure();
10876 })
10877 .Case("omp.host_ir_filepath",
10878 [&](Attribute attr) {
10879 if (auto filepathAttr = dyn_cast<StringAttr>(attr)) {
10880 llvm::OpenMPIRBuilder *ompBuilder =
10881 getOpenMPBuilder(moduleTranslation);
10882 ompBuilder->loadOffloadInfoMetadata(
10883 moduleTranslation.getFileSystem(), filepathAttr.getValue());
10884 return success();
10885 }
10886 return failure();
10887 })
10888 .Case("omp.flags",
10889 [&](Attribute attr) {
10890 if (auto rtlAttr = dyn_cast<omp::FlagsAttr>(attr))
10891 return convertFlagsAttr(op, rtlAttr, moduleTranslation);
10892 return failure();
10893 })
10894 .Case("omp.version",
10895 [&](Attribute attr) {
10896 if (auto versionAttr = dyn_cast<omp::VersionAttr>(attr)) {
10897 llvm::OpenMPIRBuilder *ompBuilder =
10898 getOpenMPBuilder(moduleTranslation);
10899 ompBuilder->M.addModuleFlag(llvm::Module::Max, "openmp",
10900 versionAttr.getVersion());
10901 return success();
10902 }
10903 return failure();
10904 })
10905 .Case("omp.declare_target",
10906 [&](Attribute attr) {
10907 if (auto declareTargetAttr =
10908 dyn_cast<omp::DeclareTargetAttr>(attr)) {
10909 llvm::OpenMPIRBuilder *ompBuilder =
10910 getOpenMPBuilder(moduleTranslation);
10911 return convertDeclareTargetAttr(op, declareTargetAttr,
10912 ompBuilder, moduleTranslation);
10913 }
10914 return failure();
10915 })
10916 .Case("omp.requires",
10917 [&](Attribute attr) {
10918 if (auto requiresAttr = dyn_cast<omp::ClauseRequiresAttr>(attr)) {
10919 using Requires = omp::ClauseRequires;
10920 Requires flags = requiresAttr.getValue();
10921 llvm::OpenMPIRBuilderConfig &config =
10922 getOpenMPBuilder(moduleTranslation)->Config;
10923 config.setHasRequiresReverseOffload(
10924 bitEnumContainsAll(flags, Requires::reverse_offload));
10925 config.setHasRequiresUnifiedAddress(
10926 bitEnumContainsAll(flags, Requires::unified_address));
10927 config.setHasRequiresUnifiedSharedMemory(
10928 bitEnumContainsAll(flags, Requires::unified_shared_memory));
10929 config.setHasRequiresDynamicAllocators(
10930 bitEnumContainsAll(flags, Requires::dynamic_allocators));
10931 return success();
10932 }
10933 return failure();
10934 })
10935 .Case("omp.target_triples",
10936 [&](Attribute attr) {
10937 if (auto triplesAttr = dyn_cast<ArrayAttr>(attr)) {
10938 llvm::OpenMPIRBuilderConfig &config =
10939 getOpenMPBuilder(moduleTranslation)->Config;
10940 config.TargetTriples.clear();
10941 config.TargetTriples.reserve(triplesAttr.size());
10942 for (Attribute tripleAttr : triplesAttr) {
10943 if (auto tripleStrAttr = dyn_cast<StringAttr>(tripleAttr))
10944 config.TargetTriples.emplace_back(tripleStrAttr.getValue());
10945 else
10946 return failure();
10947 }
10948 return success();
10949 }
10950 return failure();
10951 })
10952 .Case("omp.integer_wrap_around",
10953 [&](Attribute attr) {
10954 if (auto wrapAttr = dyn_cast<omp::IntegerWrapAroundAttr>(attr)) {
10955 llvm::OpenMPIRBuilderConfig &config =
10956 getOpenMPBuilder(moduleTranslation)->Config;
10957 config.setNoSignedWrap(!wrapAttr.getIntegerWrapAround());
10958 return success();
10959 }
10960 return failure();
10961 })
10962 .Default([](Attribute) {
10963 // Fall through for omp attributes that do not require lowering.
10964 return success();
10965 })(attribute.getValue());
10966
10967 return failure();
10968}
10969
10970// Returns true if the operation is not inside a TargetOp, it is part of a
10971// function and that function is not declare target.
10972static bool isHostDeviceOp(Operation *op) {
10973 // Assumes no reverse offloading
10974 if (op->getParentOfType<omp::TargetOp>())
10975 return false;
10976
10977 if (auto parentFn = op->getParentOfType<LLVM::LLVMFuncOp>()) {
10978 if (auto declareTargetIface =
10979 llvm::dyn_cast<mlir::omp::DeclareTargetInterface>(
10980 parentFn.getOperation())) {
10981 omp::DeclareTargetAttr declareTargetAttr =
10982 declareTargetIface.getDeclareTarget();
10983 if (declareTargetAttr && declareTargetAttr.getDeviceType() !=
10984 mlir::omp::DeclareTargetDeviceType::host)
10985 return false;
10986 }
10987
10988 return true;
10989 }
10990
10991 return false;
10992}
10993
10994static llvm::Function *getOmpTargetAlloc(llvm::IRBuilderBase &builder,
10995 llvm::Module *llvmModule) {
10996 llvm::Type *i64Ty = builder.getInt64Ty();
10997 llvm::Type *i32Ty = builder.getInt32Ty();
10998 llvm::Type *returnType = builder.getPtrTy(0);
10999 llvm::FunctionType *fnType =
11000 llvm::FunctionType::get(returnType, {i64Ty, i32Ty}, false);
11001 llvm::Function *func = cast<llvm::Function>(
11002 llvmModule->getOrInsertFunction("omp_target_alloc", fnType).getCallee());
11003 return func;
11004}
11005
11006template <typename T>
11007static llvm::Value *
11008getAllocationSize(llvm::IRBuilderBase &builder,
11009 LLVM::ModuleTranslation &moduleTranslation, T op) {
11010 llvm::DataLayout dataLayout =
11011 moduleTranslation.getLLVMModule()->getDataLayout();
11012 llvm::Type *llvmHeapTy =
11013 moduleTranslation.convertType(op.getMemElemTypeAttr().getValue());
11014
11015 auto alignment = op.getMemAlignment();
11016 llvm::TypeSize typeSize = llvm::alignTo(
11017 dataLayout.getTypeStoreSize(llvmHeapTy),
11018 alignment ? *alignment : dataLayout.getABITypeAlign(llvmHeapTy).value());
11019
11020 llvm::Value *allocSize = builder.getInt64(typeSize.getFixedValue());
11021 return builder.CreateMul(
11022 allocSize,
11023 builder.CreateIntCast(moduleTranslation.lookupValue(op.getMemArraySize()),
11024 builder.getInt64Ty(),
11025 /*isSigned=*/false));
11026}
11027
11028template <>
11029llvm::Value *getAllocationSize(llvm::IRBuilderBase &builder,
11030 LLVM::ModuleTranslation &moduleTranslation,
11031 omp::TargetAllocMemOp op) {
11032 llvm::DataLayout dataLayout =
11033 moduleTranslation.getLLVMModule()->getDataLayout();
11034 llvm::Type *llvmHeapTy = moduleTranslation.convertType(op.getAllocatedType());
11035 llvm::TypeSize typeSize = dataLayout.getTypeAllocSize(llvmHeapTy);
11036 llvm::Value *allocSize = builder.getInt64(typeSize.getFixedValue());
11037 for (auto typeParam : op.getTypeparams()) {
11038 allocSize = builder.CreateMul(
11039 allocSize,
11040 builder.CreateIntCast(moduleTranslation.lookupValue(typeParam),
11041 builder.getInt64Ty(),
11042 /*isSigned=*/false));
11043 }
11044 return allocSize;
11045}
11046
11047static LogicalResult
11048convertTargetAllocMemOp(Operation &opInst, llvm::IRBuilderBase &builder,
11049 LLVM::ModuleTranslation &moduleTranslation) {
11050 auto allocMemOp = cast<omp::TargetAllocMemOp>(opInst);
11051 if (!allocMemOp)
11052 return failure();
11053
11054 // Get "omp_target_alloc" function
11055 llvm::Module *llvmModule = moduleTranslation.getLLVMModule();
11056 llvm::Function *ompTargetAllocFunc = getOmpTargetAlloc(builder, llvmModule);
11057 // Get the corresponding device value in llvm
11058 mlir::Value deviceNum = allocMemOp.getDevice();
11059 llvm::Value *llvmDeviceNum = moduleTranslation.lookupValue(deviceNum);
11060 // Get the allocation size.
11061 llvm::Value *allocSize =
11062 getAllocationSize(builder, moduleTranslation, allocMemOp);
11063 // Create call to "omp_target_alloc" with the args as translated llvm values.
11064 llvm::CallInst *call =
11065 builder.CreateCall(ompTargetAllocFunc, {allocSize, llvmDeviceNum});
11066 llvm::Value *resultI64 = builder.CreatePtrToInt(call, builder.getInt64Ty());
11067
11068 // Map the result
11069 moduleTranslation.mapValue(allocMemOp.getResult(), resultI64);
11070 return success();
11071}
11072
11073static LogicalResult
11074convertAllocSharedMemOp(omp::AllocSharedMemOp allocMemOp,
11075 llvm::IRBuilderBase &builder,
11076 LLVM::ModuleTranslation &moduleTranslation) {
11077 llvm::OpenMPIRBuilder *ompBuilder = getOpenMPBuilder(moduleTranslation);
11078 llvm::Value *size = getAllocationSize(builder, moduleTranslation, allocMemOp);
11079 moduleTranslation.mapValue(allocMemOp.getResult(),
11080 ompBuilder->createOMPAllocShared(builder, size));
11081 return success();
11082}
11083
11084static LogicalResult
11085convertAllocateDirOp(Operation &opInst, llvm::IRBuilderBase &builder,
11086 LLVM::ModuleTranslation &moduleTranslation,
11087 const OpenMPDialectLLVMIRTranslationInterface &ompIface) {
11088 auto allocateDirOp = cast<omp::AllocateDirOp>(opInst);
11089 llvm::OpenMPIRBuilder *ompBuilder = getOpenMPBuilder(moduleTranslation);
11090
11091 llvm::OpenMPIRBuilder::LocationDescription ompLoc(builder);
11092 llvm::Module *llvmModule = moduleTranslation.getLLVMModule();
11093 llvm::DataLayout dataLayout = llvmModule->getDataLayout();
11094 SmallVector<Value> vars = allocateDirOp.getVarList();
11095 std::optional<int64_t> alignAttr = allocateDirOp.getAlign();
11096
11097 llvm::Value *allocator;
11098 if (auto allocatorVar = allocateDirOp.getAllocator()) {
11099 allocator = moduleTranslation.lookupValue(allocatorVar);
11100 if (allocator->getType()->isIntegerTy())
11101 allocator = builder.CreateIntToPtr(allocator, builder.getPtrTy());
11102 else if (allocator->getType()->isPointerTy())
11103 allocator = builder.CreatePointerBitCastOrAddrSpaceCast(
11104 allocator, builder.getPtrTy());
11105 } else {
11106 allocator = llvm::ConstantPointerNull::get(builder.getPtrTy());
11107 }
11108
11109 for (Value var : vars) {
11110 Value baseVar = getBaseValueForTypeLookup(var);
11111 llvm::Type *typeToInspect =
11112 getAllocatedLlvmTypeForVariable(var, baseVar, moduleTranslation);
11113
11114 llvm::Value *size;
11115 if (std::optional<llvm::Value *> dynamicSize = getDynamicAllocatedSize(
11116 var, baseVar, moduleTranslation, builder, dataLayout)) {
11117 size = *dynamicSize;
11118 } else if (typeToInspect->isArrayTy()) {
11119 size = builder.getInt64(
11120 dataLayout.getTypeAllocSize(typeToInspect).getFixedValue());
11121 } else {
11122 size = builder.getInt64(
11123 dataLayout.getTypeAllocSize(typeToInspect).getFixedValue());
11124 }
11125
11126 uint64_t alignValue =
11127 alignAttr ? alignAttr.value()
11128 : dataLayout.getABITypeAlign(typeToInspect).value();
11129 llvm::Value *alignConst = builder.getInt64(alignValue);
11130 // Align the size: ((size + align - 1) / align) * align
11131 size = builder.CreateAdd(size, builder.getInt64(alignValue - 1), "", true);
11132 size = builder.CreateUDiv(size, alignConst);
11133 size = builder.CreateMul(size, alignConst, "", true);
11134
11135 std::string allocName =
11136 ompBuilder->createPlatformSpecificName({".void.addr"});
11137 llvm::CallInst *allocCall;
11138 if (alignAttr.has_value()) {
11139 allocCall = ompBuilder->createOMPAlignedAlloc(
11140 ompLoc, builder.getInt64(alignAttr.value()), size, allocator,
11141 allocName);
11142 } else {
11143 allocCall =
11144 ompBuilder->createOMPAlloc(ompLoc, size, allocator, allocName);
11145 }
11146 // Record the alloc pointer keyed by the MLIR variable value.
11147 ompIface.registerAllocatedPtr(var, allocCall);
11148
11149 if (llvm::Value *baseLlvm = moduleTranslation.lookupValue(baseVar)) {
11150 llvm::Value *boundPtr = builder.CreatePointerBitCastOrAddrSpaceCast(
11151 allocCall, baseLlvm->getType());
11152 moduleTranslation.remapAllValuesWith(baseLlvm, boundPtr);
11153 } else if (llvm::Value *varLlvm = moduleTranslation.lookupValue(var)) {
11154 llvm::Value *boundPtr = builder.CreatePointerBitCastOrAddrSpaceCast(
11155 allocCall, varLlvm->getType());
11156 moduleTranslation.remapAllValuesWith(varLlvm, boundPtr);
11157 }
11158 }
11159
11160 return success();
11161}
11162
11163static LogicalResult
11164convertAllocateFreeOp(Operation &opInst, llvm::IRBuilderBase &builder,
11165 LLVM::ModuleTranslation &moduleTranslation,
11166 const OpenMPDialectLLVMIRTranslationInterface &ompIface) {
11167 auto freeOp = cast<omp::AllocateFreeOp>(opInst);
11168 llvm::OpenMPIRBuilder *ompBuilder = getOpenMPBuilder(moduleTranslation);
11169 llvm::OpenMPIRBuilder::LocationDescription ompLoc(builder);
11170
11171 llvm::Value *allocator;
11172 if (auto allocatorVar = freeOp.getAllocator()) {
11173 allocator = moduleTranslation.lookupValue(allocatorVar);
11174 if (allocator->getType()->isIntegerTy())
11175 allocator = builder.CreateIntToPtr(allocator, builder.getPtrTy());
11176 else if (allocator->getType()->isPointerTy())
11177 allocator = builder.CreatePointerBitCastOrAddrSpaceCast(
11178 allocator, builder.getPtrTy());
11179 } else {
11180 allocator = llvm::ConstantPointerNull::get(builder.getPtrTy());
11181 }
11182
11183 // Emit __kmpc_free for each variable in reverse allocation order.
11184 SmallVector<Value> vars = freeOp.getVarList();
11185 for (Value var : llvm::reverse(vars)) {
11186 llvm::Value *allocPtr = ompIface.lookupAllocatedPtr(var);
11187 if (!allocPtr)
11188 return opInst.emitError("omp.allocate_free: no allocation recorded");
11189 ompBuilder->createOMPFree(ompLoc, allocPtr, allocator, "");
11190 }
11191
11192 return success();
11193}
11194
11195static llvm::Function *getOmpTargetFree(llvm::IRBuilderBase &builder,
11196 llvm::Module *llvmModule) {
11197 llvm::Type *ptrTy = builder.getPtrTy(0);
11198 llvm::Type *i32Ty = builder.getInt32Ty();
11199 llvm::Type *voidTy = builder.getVoidTy();
11200 llvm::FunctionType *fnType =
11201 llvm::FunctionType::get(voidTy, {ptrTy, i32Ty}, false);
11202 llvm::Function *func = dyn_cast<llvm::Function>(
11203 llvmModule->getOrInsertFunction("omp_target_free", fnType).getCallee());
11204 return func;
11205}
11206
11207static LogicalResult
11208convertTargetFreeMemOp(Operation &opInst, llvm::IRBuilderBase &builder,
11209 LLVM::ModuleTranslation &moduleTranslation) {
11210 auto freeMemOp = cast<omp::TargetFreeMemOp>(opInst);
11211 if (!freeMemOp)
11212 return failure();
11213
11214 // Get "omp_target_free" function
11215 llvm::Module *llvmModule = moduleTranslation.getLLVMModule();
11216 llvm::Function *ompTragetFreeFunc = getOmpTargetFree(builder, llvmModule);
11217 // Get the corresponding device value in llvm
11218 mlir::Value deviceNum = freeMemOp.getDevice();
11219 llvm::Value *llvmDeviceNum = moduleTranslation.lookupValue(deviceNum);
11220 // Get the corresponding heapref value in llvm
11221 mlir::Value heapref = freeMemOp.getHeapref();
11222 llvm::Value *llvmHeapref = moduleTranslation.lookupValue(heapref);
11223 // Convert heapref int to ptr and call "omp_target_free"
11224 llvm::Value *intToPtr =
11225 builder.CreateIntToPtr(llvmHeapref, builder.getPtrTy(0));
11226 builder.CreateCall(ompTragetFreeFunc, {intToPtr, llvmDeviceNum});
11227 return success();
11228}
11229
11230static LogicalResult
11231convertFreeSharedMemOp(omp::FreeSharedMemOp freeMemOp,
11232 llvm::IRBuilderBase &builder,
11233 LLVM::ModuleTranslation &moduleTranslation) {
11234 llvm::OpenMPIRBuilder *ompBuilder = getOpenMPBuilder(moduleTranslation);
11235 llvm::Value *size = getAllocationSize(builder, moduleTranslation, freeMemOp);
11236 ompBuilder->createOMPFreeShared(
11237 builder, moduleTranslation.lookupValue(freeMemOp.getHeapref()), size);
11238 return success();
11239}
11240
11241/// Converts an OpenMP groupprivate operation into LLVM IR.
11242static LogicalResult
11243convertOmpGroupprivate(Operation &opInst, llvm::IRBuilderBase &builder,
11244 LLVM::ModuleTranslation &moduleTranslation) {
11245 llvm::OpenMPIRBuilder *ompBuilder = getOpenMPBuilder(moduleTranslation);
11246 auto groupprivateOp = cast<omp::GroupprivateOp>(opInst);
11247
11248 if (failed(checkImplementationStatus(opInst)))
11249 return failure();
11250
11251 bool isTargetDevice = ompBuilder->Config.isTargetDevice();
11252
11253 // Determine whether group-private storage should be allocated based on
11254 // device_type. When not specified, default to 'any' (allocate on both).
11255 bool shouldAllocate = true;
11256 switch (groupprivateOp.getDeviceType().value_or(
11257 mlir::omp::DeclareTargetDeviceType::any)) {
11258 case mlir::omp::DeclareTargetDeviceType::host:
11259 shouldAllocate = !isTargetDevice;
11260 break;
11261 case mlir::omp::DeclareTargetDeviceType::nohost:
11262 shouldAllocate = isTargetDevice;
11263 break;
11264 case mlir::omp::DeclareTargetDeviceType::any:
11265 shouldAllocate = true;
11266 break;
11267 }
11268
11269 // Look up the global variable directly by symbol name.
11271 &opInst, groupprivateOp.getSymNameAttr());
11272 if (!global)
11273 return opInst.emitError()
11274 << "expected symbol '" << groupprivateOp.getSymName()
11275 << "' to reference an LLVM global variable";
11276
11277 llvm::GlobalValue *globalValue = moduleTranslation.lookupGlobal(global);
11278 llvm::Type *varType = moduleTranslation.convertType(global.getType());
11279 std::string varName = globalValue->getName().str();
11280
11281 llvm::Value *resultPtr;
11282 if (shouldAllocate && isTargetDevice) {
11283 llvm::Module *llvmModule = moduleTranslation.getLLVMModule();
11284 llvm::Triple targetTriple(llvmModule->getTargetTriple());
11285 unsigned sharedAddressSpace;
11286 if (targetTriple.isAMDGCN())
11287 sharedAddressSpace = llvm::AMDGPUAS::LOCAL_ADDRESS;
11288 else if (targetTriple.isNVPTX())
11289 sharedAddressSpace = llvm::NVPTXAS::ADDRESS_SPACE_SHARED;
11290 else
11291 return opInst.emitError() << "groupprivate is not supported for target: "
11292 << targetTriple.str();
11293 llvm::GlobalVariable *sharedVar = new llvm::GlobalVariable(
11294 *llvmModule, varType, /*isConstant=*/false,
11295 llvm::GlobalValue::InternalLinkage, llvm::PoisonValue::get(varType),
11296 varName, /*InsertBefore=*/nullptr, llvm::GlobalValue::NotThreadLocal,
11297 sharedAddressSpace,
11298 /*isExternallyInitialized=*/false);
11299 resultPtr = sharedVar;
11300 } else {
11301 if (shouldAllocate && !isTargetDevice)
11302 opInst.emitWarning("groupprivate directive is currently ignored on the "
11303 "host, using original global");
11304 resultPtr = globalValue;
11305 }
11306
11307 moduleTranslation.mapValue(opInst.getResult(0), resultPtr);
11308 return success();
11309}
11310
11311/// Given an OpenMP MLIR operation, create the corresponding LLVM IR (including
11312/// OpenMP runtime calls).
11313LogicalResult OpenMPDialectLLVMIRTranslationInterface::convertOperation(
11314 Operation *op, llvm::IRBuilderBase &builder,
11315 LLVM::ModuleTranslation &moduleTranslation) const {
11316 llvm::OpenMPIRBuilder *ompBuilder = getOpenMPBuilder(moduleTranslation);
11317
11318 if (ompBuilder->Config.isTargetDevice() &&
11319 !isa<omp::TargetOp, omp::MapInfoOp, omp::TerminatorOp, omp::YieldOp>(
11320 op) &&
11321 isHostDeviceOp(op))
11322 return op->emitOpError() << "unsupported host op found in device";
11323
11324 // For each loop, introduce one stack frame to hold loop information. Ensure
11325 // this is only done for the outermost loop wrapper to prevent introducing
11326 // multiple stack frames for a single loop. Initially set to null, the loop
11327 // information structure is initialized during translation of the nested
11328 // omp.loop_nest operation, making it available to translation of all loop
11329 // wrappers after their body has been successfully translated.
11330 bool isOutermostLoopWrapper =
11331 isa_and_present<omp::LoopWrapperInterface>(op) &&
11332 !dyn_cast_if_present<omp::LoopWrapperInterface>(op->getParentOp());
11333
11334 // The TASKLOOP construct is implemented with an outer taskloop.context
11335 // operation which is not a loop wrapper, containing an inner taskloop
11336 // operation which is a loop wrapper. The stack frame should be pushed when
11337 // translating the outer taskloop.context and popped when translating the
11338 // inner taskloop which is a loop wrapper. We need access to the loop
11339 // information in the outer taskloop context so we need to create it and pop
11340 // it around the taskloop context not the inner loop wrapper.
11341 if (isa<omp::TaskloopContextOp>(op))
11342 isOutermostLoopWrapper = true;
11343 else if (isa<omp::TaskloopWrapperOp>(op))
11344 isOutermostLoopWrapper = false;
11345
11346 if (isOutermostLoopWrapper)
11347 moduleTranslation.stackPush<OpenMPLoopInfoStackFrame>();
11348
11349 auto result =
11350 llvm::TypeSwitch<Operation *, LogicalResult>(op)
11351 .Case([&](omp::BarrierOp op) -> LogicalResult {
11353 return failure();
11354
11355 llvm::OpenMPIRBuilder::InsertPointOrErrorTy afterIP =
11356 ompBuilder->createBarrier(builder, llvm::omp::OMPD_barrier);
11357 LogicalResult res = handleError(afterIP, *op);
11358 if (res.succeeded()) {
11359 // If the barrier generated a cancellation check, the insertion
11360 // point might now need to be changed to a new continuation block
11361 builder.restoreIP(*afterIP);
11362 }
11363 return res;
11364 })
11365 .Case([&](omp::TaskyieldOp op) {
11367 return failure();
11368
11369 ompBuilder->createTaskyield(builder);
11370 return success();
11371 })
11372 .Case([&](omp::FlushOp op) {
11374 return failure();
11375
11376 // No support in Openmp runtime function (__kmpc_flush) to accept
11377 // the argument list.
11378 // OpenMP standard states the following:
11379 // "An implementation may implement a flush with a list by ignoring
11380 // the list, and treating it the same as a flush without a list."
11381 //
11382 // The argument list is discarded so that, flush with a list is
11383 // treated same as a flush without a list.
11384 ompBuilder->createFlush(builder);
11385 return success();
11386 })
11387 .Case([&](omp::ErrorOp op) {
11389 return failure();
11390
11391 llvm::Value *message = nullptr;
11392 if (mlir::Value messageExpr = op.getMessageExpr())
11393 message = moduleTranslation.lookupValue(messageExpr);
11394 else if (std::optional<StringRef> msg = op.getMessage();
11395 msg && !msg->empty())
11396 message = builder.CreateGlobalString(*msg);
11397 ompBuilder->createError(
11398 llvm::OpenMPIRBuilder::LocationDescription(builder),
11399 op.getSeverity() == omp::ClauseSeverity::fatal, message);
11400 return success();
11401 })
11402 .Case([&](omp::ParallelOp op) {
11403 return convertOmpParallel(op, builder, moduleTranslation);
11404 })
11405 .Case([&](omp::DispatchOp) {
11406 return convertOmpDispatch(*op, builder, moduleTranslation);
11407 })
11408 .Case([&](omp::MaskedOp) {
11409 return convertOmpMasked(*op, builder, moduleTranslation);
11410 })
11411 .Case([&](omp::MasterOp) {
11412 return convertOmpMaster(*op, builder, moduleTranslation);
11413 })
11414 .Case([&](omp::CriticalOp) {
11415 return convertOmpCritical(*op, builder, moduleTranslation);
11416 })
11417 .Case([&](omp::OrderedRegionOp) {
11418 return convertOmpOrderedRegion(*op, builder, moduleTranslation);
11419 })
11420 .Case([&](omp::OrderedOp) {
11421 return convertOmpOrdered(*op, builder, moduleTranslation);
11422 })
11423 .Case([&](omp::WsloopOp) {
11424 return convertOmpWsloop(*op, builder, moduleTranslation);
11425 })
11426 .Case([&](omp::SimdOp) {
11427 return convertOmpSimd(*op, builder, moduleTranslation);
11428 })
11429 .Case([&](omp::AtomicReadOp) {
11430 return convertOmpAtomicRead(*op, builder, moduleTranslation);
11431 })
11432 .Case([&](omp::AtomicWriteOp) {
11433 return convertOmpAtomicWrite(*op, builder, moduleTranslation);
11434 })
11435 .Case([&](omp::AtomicUpdateOp op) {
11436 return convertOmpAtomicUpdate(op, builder, moduleTranslation);
11437 })
11438 .Case([&](omp::AtomicCaptureOp op) {
11439 return convertOmpAtomicCapture(op, builder, moduleTranslation);
11440 })
11441 .Case([&](omp::AtomicCompareOp op) {
11442 return convertOmpAtomicCompare(op, builder, moduleTranslation);
11443 })
11444 .Case([&](omp::CancelOp op) {
11445 return convertOmpCancel(op, builder, moduleTranslation);
11446 })
11447 .Case([&](omp::CancellationPointOp op) {
11448 return convertOmpCancellationPoint(op, builder, moduleTranslation);
11449 })
11450 .Case([&](omp::SectionsOp) {
11451 return convertOmpSections(*op, builder, moduleTranslation);
11452 })
11453 .Case([&](omp::ScopeOp op) {
11454 return convertOmpScope(op, builder, moduleTranslation);
11455 })
11456 .Case([&](omp::SingleOp op) {
11457 return convertOmpSingle(op, builder, moduleTranslation);
11458 })
11459 .Case([&](omp::TeamsOp op) {
11460 return convertOmpTeams(op, builder, moduleTranslation);
11461 })
11462 .Case([&](omp::TaskOp op) {
11463 return convertOmpTaskOp(op, builder, moduleTranslation);
11464 })
11465 .Case([&](omp::TaskloopWrapperOp op) {
11466 return convertOmpTaskloopWrapperOp(op, builder, moduleTranslation);
11467 })
11468 .Case([&](omp::TaskloopContextOp op) {
11469 return convertOmpTaskloopContextOp(op, builder, moduleTranslation);
11470 })
11471 .Case([&](omp::TaskgroupOp op) {
11472 return convertOmpTaskgroupOp(op, builder, moduleTranslation);
11473 })
11474 .Case([&](omp::TaskwaitOp op) {
11475 return convertOmpTaskwaitOp(op, builder, moduleTranslation);
11476 })
11477 .Case([&](omp::InteropInitOp op) {
11478 return convertOmpInteropInitOp(op, builder, moduleTranslation);
11479 })
11480 .Case([&](omp::InteropDestroyOp op) {
11481 return convertOmpInteropDestroyOp(op, builder, moduleTranslation);
11482 })
11483 .Case([&](omp::InteropUseOp op) {
11484 return convertOmpInteropUseOp(op, builder, moduleTranslation);
11485 })
11486 .Case<omp::YieldOp, omp::TerminatorOp, omp::DeclareMapperOp,
11487 omp::DeclareMapperInfoOp, omp::DeclareReductionOp,
11488 omp::CriticalDeclareOp>([](auto op) {
11489 // `yield` and `terminator` can be just omitted. The block structure
11490 // was created in the region that handles their parent operation.
11491 // `declare_reduction` will be used by reductions and is not
11492 // converted directly, skip it.
11493 // `declare_mapper` and `declare_mapper.info` are handled whenever
11494 // they are referred to through a `map` clause.
11495 // `critical.declare` is only used to declare names of critical
11496 // sections which will be used by `critical` ops and hence can be
11497 // ignored for lowering. The OpenMP IRBuilder will create unique
11498 // name for critical section names.
11499 return success();
11500 })
11501 .Case([&](omp::ThreadprivateOp) {
11502 return convertOmpThreadprivate(*op, builder, moduleTranslation);
11503 })
11504 .Case<omp::TargetDataOp, omp::TargetEnterDataOp,
11505 omp::TargetExitDataOp, omp::TargetUpdateOp>([&](auto op) {
11506 return convertOmpTargetData(op, builder, moduleTranslation);
11507 })
11508 .Case([&](omp::TargetOp) {
11509 return convertOmpTarget(*op, builder, moduleTranslation);
11510 })
11511 .Case([&](omp::DistributeOp) {
11512 return convertOmpDistribute(*op, builder, moduleTranslation);
11513 })
11514 .Case([&](omp::LoopNestOp) {
11515 return convertOmpLoopNest(*op, builder, moduleTranslation);
11516 })
11517 .Case<omp::MapInfoOp, omp::MapBoundsOp, omp::PrivateClauseOp,
11518 omp::AffinityEntryOp, omp::IteratorOp>([&](auto op) {
11519 // No-op, should be handled by relevant owning operations e.g.
11520 // TargetOp, TargetEnterDataOp, TargetExitDataOp, TargetDataOp
11521 // etc. and then discarded
11522 return success();
11523 })
11524 .Case([&](omp::NewCliOp op) {
11525 // Meta-operation: Doesn't do anything by itself, but used to
11526 // identify a loop.
11527 return success();
11528 })
11529 .Case([&](omp::CanonicalLoopOp op) {
11530 return convertOmpCanonicalLoopOp(op, builder, moduleTranslation);
11531 })
11532 .Case([&](omp::UnrollHeuristicOp op) {
11533 // FIXME: Handling omp.unroll_heuristic as an executable requires
11534 // that the generator (e.g. omp.canonical_loop) has been seen first.
11535 // For construct that require all codegen to occur inside a callback
11536 // (e.g. OpenMPIRBilder::createParallel), all codegen of that
11537 // contained region including their transformations must occur at
11538 // the omp.canonical_loop.
11539 return applyUnrollHeuristic(op, builder, moduleTranslation);
11540 })
11541 .Case([&](omp::UnrollFullOp op) {
11542 return applyUnrollFull(op, builder, moduleTranslation);
11543 })
11544 .Case([&](omp::UnrollPartialOp op) {
11545 return applyUnrollPartial(op, builder, moduleTranslation);
11546 })
11547 .Case([&](omp::TileOp op) {
11548 return applyTile(op, builder, moduleTranslation);
11549 })
11550 .Case([&](omp::FuseOp op) {
11551 return applyFuse(op, builder, moduleTranslation);
11552 })
11553 .Case([&](omp::TargetAllocMemOp) {
11554 return convertTargetAllocMemOp(*op, builder, moduleTranslation);
11555 })
11556 .Case([&](omp::TargetFreeMemOp) {
11557 return convertTargetFreeMemOp(*op, builder, moduleTranslation);
11558 })
11559 .Case([&](omp::AllocateDirOp) {
11560 return convertAllocateDirOp(*op, builder, moduleTranslation, *this);
11561 })
11562 .Case([&](omp::AllocateFreeOp) {
11563 return convertAllocateFreeOp(*op, builder, moduleTranslation,
11564 *this);
11565 })
11566 .Case([&](omp::AllocSharedMemOp op) {
11567 return convertAllocSharedMemOp(op, builder, moduleTranslation);
11568 })
11569 .Case([&](omp::FreeSharedMemOp op) {
11570 return convertFreeSharedMemOp(op, builder, moduleTranslation);
11571 })
11572 .Case([&](omp::GroupprivateOp) {
11573 return convertOmpGroupprivate(*op, builder, moduleTranslation);
11574 })
11575 .Case([&](omp::DeclareSimdOp) {
11576 // TODO: Implement.
11577 // DECLARE_SIMD can be ignored. There is warning emitted in
11578 // semantic checks about the current situation, but not having an
11579 // implementation should not prevent compilation.
11580 return success();
11581 })
11582 .Default([&](Operation *inst) {
11583 return inst->emitError()
11584 << "not yet implemented: " << inst->getName();
11585 });
11586
11587 if (isOutermostLoopWrapper)
11588 moduleTranslation.stackPop();
11589
11590 return result;
11591}
11592
11594 static llvm::cl::opt<bool, /*ExternalStorage=*/true> option(
11595 "openmp-disable-virtual-collapse", llvm::cl::Hidden,
11596 llvm::cl::desc("Disable virtual collapse of eligible host loops"),
11597 llvm::cl::location(disableVirtualCollapse));
11598}
11599
11601 registry.insert<omp::OpenMPDialect>();
11602 registry.addExtension(+[](MLIRContext *ctx, omp::OpenMPDialect *dialect) {
11603 dialect->addInterfaces<OpenMPDialectLLVMIRTranslationInterface>();
11604 });
11605}
11606
11608 DialectRegistry registry;
11610 context.appendDialectRegistry(registry);
11611}
return success()
static void copy(Location loc, Value dst, Value src, Value size, OpBuilder &builder)
Copies the given number of bytes from src to dst pointers.
b
Return true if permutation is a valid permutation of the outer_dims_perm (case OuterOrInnerPerm::Oute...
ArrayAttr()
if(!isCopyOut)
auto load
static mlir::LogicalResult buildDependData(OperandRange dependVars, std::optional< ArrayAttr > dependKinds, OperandRange dependIterated, std::optional< ArrayAttr > dependIteratedKinds, llvm::IRBuilderBase &builder, mlir::LLVM::ModuleTranslation &moduleTranslation, llvm::OpenMPIRBuilder::DependenciesInfo &taskDeps)
static LogicalResult convertOmpAtomicUpdate(omp::AtomicUpdateOp &opInst, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation)
Converts an OpenMP atomic update operation using OpenMPIRBuilder.
static llvm::omp::OrderKind convertOrderKind(std::optional< omp::ClauseOrderKind > o)
Convert Order attribute to llvm::omp::OrderKind.
static void mapParentWithMembers(LLVM::ModuleTranslation &moduleTranslation, llvm::IRBuilderBase &builder, llvm::OpenMPIRBuilder &ompBuilder, DataLayout &dl, MapInfosTy &combinedInfo, MapInfoData &mapData, uint64_t mapDataIndex, llvm::omp::OpenMPOffloadMappingFlags memberOfFlag, TargetDirectiveEnumTy targetDirective)
static llvm::OpenMPIRBuilder::CollapseIVMapping selectCollapseIVMapping(omp::LoopNestOp loopOp, bool isTargetDevice)
Select Virtual only for two host worksharing loops.
static llvm::OpenMPIRBuilder::InsertPointTy findAllocInsertPoints(llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation, llvm::SmallVectorImpl< llvm::BasicBlock * > *deallocBlocks=nullptr)
Find the insertion point for allocas given the current insertion point for normal operations in the b...
static void sortMapIndices(llvm::SmallVectorImpl< size_t > &indices, omp::MapInfoOp mapInfo, bool first=true)
static LogicalResult convertOmpAtomicCapture(omp::AtomicCaptureOp atomicCaptureOp, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation)
static LogicalResult convertOmpTaskloopContextOp(omp::TaskloopContextOp contextOp, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation)
static Operation * getGlobalOpFromValue(Value value)
static llvm::OffloadEntriesInfoManager::OMPTargetGlobalVarEntryKind convertToCaptureClauseKind(mlir::omp::DeclareTargetCaptureClause captureClause)
static omp::MapInfoOp getFirstOrLastMappedMemberPtr(omp::MapInfoOp mapInfo, bool first)
static LogicalResult convertOmpDispatch(Operation &opInst, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation)
Convert 'dispatch' operation into LLVM IR.
static OpTy castOrGetParentOfType(Operation *op, bool immediateParent=false)
If op is of the given type parameter, return it casted to that type. Otherwise, if its immediate pare...
static LogicalResult convertOmpOrderedRegion(Operation &opInst, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation)
Converts an OpenMP 'ordered_region' operation into LLVM IR using OpenMPIRBuilder.
static LogicalResult convertFreeSharedMemOp(omp::FreeSharedMemOp freeMemOp, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation)
static LogicalResult convertTargetFreeMemOp(Operation &opInst, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation)
static LogicalResult convertOmpAtomicWrite(Operation &opInst, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation)
Converts an omp.atomic.write operation to LLVM IR.
static OwningAtomicReductionGen makeAtomicReductionGen(omp::DeclareReductionOp decl, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation)
Create an OpenMPIRBuilder-compatible atomic reduction generator for the given reduction declaration.
static void invalidateOmpLoop(LLVM::ModuleTranslation &moduleTranslation, Value mlir)
Mark an OpenMP loop as having been consumed.
static OwningDataPtrPtrReductionGen makeRefDataPtrGen(omp::DeclareReductionOp decl, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation, bool isByRef)
Create an OpenMPIRBuilder-compatible data_ptr_ptr reduction generator for the given reduction declara...
static llvm::Value * getRefPtrIfDeclareTarget(Value value, LLVM::ModuleTranslation &moduleTranslation)
static llvm::Function * emitTaskReductionCombFn(omp::DeclareReductionOp decl, StringRef baseName, LLVM::ModuleTranslation &moduleTranslation)
Build an outlined combiner helper for a task_reduction declare_reduction op. Signature: void(ptr lhs,...
static LogicalResult convertOmpWsloop(Operation &opInst, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation)
Converts an OpenMP workshare loop into LLVM IR using OpenMPIRBuilder.
static LogicalResult applyUnrollHeuristic(omp::UnrollHeuristicOp op, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation)
Apply a #pragma omp unroll / "!$omp unroll" transformation using the OpenMPIRBuilder.
static LogicalResult convertOmpMaster(Operation &opInst, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation)
Converts an OpenMP 'master' operation into LLVM IR using OpenMPIRBuilder.
static void getAsIntegers(ArrayAttr values, llvm::SmallVector< int64_t > &ints)
static void emitComplexAtomicCmpXchg(llvm::IRBuilderBase &builder, llvm::Value *llvmX, llvm::Type *complexTy, llvm::Value *eVal, llvm::Value *dVal, llvm::AtomicOrdering atomicOrdering, llvm::AtomicOrdering failOrdering, bool isWeak, llvm::Value *&oldComplex, llvm::Value *&cmpOk)
Emit an IEEE-754-correct cmpxchg for a complex (struct-typed) atomic compare with fcmp oeq....
static llvm::Value * findAssociatedValue(Value privateVar, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation, llvm::DenseMap< Value, Value > *mappedPrivateVars=nullptr)
Return the llvm::Value * corresponding to the privateVar that is being privatized....
static llvm::Expected< llvm::Value * > lookupOrTranslatePureValue(Value value, LLVM::ModuleTranslation &moduleTranslation, llvm::IRBuilderBase &builder)
Look up the given value in the mapping, and if it's not there, translate its defining operation at th...
static void emitTaskReductionModifierFini(bool isWorksharing, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation)
Emits __kmpc_task_reduction_modifier_fini(loc, gtid, is_ws) at the current builder insertion point,...
static LogicalResult convertOmpInteropUseOp(omp::InteropUseOp useOp, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation)
static LogicalResult convertOmpTaskwaitOp(omp::TaskwaitOp twOp, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation)
static LogicalResult collectAndValidateTaskloopRedDecls(Operation *contextOp, std::optional< ArrayAttr > syms, StringRef opName, StringRef clauseName, SmallVectorImpl< omp::DeclareReductionOp > &out)
Look up and validate the declare_reduction ops referenced by a reduction-like clause on the omp....
static LogicalResult convertOmpLoopNest(Operation &opInst, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation)
Converts an OpenMP loop nest into LLVM IR using OpenMPIRBuilder.
static LogicalResult allocAndInitializeReductionVars(Operation &op, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation, llvm::OpenMPIRBuilder::InsertPointTy &allocaIP, ReductionVarsInfo &redInfo)
static mlir::LogicalResult fillIteratorLoop(mlir::omp::IteratorOp itersOp, llvm::IRBuilderBase &builder, mlir::LLVM::ModuleTranslation &moduleTranslation, IteratorInfo &iterInfo, llvm::StringRef loopName, IteratorStoreEntryTy genStoreEntry)
static void createAlteredByCaptureMap(MapInfoData &mapData, LLVM::ModuleTranslation &moduleTranslation, llvm::IRBuilderBase &builder)
static LogicalResult convertOmpTaskOp(omp::TaskOp taskOp, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation)
Converts an OpenMP task construct into LLVM IR using OpenMPIRBuilder.
static void genMapInfos(llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation, DataLayout &dl, MapInfosTy &combinedInfo, MapInfoData &mapData, TargetDirectiveEnumTy targetDirective)
static llvm::AtomicOrdering convertAtomicOrdering(std::optional< omp::ClauseMemoryOrderKind > ao)
Convert an Atomic Ordering attribute to llvm::AtomicOrdering.
static LogicalResult convertOmpInteropInitOp(omp::InteropInitOp initOp, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation)
static void setInsertPointForPossiblyEmptyBlock(llvm::IRBuilderBase &builder, llvm::BasicBlock *block=nullptr)
static void mapInitializationArgs(LLVM::ModuleTranslation &moduleTranslation, llvm::IRBuilderBase &builder, const ReductionVarsInfo::VarInfo &redVarInfo)
Map input arguments to reduction initialization region.
static mlir::LogicalResult convertIteratorRegion(llvm::Value *linearIV, IteratorInfo &iterInfo, mlir::Region &iteratorRegion, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation)
llvm::function_ref< void(llvm::Value *linearIV, mlir::omp::YieldOp yield)> IteratorStoreEntryTy
static llvm::Function * emitTaskReductionInitFn(omp::DeclareReductionOp decl, StringRef baseName, LLVM::ModuleTranslation &moduleTranslation)
Build an outlined init helper for a task_reduction declare_reduction op. Signature: void(ptr priv,...
static LogicalResult convertOmpSections(Operation &opInst, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation)
static llvm::Expected< llvm::BasicBlock * > allocatePrivateVars(T op, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation, PrivateVarsInfo &privateVarsInfo, llvm::OpenMPIRBuilder::InsertPointTy &allocaIP, llvm::DenseMap< Value, Value > *mappedPrivateVars=nullptr, std::optional< llvm::OpenMPIRBuilder::InsertPointTy > allocatorIP=std::nullopt)
Allocate and initialize delayed private variables. Returns the basic block which comes after all of t...
static LogicalResult applyUnrollPartial(omp::UnrollPartialOp op, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation)
Apply a #pragma omp unroll partial / !$omp unroll partial transformation using the OpenMPIRBuilder.
static void addNonContiguousUpdate(LLVM::ModuleTranslation &moduleTranslation, llvm::IRBuilderBase &builder, MapInfoData &mapData, size_t mapDataIdx, MapInfosTy &combinedInfo)
Describe a bounded update as a set of contiguous pieces. Bounds follow the dialect's normalized faste...
static LogicalResult convertOmpCritical(Operation &opInst, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation)
Converts an OpenMP 'critical' operation into LLVM IR using OpenMPIRBuilder.
static LogicalResult convertTargetAllocMemOp(Operation &opInst, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation)
static omp::DistributeOp getDistributeCapturingTeamsReduction(omp::TeamsOp teamsOp)
static LogicalResult convertOmpCanonicalLoopOp(omp::CanonicalLoopOp op, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation)
Convert an omp.canonical_loop to LLVM-IR.
static LogicalResult convertOmpTargetData(Operation *op, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation)
static std::optional< int64_t > extractConstInteger(Value value)
If the given value is defined by an llvm.mlir.constant operation and it is of an integer type,...
static llvm::Expected< llvm::Value * > initPrivateVar(llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation, omp::PrivateClauseOp &privDecl, llvm::Value *nonPrivateVar, BlockArgument &blockArg, llvm::Value *llvmPrivateVar, llvm::BasicBlock *privInitBlock, llvm::DenseMap< Value, Value > *mappedPrivateVars=nullptr)
Initialize a single (first)private variable. You probably want to use allocateAndInitPrivateVars inst...
static OpenMPTranslationState & getOpenMPState(LLVM::ModuleTranslation &moduleTranslation)
static mlir::LogicalResult buildAffinityData(mlir::omp::TaskOp &taskOp, llvm::IRBuilderBase &builder, mlir::LLVM::ModuleTranslation &moduleTranslation, llvm::OpenMPIRBuilder::AffinityData &ad)
static LogicalResult convertOmpSimd(Operation &opInst, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation)
Converts an OpenMP simd loop into LLVM IR using OpenMPIRBuilder.
static void processIndividualMap(LLVM::ModuleTranslation &moduleTranslation, llvm::IRBuilderBase &builder, llvm::OpenMPIRBuilder &ompBuilder, MapInfoData &mapData, size_t mapDataIdx, MapInfosTy &combinedInfo, TargetDirectiveEnumTy targetDirective, llvm::omp::OpenMPOffloadMappingFlags memberOfFlag=llvm::omp::OpenMPOffloadMappingFlags::OMP_MAP_NONE, bool isTargetParam=true, int mapDataParentIdx=-1)
This function handles the insertion of a single item of map data from MapInfoData into the OMPIRBuild...
static LogicalResult convertOmpInteropDestroyOp(omp::InteropDestroyOp destroyOp, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation)
static void mapOmpLoop(LLVM::ModuleTranslation &moduleTranslation, Value mlir, llvm::CanonicalLoopInfo *llvm)
Map an MLIR OpenMP dialect CanonicalLoopInfo to its lowered LLVM-IR OpenMPIRBuilder CanonicalLoopInfo...
static LogicalResult convertOmpDistribute(Operation &opInst, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation)
static llvm::Value * getAllocationSize(llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation, T op)
static LogicalResult allocReductionVars(Operation &op, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation, const llvm::OpenMPIRBuilder::InsertPointTy &allocaIP, ReductionVarsInfo &redInfo)
Allocate space for privatized reduction variables.
static llvm::Function * getOmpTargetAlloc(llvm::IRBuilderBase &builder, llvm::Module *llvmModule)
static llvm::omp::OMPDynGroupprivateFallbackType getDynGroupprivateFallbackType(omp::FallbackModifierAttr fallbackAttr)
static llvm::Expected< llvm::Function * > emitUserDefinedMapper(Operation *declMapperOp, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation, llvm::StringRef mapperFuncName, TargetDirectiveEnumTy targetDirective)
static LogicalResult convertOmpOrdered(Operation &opInst, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation)
Converts an OpenMP 'ordered' operation into LLVM IR using OpenMPIRBuilder.
static LogicalResult cleanupPrivateVars(T op, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation, Location loc, PrivateVarsInfo &privateVarsInfo)
static void processMapWithMembersOf(LLVM::ModuleTranslation &moduleTranslation, llvm::IRBuilderBase &builder, llvm::OpenMPIRBuilder &ompBuilder, DataLayout &dl, MapInfosTy &combinedInfo, MapInfoData &mapData, uint64_t mapDataIndex, TargetDirectiveEnumTy targetDirective)
static LogicalResult convertOmpMasked(Operation &opInst, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation)
Converts an OpenMP 'masked' operation into LLVM IR using OpenMPIRBuilder.
static llvm::CanonicalLoopInfo * lookupOMPLoop(LLVM::ModuleTranslation &moduleTranslation, Value mlir)
Find the LLVM-IR loop that represents an MLIR loop.
static llvm::AtomicRMWInst::BinOp convertBinOpToAtomic(Operation &op)
Converts an LLVM dialect binary operation to the corresponding enum value for atomicrmw supported bin...
static LogicalResult createReductionsAndCleanup(Operation &op, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation, llvm::OpenMPIRBuilder::InsertPointTy &allocaIP, ReductionVarsInfo &redInfo, bool isNowait=false, bool isTeamsReduction=false)
static LogicalResult convertOmpCancel(omp::CancelOp op, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation)
static int getMapDataMemberIdx(MapInfoData &mapData, omp::MapInfoOp memberOp)
allocatedType moduleTranslation static convertType(allocatedType) LogicalResult inlineOmpRegionCleanup(llvm::SmallVectorImpl< Region * > &cleanupRegions, llvm::ArrayRef< llvm::Value * > privateVariables, LLVM::ModuleTranslation &moduleTranslation, llvm::IRBuilderBase &builder, StringRef regionName, bool shouldLoadCleanupRegionArg=true)
handling of DeclareReductionOp's cleanup region
static LogicalResult applyFuse(omp::FuseOp op, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation)
Apply a #pragma omp fuse / !$omp fuse transformation using the OpenMPIRBuilder.
static llvm::Value * materializeRegionArgValue(llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation, BlockArgument regionArg, llvm::Value *value)
static LogicalResult convertOmpScope(omp::ScopeOp &scopeOp, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation)
Converts an OpenMP scope construct into LLVM IR.
static bool isPrivatizeableAttachMap(omp::ClauseMapFlags mapType)
static llvm::Value * getSizeInBytes(DataLayout &dl, const mlir::Type &type, Operation *clauseOp, llvm::Value *basePointer, llvm::Type *baseType, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation)
static llvm::Error initPrivateVars(llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation, PrivateVarsInfo &privateVarsInfo, llvm::DenseMap< Value, Value > *mappedPrivateVars=nullptr)
static LogicalResult convertAllocSharedMemOp(omp::AllocSharedMemOp allocMemOp, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation)
static llvm::CanonicalLoopInfo * findCurrentLoopInfo(LLVM::ModuleTranslation &moduleTranslation)
Find the loop information structure for the loop nest being translated.
static OwningReductionGen makeReductionGen(omp::DeclareReductionOp decl, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation)
Create an OpenMPIRBuilder-compatible reduction generator for the given reduction declaration.
static void storeAffinityEntry(llvm::IRBuilderBase &builder, llvm::OpenMPIRBuilder &ompBuilder, llvm::Value *affinityList, llvm::Value *index, llvm::Value *addr, llvm::Value *len)
static LogicalResult convertOmpParallel(omp::ParallelOp opInst, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation)
Converts the OpenMP parallel operation to LLVM IR.
static void pushCancelFinalizationCB(SmallVectorImpl< llvm::UncondBrInst * > &cancelTerminators, llvm::IRBuilderBase &llvmBuilder, llvm::OpenMPIRBuilder &ompBuilder, mlir::Operation *op, llvm::omp::Directive cancelDirective)
Shared implementation of a callback which adds a termiator for the new block created for the branch t...
static LogicalResult inlineConvertOmpRegions(Region &region, StringRef blockName, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation, SmallVectorImpl< llvm::Value * > *continuationBlockArgs=nullptr)
Translates the blocks contained in the given region and appends them to at the current insertion poin...
static void getTargetEntryUniqueInfo(llvm::TargetRegionEntryInfo &targetInfo, omp::TargetOp targetOp, llvm::OpenMPIRBuilder &ompBuilder, llvm::vfs::FileSystem &vfs, llvm::StringRef parentName="")
static LogicalResult convertOmpThreadprivate(Operation &opInst, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation)
Converts an OpenMP Threadprivate operation into LLVM IR using OpenMPIRBuilder.
static omp::PrivateClauseOp findPrivatizer(Operation *from, SymbolRefAttr symbolName)
Looks up from the operation from and returns the PrivateClauseOp with name symbolName.
static llvm::OpenMPIRBuilder * getOpenMPBuilder(LLVM::ModuleTranslation &moduleTranslation)
Returns the OpenMP IR builder associated with the LLVM IR module being constructed.
static LogicalResult applyUnrollFull(omp::UnrollFullOp op, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation)
Apply a #pragma omp unroll full / !$omp unroll full transformation using the OpenMPIRBuilder.
static LogicalResult convertOmpGroupprivate(Operation &opInst, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation)
Converts an OpenMP groupprivate operation into LLVM IR.
static llvm::Expected< llvm::Function * > getOrCreateUserDefinedMapperFunc(Operation *op, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation, TargetDirectiveEnumTy targetDirective)
static llvm::Value * getSourceLocIdentFromOp(llvm::IRBuilderBase &builder, llvm::OpenMPIRBuilder &ompBuilder, Operation *op)
static uint64_t getTypeByteSize(mlir::Type type, const DataLayout &dl)
static llvm::SmallString< 64 > getDeclareTargetRefPtrSuffix(LLVM::GlobalOp globalOp, llvm::OpenMPIRBuilder &ompBuilder, llvm::vfs::FileSystem &vfs)
static LogicalResult completePrivateVars(mlir::Operation *op, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation, const PrivateVarsInfo &privateVarsInfo, bool insertBarrier, ArrayRef< llvm::Value * > moldVars={}, ArrayRef< llvm::Value * > llvmPrivateVars={}, DenseMap< Value, Value > *mappedPrivateVars=nullptr)
Applies the firstprivate copy region for each variable, pairing the mold values with the private allo...
static void extractHostEvalClauses(omp::TargetOp targetOp, Value &numThreads, Value &numTeamsLower, Value &numTeamsUpper, Value &threadLimit, llvm::SmallVectorImpl< Value > *lowerBounds=nullptr, llvm::SmallVectorImpl< Value > *upperBounds=nullptr, llvm::SmallVectorImpl< Value > *steps=nullptr)
Follow uses of host_eval-defined block arguments of the given omp.target operation and populate outpu...
static llvm::Expected< llvm::BasicBlock * > convertOmpOpRegions(Region &region, StringRef blockName, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation, SmallVectorImpl< llvm::PHINode * > *continuationBlockPHIs=nullptr)
Converts the given region that appears within an OpenMP dialect operation to LLVM IR,...
static LogicalResult extractAtomicComparePattern(Block &block, llvm::function_ref< llvm::Value *(mlir::Value)> materializeValue, omp::AtomicCompareOp atomicCompareOp, AtomicComparePatternInfo &info)
Extract comparison predicate, expected value (e), desired value (d), and related flags from an atomic...
static LogicalResult convertOmpAtomicCompare(omp::AtomicCompareOp atomicCompareOp, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation)
Converts an omp.atomic.compare operation to LLVM IR.
static void hoistMapperAllocasToEntry(llvm::Function &mapperFn)
The mapper body (and any iterator regions in it) is emitted inside the mapper's per-element loop,...
static LogicalResult convertAllocateDirOp(Operation &opInst, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation, const OpenMPDialectLLVMIRTranslationInterface &ompIface)
static bool constructIsCancellable(Operation *op)
Returns true if the construct contains omp.cancel or omp.cancellation_point.
static llvm::omp::OpenMPOffloadMappingFlags convertClauseMapFlags(omp::ClauseMapFlags mlirFlags)
static LogicalResult convertAllocatorVars(Operation &op, ValueRange allocatorVars, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation, PrivateVarsInfo &privateVarsInfo)
static void buildDependDataLocator(std::optional< ArrayAttr > dependKinds, OperandRange dependVars, LLVM::ModuleTranslation &moduleTranslation, SmallVectorImpl< llvm::OpenMPIRBuilder::DependData > &dds)
static std::optional< llvm::omp::OMPAtomicCompareOp > convertFCmpPredicateToAtomicCompareOp(LLVM::FCmpPredicate predicate)
Helper to extract the OMPAtomicCompareOp from a floating-point comparison predicate....
static llvm::Value * emitTaskReductionInitCall(ArrayRef< omp::DeclareReductionOp > redDecls, ArrayRef< llvm::Value * > origPtrs, StringRef helperNamePrefix, llvm::IRBuilderBase &builder, llvm::OpenMPIRBuilder::InsertPointTy allocaIP, LLVM::ModuleTranslation &moduleTranslation, bool isModifier=false, bool isWorksharing=false)
Emit the per-taskgroup task_reduction descriptor array and the __kmpc_taskred_init runtime call....
static llvm::Expected< llvm::Value * > getPrivateDataAddress(llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation, omp::PrivateClauseOp privatizer, llvm::Value *var)
Returns the address of the data in var, via the data_address region.
static llvm::omp::ProcBindKind getProcBindKind(omp::ClauseProcBindKind kind)
Convert ProcBindKind from MLIR-generated enum to LLVM enum.
static void fillAffinityLocators(Operation::operand_range affinityVars, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation, llvm::Value *affinityList)
static LogicalResult convertOmpTaskloopWrapperOp(omp::TaskloopWrapperOp loopWrapperOp, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation)
The correct entry point is convertOmpTaskloopContextOp. This gets called whilst lowering the body of ...
static void getOverlappedMembers(llvm::SmallVectorImpl< size_t > &overlapMapDataIdxs, omp::MapInfoOp parentOp)
static LogicalResult convertOmpSingle(omp::SingleOp &singleOp, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation)
Converts an OpenMP single construct into LLVM IR using OpenMPIRBuilder.
static bool isDeclareTargetTo(Value value)
static uint64_t getArrayElementSizeInBits(LLVM::LLVMArrayType arrTy, DataLayout &dl)
static void popCancelFinalizationCB(const ArrayRef< llvm::UncondBrInst * > cancelTerminators, llvm::OpenMPIRBuilder &ompBuilder, llvm::BasicBlock *afterBB)
If we cancelled the construct, we should branch to the finalization block of that construct....
static void collectReductionDecls(T op, SmallVectorImpl< omp::DeclareReductionOp > &reductions)
Populates reductions with reduction declarations used in the given op.
static LogicalResult handleError(llvm::Error error, Operation &op)
static LogicalResult convertOmpTarget(Operation &opInst, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation)
static llvm::OffloadEntriesInfoManager::OMPTargetDeviceClauseKind convertToDeviceClauseKind(mlir::omp::DeclareTargetDeviceType deviceClause)
static std::optional< llvm::omp::OMPAtomicCompareOp > convertICmpPredicateToAtomicCompareOp(LLVM::ICmpPredicate predicate)
Helper to extract the OMPAtomicCompareOp from an integer comparison predicate. Returns std::nullopt f...
static llvm::Error computeTaskloopBounds(omp::LoopNestOp loopOp, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation, llvm::Value *&lbVal, llvm::Value *&ubVal, llvm::Value *&stepVal)
static LogicalResult checkImplementationStatus(Operation &op)
Check whether translation to LLVM IR for the given operation is currently supported.
static llvm::IRBuilderBase::InsertPoint createDeviceArgumentAccessor(omp::TargetOp targetOp, MapInfoData &mapData, llvm::Argument &arg, llvm::Value *input, llvm::Value *&retVal, llvm::IRBuilderBase &builder, llvm::OpenMPIRBuilder &ompBuilder, LLVM::ModuleTranslation &moduleTranslation, llvm::IRBuilderBase::InsertPoint allocaIP, llvm::IRBuilderBase::InsertPoint codeGenIP, llvm::ArrayRef< llvm::IRBuilderBase::InsertPoint > deallocIPs)
static LogicalResult convertOmpCancellationPoint(omp::CancellationPointOp op, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation)
static llvm::omp::AtomicControl extractAtomicControlFlags(omp::AtomicUpdateOp atomicUpdateOp)
static uint64_t getReductionDataSize(OpTy &op)
static bool opMightBeSafeForBarriers(mlir::Operation *op)
A compiler-generated barrier is unsafe when only part of the current team can reach it....
static LogicalResult convertOmpAtomicRead(Operation &opInst, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation)
Convert omp.atomic.read operation to LLVM IR.
static llvm::omp::Directive convertCancellationConstructType(omp::ClauseCancellationConstructType directive)
static void initTargetDefaultAttrs(omp::TargetOp targetOp, Operation *capturedOp, llvm::OpenMPIRBuilder::TargetKernelDefaultAttrs &attrs, bool isTargetDevice, bool isGPU)
Populate default MinTeams, MaxTeams and MaxThreads to their default values as stated by the correspon...
static llvm::AtomicOrdering getAtomicCompareFailureOrdering(omp::AtomicCompareOp atomicCompareOp, llvm::AtomicOrdering atomicOrdering)
Compute the cmpxchg failure ordering for an atomic compare op: use the fail clause ordering when pres...
static llvm::Value * emitTaskReductionModifierInitCall(OpTy op, ArrayRef< omp::DeclareReductionOp > reductionDecls, ArrayRef< llvm::Value * > privateReductionVariables, llvm::IRBuilderBase &builder, llvm::OpenMPIRBuilder::InsertPointTy allocaIP, LLVM::ModuleTranslation &moduleTranslation, bool isWorksharing)
Register only the task-modified items. All items still participate in the enclosing construct's ordin...
static llvm::omp::RTLDependenceKindTy convertDependKind(mlir::omp::ClauseTaskDepend kind)
static void initTargetRuntimeAttrs(llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation, omp::TargetOp targetOp, Operation *capturedOp, llvm::OpenMPIRBuilder::TargetKernelRuntimeAttrs &attrs)
Gather LLVM runtime values for all clauses evaluated in the host that are passed to the kernel invoca...
static LogicalResult emitPrivatizationBarrier(mlir::Operation *op, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation)
static ComplexComparePattern detectComplexCompareEq(Block &block)
Detect a decomposed complex equality comparison in an atomic compare region: re_x = llvm....
static LogicalResult convertOmpTeams(omp::TeamsOp op, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation)
static Value getBaseValueForTypeLookup(Value value)
static bool isHostDeviceOp(Operation *op)
static LogicalResult convertDeclareTargetAttr(Operation *op, mlir::omp::DeclareTargetAttr attribute, llvm::OpenMPIRBuilder *ompBuilder, LLVM::ModuleTranslation &moduleTranslation)
static bool isDeclareTargetLink(Value value)
static LogicalResult convertFlagsAttr(Operation *op, mlir::omp::FlagsAttr attribute, LLVM::ModuleTranslation &moduleTranslation)
Lowers the FlagsAttr which is applied to the module when offloading. This attribute contains OpenMP R...
static bool checkIfPointerMap(omp::MapInfoOp mapOp)
static llvm::Type * getAllocatedLlvmTypeForVariable(Value var, Value baseVar, LLVM::ModuleTranslation &moduleTranslation)
static LogicalResult applyTile(omp::TileOp op, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation)
Apply a #pragma omp tile / !$omp tile transformation using the OpenMPIRBuilder.
static LogicalResult convertAllocateFreeOp(Operation &opInst, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation, const OpenMPDialectLLVMIRTranslationInterface &ompIface)
static StringRef getMapClauseName(omp::MapInfoOp mapOp)
static std::vector< llvm::Value * > calculateBoundsOffset(LLVM::ModuleTranslation &moduleTranslation, llvm::IRBuilderBase &builder, bool isArrayTy, OperandRange bounds, bool &isByteOffset)
This function calculates the array/pointer offset for map data provided with bounds operations,...
static llvm::Function * getOmpTargetFree(llvm::IRBuilderBase &builder, llvm::Module *llvmModule)
static LogicalResult convertOmpTaskgroupOp(omp::TaskgroupOp tgOp, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation)
Converts an OpenMP taskgroup construct into LLVM IR using OpenMPIRBuilder.
static std::optional< llvm::Value * > getDynamicAllocatedSize(Value var, Value baseVar, LLVM::ModuleTranslation &moduleTranslation, llvm::IRBuilderBase &builder, const llvm::DataLayout &dataLayout)
static void collectMapDataFromMapOperands(MapInfoData &mapData, SmallVectorImpl< Value > &mapVars, LLVM::ModuleTranslation &moduleTranslation, DataLayout &dl, llvm::IRBuilderBase &builder, ArrayRef< Value > useDevPtrOperands={}, ArrayRef< Value > useDevAddrOperands={}, ArrayRef< Value > hasDevAddrOperands={})
static Operation * genLoop(CodegenEnv &env, OpBuilder &builder, LoopId curr, unsigned numCases, bool needsUniv, ArrayRef< TensorLevel > tidLvls)
Generates a for-loop or a while-loop, depending on whether it implements singleton iteration or co-it...
#define MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(CLASS_NAME)
Definition TypeID.h:331
Attributes are known-constant values of operations.
Definition Attributes.h:25
This class represents an argument of a Block.
Definition Value.h:308
Block represents an ordered list of Operations.
Definition Block.h:34
BlockArgument getArgument(unsigned i)
Definition Block.h:154
unsigned getNumArguments()
Definition Block.h:153
OpListType & getOperations()
Definition Block.h:162
Operation & front()
Definition Block.h:178
Operation & back()
Definition Block.h:177
Operation * getTerminator()
Get the terminator operation of this block.
Definition Block.cpp:249
iterator_range< iterator > without_terminator()
Return an iterator range over the operation within this block excluding the terminator operation at t...
Definition Block.h:222
iterator begin()
Definition Block.h:168
The main mechanism for performing data layout queries.
llvm::TypeSize getTypeSize(Type t) const
Returns the size of the given type in the current scope.
llvm::TypeSize getTypeSizeInBits(Type t) const
Returns the size in bits of the given type in the current scope.
The DialectRegistry maps a dialect namespace to a constructor for the matching dialect.
bool addExtension(TypeID extensionID, std::unique_ptr< DialectExtensionBase > extension)
Add the given extension to the registry.
An instance of this location represents a tuple of file, line number, and column number.
Definition Location.h:176
Base class for state that lives as long as the module translation.
Implementation class for module translation.
llvm::BasicBlock * lookupBlock(Block *block) const
Finds an LLVM IR basic block that corresponds to the given MLIR block.
WalkResult stackWalk(llvm::function_ref< WalkResult(T &)> callback)
Calls callback for every ModuleTranslation stack frame of type T starting from the top of the stack.
void stackPush(Args &&...args)
Creates a stack frame of type T on ModuleTranslation stack.
LogicalResult convertBlock(Block &bb, bool ignoreArguments, llvm::IRBuilderBase &builder)
Translates the contents of the given block to LLVM IR using this translator.
SmallVector< llvm::Value * > lookupValues(ValueRange values)
Looks up remapped a list of remapped values.
void mapFunction(StringRef name, llvm::Function *func)
Stores the mapping between a function name and its LLVM IR representation.
T & getOrCreateExtension(Args &&...args)
Returns the extension of type T, constructing it from args on first use.
llvm::Value * lookupValue(Value value) const
Finds an LLVM IR value corresponding to the given MLIR value.
SymbolTableCollection & symbolTable()
llvm::Type * convertType(Type type)
Converts the type from MLIR LLVM dialect to LLVM.
llvm::vfs::FileSystem & getFileSystem()
Returns the virtual filesystem to use for file operations.
llvm::GlobalValue * lookupGlobal(Operation *op)
Finds an LLVM IR global value that corresponds to the given MLIR operation defining a global value.
SaveStateStack< T, ModuleTranslation > SaveStack
RAII object calling stackPush/stackPop on construction/destruction.
void remapAllValuesWith(llvm::Value *oldValue, llvm::Value *newValue)
Remap old value with new value in the MLIR-to-LLVM value map so later translations use the replacemen...
LogicalResult convertOperation(Operation &op, llvm::IRBuilderBase &builder)
Converts the given MLIR operation into LLVM IR using this translator.
llvm::Function * lookupFunction(StringRef name) const
Finds an LLVM IR function by its name.
void mapBlock(Block *mlir, llvm::BasicBlock *llvm)
Stores the mapping between an MLIR block and LLVM IR basic block.
llvm::Module * getLLVMModule()
Returns the LLVM module in which the IR is being constructed.
void stackPop()
Pops the last element from the ModuleTranslation stack.
void forgetMapping(Region &region)
Removes the mapping for blocks contained in the region and values defined in these blocks.
void mapValue(Value mlir, llvm::Value *llvm)
Stores the mapping between an MLIR value and its LLVM IR counterpart.
llvm::LLVMContext & getLLVMContext() const
Returns the LLVM context in which the IR is being constructed.
Utility class to translate MLIR LLVM dialect types to LLVM IR.
Definition TypeToLLVM.h:39
unsigned getPreferredAlignment(Type type, const llvm::DataLayout &layout)
Returns the preferred alignment for the type given the data layout.
T findInstanceOf()
Return an instance of the given location type if one is nested under the current location.
Definition Location.h:45
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
Definition Location.h:76
MLIRContext is the top-level object for a collection of MLIR operations.
Definition MLIRContext.h:71
void appendDialectRegistry(const DialectRegistry &registry)
Append the contents of the given dialect registry to the registry associated with this context.
StringAttr getName() const
Return the name of the attribute.
Attribute getValue() const
Return the value of the attribute.
Definition Attributes.h:181
This class implements the operand iterators for the Operation class.
Definition ValueRange.h:44
StringAttr getIdentifier() const
Return the name of this operation as a StringAttr.
Operation is the basic unit of execution within MLIR.
Definition Operation.h:87
Region & getRegion(unsigned index)
Returns the region held by this operation at position 'index'.
Definition Operation.h:740
Value getOperand(unsigned idx)
Definition Operation.h:377
InFlightDiagnostic emitWarning(const Twine &message={})
Emit a warning about this operation, reporting up to any diagnostic handlers that may be listening.
OpResult getResult(unsigned idx)
Get the 'idx'th result of this operation.
Definition Operation.h:434
unsigned getNumRegions()
Returns the number of regions held by this operation.
Definition Operation.h:728
Location getLoc()
The source location the operation was defined or derived from.
Definition Operation.h:240
Operation * getParentOp()
Returns the closest surrounding operation that contains this operation or nullptr if this is a top-le...
Definition Operation.h:251
unsigned getNumOperands()
Definition Operation.h:373
OperandRange operand_range
Definition Operation.h:398
InFlightDiagnostic emitError(const Twine &message={})
Emit an error about fatal conditions with this operation, reporting up to any diagnostic handlers tha...
OpTy getParentOfType()
Return the closest surrounding parent operation that is of type 'OpTy'.
Definition Operation.h:255
OperationName getName()
The name of an operation is the key identifier for it.
Definition Operation.h:115
operand_range getOperands()
Returns an iterator on the underlying Value's.
Definition Operation.h:405
std::enable_if_t< llvm::function_traits< std::decay_t< FnT > >::num_args==1, RetT > walk(FnT &&callback)
Walk the operation by calling the callback for each nested operation (including this one),...
Definition Operation.h:851
user_range getUsers()
Returns a range of all users.
Definition Operation.h:927
result_range getResults()
Definition Operation.h:442
MLIRContext * getContext()
Return the context this operation is associated with.
Definition Operation.h:233
InFlightDiagnostic emitOpError(const Twine &message={})
Emit an error with the op name prefixed, like "'dim' op " which is convenient for verifiers.
unsigned getNumResults()
Return the number of results held by this operation.
Definition Operation.h:431
This class contains a list of basic blocks and a link to the parent operation it is attached to.
Definition Region.h:26
Block & front()
Definition Region.h:65
BlockArgListType getArguments()
Definition Region.h:94
bool empty()
Definition Region.h:60
unsigned getNumArguments()
Definition Region.h:136
iterator begin()
Definition Region.h:55
Operation * getParentOp()
Return the parent operation this region is attached to.
Definition Region.h:198
BlockListType & getBlocks()
Definition Region.h:45
bool hasOneBlock()
Return true if this region has exactly one block.
Definition Region.h:68
Concrete CRTP base class for StateStack frames.
Definition StateStack.h:47
@ Private
The symbol is private and may only be referenced by SymbolRefAttrs local to the operations within the...
Definition SymbolTable.h:92
static Operation * lookupNearestSymbolFrom(Operation *from, StringAttr symbol)
Returns the operation registered with the given symbol name within the closest parent operation of,...
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
Definition Types.h:74
This class provides an abstraction over the different types of ranges over Values.
Definition ValueRange.h:392
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
user_range getUsers() const
Definition Value.h:218
Operation * getDefiningOp() const
If this value is the result of an operation, return the operation that defines it.
Definition Value.cpp:18
A utility result that is used to signal how to proceed with an ongoing walk:
Definition WalkResult.h:29
static WalkResult skip()
Definition WalkResult.h:48
static WalkResult advance()
Definition WalkResult.h:47
bool wasInterrupted() const
Returns true if the walk was interrupted.
Definition WalkResult.h:51
static WalkResult interrupt()
Definition WalkResult.h:46
The OpAsmOpInterface, see OpAsmInterface.td for more details.
Definition CallGraph.h:229
void connectPHINodes(Region &region, const ModuleTranslation &state)
For all blocks in the region that were converted to LLVM IR using the given ModuleTranslation,...
llvm::Constant * createMappingInformation(Location loc, llvm::OpenMPIRBuilder &builder, StringRef mapName={})
Create a constant string representing the mapping information extracted from the MLIR location inform...
llvm::Constant * createSourceLocStrFromLocation(Location loc, llvm::OpenMPIRBuilder &builder, StringRef name, uint32_t &strLen, bool ForOffloadMap=false)
Create a constant string location from the MLIR Location information.
int64_t getOpenMPVersionAttribute(ModuleOp module, int64_t fallback=-1)
Returns the value of the omp.version attribute, if present, or the fallback.
Definition Utils.cpp:58
bool opInSharedDeviceContext(Operation &op)
Check whether the given operation is located in a context where an allocation to be used by multiple ...
Definition Utils.cpp:115
bool allocaUsesRequireSharedMem(Value alloc)
Check whether the value representing an allocation, assumed to have been defined in a shared device c...
Definition Utils.cpp:100
detail::InFlightRemark failed(Location loc, RemarkOpts opts)
Report an optimization remark that failed.
Definition Remarks.h:886
auto getDims(VectorType vType)
Returns a range over the dims (size and scalability) of a VectorType.
Include the generated interface declarations.
detail::DenseArrayAttrImpl< int64_t > DenseI64ArrayAttr
SetVector< Block * > getBlocksSortedByDominance(Region &region)
Gets a list of blocks that is sorted according to dominance.
InFlightDiagnostic emitError(Location loc)
Utility method to emit an error message using this location.
bool isPure(Operation *op)
Returns true if the given operation is pure, i.e., is speculatable that does not touch memory.
void registerOpenMPDialectTranslation(DialectRegistry &registry)
Register the OpenMP dialect and the translation from it to the LLVM IR in the given registry;.
llvm::SetVector< T, Vector, Set, N > SetVector
Definition LLVM.h:128
SmallVector< Loops, 8 > tile(ArrayRef< scf::ForOp > forOps, ArrayRef< Value > sizes, ArrayRef< scf::ForOp > targets)
Performs tiling fo imperfectly nested loops (with interchange) by strip-mining the forOps by sizes an...
Definition Utils.cpp:1411
llvm::DenseMap< KeyT, ValueT, KeyInfoT, BucketT > DenseMap
Definition LLVM.h:123
void registerOpenMPTranslationCLOptions()
Register OpenMP translation command-line options before parsing them.
Holds the extracted comparison pattern information from an atomic compare region.
llvm::omp::OMPAtomicCompareOp compareOp
Result of matching the decomposed complex equality pattern inside an atomic compare region.
Eliminates variable at the specified position using Fourier-Motzkin variable elimination.