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/TypeToLLVM.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/IntrinsicsNVPTX.h"
39 #include "llvm/IR/LLVMContext.h"
40 #include "llvm/IR/MDBuilder.h"
41 #include "llvm/IR/Module.h"
42 #include "llvm/IR/Verifier.h"
43 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
44 #include "llvm/Transforms/Utils/Cloning.h"
45 #include "llvm/Transforms/Utils/ModuleUtils.h"
46 
47 using namespace mlir;
48 using namespace mlir::LLVM;
49 using namespace mlir::LLVM::detail;
50 
51 #include "mlir/Dialect/LLVMIR/LLVMConversionEnumsToLLVM.inc"
52 
53 /// Builds a constant of a sequential LLVM type `type`, potentially containing
54 /// other sequential types recursively, from the individual constant values
55 /// provided in `constants`. `shape` contains the number of elements in nested
56 /// sequential types. Reports errors at `loc` and returns nullptr on error.
57 static llvm::Constant *
58 buildSequentialConstant(ArrayRef<llvm::Constant *> &constants,
59                         ArrayRef<int64_t> shape, llvm::Type *type,
60                         Location loc) {
61   if (shape.empty()) {
62     llvm::Constant *result = constants.front();
63     constants = constants.drop_front();
64     return result;
65   }
66 
67   llvm::Type *elementType;
68   if (auto *arrayTy = dyn_cast<llvm::ArrayType>(type)) {
69     elementType = arrayTy->getElementType();
70   } else if (auto *vectorTy = dyn_cast<llvm::VectorType>(type)) {
71     elementType = vectorTy->getElementType();
72   } else {
73     emitError(loc) << "expected sequential LLVM types wrapping a scalar";
74     return nullptr;
75   }
76 
77   SmallVector<llvm::Constant *, 8> nested;
78   nested.reserve(shape.front());
79   for (int64_t i = 0; i < shape.front(); ++i) {
80     nested.push_back(buildSequentialConstant(constants, shape.drop_front(),
81                                              elementType, loc));
82     if (!nested.back())
83       return nullptr;
84   }
85 
86   if (shape.size() == 1 && type->isVectorTy())
87     return llvm::ConstantVector::get(nested);
88   return llvm::ConstantArray::get(
89       llvm::ArrayType::get(elementType, shape.front()), nested);
90 }
91 
92 /// Returns the first non-sequential type nested in sequential types.
93 static llvm::Type *getInnermostElementType(llvm::Type *type) {
94   do {
95     if (auto *arrayTy = dyn_cast<llvm::ArrayType>(type)) {
96       type = arrayTy->getElementType();
97     } else if (auto *vectorTy = dyn_cast<llvm::VectorType>(type)) {
98       type = vectorTy->getElementType();
99     } else {
100       return type;
101     }
102   } while (true);
103 }
104 
105 /// Convert a dense elements attribute to an LLVM IR constant using its raw data
106 /// storage if possible. This supports elements attributes of tensor or vector
107 /// type and avoids constructing separate objects for individual values of the
108 /// innermost dimension. Constants for other dimensions are still constructed
109 /// recursively. Returns null if constructing from raw data is not supported for
110 /// this type, e.g., element type is not a power-of-two-sized primitive. Reports
111 /// other errors at `loc`.
112 static llvm::Constant *
113 convertDenseElementsAttr(Location loc, DenseElementsAttr denseElementsAttr,
114                          llvm::Type *llvmType,
115                          const ModuleTranslation &moduleTranslation) {
116   if (!denseElementsAttr)
117     return nullptr;
118 
119   llvm::Type *innermostLLVMType = getInnermostElementType(llvmType);
120   if (!llvm::ConstantDataSequential::isElementTypeCompatible(innermostLLVMType))
121     return nullptr;
122 
123   ShapedType type = denseElementsAttr.getType();
124   if (type.getNumElements() == 0)
125     return nullptr;
126 
127   // Compute the shape of all dimensions but the innermost. Note that the
128   // innermost dimension may be that of the vector element type.
129   bool hasVectorElementType = type.getElementType().isa<VectorType>();
130   unsigned numAggregates =
131       denseElementsAttr.getNumElements() /
132       (hasVectorElementType ? 1
133                             : denseElementsAttr.getType().getShape().back());
134   ArrayRef<int64_t> outerShape = type.getShape();
135   if (!hasVectorElementType)
136     outerShape = outerShape.drop_back();
137 
138   // Handle the case of vector splat, LLVM has special support for it.
139   if (denseElementsAttr.isSplat() &&
140       (type.isa<VectorType>() || hasVectorElementType)) {
141     llvm::Constant *splatValue = LLVM::detail::getLLVMConstant(
142         innermostLLVMType, denseElementsAttr.getSplatValue(), loc,
143         moduleTranslation, /*isTopLevel=*/false);
144     llvm::Constant *splatVector =
145         llvm::ConstantDataVector::getSplat(0, splatValue);
146     SmallVector<llvm::Constant *> constants(numAggregates, splatVector);
147     ArrayRef<llvm::Constant *> constantsRef = constants;
148     return buildSequentialConstant(constantsRef, outerShape, llvmType, loc);
149   }
150   if (denseElementsAttr.isSplat())
151     return nullptr;
152 
153   // In case of non-splat, create a constructor for the innermost constant from
154   // a piece of raw data.
155   std::function<llvm::Constant *(StringRef)> buildCstData;
156   if (type.isa<TensorType>()) {
157     auto vectorElementType = type.getElementType().dyn_cast<VectorType>();
158     if (vectorElementType && vectorElementType.getRank() == 1) {
159       buildCstData = [&](StringRef data) {
160         return llvm::ConstantDataVector::getRaw(
161             data, vectorElementType.getShape().back(), innermostLLVMType);
162       };
163     } else if (!vectorElementType) {
164       buildCstData = [&](StringRef data) {
165         return llvm::ConstantDataArray::getRaw(data, type.getShape().back(),
166                                                innermostLLVMType);
167       };
168     }
169   } else if (type.isa<VectorType>()) {
170     buildCstData = [&](StringRef data) {
171       return llvm::ConstantDataVector::getRaw(data, type.getShape().back(),
172                                               innermostLLVMType);
173     };
174   }
175   if (!buildCstData)
176     return nullptr;
177 
178   // Create innermost constants and defer to the default constant creation
179   // mechanism for other dimensions.
180   SmallVector<llvm::Constant *> constants;
181   unsigned aggregateSize = denseElementsAttr.getType().getShape().back() *
182                            (innermostLLVMType->getScalarSizeInBits() / 8);
183   constants.reserve(numAggregates);
184   for (unsigned i = 0; i < numAggregates; ++i) {
185     StringRef data(denseElementsAttr.getRawData().data() + i * aggregateSize,
186                    aggregateSize);
187     constants.push_back(buildCstData(data));
188   }
189 
190   ArrayRef<llvm::Constant *> constantsRef = constants;
191   return buildSequentialConstant(constantsRef, outerShape, llvmType, loc);
192 }
193 
194 /// Create an LLVM IR constant of `llvmType` from the MLIR attribute `attr`.
195 /// This currently supports integer, floating point, splat and dense element
196 /// attributes and combinations thereof. Also, an array attribute with two
197 /// elements is supported to represent a complex constant.  In case of error,
198 /// report it to `loc` and return nullptr.
199 llvm::Constant *mlir::LLVM::detail::getLLVMConstant(
200     llvm::Type *llvmType, Attribute attr, Location loc,
201     const ModuleTranslation &moduleTranslation, bool isTopLevel) {
202   if (!attr)
203     return llvm::UndefValue::get(llvmType);
204   if (auto *structType = dyn_cast<::llvm::StructType>(llvmType)) {
205     if (!isTopLevel) {
206       emitError(loc, "nested struct types are not supported in constants");
207       return nullptr;
208     }
209     auto arrayAttr = attr.cast<ArrayAttr>();
210     llvm::Type *elementType = structType->getElementType(0);
211     llvm::Constant *real = getLLVMConstant(elementType, arrayAttr[0], loc,
212                                            moduleTranslation, false);
213     if (!real)
214       return nullptr;
215     llvm::Constant *imag = getLLVMConstant(elementType, arrayAttr[1], loc,
216                                            moduleTranslation, false);
217     if (!imag)
218       return nullptr;
219     return llvm::ConstantStruct::get(structType, {real, imag});
220   }
221   // For integer types, we allow a mismatch in sizes as the index type in
222   // MLIR might have a different size than the index type in the LLVM module.
223   if (auto intAttr = attr.dyn_cast<IntegerAttr>())
224     return llvm::ConstantInt::get(
225         llvmType,
226         intAttr.getValue().sextOrTrunc(llvmType->getIntegerBitWidth()));
227   if (auto floatAttr = attr.dyn_cast<FloatAttr>()) {
228     if (llvmType !=
229         llvm::Type::getFloatingPointTy(llvmType->getContext(),
230                                        floatAttr.getValue().getSemantics())) {
231       emitError(loc, "FloatAttr does not match expected type of the constant");
232       return nullptr;
233     }
234     return llvm::ConstantFP::get(llvmType, floatAttr.getValue());
235   }
236   if (auto funcAttr = attr.dyn_cast<FlatSymbolRefAttr>())
237     return llvm::ConstantExpr::getBitCast(
238         moduleTranslation.lookupFunction(funcAttr.getValue()), llvmType);
239   if (auto splatAttr = attr.dyn_cast<SplatElementsAttr>()) {
240     llvm::Type *elementType;
241     uint64_t numElements;
242     if (auto *arrayTy = dyn_cast<llvm::ArrayType>(llvmType)) {
243       elementType = arrayTy->getElementType();
244       numElements = arrayTy->getNumElements();
245     } else {
246       auto *vectorTy = cast<llvm::FixedVectorType>(llvmType);
247       elementType = vectorTy->getElementType();
248       numElements = vectorTy->getNumElements();
249     }
250     // Splat value is a scalar. Extract it only if the element type is not
251     // another sequence type. The recursion terminates because each step removes
252     // one outer sequential type.
253     bool elementTypeSequential =
254         isa<llvm::ArrayType, llvm::VectorType>(elementType);
255     llvm::Constant *child = getLLVMConstant(
256         elementType,
257         elementTypeSequential ? splatAttr : splatAttr.getSplatValue(), loc,
258         moduleTranslation, false);
259     if (!child)
260       return nullptr;
261     if (llvmType->isVectorTy())
262       return llvm::ConstantVector::getSplat(
263           llvm::ElementCount::get(numElements, /*Scalable=*/false), child);
264     if (llvmType->isArrayTy()) {
265       auto *arrayType = llvm::ArrayType::get(elementType, numElements);
266       SmallVector<llvm::Constant *, 8> constants(numElements, child);
267       return llvm::ConstantArray::get(arrayType, constants);
268     }
269   }
270 
271   // Try using raw elements data if possible.
272   if (llvm::Constant *result =
273           convertDenseElementsAttr(loc, attr.dyn_cast<DenseElementsAttr>(),
274                                    llvmType, moduleTranslation)) {
275     return result;
276   }
277 
278   // Fall back to element-by-element construction otherwise.
279   if (auto elementsAttr = attr.dyn_cast<ElementsAttr>()) {
280     assert(elementsAttr.getType().hasStaticShape());
281     assert(!elementsAttr.getType().getShape().empty() &&
282            "unexpected empty elements attribute shape");
283 
284     SmallVector<llvm::Constant *, 8> constants;
285     constants.reserve(elementsAttr.getNumElements());
286     llvm::Type *innermostType = getInnermostElementType(llvmType);
287     for (auto n : elementsAttr.getValues<Attribute>()) {
288       constants.push_back(
289           getLLVMConstant(innermostType, n, loc, moduleTranslation, false));
290       if (!constants.back())
291         return nullptr;
292     }
293     ArrayRef<llvm::Constant *> constantsRef = constants;
294     llvm::Constant *result = buildSequentialConstant(
295         constantsRef, elementsAttr.getType().getShape(), llvmType, loc);
296     assert(constantsRef.empty() && "did not consume all elemental constants");
297     return result;
298   }
299 
300   if (auto stringAttr = attr.dyn_cast<StringAttr>()) {
301     return llvm::ConstantDataArray::get(
302         moduleTranslation.getLLVMContext(),
303         ArrayRef<char>{stringAttr.getValue().data(),
304                        stringAttr.getValue().size()});
305   }
306   emitError(loc, "unsupported constant value");
307   return nullptr;
308 }
309 
310 ModuleTranslation::ModuleTranslation(Operation *module,
311                                      std::unique_ptr<llvm::Module> llvmModule)
312     : mlirModule(module), llvmModule(std::move(llvmModule)),
313       debugTranslation(
314           std::make_unique<DebugTranslation>(module, *this->llvmModule)),
315       typeTranslator(this->llvmModule->getContext()),
316       iface(module->getContext()) {
317   assert(satisfiesLLVMModule(mlirModule) &&
318          "mlirModule should honor LLVM's module semantics.");
319 }
320 ModuleTranslation::~ModuleTranslation() {
321   if (ompBuilder)
322     ompBuilder->finalize();
323 }
324 
325 void ModuleTranslation::forgetMapping(Region &region) {
326   SmallVector<Region *> toProcess;
327   toProcess.push_back(&region);
328   while (!toProcess.empty()) {
329     Region *current = toProcess.pop_back_val();
330     for (Block &block : *current) {
331       blockMapping.erase(&block);
332       for (Value arg : block.getArguments())
333         valueMapping.erase(arg);
334       for (Operation &op : block) {
335         for (Value value : op.getResults())
336           valueMapping.erase(value);
337         if (op.hasSuccessors())
338           branchMapping.erase(&op);
339         if (isa<LLVM::GlobalOp>(op))
340           globalsMapping.erase(&op);
341         accessGroupMetadataMapping.erase(&op);
342         llvm::append_range(
343             toProcess,
344             llvm::map_range(op.getRegions(), [](Region &r) { return &r; }));
345       }
346     }
347   }
348 }
349 
350 /// Get the SSA value passed to the current block from the terminator operation
351 /// of its predecessor.
352 static Value getPHISourceValue(Block *current, Block *pred,
353                                unsigned numArguments, unsigned index) {
354   Operation &terminator = *pred->getTerminator();
355   if (isa<LLVM::BrOp>(terminator))
356     return terminator.getOperand(index);
357 
358   SuccessorRange successors = terminator.getSuccessors();
359   assert(std::adjacent_find(successors.begin(), successors.end()) ==
360              successors.end() &&
361          "successors with arguments in LLVM branches must be different blocks");
362   (void)successors;
363 
364   // For instructions that branch based on a condition value, we need to take
365   // the operands for the branch that was taken.
366   if (auto condBranchOp = dyn_cast<LLVM::CondBrOp>(terminator)) {
367     // For conditional branches, we take the operands from either the "true" or
368     // the "false" branch.
369     return condBranchOp.getSuccessor(0) == current
370                ? condBranchOp.getTrueDestOperands()[index]
371                : condBranchOp.getFalseDestOperands()[index];
372   }
373 
374   if (auto switchOp = dyn_cast<LLVM::SwitchOp>(terminator)) {
375     // For switches, we take the operands from either the default case, or from
376     // the case branch that was taken.
377     if (switchOp.getDefaultDestination() == current)
378       return switchOp.getDefaultOperands()[index];
379     for (auto i : llvm::enumerate(switchOp.getCaseDestinations()))
380       if (i.value() == current)
381         return switchOp.getCaseOperands(i.index())[index];
382   }
383 
384   llvm_unreachable("only branch or switch operations can be terminators of a "
385                    "block that has successors");
386 }
387 
388 /// Connect the PHI nodes to the results of preceding blocks.
389 void mlir::LLVM::detail::connectPHINodes(Region &region,
390                                          const ModuleTranslation &state) {
391   // Skip the first block, it cannot be branched to and its arguments correspond
392   // to the arguments of the LLVM function.
393   for (auto it = std::next(region.begin()), eit = region.end(); it != eit;
394        ++it) {
395     Block *bb = &*it;
396     llvm::BasicBlock *llvmBB = state.lookupBlock(bb);
397     auto phis = llvmBB->phis();
398     auto numArguments = bb->getNumArguments();
399     assert(numArguments == std::distance(phis.begin(), phis.end()));
400     for (auto &numberedPhiNode : llvm::enumerate(phis)) {
401       auto &phiNode = numberedPhiNode.value();
402       unsigned index = numberedPhiNode.index();
403       for (auto *pred : bb->getPredecessors()) {
404         // Find the LLVM IR block that contains the converted terminator
405         // instruction and use it in the PHI node. Note that this block is not
406         // necessarily the same as state.lookupBlock(pred), some operations
407         // (in particular, OpenMP operations using OpenMPIRBuilder) may have
408         // split the blocks.
409         llvm::Instruction *terminator =
410             state.lookupBranch(pred->getTerminator());
411         assert(terminator && "missing the mapping for a terminator");
412         phiNode.addIncoming(
413             state.lookupValue(getPHISourceValue(bb, pred, numArguments, index)),
414             terminator->getParent());
415       }
416     }
417   }
418 }
419 
420 /// Sort function blocks topologically.
421 SetVector<Block *>
422 mlir::LLVM::detail::getTopologicallySortedBlocks(Region &region) {
423   // For each block that has not been visited yet (i.e. that has no
424   // predecessors), add it to the list as well as its successors.
425   SetVector<Block *> blocks;
426   for (Block &b : region) {
427     if (blocks.count(&b) == 0) {
428       llvm::ReversePostOrderTraversal<Block *> traversal(&b);
429       blocks.insert(traversal.begin(), traversal.end());
430     }
431   }
432   assert(blocks.size() == region.getBlocks().size() &&
433          "some blocks are not sorted");
434 
435   return blocks;
436 }
437 
438 llvm::Value *mlir::LLVM::detail::createIntrinsicCall(
439     llvm::IRBuilderBase &builder, llvm::Intrinsic::ID intrinsic,
440     ArrayRef<llvm::Value *> args, ArrayRef<llvm::Type *> tys) {
441   llvm::Module *module = builder.GetInsertBlock()->getModule();
442   llvm::Function *fn = llvm::Intrinsic::getDeclaration(module, intrinsic, tys);
443   return builder.CreateCall(fn, args);
444 }
445 
446 /// Given a single MLIR operation, create the corresponding LLVM IR operation
447 /// using the `builder`.
448 LogicalResult
449 ModuleTranslation::convertOperation(Operation &op,
450                                     llvm::IRBuilderBase &builder) {
451   const LLVMTranslationDialectInterface *opIface = iface.getInterfaceFor(&op);
452   if (!opIface)
453     return op.emitError("cannot be converted to LLVM IR: missing "
454                         "`LLVMTranslationDialectInterface` registration for "
455                         "dialect for op: ")
456            << op.getName();
457 
458   if (failed(opIface->convertOperation(&op, builder, *this)))
459     return op.emitError("LLVM Translation failed for operation: ")
460            << op.getName();
461 
462   return convertDialectAttributes(&op);
463 }
464 
465 /// Convert block to LLVM IR.  Unless `ignoreArguments` is set, emit PHI nodes
466 /// to define values corresponding to the MLIR block arguments.  These nodes
467 /// are not connected to the source basic blocks, which may not exist yet.  Uses
468 /// `builder` to construct the LLVM IR. Expects the LLVM IR basic block to have
469 /// been created for `bb` and included in the block mapping.  Inserts new
470 /// instructions at the end of the block and leaves `builder` in a state
471 /// suitable for further insertion into the end of the block.
472 LogicalResult ModuleTranslation::convertBlock(Block &bb, bool ignoreArguments,
473                                               llvm::IRBuilderBase &builder) {
474   builder.SetInsertPoint(lookupBlock(&bb));
475   auto *subprogram = builder.GetInsertBlock()->getParent()->getSubprogram();
476 
477   // Before traversing operations, make block arguments available through
478   // value remapping and PHI nodes, but do not add incoming edges for the PHI
479   // nodes just yet: those values may be defined by this or following blocks.
480   // This step is omitted if "ignoreArguments" is set.  The arguments of the
481   // first block have been already made available through the remapping of
482   // LLVM function arguments.
483   if (!ignoreArguments) {
484     auto predecessors = bb.getPredecessors();
485     unsigned numPredecessors =
486         std::distance(predecessors.begin(), predecessors.end());
487     for (auto arg : bb.getArguments()) {
488       auto wrappedType = arg.getType();
489       if (!isCompatibleType(wrappedType))
490         return emitError(bb.front().getLoc(),
491                          "block argument does not have an LLVM type");
492       llvm::Type *type = convertType(wrappedType);
493       llvm::PHINode *phi = builder.CreatePHI(type, numPredecessors);
494       mapValue(arg, phi);
495     }
496   }
497 
498   // Traverse operations.
499   for (auto &op : bb) {
500     // Set the current debug location within the builder.
501     builder.SetCurrentDebugLocation(
502         debugTranslation->translateLoc(op.getLoc(), subprogram));
503 
504     if (failed(convertOperation(op, builder)))
505       return failure();
506   }
507 
508   return success();
509 }
510 
511 /// A helper method to get the single Block in an operation honoring LLVM's
512 /// module requirements.
513 static Block &getModuleBody(Operation *module) {
514   return module->getRegion(0).front();
515 }
516 
517 /// A helper method to decide if a constant must not be set as a global variable
518 /// initializer. For an external linkage variable, the variable with an
519 /// initializer is considered externally visible and defined in this module, the
520 /// variable without an initializer is externally available and is defined
521 /// elsewhere.
522 static bool shouldDropGlobalInitializer(llvm::GlobalValue::LinkageTypes linkage,
523                                         llvm::Constant *cst) {
524   return (linkage == llvm::GlobalVariable::ExternalLinkage && !cst) ||
525          linkage == llvm::GlobalVariable::ExternalWeakLinkage;
526 }
527 
528 /// Sets the runtime preemption specifier of `gv` to dso_local if
529 /// `dsoLocalRequested` is true, otherwise it is left unchanged.
530 static void addRuntimePreemptionSpecifier(bool dsoLocalRequested,
531                                           llvm::GlobalValue *gv) {
532   if (dsoLocalRequested)
533     gv->setDSOLocal(true);
534 }
535 
536 /// Create named global variables that correspond to llvm.mlir.global
537 /// definitions. Convert llvm.global_ctors and global_dtors ops.
538 LogicalResult ModuleTranslation::convertGlobals() {
539   for (auto op : getModuleBody(mlirModule).getOps<LLVM::GlobalOp>()) {
540     llvm::Type *type = convertType(op.getType());
541     llvm::Constant *cst = nullptr;
542     if (op.getValueOrNull()) {
543       // String attributes are treated separately because they cannot appear as
544       // in-function constants and are thus not supported by getLLVMConstant.
545       if (auto strAttr = op.getValueOrNull().dyn_cast_or_null<StringAttr>()) {
546         cst = llvm::ConstantDataArray::getString(
547             llvmModule->getContext(), strAttr.getValue(), /*AddNull=*/false);
548         type = cst->getType();
549       } else if (!(cst = getLLVMConstant(type, op.getValueOrNull(), op.getLoc(),
550                                          *this))) {
551         return failure();
552       }
553     }
554 
555     auto linkage = convertLinkageToLLVM(op.getLinkage());
556     auto addrSpace = op.getAddrSpace();
557 
558     // LLVM IR requires constant with linkage other than external or weak
559     // external to have initializers. If MLIR does not provide an initializer,
560     // default to undef.
561     bool dropInitializer = shouldDropGlobalInitializer(linkage, cst);
562     if (!dropInitializer && !cst)
563       cst = llvm::UndefValue::get(type);
564     else if (dropInitializer && cst)
565       cst = nullptr;
566 
567     auto *var = new llvm::GlobalVariable(
568         *llvmModule, type, op.getConstant(), linkage, cst, op.getSymName(),
569         /*InsertBefore=*/nullptr, llvm::GlobalValue::NotThreadLocal, addrSpace);
570 
571     if (op.getUnnamedAddr().hasValue())
572       var->setUnnamedAddr(convertUnnamedAddrToLLVM(*op.getUnnamedAddr()));
573 
574     if (op.getSection().hasValue())
575       var->setSection(*op.getSection());
576 
577     addRuntimePreemptionSpecifier(op.getDsoLocal(), var);
578 
579     Optional<uint64_t> alignment = op.getAlignment();
580     if (alignment.hasValue())
581       var->setAlignment(llvm::MaybeAlign(alignment.getValue()));
582 
583     globalsMapping.try_emplace(op, var);
584   }
585 
586   // Convert global variable bodies. This is done after all global variables
587   // have been created in LLVM IR because a global body may refer to another
588   // global or itself. So all global variables need to be mapped first.
589   for (auto op : getModuleBody(mlirModule).getOps<LLVM::GlobalOp>()) {
590     if (Block *initializer = op.getInitializerBlock()) {
591       llvm::IRBuilder<> builder(llvmModule->getContext());
592       for (auto &op : initializer->without_terminator()) {
593         if (failed(convertOperation(op, builder)) ||
594             !isa<llvm::Constant>(lookupValue(op.getResult(0))))
595           return emitError(op.getLoc(), "unemittable constant value");
596       }
597       ReturnOp ret = cast<ReturnOp>(initializer->getTerminator());
598       llvm::Constant *cst =
599           cast<llvm::Constant>(lookupValue(ret.getOperand(0)));
600       auto *global = cast<llvm::GlobalVariable>(lookupGlobal(op));
601       if (!shouldDropGlobalInitializer(global->getLinkage(), cst))
602         global->setInitializer(cst);
603     }
604   }
605 
606   // Convert llvm.mlir.global_ctors and dtors.
607   for (Operation &op : getModuleBody(mlirModule)) {
608     auto ctorOp = dyn_cast<GlobalCtorsOp>(op);
609     auto dtorOp = dyn_cast<GlobalDtorsOp>(op);
610     if (!ctorOp && !dtorOp)
611       continue;
612     auto range = ctorOp ? llvm::zip(ctorOp.ctors(), ctorOp.priorities())
613                         : llvm::zip(dtorOp.dtors(), dtorOp.priorities());
614     auto appendGlobalFn =
615         ctorOp ? llvm::appendToGlobalCtors : llvm::appendToGlobalDtors;
616     for (auto symbolAndPriority : range) {
617       llvm::Function *f = lookupFunction(
618           std::get<0>(symbolAndPriority).cast<FlatSymbolRefAttr>().getValue());
619       appendGlobalFn(
620           *llvmModule.get(), f,
621           std::get<1>(symbolAndPriority).cast<IntegerAttr>().getInt(),
622           /*Data=*/nullptr);
623     }
624   }
625 
626   return success();
627 }
628 
629 /// Attempts to add an attribute identified by `key`, optionally with the given
630 /// `value` to LLVM function `llvmFunc`. Reports errors at `loc` if any. If the
631 /// attribute has a kind known to LLVM IR, create the attribute of this kind,
632 /// otherwise keep it as a string attribute. Performs additional checks for
633 /// attributes known to have or not have a value in order to avoid assertions
634 /// inside LLVM upon construction.
635 static LogicalResult checkedAddLLVMFnAttribute(Location loc,
636                                                llvm::Function *llvmFunc,
637                                                StringRef key,
638                                                StringRef value = StringRef()) {
639   auto kind = llvm::Attribute::getAttrKindFromName(key);
640   if (kind == llvm::Attribute::None) {
641     llvmFunc->addFnAttr(key, value);
642     return success();
643   }
644 
645   if (llvm::Attribute::isIntAttrKind(kind)) {
646     if (value.empty())
647       return emitError(loc) << "LLVM attribute '" << key << "' expects a value";
648 
649     int result;
650     if (!value.getAsInteger(/*Radix=*/0, result))
651       llvmFunc->addFnAttr(
652           llvm::Attribute::get(llvmFunc->getContext(), kind, result));
653     else
654       llvmFunc->addFnAttr(key, value);
655     return success();
656   }
657 
658   if (!value.empty())
659     return emitError(loc) << "LLVM attribute '" << key
660                           << "' does not expect a value, found '" << value
661                           << "'";
662 
663   llvmFunc->addFnAttr(kind);
664   return success();
665 }
666 
667 /// Attaches the attributes listed in the given array attribute to `llvmFunc`.
668 /// Reports error to `loc` if any and returns immediately. Expects `attributes`
669 /// to be an array attribute containing either string attributes, treated as
670 /// value-less LLVM attributes, or array attributes containing two string
671 /// attributes, with the first string being the name of the corresponding LLVM
672 /// attribute and the second string beings its value. Note that even integer
673 /// attributes are expected to have their values expressed as strings.
674 static LogicalResult
675 forwardPassthroughAttributes(Location loc, Optional<ArrayAttr> attributes,
676                              llvm::Function *llvmFunc) {
677   if (!attributes)
678     return success();
679 
680   for (Attribute attr : *attributes) {
681     if (auto stringAttr = attr.dyn_cast<StringAttr>()) {
682       if (failed(
683               checkedAddLLVMFnAttribute(loc, llvmFunc, stringAttr.getValue())))
684         return failure();
685       continue;
686     }
687 
688     auto arrayAttr = attr.dyn_cast<ArrayAttr>();
689     if (!arrayAttr || arrayAttr.size() != 2)
690       return emitError(loc)
691              << "expected 'passthrough' to contain string or array attributes";
692 
693     auto keyAttr = arrayAttr[0].dyn_cast<StringAttr>();
694     auto valueAttr = arrayAttr[1].dyn_cast<StringAttr>();
695     if (!keyAttr || !valueAttr)
696       return emitError(loc)
697              << "expected arrays within 'passthrough' to contain two strings";
698 
699     if (failed(checkedAddLLVMFnAttribute(loc, llvmFunc, keyAttr.getValue(),
700                                          valueAttr.getValue())))
701       return failure();
702   }
703   return success();
704 }
705 
706 LogicalResult ModuleTranslation::convertOneFunction(LLVMFuncOp func) {
707   // Clear the block, branch value mappings, they are only relevant within one
708   // function.
709   blockMapping.clear();
710   valueMapping.clear();
711   branchMapping.clear();
712   llvm::Function *llvmFunc = lookupFunction(func.getName());
713 
714   // Translate the debug information for this function.
715   debugTranslation->translate(func, *llvmFunc);
716 
717   // Add function arguments to the value remapping table.
718   // If there was noalias info then we decorate each argument accordingly.
719   unsigned int argIdx = 0;
720   for (auto kvp : llvm::zip(func.getArguments(), llvmFunc->args())) {
721     llvm::Argument &llvmArg = std::get<1>(kvp);
722     BlockArgument mlirArg = std::get<0>(kvp);
723 
724     if (auto attr = func.getArgAttrOfType<UnitAttr>(
725             argIdx, LLVMDialect::getNoAliasAttrName())) {
726       // NB: Attribute already verified to be boolean, so check if we can indeed
727       // attach the attribute to this argument, based on its type.
728       auto argTy = mlirArg.getType();
729       if (!argTy.isa<LLVM::LLVMPointerType>())
730         return func.emitError(
731             "llvm.noalias attribute attached to LLVM non-pointer argument");
732       llvmArg.addAttr(llvm::Attribute::AttrKind::NoAlias);
733     }
734 
735     if (auto attr = func.getArgAttrOfType<IntegerAttr>(
736             argIdx, LLVMDialect::getAlignAttrName())) {
737       // NB: Attribute already verified to be int, so check if we can indeed
738       // attach the attribute to this argument, based on its type.
739       auto argTy = mlirArg.getType();
740       if (!argTy.isa<LLVM::LLVMPointerType>())
741         return func.emitError(
742             "llvm.align attribute attached to LLVM non-pointer argument");
743       llvmArg.addAttrs(
744           llvm::AttrBuilder().addAlignmentAttr(llvm::Align(attr.getInt())));
745     }
746 
747     if (auto attr = func.getArgAttrOfType<UnitAttr>(argIdx, "llvm.sret")) {
748       auto argTy = mlirArg.getType();
749       if (!argTy.isa<LLVM::LLVMPointerType>())
750         return func.emitError(
751             "llvm.sret attribute attached to LLVM non-pointer argument");
752       llvmArg.addAttrs(llvm::AttrBuilder().addStructRetAttr(
753           llvmArg.getType()->getPointerElementType()));
754     }
755 
756     if (auto attr = func.getArgAttrOfType<UnitAttr>(argIdx, "llvm.byval")) {
757       auto argTy = mlirArg.getType();
758       if (!argTy.isa<LLVM::LLVMPointerType>())
759         return func.emitError(
760             "llvm.byval attribute attached to LLVM non-pointer argument");
761       llvmArg.addAttrs(llvm::AttrBuilder().addByValAttr(
762           llvmArg.getType()->getPointerElementType()));
763     }
764 
765     mapValue(mlirArg, &llvmArg);
766     argIdx++;
767   }
768 
769   // Check the personality and set it.
770   if (func.getPersonality().hasValue()) {
771     llvm::Type *ty = llvm::Type::getInt8PtrTy(llvmFunc->getContext());
772     if (llvm::Constant *pfunc = getLLVMConstant(ty, func.getPersonalityAttr(),
773                                                 func.getLoc(), *this))
774       llvmFunc->setPersonalityFn(pfunc);
775   }
776 
777   // First, create all blocks so we can jump to them.
778   llvm::LLVMContext &llvmContext = llvmFunc->getContext();
779   for (auto &bb : func) {
780     auto *llvmBB = llvm::BasicBlock::Create(llvmContext);
781     llvmBB->insertInto(llvmFunc);
782     mapBlock(&bb, llvmBB);
783   }
784 
785   // Then, convert blocks one by one in topological order to ensure defs are
786   // converted before uses.
787   auto blocks = detail::getTopologicallySortedBlocks(func.getBody());
788   for (Block *bb : blocks) {
789     llvm::IRBuilder<> builder(llvmContext);
790     if (failed(convertBlock(*bb, bb->isEntryBlock(), builder)))
791       return failure();
792   }
793 
794   // After all blocks have been traversed and values mapped, connect the PHI
795   // nodes to the results of preceding blocks.
796   detail::connectPHINodes(func.getBody(), *this);
797 
798   // Finally, convert dialect attributes attached to the function.
799   return convertDialectAttributes(func);
800 }
801 
802 LogicalResult ModuleTranslation::convertDialectAttributes(Operation *op) {
803   for (NamedAttribute attribute : op->getDialectAttrs())
804     if (failed(iface.amendOperation(op, attribute, *this)))
805       return failure();
806   return success();
807 }
808 
809 LogicalResult ModuleTranslation::convertFunctionSignatures() {
810   // Declare all functions first because there may be function calls that form a
811   // call graph with cycles, or global initializers that reference functions.
812   for (auto function : getModuleBody(mlirModule).getOps<LLVMFuncOp>()) {
813     llvm::FunctionCallee llvmFuncCst = llvmModule->getOrInsertFunction(
814         function.getName(),
815         cast<llvm::FunctionType>(convertType(function.getType())));
816     llvm::Function *llvmFunc = cast<llvm::Function>(llvmFuncCst.getCallee());
817     llvmFunc->setLinkage(convertLinkageToLLVM(function.getLinkage()));
818     mapFunction(function.getName(), llvmFunc);
819     addRuntimePreemptionSpecifier(function.getDsoLocal(), llvmFunc);
820 
821     // Forward the pass-through attributes to LLVM.
822     if (failed(forwardPassthroughAttributes(
823             function.getLoc(), function.getPassthrough(), llvmFunc)))
824       return failure();
825   }
826 
827   return success();
828 }
829 
830 LogicalResult ModuleTranslation::convertFunctions() {
831   // Convert functions.
832   for (auto function : getModuleBody(mlirModule).getOps<LLVMFuncOp>()) {
833     // Ignore external functions.
834     if (function.isExternal())
835       continue;
836 
837     if (failed(convertOneFunction(function)))
838       return failure();
839   }
840 
841   return success();
842 }
843 
844 llvm::MDNode *
845 ModuleTranslation::getAccessGroup(Operation &opInst,
846                                   SymbolRefAttr accessGroupRef) const {
847   auto metadataName = accessGroupRef.getRootReference();
848   auto accessGroupName = accessGroupRef.getLeafReference();
849   auto metadataOp = SymbolTable::lookupNearestSymbolFrom<LLVM::MetadataOp>(
850       opInst.getParentOp(), metadataName);
851   auto *accessGroupOp =
852       SymbolTable::lookupNearestSymbolFrom(metadataOp, accessGroupName);
853   return accessGroupMetadataMapping.lookup(accessGroupOp);
854 }
855 
856 LogicalResult ModuleTranslation::createAccessGroupMetadata() {
857   mlirModule->walk([&](LLVM::MetadataOp metadatas) {
858     metadatas.walk([&](LLVM::AccessGroupMetadataOp op) {
859       llvm::LLVMContext &ctx = llvmModule->getContext();
860       llvm::MDNode *accessGroup = llvm::MDNode::getDistinct(ctx, {});
861       accessGroupMetadataMapping.insert({op, accessGroup});
862     });
863   });
864   return success();
865 }
866 
867 void ModuleTranslation::setAccessGroupsMetadata(Operation *op,
868                                                 llvm::Instruction *inst) {
869   auto accessGroups =
870       op->getAttrOfType<ArrayAttr>(LLVMDialect::getAccessGroupsAttrName());
871   if (accessGroups && !accessGroups.empty()) {
872     llvm::Module *module = inst->getModule();
873     SmallVector<llvm::Metadata *> metadatas;
874     for (SymbolRefAttr accessGroupRef :
875          accessGroups.getAsRange<SymbolRefAttr>())
876       metadatas.push_back(getAccessGroup(*op, accessGroupRef));
877 
878     llvm::MDNode *unionMD = nullptr;
879     if (metadatas.size() == 1)
880       unionMD = llvm::cast<llvm::MDNode>(metadatas.front());
881     else if (metadatas.size() >= 2)
882       unionMD = llvm::MDNode::get(module->getContext(), metadatas);
883 
884     inst->setMetadata(module->getMDKindID("llvm.access.group"), unionMD);
885   }
886 }
887 
888 LogicalResult ModuleTranslation::createAliasScopeMetadata() {
889   mlirModule->walk([&](LLVM::MetadataOp metadatas) {
890     // Create the domains first, so they can be reference below in the scopes.
891     DenseMap<Operation *, llvm::MDNode *> aliasScopeDomainMetadataMapping;
892     metadatas.walk([&](LLVM::AliasScopeDomainMetadataOp op) {
893       llvm::LLVMContext &ctx = llvmModule->getContext();
894       llvm::SmallVector<llvm::Metadata *, 2> operands;
895       operands.push_back({}); // Placeholder for self-reference
896       if (Optional<StringRef> description = op.getDescription())
897         operands.push_back(llvm::MDString::get(ctx, description.getValue()));
898       llvm::MDNode *domain = llvm::MDNode::get(ctx, operands);
899       domain->replaceOperandWith(0, domain); // Self-reference for uniqueness
900       aliasScopeDomainMetadataMapping.insert({op, domain});
901     });
902 
903     // Now create the scopes, referencing the domains created above.
904     metadatas.walk([&](LLVM::AliasScopeMetadataOp op) {
905       llvm::LLVMContext &ctx = llvmModule->getContext();
906       assert(isa<LLVM::MetadataOp>(op->getParentOp()));
907       auto metadataOp = dyn_cast<LLVM::MetadataOp>(op->getParentOp());
908       Operation *domainOp =
909           SymbolTable::lookupNearestSymbolFrom(metadataOp, op.getDomainAttr());
910       llvm::MDNode *domain = aliasScopeDomainMetadataMapping.lookup(domainOp);
911       assert(domain && "Scope's domain should already be valid");
912       llvm::SmallVector<llvm::Metadata *, 3> operands;
913       operands.push_back({}); // Placeholder for self-reference
914       operands.push_back(domain);
915       if (Optional<StringRef> description = op.getDescription())
916         operands.push_back(llvm::MDString::get(ctx, description.getValue()));
917       llvm::MDNode *scope = llvm::MDNode::get(ctx, operands);
918       scope->replaceOperandWith(0, scope); // Self-reference for uniqueness
919       aliasScopeMetadataMapping.insert({op, scope});
920     });
921   });
922   return success();
923 }
924 
925 llvm::MDNode *
926 ModuleTranslation::getAliasScope(Operation &opInst,
927                                  SymbolRefAttr aliasScopeRef) const {
928   StringAttr metadataName = aliasScopeRef.getRootReference();
929   StringAttr scopeName = aliasScopeRef.getLeafReference();
930   auto metadataOp = SymbolTable::lookupNearestSymbolFrom<LLVM::MetadataOp>(
931       opInst.getParentOp(), metadataName);
932   Operation *aliasScopeOp =
933       SymbolTable::lookupNearestSymbolFrom(metadataOp, scopeName);
934   return aliasScopeMetadataMapping.lookup(aliasScopeOp);
935 }
936 
937 void ModuleTranslation::setAliasScopeMetadata(Operation *op,
938                                               llvm::Instruction *inst) {
939   auto populateScopeMetadata = [this, op, inst](StringRef attrName,
940                                                 StringRef llvmMetadataName) {
941     auto scopes = op->getAttrOfType<ArrayAttr>(attrName);
942     if (!scopes || scopes.empty())
943       return;
944     llvm::Module *module = inst->getModule();
945     SmallVector<llvm::Metadata *> scopeMDs;
946     for (SymbolRefAttr scopeRef : scopes.getAsRange<SymbolRefAttr>())
947       scopeMDs.push_back(getAliasScope(*op, scopeRef));
948     llvm::MDNode *unionMD = llvm::MDNode::get(module->getContext(), scopeMDs);
949     inst->setMetadata(module->getMDKindID(llvmMetadataName), unionMD);
950   };
951 
952   populateScopeMetadata(LLVMDialect::getAliasScopesAttrName(), "alias.scope");
953   populateScopeMetadata(LLVMDialect::getNoAliasScopesAttrName(), "noalias");
954 }
955 
956 llvm::Type *ModuleTranslation::convertType(Type type) {
957   return typeTranslator.translateType(type);
958 }
959 
960 /// A helper to look up remapped operands in the value remapping table.
961 SmallVector<llvm::Value *> ModuleTranslation::lookupValues(ValueRange values) {
962   SmallVector<llvm::Value *> remapped;
963   remapped.reserve(values.size());
964   for (Value v : values)
965     remapped.push_back(lookupValue(v));
966   return remapped;
967 }
968 
969 const llvm::DILocation *
970 ModuleTranslation::translateLoc(Location loc, llvm::DILocalScope *scope) {
971   return debugTranslation->translateLoc(loc, scope);
972 }
973 
974 llvm::NamedMDNode *
975 ModuleTranslation::getOrInsertNamedModuleMetadata(StringRef name) {
976   return llvmModule->getOrInsertNamedMetadata(name);
977 }
978 
979 void ModuleTranslation::StackFrame::anchor() {}
980 
981 static std::unique_ptr<llvm::Module>
982 prepareLLVMModule(Operation *m, llvm::LLVMContext &llvmContext,
983                   StringRef name) {
984   m->getContext()->getOrLoadDialect<LLVM::LLVMDialect>();
985   auto llvmModule = std::make_unique<llvm::Module>(name, llvmContext);
986   if (auto dataLayoutAttr =
987           m->getAttr(LLVM::LLVMDialect::getDataLayoutAttrName()))
988     llvmModule->setDataLayout(dataLayoutAttr.cast<StringAttr>().getValue());
989   if (auto targetTripleAttr =
990           m->getAttr(LLVM::LLVMDialect::getTargetTripleAttrName()))
991     llvmModule->setTargetTriple(targetTripleAttr.cast<StringAttr>().getValue());
992 
993   // Inject declarations for `malloc` and `free` functions that can be used in
994   // memref allocation/deallocation coming from standard ops lowering.
995   llvm::IRBuilder<> builder(llvmContext);
996   llvmModule->getOrInsertFunction("malloc", builder.getInt8PtrTy(),
997                                   builder.getInt64Ty());
998   llvmModule->getOrInsertFunction("free", builder.getVoidTy(),
999                                   builder.getInt8PtrTy());
1000 
1001   return llvmModule;
1002 }
1003 
1004 std::unique_ptr<llvm::Module>
1005 mlir::translateModuleToLLVMIR(Operation *module, llvm::LLVMContext &llvmContext,
1006                               StringRef name) {
1007   if (!satisfiesLLVMModule(module))
1008     return nullptr;
1009   std::unique_ptr<llvm::Module> llvmModule =
1010       prepareLLVMModule(module, llvmContext, name);
1011 
1012   LLVM::ensureDistinctSuccessors(module);
1013 
1014   ModuleTranslation translator(module, std::move(llvmModule));
1015   if (failed(translator.convertFunctionSignatures()))
1016     return nullptr;
1017   if (failed(translator.convertGlobals()))
1018     return nullptr;
1019   if (failed(translator.createAccessGroupMetadata()))
1020     return nullptr;
1021   if (failed(translator.createAliasScopeMetadata()))
1022     return nullptr;
1023   if (failed(translator.convertFunctions()))
1024     return nullptr;
1025 
1026   // Convert other top-level operations if possible.
1027   llvm::IRBuilder<> llvmBuilder(llvmContext);
1028   for (Operation &o : getModuleBody(module).getOperations()) {
1029     if (!isa<LLVM::LLVMFuncOp, LLVM::GlobalOp, LLVM::GlobalCtorsOp,
1030              LLVM::GlobalDtorsOp, LLVM::MetadataOp>(&o) &&
1031         !o.hasTrait<OpTrait::IsTerminator>() &&
1032         failed(translator.convertOperation(o, llvmBuilder))) {
1033       return nullptr;
1034     }
1035   }
1036 
1037   if (llvm::verifyModule(*translator.llvmModule, &llvm::errs()))
1038     return nullptr;
1039 
1040   return std::move(translator.llvmModule);
1041 }
1042