31#include "llvm/ADT/TypeSwitch.h"
32#include "llvm/Support/Debug.h"
39#define DEBUG_TYPE "acc-atomic-patterns"
48template <
typename AtomicOpTy>
57 accSupport(accSupport), getLoadAddress(getLoadAddress) {}
60 matchAndRewrite(AtomicOpTy op, OpAdaptor adaptor,
61 ConversionPatternRewriter &rewriter)
const override;
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())
73 size_t elementSizeInBits = structType.getBody()[0].getIntOrFloatBitWidth();
74 if (elementSizeInBits == 0 || elementSizeInBits > 64)
75 llvm_unreachable(
"unexpected complex type");
76 return elementSizeInBits;
80 Value serializeExpr(
Value expr, ConversionPatternRewriter &rewriter)
const {
81 size_t elementSizeInBits =
82 getComplexStructElementSizeInBits(expr.
getType());
83 if (!elementSizeInBits)
87 Value firstValue = LLVM::ExtractValueOp::create(rewriter, loc, expr, 0);
88 Value secondValue = LLVM::ExtractValueOp::create(rewriter, loc, expr, 1);
90 Type intCastTy = IntegerType::get(context, elementSizeInBits);
91 Type intTy = IntegerType::get(context, elementSizeInBits * 2);
92 firstValue = LLVM::BitcastOp::create(rewriter, loc, intCastTy, firstValue);
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);
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);
106 ConversionPatternRewriter &rewriter)
const {
107 size_t elementSizeInBits = getComplexStructElementSizeInBits(origTy);
108 assert(elementSizeInBits &&
"expected a complex type");
110 IntegerType::get(rewriter.getContext(), elementSizeInBits * 2) &&
111 "expected an integer of the size of the complex type");
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];
118 if (origElemTy != elemTy)
119 real = LLVM::BitcastOp::create(rewriter, loc, origElemTy,
real);
126 ConversionPatternRewriter &rewriter)
const {
127 size_t elementSizeInBits = getComplexStructElementSizeInBits(origTy);
128 if (!elementSizeInBits)
131 auto intTy = dyn_cast<IntegerType>(expr.
getType());
132 if (!intTy || intTy.getWidth() != elementSizeInBits * 2)
137 Type elemTy = IntegerType::get(context, elementSizeInBits);
138 Value low = LLVM::TruncOp::create(rewriter, loc, elemTy, expr);
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);
148 Value undefStruct = LLVM::UndefOp::create(rewriter, loc, origTy);
149 Value structWithLow = LLVM::InsertValueOp::create(
151 return LLVM::InsertValueOp::create(rewriter, loc, origTy, structWithLow,
161 Location loc, ConversionPatternRewriter &rewriter)
const {
167 bool fromComplex = getComplexStructElementSizeInBits(fromTy) != 0;
168 bool toComplex = getComplexStructElementSizeInBits(toTy) != 0;
170 if (!fromComplex && !toComplex)
171 return ptrType.genCast(rewriter, loc, value, toTy);
176 real = LLVM::ExtractValueOp::create(rewriter, loc, value, 0);
179 return genConvert(ptrType,
real, toTy, loc, rewriter);
181 Type toElemTy = cast<LLVM::LLVMStructType>(toTy).getBody()[0];
182 real = genConvert(ptrType,
real, toElemTy, loc, rewriter);
190 imag = LLVM::ExtractValueOp::create(rewriter, loc, value, 1);
191 imag = genConvert(ptrType,
imag, toElemTy, loc, rewriter);
196 imag = LLVM::ZeroOp::create(rewriter, loc, toElemTy);
199 Value result = LLVM::UndefOp::create(rewriter, loc, toTy);
202 return LLVM::InsertValueOp::create(rewriter, loc, toTy,
result,
imag,
206 uint64_t getAtomicSizeInBytes(
Type originalTy,
Type convertedTy,
207 ModuleOp module)
const {
208 std::optional<TypeSizeAndAlignment> sizeAndAlignment =
210 if (!sizeAndAlignment)
213 assert(sizeAndAlignment &&
"atomic type size is not computable");
214 return sizeAndAlignment->first.getFixedValue();
217 Type getAtomicType(
Type originalTy,
Type convertedTy, ModuleOp module)
const {
220 return IntegerType::get(
222 getAtomicSizeInBytes(originalTy, convertedTy, module) *
kBitsInByte);
225 Type getReferencedElementType(
Value ref, ModuleOp module =
nullptr)
const {
226 auto ptr = dyn_cast<PointerLikeType>(ref.
getType());
228 llvm_unreachable(
"unexpected type");
229 Type elementTy =
ptr.getElementType();
230 Type convertedTy = this->getTypeConverter()->convertType(elementTy);
232 return getAtomicType(elementTy, convertedTy, module);
239 ConversionPatternRewriter &rewriter)
const {
240 auto memrefTy = dyn_cast<MemRefType>(originalRef.
getType());
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()),
260 ConversionPatternRewriter &rewriter)
const {
261 Type xValueType = getReferencedElementType(read.getX());
262 Type vValueType = getReferencedElementType(read.getV());
264 if (xValueType == vValueType)
267 if (value.
getType() != xValueType) {
269 if (getComplexStructElementSizeInBits(xValueType) &&
270 !getComplexStructElementSizeInBits(vValueType))
271 value = deserializeRealPart(value, xValueType, rewriter);
273 value = deserializeExpr(value, xValueType, rewriter);
276 return genConvert(cast<PointerLikeType>(read.getV().getType()), value,
277 vValueType, loc, rewriter);
281 ConversionPatternRewriter &rewriter)
const;
286 tryEmitCaptureAtomicRMW(AtomicCaptureOp capture, AtomicUpdateOp update,
288 ConversionPatternRewriter &rewriter)
const;
290 Value genUpdateCmpxchgLoop(AtomicUpdateOp update,
291 ConversionPatternRewriter &rewriter)
const;
295LogicalResult ACCAtomicOpConversion<AtomicReadOp>::matchAndRewrite(
296 AtomicReadOp read, OpAdaptor adaptor,
297 ConversionPatternRewriter &rewriter)
const {
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);
304 auto ordering = LLVM::AtomicOrdering::monotonic;
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);
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);
319 Value vRef = read.getV();
320 Value vPtr = getAtomicPointer(vRef, adaptor.getV(), loc, rewriter);
322 storeVal = convertReadValue(read, storeVal, loc, rewriter);
325 return rewriter.notifyMatchFailure(
326 read,
"failed to convert the loaded value to the destination type");
329 auto storeOp = LLVM::StoreOp::create(rewriter, loc, storeVal, vPtr);
330 rewriter.replaceOp(read, storeOp);
335LogicalResult ACCAtomicOpConversion<AtomicWriteOp>::matchAndRewrite(
336 AtomicWriteOp write, OpAdaptor adaptor,
337 ConversionPatternRewriter &rewriter)
const {
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);
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);
351 LLVM::AtomicRMWOp::create(rewriter, loc, LLVM::AtomicBinOp::xchg, xPtr, expr,
353 rewriter.eraseOp(write);
358template <
typename AtomicOpTy>
359Block *ACCAtomicOpConversion<AtomicOpTy>::constructCmpxchgLoop(
361 ConversionPatternRewriter &rewriter)
const {
363 Location loc = rewriter.getInsertionPoint()->getLoc();
364 Block *initBlock = rewriter.getInsertionBlock();
366 rewriter.splitBlock(initBlock, rewriter.getInsertionPoint());
369 rewriter.splitBlock(loopBlock, rewriter.getInsertionPoint());
372 rewriter.setInsertionPointToEnd(initBlock);
373 Value init = LLVM::LoadOp::create(rewriter, loc, type,
ptr);
374 LLVM::BrOp::create(rewriter, loc, init, loopBlock);
377 rewriter.setInsertionPointToStart(loopBlock);
380 Value result = serializeExpr(rewriter.getRemappedValue(expr), rewriter);
382 Type convertedExprType =
383 this->getTypeConverter()->convertType(expr.
getType());
384 Type exprType = getAtomicType(expr.
getType(), convertedExprType, mod);
388 Type tmpType = IntegerType::get(
389 rewriter.getContext(),
390 getAtomicSizeInBytes(expr.
getType(), convertedExprType, mod) *
392 result = LLVM::BitcastOp::create(rewriter, loc, tmpType,
result);
394 LLVM::BitcastOp::create(rewriter, loc, tmpType, loopArgument);
399 auto successOrdering = LLVM::AtomicOrdering::acq_rel;
400 auto failureOrdering = LLVM::AtomicOrdering::monotonic;
402 LLVM::AtomicCmpXchgOp::create(rewriter, loc,
ptr, loopArgument,
result,
403 successOrdering, failureOrdering);
405 Value newLoaded = LLVM::ExtractValueOp::create(rewriter, loc, cmpxchg, 0);
406 Value ok = LLVM::ExtractValueOp::create(rewriter, loc, cmpxchg, 1);
410 newLoaded = LLVM::BitcastOp::create(rewriter, loc, exprType, newLoaded);
414 loopBlock, newLoaded);
419static Value skipUnrealizedConversionOp(
Value v) {
421 dyn_cast_or_null<UnrealizedConversionCastOp>(v.
getDefiningOp()))
422 return skipUnrealizedConversionOp(convOp.getOperand(0));
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();
433 if (
auto extractOp = dyn_cast_or_null<LLVM::ExtractValueOp>(op)) {
436 ArrayRef extractingPosition = extractOp.getPosition();
437 Value container = skipUnrealizedConversionOp(extractOp.getContainer());
438 Value remappedContainer = rewriter.getRemappedValue(container);
439 op = remappedContainer ? remappedContainer.
getDefiningOp() :
nullptr;
441 while (
auto insertValueOp = dyn_cast_or_null<LLVM::InsertValueOp>(op)) {
442 ArrayRef insertingPosition = insertValueOp.getPosition();
443 if (insertingPosition == extractingPosition) {
444 addr = insertValueOp.getValue();
448 op = insertValueOp.getContainer().getDefiningOp();
456 return skipUnrealizedConversionOp(addr);
463 ConversionPatternRewriter &rewriter,
465 Value vStorage = getBaseStorage(vPtr, rewriter);
468 Value vStorageRef = skipUnrealizedConversionOp(vRef);
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";
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;
482 worklist.insert(std::pair{exprDef, std::set<Operation *>{}});
484 while (!worklist.empty()) {
485 auto [dep, post] = worklist.extract(worklist.begin()).value();
488 LLVM_DEBUG(llvm::dbgs() <<
" visit dep = " << *dep <<
"\n");
492 LLVM_DEBUG(llvm::dbgs() <<
" -> skipped: not in parental region\n");
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);
505 Value baseStorage = getBaseStorage(addr, rewriter);
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)
513 << (rewriter.getRemappedValue(baseStorage) == vStorage)
516 if (baseStorage == vStorageRef ||
517 rewriter.getRemappedValue(baseStorage) == vStorage) {
521 rewriter.modifyOpInPlace(op, [&] {
522 op->replaceUsesOfWith(remappedToOriginal[
load], loopArgument);
527 replaceUses(&loopHead);
528 included.insert(post.begin(), post.end());
533 for (
Value operand : dep->getOperands()) {
534 Value mappedOperand = rewriter.getRemappedValue(operand);
537 if (
auto *op = operand.getDefiningOp()) {
538 remappedToOriginal[op->getResult(0)] = operand;
539 worklist.insert(std::pair{op, post});
542 remappedToOriginal[mappedOperand] = operand;
543 worklist.insert(std::pair{d, post});
552 if (included.find(op) != included.end())
553 includedInOrder.push_back(op);
556 d->moveBefore(&loopHead);
560template <
typename AtomicOpTy>
561Value ACCAtomicOpConversion<AtomicOpTy>::genUpdateCmpxchgLoop(
562 AtomicUpdateOp update, ConversionPatternRewriter &rewriter)
const {
564 Value xRef = update.getX();
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);
571 Block &updateBlock = update.getRegion().
front();
576 Block *loopBlock = constructCmpxchgLoop(xPtr, xType, expr, rewriter);
580 rewriter.setInsertionPointToStart(loopBlock);
581 loopArgument = deserializeExpr(loopArgument, xTypeOrig, rewriter);
585 moveDependency(xRef, xPtr, expr, loopArgument, loopHead, rewriter,
588 rewriter.replaceAllUsesWith(cast<BlockArgument>(updateArgument),
593 rewriter.moveOpBefore(op, &loopHead);
596 if (
auto cmpxchg = dyn_cast<LLVM::AtomicCmpXchgOp>(loopHead))
597 return cmpxchg.getVal();
598 if (
auto bitcast = dyn_cast<LLVM::BitcastOp>(loopHead))
600 return bitcast.getArg();
601 if (
auto extract = dyn_cast<LLVM::ExtractValueOp>(loopHead))
603 return extract.getContainer();
604 llvm_unreachable(
"invalid cmpxchg loop");
607static std::optional<LLVM::AtomicBinOp> getAtomicBinOp(
Operation *op,
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> {
617 return LLVM::AtomicBinOp::fsub;
619 .Case<arith::SubIOp>(
620 [updateIsLhs](
auto) -> std::optional<LLVM::AtomicBinOp> {
624 return LLVM::AtomicBinOp::sub;
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; });
646static std::optional<std::pair<LLVM::AtomicBinOp, Operation *>>
647matchAtomicBinOpUpdate(AtomicUpdateOp update) {
660 bool updateIsLhs = binOp->
getOperand(0) == arg;
661 std::optional<LLVM::AtomicBinOp> kind = getAtomicBinOp(binOp, updateIsLhs);
664 return std::make_pair(*kind, binOp);
669LogicalResult ACCAtomicOpConversion<AtomicUpdateOp>::matchAndRewrite(
670 AtomicUpdateOp update, OpAdaptor adaptor,
671 ConversionPatternRewriter &rewriter)
const {
672 Block &updateBlock = update.getRegion().
front();
676 std::set<Operation *> dependents;
678 worklist.push_back(updateArgument);
679 while (!worklist.empty()) {
680 Value value = worklist.back();
684 dependents.insert(useOp);
693 if (dependents.find(&op) == dependents.end()) {
695 llvm_unreachable(
"invalid update operation");
696 independent.push_back(&op);
700 rewriter.moveOpBefore(op, update);
721 std::optional<Value> val = std::nullopt;
722 std::optional<LLVM::AtomicBinOp> kind = std::nullopt;
724 if (
auto matched = matchAtomicBinOpUpdate(update)) {
726 bool updateIsLhs = binOp->
getOperand(0) == updateArgument;
727 kind = matched->first;
734 struct ComponentAtomic {
735 LLVM::AtomicBinOp 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) {
752 int32_t fieldIdx = -1;
753 Value externalVal =
nullptr;
754 bool updateIsLhs =
false;
755 for (
unsigned i = 0; i < 2; ++i) {
758 if (reOp.getOperand() == updateArgument) {
761 updateIsLhs = i == 0;
763 }
else if (
auto imOp = operand.
getDefiningOp<complex::ImOp>()) {
764 if (imOp.getOperand() == updateArgument) {
767 updateIsLhs = i == 0;
773 auto componentKind = getAtomicBinOp(&op, updateIsLhs);
776 componentAtomics.push_back({*componentKind, externalVal, fieldIdx});
783 Value xPtr = getAtomicPointer(update.getX(), adaptor.getX(), loc, rewriter);
787 bool hasDistinctComplexLanes =
false;
788 if (componentAtomics.size() == 2) {
790 for (
const ComponentAtomic &ca : componentAtomics) {
791 if (ca.fieldIdx == 0 || ca.fieldIdx == 1)
792 lanes |= 1u << ca.fieldIdx;
794 hasDistinctComplexLanes = lanes == 0b11;
798 auto ordering = LLVM::AtomicOrdering::monotonic;
799 Value operand = rewriter.getRemappedValue(*val);
803 llvm::is_contained({LLVM::AtomicBinOp::_and, LLVM::AtomicBinOp::_or,
804 LLVM::AtomicBinOp::_xor},
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) {
816 LLVM::GEPOp::create(rewriter, loc, ptrType, structTy, xPtr,
818 LLVM::AtomicRMWOp::create(rewriter, loc, ca.kind, elemPtr,
819 rewriter.getRemappedValue(ca.val), ordering);
823 genUpdateCmpxchgLoop(update, rewriter);
825 rewriter.eraseOp(update);
833static bool exprReadsMemory(
Value expr) {
836 while (!worklist.empty()) {
837 Operation *def = worklist.pop_back_val().getDefiningOp();
838 if (!def || !seen.insert(def).second)
848template <
typename AtomicOpTy>
849LogicalResult ACCAtomicOpConversion<AtomicOpTy>::tryEmitCaptureAtomicRMW(
850 AtomicCaptureOp capture, AtomicUpdateOp update, AtomicReadOp read,
851 ConversionPatternRewriter &rewriter)
const {
852 if (read.getX() != update.getX())
854 auto matched = matchAtomicBinOpUpdate(update);
857 auto [kind, binOp] = *matched;
859 Value arg = update.getRegion().front().getArgument(0);
860 bool updateIsLhs = binOp->getOperand(0) == arg;
861 Value expr = binOp->getOperand(updateIsLhs ? 1 : 0);
866 this->getTypeConverter()->convertType(argTy) != argTy)
870 if (exprDef && exprDef->
getBlock() == &update.getRegion().
front())
872 if (exprReadsMemory(expr))
876 Value xRef = update.getX();
877 Value vRef = read.getV();
879 getAtomicPointer(xRef, rewriter.getRemappedValue(xRef), loc, rewriter);
881 getAtomicPointer(vRef, rewriter.getRemappedValue(vRef), loc, rewriter);
883 rewriter.setInsertionPoint(capture);
884 auto rmw = LLVM::AtomicRMWOp::create(rewriter, loc, kind, xPtr,
885 rewriter.getRemappedValue(expr),
886 LLVM::AtomicOrdering::monotonic);
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);
895 captured = convertReadValue(read, captured, loc, rewriter);
896 assert(captured &&
"failed to convert the captured value to the type of `v`");
898 rewriter.replaceOpWithNewOp<LLVM::StoreOp>(capture, captured, vPtr);
904LogicalResult ACCAtomicOpConversion<AtomicCaptureOp>::matchAndRewrite(
905 AtomicCaptureOp capture, OpAdaptor ,
906 ConversionPatternRewriter &rewriter)
const {
907 Operation *firstOp = capture.getFirstOp();
908 Operation *secondOp = capture.getSecondOp();
909 Value vPtr =
nullptr;
910 Value storeVal =
nullptr;
914 if (AtomicUpdateOp update = capture.getAtomicUpdateOp())
915 if (AtomicReadOp read = capture.getAtomicReadOp())
916 if (succeeded(tryEmitCaptureAtomicRMW(capture, update, read, rewriter)))
919 if (
auto firstReadStmt = dyn_cast<AtomicReadOp>(firstOp)) {
921 Value xRef = firstReadStmt.getX();
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();
929 getAtomicPointer(vRef, rewriter.getRemappedValue(vRef), loc, rewriter);
931 Value expr =
nullptr;
932 if (
auto secondWriteStmt = dyn_cast<AtomicWriteOp>(secondOp)) {
934 expr = secondWriteStmt.getExpr();
935 }
else if (
auto secondUpdateStmt = dyn_cast<AtomicUpdateOp>(secondOp)) {
937 Block &updateBlock = secondUpdateStmt.getRegion().
front();
942 Block *loopBlock = constructCmpxchgLoop(xPtr, xType, expr, rewriter);
945 auto condBr = cast<LLVM::CondBrOp>(loopBlock->
back());
946 storeVal = condBr.getFalseDestOperands()[0];
948 rewriter.setInsertionPointToStart(loopBlock);
949 loopArgument = deserializeExpr(loopArgument, xTypeOrig, rewriter);
952 if (
auto secondUpdateStmt = dyn_cast<AtomicUpdateOp>(secondOp)) {
953 Block &updateBlock = secondUpdateStmt.getRegion().
front();
958 rewriter.moveOpBefore(op, &loopHead);
961 moveDependency(vRef, vPtr, expr, loopArgument, loopHead, rewriter,
963 }
else if (
auto firstUpdateStmt = dyn_cast<AtomicUpdateOp>(firstOp)) {
964 if (
auto secondReadStmt = dyn_cast<AtomicReadOp>(secondOp)) {
966 storeVal = genUpdateCmpxchgLoop(firstUpdateStmt, rewriter);
968 Value vRef = secondReadStmt.getV();
969 vPtr = getAtomicPointer(vRef, rewriter.getRemappedValue(vRef),
970 capture.getLoc(), rewriter);
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`");
979 rewriter.replaceOpWithNewOp<LLVM::StoreOp>(capture, storeVal, vPtr);
988 target.addIllegalOp<AtomicReadOp, AtomicWriteOp, AtomicUpdateOp,
996 patterns.
add<ACCAtomicOpConversion<AtomicReadOp>,
997 ACCAtomicOpConversion<AtomicWriteOp>,
998 ACCAtomicOpConversion<AtomicUpdateOp>,
999 ACCAtomicOpConversion<AtomicCaptureOp>>(converter, accSupport,
return MutableOperandRange * this
constexpr static const uint64_t kBitsInByte
*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.
BlockArgument getArgument(unsigned i)
Region * getParent() const
Provide a 'getParent' method for ilist_node_with_parent methods.
OpListType & getOperations()
RetT walk(FnT &&callback)
Walk all nested operations, blocks (including this block) or regions, depending on the type of callba...
Operation * getTerminator()
Get the terminator operation of this block.
BlockArgument addArgument(Type type, Location loc)
Add one value to the argument list.
Utility class for operation conversions targeting the LLVM dialect that match exactly one source oper...
typename SourceOp::Adaptor OpAdaptor
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...
MLIRContext is the top-level object for a collection of MLIR operations.
This class represents an operand of an operation.
This class provides the API for ops that are known to be terminators.
Operation is the basic unit of execution within MLIR.
Value getOperand(unsigned idx)
bool hasTrait()
Returns true if the operation was registered with a particular trait, e.g.
Block * getBlock()
Returns the operation block that contains this operation.
OpResult getResult(unsigned idx)
Get the 'idx'th result of this operation.
Operation * getParentOp()
Returns the closest surrounding operation that contains this operation or nullptr if this is a top-le...
unsigned getNumOperands()
operand_range getOperands()
Returns an iterator on the underlying Value's.
bool isAncestor(Operation *other)
Return true if this operation is an ancestor of the other operation.
unsigned getNumResults()
Return the number of results held by this operation.
ParentT getParentOfType()
Find the first parent operation of the given type, or nullptr if there is no ancestor operation.
RetT walk(FnT &&callback)
Walk all nested operations, blocks or regions (including this region), depending on the type of callb...
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...
MLIRContext * getContext() const
Return the MLIRContext in which this type was uniqued.
bool isSignlessInteger() const
Return true if this is a signless integer type (with the specified width).
bool isInteger() const
Return true if this is an integer type (with the specified width).
bool isIntOrFloat() const
Return true if this is an integer (of any signedness) or a float type.
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Type getType() const
Return the type of this value.
use_range getUses() const
Returns a range of all uses, which is useful for iterating over all uses.
void replaceAllUsesWith(Value newValue)
Replace all uses of 'this' value with the new value, updating anything in the IR that uses 'this' to ...
bool hasOneUse() const
Returns true if this value has exactly one use.
Location getLoc() const
Return the location of this value.
Operation * getDefiningOp() const
If this value is the result of an operation, return the operation that defines it.
Region * getParentRegion()
Return the Region in which this Value is defined.
use_iterator use_begin() const
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)
bool isMemoryEffectFree(Operation *op)
Returns true if the given operation is free of memory effects.
llvm::TypeSwitch< T, ResultT > TypeSwitch
constexpr T imag(const NonFloatComplex< T > &x)
std::function< Value(Operation *)> ACCAtomicLoadAddressCallback
Returns the address operand of a dialect-specific load operation.
void configureACCAtomicConversionLegality(ConversionTarget &target)
Configure conversion legality for OpenACC atomic operations.