1cde4d5a6SJacques Pienaar //===- ModuleTranslation.cpp - MLIR to LLVM conversion --------------------===//
25d7231d8SStephan Herhut //
330857107SMehdi Amini // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
456222a06SMehdi Amini // See https://llvm.org/LICENSE.txt for license information.
556222a06SMehdi Amini // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
65d7231d8SStephan Herhut //
756222a06SMehdi Amini //===----------------------------------------------------------------------===//
85d7231d8SStephan Herhut //
95d7231d8SStephan Herhut // This file implements the translation between an MLIR LLVM dialect module and
105d7231d8SStephan Herhut // the corresponding LLVMIR module. It only handles core LLVM IR operations.
115d7231d8SStephan Herhut //
125d7231d8SStephan Herhut //===----------------------------------------------------------------------===//
135d7231d8SStephan Herhut 
145d7231d8SStephan Herhut #include "mlir/Target/LLVMIR/ModuleTranslation.h"
155d7231d8SStephan Herhut 
16c33d6970SRiver Riddle #include "DebugTranslation.h"
17ba0fa925SRiver Riddle #include "mlir/Dialect/LLVMIR/LLVMDialect.h"
18ce8f10d6SAlex Zinenko #include "mlir/Dialect/LLVMIR/Transforms/LegalizeForExport.h"
1992a295ebSKiran Chandramohan #include "mlir/Dialect/OpenMP/OpenMPDialect.h"
205d7231d8SStephan Herhut #include "mlir/IR/Attributes.h"
2165fcddffSRiver Riddle #include "mlir/IR/BuiltinOps.h"
2209f7a55fSRiver Riddle #include "mlir/IR/BuiltinTypes.h"
23d4568ed7SGeorge Mitenkov #include "mlir/IR/RegionGraphTraits.h"
245d7231d8SStephan Herhut #include "mlir/Support/LLVM.h"
25b77bac05SAlex Zinenko #include "mlir/Target/LLVMIR/LLVMTranslationInterface.h"
26929189a4SWilliam S. Moses #include "mlir/Target/LLVMIR/TypeToLLVM.h"
27ebf190fcSRiver Riddle #include "llvm/ADT/TypeSwitch.h"
285d7231d8SStephan Herhut 
29d4568ed7SGeorge Mitenkov #include "llvm/ADT/PostOrderIterator.h"
305d7231d8SStephan Herhut #include "llvm/ADT/SetVector.h"
3192a295ebSKiran Chandramohan #include "llvm/Frontend/OpenMP/OMPIRBuilder.h"
325d7231d8SStephan Herhut #include "llvm/IR/BasicBlock.h"
33d9067dcaSKiran Chandramohan #include "llvm/IR/CFG.h"
345d7231d8SStephan Herhut #include "llvm/IR/Constants.h"
355d7231d8SStephan Herhut #include "llvm/IR/DerivedTypes.h"
365d7231d8SStephan Herhut #include "llvm/IR/IRBuilder.h"
37047400edSNicolas Vasilache #include "llvm/IR/InlineAsm.h"
38875eb523SNavdeep Kumar #include "llvm/IR/IntrinsicsNVPTX.h"
395d7231d8SStephan Herhut #include "llvm/IR/LLVMContext.h"
4099d03f03SGeorge Mitenkov #include "llvm/IR/MDBuilder.h"
415d7231d8SStephan Herhut #include "llvm/IR/Module.h"
42ce8f10d6SAlex Zinenko #include "llvm/IR/Verifier.h"
43d9067dcaSKiran Chandramohan #include "llvm/Transforms/Utils/BasicBlockUtils.h"
445d7231d8SStephan Herhut #include "llvm/Transforms/Utils/Cloning.h"
455d7231d8SStephan Herhut 
462666b973SRiver Riddle using namespace mlir;
472666b973SRiver Riddle using namespace mlir::LLVM;
48c33d6970SRiver Riddle using namespace mlir::LLVM::detail;
495d7231d8SStephan Herhut 
50eb67bd78SAlex Zinenko #include "mlir/Dialect/LLVMIR/LLVMConversionEnumsToLLVM.inc"
51eb67bd78SAlex Zinenko 
52a922e231SAlex Zinenko /// Builds a constant of a sequential LLVM type `type`, potentially containing
53a922e231SAlex Zinenko /// other sequential types recursively, from the individual constant values
54a922e231SAlex Zinenko /// provided in `constants`. `shape` contains the number of elements in nested
55a922e231SAlex Zinenko /// sequential types. Reports errors at `loc` and returns nullptr on error.
56a4a42160SAlex Zinenko static llvm::Constant *
57a4a42160SAlex Zinenko buildSequentialConstant(ArrayRef<llvm::Constant *> &constants,
58a4a42160SAlex Zinenko                         ArrayRef<int64_t> shape, llvm::Type *type,
59a4a42160SAlex Zinenko                         Location loc) {
60a4a42160SAlex Zinenko   if (shape.empty()) {
61a4a42160SAlex Zinenko     llvm::Constant *result = constants.front();
62a4a42160SAlex Zinenko     constants = constants.drop_front();
63a4a42160SAlex Zinenko     return result;
64a4a42160SAlex Zinenko   }
65a4a42160SAlex Zinenko 
6668b03aeeSEli Friedman   llvm::Type *elementType;
6768b03aeeSEli Friedman   if (auto *arrayTy = dyn_cast<llvm::ArrayType>(type)) {
6868b03aeeSEli Friedman     elementType = arrayTy->getElementType();
6968b03aeeSEli Friedman   } else if (auto *vectorTy = dyn_cast<llvm::VectorType>(type)) {
7068b03aeeSEli Friedman     elementType = vectorTy->getElementType();
7168b03aeeSEli Friedman   } else {
72a4a42160SAlex Zinenko     emitError(loc) << "expected sequential LLVM types wrapping a scalar";
73a4a42160SAlex Zinenko     return nullptr;
74a4a42160SAlex Zinenko   }
75a4a42160SAlex Zinenko 
76a4a42160SAlex Zinenko   SmallVector<llvm::Constant *, 8> nested;
77a4a42160SAlex Zinenko   nested.reserve(shape.front());
78a4a42160SAlex Zinenko   for (int64_t i = 0; i < shape.front(); ++i) {
79a4a42160SAlex Zinenko     nested.push_back(buildSequentialConstant(constants, shape.drop_front(),
80a4a42160SAlex Zinenko                                              elementType, loc));
81a4a42160SAlex Zinenko     if (!nested.back())
82a4a42160SAlex Zinenko       return nullptr;
83a4a42160SAlex Zinenko   }
84a4a42160SAlex Zinenko 
85a4a42160SAlex Zinenko   if (shape.size() == 1 && type->isVectorTy())
86a4a42160SAlex Zinenko     return llvm::ConstantVector::get(nested);
87a4a42160SAlex Zinenko   return llvm::ConstantArray::get(
88a4a42160SAlex Zinenko       llvm::ArrayType::get(elementType, shape.front()), nested);
89a4a42160SAlex Zinenko }
90a4a42160SAlex Zinenko 
91fc817b09SKazuaki Ishizaki /// Returns the first non-sequential type nested in sequential types.
92a4a42160SAlex Zinenko static llvm::Type *getInnermostElementType(llvm::Type *type) {
9368b03aeeSEli Friedman   do {
9468b03aeeSEli Friedman     if (auto *arrayTy = dyn_cast<llvm::ArrayType>(type)) {
9568b03aeeSEli Friedman       type = arrayTy->getElementType();
9668b03aeeSEli Friedman     } else if (auto *vectorTy = dyn_cast<llvm::VectorType>(type)) {
9768b03aeeSEli Friedman       type = vectorTy->getElementType();
9868b03aeeSEli Friedman     } else {
99a4a42160SAlex Zinenko       return type;
100a4a42160SAlex Zinenko     }
1010881a4f1SAlex Zinenko   } while (true);
10268b03aeeSEli Friedman }
103a4a42160SAlex Zinenko 
104*f9be7a7aSAlex Zinenko /// Convert a dense elements attribute to an LLVM IR constant using its raw data
105*f9be7a7aSAlex Zinenko /// storage if possible. This supports elements attributes of tensor or vector
106*f9be7a7aSAlex Zinenko /// type and avoids constructing separate objects for individual values of the
107*f9be7a7aSAlex Zinenko /// innermost dimension. Constants for other dimensions are still constructed
108*f9be7a7aSAlex Zinenko /// recursively. Returns null if constructing from raw data is not supported for
109*f9be7a7aSAlex Zinenko /// this type, e.g., element type is not a power-of-two-sized primitive. Reports
110*f9be7a7aSAlex Zinenko /// other errors at `loc`.
111*f9be7a7aSAlex Zinenko static llvm::Constant *
112*f9be7a7aSAlex Zinenko convertDenseElementsAttr(Location loc, DenseElementsAttr denseElementsAttr,
113*f9be7a7aSAlex Zinenko                          llvm::Type *llvmType,
114*f9be7a7aSAlex Zinenko                          const ModuleTranslation &moduleTranslation) {
115*f9be7a7aSAlex Zinenko   if (!denseElementsAttr)
116*f9be7a7aSAlex Zinenko     return nullptr;
117*f9be7a7aSAlex Zinenko 
118*f9be7a7aSAlex Zinenko   llvm::Type *innermostLLVMType = getInnermostElementType(llvmType);
119*f9be7a7aSAlex Zinenko   if (!llvm::ConstantDataSequential::isElementTypeCompatible(innermostLLVMType))
120*f9be7a7aSAlex Zinenko     return nullptr;
121*f9be7a7aSAlex Zinenko 
122*f9be7a7aSAlex Zinenko   // Compute the shape of all dimensions but the innermost. Note that the
123*f9be7a7aSAlex Zinenko   // innermost dimension may be that of the vector element type.
124*f9be7a7aSAlex Zinenko   ShapedType type = denseElementsAttr.getType();
125*f9be7a7aSAlex Zinenko   bool hasVectorElementType = type.getElementType().isa<VectorType>();
126*f9be7a7aSAlex Zinenko   unsigned numAggregates =
127*f9be7a7aSAlex Zinenko       denseElementsAttr.getNumElements() /
128*f9be7a7aSAlex Zinenko       (hasVectorElementType ? 1
129*f9be7a7aSAlex Zinenko                             : denseElementsAttr.getType().getShape().back());
130*f9be7a7aSAlex Zinenko   ArrayRef<int64_t> outerShape = type.getShape();
131*f9be7a7aSAlex Zinenko   if (!hasVectorElementType)
132*f9be7a7aSAlex Zinenko     outerShape = outerShape.drop_back();
133*f9be7a7aSAlex Zinenko 
134*f9be7a7aSAlex Zinenko   // Handle the case of vector splat, LLVM has special support for it.
135*f9be7a7aSAlex Zinenko   if (denseElementsAttr.isSplat() &&
136*f9be7a7aSAlex Zinenko       (type.isa<VectorType>() || hasVectorElementType)) {
137*f9be7a7aSAlex Zinenko     llvm::Constant *splatValue = LLVM::detail::getLLVMConstant(
138*f9be7a7aSAlex Zinenko         innermostLLVMType, denseElementsAttr.getSplatValue(), loc,
139*f9be7a7aSAlex Zinenko         moduleTranslation, /*isTopLevel=*/false);
140*f9be7a7aSAlex Zinenko     llvm::Constant *splatVector =
141*f9be7a7aSAlex Zinenko         llvm::ConstantDataVector::getSplat(0, splatValue);
142*f9be7a7aSAlex Zinenko     SmallVector<llvm::Constant *> constants(numAggregates, splatVector);
143*f9be7a7aSAlex Zinenko     ArrayRef<llvm::Constant *> constantsRef = constants;
144*f9be7a7aSAlex Zinenko     return buildSequentialConstant(constantsRef, outerShape, llvmType, loc);
145*f9be7a7aSAlex Zinenko   }
146*f9be7a7aSAlex Zinenko   if (denseElementsAttr.isSplat())
147*f9be7a7aSAlex Zinenko     return nullptr;
148*f9be7a7aSAlex Zinenko 
149*f9be7a7aSAlex Zinenko   // In case of non-splat, create a constructor for the innermost constant from
150*f9be7a7aSAlex Zinenko   // a piece of raw data.
151*f9be7a7aSAlex Zinenko   std::function<llvm::Constant *(StringRef)> buildCstData;
152*f9be7a7aSAlex Zinenko   if (type.isa<TensorType>()) {
153*f9be7a7aSAlex Zinenko     auto vectorElementType = type.getElementType().dyn_cast<VectorType>();
154*f9be7a7aSAlex Zinenko     if (vectorElementType && vectorElementType.getRank() == 1) {
155*f9be7a7aSAlex Zinenko       buildCstData = [&](StringRef data) {
156*f9be7a7aSAlex Zinenko         return llvm::ConstantDataVector::getRaw(
157*f9be7a7aSAlex Zinenko             data, vectorElementType.getShape().back(), innermostLLVMType);
158*f9be7a7aSAlex Zinenko       };
159*f9be7a7aSAlex Zinenko     } else if (!vectorElementType) {
160*f9be7a7aSAlex Zinenko       buildCstData = [&](StringRef data) {
161*f9be7a7aSAlex Zinenko         return llvm::ConstantDataArray::getRaw(data, type.getShape().back(),
162*f9be7a7aSAlex Zinenko                                                innermostLLVMType);
163*f9be7a7aSAlex Zinenko       };
164*f9be7a7aSAlex Zinenko     }
165*f9be7a7aSAlex Zinenko   } else if (type.isa<VectorType>()) {
166*f9be7a7aSAlex Zinenko     buildCstData = [&](StringRef data) {
167*f9be7a7aSAlex Zinenko       return llvm::ConstantDataVector::getRaw(data, type.getShape().back(),
168*f9be7a7aSAlex Zinenko                                               innermostLLVMType);
169*f9be7a7aSAlex Zinenko     };
170*f9be7a7aSAlex Zinenko   }
171*f9be7a7aSAlex Zinenko   if (!buildCstData)
172*f9be7a7aSAlex Zinenko     return nullptr;
173*f9be7a7aSAlex Zinenko 
174*f9be7a7aSAlex Zinenko   // Create innermost constants and defer to the default constant creation
175*f9be7a7aSAlex Zinenko   // mechanism for other dimensions.
176*f9be7a7aSAlex Zinenko   SmallVector<llvm::Constant *> constants;
177*f9be7a7aSAlex Zinenko   unsigned aggregateSize = denseElementsAttr.getType().getShape().back() *
178*f9be7a7aSAlex Zinenko                            (innermostLLVMType->getScalarSizeInBits() / 8);
179*f9be7a7aSAlex Zinenko   constants.reserve(numAggregates);
180*f9be7a7aSAlex Zinenko   for (unsigned i = 0; i < numAggregates; ++i) {
181*f9be7a7aSAlex Zinenko     StringRef data(denseElementsAttr.getRawData().data() + i * aggregateSize,
182*f9be7a7aSAlex Zinenko                    aggregateSize);
183*f9be7a7aSAlex Zinenko     constants.push_back(buildCstData(data));
184*f9be7a7aSAlex Zinenko   }
185*f9be7a7aSAlex Zinenko 
186*f9be7a7aSAlex Zinenko   ArrayRef<llvm::Constant *> constantsRef = constants;
187*f9be7a7aSAlex Zinenko   return buildSequentialConstant(constantsRef, outerShape, llvmType, loc);
188*f9be7a7aSAlex Zinenko }
189*f9be7a7aSAlex Zinenko 
1902666b973SRiver Riddle /// Create an LLVM IR constant of `llvmType` from the MLIR attribute `attr`.
1912666b973SRiver Riddle /// This currently supports integer, floating point, splat and dense element
1925ef21506SAdrian Kuegel /// attributes and combinations thereof. Also, an array attribute with two
1935ef21506SAdrian Kuegel /// elements is supported to represent a complex constant.  In case of error,
1945ef21506SAdrian Kuegel /// report it to `loc` and return nullptr.
195176379e0SAlex Zinenko llvm::Constant *mlir::LLVM::detail::getLLVMConstant(
196176379e0SAlex Zinenko     llvm::Type *llvmType, Attribute attr, Location loc,
1975ef21506SAdrian Kuegel     const ModuleTranslation &moduleTranslation, bool isTopLevel) {
19833a3a91bSChristian Sigg   if (!attr)
19933a3a91bSChristian Sigg     return llvm::UndefValue::get(llvmType);
2005ef21506SAdrian Kuegel   if (auto *structType = dyn_cast<::llvm::StructType>(llvmType)) {
2015ef21506SAdrian Kuegel     if (!isTopLevel) {
2025ef21506SAdrian Kuegel       emitError(loc, "nested struct types are not supported in constants");
203a4a42160SAlex Zinenko       return nullptr;
204a4a42160SAlex Zinenko     }
2055ef21506SAdrian Kuegel     auto arrayAttr = attr.cast<ArrayAttr>();
2065ef21506SAdrian Kuegel     llvm::Type *elementType = structType->getElementType(0);
2075ef21506SAdrian Kuegel     llvm::Constant *real = getLLVMConstant(elementType, arrayAttr[0], loc,
2085ef21506SAdrian Kuegel                                            moduleTranslation, false);
2095ef21506SAdrian Kuegel     if (!real)
2105ef21506SAdrian Kuegel       return nullptr;
2115ef21506SAdrian Kuegel     llvm::Constant *imag = getLLVMConstant(elementType, arrayAttr[1], loc,
2125ef21506SAdrian Kuegel                                            moduleTranslation, false);
2135ef21506SAdrian Kuegel     if (!imag)
2145ef21506SAdrian Kuegel       return nullptr;
2155ef21506SAdrian Kuegel     return llvm::ConstantStruct::get(structType, {real, imag});
2165ef21506SAdrian Kuegel   }
217ac9d742bSStephan Herhut   // For integer types, we allow a mismatch in sizes as the index type in
218ac9d742bSStephan Herhut   // MLIR might have a different size than the index type in the LLVM module.
2195d7231d8SStephan Herhut   if (auto intAttr = attr.dyn_cast<IntegerAttr>())
220ac9d742bSStephan Herhut     return llvm::ConstantInt::get(
221ac9d742bSStephan Herhut         llvmType,
222ac9d742bSStephan Herhut         intAttr.getValue().sextOrTrunc(llvmType->getIntegerBitWidth()));
2235ef21506SAdrian Kuegel   if (auto floatAttr = attr.dyn_cast<FloatAttr>()) {
2245ef21506SAdrian Kuegel     if (llvmType !=
2255ef21506SAdrian Kuegel         llvm::Type::getFloatingPointTy(llvmType->getContext(),
2265ef21506SAdrian Kuegel                                        floatAttr.getValue().getSemantics())) {
2275ef21506SAdrian Kuegel       emitError(loc, "FloatAttr does not match expected type of the constant");
2285ef21506SAdrian Kuegel       return nullptr;
2295ef21506SAdrian Kuegel     }
2305d7231d8SStephan Herhut     return llvm::ConstantFP::get(llvmType, floatAttr.getValue());
2315ef21506SAdrian Kuegel   }
2329b9c647cSRiver Riddle   if (auto funcAttr = attr.dyn_cast<FlatSymbolRefAttr>())
233176379e0SAlex Zinenko     return llvm::ConstantExpr::getBitCast(
234176379e0SAlex Zinenko         moduleTranslation.lookupFunction(funcAttr.getValue()), llvmType);
2355d7231d8SStephan Herhut   if (auto splatAttr = attr.dyn_cast<SplatElementsAttr>()) {
23668b03aeeSEli Friedman     llvm::Type *elementType;
23768b03aeeSEli Friedman     uint64_t numElements;
23868b03aeeSEli Friedman     if (auto *arrayTy = dyn_cast<llvm::ArrayType>(llvmType)) {
23968b03aeeSEli Friedman       elementType = arrayTy->getElementType();
24068b03aeeSEli Friedman       numElements = arrayTy->getNumElements();
24168b03aeeSEli Friedman     } else {
2425cba1c63SChristopher Tetreault       auto *vectorTy = cast<llvm::FixedVectorType>(llvmType);
24368b03aeeSEli Friedman       elementType = vectorTy->getElementType();
24468b03aeeSEli Friedman       numElements = vectorTy->getNumElements();
24568b03aeeSEli Friedman     }
246d6ea8ff0SAlex Zinenko     // Splat value is a scalar. Extract it only if the element type is not
247d6ea8ff0SAlex Zinenko     // another sequence type. The recursion terminates because each step removes
248d6ea8ff0SAlex Zinenko     // one outer sequential type.
24968b03aeeSEli Friedman     bool elementTypeSequential =
250d891d738SRahul Joshi         isa<llvm::ArrayType, llvm::VectorType>(elementType);
251d6ea8ff0SAlex Zinenko     llvm::Constant *child = getLLVMConstant(
252d6ea8ff0SAlex Zinenko         elementType,
253176379e0SAlex Zinenko         elementTypeSequential ? splatAttr : splatAttr.getSplatValue(), loc,
2545ef21506SAdrian Kuegel         moduleTranslation, false);
255a4a42160SAlex Zinenko     if (!child)
256a4a42160SAlex Zinenko       return nullptr;
2572f13df13SMLIR Team     if (llvmType->isVectorTy())
258396a42d9SRiver Riddle       return llvm::ConstantVector::getSplat(
2590f95e731SAlex Zinenko           llvm::ElementCount::get(numElements, /*Scalable=*/false), child);
2602f13df13SMLIR Team     if (llvmType->isArrayTy()) {
261ac9d742bSStephan Herhut       auto *arrayType = llvm::ArrayType::get(elementType, numElements);
2622f13df13SMLIR Team       SmallVector<llvm::Constant *, 8> constants(numElements, child);
2632f13df13SMLIR Team       return llvm::ConstantArray::get(arrayType, constants);
2642f13df13SMLIR Team     }
2655d7231d8SStephan Herhut   }
266a4a42160SAlex Zinenko 
267*f9be7a7aSAlex Zinenko   // Try using raw elements data if possible.
268*f9be7a7aSAlex Zinenko   if (llvm::Constant *result =
269*f9be7a7aSAlex Zinenko           convertDenseElementsAttr(loc, attr.dyn_cast<DenseElementsAttr>(),
270*f9be7a7aSAlex Zinenko                                    llvmType, moduleTranslation)) {
271*f9be7a7aSAlex Zinenko     return result;
272*f9be7a7aSAlex Zinenko   }
273*f9be7a7aSAlex Zinenko 
274*f9be7a7aSAlex Zinenko   // Fall back to element-by-element construction otherwise.
275d906f84bSRiver Riddle   if (auto elementsAttr = attr.dyn_cast<ElementsAttr>()) {
276a4a42160SAlex Zinenko     assert(elementsAttr.getType().hasStaticShape());
277a4a42160SAlex Zinenko     assert(!elementsAttr.getType().getShape().empty() &&
278a4a42160SAlex Zinenko            "unexpected empty elements attribute shape");
279a4a42160SAlex Zinenko 
2805d7231d8SStephan Herhut     SmallVector<llvm::Constant *, 8> constants;
281a4a42160SAlex Zinenko     constants.reserve(elementsAttr.getNumElements());
282a4a42160SAlex Zinenko     llvm::Type *innermostType = getInnermostElementType(llvmType);
283d906f84bSRiver Riddle     for (auto n : elementsAttr.getValues<Attribute>()) {
284176379e0SAlex Zinenko       constants.push_back(
2855ef21506SAdrian Kuegel           getLLVMConstant(innermostType, n, loc, moduleTranslation, false));
2865d7231d8SStephan Herhut       if (!constants.back())
2875d7231d8SStephan Herhut         return nullptr;
2885d7231d8SStephan Herhut     }
289a4a42160SAlex Zinenko     ArrayRef<llvm::Constant *> constantsRef = constants;
290a4a42160SAlex Zinenko     llvm::Constant *result = buildSequentialConstant(
291a4a42160SAlex Zinenko         constantsRef, elementsAttr.getType().getShape(), llvmType, loc);
292a4a42160SAlex Zinenko     assert(constantsRef.empty() && "did not consume all elemental constants");
293a4a42160SAlex Zinenko     return result;
2942f13df13SMLIR Team   }
295a4a42160SAlex Zinenko 
296cb348dffSStephan Herhut   if (auto stringAttr = attr.dyn_cast<StringAttr>()) {
297cb348dffSStephan Herhut     return llvm::ConstantDataArray::get(
298176379e0SAlex Zinenko         moduleTranslation.getLLVMContext(),
299176379e0SAlex Zinenko         ArrayRef<char>{stringAttr.getValue().data(),
300cb348dffSStephan Herhut                        stringAttr.getValue().size()});
301cb348dffSStephan Herhut   }
302a4c3a645SRiver Riddle   emitError(loc, "unsupported constant value");
3035d7231d8SStephan Herhut   return nullptr;
3045d7231d8SStephan Herhut }
3055d7231d8SStephan Herhut 
306c33d6970SRiver Riddle ModuleTranslation::ModuleTranslation(Operation *module,
307c33d6970SRiver Riddle                                      std::unique_ptr<llvm::Module> llvmModule)
308c33d6970SRiver Riddle     : mlirModule(module), llvmModule(std::move(llvmModule)),
309c33d6970SRiver Riddle       debugTranslation(
31092a295ebSKiran Chandramohan           std::make_unique<DebugTranslation>(module, *this->llvmModule)),
311b77bac05SAlex Zinenko       typeTranslator(this->llvmModule->getContext()),
312b77bac05SAlex Zinenko       iface(module->getContext()) {
313c33d6970SRiver Riddle   assert(satisfiesLLVMModule(mlirModule) &&
314c33d6970SRiver Riddle          "mlirModule should honor LLVM's module semantics.");
315c33d6970SRiver Riddle }
316d9067dcaSKiran Chandramohan ModuleTranslation::~ModuleTranslation() {
317d9067dcaSKiran Chandramohan   if (ompBuilder)
318d9067dcaSKiran Chandramohan     ompBuilder->finalize();
319d9067dcaSKiran Chandramohan }
320d9067dcaSKiran Chandramohan 
3218647e4c3SAlex Zinenko void ModuleTranslation::forgetMapping(Region &region) {
3228647e4c3SAlex Zinenko   SmallVector<Region *> toProcess;
3238647e4c3SAlex Zinenko   toProcess.push_back(&region);
3248647e4c3SAlex Zinenko   while (!toProcess.empty()) {
3258647e4c3SAlex Zinenko     Region *current = toProcess.pop_back_val();
3268647e4c3SAlex Zinenko     for (Block &block : *current) {
3278647e4c3SAlex Zinenko       blockMapping.erase(&block);
3288647e4c3SAlex Zinenko       for (Value arg : block.getArguments())
3298647e4c3SAlex Zinenko         valueMapping.erase(arg);
3308647e4c3SAlex Zinenko       for (Operation &op : block) {
3318647e4c3SAlex Zinenko         for (Value value : op.getResults())
3328647e4c3SAlex Zinenko           valueMapping.erase(value);
3338647e4c3SAlex Zinenko         if (op.hasSuccessors())
3348647e4c3SAlex Zinenko           branchMapping.erase(&op);
3358647e4c3SAlex Zinenko         if (isa<LLVM::GlobalOp>(op))
3368647e4c3SAlex Zinenko           globalsMapping.erase(&op);
3378647e4c3SAlex Zinenko         accessGroupMetadataMapping.erase(&op);
3388647e4c3SAlex Zinenko         llvm::append_range(
3398647e4c3SAlex Zinenko             toProcess,
3408647e4c3SAlex Zinenko             llvm::map_range(op.getRegions(), [](Region &r) { return &r; }));
3418647e4c3SAlex Zinenko       }
3428647e4c3SAlex Zinenko     }
3438647e4c3SAlex Zinenko   }
3448647e4c3SAlex Zinenko }
3458647e4c3SAlex Zinenko 
346d9067dcaSKiran Chandramohan /// Get the SSA value passed to the current block from the terminator operation
347d9067dcaSKiran Chandramohan /// of its predecessor.
348d9067dcaSKiran Chandramohan static Value getPHISourceValue(Block *current, Block *pred,
349d9067dcaSKiran Chandramohan                                unsigned numArguments, unsigned index) {
350d9067dcaSKiran Chandramohan   Operation &terminator = *pred->getTerminator();
351d9067dcaSKiran Chandramohan   if (isa<LLVM::BrOp>(terminator))
352d9067dcaSKiran Chandramohan     return terminator.getOperand(index);
353d9067dcaSKiran Chandramohan 
35414f24155SBrian Gesiak   SuccessorRange successors = terminator.getSuccessors();
35514f24155SBrian Gesiak   assert(std::adjacent_find(successors.begin(), successors.end()) ==
35614f24155SBrian Gesiak              successors.end() &&
35714f24155SBrian Gesiak          "successors with arguments in LLVM branches must be different blocks");
35858f2b765SChristian Sigg   (void)successors;
359d9067dcaSKiran Chandramohan 
36014f24155SBrian Gesiak   // For instructions that branch based on a condition value, we need to take
36114f24155SBrian Gesiak   // the operands for the branch that was taken.
36214f24155SBrian Gesiak   if (auto condBranchOp = dyn_cast<LLVM::CondBrOp>(terminator)) {
36314f24155SBrian Gesiak     // For conditional branches, we take the operands from either the "true" or
36414f24155SBrian Gesiak     // the "false" branch.
365d9067dcaSKiran Chandramohan     return condBranchOp.getSuccessor(0) == current
366d9067dcaSKiran Chandramohan                ? condBranchOp.trueDestOperands()[index]
367d9067dcaSKiran Chandramohan                : condBranchOp.falseDestOperands()[index];
3680881a4f1SAlex Zinenko   }
3690881a4f1SAlex Zinenko 
3700881a4f1SAlex Zinenko   if (auto switchOp = dyn_cast<LLVM::SwitchOp>(terminator)) {
37114f24155SBrian Gesiak     // For switches, we take the operands from either the default case, or from
37214f24155SBrian Gesiak     // the case branch that was taken.
37314f24155SBrian Gesiak     if (switchOp.defaultDestination() == current)
37414f24155SBrian Gesiak       return switchOp.defaultOperands()[index];
37514f24155SBrian Gesiak     for (auto i : llvm::enumerate(switchOp.caseDestinations()))
37614f24155SBrian Gesiak       if (i.value() == current)
37714f24155SBrian Gesiak         return switchOp.getCaseOperands(i.index())[index];
37814f24155SBrian Gesiak   }
37914f24155SBrian Gesiak 
38014f24155SBrian Gesiak   llvm_unreachable("only branch or switch operations can be terminators of a "
38114f24155SBrian Gesiak                    "block that has successors");
382d9067dcaSKiran Chandramohan }
383d9067dcaSKiran Chandramohan 
384d9067dcaSKiran Chandramohan /// Connect the PHI nodes to the results of preceding blocks.
38566900b3eSAlex Zinenko void mlir::LLVM::detail::connectPHINodes(Region &region,
38666900b3eSAlex Zinenko                                          const ModuleTranslation &state) {
387d9067dcaSKiran Chandramohan   // Skip the first block, it cannot be branched to and its arguments correspond
388d9067dcaSKiran Chandramohan   // to the arguments of the LLVM function.
38966900b3eSAlex Zinenko   for (auto it = std::next(region.begin()), eit = region.end(); it != eit;
39066900b3eSAlex Zinenko        ++it) {
391d9067dcaSKiran Chandramohan     Block *bb = &*it;
3920881a4f1SAlex Zinenko     llvm::BasicBlock *llvmBB = state.lookupBlock(bb);
393d9067dcaSKiran Chandramohan     auto phis = llvmBB->phis();
394d9067dcaSKiran Chandramohan     auto numArguments = bb->getNumArguments();
395d9067dcaSKiran Chandramohan     assert(numArguments == std::distance(phis.begin(), phis.end()));
396d9067dcaSKiran Chandramohan     for (auto &numberedPhiNode : llvm::enumerate(phis)) {
397d9067dcaSKiran Chandramohan       auto &phiNode = numberedPhiNode.value();
398d9067dcaSKiran Chandramohan       unsigned index = numberedPhiNode.index();
399d9067dcaSKiran Chandramohan       for (auto *pred : bb->getPredecessors()) {
400db884dafSAlex Zinenko         // Find the LLVM IR block that contains the converted terminator
401db884dafSAlex Zinenko         // instruction and use it in the PHI node. Note that this block is not
4020881a4f1SAlex Zinenko         // necessarily the same as state.lookupBlock(pred), some operations
403db884dafSAlex Zinenko         // (in particular, OpenMP operations using OpenMPIRBuilder) may have
404db884dafSAlex Zinenko         // split the blocks.
405db884dafSAlex Zinenko         llvm::Instruction *terminator =
4060881a4f1SAlex Zinenko             state.lookupBranch(pred->getTerminator());
407db884dafSAlex Zinenko         assert(terminator && "missing the mapping for a terminator");
4080881a4f1SAlex Zinenko         phiNode.addIncoming(
4090881a4f1SAlex Zinenko             state.lookupValue(getPHISourceValue(bb, pred, numArguments, index)),
410db884dafSAlex Zinenko             terminator->getParent());
411d9067dcaSKiran Chandramohan       }
412d9067dcaSKiran Chandramohan     }
413d9067dcaSKiran Chandramohan   }
414d9067dcaSKiran Chandramohan }
415d9067dcaSKiran Chandramohan 
416d9067dcaSKiran Chandramohan /// Sort function blocks topologically.
4174efb7754SRiver Riddle SetVector<Block *>
41866900b3eSAlex Zinenko mlir::LLVM::detail::getTopologicallySortedBlocks(Region &region) {
419d4568ed7SGeorge Mitenkov   // For each block that has not been visited yet (i.e. that has no
420d4568ed7SGeorge Mitenkov   // predecessors), add it to the list as well as its successors.
4214efb7754SRiver Riddle   SetVector<Block *> blocks;
42266900b3eSAlex Zinenko   for (Block &b : region) {
423d4568ed7SGeorge Mitenkov     if (blocks.count(&b) == 0) {
424d4568ed7SGeorge Mitenkov       llvm::ReversePostOrderTraversal<Block *> traversal(&b);
425d4568ed7SGeorge Mitenkov       blocks.insert(traversal.begin(), traversal.end());
426d4568ed7SGeorge Mitenkov     }
427d9067dcaSKiran Chandramohan   }
42866900b3eSAlex Zinenko   assert(blocks.size() == region.getBlocks().size() &&
42966900b3eSAlex Zinenko          "some blocks are not sorted");
430d9067dcaSKiran Chandramohan 
431d9067dcaSKiran Chandramohan   return blocks;
432d9067dcaSKiran Chandramohan }
433d9067dcaSKiran Chandramohan 
434176379e0SAlex Zinenko llvm::Value *mlir::LLVM::detail::createIntrinsicCall(
435176379e0SAlex Zinenko     llvm::IRBuilderBase &builder, llvm::Intrinsic::ID intrinsic,
436176379e0SAlex Zinenko     ArrayRef<llvm::Value *> args, ArrayRef<llvm::Type *> tys) {
437176379e0SAlex Zinenko   llvm::Module *module = builder.GetInsertBlock()->getModule();
438176379e0SAlex Zinenko   llvm::Function *fn = llvm::Intrinsic::getDeclaration(module, intrinsic, tys);
439176379e0SAlex Zinenko   return builder.CreateCall(fn, args);
440176379e0SAlex Zinenko }
441176379e0SAlex Zinenko 
442875eb523SNavdeep Kumar llvm::Value *
443875eb523SNavdeep Kumar mlir::LLVM::detail::createNvvmIntrinsicCall(llvm::IRBuilderBase &builder,
444875eb523SNavdeep Kumar                                             llvm::Intrinsic::ID intrinsic,
445875eb523SNavdeep Kumar                                             ArrayRef<llvm::Value *> args) {
446875eb523SNavdeep Kumar   llvm::Module *module = builder.GetInsertBlock()->getModule();
447875eb523SNavdeep Kumar   llvm::Function *fn;
448875eb523SNavdeep Kumar   if (llvm::Intrinsic::isOverloaded(intrinsic)) {
449875eb523SNavdeep Kumar     if (intrinsic != llvm::Intrinsic::nvvm_wmma_m16n16k16_mma_row_row_f16_f16 &&
450875eb523SNavdeep Kumar         intrinsic != llvm::Intrinsic::nvvm_wmma_m16n16k16_mma_row_row_f32_f32) {
451875eb523SNavdeep Kumar       // NVVM load and store instrinsic names are overloaded on the
452875eb523SNavdeep Kumar       // source/destination pointer type. Pointer is the first argument in the
453875eb523SNavdeep Kumar       // corresponding NVVM Op.
454875eb523SNavdeep Kumar       fn = llvm::Intrinsic::getDeclaration(module, intrinsic,
455875eb523SNavdeep Kumar                                            {args[0]->getType()});
456875eb523SNavdeep Kumar     } else {
457875eb523SNavdeep Kumar       fn = llvm::Intrinsic::getDeclaration(module, intrinsic, {});
458875eb523SNavdeep Kumar     }
459875eb523SNavdeep Kumar   } else {
460875eb523SNavdeep Kumar     fn = llvm::Intrinsic::getDeclaration(module, intrinsic);
461875eb523SNavdeep Kumar   }
462875eb523SNavdeep Kumar   return builder.CreateCall(fn, args);
463875eb523SNavdeep Kumar }
464875eb523SNavdeep Kumar 
4652666b973SRiver Riddle /// Given a single MLIR operation, create the corresponding LLVM IR operation
466176379e0SAlex Zinenko /// using the `builder`.
467ce8f10d6SAlex Zinenko LogicalResult
46838b106f6SMehdi Amini ModuleTranslation::convertOperation(Operation &op,
469ce8f10d6SAlex Zinenko                                     llvm::IRBuilderBase &builder) {
47038b106f6SMehdi Amini   const LLVMTranslationDialectInterface *opIface = iface.getInterfaceFor(&op);
47138b106f6SMehdi Amini   if (!opIface)
47238b106f6SMehdi Amini     return op.emitError("cannot be converted to LLVM IR: missing "
47338b106f6SMehdi Amini                         "`LLVMTranslationDialectInterface` registration for "
47438b106f6SMehdi Amini                         "dialect for op: ")
47538b106f6SMehdi Amini            << op.getName();
476176379e0SAlex Zinenko 
47738b106f6SMehdi Amini   if (failed(opIface->convertOperation(&op, builder, *this)))
47838b106f6SMehdi Amini     return op.emitError("LLVM Translation failed for operation: ")
47938b106f6SMehdi Amini            << op.getName();
48038b106f6SMehdi Amini 
48138b106f6SMehdi Amini   return convertDialectAttributes(&op);
4825d7231d8SStephan Herhut }
4835d7231d8SStephan Herhut 
4842666b973SRiver Riddle /// Convert block to LLVM IR.  Unless `ignoreArguments` is set, emit PHI nodes
4852666b973SRiver Riddle /// to define values corresponding to the MLIR block arguments.  These nodes
48610164a2eSAlex Zinenko /// are not connected to the source basic blocks, which may not exist yet.  Uses
48710164a2eSAlex Zinenko /// `builder` to construct the LLVM IR. Expects the LLVM IR basic block to have
48810164a2eSAlex Zinenko /// been created for `bb` and included in the block mapping.  Inserts new
48910164a2eSAlex Zinenko /// instructions at the end of the block and leaves `builder` in a state
49010164a2eSAlex Zinenko /// suitable for further insertion into the end of the block.
49110164a2eSAlex Zinenko LogicalResult ModuleTranslation::convertBlock(Block &bb, bool ignoreArguments,
492ce8f10d6SAlex Zinenko                                               llvm::IRBuilderBase &builder) {
4930881a4f1SAlex Zinenko   builder.SetInsertPoint(lookupBlock(&bb));
494c33d6970SRiver Riddle   auto *subprogram = builder.GetInsertBlock()->getParent()->getSubprogram();
4955d7231d8SStephan Herhut 
4965d7231d8SStephan Herhut   // Before traversing operations, make block arguments available through
4975d7231d8SStephan Herhut   // value remapping and PHI nodes, but do not add incoming edges for the PHI
4985d7231d8SStephan Herhut   // nodes just yet: those values may be defined by this or following blocks.
4995d7231d8SStephan Herhut   // This step is omitted if "ignoreArguments" is set.  The arguments of the
5005d7231d8SStephan Herhut   // first block have been already made available through the remapping of
5015d7231d8SStephan Herhut   // LLVM function arguments.
5025d7231d8SStephan Herhut   if (!ignoreArguments) {
5035d7231d8SStephan Herhut     auto predecessors = bb.getPredecessors();
5045d7231d8SStephan Herhut     unsigned numPredecessors =
5055d7231d8SStephan Herhut         std::distance(predecessors.begin(), predecessors.end());
50635807bc4SRiver Riddle     for (auto arg : bb.getArguments()) {
507c69c9e0fSAlex Zinenko       auto wrappedType = arg.getType();
508c69c9e0fSAlex Zinenko       if (!isCompatibleType(wrappedType))
509baa1ec22SAlex Zinenko         return emitError(bb.front().getLoc(),
510a4c3a645SRiver Riddle                          "block argument does not have an LLVM type");
511aec38c61SAlex Zinenko       llvm::Type *type = convertType(wrappedType);
5125d7231d8SStephan Herhut       llvm::PHINode *phi = builder.CreatePHI(type, numPredecessors);
5130881a4f1SAlex Zinenko       mapValue(arg, phi);
5145d7231d8SStephan Herhut     }
5155d7231d8SStephan Herhut   }
5165d7231d8SStephan Herhut 
5175d7231d8SStephan Herhut   // Traverse operations.
5185d7231d8SStephan Herhut   for (auto &op : bb) {
519c33d6970SRiver Riddle     // Set the current debug location within the builder.
520c33d6970SRiver Riddle     builder.SetCurrentDebugLocation(
521c33d6970SRiver Riddle         debugTranslation->translateLoc(op.getLoc(), subprogram));
522c33d6970SRiver Riddle 
523baa1ec22SAlex Zinenko     if (failed(convertOperation(op, builder)))
524baa1ec22SAlex Zinenko       return failure();
5255d7231d8SStephan Herhut   }
5265d7231d8SStephan Herhut 
527baa1ec22SAlex Zinenko   return success();
5285d7231d8SStephan Herhut }
5295d7231d8SStephan Herhut 
530ce8f10d6SAlex Zinenko /// A helper method to get the single Block in an operation honoring LLVM's
531ce8f10d6SAlex Zinenko /// module requirements.
532ce8f10d6SAlex Zinenko static Block &getModuleBody(Operation *module) {
533ce8f10d6SAlex Zinenko   return module->getRegion(0).front();
534ce8f10d6SAlex Zinenko }
535ce8f10d6SAlex Zinenko 
536ffa455d4SJean Perier /// A helper method to decide if a constant must not be set as a global variable
537d4df3825SAlex Zinenko /// initializer. For an external linkage variable, the variable with an
538d4df3825SAlex Zinenko /// initializer is considered externally visible and defined in this module, the
539d4df3825SAlex Zinenko /// variable without an initializer is externally available and is defined
540d4df3825SAlex Zinenko /// elsewhere.
541ffa455d4SJean Perier static bool shouldDropGlobalInitializer(llvm::GlobalValue::LinkageTypes linkage,
542ffa455d4SJean Perier                                         llvm::Constant *cst) {
543d4df3825SAlex Zinenko   return (linkage == llvm::GlobalVariable::ExternalLinkage && !cst) ||
544ffa455d4SJean Perier          linkage == llvm::GlobalVariable::ExternalWeakLinkage;
545ffa455d4SJean Perier }
546ffa455d4SJean Perier 
5478ca04b05SFelipe de Azevedo Piovezan /// Sets the runtime preemption specifier of `gv` to dso_local if
5488ca04b05SFelipe de Azevedo Piovezan /// `dsoLocalRequested` is true, otherwise it is left unchanged.
5498ca04b05SFelipe de Azevedo Piovezan static void addRuntimePreemptionSpecifier(bool dsoLocalRequested,
5508ca04b05SFelipe de Azevedo Piovezan                                           llvm::GlobalValue *gv) {
5518ca04b05SFelipe de Azevedo Piovezan   if (dsoLocalRequested)
5528ca04b05SFelipe de Azevedo Piovezan     gv->setDSOLocal(true);
5538ca04b05SFelipe de Azevedo Piovezan }
5548ca04b05SFelipe de Azevedo Piovezan 
5552666b973SRiver Riddle /// Create named global variables that correspond to llvm.mlir.global
5562666b973SRiver Riddle /// definitions.
557efa2d533SAlex Zinenko LogicalResult ModuleTranslation::convertGlobals() {
55844fc7d72STres Popp   for (auto op : getModuleBody(mlirModule).getOps<LLVM::GlobalOp>()) {
559aec38c61SAlex Zinenko     llvm::Type *type = convertType(op.getType());
560d4df3825SAlex Zinenko     llvm::Constant *cst = nullptr;
561250a11aeSJames Molloy     if (op.getValueOrNull()) {
56268451df2SAlex Zinenko       // String attributes are treated separately because they cannot appear as
56368451df2SAlex Zinenko       // in-function constants and are thus not supported by getLLVMConstant.
56433a3a91bSChristian Sigg       if (auto strAttr = op.getValueOrNull().dyn_cast_or_null<StringAttr>()) {
5652dd38b09SAlex Zinenko         cst = llvm::ConstantDataArray::getString(
56668451df2SAlex Zinenko             llvmModule->getContext(), strAttr.getValue(), /*AddNull=*/false);
5672dd38b09SAlex Zinenko         type = cst->getType();
568176379e0SAlex Zinenko       } else if (!(cst = getLLVMConstant(type, op.getValueOrNull(), op.getLoc(),
569176379e0SAlex Zinenko                                          *this))) {
570efa2d533SAlex Zinenko         return failure();
57168451df2SAlex Zinenko       }
572ffa455d4SJean Perier     }
573ffa455d4SJean Perier 
574ffa455d4SJean Perier     auto linkage = convertLinkageToLLVM(op.linkage());
575ffa455d4SJean Perier     auto addrSpace = op.addr_space();
576d4df3825SAlex Zinenko 
577d4df3825SAlex Zinenko     // LLVM IR requires constant with linkage other than external or weak
578d4df3825SAlex Zinenko     // external to have initializers. If MLIR does not provide an initializer,
579d4df3825SAlex Zinenko     // default to undef.
580d4df3825SAlex Zinenko     bool dropInitializer = shouldDropGlobalInitializer(linkage, cst);
581d4df3825SAlex Zinenko     if (!dropInitializer && !cst)
582d4df3825SAlex Zinenko       cst = llvm::UndefValue::get(type);
583d4df3825SAlex Zinenko     else if (dropInitializer && cst)
584d4df3825SAlex Zinenko       cst = nullptr;
585d4df3825SAlex Zinenko 
586ffa455d4SJean Perier     auto *var = new llvm::GlobalVariable(
587d4df3825SAlex Zinenko         *llvmModule, type, op.constant(), linkage, cst, op.sym_name(),
588ffa455d4SJean Perier         /*InsertBefore=*/nullptr, llvm::GlobalValue::NotThreadLocal, addrSpace);
589ffa455d4SJean Perier 
590c46a8862Sclementval     if (op.unnamed_addr().hasValue())
591c46a8862Sclementval       var->setUnnamedAddr(convertUnnamedAddrToLLVM(*op.unnamed_addr()));
592c46a8862Sclementval 
593b65472d6SRanjith Kumar H     if (op.section().hasValue())
594b65472d6SRanjith Kumar H       var->setSection(*op.section());
595b65472d6SRanjith Kumar H 
5968ca04b05SFelipe de Azevedo Piovezan     addRuntimePreemptionSpecifier(op.dso_local(), var);
5978ca04b05SFelipe de Azevedo Piovezan 
5989a0ea599SDumitru Potop     Optional<uint64_t> alignment = op.alignment();
5999a0ea599SDumitru Potop     if (alignment.hasValue())
6009a0ea599SDumitru Potop       var->setAlignment(llvm::MaybeAlign(alignment.getValue()));
6019a0ea599SDumitru Potop 
602ffa455d4SJean Perier     globalsMapping.try_emplace(op, var);
603ffa455d4SJean Perier   }
604ffa455d4SJean Perier 
605ffa455d4SJean Perier   // Convert global variable bodies. This is done after all global variables
606ffa455d4SJean Perier   // have been created in LLVM IR because a global body may refer to another
607ffa455d4SJean Perier   // global or itself. So all global variables need to be mapped first.
608ffa455d4SJean Perier   for (auto op : getModuleBody(mlirModule).getOps<LLVM::GlobalOp>()) {
609ffa455d4SJean Perier     if (Block *initializer = op.getInitializerBlock()) {
610250a11aeSJames Molloy       llvm::IRBuilder<> builder(llvmModule->getContext());
611250a11aeSJames Molloy       for (auto &op : initializer->without_terminator()) {
612250a11aeSJames Molloy         if (failed(convertOperation(op, builder)) ||
6130881a4f1SAlex Zinenko             !isa<llvm::Constant>(lookupValue(op.getResult(0))))
614efa2d533SAlex Zinenko           return emitError(op.getLoc(), "unemittable constant value");
615250a11aeSJames Molloy       }
616250a11aeSJames Molloy       ReturnOp ret = cast<ReturnOp>(initializer->getTerminator());
617ffa455d4SJean Perier       llvm::Constant *cst =
618ffa455d4SJean Perier           cast<llvm::Constant>(lookupValue(ret.getOperand(0)));
619ffa455d4SJean Perier       auto *global = cast<llvm::GlobalVariable>(lookupGlobal(op));
620ffa455d4SJean Perier       if (!shouldDropGlobalInitializer(global->getLinkage(), cst))
621ffa455d4SJean Perier         global->setInitializer(cst);
622250a11aeSJames Molloy     }
623b9ff2dd8SAlex Zinenko   }
624efa2d533SAlex Zinenko 
625efa2d533SAlex Zinenko   return success();
626b9ff2dd8SAlex Zinenko }
627b9ff2dd8SAlex Zinenko 
6280a2131b7SAlex Zinenko /// Attempts to add an attribute identified by `key`, optionally with the given
6290a2131b7SAlex Zinenko /// `value` to LLVM function `llvmFunc`. Reports errors at `loc` if any. If the
6300a2131b7SAlex Zinenko /// attribute has a kind known to LLVM IR, create the attribute of this kind,
6310a2131b7SAlex Zinenko /// otherwise keep it as a string attribute. Performs additional checks for
6320a2131b7SAlex Zinenko /// attributes known to have or not have a value in order to avoid assertions
6330a2131b7SAlex Zinenko /// inside LLVM upon construction.
6340a2131b7SAlex Zinenko static LogicalResult checkedAddLLVMFnAttribute(Location loc,
6350a2131b7SAlex Zinenko                                                llvm::Function *llvmFunc,
6360a2131b7SAlex Zinenko                                                StringRef key,
6370a2131b7SAlex Zinenko                                                StringRef value = StringRef()) {
6380a2131b7SAlex Zinenko   auto kind = llvm::Attribute::getAttrKindFromName(key);
6390a2131b7SAlex Zinenko   if (kind == llvm::Attribute::None) {
6400a2131b7SAlex Zinenko     llvmFunc->addFnAttr(key, value);
6410a2131b7SAlex Zinenko     return success();
6420a2131b7SAlex Zinenko   }
6430a2131b7SAlex Zinenko 
6446ac32872SNikita Popov   if (llvm::Attribute::isIntAttrKind(kind)) {
6450a2131b7SAlex Zinenko     if (value.empty())
6460a2131b7SAlex Zinenko       return emitError(loc) << "LLVM attribute '" << key << "' expects a value";
6470a2131b7SAlex Zinenko 
6480a2131b7SAlex Zinenko     int result;
6490a2131b7SAlex Zinenko     if (!value.getAsInteger(/*Radix=*/0, result))
6500a2131b7SAlex Zinenko       llvmFunc->addFnAttr(
6510a2131b7SAlex Zinenko           llvm::Attribute::get(llvmFunc->getContext(), kind, result));
6520a2131b7SAlex Zinenko     else
6530a2131b7SAlex Zinenko       llvmFunc->addFnAttr(key, value);
6540a2131b7SAlex Zinenko     return success();
6550a2131b7SAlex Zinenko   }
6560a2131b7SAlex Zinenko 
6570a2131b7SAlex Zinenko   if (!value.empty())
6580a2131b7SAlex Zinenko     return emitError(loc) << "LLVM attribute '" << key
6590a2131b7SAlex Zinenko                           << "' does not expect a value, found '" << value
6600a2131b7SAlex Zinenko                           << "'";
6610a2131b7SAlex Zinenko 
6620a2131b7SAlex Zinenko   llvmFunc->addFnAttr(kind);
6630a2131b7SAlex Zinenko   return success();
6640a2131b7SAlex Zinenko }
6650a2131b7SAlex Zinenko 
6660a2131b7SAlex Zinenko /// Attaches the attributes listed in the given array attribute to `llvmFunc`.
6670a2131b7SAlex Zinenko /// Reports error to `loc` if any and returns immediately. Expects `attributes`
6680a2131b7SAlex Zinenko /// to be an array attribute containing either string attributes, treated as
6690a2131b7SAlex Zinenko /// value-less LLVM attributes, or array attributes containing two string
6700a2131b7SAlex Zinenko /// attributes, with the first string being the name of the corresponding LLVM
6710a2131b7SAlex Zinenko /// attribute and the second string beings its value. Note that even integer
6720a2131b7SAlex Zinenko /// attributes are expected to have their values expressed as strings.
6730a2131b7SAlex Zinenko static LogicalResult
6740a2131b7SAlex Zinenko forwardPassthroughAttributes(Location loc, Optional<ArrayAttr> attributes,
6750a2131b7SAlex Zinenko                              llvm::Function *llvmFunc) {
6760a2131b7SAlex Zinenko   if (!attributes)
6770a2131b7SAlex Zinenko     return success();
6780a2131b7SAlex Zinenko 
6790a2131b7SAlex Zinenko   for (Attribute attr : *attributes) {
6800a2131b7SAlex Zinenko     if (auto stringAttr = attr.dyn_cast<StringAttr>()) {
6810a2131b7SAlex Zinenko       if (failed(
6820a2131b7SAlex Zinenko               checkedAddLLVMFnAttribute(loc, llvmFunc, stringAttr.getValue())))
6830a2131b7SAlex Zinenko         return failure();
6840a2131b7SAlex Zinenko       continue;
6850a2131b7SAlex Zinenko     }
6860a2131b7SAlex Zinenko 
6870a2131b7SAlex Zinenko     auto arrayAttr = attr.dyn_cast<ArrayAttr>();
6880a2131b7SAlex Zinenko     if (!arrayAttr || arrayAttr.size() != 2)
6890a2131b7SAlex Zinenko       return emitError(loc)
6900a2131b7SAlex Zinenko              << "expected 'passthrough' to contain string or array attributes";
6910a2131b7SAlex Zinenko 
6920a2131b7SAlex Zinenko     auto keyAttr = arrayAttr[0].dyn_cast<StringAttr>();
6930a2131b7SAlex Zinenko     auto valueAttr = arrayAttr[1].dyn_cast<StringAttr>();
6940a2131b7SAlex Zinenko     if (!keyAttr || !valueAttr)
6950a2131b7SAlex Zinenko       return emitError(loc)
6960a2131b7SAlex Zinenko              << "expected arrays within 'passthrough' to contain two strings";
6970a2131b7SAlex Zinenko 
6980a2131b7SAlex Zinenko     if (failed(checkedAddLLVMFnAttribute(loc, llvmFunc, keyAttr.getValue(),
6990a2131b7SAlex Zinenko                                          valueAttr.getValue())))
7000a2131b7SAlex Zinenko       return failure();
7010a2131b7SAlex Zinenko   }
7020a2131b7SAlex Zinenko   return success();
7030a2131b7SAlex Zinenko }
7040a2131b7SAlex Zinenko 
7055e7959a3SAlex Zinenko LogicalResult ModuleTranslation::convertOneFunction(LLVMFuncOp func) {
706db884dafSAlex Zinenko   // Clear the block, branch value mappings, they are only relevant within one
7075d7231d8SStephan Herhut   // function.
7085d7231d8SStephan Herhut   blockMapping.clear();
7095d7231d8SStephan Herhut   valueMapping.clear();
710db884dafSAlex Zinenko   branchMapping.clear();
7110881a4f1SAlex Zinenko   llvm::Function *llvmFunc = lookupFunction(func.getName());
712c33d6970SRiver Riddle 
713c33d6970SRiver Riddle   // Translate the debug information for this function.
714c33d6970SRiver Riddle   debugTranslation->translate(func, *llvmFunc);
715c33d6970SRiver Riddle 
7165d7231d8SStephan Herhut   // Add function arguments to the value remapping table.
7175d7231d8SStephan Herhut   // If there was noalias info then we decorate each argument accordingly.
7185d7231d8SStephan Herhut   unsigned int argIdx = 0;
719eeef50b1SFangrui Song   for (auto kvp : llvm::zip(func.getArguments(), llvmFunc->args())) {
7205d7231d8SStephan Herhut     llvm::Argument &llvmArg = std::get<1>(kvp);
721e62a6956SRiver Riddle     BlockArgument mlirArg = std::get<0>(kvp);
7225d7231d8SStephan Herhut 
7231c777ab4SUday Bondhugula     if (auto attr = func.getArgAttrOfType<UnitAttr>(
72467cc5cecSStephan Herhut             argIdx, LLVMDialect::getNoAliasAttrName())) {
7255d7231d8SStephan Herhut       // NB: Attribute already verified to be boolean, so check if we can indeed
7265d7231d8SStephan Herhut       // attach the attribute to this argument, based on its type.
727c69c9e0fSAlex Zinenko       auto argTy = mlirArg.getType();
7288de43b92SAlex Zinenko       if (!argTy.isa<LLVM::LLVMPointerType>())
729baa1ec22SAlex Zinenko         return func.emitError(
7305d7231d8SStephan Herhut             "llvm.noalias attribute attached to LLVM non-pointer argument");
7315d7231d8SStephan Herhut       llvmArg.addAttr(llvm::Attribute::AttrKind::NoAlias);
7325d7231d8SStephan Herhut     }
7332416e28cSStephan Herhut 
73467cc5cecSStephan Herhut     if (auto attr = func.getArgAttrOfType<IntegerAttr>(
73567cc5cecSStephan Herhut             argIdx, LLVMDialect::getAlignAttrName())) {
7362416e28cSStephan Herhut       // NB: Attribute already verified to be int, so check if we can indeed
7372416e28cSStephan Herhut       // attach the attribute to this argument, based on its type.
738c69c9e0fSAlex Zinenko       auto argTy = mlirArg.getType();
7398de43b92SAlex Zinenko       if (!argTy.isa<LLVM::LLVMPointerType>())
7402416e28cSStephan Herhut         return func.emitError(
7412416e28cSStephan Herhut             "llvm.align attribute attached to LLVM non-pointer argument");
7422416e28cSStephan Herhut       llvmArg.addAttrs(
7432416e28cSStephan Herhut           llvm::AttrBuilder().addAlignmentAttr(llvm::Align(attr.getInt())));
7442416e28cSStephan Herhut     }
7452416e28cSStephan Herhut 
74670b841acSEric Schweitz     if (auto attr = func.getArgAttrOfType<UnitAttr>(argIdx, "llvm.sret")) {
74770b841acSEric Schweitz       auto argTy = mlirArg.getType();
74870b841acSEric Schweitz       if (!argTy.isa<LLVM::LLVMPointerType>())
74970b841acSEric Schweitz         return func.emitError(
75070b841acSEric Schweitz             "llvm.sret attribute attached to LLVM non-pointer argument");
7511d6df1fcSEric Schweitz       llvmArg.addAttrs(llvm::AttrBuilder().addStructRetAttr(
7521d6df1fcSEric Schweitz           llvmArg.getType()->getPointerElementType()));
75370b841acSEric Schweitz     }
75470b841acSEric Schweitz 
75570b841acSEric Schweitz     if (auto attr = func.getArgAttrOfType<UnitAttr>(argIdx, "llvm.byval")) {
75670b841acSEric Schweitz       auto argTy = mlirArg.getType();
75770b841acSEric Schweitz       if (!argTy.isa<LLVM::LLVMPointerType>())
75870b841acSEric Schweitz         return func.emitError(
75970b841acSEric Schweitz             "llvm.byval attribute attached to LLVM non-pointer argument");
7601d6df1fcSEric Schweitz       llvmArg.addAttrs(llvm::AttrBuilder().addByValAttr(
7611d6df1fcSEric Schweitz           llvmArg.getType()->getPointerElementType()));
76270b841acSEric Schweitz     }
76370b841acSEric Schweitz 
7640881a4f1SAlex Zinenko     mapValue(mlirArg, &llvmArg);
7655d7231d8SStephan Herhut     argIdx++;
7665d7231d8SStephan Herhut   }
7675d7231d8SStephan Herhut 
768ff77397fSShraiysh Vaishay   // Check the personality and set it.
769ff77397fSShraiysh Vaishay   if (func.personality().hasValue()) {
770ff77397fSShraiysh Vaishay     llvm::Type *ty = llvm::Type::getInt8PtrTy(llvmFunc->getContext());
771ff77397fSShraiysh Vaishay     if (llvm::Constant *pfunc =
772176379e0SAlex Zinenko             getLLVMConstant(ty, func.personalityAttr(), func.getLoc(), *this))
773ff77397fSShraiysh Vaishay       llvmFunc->setPersonalityFn(pfunc);
774ff77397fSShraiysh Vaishay   }
775ff77397fSShraiysh Vaishay 
7765d7231d8SStephan Herhut   // First, create all blocks so we can jump to them.
7775d7231d8SStephan Herhut   llvm::LLVMContext &llvmContext = llvmFunc->getContext();
7785d7231d8SStephan Herhut   for (auto &bb : func) {
7795d7231d8SStephan Herhut     auto *llvmBB = llvm::BasicBlock::Create(llvmContext);
7805d7231d8SStephan Herhut     llvmBB->insertInto(llvmFunc);
7810881a4f1SAlex Zinenko     mapBlock(&bb, llvmBB);
7825d7231d8SStephan Herhut   }
7835d7231d8SStephan Herhut 
7845d7231d8SStephan Herhut   // Then, convert blocks one by one in topological order to ensure defs are
7855d7231d8SStephan Herhut   // converted before uses.
78666900b3eSAlex Zinenko   auto blocks = detail::getTopologicallySortedBlocks(func.getBody());
78710164a2eSAlex Zinenko   for (Block *bb : blocks) {
78810164a2eSAlex Zinenko     llvm::IRBuilder<> builder(llvmContext);
78910164a2eSAlex Zinenko     if (failed(convertBlock(*bb, bb->isEntryBlock(), builder)))
790baa1ec22SAlex Zinenko       return failure();
7915d7231d8SStephan Herhut   }
7925d7231d8SStephan Herhut 
793176379e0SAlex Zinenko   // After all blocks have been traversed and values mapped, connect the PHI
794176379e0SAlex Zinenko   // nodes to the results of preceding blocks.
79566900b3eSAlex Zinenko   detail::connectPHINodes(func.getBody(), *this);
796176379e0SAlex Zinenko 
797176379e0SAlex Zinenko   // Finally, convert dialect attributes attached to the function.
798176379e0SAlex Zinenko   return convertDialectAttributes(func);
799176379e0SAlex Zinenko }
800176379e0SAlex Zinenko 
801176379e0SAlex Zinenko LogicalResult ModuleTranslation::convertDialectAttributes(Operation *op) {
802176379e0SAlex Zinenko   for (NamedAttribute attribute : op->getDialectAttrs())
803176379e0SAlex Zinenko     if (failed(iface.amendOperation(op, attribute, *this)))
804176379e0SAlex Zinenko       return failure();
805baa1ec22SAlex Zinenko   return success();
8065d7231d8SStephan Herhut }
8075d7231d8SStephan Herhut 
808a084b94fSSean Silva LogicalResult ModuleTranslation::convertFunctionSignatures() {
8095d7231d8SStephan Herhut   // Declare all functions first because there may be function calls that form a
810a084b94fSSean Silva   // call graph with cycles, or global initializers that reference functions.
81144fc7d72STres Popp   for (auto function : getModuleBody(mlirModule).getOps<LLVMFuncOp>()) {
8125e7959a3SAlex Zinenko     llvm::FunctionCallee llvmFuncCst = llvmModule->getOrInsertFunction(
8135e7959a3SAlex Zinenko         function.getName(),
814aec38c61SAlex Zinenko         cast<llvm::FunctionType>(convertType(function.getType())));
8150a2131b7SAlex Zinenko     llvm::Function *llvmFunc = cast<llvm::Function>(llvmFuncCst.getCallee());
816ebbdecddSAlex Zinenko     llvmFunc->setLinkage(convertLinkageToLLVM(function.linkage()));
8170881a4f1SAlex Zinenko     mapFunction(function.getName(), llvmFunc);
8188ca04b05SFelipe de Azevedo Piovezan     addRuntimePreemptionSpecifier(function.dso_local(), llvmFunc);
8190a2131b7SAlex Zinenko 
8200a2131b7SAlex Zinenko     // Forward the pass-through attributes to LLVM.
8210a2131b7SAlex Zinenko     if (failed(forwardPassthroughAttributes(function.getLoc(),
8220a2131b7SAlex Zinenko                                             function.passthrough(), llvmFunc)))
8230a2131b7SAlex Zinenko       return failure();
8245d7231d8SStephan Herhut   }
8255d7231d8SStephan Herhut 
826a084b94fSSean Silva   return success();
827a084b94fSSean Silva }
828a084b94fSSean Silva 
829a084b94fSSean Silva LogicalResult ModuleTranslation::convertFunctions() {
8305d7231d8SStephan Herhut   // Convert functions.
83144fc7d72STres Popp   for (auto function : getModuleBody(mlirModule).getOps<LLVMFuncOp>()) {
8325d7231d8SStephan Herhut     // Ignore external functions.
8335d7231d8SStephan Herhut     if (function.isExternal())
8345d7231d8SStephan Herhut       continue;
8355d7231d8SStephan Herhut 
836baa1ec22SAlex Zinenko     if (failed(convertOneFunction(function)))
837baa1ec22SAlex Zinenko       return failure();
8385d7231d8SStephan Herhut   }
8395d7231d8SStephan Herhut 
840baa1ec22SAlex Zinenko   return success();
8415d7231d8SStephan Herhut }
8425d7231d8SStephan Herhut 
8434a2930f4SArpith C. Jacob llvm::MDNode *
8444a2930f4SArpith C. Jacob ModuleTranslation::getAccessGroup(Operation &opInst,
8454a2930f4SArpith C. Jacob                                   SymbolRefAttr accessGroupRef) const {
8464a2930f4SArpith C. Jacob   auto metadataName = accessGroupRef.getRootReference();
8474a2930f4SArpith C. Jacob   auto accessGroupName = accessGroupRef.getLeafReference();
8484a2930f4SArpith C. Jacob   auto metadataOp = SymbolTable::lookupNearestSymbolFrom<LLVM::MetadataOp>(
8494a2930f4SArpith C. Jacob       opInst.getParentOp(), metadataName);
8504a2930f4SArpith C. Jacob   auto *accessGroupOp =
8514a2930f4SArpith C. Jacob       SymbolTable::lookupNearestSymbolFrom(metadataOp, accessGroupName);
8524a2930f4SArpith C. Jacob   return accessGroupMetadataMapping.lookup(accessGroupOp);
8534a2930f4SArpith C. Jacob }
8544a2930f4SArpith C. Jacob 
8554a2930f4SArpith C. Jacob LogicalResult ModuleTranslation::createAccessGroupMetadata() {
8564a2930f4SArpith C. Jacob   mlirModule->walk([&](LLVM::MetadataOp metadatas) {
8574a2930f4SArpith C. Jacob     metadatas.walk([&](LLVM::AccessGroupMetadataOp op) {
8584a2930f4SArpith C. Jacob       llvm::LLVMContext &ctx = llvmModule->getContext();
8594a2930f4SArpith C. Jacob       llvm::MDNode *accessGroup = llvm::MDNode::getDistinct(ctx, {});
8604a2930f4SArpith C. Jacob       accessGroupMetadataMapping.insert({op, accessGroup});
8614a2930f4SArpith C. Jacob     });
8624a2930f4SArpith C. Jacob   });
8634a2930f4SArpith C. Jacob   return success();
8644a2930f4SArpith C. Jacob }
8654a2930f4SArpith C. Jacob 
8664e393350SArpith C. Jacob void ModuleTranslation::setAccessGroupsMetadata(Operation *op,
8674e393350SArpith C. Jacob                                                 llvm::Instruction *inst) {
8684e393350SArpith C. Jacob   auto accessGroups =
8694e393350SArpith C. Jacob       op->getAttrOfType<ArrayAttr>(LLVMDialect::getAccessGroupsAttrName());
8704e393350SArpith C. Jacob   if (accessGroups && !accessGroups.empty()) {
8714e393350SArpith C. Jacob     llvm::Module *module = inst->getModule();
8724e393350SArpith C. Jacob     SmallVector<llvm::Metadata *> metadatas;
8734e393350SArpith C. Jacob     for (SymbolRefAttr accessGroupRef :
8744e393350SArpith C. Jacob          accessGroups.getAsRange<SymbolRefAttr>())
8754e393350SArpith C. Jacob       metadatas.push_back(getAccessGroup(*op, accessGroupRef));
8764e393350SArpith C. Jacob 
8774e393350SArpith C. Jacob     llvm::MDNode *unionMD = nullptr;
8784e393350SArpith C. Jacob     if (metadatas.size() == 1)
8794e393350SArpith C. Jacob       unionMD = llvm::cast<llvm::MDNode>(metadatas.front());
8804e393350SArpith C. Jacob     else if (metadatas.size() >= 2)
8814e393350SArpith C. Jacob       unionMD = llvm::MDNode::get(module->getContext(), metadatas);
8824e393350SArpith C. Jacob 
8834e393350SArpith C. Jacob     inst->setMetadata(module->getMDKindID("llvm.access.group"), unionMD);
8844e393350SArpith C. Jacob   }
8854e393350SArpith C. Jacob }
8864e393350SArpith C. Jacob 
887d25e91d7STyler Augustine LogicalResult ModuleTranslation::createAliasScopeMetadata() {
888d25e91d7STyler Augustine   mlirModule->walk([&](LLVM::MetadataOp metadatas) {
889d25e91d7STyler Augustine     // Create the domains first, so they can be reference below in the scopes.
890d25e91d7STyler Augustine     DenseMap<Operation *, llvm::MDNode *> aliasScopeDomainMetadataMapping;
891d25e91d7STyler Augustine     metadatas.walk([&](LLVM::AliasScopeDomainMetadataOp op) {
892d25e91d7STyler Augustine       llvm::LLVMContext &ctx = llvmModule->getContext();
893d25e91d7STyler Augustine       llvm::SmallVector<llvm::Metadata *, 2> operands;
894d25e91d7STyler Augustine       operands.push_back({}); // Placeholder for self-reference
895d25e91d7STyler Augustine       if (Optional<StringRef> description = op.description())
896d25e91d7STyler Augustine         operands.push_back(llvm::MDString::get(ctx, description.getValue()));
897d25e91d7STyler Augustine       llvm::MDNode *domain = llvm::MDNode::get(ctx, operands);
898d25e91d7STyler Augustine       domain->replaceOperandWith(0, domain); // Self-reference for uniqueness
899d25e91d7STyler Augustine       aliasScopeDomainMetadataMapping.insert({op, domain});
900d25e91d7STyler Augustine     });
901d25e91d7STyler Augustine 
902d25e91d7STyler Augustine     // Now create the scopes, referencing the domains created above.
903d25e91d7STyler Augustine     metadatas.walk([&](LLVM::AliasScopeMetadataOp op) {
904d25e91d7STyler Augustine       llvm::LLVMContext &ctx = llvmModule->getContext();
905d25e91d7STyler Augustine       assert(isa<LLVM::MetadataOp>(op->getParentOp()));
906d25e91d7STyler Augustine       auto metadataOp = dyn_cast<LLVM::MetadataOp>(op->getParentOp());
907d25e91d7STyler Augustine       Operation *domainOp =
908d25e91d7STyler Augustine           SymbolTable::lookupNearestSymbolFrom(metadataOp, op.domainAttr());
909d25e91d7STyler Augustine       llvm::MDNode *domain = aliasScopeDomainMetadataMapping.lookup(domainOp);
910d25e91d7STyler Augustine       assert(domain && "Scope's domain should already be valid");
911d25e91d7STyler Augustine       llvm::SmallVector<llvm::Metadata *, 3> operands;
912d25e91d7STyler Augustine       operands.push_back({}); // Placeholder for self-reference
913d25e91d7STyler Augustine       operands.push_back(domain);
914d25e91d7STyler Augustine       if (Optional<StringRef> description = op.description())
915d25e91d7STyler Augustine         operands.push_back(llvm::MDString::get(ctx, description.getValue()));
916d25e91d7STyler Augustine       llvm::MDNode *scope = llvm::MDNode::get(ctx, operands);
917d25e91d7STyler Augustine       scope->replaceOperandWith(0, scope); // Self-reference for uniqueness
918d25e91d7STyler Augustine       aliasScopeMetadataMapping.insert({op, scope});
919d25e91d7STyler Augustine     });
920d25e91d7STyler Augustine   });
921d25e91d7STyler Augustine   return success();
922d25e91d7STyler Augustine }
923d25e91d7STyler Augustine 
924d25e91d7STyler Augustine llvm::MDNode *
925d25e91d7STyler Augustine ModuleTranslation::getAliasScope(Operation &opInst,
926d25e91d7STyler Augustine                                  SymbolRefAttr aliasScopeRef) const {
92741d4aa7dSChris Lattner   StringAttr metadataName = aliasScopeRef.getRootReference();
92841d4aa7dSChris Lattner   StringAttr scopeName = aliasScopeRef.getLeafReference();
929d25e91d7STyler Augustine   auto metadataOp = SymbolTable::lookupNearestSymbolFrom<LLVM::MetadataOp>(
930d25e91d7STyler Augustine       opInst.getParentOp(), metadataName);
931d25e91d7STyler Augustine   Operation *aliasScopeOp =
932d25e91d7STyler Augustine       SymbolTable::lookupNearestSymbolFrom(metadataOp, scopeName);
933d25e91d7STyler Augustine   return aliasScopeMetadataMapping.lookup(aliasScopeOp);
934d25e91d7STyler Augustine }
935d25e91d7STyler Augustine 
936d25e91d7STyler Augustine void ModuleTranslation::setAliasScopeMetadata(Operation *op,
937d25e91d7STyler Augustine                                               llvm::Instruction *inst) {
938d25e91d7STyler Augustine   auto populateScopeMetadata = [this, op, inst](StringRef attrName,
939d25e91d7STyler Augustine                                                 StringRef llvmMetadataName) {
940d25e91d7STyler Augustine     auto scopes = op->getAttrOfType<ArrayAttr>(attrName);
941d25e91d7STyler Augustine     if (!scopes || scopes.empty())
942d25e91d7STyler Augustine       return;
943d25e91d7STyler Augustine     llvm::Module *module = inst->getModule();
944d25e91d7STyler Augustine     SmallVector<llvm::Metadata *> scopeMDs;
945d25e91d7STyler Augustine     for (SymbolRefAttr scopeRef : scopes.getAsRange<SymbolRefAttr>())
946d25e91d7STyler Augustine       scopeMDs.push_back(getAliasScope(*op, scopeRef));
947d25e91d7STyler Augustine     llvm::MDNode *unionMD = nullptr;
948d25e91d7STyler Augustine     if (scopeMDs.size() == 1)
949d25e91d7STyler Augustine       unionMD = llvm::cast<llvm::MDNode>(scopeMDs.front());
950d25e91d7STyler Augustine     else if (scopeMDs.size() >= 2)
951d25e91d7STyler Augustine       unionMD = llvm::MDNode::get(module->getContext(), scopeMDs);
952d25e91d7STyler Augustine     inst->setMetadata(module->getMDKindID(llvmMetadataName), unionMD);
953d25e91d7STyler Augustine   };
954d25e91d7STyler Augustine 
955d25e91d7STyler Augustine   populateScopeMetadata(LLVMDialect::getAliasScopesAttrName(), "alias.scope");
956d25e91d7STyler Augustine   populateScopeMetadata(LLVMDialect::getNoAliasScopesAttrName(), "noalias");
957d25e91d7STyler Augustine }
958d25e91d7STyler Augustine 
959c69c9e0fSAlex Zinenko llvm::Type *ModuleTranslation::convertType(Type type) {
960b2ab375dSAlex Zinenko   return typeTranslator.translateType(type);
961aec38c61SAlex Zinenko }
962aec38c61SAlex Zinenko 
9638647e4c3SAlex Zinenko /// A helper to look up remapped operands in the value remapping table.
9648647e4c3SAlex Zinenko SmallVector<llvm::Value *> ModuleTranslation::lookupValues(ValueRange values) {
9658647e4c3SAlex Zinenko   SmallVector<llvm::Value *> remapped;
966efadb6b8SAlex Zinenko   remapped.reserve(values.size());
9670881a4f1SAlex Zinenko   for (Value v : values)
9680881a4f1SAlex Zinenko     remapped.push_back(lookupValue(v));
969efadb6b8SAlex Zinenko   return remapped;
970efadb6b8SAlex Zinenko }
971efadb6b8SAlex Zinenko 
97266900b3eSAlex Zinenko const llvm::DILocation *
97366900b3eSAlex Zinenko ModuleTranslation::translateLoc(Location loc, llvm::DILocalScope *scope) {
97466900b3eSAlex Zinenko   return debugTranslation->translateLoc(loc, scope);
97566900b3eSAlex Zinenko }
97666900b3eSAlex Zinenko 
977176379e0SAlex Zinenko llvm::NamedMDNode *
978176379e0SAlex Zinenko ModuleTranslation::getOrInsertNamedModuleMetadata(StringRef name) {
979176379e0SAlex Zinenko   return llvmModule->getOrInsertNamedMetadata(name);
980176379e0SAlex Zinenko }
981176379e0SAlex Zinenko 
98272d013ddSAlex Zinenko void ModuleTranslation::StackFrame::anchor() {}
98372d013ddSAlex Zinenko 
984ce8f10d6SAlex Zinenko static std::unique_ptr<llvm::Module>
985ce8f10d6SAlex Zinenko prepareLLVMModule(Operation *m, llvm::LLVMContext &llvmContext,
986ce8f10d6SAlex Zinenko                   StringRef name) {
987f9dc2b70SMehdi Amini   m->getContext()->getOrLoadDialect<LLVM::LLVMDialect>();
988db1c197bSAlex Zinenko   auto llvmModule = std::make_unique<llvm::Module>(name, llvmContext);
989168213f9SAlex Zinenko   if (auto dataLayoutAttr =
990168213f9SAlex Zinenko           m->getAttr(LLVM::LLVMDialect::getDataLayoutAttrName()))
991168213f9SAlex Zinenko     llvmModule->setDataLayout(dataLayoutAttr.cast<StringAttr>().getValue());
9925dd5a083SNicolas Vasilache   if (auto targetTripleAttr =
9935dd5a083SNicolas Vasilache           m->getAttr(LLVM::LLVMDialect::getTargetTripleAttrName()))
9945dd5a083SNicolas Vasilache     llvmModule->setTargetTriple(targetTripleAttr.cast<StringAttr>().getValue());
9955d7231d8SStephan Herhut 
9965d7231d8SStephan Herhut   // Inject declarations for `malloc` and `free` functions that can be used in
9975d7231d8SStephan Herhut   // memref allocation/deallocation coming from standard ops lowering.
998db1c197bSAlex Zinenko   llvm::IRBuilder<> builder(llvmContext);
9995d7231d8SStephan Herhut   llvmModule->getOrInsertFunction("malloc", builder.getInt8PtrTy(),
10005d7231d8SStephan Herhut                                   builder.getInt64Ty());
10015d7231d8SStephan Herhut   llvmModule->getOrInsertFunction("free", builder.getVoidTy(),
10025d7231d8SStephan Herhut                                   builder.getInt8PtrTy());
10035d7231d8SStephan Herhut 
10045d7231d8SStephan Herhut   return llvmModule;
10055d7231d8SStephan Herhut }
1006ce8f10d6SAlex Zinenko 
1007ce8f10d6SAlex Zinenko std::unique_ptr<llvm::Module>
1008ce8f10d6SAlex Zinenko mlir::translateModuleToLLVMIR(Operation *module, llvm::LLVMContext &llvmContext,
1009ce8f10d6SAlex Zinenko                               StringRef name) {
1010ce8f10d6SAlex Zinenko   if (!satisfiesLLVMModule(module))
1011ce8f10d6SAlex Zinenko     return nullptr;
1012ce8f10d6SAlex Zinenko   std::unique_ptr<llvm::Module> llvmModule =
1013ce8f10d6SAlex Zinenko       prepareLLVMModule(module, llvmContext, name);
1014ce8f10d6SAlex Zinenko 
1015ce8f10d6SAlex Zinenko   LLVM::ensureDistinctSuccessors(module);
1016ce8f10d6SAlex Zinenko 
1017ce8f10d6SAlex Zinenko   ModuleTranslation translator(module, std::move(llvmModule));
1018ce8f10d6SAlex Zinenko   if (failed(translator.convertFunctionSignatures()))
1019ce8f10d6SAlex Zinenko     return nullptr;
1020ce8f10d6SAlex Zinenko   if (failed(translator.convertGlobals()))
1021ce8f10d6SAlex Zinenko     return nullptr;
10224a2930f4SArpith C. Jacob   if (failed(translator.createAccessGroupMetadata()))
10234a2930f4SArpith C. Jacob     return nullptr;
1024d25e91d7STyler Augustine   if (failed(translator.createAliasScopeMetadata()))
1025d25e91d7STyler Augustine     return nullptr;
1026ce8f10d6SAlex Zinenko   if (failed(translator.convertFunctions()))
1027ce8f10d6SAlex Zinenko     return nullptr;
10288647e4c3SAlex Zinenko 
10298647e4c3SAlex Zinenko   // Convert other top-level operations if possible.
10308647e4c3SAlex Zinenko   llvm::IRBuilder<> llvmBuilder(llvmContext);
10318647e4c3SAlex Zinenko   for (Operation &o : getModuleBody(module).getOperations()) {
10328647e4c3SAlex Zinenko     if (!isa<LLVM::LLVMFuncOp, LLVM::GlobalOp, LLVM::MetadataOp>(&o) &&
10338647e4c3SAlex Zinenko         !o.hasTrait<OpTrait::IsTerminator>() &&
10348647e4c3SAlex Zinenko         failed(translator.convertOperation(o, llvmBuilder))) {
10358647e4c3SAlex Zinenko       return nullptr;
10368647e4c3SAlex Zinenko     }
10378647e4c3SAlex Zinenko   }
10388647e4c3SAlex Zinenko 
1039ce8f10d6SAlex Zinenko   if (llvm::verifyModule(*translator.llvmModule, &llvm::errs()))
1040ce8f10d6SAlex Zinenko     return nullptr;
1041ce8f10d6SAlex Zinenko 
1042ce8f10d6SAlex Zinenko   return std::move(translator.llvmModule);
1043ce8f10d6SAlex Zinenko }
1044