1 //===- ModuleTranslation.cpp - MLIR to LLVM 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 the translation between an MLIR LLVM dialect module and
10 // the corresponding LLVMIR module. It only handles core LLVM IR operations.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "mlir/Target/LLVMIR/ModuleTranslation.h"
15 
16 #include "DebugTranslation.h"
17 #include "mlir/Dialect/LLVMIR/LLVMDialect.h"
18 #include "mlir/Dialect/LLVMIR/Transforms/LegalizeForExport.h"
19 #include "mlir/Dialect/OpenMP/OpenMPDialect.h"
20 #include "mlir/IR/Attributes.h"
21 #include "mlir/IR/BuiltinOps.h"
22 #include "mlir/IR/BuiltinTypes.h"
23 #include "mlir/IR/RegionGraphTraits.h"
24 #include "mlir/Support/LLVM.h"
25 #include "mlir/Target/LLVMIR/LLVMTranslationInterface.h"
26 #include "mlir/Target/LLVMIR/TypeTranslation.h"
27 #include "llvm/ADT/TypeSwitch.h"
28 
29 #include "llvm/ADT/PostOrderIterator.h"
30 #include "llvm/ADT/SetVector.h"
31 #include "llvm/Frontend/OpenMP/OMPIRBuilder.h"
32 #include "llvm/IR/BasicBlock.h"
33 #include "llvm/IR/CFG.h"
34 #include "llvm/IR/Constants.h"
35 #include "llvm/IR/DerivedTypes.h"
36 #include "llvm/IR/IRBuilder.h"
37 #include "llvm/IR/InlineAsm.h"
38 #include "llvm/IR/LLVMContext.h"
39 #include "llvm/IR/MDBuilder.h"
40 #include "llvm/IR/Module.h"
41 #include "llvm/IR/Verifier.h"
42 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
43 #include "llvm/Transforms/Utils/Cloning.h"
44 
45 using namespace mlir;
46 using namespace mlir::LLVM;
47 using namespace mlir::LLVM::detail;
48 
49 // The include below has a static function unused in this translation unit,
50 // declare it as such to silence a warning.
51 static LLVM_ATTRIBUTE_UNUSED ::llvm::InlineAsm::AsmDialect
52 convertAsmDialectToLLVM(::mlir::LLVM::AsmDialect value);
53 
54 #include "mlir/Dialect/LLVMIR/LLVMConversionEnumsToLLVM.inc"
55 
56 /// Builds a constant of a sequential LLVM type `type`, potentially containing
57 /// other sequential types recursively, from the individual constant values
58 /// provided in `constants`. `shape` contains the number of elements in nested
59 /// sequential types. Reports errors at `loc` and returns nullptr on error.
60 static llvm::Constant *
61 buildSequentialConstant(ArrayRef<llvm::Constant *> &constants,
62                         ArrayRef<int64_t> shape, llvm::Type *type,
63                         Location loc) {
64   if (shape.empty()) {
65     llvm::Constant *result = constants.front();
66     constants = constants.drop_front();
67     return result;
68   }
69 
70   llvm::Type *elementType;
71   if (auto *arrayTy = dyn_cast<llvm::ArrayType>(type)) {
72     elementType = arrayTy->getElementType();
73   } else if (auto *vectorTy = dyn_cast<llvm::VectorType>(type)) {
74     elementType = vectorTy->getElementType();
75   } else {
76     emitError(loc) << "expected sequential LLVM types wrapping a scalar";
77     return nullptr;
78   }
79 
80   SmallVector<llvm::Constant *, 8> nested;
81   nested.reserve(shape.front());
82   for (int64_t i = 0; i < shape.front(); ++i) {
83     nested.push_back(buildSequentialConstant(constants, shape.drop_front(),
84                                              elementType, loc));
85     if (!nested.back())
86       return nullptr;
87   }
88 
89   if (shape.size() == 1 && type->isVectorTy())
90     return llvm::ConstantVector::get(nested);
91   return llvm::ConstantArray::get(
92       llvm::ArrayType::get(elementType, shape.front()), nested);
93 }
94 
95 /// Returns the first non-sequential type nested in sequential types.
96 static llvm::Type *getInnermostElementType(llvm::Type *type) {
97   do {
98     if (auto *arrayTy = dyn_cast<llvm::ArrayType>(type)) {
99       type = arrayTy->getElementType();
100     } else if (auto *vectorTy = dyn_cast<llvm::VectorType>(type)) {
101       type = vectorTy->getElementType();
102     } else {
103       return type;
104     }
105   } while (true);
106 }
107 
108 /// Create an LLVM IR constant of `llvmType` from the MLIR attribute `attr`.
109 /// This currently supports integer, floating point, splat and dense element
110 /// attributes and combinations thereof.  In case of error, report it to `loc`
111 /// and return nullptr.
112 llvm::Constant *mlir::LLVM::detail::getLLVMConstant(
113     llvm::Type *llvmType, Attribute attr, Location loc,
114     const ModuleTranslation &moduleTranslation) {
115   if (!attr)
116     return llvm::UndefValue::get(llvmType);
117   if (llvmType->isStructTy()) {
118     emitError(loc, "struct types are not supported in constants");
119     return nullptr;
120   }
121   // For integer types, we allow a mismatch in sizes as the index type in
122   // MLIR might have a different size than the index type in the LLVM module.
123   if (auto intAttr = attr.dyn_cast<IntegerAttr>())
124     return llvm::ConstantInt::get(
125         llvmType,
126         intAttr.getValue().sextOrTrunc(llvmType->getIntegerBitWidth()));
127   if (auto floatAttr = attr.dyn_cast<FloatAttr>())
128     return llvm::ConstantFP::get(llvmType, floatAttr.getValue());
129   if (auto funcAttr = attr.dyn_cast<FlatSymbolRefAttr>())
130     return llvm::ConstantExpr::getBitCast(
131         moduleTranslation.lookupFunction(funcAttr.getValue()), llvmType);
132   if (auto splatAttr = attr.dyn_cast<SplatElementsAttr>()) {
133     llvm::Type *elementType;
134     uint64_t numElements;
135     if (auto *arrayTy = dyn_cast<llvm::ArrayType>(llvmType)) {
136       elementType = arrayTy->getElementType();
137       numElements = arrayTy->getNumElements();
138     } else {
139       auto *vectorTy = cast<llvm::FixedVectorType>(llvmType);
140       elementType = vectorTy->getElementType();
141       numElements = vectorTy->getNumElements();
142     }
143     // Splat value is a scalar. Extract it only if the element type is not
144     // another sequence type. The recursion terminates because each step removes
145     // one outer sequential type.
146     bool elementTypeSequential =
147         isa<llvm::ArrayType, llvm::VectorType>(elementType);
148     llvm::Constant *child = getLLVMConstant(
149         elementType,
150         elementTypeSequential ? splatAttr : splatAttr.getSplatValue(), loc,
151         moduleTranslation);
152     if (!child)
153       return nullptr;
154     if (llvmType->isVectorTy())
155       return llvm::ConstantVector::getSplat(
156           llvm::ElementCount::get(numElements, /*Scalable=*/false), child);
157     if (llvmType->isArrayTy()) {
158       auto *arrayType = llvm::ArrayType::get(elementType, numElements);
159       SmallVector<llvm::Constant *, 8> constants(numElements, child);
160       return llvm::ConstantArray::get(arrayType, constants);
161     }
162   }
163 
164   if (auto elementsAttr = attr.dyn_cast<ElementsAttr>()) {
165     assert(elementsAttr.getType().hasStaticShape());
166     assert(elementsAttr.getNumElements() != 0 &&
167            "unexpected empty elements attribute");
168     assert(!elementsAttr.getType().getShape().empty() &&
169            "unexpected empty elements attribute shape");
170 
171     SmallVector<llvm::Constant *, 8> constants;
172     constants.reserve(elementsAttr.getNumElements());
173     llvm::Type *innermostType = getInnermostElementType(llvmType);
174     for (auto n : elementsAttr.getValues<Attribute>()) {
175       constants.push_back(
176           getLLVMConstant(innermostType, n, loc, moduleTranslation));
177       if (!constants.back())
178         return nullptr;
179     }
180     ArrayRef<llvm::Constant *> constantsRef = constants;
181     llvm::Constant *result = buildSequentialConstant(
182         constantsRef, elementsAttr.getType().getShape(), llvmType, loc);
183     assert(constantsRef.empty() && "did not consume all elemental constants");
184     return result;
185   }
186 
187   if (auto stringAttr = attr.dyn_cast<StringAttr>()) {
188     return llvm::ConstantDataArray::get(
189         moduleTranslation.getLLVMContext(),
190         ArrayRef<char>{stringAttr.getValue().data(),
191                        stringAttr.getValue().size()});
192   }
193   emitError(loc, "unsupported constant value");
194   return nullptr;
195 }
196 
197 ModuleTranslation::ModuleTranslation(Operation *module,
198                                      std::unique_ptr<llvm::Module> llvmModule)
199     : mlirModule(module), llvmModule(std::move(llvmModule)),
200       debugTranslation(
201           std::make_unique<DebugTranslation>(module, *this->llvmModule)),
202       typeTranslator(this->llvmModule->getContext()),
203       iface(module->getContext()) {
204   assert(satisfiesLLVMModule(mlirModule) &&
205          "mlirModule should honor LLVM's module semantics.");
206 }
207 ModuleTranslation::~ModuleTranslation() {
208   if (ompBuilder)
209     ompBuilder->finalize();
210 }
211 
212 /// Get the SSA value passed to the current block from the terminator operation
213 /// of its predecessor.
214 static Value getPHISourceValue(Block *current, Block *pred,
215                                unsigned numArguments, unsigned index) {
216   Operation &terminator = *pred->getTerminator();
217   if (isa<LLVM::BrOp>(terminator))
218     return terminator.getOperand(index);
219 
220   SuccessorRange successors = terminator.getSuccessors();
221   assert(std::adjacent_find(successors.begin(), successors.end()) ==
222              successors.end() &&
223          "successors with arguments in LLVM branches must be different blocks");
224   (void)successors;
225 
226   // For instructions that branch based on a condition value, we need to take
227   // the operands for the branch that was taken.
228   if (auto condBranchOp = dyn_cast<LLVM::CondBrOp>(terminator)) {
229     // For conditional branches, we take the operands from either the "true" or
230     // the "false" branch.
231     return condBranchOp.getSuccessor(0) == current
232                ? condBranchOp.trueDestOperands()[index]
233                : condBranchOp.falseDestOperands()[index];
234   }
235 
236   if (auto switchOp = dyn_cast<LLVM::SwitchOp>(terminator)) {
237     // For switches, we take the operands from either the default case, or from
238     // the case branch that was taken.
239     if (switchOp.defaultDestination() == current)
240       return switchOp.defaultOperands()[index];
241     for (auto i : llvm::enumerate(switchOp.caseDestinations()))
242       if (i.value() == current)
243         return switchOp.getCaseOperands(i.index())[index];
244   }
245 
246   llvm_unreachable("only branch or switch operations can be terminators of a "
247                    "block that has successors");
248 }
249 
250 /// Connect the PHI nodes to the results of preceding blocks.
251 void mlir::LLVM::detail::connectPHINodes(Region &region,
252                                          const ModuleTranslation &state) {
253   // Skip the first block, it cannot be branched to and its arguments correspond
254   // to the arguments of the LLVM function.
255   for (auto it = std::next(region.begin()), eit = region.end(); it != eit;
256        ++it) {
257     Block *bb = &*it;
258     llvm::BasicBlock *llvmBB = state.lookupBlock(bb);
259     auto phis = llvmBB->phis();
260     auto numArguments = bb->getNumArguments();
261     assert(numArguments == std::distance(phis.begin(), phis.end()));
262     for (auto &numberedPhiNode : llvm::enumerate(phis)) {
263       auto &phiNode = numberedPhiNode.value();
264       unsigned index = numberedPhiNode.index();
265       for (auto *pred : bb->getPredecessors()) {
266         // Find the LLVM IR block that contains the converted terminator
267         // instruction and use it in the PHI node. Note that this block is not
268         // necessarily the same as state.lookupBlock(pred), some operations
269         // (in particular, OpenMP operations using OpenMPIRBuilder) may have
270         // split the blocks.
271         llvm::Instruction *terminator =
272             state.lookupBranch(pred->getTerminator());
273         assert(terminator && "missing the mapping for a terminator");
274         phiNode.addIncoming(
275             state.lookupValue(getPHISourceValue(bb, pred, numArguments, index)),
276             terminator->getParent());
277       }
278     }
279   }
280 }
281 
282 /// Sort function blocks topologically.
283 llvm::SetVector<Block *>
284 mlir::LLVM::detail::getTopologicallySortedBlocks(Region &region) {
285   // For each block that has not been visited yet (i.e. that has no
286   // predecessors), add it to the list as well as its successors.
287   llvm::SetVector<Block *> blocks;
288   for (Block &b : region) {
289     if (blocks.count(&b) == 0) {
290       llvm::ReversePostOrderTraversal<Block *> traversal(&b);
291       blocks.insert(traversal.begin(), traversal.end());
292     }
293   }
294   assert(blocks.size() == region.getBlocks().size() &&
295          "some blocks are not sorted");
296 
297   return blocks;
298 }
299 
300 llvm::Value *mlir::LLVM::detail::createIntrinsicCall(
301     llvm::IRBuilderBase &builder, llvm::Intrinsic::ID intrinsic,
302     ArrayRef<llvm::Value *> args, ArrayRef<llvm::Type *> tys) {
303   llvm::Module *module = builder.GetInsertBlock()->getModule();
304   llvm::Function *fn = llvm::Intrinsic::getDeclaration(module, intrinsic, tys);
305   return builder.CreateCall(fn, args);
306 }
307 
308 /// Given a single MLIR operation, create the corresponding LLVM IR operation
309 /// using the `builder`.
310 LogicalResult
311 ModuleTranslation::convertOperation(Operation &opInst,
312                                     llvm::IRBuilderBase &builder) {
313   if (failed(iface.convertOperation(&opInst, builder, *this)))
314     return opInst.emitError("unsupported or non-LLVM operation: ")
315            << opInst.getName();
316 
317   return convertDialectAttributes(&opInst);
318 }
319 
320 /// Convert block to LLVM IR.  Unless `ignoreArguments` is set, emit PHI nodes
321 /// to define values corresponding to the MLIR block arguments.  These nodes
322 /// are not connected to the source basic blocks, which may not exist yet.  Uses
323 /// `builder` to construct the LLVM IR. Expects the LLVM IR basic block to have
324 /// been created for `bb` and included in the block mapping.  Inserts new
325 /// instructions at the end of the block and leaves `builder` in a state
326 /// suitable for further insertion into the end of the block.
327 LogicalResult ModuleTranslation::convertBlock(Block &bb, bool ignoreArguments,
328                                               llvm::IRBuilderBase &builder) {
329   builder.SetInsertPoint(lookupBlock(&bb));
330   auto *subprogram = builder.GetInsertBlock()->getParent()->getSubprogram();
331 
332   // Before traversing operations, make block arguments available through
333   // value remapping and PHI nodes, but do not add incoming edges for the PHI
334   // nodes just yet: those values may be defined by this or following blocks.
335   // This step is omitted if "ignoreArguments" is set.  The arguments of the
336   // first block have been already made available through the remapping of
337   // LLVM function arguments.
338   if (!ignoreArguments) {
339     auto predecessors = bb.getPredecessors();
340     unsigned numPredecessors =
341         std::distance(predecessors.begin(), predecessors.end());
342     for (auto arg : bb.getArguments()) {
343       auto wrappedType = arg.getType();
344       if (!isCompatibleType(wrappedType))
345         return emitError(bb.front().getLoc(),
346                          "block argument does not have an LLVM type");
347       llvm::Type *type = convertType(wrappedType);
348       llvm::PHINode *phi = builder.CreatePHI(type, numPredecessors);
349       mapValue(arg, phi);
350     }
351   }
352 
353   // Traverse operations.
354   for (auto &op : bb) {
355     // Set the current debug location within the builder.
356     builder.SetCurrentDebugLocation(
357         debugTranslation->translateLoc(op.getLoc(), subprogram));
358 
359     if (failed(convertOperation(op, builder)))
360       return failure();
361   }
362 
363   return success();
364 }
365 
366 /// A helper method to get the single Block in an operation honoring LLVM's
367 /// module requirements.
368 static Block &getModuleBody(Operation *module) {
369   return module->getRegion(0).front();
370 }
371 
372 /// Create named global variables that correspond to llvm.mlir.global
373 /// definitions.
374 LogicalResult ModuleTranslation::convertGlobals() {
375   for (auto op : getModuleBody(mlirModule).getOps<LLVM::GlobalOp>()) {
376     llvm::Type *type = convertType(op.getType());
377     llvm::Constant *cst = llvm::UndefValue::get(type);
378     if (op.getValueOrNull()) {
379       // String attributes are treated separately because they cannot appear as
380       // in-function constants and are thus not supported by getLLVMConstant.
381       if (auto strAttr = op.getValueOrNull().dyn_cast_or_null<StringAttr>()) {
382         cst = llvm::ConstantDataArray::getString(
383             llvmModule->getContext(), strAttr.getValue(), /*AddNull=*/false);
384         type = cst->getType();
385       } else if (!(cst = getLLVMConstant(type, op.getValueOrNull(), op.getLoc(),
386                                          *this))) {
387         return failure();
388       }
389     } else if (Block *initializer = op.getInitializerBlock()) {
390       llvm::IRBuilder<> builder(llvmModule->getContext());
391       for (auto &op : initializer->without_terminator()) {
392         if (failed(convertOperation(op, builder)) ||
393             !isa<llvm::Constant>(lookupValue(op.getResult(0))))
394           return emitError(op.getLoc(), "unemittable constant value");
395       }
396       ReturnOp ret = cast<ReturnOp>(initializer->getTerminator());
397       cst = cast<llvm::Constant>(lookupValue(ret.getOperand(0)));
398     }
399 
400     auto linkage = convertLinkageToLLVM(op.linkage());
401     bool anyExternalLinkage =
402         ((linkage == llvm::GlobalVariable::ExternalLinkage &&
403           isa<llvm::UndefValue>(cst)) ||
404          linkage == llvm::GlobalVariable::ExternalWeakLinkage);
405     auto addrSpace = op.addr_space();
406     auto *var = new llvm::GlobalVariable(
407         *llvmModule, type, op.constant(), linkage,
408         anyExternalLinkage ? nullptr : cst, op.sym_name(),
409         /*InsertBefore=*/nullptr, llvm::GlobalValue::NotThreadLocal, addrSpace);
410 
411     globalsMapping.try_emplace(op, var);
412   }
413 
414   return success();
415 }
416 
417 /// Attempts to add an attribute identified by `key`, optionally with the given
418 /// `value` to LLVM function `llvmFunc`. Reports errors at `loc` if any. If the
419 /// attribute has a kind known to LLVM IR, create the attribute of this kind,
420 /// otherwise keep it as a string attribute. Performs additional checks for
421 /// attributes known to have or not have a value in order to avoid assertions
422 /// inside LLVM upon construction.
423 static LogicalResult checkedAddLLVMFnAttribute(Location loc,
424                                                llvm::Function *llvmFunc,
425                                                StringRef key,
426                                                StringRef value = StringRef()) {
427   auto kind = llvm::Attribute::getAttrKindFromName(key);
428   if (kind == llvm::Attribute::None) {
429     llvmFunc->addFnAttr(key, value);
430     return success();
431   }
432 
433   if (llvm::Attribute::doesAttrKindHaveArgument(kind)) {
434     if (value.empty())
435       return emitError(loc) << "LLVM attribute '" << key << "' expects a value";
436 
437     int result;
438     if (!value.getAsInteger(/*Radix=*/0, result))
439       llvmFunc->addFnAttr(
440           llvm::Attribute::get(llvmFunc->getContext(), kind, result));
441     else
442       llvmFunc->addFnAttr(key, value);
443     return success();
444   }
445 
446   if (!value.empty())
447     return emitError(loc) << "LLVM attribute '" << key
448                           << "' does not expect a value, found '" << value
449                           << "'";
450 
451   llvmFunc->addFnAttr(kind);
452   return success();
453 }
454 
455 /// Attaches the attributes listed in the given array attribute to `llvmFunc`.
456 /// Reports error to `loc` if any and returns immediately. Expects `attributes`
457 /// to be an array attribute containing either string attributes, treated as
458 /// value-less LLVM attributes, or array attributes containing two string
459 /// attributes, with the first string being the name of the corresponding LLVM
460 /// attribute and the second string beings its value. Note that even integer
461 /// attributes are expected to have their values expressed as strings.
462 static LogicalResult
463 forwardPassthroughAttributes(Location loc, Optional<ArrayAttr> attributes,
464                              llvm::Function *llvmFunc) {
465   if (!attributes)
466     return success();
467 
468   for (Attribute attr : *attributes) {
469     if (auto stringAttr = attr.dyn_cast<StringAttr>()) {
470       if (failed(
471               checkedAddLLVMFnAttribute(loc, llvmFunc, stringAttr.getValue())))
472         return failure();
473       continue;
474     }
475 
476     auto arrayAttr = attr.dyn_cast<ArrayAttr>();
477     if (!arrayAttr || arrayAttr.size() != 2)
478       return emitError(loc)
479              << "expected 'passthrough' to contain string or array attributes";
480 
481     auto keyAttr = arrayAttr[0].dyn_cast<StringAttr>();
482     auto valueAttr = arrayAttr[1].dyn_cast<StringAttr>();
483     if (!keyAttr || !valueAttr)
484       return emitError(loc)
485              << "expected arrays within 'passthrough' to contain two strings";
486 
487     if (failed(checkedAddLLVMFnAttribute(loc, llvmFunc, keyAttr.getValue(),
488                                          valueAttr.getValue())))
489       return failure();
490   }
491   return success();
492 }
493 
494 LogicalResult ModuleTranslation::convertOneFunction(LLVMFuncOp func) {
495   // Clear the block, branch value mappings, they are only relevant within one
496   // function.
497   blockMapping.clear();
498   valueMapping.clear();
499   branchMapping.clear();
500   llvm::Function *llvmFunc = lookupFunction(func.getName());
501 
502   // Translate the debug information for this function.
503   debugTranslation->translate(func, *llvmFunc);
504 
505   // Add function arguments to the value remapping table.
506   // If there was noalias info then we decorate each argument accordingly.
507   unsigned int argIdx = 0;
508   for (auto kvp : llvm::zip(func.getArguments(), llvmFunc->args())) {
509     llvm::Argument &llvmArg = std::get<1>(kvp);
510     BlockArgument mlirArg = std::get<0>(kvp);
511 
512     if (auto attr = func.getArgAttrOfType<BoolAttr>(
513             argIdx, LLVMDialect::getNoAliasAttrName())) {
514       // NB: Attribute already verified to be boolean, so check if we can indeed
515       // attach the attribute to this argument, based on its type.
516       auto argTy = mlirArg.getType();
517       if (!argTy.isa<LLVM::LLVMPointerType>())
518         return func.emitError(
519             "llvm.noalias attribute attached to LLVM non-pointer argument");
520       if (attr.getValue())
521         llvmArg.addAttr(llvm::Attribute::AttrKind::NoAlias);
522     }
523 
524     if (auto attr = func.getArgAttrOfType<IntegerAttr>(
525             argIdx, LLVMDialect::getAlignAttrName())) {
526       // NB: Attribute already verified to be int, so check if we can indeed
527       // attach the attribute to this argument, based on its type.
528       auto argTy = mlirArg.getType();
529       if (!argTy.isa<LLVM::LLVMPointerType>())
530         return func.emitError(
531             "llvm.align attribute attached to LLVM non-pointer argument");
532       llvmArg.addAttrs(
533           llvm::AttrBuilder().addAlignmentAttr(llvm::Align(attr.getInt())));
534     }
535 
536     if (auto attr = func.getArgAttrOfType<UnitAttr>(argIdx, "llvm.sret")) {
537       auto argTy = mlirArg.getType();
538       if (!argTy.isa<LLVM::LLVMPointerType>())
539         return func.emitError(
540             "llvm.sret attribute attached to LLVM non-pointer argument");
541       llvmArg.addAttrs(llvm::AttrBuilder().addStructRetAttr(
542           llvmArg.getType()->getPointerElementType()));
543     }
544 
545     if (auto attr = func.getArgAttrOfType<UnitAttr>(argIdx, "llvm.byval")) {
546       auto argTy = mlirArg.getType();
547       if (!argTy.isa<LLVM::LLVMPointerType>())
548         return func.emitError(
549             "llvm.byval attribute attached to LLVM non-pointer argument");
550       llvmArg.addAttrs(llvm::AttrBuilder().addByValAttr(
551           llvmArg.getType()->getPointerElementType()));
552     }
553 
554     mapValue(mlirArg, &llvmArg);
555     argIdx++;
556   }
557 
558   // Check the personality and set it.
559   if (func.personality().hasValue()) {
560     llvm::Type *ty = llvm::Type::getInt8PtrTy(llvmFunc->getContext());
561     if (llvm::Constant *pfunc =
562             getLLVMConstant(ty, func.personalityAttr(), func.getLoc(), *this))
563       llvmFunc->setPersonalityFn(pfunc);
564   }
565 
566   // First, create all blocks so we can jump to them.
567   llvm::LLVMContext &llvmContext = llvmFunc->getContext();
568   for (auto &bb : func) {
569     auto *llvmBB = llvm::BasicBlock::Create(llvmContext);
570     llvmBB->insertInto(llvmFunc);
571     mapBlock(&bb, llvmBB);
572   }
573 
574   // Then, convert blocks one by one in topological order to ensure defs are
575   // converted before uses.
576   auto blocks = detail::getTopologicallySortedBlocks(func.getBody());
577   for (Block *bb : blocks) {
578     llvm::IRBuilder<> builder(llvmContext);
579     if (failed(convertBlock(*bb, bb->isEntryBlock(), builder)))
580       return failure();
581   }
582 
583   // After all blocks have been traversed and values mapped, connect the PHI
584   // nodes to the results of preceding blocks.
585   detail::connectPHINodes(func.getBody(), *this);
586 
587   // Finally, convert dialect attributes attached to the function.
588   return convertDialectAttributes(func);
589 }
590 
591 LogicalResult ModuleTranslation::convertDialectAttributes(Operation *op) {
592   for (NamedAttribute attribute : op->getDialectAttrs())
593     if (failed(iface.amendOperation(op, attribute, *this)))
594       return failure();
595   return success();
596 }
597 
598 /// Check whether the module contains only supported ops directly in its body.
599 static LogicalResult checkSupportedModuleOps(Operation *m) {
600   for (Operation &o : getModuleBody(m).getOperations())
601     if (!isa<LLVM::LLVMFuncOp, LLVM::GlobalOp>(&o) &&
602         !o.hasTrait<OpTrait::IsTerminator>())
603       return o.emitOpError("unsupported module-level operation");
604   return success();
605 }
606 
607 LogicalResult ModuleTranslation::convertFunctionSignatures() {
608   // Declare all functions first because there may be function calls that form a
609   // call graph with cycles, or global initializers that reference functions.
610   for (auto function : getModuleBody(mlirModule).getOps<LLVMFuncOp>()) {
611     llvm::FunctionCallee llvmFuncCst = llvmModule->getOrInsertFunction(
612         function.getName(),
613         cast<llvm::FunctionType>(convertType(function.getType())));
614     llvm::Function *llvmFunc = cast<llvm::Function>(llvmFuncCst.getCallee());
615     llvmFunc->setLinkage(convertLinkageToLLVM(function.linkage()));
616     mapFunction(function.getName(), llvmFunc);
617 
618     // Forward the pass-through attributes to LLVM.
619     if (failed(forwardPassthroughAttributes(function.getLoc(),
620                                             function.passthrough(), llvmFunc)))
621       return failure();
622   }
623 
624   return success();
625 }
626 
627 LogicalResult ModuleTranslation::convertFunctions() {
628   // Convert functions.
629   for (auto function : getModuleBody(mlirModule).getOps<LLVMFuncOp>()) {
630     // Ignore external functions.
631     if (function.isExternal())
632       continue;
633 
634     if (failed(convertOneFunction(function)))
635       return failure();
636   }
637 
638   return success();
639 }
640 
641 llvm::Type *ModuleTranslation::convertType(Type type) {
642   return typeTranslator.translateType(type);
643 }
644 
645 /// A helper to look up remapped operands in the value remapping table.`
646 SmallVector<llvm::Value *, 8>
647 ModuleTranslation::lookupValues(ValueRange values) {
648   SmallVector<llvm::Value *, 8> remapped;
649   remapped.reserve(values.size());
650   for (Value v : values)
651     remapped.push_back(lookupValue(v));
652   return remapped;
653 }
654 
655 const llvm::DILocation *
656 ModuleTranslation::translateLoc(Location loc, llvm::DILocalScope *scope) {
657   return debugTranslation->translateLoc(loc, scope);
658 }
659 
660 llvm::NamedMDNode *
661 ModuleTranslation::getOrInsertNamedModuleMetadata(StringRef name) {
662   return llvmModule->getOrInsertNamedMetadata(name);
663 }
664 
665 static std::unique_ptr<llvm::Module>
666 prepareLLVMModule(Operation *m, llvm::LLVMContext &llvmContext,
667                   StringRef name) {
668   m->getContext()->getOrLoadDialect<LLVM::LLVMDialect>();
669   auto llvmModule = std::make_unique<llvm::Module>(name, llvmContext);
670   if (auto dataLayoutAttr =
671           m->getAttr(LLVM::LLVMDialect::getDataLayoutAttrName()))
672     llvmModule->setDataLayout(dataLayoutAttr.cast<StringAttr>().getValue());
673   if (auto targetTripleAttr =
674           m->getAttr(LLVM::LLVMDialect::getTargetTripleAttrName()))
675     llvmModule->setTargetTriple(targetTripleAttr.cast<StringAttr>().getValue());
676 
677   // Inject declarations for `malloc` and `free` functions that can be used in
678   // memref allocation/deallocation coming from standard ops lowering.
679   llvm::IRBuilder<> builder(llvmContext);
680   llvmModule->getOrInsertFunction("malloc", builder.getInt8PtrTy(),
681                                   builder.getInt64Ty());
682   llvmModule->getOrInsertFunction("free", builder.getVoidTy(),
683                                   builder.getInt8PtrTy());
684 
685   return llvmModule;
686 }
687 
688 std::unique_ptr<llvm::Module>
689 mlir::translateModuleToLLVMIR(Operation *module, llvm::LLVMContext &llvmContext,
690                               StringRef name) {
691   if (!satisfiesLLVMModule(module))
692     return nullptr;
693   if (failed(checkSupportedModuleOps(module)))
694     return nullptr;
695   std::unique_ptr<llvm::Module> llvmModule =
696       prepareLLVMModule(module, llvmContext, name);
697 
698   LLVM::ensureDistinctSuccessors(module);
699 
700   ModuleTranslation translator(module, std::move(llvmModule));
701   if (failed(translator.convertFunctionSignatures()))
702     return nullptr;
703   if (failed(translator.convertGlobals()))
704     return nullptr;
705   if (failed(translator.convertFunctions()))
706     return nullptr;
707   if (llvm::verifyModule(*translator.llvmModule, &llvm::errs()))
708     return nullptr;
709 
710   return std::move(translator.llvmModule);
711 }
712