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