1 //===- FuncToLLVM.cpp - Func to LLVM dialect conversion -------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements a pass to convert MLIR Func and builtin dialects
10 // into the LLVM IR dialect.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "../PassDetail.h"
15 #include "mlir/Analysis/DataLayoutAnalysis.h"
16 #include "mlir/Conversion/ArithmeticToLLVM/ArithmeticToLLVM.h"
17 #include "mlir/Conversion/ControlFlowToLLVM/ControlFlowToLLVM.h"
18 #include "mlir/Conversion/FuncToLLVM/ConvertFuncToLLVM.h"
19 #include "mlir/Conversion/FuncToLLVM/ConvertFuncToLLVMPass.h"
20 #include "mlir/Conversion/LLVMCommon/ConversionTarget.h"
21 #include "mlir/Conversion/LLVMCommon/Pattern.h"
22 #include "mlir/Conversion/LLVMCommon/VectorPattern.h"
23 #include "mlir/Dialect/Func/IR/FuncOps.h"
24 #include "mlir/Dialect/LLVMIR/FunctionCallUtils.h"
25 #include "mlir/Dialect/LLVMIR/LLVMDialect.h"
26 #include "mlir/Dialect/Utils/StaticValueUtils.h"
27 #include "mlir/IR/Attributes.h"
28 #include "mlir/IR/BlockAndValueMapping.h"
29 #include "mlir/IR/Builders.h"
30 #include "mlir/IR/BuiltinOps.h"
31 #include "mlir/IR/PatternMatch.h"
32 #include "mlir/IR/TypeUtilities.h"
33 #include "mlir/Support/LogicalResult.h"
34 #include "mlir/Support/MathExtras.h"
35 #include "mlir/Transforms/DialectConversion.h"
36 #include "mlir/Transforms/Passes.h"
37 #include "llvm/ADT/TypeSwitch.h"
38 #include "llvm/IR/DerivedTypes.h"
39 #include "llvm/IR/IRBuilder.h"
40 #include "llvm/IR/Type.h"
41 #include "llvm/Support/CommandLine.h"
42 #include "llvm/Support/FormatVariadic.h"
43 #include <algorithm>
44 #include <functional>
45 
46 using namespace mlir;
47 
48 #define PASS_NAME "convert-func-to-llvm"
49 
50 /// Only retain those attributes that are not constructed by
51 /// `LLVMFuncOp::build`. If `filterArgAttrs` is set, also filter out argument
52 /// attributes.
53 static void filterFuncAttributes(ArrayRef<NamedAttribute> attrs,
54                                  bool filterArgAndResAttrs,
55                                  SmallVectorImpl<NamedAttribute> &result) {
56   for (const auto &attr : attrs) {
57     if (attr.getName() == SymbolTable::getSymbolAttrName() ||
58         attr.getName() == FunctionOpInterface::getTypeAttrName() ||
59         attr.getName() == "func.varargs" ||
60         (filterArgAndResAttrs &&
61          (attr.getName() == FunctionOpInterface::getArgDictAttrName() ||
62           attr.getName() == FunctionOpInterface::getResultDictAttrName())))
63       continue;
64     result.push_back(attr);
65   }
66 }
67 
68 /// Helper function for wrapping all attributes into a single DictionaryAttr
69 static auto wrapAsStructAttrs(OpBuilder &b, ArrayAttr attrs) {
70   return DictionaryAttr::get(
71       b.getContext(),
72       b.getNamedAttr(LLVM::LLVMDialect::getStructAttrsAttrName(), attrs));
73 }
74 
75 /// Combines all result attributes into a single DictionaryAttr
76 /// and prepends to argument attrs.
77 /// This is intended to be used to format the attributes for a C wrapper
78 /// function when the result(s) is converted to the first function argument
79 /// (in the multiple return case, all returns get wrapped into a single
80 /// argument). The total number of argument attributes should be equal to
81 /// (number of function arguments) + 1.
82 static void
83 prependResAttrsToArgAttrs(OpBuilder &builder,
84                           SmallVectorImpl<NamedAttribute> &attributes,
85                           size_t numArguments) {
86   auto allAttrs = SmallVector<Attribute>(
87       numArguments + 1, DictionaryAttr::get(builder.getContext()));
88   NamedAttribute *argAttrs = nullptr;
89   for (auto it = attributes.begin(); it != attributes.end();) {
90     if (it->getName() == FunctionOpInterface::getArgDictAttrName()) {
91       auto arrayAttrs = it->getValue().cast<ArrayAttr>();
92       assert(arrayAttrs.size() == numArguments &&
93              "Number of arg attrs and args should match");
94       std::copy(arrayAttrs.begin(), arrayAttrs.end(), allAttrs.begin() + 1);
95       argAttrs = it;
96     } else if (it->getName() == FunctionOpInterface::getResultDictAttrName()) {
97       auto arrayAttrs = it->getValue().cast<ArrayAttr>();
98       assert(!arrayAttrs.empty() && "expected array to be non-empty");
99       allAttrs[0] = (arrayAttrs.size() == 1)
100                         ? arrayAttrs[0]
101                         : wrapAsStructAttrs(builder, arrayAttrs);
102       it = attributes.erase(it);
103       continue;
104     }
105     it++;
106   }
107 
108   auto newArgAttrs =
109       builder.getNamedAttr(FunctionOpInterface::getArgDictAttrName(),
110                            builder.getArrayAttr(allAttrs));
111   if (!argAttrs) {
112     attributes.emplace_back(newArgAttrs);
113     return;
114   }
115   *argAttrs = newArgAttrs;
116   return;
117 }
118 
119 /// Creates an auxiliary function with pointer-to-memref-descriptor-struct
120 /// arguments instead of unpacked arguments. This function can be called from C
121 /// by passing a pointer to a C struct corresponding to a memref descriptor.
122 /// Similarly, returned memrefs are passed via pointers to a C struct that is
123 /// passed as additional argument.
124 /// Internally, the auxiliary function unpacks the descriptor into individual
125 /// components and forwards them to `newFuncOp` and forwards the results to
126 /// the extra arguments.
127 static void wrapForExternalCallers(OpBuilder &rewriter, Location loc,
128                                    LLVMTypeConverter &typeConverter,
129                                    FuncOp funcOp, LLVM::LLVMFuncOp newFuncOp) {
130   auto type = funcOp.getFunctionType();
131   SmallVector<NamedAttribute, 4> attributes;
132   filterFuncAttributes(funcOp->getAttrs(), /*filterArgAndResAttrs=*/false,
133                        attributes);
134   Type wrapperFuncType;
135   bool resultIsNowArg;
136   std::tie(wrapperFuncType, resultIsNowArg) =
137       typeConverter.convertFunctionTypeCWrapper(type);
138   if (resultIsNowArg)
139     prependResAttrsToArgAttrs(rewriter, attributes, funcOp.getNumArguments());
140   auto wrapperFuncOp = rewriter.create<LLVM::LLVMFuncOp>(
141       loc, llvm::formatv("_mlir_ciface_{0}", funcOp.getName()).str(),
142       wrapperFuncType, LLVM::Linkage::External, /*dsoLocal*/ false, attributes);
143 
144   OpBuilder::InsertionGuard guard(rewriter);
145   rewriter.setInsertionPointToStart(wrapperFuncOp.addEntryBlock());
146 
147   SmallVector<Value, 8> args;
148   size_t argOffset = resultIsNowArg ? 1 : 0;
149   for (auto &en : llvm::enumerate(type.getInputs())) {
150     Value arg = wrapperFuncOp.getArgument(en.index() + argOffset);
151     if (auto memrefType = en.value().dyn_cast<MemRefType>()) {
152       Value loaded = rewriter.create<LLVM::LoadOp>(loc, arg);
153       MemRefDescriptor::unpack(rewriter, loc, loaded, memrefType, args);
154       continue;
155     }
156     if (en.value().isa<UnrankedMemRefType>()) {
157       Value loaded = rewriter.create<LLVM::LoadOp>(loc, arg);
158       UnrankedMemRefDescriptor::unpack(rewriter, loc, loaded, args);
159       continue;
160     }
161 
162     args.push_back(arg);
163   }
164 
165   auto call = rewriter.create<LLVM::CallOp>(loc, newFuncOp, args);
166 
167   if (resultIsNowArg) {
168     rewriter.create<LLVM::StoreOp>(loc, call.getResult(0),
169                                    wrapperFuncOp.getArgument(0));
170     rewriter.create<LLVM::ReturnOp>(loc, ValueRange{});
171   } else {
172     rewriter.create<LLVM::ReturnOp>(loc, call.getResults());
173   }
174 }
175 
176 /// Creates an auxiliary function with pointer-to-memref-descriptor-struct
177 /// arguments instead of unpacked arguments. Creates a body for the (external)
178 /// `newFuncOp` that allocates a memref descriptor on stack, packs the
179 /// individual arguments into this descriptor and passes a pointer to it into
180 /// the auxiliary function. If the result of the function cannot be directly
181 /// returned, we write it to a special first argument that provides a pointer
182 /// to a corresponding struct. This auxiliary external function is now
183 /// compatible with functions defined in C using pointers to C structs
184 /// corresponding to a memref descriptor.
185 static void wrapExternalFunction(OpBuilder &builder, Location loc,
186                                  LLVMTypeConverter &typeConverter,
187                                  FuncOp funcOp, LLVM::LLVMFuncOp newFuncOp) {
188   OpBuilder::InsertionGuard guard(builder);
189 
190   Type wrapperType;
191   bool resultIsNowArg;
192   std::tie(wrapperType, resultIsNowArg) =
193       typeConverter.convertFunctionTypeCWrapper(funcOp.getFunctionType());
194   // This conversion can only fail if it could not convert one of the argument
195   // types. But since it has been applied to a non-wrapper function before, it
196   // should have failed earlier and not reach this point at all.
197   assert(wrapperType && "unexpected type conversion failure");
198 
199   SmallVector<NamedAttribute, 4> attributes;
200   filterFuncAttributes(funcOp->getAttrs(), /*filterArgAndResAttrs=*/false,
201                        attributes);
202 
203   if (resultIsNowArg)
204     prependResAttrsToArgAttrs(builder, attributes, funcOp.getNumArguments());
205   // Create the auxiliary function.
206   auto wrapperFunc = builder.create<LLVM::LLVMFuncOp>(
207       loc, llvm::formatv("_mlir_ciface_{0}", funcOp.getName()).str(),
208       wrapperType, LLVM::Linkage::External, /*dsoLocal*/ false, attributes);
209 
210   builder.setInsertionPointToStart(newFuncOp.addEntryBlock());
211 
212   // Get a ValueRange containing arguments.
213   FunctionType type = funcOp.getFunctionType();
214   SmallVector<Value, 8> args;
215   args.reserve(type.getNumInputs());
216   ValueRange wrapperArgsRange(newFuncOp.getArguments());
217 
218   if (resultIsNowArg) {
219     // Allocate the struct on the stack and pass the pointer.
220     Type resultType =
221         wrapperType.cast<LLVM::LLVMFunctionType>().getParamType(0);
222     Value one = builder.create<LLVM::ConstantOp>(
223         loc, typeConverter.convertType(builder.getIndexType()),
224         builder.getIntegerAttr(builder.getIndexType(), 1));
225     Value result = builder.create<LLVM::AllocaOp>(loc, resultType, one);
226     args.push_back(result);
227   }
228 
229   // Iterate over the inputs of the original function and pack values into
230   // memref descriptors if the original type is a memref.
231   for (auto &en : llvm::enumerate(type.getInputs())) {
232     Value arg;
233     int numToDrop = 1;
234     auto memRefType = en.value().dyn_cast<MemRefType>();
235     auto unrankedMemRefType = en.value().dyn_cast<UnrankedMemRefType>();
236     if (memRefType || unrankedMemRefType) {
237       numToDrop = memRefType
238                       ? MemRefDescriptor::getNumUnpackedValues(memRefType)
239                       : UnrankedMemRefDescriptor::getNumUnpackedValues();
240       Value packed =
241           memRefType
242               ? MemRefDescriptor::pack(builder, loc, typeConverter, memRefType,
243                                        wrapperArgsRange.take_front(numToDrop))
244               : UnrankedMemRefDescriptor::pack(
245                     builder, loc, typeConverter, unrankedMemRefType,
246                     wrapperArgsRange.take_front(numToDrop));
247 
248       auto ptrTy = LLVM::LLVMPointerType::get(packed.getType());
249       Value one = builder.create<LLVM::ConstantOp>(
250           loc, typeConverter.convertType(builder.getIndexType()),
251           builder.getIntegerAttr(builder.getIndexType(), 1));
252       Value allocated =
253           builder.create<LLVM::AllocaOp>(loc, ptrTy, one, /*alignment=*/0);
254       builder.create<LLVM::StoreOp>(loc, packed, allocated);
255       arg = allocated;
256     } else {
257       arg = wrapperArgsRange[0];
258     }
259 
260     args.push_back(arg);
261     wrapperArgsRange = wrapperArgsRange.drop_front(numToDrop);
262   }
263   assert(wrapperArgsRange.empty() && "did not map some of the arguments");
264 
265   auto call = builder.create<LLVM::CallOp>(loc, wrapperFunc, args);
266 
267   if (resultIsNowArg) {
268     Value result = builder.create<LLVM::LoadOp>(loc, args.front());
269     builder.create<LLVM::ReturnOp>(loc, ValueRange{result});
270   } else {
271     builder.create<LLVM::ReturnOp>(loc, call.getResults());
272   }
273 }
274 
275 namespace {
276 
277 struct FuncOpConversionBase : public ConvertOpToLLVMPattern<FuncOp> {
278 protected:
279   using ConvertOpToLLVMPattern<FuncOp>::ConvertOpToLLVMPattern;
280 
281   // Convert input FuncOp to LLVMFuncOp by using the LLVMTypeConverter provided
282   // to this legalization pattern.
283   LLVM::LLVMFuncOp
284   convertFuncOpToLLVMFuncOp(FuncOp funcOp,
285                             ConversionPatternRewriter &rewriter) const {
286     // Convert the original function arguments. They are converted using the
287     // LLVMTypeConverter provided to this legalization pattern.
288     auto varargsAttr = funcOp->getAttrOfType<BoolAttr>("func.varargs");
289     TypeConverter::SignatureConversion result(funcOp.getNumArguments());
290     auto llvmType = getTypeConverter()->convertFunctionSignature(
291         funcOp.getFunctionType(), varargsAttr && varargsAttr.getValue(),
292         result);
293     if (!llvmType)
294       return nullptr;
295 
296     // Propagate argument/result attributes to all converted arguments/result
297     // obtained after converting a given original argument/result.
298     SmallVector<NamedAttribute, 4> attributes;
299     filterFuncAttributes(funcOp->getAttrs(), /*filterArgAndResAttrs=*/true,
300                          attributes);
301     if (ArrayAttr resAttrDicts = funcOp.getAllResultAttrs()) {
302       assert(!resAttrDicts.empty() && "expected array to be non-empty");
303       auto newResAttrDicts =
304           (funcOp.getNumResults() == 1)
305               ? resAttrDicts
306               : rewriter.getArrayAttr(
307                     {wrapAsStructAttrs(rewriter, resAttrDicts)});
308       attributes.push_back(rewriter.getNamedAttr(
309           FunctionOpInterface::getResultDictAttrName(), newResAttrDicts));
310     }
311     if (ArrayAttr argAttrDicts = funcOp.getAllArgAttrs()) {
312       SmallVector<Attribute, 4> newArgAttrs(
313           llvmType.cast<LLVM::LLVMFunctionType>().getNumParams());
314       for (unsigned i = 0, e = funcOp.getNumArguments(); i < e; ++i) {
315         auto mapping = result.getInputMapping(i);
316         assert(mapping.hasValue() &&
317                "unexpected deletion of function argument");
318         for (size_t j = 0; j < mapping->size; ++j)
319           newArgAttrs[mapping->inputNo + j] = argAttrDicts[i];
320       }
321       attributes.push_back(
322           rewriter.getNamedAttr(FunctionOpInterface::getArgDictAttrName(),
323                                 rewriter.getArrayAttr(newArgAttrs)));
324     }
325     for (const auto &pair : llvm::enumerate(attributes)) {
326       if (pair.value().getName() == "llvm.linkage") {
327         attributes.erase(attributes.begin() + pair.index());
328         break;
329       }
330     }
331 
332     // Create an LLVM function, use external linkage by default until MLIR
333     // functions have linkage.
334     LLVM::Linkage linkage = LLVM::Linkage::External;
335     if (funcOp->hasAttr("llvm.linkage")) {
336       auto attr =
337           funcOp->getAttr("llvm.linkage").dyn_cast<mlir::LLVM::LinkageAttr>();
338       if (!attr) {
339         funcOp->emitError()
340             << "Contains llvm.linkage attribute not of type LLVM::LinkageAttr";
341         return nullptr;
342       }
343       linkage = attr.getLinkage();
344     }
345     auto newFuncOp = rewriter.create<LLVM::LLVMFuncOp>(
346         funcOp.getLoc(), funcOp.getName(), llvmType, linkage,
347         /*dsoLocal*/ false, attributes);
348     rewriter.inlineRegionBefore(funcOp.getBody(), newFuncOp.getBody(),
349                                 newFuncOp.end());
350     if (failed(rewriter.convertRegionTypes(&newFuncOp.getBody(), *typeConverter,
351                                            &result)))
352       return nullptr;
353 
354     return newFuncOp;
355   }
356 };
357 
358 /// FuncOp legalization pattern that converts MemRef arguments to pointers to
359 /// MemRef descriptors (LLVM struct data types) containing all the MemRef type
360 /// information.
361 static constexpr StringRef kEmitIfaceAttrName = "llvm.emit_c_interface";
362 struct FuncOpConversion : public FuncOpConversionBase {
363   FuncOpConversion(LLVMTypeConverter &converter)
364       : FuncOpConversionBase(converter) {}
365 
366   LogicalResult
367   matchAndRewrite(FuncOp funcOp, OpAdaptor adaptor,
368                   ConversionPatternRewriter &rewriter) const override {
369     auto newFuncOp = convertFuncOpToLLVMFuncOp(funcOp, rewriter);
370     if (!newFuncOp)
371       return failure();
372 
373     if (getTypeConverter()->getOptions().emitCWrappers ||
374         funcOp->getAttrOfType<UnitAttr>(kEmitIfaceAttrName)) {
375       if (newFuncOp.isExternal())
376         wrapExternalFunction(rewriter, funcOp.getLoc(), *getTypeConverter(),
377                              funcOp, newFuncOp);
378       else
379         wrapForExternalCallers(rewriter, funcOp.getLoc(), *getTypeConverter(),
380                                funcOp, newFuncOp);
381     }
382 
383     rewriter.eraseOp(funcOp);
384     return success();
385   }
386 };
387 
388 /// FuncOp legalization pattern that converts MemRef arguments to bare pointers
389 /// to the MemRef element type. This will impact the calling convention and ABI.
390 struct BarePtrFuncOpConversion : public FuncOpConversionBase {
391   using FuncOpConversionBase::FuncOpConversionBase;
392 
393   LogicalResult
394   matchAndRewrite(FuncOp funcOp, OpAdaptor adaptor,
395                   ConversionPatternRewriter &rewriter) const override {
396 
397     // TODO: bare ptr conversion could be handled by argument materialization
398     // and most of the code below would go away. But to do this, we would need a
399     // way to distinguish between FuncOp and other regions in the
400     // addArgumentMaterialization hook.
401 
402     // Store the type of memref-typed arguments before the conversion so that we
403     // can promote them to MemRef descriptor at the beginning of the function.
404     SmallVector<Type, 8> oldArgTypes =
405         llvm::to_vector<8>(funcOp.getFunctionType().getInputs());
406 
407     auto newFuncOp = convertFuncOpToLLVMFuncOp(funcOp, rewriter);
408     if (!newFuncOp)
409       return failure();
410     if (newFuncOp.getBody().empty()) {
411       rewriter.eraseOp(funcOp);
412       return success();
413     }
414 
415     // Promote bare pointers from memref arguments to memref descriptors at the
416     // beginning of the function so that all the memrefs in the function have a
417     // uniform representation.
418     Block *entryBlock = &newFuncOp.getBody().front();
419     auto blockArgs = entryBlock->getArguments();
420     assert(blockArgs.size() == oldArgTypes.size() &&
421            "The number of arguments and types doesn't match");
422 
423     OpBuilder::InsertionGuard guard(rewriter);
424     rewriter.setInsertionPointToStart(entryBlock);
425     for (auto it : llvm::zip(blockArgs, oldArgTypes)) {
426       BlockArgument arg = std::get<0>(it);
427       Type argTy = std::get<1>(it);
428 
429       // Unranked memrefs are not supported in the bare pointer calling
430       // convention. We should have bailed out before in the presence of
431       // unranked memrefs.
432       assert(!argTy.isa<UnrankedMemRefType>() &&
433              "Unranked memref is not supported");
434       auto memrefTy = argTy.dyn_cast<MemRefType>();
435       if (!memrefTy)
436         continue;
437 
438       // Replace barePtr with a placeholder (undef), promote barePtr to a ranked
439       // or unranked memref descriptor and replace placeholder with the last
440       // instruction of the memref descriptor.
441       // TODO: The placeholder is needed to avoid replacing barePtr uses in the
442       // MemRef descriptor instructions. We may want to have a utility in the
443       // rewriter to properly handle this use case.
444       Location loc = funcOp.getLoc();
445       auto placeholder = rewriter.create<LLVM::UndefOp>(
446           loc, getTypeConverter()->convertType(memrefTy));
447       rewriter.replaceUsesOfBlockArgument(arg, placeholder);
448 
449       Value desc = MemRefDescriptor::fromStaticShape(
450           rewriter, loc, *getTypeConverter(), memrefTy, arg);
451       rewriter.replaceOp(placeholder, {desc});
452     }
453 
454     rewriter.eraseOp(funcOp);
455     return success();
456   }
457 };
458 
459 struct ConstantOpLowering : public ConvertOpToLLVMPattern<func::ConstantOp> {
460   using ConvertOpToLLVMPattern<func::ConstantOp>::ConvertOpToLLVMPattern;
461 
462   LogicalResult
463   matchAndRewrite(func::ConstantOp op, OpAdaptor adaptor,
464                   ConversionPatternRewriter &rewriter) const override {
465     auto type = typeConverter->convertType(op.getResult().getType());
466     if (!type || !LLVM::isCompatibleType(type))
467       return rewriter.notifyMatchFailure(op, "failed to convert result type");
468 
469     auto newOp =
470         rewriter.create<LLVM::AddressOfOp>(op.getLoc(), type, op.getValue());
471     for (const NamedAttribute &attr : op->getAttrs()) {
472       if (attr.getName().strref() == "value")
473         continue;
474       newOp->setAttr(attr.getName(), attr.getValue());
475     }
476     rewriter.replaceOp(op, newOp->getResults());
477     return success();
478   }
479 };
480 
481 // A CallOp automatically promotes MemRefType to a sequence of alloca/store and
482 // passes the pointer to the MemRef across function boundaries.
483 template <typename CallOpType>
484 struct CallOpInterfaceLowering : public ConvertOpToLLVMPattern<CallOpType> {
485   using ConvertOpToLLVMPattern<CallOpType>::ConvertOpToLLVMPattern;
486   using Super = CallOpInterfaceLowering<CallOpType>;
487   using Base = ConvertOpToLLVMPattern<CallOpType>;
488 
489   LogicalResult
490   matchAndRewrite(CallOpType callOp, typename CallOpType::Adaptor adaptor,
491                   ConversionPatternRewriter &rewriter) const override {
492     // Pack the result types into a struct.
493     Type packedResult = nullptr;
494     unsigned numResults = callOp.getNumResults();
495     auto resultTypes = llvm::to_vector<4>(callOp.getResultTypes());
496 
497     if (numResults != 0) {
498       if (!(packedResult =
499                 this->getTypeConverter()->packFunctionResults(resultTypes)))
500         return failure();
501     }
502 
503     auto promoted = this->getTypeConverter()->promoteOperands(
504         callOp.getLoc(), /*opOperands=*/callOp->getOperands(),
505         adaptor.getOperands(), rewriter);
506     auto newOp = rewriter.create<LLVM::CallOp>(
507         callOp.getLoc(), packedResult ? TypeRange(packedResult) : TypeRange(),
508         promoted, callOp->getAttrs());
509 
510     SmallVector<Value, 4> results;
511     if (numResults < 2) {
512       // If < 2 results, packing did not do anything and we can just return.
513       results.append(newOp.result_begin(), newOp.result_end());
514     } else {
515       // Otherwise, it had been converted to an operation producing a structure.
516       // Extract individual results from the structure and return them as list.
517       results.reserve(numResults);
518       for (unsigned i = 0; i < numResults; ++i) {
519         auto type =
520             this->typeConverter->convertType(callOp.getResult(i).getType());
521         results.push_back(rewriter.create<LLVM::ExtractValueOp>(
522             callOp.getLoc(), type, newOp->getResult(0),
523             rewriter.getI64ArrayAttr(i)));
524       }
525     }
526 
527     if (this->getTypeConverter()->getOptions().useBarePtrCallConv) {
528       // For the bare-ptr calling convention, promote memref results to
529       // descriptors.
530       assert(results.size() == resultTypes.size() &&
531              "The number of arguments and types doesn't match");
532       this->getTypeConverter()->promoteBarePtrsToDescriptors(
533           rewriter, callOp.getLoc(), resultTypes, results);
534     } else if (failed(this->copyUnrankedDescriptors(rewriter, callOp.getLoc(),
535                                                     resultTypes, results,
536                                                     /*toDynamic=*/false))) {
537       return failure();
538     }
539 
540     rewriter.replaceOp(callOp, results);
541     return success();
542   }
543 };
544 
545 struct CallOpLowering : public CallOpInterfaceLowering<func::CallOp> {
546   using Super::Super;
547 };
548 
549 struct CallIndirectOpLowering
550     : public CallOpInterfaceLowering<func::CallIndirectOp> {
551   using Super::Super;
552 };
553 
554 struct UnrealizedConversionCastOpLowering
555     : public ConvertOpToLLVMPattern<UnrealizedConversionCastOp> {
556   using ConvertOpToLLVMPattern<
557       UnrealizedConversionCastOp>::ConvertOpToLLVMPattern;
558 
559   LogicalResult
560   matchAndRewrite(UnrealizedConversionCastOp op, OpAdaptor adaptor,
561                   ConversionPatternRewriter &rewriter) const override {
562     SmallVector<Type> convertedTypes;
563     if (succeeded(typeConverter->convertTypes(op.getOutputs().getTypes(),
564                                               convertedTypes)) &&
565         convertedTypes == adaptor.getInputs().getTypes()) {
566       rewriter.replaceOp(op, adaptor.getInputs());
567       return success();
568     }
569 
570     convertedTypes.clear();
571     if (succeeded(typeConverter->convertTypes(adaptor.getInputs().getTypes(),
572                                               convertedTypes)) &&
573         convertedTypes == op.getOutputs().getType()) {
574       rewriter.replaceOp(op, adaptor.getInputs());
575       return success();
576     }
577     return failure();
578   }
579 };
580 
581 // Special lowering pattern for `ReturnOps`.  Unlike all other operations,
582 // `ReturnOp` interacts with the function signature and must have as many
583 // operands as the function has return values.  Because in LLVM IR, functions
584 // can only return 0 or 1 value, we pack multiple values into a structure type.
585 // Emit `UndefOp` followed by `InsertValueOp`s to create such structure if
586 // necessary before returning it
587 struct ReturnOpLowering : public ConvertOpToLLVMPattern<func::ReturnOp> {
588   using ConvertOpToLLVMPattern<func::ReturnOp>::ConvertOpToLLVMPattern;
589 
590   LogicalResult
591   matchAndRewrite(func::ReturnOp op, OpAdaptor adaptor,
592                   ConversionPatternRewriter &rewriter) const override {
593     Location loc = op.getLoc();
594     unsigned numArguments = op.getNumOperands();
595     SmallVector<Value, 4> updatedOperands;
596 
597     if (getTypeConverter()->getOptions().useBarePtrCallConv) {
598       // For the bare-ptr calling convention, extract the aligned pointer to
599       // be returned from the memref descriptor.
600       for (auto it : llvm::zip(op->getOperands(), adaptor.getOperands())) {
601         Type oldTy = std::get<0>(it).getType();
602         Value newOperand = std::get<1>(it);
603         if (oldTy.isa<MemRefType>()) {
604           MemRefDescriptor memrefDesc(newOperand);
605           newOperand = memrefDesc.alignedPtr(rewriter, loc);
606         } else if (oldTy.isa<UnrankedMemRefType>()) {
607           // Unranked memref is not supported in the bare pointer calling
608           // convention.
609           return failure();
610         }
611         updatedOperands.push_back(newOperand);
612       }
613     } else {
614       updatedOperands = llvm::to_vector<4>(adaptor.getOperands());
615       (void)copyUnrankedDescriptors(rewriter, loc, op.getOperands().getTypes(),
616                                     updatedOperands,
617                                     /*toDynamic=*/true);
618     }
619 
620     // If ReturnOp has 0 or 1 operand, create it and return immediately.
621     if (numArguments == 0) {
622       rewriter.replaceOpWithNewOp<LLVM::ReturnOp>(op, TypeRange(), ValueRange(),
623                                                   op->getAttrs());
624       return success();
625     }
626     if (numArguments == 1) {
627       rewriter.replaceOpWithNewOp<LLVM::ReturnOp>(
628           op, TypeRange(), updatedOperands, op->getAttrs());
629       return success();
630     }
631 
632     // Otherwise, we need to pack the arguments into an LLVM struct type before
633     // returning.
634     auto packedType = getTypeConverter()->packFunctionResults(
635         llvm::to_vector<4>(op.getOperandTypes()));
636 
637     Value packed = rewriter.create<LLVM::UndefOp>(loc, packedType);
638     for (unsigned i = 0; i < numArguments; ++i) {
639       packed = rewriter.create<LLVM::InsertValueOp>(
640           loc, packedType, packed, updatedOperands[i],
641           rewriter.getI64ArrayAttr(i));
642     }
643     rewriter.replaceOpWithNewOp<LLVM::ReturnOp>(op, TypeRange(), packed,
644                                                 op->getAttrs());
645     return success();
646   }
647 };
648 } // namespace
649 
650 void mlir::populateFuncToLLVMFuncOpConversionPattern(
651     LLVMTypeConverter &converter, RewritePatternSet &patterns) {
652   if (converter.getOptions().useBarePtrCallConv)
653     patterns.add<BarePtrFuncOpConversion>(converter);
654   else
655     patterns.add<FuncOpConversion>(converter);
656 }
657 
658 void mlir::populateFuncToLLVMConversionPatterns(LLVMTypeConverter &converter,
659                                                 RewritePatternSet &patterns) {
660   populateFuncToLLVMFuncOpConversionPattern(converter, patterns);
661   // clang-format off
662   patterns.add<
663       CallIndirectOpLowering,
664       CallOpLowering,
665       ConstantOpLowering,
666       ReturnOpLowering>(converter);
667   // clang-format on
668 }
669 
670 namespace {
671 /// A pass converting Func operations into the LLVM IR dialect.
672 struct ConvertFuncToLLVMPass
673     : public ConvertFuncToLLVMBase<ConvertFuncToLLVMPass> {
674   ConvertFuncToLLVMPass() = default;
675   ConvertFuncToLLVMPass(bool useBarePtrCallConv, bool emitCWrappers,
676                         unsigned indexBitwidth, bool useAlignedAlloc,
677                         const llvm::DataLayout &dataLayout) {
678     this->useBarePtrCallConv = useBarePtrCallConv;
679     this->emitCWrappers = emitCWrappers;
680     this->indexBitwidth = indexBitwidth;
681     this->dataLayout = dataLayout.getStringRepresentation();
682   }
683 
684   /// Run the dialect converter on the module.
685   void runOnOperation() override {
686     if (useBarePtrCallConv && emitCWrappers) {
687       getOperation().emitError()
688           << "incompatible conversion options: bare-pointer calling convention "
689              "and C wrapper emission";
690       signalPassFailure();
691       return;
692     }
693     if (failed(LLVM::LLVMDialect::verifyDataLayoutString(
694             this->dataLayout, [this](const Twine &message) {
695               getOperation().emitError() << message.str();
696             }))) {
697       signalPassFailure();
698       return;
699     }
700 
701     ModuleOp m = getOperation();
702     const auto &dataLayoutAnalysis = getAnalysis<DataLayoutAnalysis>();
703 
704     LowerToLLVMOptions options(&getContext(),
705                                dataLayoutAnalysis.getAtOrAbove(m));
706     options.useBarePtrCallConv = useBarePtrCallConv;
707     options.emitCWrappers = emitCWrappers;
708     if (indexBitwidth != kDeriveIndexBitwidthFromDataLayout)
709       options.overrideIndexBitwidth(indexBitwidth);
710     options.dataLayout = llvm::DataLayout(this->dataLayout);
711 
712     LLVMTypeConverter typeConverter(&getContext(), options,
713                                     &dataLayoutAnalysis);
714 
715     RewritePatternSet patterns(&getContext());
716     populateFuncToLLVMConversionPatterns(typeConverter, patterns);
717 
718     // TODO: Remove these in favor of their dedicated conversion passes.
719     arith::populateArithmeticToLLVMConversionPatterns(typeConverter, patterns);
720     cf::populateControlFlowToLLVMConversionPatterns(typeConverter, patterns);
721 
722     LLVMConversionTarget target(getContext());
723     if (failed(applyPartialConversion(m, target, std::move(patterns))))
724       signalPassFailure();
725 
726     m->setAttr(LLVM::LLVMDialect::getDataLayoutAttrName(),
727                StringAttr::get(m.getContext(), this->dataLayout));
728   }
729 };
730 } // namespace
731 
732 std::unique_ptr<OperationPass<ModuleOp>> mlir::createConvertFuncToLLVMPass() {
733   return std::make_unique<ConvertFuncToLLVMPass>();
734 }
735 
736 std::unique_ptr<OperationPass<ModuleOp>>
737 mlir::createConvertFuncToLLVMPass(const LowerToLLVMOptions &options) {
738   auto allocLowering = options.allocLowering;
739   // There is no way to provide additional patterns for pass, so
740   // AllocLowering::None will always fail.
741   assert(allocLowering != LowerToLLVMOptions::AllocLowering::None &&
742          "ConvertFuncToLLVMPass doesn't support AllocLowering::None");
743   bool useAlignedAlloc =
744       (allocLowering == LowerToLLVMOptions::AllocLowering::AlignedAlloc);
745   return std::make_unique<ConvertFuncToLLVMPass>(
746       options.useBarePtrCallConv, options.emitCWrappers,
747       options.getIndexBitwidth(), useAlignedAlloc, options.dataLayout);
748 }
749