42#include "llvm/ADT/SmallVector.h"
43#include "llvm/IR/Type.h"
44#include "llvm/Support/DebugLog.h"
45#include "llvm/Support/FormatVariadic.h"
49#define GEN_PASS_DEF_CONVERTFUNCTOLLVMPASS
50#define GEN_PASS_DEF_SETLLVMMODULEDATALAYOUTPASS
51#include "mlir/Conversion/Passes.h.inc"
56#define PASS_NAME "convert-func-to-llvm"
57#define DEBUG_TYPE PASS_NAME
72 name == LLVM::LLVMDialect::getReadnoneAttrName();
80 func->getDiscardableAttrDictionary().getValue()) {
89 FunctionOpInterface funcOp,
90 LLVM::LLVMFuncOp wrapperFuncOp) {
91 auto argAttrs = funcOp.getAllArgAttrs();
92 if (!resultStructType) {
93 if (
auto resAttrs = funcOp.getAllResultAttrs())
94 wrapperFuncOp.setAllResultAttrs(resAttrs);
96 wrapperFuncOp.setAllArgAttrs(argAttrs);
103 argAttributes.append(argAttrs.begin(), argAttrs.end());
104 wrapperFuncOp.setAllArgAttrs(argAttributes);
107 cast<FunctionOpInterface>(wrapperFuncOp.getOperation())
108 .setVisibility(funcOp.getVisibility());
121 FunctionOpInterface funcOp,
122 LLVM::LLVMFuncOp newFuncOp) {
123 auto type = cast<FunctionType>(funcOp.getFunctionType());
124 auto [wrapperFuncType, resultStructType] =
130 auto wrapperFuncOp = LLVM::LLVMFuncOp::create(
131 rewriter, loc, llvm::formatv(
"_mlir_ciface_{0}", funcOp.getName()).str(),
132 wrapperFuncType, LLVM::Linkage::External,
false,
133 LLVM::CConv::C,
nullptr, attributes);
140 size_t argOffset = resultStructType ? 1 : 0;
141 for (
auto [
index, argType] : llvm::enumerate(type.getInputs())) {
142 Value arg = wrapperFuncOp.getArgument(
index + argOffset);
143 if (
auto memrefType = dyn_cast<MemRefType>(argType)) {
144 Value loaded = LLVM::LoadOp::create(
145 rewriter, loc, typeConverter.convertType(memrefType), arg);
149 if (isa<UnrankedMemRefType>(argType)) {
150 Value loaded = LLVM::LoadOp::create(
151 rewriter, loc, typeConverter.convertType(argType), arg);
159 auto call = LLVM::CallOp::create(rewriter, loc, newFuncOp, args);
161 if (resultStructType) {
162 LLVM::StoreOp::create(rewriter, loc, call.getResult(),
163 wrapperFuncOp.getArgument(0));
164 LLVM::ReturnOp::create(rewriter, loc,
ValueRange{});
166 LLVM::ReturnOp::create(rewriter, loc, call.getResults());
181 FunctionOpInterface funcOp,
182 LLVM::LLVMFuncOp newFuncOp) {
185 auto [wrapperType, resultStructType] =
187 cast<FunctionType>(funcOp.getFunctionType()));
191 assert(wrapperType &&
"unexpected type conversion failure");
197 auto wrapperFunc = LLVM::LLVMFuncOp::create(
198 builder, loc, llvm::formatv(
"_mlir_ciface_{0}", funcOp.getName()).str(),
199 wrapperType, LLVM::Linkage::External,
false,
200 LLVM::CConv::C,
nullptr, attributes);
204 newFuncOp.setLinkage(LLVM::Linkage::Private);
208 FunctionType type = cast<FunctionType>(funcOp.getFunctionType());
210 args.reserve(type.getNumInputs());
211 ValueRange wrapperArgsRange(newFuncOp.getArguments());
213 if (resultStructType) {
215 Type resultType = cast<LLVM::LLVMFunctionType>(wrapperType).getParamType(0);
217 Value one = LLVM::ConstantOp::create(builder, loc, indexType,
220 LLVM::AllocaOp::create(builder, loc, resultType, resultStructType, one);
226 for (
Type input : type.getInputs()) {
229 auto memRefType = dyn_cast<MemRefType>(input);
230 auto unrankedMemRefType = dyn_cast<UnrankedMemRefType>(input);
231 if (memRefType || unrankedMemRefType) {
232 numToDrop = memRefType
238 wrapperArgsRange.take_front(numToDrop))
240 builder, loc, typeConverter, unrankedMemRefType,
241 wrapperArgsRange.take_front(numToDrop));
243 auto ptrTy = LLVM::LLVMPointerType::get(builder.
getContext());
245 Value one = LLVM::ConstantOp::create(
247 Value allocated = LLVM::AllocaOp::create(
248 builder, loc, ptrTy, packed.
getType(), one, 0);
249 LLVM::StoreOp::create(builder, loc, packed, allocated);
252 arg = wrapperArgsRange[0];
256 wrapperArgsRange = wrapperArgsRange.drop_front(numToDrop);
258 assert(wrapperArgsRange.empty() &&
"did not map some of the arguments");
260 auto call = LLVM::CallOp::create(builder, loc, wrapperFunc, args);
262 if (resultStructType) {
264 LLVM::LoadOp::create(builder, loc, resultStructType, args.front());
265 LLVM::ReturnOp::create(builder, loc,
result);
267 LLVM::ReturnOp::create(builder, loc, call.getResults());
276 ArrayRef<std::optional<NamedAttribute>> byValRefNonPtrAttrs,
277 LLVM::LLVMFuncOp funcOp) {
279 if (funcOp.isExternal())
282 ConversionPatternRewriter::InsertionGuard guard(rewriter);
283 rewriter.setInsertionPointToStart(&funcOp.getFunctionBody().front());
285 for (
const auto &[arg, byValRefAttr] :
286 llvm::zip(funcOp.getArguments(), byValRefNonPtrAttrs)) {
292 assert(isa<LLVM::LLVMPointerType>(arg.getType()) &&
293 "Expected LLVM pointer type for argument with "
294 "`llvm.byval`/`llvm.byref` attribute");
295 Type resTy = typeConverter.convertType(
296 cast<TypeAttr>(byValRefAttr->getValue()).getValue());
298 Value valueArg = LLVM::LoadOp::create(rewriter, arg.getLoc(), resTy, arg);
299 rewriter.replaceAllUsesWith(arg, valueArg);
305 bool useBarePtrCallConv, TypeConverter::SignatureConversion &
result,
309 auto llvmType = dyn_cast_or_null<LLVM::LLVMFunctionType>(
311 funcOp, varargsAttr && varargsAttr.getValue(), useBarePtrCallConv,
312 result, byValRefNonPtrAttrs));
319 ConversionPatternRewriter &rewriter,
320 LLVM::LLVMFunctionType llvmType,
324 if (symbolTables && symbolTableOp) {
326 symbolTable.
remove(funcOp);
329 LLVM::CConvAttr::get(rewriter.getContext(), LLVM::CConv::C));
330 auto newFuncOp = LLVM::LLVMFuncOp::create(rewriter, funcOp.getLoc(),
334 if (symbolTables && symbolTableOp) {
335 auto ip = rewriter.getInsertionPoint();
337 symbolTable.
insert(newFuncOp, ip);
340 cast<FunctionOpInterface>(newFuncOp.getOperation())
341 .setVisibility(funcOp.getVisibility());
344 if (funcOp->hasDiscardableAttr(LLVM::LLVMDialect::getReadnoneAttrName())) {
345 auto memoryAttr = LLVM::MemoryEffectsAttr::get(
346 rewriter.getContext(), {LLVM::ModRefInfo::NoModRef,
347 LLVM::ModRefInfo::NoModRef,
348 LLVM::ModRefInfo::NoModRef,
349 LLVM::ModRefInfo::NoModRef,
350 LLVM::ModRefInfo::NoModRef,
351 LLVM::ModRefInfo::NoModRef});
352 newFuncOp.setMemoryEffectsAttr(memoryAttr);
360 ConversionPatternRewriter &rewriter,
363 convertedAttrs.reserve(attrsDict.size());
366 return TypeAttr::get(
367 converter.convertType(cast<TypeAttr>(attr.getValue()).getValue()));
369 if (attr.getName().getValue() == LLVM::LLVMDialect::getByValAttrName()) {
370 convertedAttrs.push_back(rewriter.getNamedAttr(
371 LLVM::LLVMDialect::getByValAttrName(), convert(attr)));
372 }
else if (attr.getName().getValue() ==
373 LLVM::LLVMDialect::getByRefAttrName()) {
374 convertedAttrs.push_back(rewriter.getNamedAttr(
375 LLVM::LLVMDialect::getByRefAttrName(), convert(attr)));
376 }
else if (attr.getName().getValue() ==
377 LLVM::LLVMDialect::getStructRetAttrName()) {
378 convertedAttrs.push_back(rewriter.getNamedAttr(
379 LLVM::LLVMDialect::getStructRetAttrName(), convert(attr)));
380 }
else if (attr.getName().getValue() ==
381 LLVM::LLVMDialect::getInAllocaAttrName()) {
382 convertedAttrs.push_back(rewriter.getNamedAttr(
383 LLVM::LLVMDialect::getInAllocaAttrName(), convert(attr)));
385 convertedAttrs.push_back(attr);
388 return convertedAttrs;
392 FunctionOpInterface funcOp, ConversionPatternRewriter &rewriter,
394 LLVM::LLVMFunctionType llvmType, LLVM::LLVMFuncOp newFuncOp) {
397 if (
ArrayAttr resAttrDicts = funcOp.getAllResultAttrs()) {
398 assert(!resAttrDicts.empty() &&
"expected array to be non-empty");
399 if (funcOp.getNumResults() == 1)
400 newFuncOp.setAllResultAttrs(resAttrDicts);
402 if (
ArrayAttr argAttrDicts = funcOp.getAllArgAttrs()) {
404 for (
unsigned i = 0, e = funcOp.getNumArguments(); i < e; ++i) {
408 auto attrsDict = cast<DictionaryAttr>(argAttrDicts[i]);
411 auto mapping = sig.getInputMapping(i);
412 assert(mapping &&
"unexpected deletion of function argument");
416 if (mapping->size == 1) {
417 newArgAttrs[mapping->inputNo] =
418 DictionaryAttr::get(rewriter.getContext(), convertedAttrs);
423 for (
size_t j = 0;
j < mapping->size; ++
j)
424 newArgAttrs[mapping->inputNo +
j] =
425 DictionaryAttr::get(rewriter.getContext(), {});
427 if (!newArgAttrs.empty())
428 newFuncOp.setAllArgAttrs(rewriter.getArrayAttr(newArgAttrs));
433 ConversionPatternRewriter &rewriter,
435 LLVM::LLVMFuncOp newFuncOp) {
436 if (newFuncOp.isExternal())
455 FunctionOpInterface funcOp, ConversionPatternRewriter &rewriter,
458 auto funcTy = dyn_cast<FunctionType>(funcOp.getFunctionType());
460 return rewriter.notifyMatchFailure(
461 funcOp,
"Only support FunctionOpInterface with FunctionType");
469 TypeConverter::SignatureConversion
result(funcOp.getNumArguments());
471 funcOp, converter, useBarePtrCallConv,
result, byValRefNonPtrAttrs);
472 if (failed(llvmType))
473 return rewriter.notifyMatchFailure(funcOp,
"signature conversion failed");
476 bool emitCWrapper = funcOp->hasDiscardableAttrOfType<UnitAttr>(
477 LLVM::LLVMDialect::getEmitCWrapperAttrName());
478 if (!useBarePtrCallConv && emitCWrapper && llvmType->isVarArg())
479 return funcOp.emitError(
"C interface for variadic functions is not "
483 FailureOr<LoweredLLVMFuncAttrs> loweredAttrs =
485 if (failed(loweredAttrs))
486 return rewriter.notifyMatchFailure(funcOp,
487 "failed to lower func attributes");
490 auto newFuncOp =
createLLVMFuncOp(funcOp, rewriter, *llvmType, *loweredAttrs,
498 rewriter.inlineRegionBefore(funcOp.getFunctionBody(), newFuncOp.getBody(),
502 if (!newFuncOp.getBody().empty())
503 rewriter.applySignatureConversion(&newFuncOp.getBody().front(),
result,
514 if (!useBarePtrCallConv && emitCWrapper)
534 matchAndRewrite(func::FuncOp funcOp, OpAdaptor adaptor,
535 ConversionPatternRewriter &rewriter)
const override {
537 cast<FunctionOpInterface>(funcOp.getOperation()), rewriter,
538 *getTypeConverter(), symbolTables);
540 return rewriter.notifyMatchFailure(funcOp,
"Could not convert funcop");
542 rewriter.eraseOp(funcOp);
548 using ConvertOpToLLVMPattern<func::ConstantOp>::ConvertOpToLLVMPattern;
551 matchAndRewrite(func::ConstantOp op, OpAdaptor adaptor,
552 ConversionPatternRewriter &rewriter)
const override {
553 auto type = typeConverter->convertType(op.getResult().getType());
554 if (!type || !LLVM::isCompatibleType(type))
555 return rewriter.notifyMatchFailure(op,
"failed to convert result type");
558 LLVM::AddressOfOp::create(rewriter, op.getLoc(), type, op.getValue());
559 for (
const NamedAttribute &attr :
560 op->getDiscardableAttrDictionary().getValue()) {
561 if (attr.getName().strref() ==
"value")
563 newOp->setDiscardableAttr(attr.getName(), attr.getValue());
565 rewriter.replaceOp(op, newOp->getResults());
572template <
typename CallOpType>
574 using ConvertOpToLLVMPattern<CallOpType>::ConvertOpToLLVMPattern;
575 using Super = CallOpInterfaceLowering<CallOpType>;
576 using Base = ConvertOpToLLVMPattern<CallOpType>;
579 LogicalResult matchAndRewriteImpl(CallOpType callOp, Adaptor adaptor,
580 ConversionPatternRewriter &rewriter,
581 bool useBarePtrCallConv =
false)
const {
583 Type packedResult =
nullptr;
584 SmallVector<SmallVector<Type>> groupedResultTypes;
585 unsigned numResults = callOp.getNumResults();
586 auto resultTypes = llvm::to_vector<4>(callOp.getResultTypes());
587 int64_t numConvertedTypes = 0;
588 if (numResults != 0) {
589 if (!(packedResult = this->getTypeConverter()->packFunctionResults(
590 resultTypes, useBarePtrCallConv, &groupedResultTypes,
591 &numConvertedTypes)))
595 if (useBarePtrCallConv) {
596 for (
auto it : callOp->getOperands()) {
597 Type operandType = it.getType();
598 if (isa<UnrankedMemRefType>(operandType)) {
605 auto promoted = this->getTypeConverter()->promoteOperands(
606 callOp.getLoc(), callOp->getOperands(),
607 adaptor.getOperands(), rewriter, useBarePtrCallConv);
608 LLVM::CallOp::Properties properties{};
609 LLVM::CallOp::populateDefaultProperties(
610 OperationName(LLVM::CallOp::getOperationName(), rewriter.getContext()),
612 properties.operandSegmentSizes = {
static_cast<int32_t
>(promoted.size()), 0};
613 properties.op_bundle_sizes = rewriter.getDenseI32ArrayAttr({});
614 auto newOp = LLVM::CallOp::create(
615 rewriter, callOp.getLoc(),
617 properties, callOp->getDiscardableAttrDictionary().getValue());
618 if constexpr (std::is_same_v<CallOpType, func::CallOp>)
619 newOp.setCalleeAttr(callOp.getCalleeAttr());
628 auto getUnpackedResult = [&](
unsigned i) -> Value {
629 assert(numConvertedTypes > 0 &&
"convert op has no results");
630 if (numConvertedTypes == 1) {
631 assert(i == 0 &&
"out of bounds: converted op has only one result");
632 return newOp->getResult(0);
636 return LLVM::ExtractValueOp::create(rewriter, callOp.getLoc(),
637 newOp->getResult(0), i);
643 SmallVector<SmallVector<Value>> results;
644 results.reserve(numResults);
645 unsigned counter = 0;
646 for (
unsigned i = 0; i < numResults; ++i) {
647 SmallVector<Value> &group = results.emplace_back();
648 for (
unsigned j = 0, e = groupedResultTypes[i].size(); j < e; ++j)
649 group.push_back(getUnpackedResult(counter++));
653 for (
unsigned i = 0; i < numResults; ++i) {
654 Type origType = resultTypes[i];
655 auto memrefType = dyn_cast<MemRefType>(origType);
656 auto unrankedMemrefType = dyn_cast<UnrankedMemRefType>(origType);
657 if (useBarePtrCallConv && memrefType) {
660 assert(results[i].size() == 1 &&
"expected one converted result");
661 results[i].front() = MemRefDescriptor::fromStaticShape(
662 rewriter, callOp.getLoc(), *
this->getTypeConverter(), memrefType,
665 if (unrankedMemrefType) {
666 assert(!useBarePtrCallConv &&
"unranked memref is not supported in the "
667 "bare-ptr calling convention");
668 assert(results[i].size() == 1 &&
"expected one converted result");
669 Value desc = this->copyUnrankedDescriptor(
670 rewriter, callOp.getLoc(), unrankedMemrefType, results[i].front(),
674 results[i].front() = desc;
678 rewriter.replaceOpWithMultiple(callOp, results);
683class CallOpLowering :
public CallOpInterfaceLowering<func::CallOp> {
685 explicit CallOpLowering(
const LLVMTypeConverter &typeConverter,
686 SymbolTableCollection *symbolTables =
nullptr,
687 PatternBenefit benefit = 1)
688 : CallOpInterfaceLowering<func::CallOp>(typeConverter, benefit),
689 symbolTables(symbolTables) {}
692 matchAndRewrite(func::CallOp callOp, OneToNOpAdaptor adaptor,
693 ConversionPatternRewriter &rewriter)
const override {
694 bool useBarePtrCallConv =
false;
695 if (getTypeConverter()->getOptions().useBarePtrCallConv) {
696 useBarePtrCallConv =
true;
697 }
else if (symbolTables !=
nullptr) {
700 symbolTables->lookupNearestSymbolFrom(callOp, callOp.getCalleeAttr());
710 return matchAndRewriteImpl(callOp, adaptor, rewriter, useBarePtrCallConv);
714 SymbolTableCollection *symbolTables =
nullptr;
717struct CallIndirectOpLowering
718 :
public CallOpInterfaceLowering<func::CallIndirectOp> {
722 matchAndRewrite(func::CallIndirectOp callIndirectOp, OneToNOpAdaptor adaptor,
723 ConversionPatternRewriter &rewriter)
const override {
724 return matchAndRewriteImpl(callIndirectOp, adaptor, rewriter);
728struct UnrealizedConversionCastOpLowering
730 using ConvertOpToLLVMPattern<
731 UnrealizedConversionCastOp>::ConvertOpToLLVMPattern;
734 matchAndRewrite(UnrealizedConversionCastOp op, OpAdaptor adaptor,
735 ConversionPatternRewriter &rewriter)
const override {
736 SmallVector<Type> convertedTypes;
737 if (succeeded(typeConverter->convertTypes(op.getOutputs().getTypes(),
739 convertedTypes == adaptor.getInputs().getTypes()) {
740 rewriter.replaceOp(op, adaptor.getInputs());
744 convertedTypes.clear();
745 if (succeeded(typeConverter->convertTypes(adaptor.getInputs().getTypes(),
747 convertedTypes == op.getOutputs().getType()) {
748 rewriter.replaceOp(op, adaptor.getInputs());
762 using ConvertOpToLLVMPattern<func::ReturnOp>::ConvertOpToLLVMPattern;
765 matchAndRewrite(func::ReturnOp op, OneToNOpAdaptor adaptor,
766 ConversionPatternRewriter &rewriter)
const override {
767 Location loc = op.getLoc();
768 SmallVector<Value, 4> updatedOperands;
770 auto funcOp = op->getParentOfType<LLVM::LLVMFuncOp>();
771 bool useBarePtrCallConv =
774 for (
auto [oldOperand, newOperands] :
775 llvm::zip_equal(op->getOperands(), adaptor.getOperands())) {
776 Type oldTy = oldOperand.getType();
777 if (
auto memRefType = dyn_cast<MemRefType>(oldTy)) {
778 assert(newOperands.size() == 1 &&
"expected one converted result");
779 if (useBarePtrCallConv &&
780 getTypeConverter()->canConvertToBarePtr(memRefType)) {
783 MemRefDescriptor memrefDesc(newOperands.front());
784 updatedOperands.push_back(memrefDesc.allocatedPtr(rewriter, loc));
787 }
else if (
auto unrankedMemRefType =
788 dyn_cast<UnrankedMemRefType>(oldTy)) {
789 assert(newOperands.size() == 1 &&
"expected one converted result");
790 if (useBarePtrCallConv) {
796 copyUnrankedDescriptor(rewriter, loc, unrankedMemRefType,
797 newOperands.front(),
true);
800 updatedOperands.push_back(updatedDesc);
804 llvm::append_range(updatedOperands, newOperands);
808 if (updatedOperands.size() <= 1) {
809 rewriter.replaceOpWithNewOp<LLVM::ReturnOp>(
811 op->getDiscardableAttrDictionary().getValue());
817 auto packedType = getTypeConverter()->packFunctionResults(
818 op.getOperandTypes(), useBarePtrCallConv);
820 return rewriter.notifyMatchFailure(op,
"could not convert result types");
823 Value packed = LLVM::PoisonOp::create(rewriter, loc, packedType);
824 for (
auto [idx, operand] : llvm::enumerate(updatedOperands)) {
825 packed = LLVM::InsertValueOp::create(rewriter, loc, packed, operand, idx);
827 rewriter.replaceOpWithNewOp<LLVM::ReturnOp>(
828 op,
TypeRange(), packed, op->getDiscardableAttrDictionary().getValue());
837 patterns.
add<FuncOpConversion>(converter, symbolTables);
844 patterns.
add<CallIndirectOpLowering>(converter);
845 patterns.
add<CallOpLowering>(converter, symbolTables);
846 patterns.
add<ConstantOpLowering>(converter);
847 patterns.
add<ReturnOpLowering>(converter);
852struct ConvertFuncToLLVMPass
853 :
public impl::ConvertFuncToLLVMPassBase<ConvertFuncToLLVMPass> {
857 void runOnOperation()
override {
858 ModuleOp m = getOperation();
859 StringRef dataLayout;
860 auto dataLayoutAttr = dyn_cast_or_null<StringAttr>(
861 m->getDiscardableAttr(LLVM::LLVMDialect::getDataLayoutAttrName()));
863 dataLayout = dataLayoutAttr.getValue();
865 if (failed(LLVM::LLVMDialect::verifyDataLayoutString(
866 dataLayout, [
this](
const Twine &message) {
867 getOperation().emitError() << message.str();
873 const auto &dataLayoutAnalysis = getAnalysis<DataLayoutAnalysis>();
876 dataLayoutAnalysis.getAtOrAbove(m));
877 options.useBarePtrCallConv = useBarePtrCallConv;
879 options.overrideIndexBitwidth(indexBitwidth);
880 options.dataLayout = llvm::DataLayout(dataLayout);
883 &dataLayoutAnalysis);
886 SymbolTableCollection symbolTables;
892 if (
failed(applyPartialConversion(m,
target, std::move(patterns))))
897struct SetLLVMModuleDataLayoutPass
898 :
public impl::SetLLVMModuleDataLayoutPassBase<
899 SetLLVMModuleDataLayoutPass> {
903 void runOnOperation()
override {
904 if (
failed(LLVM::LLVMDialect::verifyDataLayoutString(
905 this->dataLayout, [
this](
const Twine &message) {
906 getOperation().emitError() << message.str();
911 ModuleOp m = getOperation();
912 m->setDiscardableAttr(LLVM::LLVMDialect::getDataLayoutAttrName(),
913 StringAttr::get(m.getContext(),
this->dataLayout));
924struct FuncToLLVMDialectInterface :
public ConvertToLLVMPatternInterface {
925 FuncToLLVMDialectInterface(Dialect *dialect)
926 : ConvertToLLVMPatternInterface(dialect) {}
929 void populateConvertToLLVMConversionPatterns(
930 ConversionTarget &
target, LLVMTypeConverter &typeConverter,
931 RewritePatternSet &patterns)
const final {
939 dialect->addInterfaces<FuncToLLVMDialectInterface>();
return MutableOperandRange * this
static FailureOr< LLVM::LLVMFunctionType > convertFuncSignature(FunctionOpInterface funcOp, const LLVMTypeConverter &converter, bool useBarePtrCallConv, TypeConverter::SignatureConversion &result, SmallVectorImpl< std::optional< NamedAttribute > > &byValRefNonPtrAttrs)
static void restoreByValRefArgumentType(ConversionPatternRewriter &rewriter, const LLVMTypeConverter &typeConverter, ArrayRef< std::optional< NamedAttribute > > byValRefNonPtrAttrs, LLVM::LLVMFuncOp funcOp)
Inserts llvm.load ops in the function body to restore the expected pointee value from llvm....
static LLVM::LLVMFuncOp createLLVMFuncOp(FunctionOpInterface funcOp, ConversionPatternRewriter &rewriter, LLVM::LLVMFunctionType llvmType, LoweredLLVMFuncAttrs &loweredAttrs, SymbolTableCollection *symbolTables)
static void propagateArgResAttrs(OpBuilder &builder, bool resultStructType, FunctionOpInterface funcOp, LLVM::LLVMFuncOp wrapperFuncOp)
Propagate argument/results attributes.
static SmallVector< NamedAttribute > convertArgumentAttributes(DictionaryAttr attrsDict, ConversionPatternRewriter &rewriter, const LLVMTypeConverter &converter)
static bool isDiscardableAttr(StringRef name)
static constexpr StringRef barePtrAttrName
static constexpr StringRef varargsAttrName
static constexpr StringRef linkageAttrName
static void filterFuncAttributes(FunctionOpInterface func, SmallVectorImpl< NamedAttribute > &result)
Only retain those attributes that are not constructed by LLVMFuncOp::build.
static void propagateFunctionArgResAttrs(FunctionOpInterface funcOp, ConversionPatternRewriter &rewriter, const LLVMTypeConverter &converter, TypeConverter::SignatureConversion &sig, LLVM::LLVMFunctionType llvmType, LLVM::LLVMFuncOp newFuncOp)
static bool shouldUseBarePtrCallConv(Operation *op, const LLVMTypeConverter *typeConverter)
Return true if the op should use bare pointer calling convention.
static void wrapExternalFunction(OpBuilder &builder, Location loc, const LLVMTypeConverter &typeConverter, FunctionOpInterface funcOp, LLVM::LLVMFuncOp newFuncOp)
Creates an auxiliary function with pointer-to-memref-descriptor-struct arguments instead of unpacked ...
static void wrapForExternalCallers(OpBuilder &rewriter, Location loc, const LLVMTypeConverter &typeConverter, FunctionOpInterface funcOp, LLVM::LLVMFuncOp newFuncOp)
Creates an auxiliary function with pointer-to-memref-descriptor-struct arguments instead of unpacked ...
static void wrapWithCInterface(FunctionOpInterface funcOp, ConversionPatternRewriter &rewriter, const LLVMTypeConverter &converter, LLVM::LLVMFuncOp newFuncOp)
static llvm::ManagedStatic< PassManagerOptions > options
Special case of IntegerAttr to represent boolean integers, i.e., signless i1 integers.
IntegerAttr getIntegerAttr(Type type, int64_t value)
MLIRContext * getContext() const
DictionaryAttr getDictionaryAttr(ArrayRef< NamedAttribute > value)
Utility class for operation conversions targeting the LLVM dialect that match exactly one source oper...
typename SourceOp::template GenericAdaptor< ArrayRef< ValueRange > > OneToNOpAdaptor
The DialectRegistry maps a dialect namespace to a constructor for the matching dialect.
bool addExtension(TypeID extensionID, std::unique_ptr< DialectExtensionBase > extension)
Add the given extension to the registry.
Conversion from types to the LLVM IR dialect.
Type convertFunctionSignature(FunctionType funcTy, bool isVariadic, bool useBarePtrCallConv, SignatureConversion &result) const
Convert a function type.
const LowerToLLVMOptions & getOptions() const
std::pair< LLVM::LLVMFunctionType, LLVM::LLVMStructType > convertFunctionTypeCWrapper(FunctionType type) const
Converts the function type to a C-compatible format, in particular using pointers to memref descripto...
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.
static void unpack(OpBuilder &builder, Location loc, Value packed, MemRefType type, SmallVectorImpl< Value > &results)
Builds IR extracting individual elements of a MemRef descriptor structure and returning them as resul...
static unsigned getNumUnpackedValues(MemRefType type)
Returns the number of non-aggregate values that would be produced by unpack.
static Value pack(OpBuilder &builder, Location loc, const LLVMTypeConverter &converter, MemRefType type, ValueRange values)
Builds IR populating a MemRef descriptor structure from a list of individual values composing that de...
NamedAttribute represents a combination of a name and an Attribute value.
RAII guard to reset the insertion point of the builder when destroyed.
This class helps build Operations.
void setInsertionPointToStart(Block *block)
Sets the insertion point to the start of the specified block.
A trait used to provide symbol table functionalities to a region operation.
Operation is the basic unit of execution within MLIR.
Operation * getParentWithTrait()
Returns the closest surrounding parent operation with trait Trait.
bool hasDiscardableAttr(StringRef name)
Return true if this operation has a discardable attribute with the provided name.
RewritePatternSet & add(ConstructorArg &&arg, ConstructorArgs &&...args)
Add an instance of each of the pattern types 'Ts' to the pattern list with the given arguments.
This class represents a collection of SymbolTables.
virtual SymbolTable & getSymbolTable(Operation *op)
Lookup, or create, a symbol table for an operation.
This class allows for representing and managing the symbol table used by operations with the 'SymbolT...
static Operation * lookupNearestSymbolFrom(Operation *from, StringAttr symbol)
Returns the operation registered with the given symbol name within the closest parent operation of,...
StringAttr insert(Operation *symbol, Block::iterator insertPt={})
Insert a new symbol into the table, and rename it as necessary to avoid collisions.
void remove(Operation *op)
Remove the given symbol from the table, without deleting it.
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
static Value pack(OpBuilder &builder, Location loc, const LLVMTypeConverter &converter, UnrankedMemRefType type, ValueRange values)
Builds IR populating an unranked MemRef descriptor structure from a list of individual constituent va...
static void unpack(OpBuilder &builder, Location loc, Value packed, SmallVectorImpl< Value > &results)
Builds IR extracting individual elements that compose an unranked memref descriptor and returns them ...
static unsigned getNumUnpackedValues()
Returns the number of non-aggregate values that would be produced by unpack.
This class provides an abstraction over the different types of ranges over Values.
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.
Include the generated interface declarations.
static constexpr unsigned kDeriveIndexBitwidthFromDataLayout
Value to pass as bitwidth for the index type when the converter is expected to derive the bitwidth fr...
void registerConvertFuncToLLVMInterface(DialectRegistry ®istry)
void populateFuncToLLVMConversionPatterns(const LLVMTypeConverter &converter, RewritePatternSet &patterns, SymbolTableCollection *symbolTables=nullptr)
Collect the patterns to convert from the Func dialect to LLVM.
void populateFuncToLLVMFuncOpConversionPattern(const LLVMTypeConverter &converter, RewritePatternSet &patterns, SymbolTableCollection *symbolTables=nullptr)
Collect the default pattern to convert a FuncOp to the LLVM dialect.
FailureOr< LoweredLLVMFuncAttrs > lowerDiscardableAttrsForLLVMFunc(FunctionOpInterface funcOp, Type llvmFuncType)
Partition funcOp's discardables for llvm.func: sym_name, function_type, and typed properties from llv...
FailureOr< LLVM::LLVMFuncOp > convertFuncOpToLLVMFuncOp(FunctionOpInterface funcOp, ConversionPatternRewriter &rewriter, const LLVMTypeConverter &converter, SymbolTableCollection *symbolTables=nullptr)
Convert input FunctionOpInterface operation to LLVMFuncOp by using the provided LLVMTypeConverter.
Result of lowering discardable attributes from a FunctionOpInterface to what llvm....
LLVM::LLVMFuncOp::Properties properties
NamedAttrList discardableAttrs
Eliminates variable at the specified position using Fourier-Motzkin variable elimination.