17#include "mlir/Dialect/LLVMIR/LLVMArithOps.h"
18#include "mlir/Dialect/LLVMIR/LLVMCallOps.h"
19#include "mlir/Dialect/LLVMIR/LLVMConstantOps.h"
20#include "mlir/Dialect/LLVMIR/LLVMConversionOps.h"
21#include "mlir/Dialect/LLVMIR/LLVMMemoryIntrinsicOps.h"
22#include "mlir/Dialect/LLVMIR/LLVMMemoryOps.h"
23#include "mlir/Dialect/LLVMIR/LLVMModuleOps.h"
24#include "mlir/Dialect/LLVMIR/LLVMTerminatorOps.h"
25#include "mlir/IR/BuiltinOps.h"
26#include "mlir/IR/Matchers.h"
28#include "llvm/ADT/SmallPtrSet.h"
29#include "llvm/ADT/SparseBitVector.h"
30#include "llvm/Support/MathExtras.h"
31#include "llvm/TargetParser/Triple.h"
32#include "llvm/Transforms/Utils/AMDGPUEmitPrintf.h"
47std::optional<llvm::APInt>
48foldConstantInt(mlir::Value value,
49 llvm::SmallPtrSetImpl<mlir::Operation *> &seen) {
50 mlir::Operation *def = value.getDefiningOp();
51 if (!def || !seen.insert(def).second)
54 if (mlir::matchPattern(value, mlir::m_Constant(&intAttr)))
55 return intAttr.getValue();
56 auto cast = mlir::dyn_cast<cir::CastOp>(def);
57 if (!cast ||
cast.getKind() != cir::CastKind::integral)
59 auto srcTy = mlir::dyn_cast<cir::IntType>(
cast.getSrc().getType());
60 auto dstTy = mlir::dyn_cast<cir::IntType>(
cast.getType());
61 if (!srcTy || !dstTy || dstTy.getWidth() < srcTy.getWidth() ||
62 dstTy.getWidth() > 64)
66 llvm::SmallVector<mlir::OpFoldResult, 1> folded;
67 if (succeeded(
cast->fold(folded)) && folded.size() == 1)
68 if (
auto attr = mlir::dyn_cast<mlir::Attribute>(folded[0]))
69 if (
auto foldedInt = mlir::dyn_cast<cir::IntAttr>(attr))
70 return foldedInt.getValue();
71 std::optional<llvm::APInt> foldedSrc = foldConstantInt(
cast.getSrc(), seen);
74 return srcTy.isUnsigned() ? foldedSrc->zextOrTrunc(dstTy.getWidth())
75 : foldedSrc->sextOrTrunc(dstTy.getWidth());
78std::optional<int64_t> getConstantInt(mlir::Value value) {
80 if (
auto intTy = mlir::dyn_cast<cir::IntType>(value.getType()))
82 llvm::SmallPtrSet<mlir::Operation *, 4> seen;
83 std::optional<llvm::APInt> result = foldConstantInt(value, seen);
84 if (!result || result->getBitWidth() > 64)
89 : result->getSignificantBits() > 64)
91 return isUnsigned ? result->getZExtValue() : result->getSExtValue();
94bool isByteType(mlir::Type ty) {
95 if (
auto intTy = mlir::dyn_cast<cir::IntType>(ty))
96 return intTy.getWidth() == 8;
97 return ty.isInteger(8);
100std::optional<int64_t> scaledOffset(
int64_t index, mlir::Type elemTy,
101 const mlir::DataLayout &dataLayout) {
102 llvm::TypeSize size = dataLayout.getTypeAllocSize(elemTy);
103 if (size.isScalable() || size.getFixedValue() >= (1ULL << 63))
106 if (llvm::MulOverflow(index,
static_cast<int64_t>(size.getFixedValue()),
112bool getConstantStringInfo(mlir::Value ptr, mlir::ModuleOp mod,
113 const mlir::DataLayout &dataLayout,
114 mlir::SymbolTableCollection &symbolTables,
117 llvm::SmallPtrSet<mlir::Operation *, 8> seen;
118 while (mlir::Operation *def = ptr.getDefiningOp()) {
119 if (!seen.insert(def).second)
121 if (
auto cast = mlir::dyn_cast<cir::CastOp>(def)) {
122 if (
cast.getKind() != cir::CastKind::array_to_ptrdecay &&
123 cast.getKind() != cir::CastKind::bitcast &&
124 cast.getKind() != cir::CastKind::address_space)
127 }
else if (
auto stride = mlir::dyn_cast<cir::PtrStrideOp>(def)) {
128 mlir::Type elemTy = stride.getElementType();
131 if (mlir::isa<cir::VoidType, cir::FuncType>(elemTy))
132 elemTy = cir::IntType::get(elemTy.getContext(), 8,
false);
133 std::optional<int64_t> index = getConstantInt(stride.getStride());
134 std::optional<int64_t>
step =
135 index ? scaledOffset(*index, elemTy, dataLayout) : std::nullopt;
136 if (!
step || llvm::AddOverflow(offset, *
step, offset))
138 ptr = stride.getBase();
139 }
else if (
auto elt = mlir::dyn_cast<cir::GetElementOp>(def)) {
141 mlir::isa<cir::ArrayType>(elt.getBaseType().getPointee());
142 std::optional<int64_t> index = getConstantInt(elt.getIndex());
143 std::optional<int64_t>
step =
145 ? scaledOffset(*index, elt.getElementType(), dataLayout)
147 if (!
step || llvm::AddOverflow(offset, *
step, offset))
155 auto getGlobal = ptr.getDefiningOp<cir::GetGlobalOp>();
158 mlir::Operation *symbol =
159 symbolTables.lookupSymbolIn(mod, getGlobal.getNameAttr());
160 auto global = mlir::dyn_cast_if_present<cir::GlobalOp>(symbol);
165 std::optional<mlir::Attribute> init = global.getInitialValue();
166 auto arrayTy = mlir::dyn_cast<cir::ArrayType>(global.getSymType());
167 if (!global.getConstant() || !init || !arrayTy ||
168 !isByteType(arrayTy.getElementType()))
170 if (
auto constArr = mlir::dyn_cast<cir::ConstArrayAttr>(*init)) {
171 if (
auto strAttr = mlir::dyn_cast<mlir::StringAttr>(constArr.getElts())) {
172 data = strAttr.getValue().str();
173 }
else if (
auto arrayAttr =
174 mlir::dyn_cast<mlir::ArrayAttr>(constArr.getElts())) {
178 data.reserve(std::max<size_t>(arrayAttr.size(), arrayTy.getSize()));
179 for (mlir::Attribute elt : arrayAttr) {
181 if (
auto intAttr = mlir::dyn_cast<cir::IntAttr>(elt)) {
182 if (!isByteType(intAttr.getType()))
184 byte = intAttr.getValue();
185 }
else if (
auto intAttr = mlir::dyn_cast<mlir::IntegerAttr>(elt)) {
186 if (!isByteType(intAttr.getType()))
188 byte = intAttr.getValue();
192 data.push_back(
static_cast<char>(
byte.getZExtValue()));
197 }
else if (!mlir::isa<cir::ZeroAttr>(*init)) {
201 data.resize(arrayTy.getSize(),
'\0');
203 if (offset < 0 ||
static_cast<uint64_t>(offset) > data.size())
205 llvm::StringRef rest = llvm::StringRef(data).drop_front(offset);
206 str = rest.substr(0, rest.find(
'\0')).str();
213 mlir::Value realSize;
214 mlir::Value alignedSize;
218class AMDGPUPrintfLowering {
220 AMDGPUPrintfLowering(cir::OffloadPrintfOp op,
221 mlir::ConversionPatternRewriter &rewriter,
222 const mlir::DataLayout &dataLayout,
223 mlir::SymbolTableCollection &symbolTables,
224 unsigned genericAddrSpace)
225 : op(op), rewriter(rewriter), dataLayout(dataLayout),
226 symbolTables(symbolTables), mod(op->getParentOfType<mlir::ModuleOp>()),
227 genericAddrSpace(genericAddrSpace) {
228 if (
auto attr = op->getAttrOfType<mlir::ArrayAttr>(
229 cir::CIRDialect::getPrintfConstStringsAttrName()))
230 if (
attr.size() == op.getArgs().size() + 1)
234 mlir::LogicalResult lower(mlir::ValueRange args,
bool isBuffered);
237 std::optional<std::string> getConstString(
size_t operandIndex)
const {
238 if (!constStrings || operandIndex >= constStrings.size())
240 auto strAttr = mlir::dyn_cast<mlir::StringAttr>(constStrings[operandIndex]);
243 return strAttr.getValue().str();
245 mlir::Value getI32(
uint32_t value) {
246 return mlir::LLVM::ConstantOp::create(
247 rewriter, op.getLoc(), rewriter.getI32Type(), llvm::APInt(32, value));
249 mlir::Value getI64(
uint64_t value) {
250 return mlir::LLVM::ConstantOp::create(
251 rewriter, op.getLoc(), rewriter.getI64Type(), llvm::APInt(64, value));
253 mlir::Value createCall(llvm::StringRef name, mlir::Type resTy,
254 mlir::ValueRange args);
255 mlir::Value gepInBounds(mlir::Value ptr, mlir::LLVM::GEPArg offset);
256 void addPrintfFormatMetadata(llvm::StringRef entry,
bool onlyIfEmpty);
258 mlir::Value fitArgInto64Bits(mlir::Value arg);
259 mlir::Value callPrintfBegin(mlir::Value version);
260 mlir::Value callAppendArgs(mlir::Value desc,
int numArgs, mlir::Value arg0,
261 mlir::Value arg1, mlir::Value arg2,
262 mlir::Value arg3, mlir::Value arg4,
263 mlir::Value arg5, mlir::Value arg6,
bool isLast);
264 mlir::Value appendArg(mlir::Value desc, mlir::Value arg,
bool isLast);
265 mlir::Value getStrlenWithNull(mlir::Value str);
266 mlir::Value callAppendStringN(mlir::Value desc, mlir::Value str,
267 mlir::Value
length,
bool isLast);
268 mlir::Value appendString(mlir::Value desc, mlir::Value arg,
bool isLast);
269 mlir::Value processArg(mlir::Value desc, mlir::Value arg,
bool specIsCString,
271 bool isCStringArg(mlir::ValueRange args,
size_t i)
const;
272 mlir::Value callBufferedPrintfStart(
273 mlir::ValueRange args, mlir::Value fmt,
bool isConstFmtStr,
274 llvm::SmallVectorImpl<StringData> &stringContents, mlir::Value &argSize);
276 processConstantStringArg(
const StringData &sd,
277 llvm::SmallVectorImpl<mlir::Value> &whatToStore);
278 mlir::Value processNonStringArg(mlir::Value arg);
279 void callBufferedPrintfArgPush(mlir::ValueRange args, mlir::Value ptrToStore,
280 llvm::ArrayRef<StringData> stringContents,
282 mlir::Value emitAMDGPUPrintfCall(mlir::ValueRange args,
bool isBuffered);
284 cir::OffloadPrintfOp op;
285 mlir::ConversionPatternRewriter &rewriter;
286 const mlir::DataLayout &dataLayout;
287 mlir::SymbolTableCollection &symbolTables;
289 unsigned genericAddrSpace;
290 mlir::ArrayAttr constStrings;
293 mlir::Block *cont =
nullptr;
295 llvm::SparseBitVector<8> specIsCString;
301 llvm::StringRef tripleStr;
302 if (
auto tripleAttr = module->getAttrOfType<mlir::StringAttr>(
303 cir::CIRDialect::getTripleAttrName()))
304 tripleStr = tripleAttr.getValue();
305 llvm::Triple triple(tripleStr);
306 return triple.isAMDGCN() ||
307 (triple.isSPIRV() && triple.getVendor() == llvm::Triple::AMD);
311 mlir::SymbolTableCollection &symbolTables) {
312 mlir::MLIRContext *ctx = mod.getContext();
313 mod.walk([&](cir::OffloadPrintfOp op) {
314 mlir::ModuleOp opModule = op->getParentOfType<mlir::ModuleOp>();
317 mlir::DataLayout opLayout(opModule);
318 auto resolve = [&](mlir::Value value) -> mlir::Attribute {
320 if (getConstantStringInfo(value, opModule, opLayout, symbolTables, str))
321 return mlir::StringAttr::get(ctx, str);
322 return mlir::UnitAttr::get(ctx);
325 entries.reserve(op.getArgs().size() + 1);
326 entries.push_back(resolve(op.getFormat()));
327 for (mlir::Value arg : op.getArgs())
328 entries.push_back(resolve(arg));
329 op->setAttr(cir::CIRDialect::getPrintfConstStringsAttrName(),
330 mlir::ArrayAttr::get(ctx, entries));
334mlir::Value AMDGPUPrintfLowering::createCall(llvm::StringRef name,
336 mlir::ValueRange args) {
337 auto fnTy = mlir::LLVM::LLVMFunctionType::get(
338 resTy, llvm::to_vector(args.getTypes()),
false);
339 createLLVMFuncOpIfNotExist(rewriter, symbolTables, op, name, fnTy);
340 return mlir::LLVM::CallOp::create(
341 rewriter, op.getLoc(), fnTy,
342 mlir::FlatSymbolRefAttr::get(rewriter.getContext(), name), args)
346mlir::Value AMDGPUPrintfLowering::gepInBounds(mlir::Value ptr,
347 mlir::LLVM::GEPArg offset) {
348 return mlir::LLVM::GEPOp::create(rewriter, op.getLoc(), ptr.getType(),
349 rewriter.getI8Type(), ptr,
351 mlir::LLVM::GEPNoWrapFlags::inbounds);
354void AMDGPUPrintfLowering::addPrintfFormatMetadata(llvm::StringRef entry,
356 constexpr llvm::StringLiteral
name =
"llvm.printf.fmts";
357 mlir::Attribute
node = mlir::LLVM::MDNodeAttr::get(
358 rewriter.getContext(),
359 {mlir::LLVM::MDStringAttr::get(
360 rewriter.getContext(),
361 mlir::StringAttr::get(rewriter.getContext(), entry))});
363 mlir::LLVM::NamedMetadataOp metaD;
364 for (
auto md : mod.getOps<mlir::LLVM::NamedMetadataOp>()) {
365 if (md.getMetadataName() == name) {
372 mlir::OpBuilder::InsertionGuard guard(rewriter);
373 rewriter.setInsertionPointToEnd(mod.getBody());
374 mlir::LLVM::NamedMetadataOp::create(rewriter, mod.getLoc(), name,
375 rewriter.getArrayAttr(node));
379 if (onlyIfEmpty && !metaD.getNodes().empty())
381 llvm::SmallVector<mlir::Attribute> nodes(metaD.getNodes().getValue());
382 nodes.push_back(node);
383 rewriter.modifyOpInPlace(
384 metaD, [&] { metaD.setNodesAttr(rewriter.getArrayAttr(nodes)); });
387mlir::Value AMDGPUPrintfLowering::fitArgInto64Bits(mlir::Value arg) {
388 mlir::Type int64Ty = rewriter.getI64Type();
389 mlir::Type ty =
arg.getType();
391 if (
auto intTy = mlir::dyn_cast<mlir::IntegerType>(ty)) {
392 switch (intTy.getWidth()) {
394 return mlir::LLVM::ZExtOp::create(rewriter, op.getLoc(), int64Ty, arg);
401 return mlir::LLVM::BitcastOp::create(rewriter, op.getLoc(), int64Ty, arg);
404 if (mlir::isa<mlir::LLVM::LLVMPointerType>(ty)) {
405 return mlir::LLVM::PtrToIntOp::create(rewriter, op.getLoc(), int64Ty, arg);
408 llvm_unreachable(
"unexpected type");
411mlir::Value AMDGPUPrintfLowering::callPrintfBegin(mlir::Value version) {
412 return createCall(
"__ockl_printf_begin", rewriter.getI64Type(), version);
415mlir::Value AMDGPUPrintfLowering::callAppendArgs(
416 mlir::Value desc,
int numArgs, mlir::Value arg0, mlir::Value arg1,
417 mlir::Value arg2, mlir::Value arg3, mlir::Value arg4, mlir::Value arg5,
418 mlir::Value arg6,
bool isLast) {
419 mlir::Value isLastValue = getI32(isLast);
420 mlir::Value numArgsValue = getI32(numArgs);
421 return createCall(
"__ockl_printf_append_args", rewriter.getI64Type(),
422 {desc, numArgsValue, arg0, arg1, arg2, arg3, arg4, arg5,
426mlir::Value AMDGPUPrintfLowering::appendArg(mlir::Value desc, mlir::Value arg,
428 mlir::Value arg0 = fitArgInto64Bits(arg);
429 mlir::Value zero = getI64(0);
430 return callAppendArgs(desc, 1, arg0, zero, zero, zero, zero, zero, zero,
436mlir::Value AMDGPUPrintfLowering::getStrlenWithNull(mlir::Value str) {
437 mlir::Block *prev = rewriter.getInsertionBlock();
438 mlir::Region *region = cont->getParent();
440 mlir::Value charZero = mlir::LLVM::ConstantOp::create(
441 rewriter, op.getLoc(), rewriter.getI8Type(), llvm::APInt(8, 0));
442 mlir::Value one = getI64(1);
443 mlir::Value zero = getI64(0);
444 mlir::Type int64Ty = rewriter.getI64Type();
452 mlir::Block *
join = rewriter.createBlock(region, cont->getIterator(),
453 {int64Ty}, {op.getLoc()});
454 mlir::Block *whileBlock = rewriter.createBlock(
455 region,
join->getIterator(), {str.getType()}, {op.getLoc()});
456 mlir::Block *whileDone = rewriter.createBlock(region,
join->getIterator());
459 rewriter.setInsertionPointToEnd(prev);
460 mlir::Value cmpNull = mlir::LLVM::ICmpOp::create(
461 rewriter, op.getLoc(), mlir::LLVM::ICmpPredicate::eq, str,
462 mlir::LLVM::ZeroOp::create(rewriter, op.getLoc(), str.getType()));
463 mlir::LLVM::CondBrOp::create(rewriter, op.getLoc(), cmpNull, join, zero,
467 rewriter.setInsertionPointToEnd(whileBlock);
469 mlir::Value ptrPhi = whileBlock->getArgument(0);
470 mlir::Value ptrNext = mlir::LLVM::GEPOp::create(
471 rewriter, op.getLoc(), str.getType(), rewriter.getI8Type(), ptrPhi,
472 llvm::ArrayRef<mlir::LLVM::GEPArg>{one});
475 mlir::Value data = mlir::LLVM::LoadOp::create(rewriter, op.getLoc(),
476 rewriter.getI8Type(), ptrPhi);
477 mlir::Value cmp = mlir::LLVM::ICmpOp::create(
478 rewriter, op.getLoc(), mlir::LLVM::ICmpPredicate::eq, data, charZero);
479 mlir::LLVM::CondBrOp::create(rewriter, op.getLoc(), cmp, whileDone,
480 mlir::ValueRange(), whileBlock, ptrNext);
483 rewriter.setInsertionPointToEnd(whileDone);
484 auto addrTy = mlir::IntegerType::get(
485 rewriter.getContext(), *dataLayout.getTypeIndexBitwidth(str.getType()));
486 mlir::Value endAddr =
487 mlir::LLVM::PtrToAddrOp::create(rewriter, op.getLoc(), addrTy, ptrPhi);
488 mlir::Value beginAddr =
489 mlir::LLVM::PtrToAddrOp::create(rewriter, op.getLoc(), addrTy, str);
491 mlir::LLVM::SubOp::create(rewriter, op.getLoc(), endAddr, beginAddr);
492 if (addrTy != int64Ty)
493 len = mlir::LLVM::ZExtOp::create(rewriter, op.getLoc(), int64Ty, len);
494 len = mlir::LLVM::AddOp::create(rewriter, op.getLoc(), len, one);
497 mlir::LLVM::BrOp::create(rewriter, op.getLoc(), len, join);
498 rewriter.setInsertionPointToEnd(join);
499 return join->getArgument(0);
502mlir::Value AMDGPUPrintfLowering::callAppendStringN(mlir::Value desc,
506 mlir::Value isLastInt32 = getI32(isLast);
510 mlir::LLVM::LLVMPointerType::get(rewriter.getContext(), genericAddrSpace);
511 if (str.getType() != ptrTy)
513 mlir::LLVM::AddrSpaceCastOp::create(rewriter, op.getLoc(), ptrTy, str);
514 return createCall(
"__ockl_printf_append_string_n", rewriter.getI64Type(),
515 {desc, str, length, isLastInt32});
518mlir::Value AMDGPUPrintfLowering::appendString(mlir::Value desc,
519 mlir::Value arg,
bool isLast) {
520 mlir::Value
length = getStrlenWithNull(arg);
521 return callAppendStringN(desc, arg,
length, isLast);
524mlir::Value AMDGPUPrintfLowering::processArg(mlir::Value desc, mlir::Value arg,
525 bool specIsCString,
bool isLast) {
526 if (specIsCString && mlir::isa<mlir::LLVM::LLVMPointerType>(
arg.getType())) {
527 return appendString(desc, arg, isLast);
532 return appendArg(desc, arg, isLast);
536bool AMDGPUPrintfLowering::isCStringArg(mlir::ValueRange args,
size_t i)
const {
537 return specIsCString.test(i) &&
538 mlir::isa<mlir::LLVM::LLVMPointerType>(args[i].
getType());
544mlir::Value AMDGPUPrintfLowering::callBufferedPrintfStart(
545 mlir::ValueRange args, mlir::Value fmt,
bool isConstFmtStr,
546 llvm::SmallVectorImpl<StringData> &stringContents, mlir::Value &argSize) {
547 mlir::Value nonConstStrLen;
548 mlir::Value lenWithNull;
549 mlir::Value lenWithNullAligned;
558 lenWithNull = getStrlenWithNull(fmt);
561 tempAdd = mlir::LLVM::AddOp::create(rewriter, op.getLoc(), lenWithNull,
564 mlir::LLVM::AndOp::create(rewriter, op.getLoc(), tempAdd, getI64(~7U));
566 stringContents.push_back({
"", lenWithNull, nonConstStrLen,
false});
569 for (
size_t i = 1; i < args.size(); i++) {
570 if (isCStringArg(args, i)) {
571 if (std::optional<std::string> argStr = getConstString(i)) {
572 auto alignedLen = llvm::alignTo(argStr->size() + 1, 8);
573 stringContents.push_back({*argStr, {},
575 bufSize += alignedLen;
577 lenWithNull = getStrlenWithNull(args[i]);
580 tempAdd = mlir::LLVM::AddOp::create(rewriter, op.getLoc(), lenWithNull,
582 lenWithNullAligned = mlir::LLVM::AndOp::create(rewriter, op.getLoc(),
583 tempAdd, getI64(~7U));
585 if (nonConstStrLen) {
586 mlir::Value val = mlir::LLVM::AddOp::create(
587 rewriter, op.getLoc(), lenWithNullAligned, nonConstStrLen);
588 nonConstStrLen = val;
590 nonConstStrLen = lenWithNullAligned;
592 stringContents.push_back({
"", lenWithNull, lenWithNullAligned,
false});
596 dataLayout.getTypeAllocSize(args[i].
getType()).getFixedValue();
599 bufSize += llvm::alignTo(allocSize, 8);
604 mlir::Value sizeToReserve = getI64(bufSize);
606 sizeToReserve = mlir::LLVM::AddOp::create(rewriter, op.getLoc(),
607 nonConstStrLen, sizeToReserve);
609 argSize = mlir::LLVM::TruncOp::create(rewriter, op.getLoc(),
610 rewriter.getI32Type(), sizeToReserve);
613 unsigned globalAS = 0;
614 if (
auto as = mlir::dyn_cast_if_present<mlir::IntegerAttr>(
615 dataLayout.getGlobalMemorySpace()))
616 globalAS = as.getValue().getZExtValue();
618 mlir::LLVM::LLVMPointerType::get(rewriter.getContext(), globalAS);
620 mlir::StringAttr::get(rewriter.getContext(),
"__printf_alloc");
621 bool declared = symbolTables.lookupSymbolIn(mod, allocName);
622 mlir::Value ptr = createCall(allocName, ptrTy, argSize);
624 mlir::cast<mlir::LLVM::LLVMFuncOp>(
625 symbolTables.lookupSymbolIn(mod, allocName))
631void AMDGPUPrintfLowering::processConstantStringArg(
632 const StringData &sd, llvm::SmallVectorImpl<mlir::Value> &whatToStore) {
633 llvm::SmallVector<uint32_t, 16> words;
634 llvm::packAMDGPUPrintfConstantString(sd.str, words);
636 whatToStore.push_back(getI32(word));
639mlir::Value AMDGPUPrintfLowering::processNonStringArg(mlir::Value arg) {
640 mlir::Type ty =
arg.getType();
642 if (
auto intTy = mlir::dyn_cast<mlir::IntegerType>(ty)) {
643 if (intTy.getWidth() < 64) {
644 return mlir::LLVM::ZExtOp::create(rewriter, op.getLoc(),
645 rewriter.getI64Type(), arg);
649 if (mlir::isa<mlir::FloatType>(ty)) {
650 if (dataLayout.getTypeAllocSize(ty).getFixedValue() < 8) {
651 return mlir::LLVM::FPExtOp::create(rewriter, op.getLoc(),
652 rewriter.getF64Type(), arg);
659void AMDGPUPrintfLowering::callBufferedPrintfArgPush(
660 mlir::ValueRange args, mlir::Value ptrToStore,
661 llvm::ArrayRef<StringData> stringContents,
bool isConstFmtStr) {
662 const StringData *strIt = stringContents.begin();
663 size_t i = isConstFmtStr ? 1 : 0;
664 for (; i < args.size(); i++) {
665 if (i != 0 && !isCStringArg(args, i)) {
668 mlir::Value toStore = processNonStringArg(args[i]);
669 mlir::LLVM::StoreOp::create(rewriter, op.getLoc(), toStore, ptrToStore);
671 dataLayout.getTypeAllocSize(toStore.getType()).getFixedValue();
672 ptrToStore = gepInBounds(ptrToStore, llvm::alignTo(allocSize, 8));
676 if (!strIt->isConst) {
682 auto memcpy = mlir::LLVM::MemcpyOp::create(
683 rewriter, op.getLoc(), ptrToStore, args[i], strIt->realSize,
685 mlir::NamedAttribute align1(mlir::LLVM::LLVMDialect::getAlignAttrName(),
686 rewriter.getI64IntegerAttr(1));
688 rewriter.getArrayAttr({rewriter.getDictionaryAttr(align1),
689 rewriter.getDictionaryAttr(align1),
690 rewriter.getDictionaryAttr({})}));
692 ptrToStore = gepInBounds(ptrToStore, strIt->alignedSize);
699 llvm::SmallVector<mlir::Value, 32> whatToStore;
700 processConstantStringArg(*strIt, whatToStore);
703 for (mlir::Value toStore : whatToStore) {
704 mlir::LLVM::StoreOp::create(rewriter, op.getLoc(), toStore, ptrToStore);
705 ptrToStore = gepInBounds(
707 dataLayout.getTypeAllocSize(toStore.getType()).getFixedValue());
712mlir::Value AMDGPUPrintfLowering::emitAMDGPUPrintfCall(mlir::ValueRange args,
714 size_t numOps = args.size();
717 mlir::Value fmt = args[0];
719 if (std::optional<std::string> resolved = getConstString(0)) {
721 llvm::locateAMDGPUPrintfCStrings(specIsCString, fmtStr);
725 llvm::SmallVector<StringData, 8> stringContents;
726 bool isConstFmtStr = !fmtStr.empty();
729 mlir::Value ptr = callBufferedPrintfStart(args, fmt, isConstFmtStr,
730 stringContents, argSize);
734 mlir::Value cmp = mlir::LLVM::ICmpOp::create(
735 rewriter, op.getLoc(), mlir::LLVM::ICmpPredicate::ne, ptr,
736 mlir::LLVM::ZeroOp::create(rewriter, op.getLoc(), ptr.getType()));
739 mlir::Block *end = cont;
740 mlir::Block *argPush =
741 rewriter.createBlock(cont->getParent(), cont->getIterator());
743 rewriter.setInsertionPointToEnd(cmp.getParentBlock());
744 mlir::LLVM::CondBrOp::create(rewriter, op.getLoc(), cmp, argPush, end);
745 rewriter.setInsertionPointToEnd(argPush);
751 mlir::Value constantTwo = getI32(2);
752 mlir::Value controlDWord =
753 mlir::LLVM::ShlOp::create(rewriter, op.getLoc(), argSize, constantTwo);
755 controlDWord = mlir::LLVM::OrOp::create(rewriter, op.getLoc(),
756 controlDWord, constantTwo);
758 mlir::LLVM::StoreOp::create(rewriter, op.getLoc(), controlDWord, ptr);
760 ptr = gepInBounds(ptr, 4);
765 addPrintfFormatMetadata(llvm::getAMDGPUPrintfFormatMetadata(fmtStr),
768 mlir::LLVM::StoreOp::create(
769 rewriter, op.getLoc(),
770 getI64(llvm::getAMDGPUPrintfFormatHash(fmtStr)), ptr);
771 ptr = gepInBounds(ptr, 8);
776 addPrintfFormatMetadata(llvm::AMDGPUPrintfNonConstFormatMetadata,
781 callBufferedPrintfArgPush(args, ptr, stringContents, isConstFmtStr);
784 mlir::LLVM::BrOp::create(rewriter, op.getLoc(), end);
785 rewriter.setInsertionPointToStart(end);
786 mlir::Value notCmp = mlir::LLVM::XOrOp::create(
787 rewriter, op.getLoc(), cmp,
788 mlir::LLVM::ConstantOp::create(
789 rewriter, op.getLoc(), rewriter.getI1Type(), llvm::APInt(1, 1)));
790 return mlir::LLVM::SExtOp::create(rewriter, op.getLoc(),
791 rewriter.getI32Type(), notCmp);
794 mlir::Value desc = callPrintfBegin(getI64(0));
795 desc = appendString(desc, fmt, numOps == 1);
800 for (
unsigned int i = 1; i != numOps; ++i) {
801 bool isLast = i == numOps - 1;
802 bool isCString = specIsCString.test(i);
803 desc = processArg(desc, args[i], isCString, isLast);
806 return mlir::LLVM::TruncOp::create(rewriter, op.getLoc(),
807 rewriter.getI32Type(), desc);
810mlir::LogicalResult AMDGPUPrintfLowering::lower(mlir::ValueRange args,
814 for (
auto [cirArg, arg] : llvm::zip(op.getArgs(), args.drop_front())) {
815 mlir::Type ty =
arg.getType();
816 if (ty.isInteger(32) || ty.isInteger(64) || ty.isF64() ||
817 mlir::isa<mlir::LLVM::LLVMPointerType>(ty))
819 return op.emitError() <<
"unsupported argument type " << cirArg.getType()
820 <<
" for AMDGPU printf";
824 mlir::Block *block = op->getBlock();
825 cont = rewriter.splitBlock(block, mlir::Block::iterator(op));
826 rewriter.setInsertionPointToEnd(block);
828 mlir::Value result = emitAMDGPUPrintfCall(args, isBuffered);
829 if (rewriter.getInsertionBlock() != cont)
830 mlir::LLVM::BrOp::create(rewriter, op.getLoc(), cont);
832 rewriter.replaceOp(op, result);
833 return mlir::success();
837 mlir::ValueRange operands,
838 mlir::ConversionPatternRewriter &rewriter,
839 const mlir::DataLayout &dataLayout,
840 mlir::SymbolTableCollection &symbolTables,
841 unsigned genericAddrSpace,
843 return AMDGPUPrintfLowering(op, rewriter, dataLayout, symbolTables,
845 .lower(operands, isBuffered);
static bool isUnsigned(SValBuilder &SVB, NonLoc Value)
__DEVICE__ void * memcpy(void *__a, const void *__b, size_t __c)
mlir::LogicalResult lowerAMDGPUPrintf(cir::OffloadPrintfOp op, mlir::ValueRange operands, mlir::ConversionPatternRewriter &rewriter, const mlir::DataLayout &dataLayout, mlir::SymbolTableCollection &symbolTables, unsigned genericAddrSpace, bool isBuffered)
Lowers op, whose lowered operands are operands, to the buffered printf runtime interface if isBuffere...
bool isAMDGPUPrintfModule(mlir::ModuleOp module)
Whether module lowers device printf with the AMDGPU runtime interface: an AMDGCN triple,...
void annotateAMDGPUPrintfStrings(mlir::ModuleOp module, mlir::SymbolTableCollection &symbolTables)
Resolve constant format strings for AMDGPU printf ops while their producers are still CIR,...
const internal::VariadicAllOfMatcher< Attr > attr
SetTy< T > join(SetTy< T > A, SetTy< T > B, typename SetTy< T >::Factory &F)
Computes the union of two ImmutableSets.
U cast(CodeGen::Address addr)
__DEVICE__ _Tp arg(const std::complex< _Tp > &__c)
float __ovld __cnfn step(float, float)
Returns 0.0 if x < edge, otherwise it returns 1.0.
float __ovld __cnfn length(float)
Return the length of vector p, i.e., sqrt(p.x2 + p.y 2 + ...)
__builtin_elementwise_add_sat __builtin_elementwise_sub_sat uint32_t int64_t
__builtin_elementwise_add_sat __builtin_elementwise_sub_sat uint32_t uint64_t __builtin_riscv_ssha_i32 __builtin_riscv_sshl_u32 uint64_t