MLIR 24.0.0git
ACCAtomicPatterns.cpp
Go to the documentation of this file.
1//===- ACCAtomicPatterns.cpp - ACC atomic to LLVM patterns ------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// Lowers OpenACC atomic operations (read, write, update, capture) to LLVM
10// dialect atomicrmw / cmpxchg sequences.
11//
12//===----------------------------------------------------------------------===//
13
15
29#include "mlir/IR/BuiltinOps.h"
31#include "llvm/ADT/TypeSwitch.h"
32#include "llvm/Support/Debug.h"
33
34#include <cstdint>
35#include <optional>
36#include <set>
37#include <utility>
38
39#define DEBUG_TYPE "acc-atomic-patterns"
40
41using namespace mlir;
42using namespace mlir::acc;
43
44namespace {
45
46constexpr uint64_t kBitsInByte = 8;
47
48template <typename AtomicOpTy>
49class ACCAtomicOpConversion : public ConvertOpToLLVMPattern<AtomicOpTy> {
51
52public:
53 ACCAtomicOpConversion(const LLVMTypeConverter &typeConverter,
54 OpenACCSupport &accSupport,
55 const ACCAtomicLoadAddressCallback &getLoadAddress)
57 accSupport(accSupport), getLoadAddress(getLoadAddress) {}
58
59 LogicalResult
60 matchAndRewrite(AtomicOpTy op, OpAdaptor adaptor,
61 ConversionPatternRewriter &rewriter) const override;
62
63private:
64 OpenACCSupport &accSupport;
65 ACCAtomicLoadAddressCallback getLoadAddress;
66
67 size_t getComplexStructElementSizeInBits(Type ty) const {
68 auto structType = dyn_cast<LLVM::LLVMStructType>(ty);
69 if (!structType || structType.getBody().size() != 2 ||
70 structType.getBody()[0] != structType.getBody()[1] ||
71 !structType.getBody()[0].isIntOrFloat())
72 return 0;
73 size_t elementSizeInBits = structType.getBody()[0].getIntOrFloatBitWidth();
74 if (elementSizeInBits == 0 || elementSizeInBits > 64)
75 llvm_unreachable("unexpected complex type");
76 return elementSizeInBits;
77 }
78
79 /// Serialize a complex value into an integer.
80 Value serializeExpr(Value expr, ConversionPatternRewriter &rewriter) const {
81 size_t elementSizeInBits =
82 getComplexStructElementSizeInBits(expr.getType());
83 if (!elementSizeInBits)
84 return expr;
85
86 Location loc = expr.getLoc();
87 Value firstValue = LLVM::ExtractValueOp::create(rewriter, loc, expr, 0);
88 Value secondValue = LLVM::ExtractValueOp::create(rewriter, loc, expr, 1);
89 MLIRContext *context = rewriter.getContext();
90 Type intCastTy = IntegerType::get(context, elementSizeInBits);
91 Type intTy = IntegerType::get(context, elementSizeInBits * 2);
92 firstValue = LLVM::BitcastOp::create(rewriter, loc, intCastTy, firstValue);
93 secondValue =
94 LLVM::BitcastOp::create(rewriter, loc, intCastTy, secondValue);
95 firstValue = LLVM::ZExtOp::create(rewriter, loc, intTy, firstValue);
96 secondValue = LLVM::ZExtOp::create(rewriter, loc, intTy, secondValue);
97 Value shlVal =
98 LLVM::ConstantOp::create(rewriter, loc, intTy, elementSizeInBits);
99 Value result = LLVM::ShlOp::create(rewriter, loc, secondValue, shlVal);
100 return LLVM::OrOp::create(rewriter, loc, result, firstValue);
101 }
102
103 /// Deserialize the real part of a complex value of type `origTy` from an
104 /// integer of the same size.
105 Value deserializeRealPart(Value expr, Type origTy,
106 ConversionPatternRewriter &rewriter) const {
107 size_t elementSizeInBits = getComplexStructElementSizeInBits(origTy);
108 assert(elementSizeInBits && "expected a complex type");
109 assert(expr.getType() ==
110 IntegerType::get(rewriter.getContext(), elementSizeInBits * 2) &&
111 "expected an integer of the size of the complex type");
112
113 Location loc = expr.getLoc();
114 Type elemTy = IntegerType::get(rewriter.getContext(), elementSizeInBits);
115 Value real = LLVM::TruncOp::create(rewriter, loc, elemTy, expr);
116 Type origElemTy = cast<LLVM::LLVMStructType>(origTy).getBody()[0];
117
118 if (origElemTy != elemTy)
119 real = LLVM::BitcastOp::create(rewriter, loc, origElemTy, real);
120
121 return real;
122 }
123
124 /// Deserialize an integer into a complex value.
125 Value deserializeExpr(Value expr, Type origTy,
126 ConversionPatternRewriter &rewriter) const {
127 size_t elementSizeInBits = getComplexStructElementSizeInBits(origTy);
128 if (!elementSizeInBits)
129 return expr;
130
131 auto intTy = dyn_cast<IntegerType>(expr.getType());
132 if (!intTy || intTy.getWidth() != elementSizeInBits * 2)
133 return expr;
134
135 Location loc = expr.getLoc();
136 MLIRContext *context = rewriter.getContext();
137 Type elemTy = IntegerType::get(context, elementSizeInBits);
138 Value low = LLVM::TruncOp::create(rewriter, loc, elemTy, expr);
139 Value shiftAmount =
140 LLVM::ConstantOp::create(rewriter, loc, intTy, elementSizeInBits);
141 Value highFull = LLVM::LShrOp::create(rewriter, loc, expr, shiftAmount);
142 Value high = LLVM::TruncOp::create(rewriter, loc, elemTy, highFull);
143 Type origElemTy = cast<LLVM::LLVMStructType>(origTy).getBody()[0];
144 if (origElemTy != elemTy) {
145 low = LLVM::BitcastOp::create(rewriter, loc, origElemTy, low);
146 high = LLVM::BitcastOp::create(rewriter, loc, origElemTy, high);
147 }
148 Value undefStruct = LLVM::UndefOp::create(rewriter, loc, origTy);
149 Value structWithLow = LLVM::InsertValueOp::create(
150 rewriter, loc, origTy, undefStruct, low, ArrayRef<int64_t>{0});
151 return LLVM::InsertValueOp::create(rewriter, loc, origTy, structWithLow,
152 high, ArrayRef<int64_t>{1});
153 }
154
155 /// Convert `value` to `toTy`. A complex value is converted part by part, a
156 /// scalar converted to a complex value is its real part with a zero
157 /// imaginary part, and a complex value converted to a scalar is its real
158 /// part. Scalar conversions are generated by `ptrType`. Returns a null value
159 /// if a conversion is not supported.
160 Value genConvert(PointerLikeType ptrType, Value value, Type toTy,
161 Location loc, ConversionPatternRewriter &rewriter) const {
162 Type fromTy = value.getType();
163
164 if (fromTy == toTy)
165 return value;
166
167 bool fromComplex = getComplexStructElementSizeInBits(fromTy) != 0;
168 bool toComplex = getComplexStructElementSizeInBits(toTy) != 0;
169
170 if (!fromComplex && !toComplex)
171 return ptrType.genCast(rewriter, loc, value, toTy);
172
173 Value real = value;
174
175 if (fromComplex)
176 real = LLVM::ExtractValueOp::create(rewriter, loc, value, 0);
177
178 if (!toComplex)
179 return genConvert(ptrType, real, toTy, loc, rewriter);
180
181 Type toElemTy = cast<LLVM::LLVMStructType>(toTy).getBody()[0];
182 real = genConvert(ptrType, real, toElemTy, loc, rewriter);
183
184 if (!real)
185 return {};
186
187 Value imag;
188
189 if (fromComplex) {
190 imag = LLVM::ExtractValueOp::create(rewriter, loc, value, 1);
191 imag = genConvert(ptrType, imag, toElemTy, loc, rewriter);
192
193 if (!imag)
194 return {};
195 } else {
196 imag = LLVM::ZeroOp::create(rewriter, loc, toElemTy);
197 }
198
199 Value result = LLVM::UndefOp::create(rewriter, loc, toTy);
200 result = LLVM::InsertValueOp::create(rewriter, loc, toTy, result, real,
202 return LLVM::InsertValueOp::create(rewriter, loc, toTy, result, imag,
204 }
205
206 uint64_t getAtomicSizeInBytes(Type originalTy, Type convertedTy,
207 ModuleOp module) const {
208 std::optional<TypeSizeAndAlignment> sizeAndAlignment =
209 acc::getTypeSizeAndAlignment(originalTy, module, &accSupport);
210 if (!sizeAndAlignment)
211 sizeAndAlignment =
212 acc::getTypeSizeAndAlignment(convertedTy, module, &accSupport);
213 assert(sizeAndAlignment && "atomic type size is not computable");
214 return sizeAndAlignment->first.getFixedValue();
215 }
216
217 Type getAtomicType(Type originalTy, Type convertedTy, ModuleOp module) const {
218 if (convertedTy.isIntOrFloat())
219 return convertedTy;
220 return IntegerType::get(
221 convertedTy.getContext(),
222 getAtomicSizeInBytes(originalTy, convertedTy, module) * kBitsInByte);
223 }
224
225 Type getReferencedElementType(Value ref, ModuleOp module = nullptr) const {
226 auto ptr = dyn_cast<PointerLikeType>(ref.getType());
227 if (!ptr)
228 llvm_unreachable("unexpected type");
229 Type elementTy = ptr.getElementType();
230 Type convertedTy = this->getTypeConverter()->convertType(elementTy);
231 if (module)
232 return getAtomicType(elementTy, convertedTy, module);
233 return convertedTy;
234 }
235
236 /// Memrefs are converted to descriptors rather than bare pointers, so the
237 /// element pointer must be recomputed from the descriptor.
238 Value getAtomicPointer(Value originalRef, Value convertedPtr, Location loc,
239 ConversionPatternRewriter &rewriter) const {
240 auto memrefTy = dyn_cast<MemRefType>(originalRef.getType());
241 if (!memrefTy)
242 return convertedPtr;
243
244 // Extract aligned base pointer (index 1) and offset (index 2).
245 Value alignedPtr =
246 LLVM::ExtractValueOp::create(rewriter, loc, convertedPtr, 1);
247 Value offset = LLVM::ExtractValueOp::create(rewriter, loc, convertedPtr, 2);
248 Type elemPtrType = LLVM::LLVMPointerType::get(rewriter.getContext());
249 return LLVM::GEPOp::create(
250 rewriter, loc, elemPtrType,
251 this->getTypeConverter()->convertType(memrefTy.getElementType()),
252 alignedPtr, offset);
253 }
254
255 /// Convert `value`, read from `x` by `read`, to the type of `v`. `value`
256 /// has the type of `x` or the type of its atomic access, e.g. an integer
257 /// for a complex value. Returns a null value if a conversion is not
258 /// supported.
259 Value convertReadValue(AtomicReadOp read, Value value, Location loc,
260 ConversionPatternRewriter &rewriter) const {
261 Type xValueType = getReferencedElementType(read.getX());
262 Type vValueType = getReferencedElementType(read.getV());
263
264 if (xValueType == vValueType)
265 return value;
266
267 if (value.getType() != xValueType) {
268 // Only the real part of a complex `x` is needed for a non-complex `v`.
269 if (getComplexStructElementSizeInBits(xValueType) &&
270 !getComplexStructElementSizeInBits(vValueType))
271 value = deserializeRealPart(value, xValueType, rewriter);
272 else
273 value = deserializeExpr(value, xValueType, rewriter);
274 }
275
276 return genConvert(cast<PointerLikeType>(read.getV().getType()), value,
277 vValueType, loc, rewriter);
278 }
279
280 Block *constructCmpxchgLoop(Value ptr, Type type, Value expr,
281 ConversionPatternRewriter &rewriter) const;
282
283 /// Emit a single atomicrmw for a `x = x <binop> expr` capture, or fail so
284 /// the caller falls back to the cmpxchg loop.
285 LogicalResult
286 tryEmitCaptureAtomicRMW(AtomicCaptureOp capture, AtomicUpdateOp update,
287 AtomicReadOp read,
288 ConversionPatternRewriter &rewriter) const;
289
290 Value genUpdateCmpxchgLoop(AtomicUpdateOp update,
291 ConversionPatternRewriter &rewriter) const;
292};
293
294template <>
295LogicalResult ACCAtomicOpConversion<AtomicReadOp>::matchAndRewrite(
296 AtomicReadOp read, OpAdaptor adaptor,
297 ConversionPatternRewriter &rewriter) const {
298 Location loc = read.getLoc();
299 Value xRef = read.getX();
300 Value xPtr = getAtomicPointer(xRef, adaptor.getX(), loc, rewriter);
301 ModuleOp mod = read->getParentOfType<ModuleOp>();
302 Type xType = getReferencedElementType(xRef, mod);
303
304 auto ordering = LLVM::AtomicOrdering::monotonic;
305 Value storeVal;
306 if (xType.isSignlessInteger()) {
307 Value zero = LLVM::ConstantOp::create(rewriter, loc, xType, 0);
308 storeVal = LLVM::AtomicRMWOp::create(rewriter, loc, LLVM::AtomicBinOp::_or,
309 xPtr, zero, ordering);
310 } else {
311 unsigned bitWidth = xType.getIntOrFloatBitWidth();
312 Type intType = IntegerType::get(rewriter.getContext(), bitWidth);
313 Value zero = LLVM::ConstantOp::create(rewriter, loc, intType, 0);
314 Value intVal = LLVM::AtomicRMWOp::create(
315 rewriter, loc, LLVM::AtomicBinOp::_or, xPtr, zero, ordering);
316 storeVal = LLVM::BitcastOp::create(rewriter, loc, xType, intVal);
317 }
318
319 Value vRef = read.getV();
320 Value vPtr = getAtomicPointer(vRef, adaptor.getV(), loc, rewriter);
321
322 storeVal = convertReadValue(read, storeVal, loc, rewriter);
323
324 if (!storeVal) {
325 return rewriter.notifyMatchFailure(
326 read, "failed to convert the loaded value to the destination type");
327 }
328
329 auto storeOp = LLVM::StoreOp::create(rewriter, loc, storeVal, vPtr);
330 rewriter.replaceOp(read, storeOp);
331 return success();
332}
333
334template <>
335LogicalResult ACCAtomicOpConversion<AtomicWriteOp>::matchAndRewrite(
336 AtomicWriteOp write, OpAdaptor adaptor,
337 ConversionPatternRewriter &rewriter) const {
338 Location loc = write.getLoc();
339 Value expr = serializeExpr(adaptor.getExpr(), rewriter);
340 Value xRef = write.getX();
341 Value xPtr = getAtomicPointer(xRef, adaptor.getX(), loc, rewriter);
342 ModuleOp mod = write->getParentOfType<ModuleOp>();
343 Type xType = getReferencedElementType(xRef, mod);
344
345 auto ordering = LLVM::AtomicOrdering::monotonic;
346 if (!xType.isSignlessInteger()) {
347 unsigned bitWidth = xType.getIntOrFloatBitWidth();
348 Type intType = IntegerType::get(rewriter.getContext(), bitWidth);
349 expr = LLVM::BitcastOp::create(rewriter, loc, intType, expr);
350 }
351 LLVM::AtomicRMWOp::create(rewriter, loc, LLVM::AtomicBinOp::xchg, xPtr, expr,
352 ordering);
353 rewriter.eraseOp(write);
354 return success();
355}
356
357// Generate a cmpxchg loop based on the GenericAtomicRMWOpLowering algorithm.
358template <typename AtomicOpTy>
359Block *ACCAtomicOpConversion<AtomicOpTy>::constructCmpxchgLoop(
360 Value ptr, Type type, Value expr,
361 ConversionPatternRewriter &rewriter) const {
362 // Split the block into initial, loop, and ending parts.
363 Location loc = rewriter.getInsertionPoint()->getLoc();
364 Block *initBlock = rewriter.getInsertionBlock();
365 Block *loopBlock =
366 rewriter.splitBlock(initBlock, rewriter.getInsertionPoint());
367 loopBlock->addArgument(type, loc);
368 Block *endBlock =
369 rewriter.splitBlock(loopBlock, rewriter.getInsertionPoint());
370
371 // Compute the loaded value and branch to the loop block.
372 rewriter.setInsertionPointToEnd(initBlock);
373 Value init = LLVM::LoadOp::create(rewriter, loc, type, ptr);
374 LLVM::BrOp::create(rewriter, loc, init, loopBlock);
375
376 // Prepare the body of the loop block.
377 rewriter.setInsertionPointToStart(loopBlock);
378
379 Value loopArgument = loopBlock->getArgument(0);
380 Value result = serializeExpr(rewriter.getRemappedValue(expr), rewriter);
381 ModuleOp mod = initBlock->getParent()->getParentOfType<ModuleOp>();
382 Type convertedExprType =
383 this->getTypeConverter()->convertType(expr.getType());
384 Type exprType = getAtomicType(expr.getType(), convertedExprType, mod);
385
386 // Cast to an integer type.
387 if (!exprType.isSignlessInteger()) {
388 Type tmpType = IntegerType::get(
389 rewriter.getContext(),
390 getAtomicSizeInBytes(expr.getType(), convertedExprType, mod) *
392 result = LLVM::BitcastOp::create(rewriter, loc, tmpType, result);
393 loopArgument =
394 LLVM::BitcastOp::create(rewriter, loc, tmpType, loopArgument);
395 }
396
397 // Prepare the epilog of the loop block.
398 // Append the cmpxchg op to the end of the loop block.
399 auto successOrdering = LLVM::AtomicOrdering::acq_rel;
400 auto failureOrdering = LLVM::AtomicOrdering::monotonic;
401 auto cmpxchg =
402 LLVM::AtomicCmpXchgOp::create(rewriter, loc, ptr, loopArgument, result,
403 successOrdering, failureOrdering);
404 // Extract the %new_loaded and %ok values from the pair.
405 Value newLoaded = LLVM::ExtractValueOp::create(rewriter, loc, cmpxchg, 0);
406 Value ok = LLVM::ExtractValueOp::create(rewriter, loc, cmpxchg, 1);
407
408 // Cast back to the original type.
409 if (!exprType.isSignlessInteger())
410 newLoaded = LLVM::BitcastOp::create(rewriter, loc, exprType, newLoaded);
411
412 // Conditionally branch to the end or back to the loop depending on %ok.
413 LLVM::CondBrOp::create(rewriter, loc, ok, endBlock, ArrayRef<Value>(),
414 loopBlock, newLoaded);
415
416 return loopBlock;
417}
418
419static Value skipUnrealizedConversionOp(Value v) {
420 if (auto convOp =
421 dyn_cast_or_null<UnrealizedConversionCastOp>(v.getDefiningOp()))
422 return skipUnrealizedConversionOp(convOp.getOperand(0));
423 return v;
424}
425
426/// Obtain the foremost value of addr to indicate the origin of the storage.
427static Value getBaseStorage(Value addr, ConversionPatternRewriter &rewriter) {
428 Operation *op = skipUnrealizedConversionOp(addr).getDefiningOp();
429 if (auto gepOp = dyn_cast_or_null<LLVM::GEPOp>(op)) {
430 addr = gepOp.getBase();
431 op = addr.getDefiningOp();
432 }
433 if (auto extractOp = dyn_cast_or_null<LLVM::ExtractValueOp>(op)) {
434 // addr is in a struct. Get the inserted value corresponding to the
435 // extraction.
436 ArrayRef extractingPosition = extractOp.getPosition();
437 Value container = skipUnrealizedConversionOp(extractOp.getContainer());
438 Value remappedContainer = rewriter.getRemappedValue(container);
439 op = remappedContainer ? remappedContainer.getDefiningOp() : nullptr;
440 bool inserted = false;
441 while (auto insertValueOp = dyn_cast_or_null<LLVM::InsertValueOp>(op)) {
442 ArrayRef insertingPosition = insertValueOp.getPosition();
443 if (insertingPosition == extractingPosition) {
444 addr = insertValueOp.getValue();
445 inserted = true;
446 break;
447 }
448 op = insertValueOp.getContainer().getDefiningOp();
449 }
450 // The aggregate holding addr is not built by insertions, so the value it
451 // is converted from identifies the storage.
452 if (!inserted)
453 addr = container;
454 }
455 // op might be alloca already, or addr might be an argument.
456 return skipUnrealizedConversionOp(addr);
457}
458
459/// Include flow dependency (v -> expr) in the generated loop of
460/// `{ atomic.read, atomic.write/update }`.
461static void moveDependency(Value vRef, Value vPtr, Value expr,
462 Value loopArgument, Operation &loopHead,
463 ConversionPatternRewriter &rewriter,
464 const ACCAtomicLoadAddressCallback &getLoadAddress) {
465 Value vStorage = getBaseStorage(vPtr, rewriter);
466 // A dependency may be reached before it is itself converted, in which case
467 // its address is still expressed in terms of `vRef`.
468 Value vStorageRef = skipUnrealizedConversionOp(vRef);
469 LLVM_DEBUG({
470 llvm::dbgs() << "[acc-atomic] moveDependency\n";
471 llvm::dbgs() << " vPtr = " << vPtr << "\n";
472 llvm::dbgs() << " vStorage = " << vStorage << "\n";
473 llvm::dbgs() << " vStorageRef = " << vStorageRef << "\n";
474 llvm::dbgs() << " expr = " << expr << "\n";
475 });
476 llvm::DenseMap<Value, Value> remappedToOriginal;
477 std::set<std::pair<Operation *, std::set<Operation *>>> worklist;
478 std::set<Operation *> included;
479 Value mappedExpr = rewriter.getRemappedValue(expr);
480 remappedToOriginal[mappedExpr] = expr;
481 if (Operation *exprDef = mappedExpr.getDefiningOp())
482 worklist.insert(std::pair{exprDef, std::set<Operation *>{}});
483
484 while (!worklist.empty()) {
485 auto [dep, post] = worklist.extract(worklist.begin()).value();
486 if (!dep)
487 continue;
488 LLVM_DEBUG(llvm::dbgs() << " visit dep = " << *dep << "\n");
489 if (vPtr.getDefiningOp() &&
490 !vPtr.getDefiningOp()->getParentOp()->isAncestor(dep)) {
491 // Outside the parental region. No load found in this flow.
492 LLVM_DEBUG(llvm::dbgs() << " -> skipped: not in parental region\n");
493 continue;
494 }
495
496 Value addr;
497 if (auto load = dyn_cast<LLVM::LoadOp>(dep)) {
498 addr = load.getAddr();
499 } else if (auto load = dyn_cast<memref::LoadOp>(dep)) {
500 addr = load.getMemref();
501 } else if (getLoadAddress) {
502 addr = getLoadAddress(dep);
503 }
504 if (addr) {
505 Value baseStorage = getBaseStorage(addr, rewriter);
506 LLVM_DEBUG({
507 llvm::dbgs() << " addr = " << addr << "\n";
508 llvm::dbgs() << " baseStorage = " << baseStorage << "\n";
509 llvm::dbgs() << " remapped = "
510 << rewriter.getRemappedValue(baseStorage) << "\n";
511 llvm::dbgs() << " matchRef=" << (baseStorage == vStorageRef)
512 << " matchConv="
513 << (rewriter.getRemappedValue(baseStorage) == vStorage)
514 << "\n";
515 });
516 if (baseStorage == vStorageRef ||
517 rewriter.getRemappedValue(baseStorage) == vStorage) {
518 // Found the load of `v`. Include this flow in dependency.
519 Value load = dep->getResult(0);
520 auto replaceUses = [&](Operation *op) {
521 rewriter.modifyOpInPlace(op, [&] {
522 op->replaceUsesOfWith(remappedToOriginal[load], loopArgument);
523 });
524 };
525 for (Operation *p : post)
526 replaceUses(p);
527 replaceUses(&loopHead);
528 included.insert(post.begin(), post.end());
529 }
530 continue;
531 }
532 post.insert(dep);
533 for (Value operand : dep->getOperands()) {
534 Value mappedOperand = rewriter.getRemappedValue(operand);
535 if (auto *d = mappedOperand.getDefiningOp()) {
536 if (dep == d) {
537 if (auto *op = operand.getDefiningOp()) {
538 remappedToOriginal[op->getResult(0)] = operand;
539 worklist.insert(std::pair{op, post});
540 }
541 } else {
542 remappedToOriginal[mappedOperand] = operand;
543 worklist.insert(std::pair{d, post});
544 }
545 }
546 }
547 }
548
549 // Include dependency.
550 SmallVector<Operation *> includedInOrder;
551 vPtr.getParentRegion()->walk([&](Operation *op) {
552 if (included.find(op) != included.end())
553 includedInOrder.push_back(op);
554 });
555 for (Operation *d : includedInOrder)
556 d->moveBefore(&loopHead);
557}
558
559/// Generate a cmpxchg loop for update and return a stored value.
560template <typename AtomicOpTy>
561Value ACCAtomicOpConversion<AtomicOpTy>::genUpdateCmpxchgLoop(
562 AtomicUpdateOp update, ConversionPatternRewriter &rewriter) const {
563 Location loc = update.getLoc();
564 Value xRef = update.getX();
565 Value xPtr =
566 getAtomicPointer(xRef, rewriter.getRemappedValue(xRef), loc, rewriter);
567 ModuleOp mod = update->getParentOfType<ModuleOp>();
568 Type xType = getReferencedElementType(xRef, mod);
569 Type xTypeOrig = getReferencedElementType(xRef);
570
571 Block &updateBlock = update.getRegion().front();
572 Value updateArgument = updateBlock.getArgument(0);
573 Operation *terminator = updateBlock.getTerminator();
574 Value expr = terminator->getOperand(0);
575
576 Block *loopBlock = constructCmpxchgLoop(xPtr, xType, expr, rewriter);
577 Value loopArgument = loopBlock->getArgument(0);
578 Operation &loopHead = loopBlock->front();
579
580 rewriter.setInsertionPointToStart(loopBlock);
581 loopArgument = deserializeExpr(loopArgument, xTypeOrig, rewriter);
582
583 // Move in and out flow dependency (x -> expr). Some computation might be
584 // outside atomic regions.
585 moveDependency(xRef, xPtr, expr, loopArgument, loopHead, rewriter,
586 getLoadAddress);
587 // Move out the residue.
588 rewriter.replaceAllUsesWith(cast<BlockArgument>(updateArgument),
589 {loopArgument});
590
591 updateBlock.walk([&](Operation *op) {
593 rewriter.moveOpBefore(op, &loopHead);
594 });
595
596 if (auto cmpxchg = dyn_cast<LLVM::AtomicCmpXchgOp>(loopHead))
597 return cmpxchg.getVal();
598 if (auto bitcast = dyn_cast<LLVM::BitcastOp>(loopHead))
599 // Handling a non-integer type.
600 return bitcast.getArg();
601 if (auto extract = dyn_cast<LLVM::ExtractValueOp>(loopHead))
602 // Handling a complex type.
603 return extract.getContainer();
604 llvm_unreachable("invalid cmpxchg loop");
605}
606
607static std::optional<LLVM::AtomicBinOp> getAtomicBinOp(Operation *op,
608 bool updateIsLhs) {
610 .Case<arith::AddFOp>([](auto) { return LLVM::AtomicBinOp::fadd; })
611 .Case<arith::AddIOp>([](auto) { return LLVM::AtomicBinOp::add; })
612 .Case<arith::SubFOp>(
613 [updateIsLhs](auto) -> std::optional<LLVM::AtomicBinOp> {
614 // atomicrmw fsub is always `*ptr = *ptr - val`.
615 if (!updateIsLhs)
616 return std::nullopt;
617 return LLVM::AtomicBinOp::fsub;
618 })
619 .Case<arith::SubIOp>(
620 [updateIsLhs](auto) -> std::optional<LLVM::AtomicBinOp> {
621 // atomicrmw sub is always `*ptr = *ptr - val`.
622 if (!updateIsLhs)
623 return std::nullopt;
624 return LLVM::AtomicBinOp::sub;
625 })
626 .Case<arith::AndIOp>([](auto) { return LLVM::AtomicBinOp::_and; })
627 .Case<arith::OrIOp>([](auto) { return LLVM::AtomicBinOp::_or; })
628 .Case<arith::XOrIOp>([](auto) { return LLVM::AtomicBinOp::_xor; })
629 .Case<arith::MaxSIOp>([](auto) { return LLVM::AtomicBinOp::max; })
630 .Case<arith::MinSIOp>([](auto) { return LLVM::AtomicBinOp::min; })
631 .Case<arith::MaxUIOp>([](auto) { return LLVM::AtomicBinOp::umax; })
632 .Case<arith::MinUIOp>([](auto) { return LLVM::AtomicBinOp::umin; })
633 .Case<arith::MaximumFOp>([](auto) { return LLVM::AtomicBinOp::fmaximum; })
634 .Case<arith::MinimumFOp>([](auto) { return LLVM::AtomicBinOp::fminimum; })
635 .Case<arith::MaxNumFOp>(
636 [](auto) { return LLVM::AtomicBinOp::fmaximumnum; })
637 .Case<arith::MinNumFOp>(
638 [](auto) { return LLVM::AtomicBinOp::fminimumnum; })
639 .Default([](Operation *) { return std::nullopt; });
640}
641
642/// Match an update region computing `x = x <binop> expr`, and return the
643/// atomicrmw kind with the binary operation. Shared by the update and capture
644/// conversions so the same region cannot take atomicrmw in one and the cmpxchg
645/// loop in the other.
646static std::optional<std::pair<LLVM::AtomicBinOp, Operation *>>
647matchAtomicBinOpUpdate(AtomicUpdateOp update) {
648 Block &block = update.getRegion().front();
649 Value arg = block.getArgument(0);
650 Operation *yield = block.getTerminator();
651 if (!yield || yield->getNumOperands() != 1)
652 return std::nullopt;
653 Operation *binOp = yield->getOperand(0).getDefiningOp();
654 if (!binOp || binOp->getBlock() != &block || binOp->getNumOperands() != 2 ||
655 binOp->getNumResults() != 1)
656 return std::nullopt;
657 // The updated value has to feed the binop and nothing else.
658 if (!arg.hasOneUse() || arg.use_begin()->getOwner() != binOp)
659 return std::nullopt;
660 bool updateIsLhs = binOp->getOperand(0) == arg;
661 std::optional<LLVM::AtomicBinOp> kind = getAtomicBinOp(binOp, updateIsLhs);
662 if (!kind)
663 return std::nullopt;
664 return std::make_pair(*kind, binOp);
665}
666
667/// Generate llvm.atomicrmw or an llvm.cmpxchg loop.
668template <>
669LogicalResult ACCAtomicOpConversion<AtomicUpdateOp>::matchAndRewrite(
670 AtomicUpdateOp update, OpAdaptor adaptor,
671 ConversionPatternRewriter &rewriter) const {
672 Block &updateBlock = update.getRegion().front();
673 Value updateArgument = updateBlock.getArgument(0);
674
675 // Collect operations that depend on the update argument.
676 std::set<Operation *> dependents;
677 SmallVector<Value> worklist;
678 worklist.push_back(updateArgument);
679 while (!worklist.empty()) {
680 Value value = worklist.back();
681 worklist.pop_back();
682 for (OpOperand &use : value.getUses()) {
683 Operation *useOp = use.getOwner();
684 dependents.insert(useOp);
685 if (useOp->getNumResults() == 1)
686 worklist.push_back(useOp->getResult(0));
687 }
688 }
689
690 // Move independent operations out of the update block.
691 SmallVector<Operation *> independent;
692 for (Operation &op : updateBlock.getOperations()) {
693 if (dependents.find(&op) == dependents.end()) {
695 llvm_unreachable("invalid update operation");
696 independent.push_back(&op);
697 }
698 }
699 for (Operation *op : independent)
700 rewriter.moveOpBefore(op, update);
701
702 // Map arith op to atomicrmw kind.
703 //
704 // In the current version of LLVM, these are the equivalences for float
705 // min/max across the different instructions intrinsics and operations -
706 // confusingly they have slightly different and not very descriptive names.
707 //
708 // | MLIR | atomicrmw inst | llvm intrinsic |
709 // |------------+----------------+-------------------|
710 // | - | fmax | llvm.maxnum.* |
711 // | MaximumFOp | fmaximum | llvm.maximum.* |
712 // | MaxNumFOp | fmaximumnum | llvm.maximumnum.* |
713 //
714 // Sources:
715 // https://llvm.org/docs/LangRef.html#id236
716 // https://llvm.org/docs/LangRef.html#floating-point-min-max-intrinsics-comparison
717 // https://mlir.llvm.org/docs/Dialects/ArithOps/#arithmaximumf-arithmaximumfop
718 // https://mlir.llvm.org/docs/Dialects/ArithOps/#arithmaxnumf-arithmaxnumfop
719
720 // Select the kind and the val of atomicrmw.
721 std::optional<Value> val = std::nullopt;
722 std::optional<LLVM::AtomicBinOp> kind = std::nullopt;
723
724 if (auto matched = matchAtomicBinOpUpdate(update)) {
725 Operation *binOp = matched->second;
726 bool updateIsLhs = binOp->getOperand(0) == updateArgument;
727 kind = matched->first;
728 val = binOp->getOperand(updateIsLhs ? 1 : 0);
729 }
730
731 // Per-component atomicrmw info for complex type decomposition.
732 // Decomposed complex ops (complex.re/im + arith binop + complex.create)
733 // produce per-component binary ops that each need a separate atomicrmw.
734 struct ComponentAtomic {
735 LLVM::AtomicBinOp kind;
736 Value val;
737 int32_t fieldIdx;
738 };
739 SmallVector<ComponentAtomic, 2> componentAtomics;
740
741 if (!val || !kind) {
742 Type convertedArgTy =
743 this->getTypeConverter()->convertType(updateArgument.getType());
744 if (auto structTy = dyn_cast<LLVM::LLVMStructType>(convertedArgTy)) {
745 if (structTy.getBody().size() == 2 &&
746 structTy.getBody()[0] == structTy.getBody()[1] &&
747 structTy.getBody()[0].isIntOrFloat() &&
748 structTy.getBody()[0].getIntOrFloatBitWidth() > 32) {
749 for (Operation &op : updateBlock.getOperations()) {
750 if (op.hasTrait<OpTrait::IsTerminator>() || op.getNumOperands() < 2)
751 continue;
752 int32_t fieldIdx = -1;
753 Value externalVal = nullptr;
754 bool updateIsLhs = false;
755 for (unsigned i = 0; i < 2; ++i) {
756 Value operand = op.getOperand(i);
757 if (auto reOp = operand.getDefiningOp<complex::ReOp>()) {
758 if (reOp.getOperand() == updateArgument) {
759 fieldIdx = 0;
760 externalVal = op.getOperand(1 - i);
761 updateIsLhs = i == 0;
762 }
763 } else if (auto imOp = operand.getDefiningOp<complex::ImOp>()) {
764 if (imOp.getOperand() == updateArgument) {
765 fieldIdx = 1;
766 externalVal = op.getOperand(1 - i);
767 updateIsLhs = i == 0;
768 }
769 }
770 }
771 if (fieldIdx < 0)
772 continue;
773 auto componentKind = getAtomicBinOp(&op, updateIsLhs);
774 if (!componentKind)
775 continue;
776 componentAtomics.push_back({*componentKind, externalVal, fieldIdx});
777 }
778 }
779 }
780 }
781
782 Location loc = update.getLoc();
783 Value xPtr = getAtomicPointer(update.getX(), adaptor.getX(), loc, rewriter);
784
785 // Require distinct real/imag lanes; duplicate fieldIdx values must fall back
786 // to cmpxchg rather than emitting two atomicrmw ops on the same component.
787 bool hasDistinctComplexLanes = false;
788 if (componentAtomics.size() == 2) {
789 unsigned lanes = 0;
790 for (const ComponentAtomic &ca : componentAtomics) {
791 if (ca.fieldIdx == 0 || ca.fieldIdx == 1)
792 lanes |= 1u << ca.fieldIdx;
793 }
794 hasDistinctComplexLanes = lanes == 0b11;
795 }
796
797 if (val && kind) {
798 auto ordering = LLVM::AtomicOrdering::monotonic;
799 Value operand = rewriter.getRemappedValue(*val);
800 // There is no atomic on i1, but it occupies a byte, and and/or/xor keep a
801 // 0/1 byte 0/1, so apply them to the byte.
802 if (operand.getType().isInteger(1) &&
803 llvm::is_contained({LLVM::AtomicBinOp::_and, LLVM::AtomicBinOp::_or,
804 LLVM::AtomicBinOp::_xor},
805 *kind))
806 operand =
807 LLVM::ZExtOp::create(rewriter, loc, rewriter.getI8Type(), operand);
808 LLVM::AtomicRMWOp::create(rewriter, loc, *kind, xPtr, operand, ordering);
809 } else if (hasDistinctComplexLanes) {
810 auto structTy = cast<LLVM::LLVMStructType>(
811 this->getTypeConverter()->convertType(updateArgument.getType()));
812 Type ptrType = LLVM::LLVMPointerType::get(rewriter.getContext());
813 auto ordering = LLVM::AtomicOrdering::monotonic;
814 for (ComponentAtomic &ca : componentAtomics) {
815 Value elemPtr =
816 LLVM::GEPOp::create(rewriter, loc, ptrType, structTy, xPtr,
817 ArrayRef<LLVM::GEPArg>{0, ca.fieldIdx});
818 LLVM::AtomicRMWOp::create(rewriter, loc, ca.kind, elemPtr,
819 rewriter.getRemappedValue(ca.val), ordering);
820 }
821 } else {
822 // Fallback to the llvm.cmpxchg loop generation.
823 genUpdateCmpxchgLoop(update, rewriter);
824 }
825 rewriter.eraseOp(update);
826 return success();
827}
828
829/// The cmpxchg loop re-points reads of `v`/`x` inside `expr` at the atomically
830/// loaded value (see moveDependency). An atomicrmw cannot do that, so any
831/// `expr` that loads from memory keeps the loop: the load may be the captured
832/// value itself, and the address is not reliably comparable here.
833static bool exprReadsMemory(Value expr) {
834 SmallVector<Value> worklist{expr};
836 while (!worklist.empty()) {
837 Operation *def = worklist.pop_back_val().getDefiningOp();
838 if (!def || !seen.insert(def).second)
839 continue;
840 if (!isMemoryEffectFree(def))
841 return true;
842 worklist.append(def->getOperands().begin(), def->getOperands().end());
843 }
844 return false;
845}
846
847/// Emit a single atomicrmw for a `x = x <binop> expr` capture.
848template <typename AtomicOpTy>
849LogicalResult ACCAtomicOpConversion<AtomicOpTy>::tryEmitCaptureAtomicRMW(
850 AtomicCaptureOp capture, AtomicUpdateOp update, AtomicReadOp read,
851 ConversionPatternRewriter &rewriter) const {
852 if (read.getX() != update.getX())
853 return failure();
854 auto matched = matchAtomicBinOpUpdate(update);
855 if (!matched)
856 return failure();
857 auto [kind, binOp] = *matched;
858
859 Value arg = update.getRegion().front().getArgument(0);
860 bool updateIsLhs = binOp->getOperand(0) == arg;
861 Value expr = binOp->getOperand(updateIsLhs ? 1 : 0);
862
863 // Keep serialized and aggregate types on the cmpxchg path.
864 Type argTy = arg.getType();
865 if (!argTy.isIntOrFloat() ||
866 this->getTypeConverter()->convertType(argTy) != argTy)
867 return failure();
868 // The operand must already be available, and must not be the captured value.
869 Operation *exprDef = expr.getDefiningOp();
870 if (exprDef && exprDef->getBlock() == &update.getRegion().front())
871 return failure();
872 if (exprReadsMemory(expr))
873 return failure();
874
875 Location loc = capture.getLoc();
876 Value xRef = update.getX();
877 Value vRef = read.getV();
878 Value xPtr =
879 getAtomicPointer(xRef, rewriter.getRemappedValue(xRef), loc, rewriter);
880 Value vPtr =
881 getAtomicPointer(vRef, rewriter.getRemappedValue(vRef), loc, rewriter);
882
883 rewriter.setInsertionPoint(capture);
884 auto rmw = LLVM::AtomicRMWOp::create(rewriter, loc, kind, xPtr,
885 rewriter.getRemappedValue(expr),
886 LLVM::AtomicOrdering::monotonic);
887 // atomicrmw yields the old value; `{update, read}` captures the new one.
888 Value captured = rmw.getRes();
889 if (capture.getFirstOp() == update.getOperation()) {
890 rewriter.moveOpAfter(binOp, rmw);
891 binOp->replaceUsesOfWith(arg, captured);
892 captured = binOp->getResult(0);
893 }
894
895 captured = convertReadValue(read, captured, loc, rewriter);
896 assert(captured && "failed to convert the captured value to the type of `v`");
897
898 rewriter.replaceOpWithNewOp<LLVM::StoreOp>(capture, captured, vPtr);
899 return success();
900}
901
902/// Generate an llvm.cmpxchg loop.
903template <>
904LogicalResult ACCAtomicOpConversion<AtomicCaptureOp>::matchAndRewrite(
905 AtomicCaptureOp capture, OpAdaptor /*adaptor*/,
906 ConversionPatternRewriter &rewriter) const {
907 Operation *firstOp = capture.getFirstOp();
908 Operation *secondOp = capture.getSecondOp();
909 Value vPtr = nullptr;
910 Value storeVal = nullptr;
911
912 // A single `x = x <binop> expr` capture becomes one atomicrmw. The cmpxchg
913 // loop below serializes retries and collapses under contention.
914 if (AtomicUpdateOp update = capture.getAtomicUpdateOp())
915 if (AtomicReadOp read = capture.getAtomicReadOp())
916 if (succeeded(tryEmitCaptureAtomicRMW(capture, update, read, rewriter)))
917 return success();
918
919 if (auto firstReadStmt = dyn_cast<AtomicReadOp>(firstOp)) {
920 Location loc = capture.getLoc();
921 Value xRef = firstReadStmt.getX();
922 Value xPtr =
923 getAtomicPointer(xRef, rewriter.getRemappedValue(xRef), loc, rewriter);
924 ModuleOp mod = capture->getParentOfType<ModuleOp>();
925 Type xType = getReferencedElementType(xRef, mod);
926 Type xTypeOrig = getReferencedElementType(xRef);
927 Value vRef = firstReadStmt.getV();
928 vPtr =
929 getAtomicPointer(vRef, rewriter.getRemappedValue(vRef), loc, rewriter);
930
931 Value expr = nullptr;
932 if (auto secondWriteStmt = dyn_cast<AtomicWriteOp>(secondOp)) {
933 // 1. `{ atomic.read, atomic.write }` pattern
934 expr = secondWriteStmt.getExpr();
935 } else if (auto secondUpdateStmt = dyn_cast<AtomicUpdateOp>(secondOp)) {
936 // 2. `{ atomic.read, atomic.update }` pattern
937 Block &updateBlock = secondUpdateStmt.getRegion().front();
938 Operation *terminator = updateBlock.getTerminator();
939 expr = terminator->getOperand(0);
940 }
941
942 Block *loopBlock = constructCmpxchgLoop(xPtr, xType, expr, rewriter);
943 Value loopArgument = loopBlock->getArgument(0);
944 Operation &loopHead = loopBlock->front();
945 auto condBr = cast<LLVM::CondBrOp>(loopBlock->back());
946 storeVal = condBr.getFalseDestOperands()[0];
947
948 rewriter.setInsertionPointToStart(loopBlock);
949 loopArgument = deserializeExpr(loopArgument, xTypeOrig, rewriter);
950
951 // Include flow dependency (v -> expr).
952 if (auto secondUpdateStmt = dyn_cast<AtomicUpdateOp>(secondOp)) {
953 Block &updateBlock = secondUpdateStmt.getRegion().front();
954 Value updateArgument = updateBlock.getArgument(0);
955 updateArgument.replaceAllUsesWith(loopArgument);
956 updateBlock.walk([&](Operation *op) {
958 rewriter.moveOpBefore(op, &loopHead);
959 });
960 }
961 moveDependency(vRef, vPtr, expr, loopArgument, loopHead, rewriter,
962 getLoadAddress);
963 } else if (auto firstUpdateStmt = dyn_cast<AtomicUpdateOp>(firstOp)) {
964 if (auto secondReadStmt = dyn_cast<AtomicReadOp>(secondOp)) {
965 // 3. `{ atomic.update, atomic.read }` pattern
966 storeVal = genUpdateCmpxchgLoop(firstUpdateStmt, rewriter);
967
968 Value vRef = secondReadStmt.getV();
969 vPtr = getAtomicPointer(vRef, rewriter.getRemappedValue(vRef),
970 capture.getLoc(), rewriter);
971 }
972 }
973 // Generate `v = x`.
974 rewriter.setInsertionPoint(capture);
975 storeVal = convertReadValue(capture.getAtomicReadOp(), storeVal,
976 capture.getLoc(), rewriter);
977 assert(storeVal && "failed to convert the captured value to the type of `v`");
978
979 rewriter.replaceOpWithNewOp<LLVM::StoreOp>(capture, storeVal, vPtr);
980 return success();
981}
982
983} // namespace
984
985namespace mlir {
986
988 target.addIllegalOp<AtomicReadOp, AtomicWriteOp, AtomicUpdateOp,
989 AtomicCaptureOp>();
990}
991
993 RewritePatternSet &patterns,
994 acc::OpenACCSupport &accSupport,
995 ACCAtomicLoadAddressCallback getLoadAddress) {
996 patterns.add<ACCAtomicOpConversion<AtomicReadOp>,
997 ACCAtomicOpConversion<AtomicWriteOp>,
998 ACCAtomicOpConversion<AtomicUpdateOp>,
999 ACCAtomicOpConversion<AtomicCaptureOp>>(converter, accSupport,
1000 getLoadAddress);
1001}
1002
1003} // namespace mlir
return success()
return MutableOperandRange * this
constexpr static const uint64_t kBitsInByte
Definition LLVMTypes.cpp:30
auto load
*if copies could not be generated due to yet unimplemented cases *copyInPlacementStart and copyOutPlacementStart in copyPlacementBlock *specify the insertion points where the incoming copies and outgoing should be inserted(the insertion happens right before the *insertion point). Since `begin` can itself be invalidated due to the memref *rewriting done from this method
Block represents an ordered list of Operations.
Definition Block.h:34
BlockArgument getArgument(unsigned i)
Definition Block.h:154
Region * getParent() const
Provide a 'getParent' method for ilist_node_with_parent methods.
Definition Block.cpp:27
OpListType & getOperations()
Definition Block.h:162
Operation & front()
Definition Block.h:178
Operation & back()
Definition Block.h:177
RetT walk(FnT &&callback)
Walk all nested operations, blocks (including this block) or regions, depending on the type of callba...
Definition Block.h:318
Operation * getTerminator()
Get the terminator operation of this block.
Definition Block.cpp:249
BlockArgument addArgument(Type type, Location loc)
Add one value to the argument list.
Definition Block.cpp:158
Utility class for operation conversions targeting the LLVM dialect that match exactly one source oper...
Definition Pattern.h:233
typename SourceOp::Adaptor OpAdaptor
Definition Pattern.h:235
Conversion from types to the LLVM IR dialect.
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
This class represents an operand of an operation.
Definition Value.h:256
This class provides the API for ops that are known to be terminators.
Operation is the basic unit of execution within MLIR.
Definition Operation.h:87
Value getOperand(unsigned idx)
Definition Operation.h:377
bool hasTrait()
Returns true if the operation was registered with a particular trait, e.g.
Definition Operation.h:803
Block * getBlock()
Returns the operation block that contains this operation.
Definition Operation.h:230
OpResult getResult(unsigned idx)
Get the 'idx'th result of this operation.
Definition Operation.h:434
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
operand_range getOperands()
Returns an iterator on the underlying Value's.
Definition Operation.h:405
bool isAncestor(Operation *other)
Return true if this operation is an ancestor of the other operation.
Definition Operation.h:288
unsigned getNumResults()
Return the number of results held by this operation.
Definition Operation.h:431
ParentT getParentOfType()
Find the first parent operation of the given type, or nullptr if there is no ancestor operation.
Definition Region.h:206
RetT walk(FnT &&callback)
Walk all nested operations, blocks or regions (including this region), depending on the type of callb...
Definition Region.h:297
RewritePatternSet & add(ConstructorArg &&arg, ConstructorArgs &&...args)
Add an instance of each of the pattern types 'Ts' to the pattern list with the given arguments.
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
Definition Types.h:74
MLIRContext * getContext() const
Return the MLIRContext in which this type was uniqued.
Definition Types.cpp:35
bool isSignlessInteger() const
Return true if this is a signless integer type (with the specified width).
Definition Types.cpp:66
bool isInteger() const
Return true if this is an integer type (with the specified width).
Definition Types.cpp:58
bool isIntOrFloat() const
Return true if this is an integer (of any signedness) or a float type.
Definition Types.cpp:118
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
use_range getUses() const
Returns a range of all uses, which is useful for iterating over all uses.
Definition Value.h:188
void replaceAllUsesWith(Value newValue)
Replace all uses of 'this' value with the new value, updating anything in the IR that uses 'this' to ...
Definition Value.h:149
bool hasOneUse() const
Returns true if this value has exactly one use.
Definition Value.h:197
Location getLoc() const
Return the location of this value.
Definition Value.cpp:24
Operation * getDefiningOp() const
If this value is the result of an operation, return the operation that defines it.
Definition Value.cpp:18
Region * getParentRegion()
Return the Region in which this Value is defined.
Definition Value.cpp:39
use_iterator use_begin() const
Definition Value.h:184
std::optional< TypeSizeAndAlignment > getTypeSizeAndAlignment(Type ty, ModuleOp module, const DataLayout &dl, OpenACCSupport *support=nullptr, Value var={})
Returns the size and ABI alignment in bytes.
Include the generated interface declarations.
void populateACCAtomicPatterns(const LLVMTypeConverter &converter, RewritePatternSet &patterns, acc::OpenACCSupport &accSupport, ACCAtomicLoadAddressCallback getLoadAddress={})
Populate patterns that lower OpenACC atomic operations to LLVM dialect.
constexpr T real(const NonFloatComplex< T > &x)
Definition Complex.h:255
bool isMemoryEffectFree(Operation *op)
Returns true if the given operation is free of memory effects.
llvm::TypeSwitch< T, ResultT > TypeSwitch
Definition LLVM.h:147
constexpr T imag(const NonFloatComplex< T > &x)
Definition Complex.h:260
std::function< Value(Operation *)> ACCAtomicLoadAddressCallback
Returns the address operand of a dialect-specific load operation.
Definition ACCToLLVM.h:53
void configureACCAtomicConversionLegality(ConversionTarget &target)
Configure conversion legality for OpenACC atomic operations.