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"
1892a295ebSKiran Chandramohan #include "mlir/Dialect/OpenMP/OpenMPDialect.h"
195d7231d8SStephan Herhut #include "mlir/IR/Attributes.h"
2065fcddffSRiver Riddle #include "mlir/IR/BuiltinOps.h"
2109f7a55fSRiver Riddle #include "mlir/IR/BuiltinTypes.h"
22d4568ed7SGeorge Mitenkov #include "mlir/IR/RegionGraphTraits.h"
235d7231d8SStephan Herhut #include "mlir/Support/LLVM.h"
24ec1f4e7cSAlex Zinenko #include "mlir/Target/LLVMIR/TypeTranslation.h"
25ebf190fcSRiver Riddle #include "llvm/ADT/TypeSwitch.h"
265d7231d8SStephan Herhut 
27d4568ed7SGeorge Mitenkov #include "llvm/ADT/PostOrderIterator.h"
285d7231d8SStephan Herhut #include "llvm/ADT/SetVector.h"
2992a295ebSKiran Chandramohan #include "llvm/Frontend/OpenMP/OMPIRBuilder.h"
305d7231d8SStephan Herhut #include "llvm/IR/BasicBlock.h"
31d9067dcaSKiran Chandramohan #include "llvm/IR/CFG.h"
325d7231d8SStephan Herhut #include "llvm/IR/Constants.h"
335d7231d8SStephan Herhut #include "llvm/IR/DerivedTypes.h"
345d7231d8SStephan Herhut #include "llvm/IR/IRBuilder.h"
35047400edSNicolas Vasilache #include "llvm/IR/InlineAsm.h"
365d7231d8SStephan Herhut #include "llvm/IR/LLVMContext.h"
3799d03f03SGeorge Mitenkov #include "llvm/IR/MDBuilder.h"
385d7231d8SStephan Herhut #include "llvm/IR/Module.h"
39d9067dcaSKiran Chandramohan #include "llvm/Transforms/Utils/BasicBlockUtils.h"
405d7231d8SStephan Herhut #include "llvm/Transforms/Utils/Cloning.h"
415d7231d8SStephan Herhut 
422666b973SRiver Riddle using namespace mlir;
432666b973SRiver Riddle using namespace mlir::LLVM;
44c33d6970SRiver Riddle using namespace mlir::LLVM::detail;
455d7231d8SStephan Herhut 
46eb67bd78SAlex Zinenko #include "mlir/Dialect/LLVMIR/LLVMConversionEnumsToLLVM.inc"
47eb67bd78SAlex Zinenko 
48a922e231SAlex Zinenko /// Builds a constant of a sequential LLVM type `type`, potentially containing
49a922e231SAlex Zinenko /// other sequential types recursively, from the individual constant values
50a922e231SAlex Zinenko /// provided in `constants`. `shape` contains the number of elements in nested
51a922e231SAlex Zinenko /// sequential types. Reports errors at `loc` and returns nullptr on error.
52a4a42160SAlex Zinenko static llvm::Constant *
53a4a42160SAlex Zinenko buildSequentialConstant(ArrayRef<llvm::Constant *> &constants,
54a4a42160SAlex Zinenko                         ArrayRef<int64_t> shape, llvm::Type *type,
55a4a42160SAlex Zinenko                         Location loc) {
56a4a42160SAlex Zinenko   if (shape.empty()) {
57a4a42160SAlex Zinenko     llvm::Constant *result = constants.front();
58a4a42160SAlex Zinenko     constants = constants.drop_front();
59a4a42160SAlex Zinenko     return result;
60a4a42160SAlex Zinenko   }
61a4a42160SAlex Zinenko 
6268b03aeeSEli Friedman   llvm::Type *elementType;
6368b03aeeSEli Friedman   if (auto *arrayTy = dyn_cast<llvm::ArrayType>(type)) {
6468b03aeeSEli Friedman     elementType = arrayTy->getElementType();
6568b03aeeSEli Friedman   } else if (auto *vectorTy = dyn_cast<llvm::VectorType>(type)) {
6668b03aeeSEli Friedman     elementType = vectorTy->getElementType();
6768b03aeeSEli Friedman   } else {
68a4a42160SAlex Zinenko     emitError(loc) << "expected sequential LLVM types wrapping a scalar";
69a4a42160SAlex Zinenko     return nullptr;
70a4a42160SAlex Zinenko   }
71a4a42160SAlex Zinenko 
72a4a42160SAlex Zinenko   SmallVector<llvm::Constant *, 8> nested;
73a4a42160SAlex Zinenko   nested.reserve(shape.front());
74a4a42160SAlex Zinenko   for (int64_t i = 0; i < shape.front(); ++i) {
75a4a42160SAlex Zinenko     nested.push_back(buildSequentialConstant(constants, shape.drop_front(),
76a4a42160SAlex Zinenko                                              elementType, loc));
77a4a42160SAlex Zinenko     if (!nested.back())
78a4a42160SAlex Zinenko       return nullptr;
79a4a42160SAlex Zinenko   }
80a4a42160SAlex Zinenko 
81a4a42160SAlex Zinenko   if (shape.size() == 1 && type->isVectorTy())
82a4a42160SAlex Zinenko     return llvm::ConstantVector::get(nested);
83a4a42160SAlex Zinenko   return llvm::ConstantArray::get(
84a4a42160SAlex Zinenko       llvm::ArrayType::get(elementType, shape.front()), nested);
85a4a42160SAlex Zinenko }
86a4a42160SAlex Zinenko 
87fc817b09SKazuaki Ishizaki /// Returns the first non-sequential type nested in sequential types.
88a4a42160SAlex Zinenko static llvm::Type *getInnermostElementType(llvm::Type *type) {
8968b03aeeSEli Friedman   do {
9068b03aeeSEli Friedman     if (auto *arrayTy = dyn_cast<llvm::ArrayType>(type)) {
9168b03aeeSEli Friedman       type = arrayTy->getElementType();
9268b03aeeSEli Friedman     } else if (auto *vectorTy = dyn_cast<llvm::VectorType>(type)) {
9368b03aeeSEli Friedman       type = vectorTy->getElementType();
9468b03aeeSEli Friedman     } else {
95a4a42160SAlex Zinenko       return type;
96a4a42160SAlex Zinenko     }
9768b03aeeSEli Friedman   } while (1);
9868b03aeeSEli Friedman }
99a4a42160SAlex Zinenko 
1002666b973SRiver Riddle /// Create an LLVM IR constant of `llvmType` from the MLIR attribute `attr`.
1012666b973SRiver Riddle /// This currently supports integer, floating point, splat and dense element
1022666b973SRiver Riddle /// attributes and combinations thereof.  In case of error, report it to `loc`
1032666b973SRiver Riddle /// and return nullptr.
1045d7231d8SStephan Herhut llvm::Constant *ModuleTranslation::getLLVMConstant(llvm::Type *llvmType,
1055d7231d8SStephan Herhut                                                    Attribute attr,
1065d7231d8SStephan Herhut                                                    Location loc) {
10733a3a91bSChristian Sigg   if (!attr)
10833a3a91bSChristian Sigg     return llvm::UndefValue::get(llvmType);
109a4a42160SAlex Zinenko   if (llvmType->isStructTy()) {
110a4a42160SAlex Zinenko     emitError(loc, "struct types are not supported in constants");
111a4a42160SAlex Zinenko     return nullptr;
112a4a42160SAlex Zinenko   }
113ac9d742bSStephan Herhut   // For integer types, we allow a mismatch in sizes as the index type in
114ac9d742bSStephan Herhut   // MLIR might have a different size than the index type in the LLVM module.
1155d7231d8SStephan Herhut   if (auto intAttr = attr.dyn_cast<IntegerAttr>())
116ac9d742bSStephan Herhut     return llvm::ConstantInt::get(
117ac9d742bSStephan Herhut         llvmType,
118ac9d742bSStephan Herhut         intAttr.getValue().sextOrTrunc(llvmType->getIntegerBitWidth()));
1195d7231d8SStephan Herhut   if (auto floatAttr = attr.dyn_cast<FloatAttr>())
1205d7231d8SStephan Herhut     return llvm::ConstantFP::get(llvmType, floatAttr.getValue());
1219b9c647cSRiver Riddle   if (auto funcAttr = attr.dyn_cast<FlatSymbolRefAttr>())
122ff77397fSShraiysh Vaishay     return llvm::ConstantExpr::getBitCast(
123ff77397fSShraiysh Vaishay         functionMapping.lookup(funcAttr.getValue()), llvmType);
1245d7231d8SStephan Herhut   if (auto splatAttr = attr.dyn_cast<SplatElementsAttr>()) {
12568b03aeeSEli Friedman     llvm::Type *elementType;
12668b03aeeSEli Friedman     uint64_t numElements;
12768b03aeeSEli Friedman     if (auto *arrayTy = dyn_cast<llvm::ArrayType>(llvmType)) {
12868b03aeeSEli Friedman       elementType = arrayTy->getElementType();
12968b03aeeSEli Friedman       numElements = arrayTy->getNumElements();
13068b03aeeSEli Friedman     } else {
1315cba1c63SChristopher Tetreault       auto *vectorTy = cast<llvm::FixedVectorType>(llvmType);
13268b03aeeSEli Friedman       elementType = vectorTy->getElementType();
13368b03aeeSEli Friedman       numElements = vectorTy->getNumElements();
13468b03aeeSEli Friedman     }
135d6ea8ff0SAlex Zinenko     // Splat value is a scalar. Extract it only if the element type is not
136d6ea8ff0SAlex Zinenko     // another sequence type. The recursion terminates because each step removes
137d6ea8ff0SAlex Zinenko     // one outer sequential type.
13868b03aeeSEli Friedman     bool elementTypeSequential =
139d891d738SRahul Joshi         isa<llvm::ArrayType, llvm::VectorType>(elementType);
140d6ea8ff0SAlex Zinenko     llvm::Constant *child = getLLVMConstant(
141d6ea8ff0SAlex Zinenko         elementType,
14268b03aeeSEli Friedman         elementTypeSequential ? splatAttr : splatAttr.getSplatValue(), loc);
143a4a42160SAlex Zinenko     if (!child)
144a4a42160SAlex Zinenko       return nullptr;
1452f13df13SMLIR Team     if (llvmType->isVectorTy())
146396a42d9SRiver Riddle       return llvm::ConstantVector::getSplat(
1470f95e731SAlex Zinenko           llvm::ElementCount::get(numElements, /*Scalable=*/false), child);
1482f13df13SMLIR Team     if (llvmType->isArrayTy()) {
149ac9d742bSStephan Herhut       auto *arrayType = llvm::ArrayType::get(elementType, numElements);
1502f13df13SMLIR Team       SmallVector<llvm::Constant *, 8> constants(numElements, child);
1512f13df13SMLIR Team       return llvm::ConstantArray::get(arrayType, constants);
1522f13df13SMLIR Team     }
1535d7231d8SStephan Herhut   }
154a4a42160SAlex Zinenko 
155d906f84bSRiver Riddle   if (auto elementsAttr = attr.dyn_cast<ElementsAttr>()) {
156a4a42160SAlex Zinenko     assert(elementsAttr.getType().hasStaticShape());
157a4a42160SAlex Zinenko     assert(elementsAttr.getNumElements() != 0 &&
158a4a42160SAlex Zinenko            "unexpected empty elements attribute");
159a4a42160SAlex Zinenko     assert(!elementsAttr.getType().getShape().empty() &&
160a4a42160SAlex Zinenko            "unexpected empty elements attribute shape");
161a4a42160SAlex Zinenko 
1625d7231d8SStephan Herhut     SmallVector<llvm::Constant *, 8> constants;
163a4a42160SAlex Zinenko     constants.reserve(elementsAttr.getNumElements());
164a4a42160SAlex Zinenko     llvm::Type *innermostType = getInnermostElementType(llvmType);
165d906f84bSRiver Riddle     for (auto n : elementsAttr.getValues<Attribute>()) {
166a4a42160SAlex Zinenko       constants.push_back(getLLVMConstant(innermostType, n, loc));
1675d7231d8SStephan Herhut       if (!constants.back())
1685d7231d8SStephan Herhut         return nullptr;
1695d7231d8SStephan Herhut     }
170a4a42160SAlex Zinenko     ArrayRef<llvm::Constant *> constantsRef = constants;
171a4a42160SAlex Zinenko     llvm::Constant *result = buildSequentialConstant(
172a4a42160SAlex Zinenko         constantsRef, elementsAttr.getType().getShape(), llvmType, loc);
173a4a42160SAlex Zinenko     assert(constantsRef.empty() && "did not consume all elemental constants");
174a4a42160SAlex Zinenko     return result;
1752f13df13SMLIR Team   }
176a4a42160SAlex Zinenko 
177cb348dffSStephan Herhut   if (auto stringAttr = attr.dyn_cast<StringAttr>()) {
178cb348dffSStephan Herhut     return llvm::ConstantDataArray::get(
179cb348dffSStephan Herhut         llvmModule->getContext(), ArrayRef<char>{stringAttr.getValue().data(),
180cb348dffSStephan Herhut                                                  stringAttr.getValue().size()});
181cb348dffSStephan Herhut   }
182a4c3a645SRiver Riddle   emitError(loc, "unsupported constant value");
1835d7231d8SStephan Herhut   return nullptr;
1845d7231d8SStephan Herhut }
1855d7231d8SStephan Herhut 
1862666b973SRiver Riddle /// Convert MLIR integer comparison predicate to LLVM IR comparison predicate.
187ec82e1c9SAlex Zinenko static llvm::CmpInst::Predicate getLLVMCmpPredicate(ICmpPredicate p) {
1885d7231d8SStephan Herhut   switch (p) {
189ec82e1c9SAlex Zinenko   case LLVM::ICmpPredicate::eq:
1905d7231d8SStephan Herhut     return llvm::CmpInst::Predicate::ICMP_EQ;
191ec82e1c9SAlex Zinenko   case LLVM::ICmpPredicate::ne:
1925d7231d8SStephan Herhut     return llvm::CmpInst::Predicate::ICMP_NE;
193ec82e1c9SAlex Zinenko   case LLVM::ICmpPredicate::slt:
1945d7231d8SStephan Herhut     return llvm::CmpInst::Predicate::ICMP_SLT;
195ec82e1c9SAlex Zinenko   case LLVM::ICmpPredicate::sle:
1965d7231d8SStephan Herhut     return llvm::CmpInst::Predicate::ICMP_SLE;
197ec82e1c9SAlex Zinenko   case LLVM::ICmpPredicate::sgt:
1985d7231d8SStephan Herhut     return llvm::CmpInst::Predicate::ICMP_SGT;
199ec82e1c9SAlex Zinenko   case LLVM::ICmpPredicate::sge:
2005d7231d8SStephan Herhut     return llvm::CmpInst::Predicate::ICMP_SGE;
201ec82e1c9SAlex Zinenko   case LLVM::ICmpPredicate::ult:
2025d7231d8SStephan Herhut     return llvm::CmpInst::Predicate::ICMP_ULT;
203ec82e1c9SAlex Zinenko   case LLVM::ICmpPredicate::ule:
2045d7231d8SStephan Herhut     return llvm::CmpInst::Predicate::ICMP_ULE;
205ec82e1c9SAlex Zinenko   case LLVM::ICmpPredicate::ugt:
2065d7231d8SStephan Herhut     return llvm::CmpInst::Predicate::ICMP_UGT;
207ec82e1c9SAlex Zinenko   case LLVM::ICmpPredicate::uge:
2085d7231d8SStephan Herhut     return llvm::CmpInst::Predicate::ICMP_UGE;
2095d7231d8SStephan Herhut   }
210e6365f3dSJacques Pienaar   llvm_unreachable("incorrect comparison predicate");
2115d7231d8SStephan Herhut }
2125d7231d8SStephan Herhut 
21348fdc8d7SNagy Mostafa static llvm::CmpInst::Predicate getLLVMCmpPredicate(FCmpPredicate p) {
21448fdc8d7SNagy Mostafa   switch (p) {
21548fdc8d7SNagy Mostafa   case LLVM::FCmpPredicate::_false:
21648fdc8d7SNagy Mostafa     return llvm::CmpInst::Predicate::FCMP_FALSE;
21748fdc8d7SNagy Mostafa   case LLVM::FCmpPredicate::oeq:
21848fdc8d7SNagy Mostafa     return llvm::CmpInst::Predicate::FCMP_OEQ;
21948fdc8d7SNagy Mostafa   case LLVM::FCmpPredicate::ogt:
22048fdc8d7SNagy Mostafa     return llvm::CmpInst::Predicate::FCMP_OGT;
22148fdc8d7SNagy Mostafa   case LLVM::FCmpPredicate::oge:
22248fdc8d7SNagy Mostafa     return llvm::CmpInst::Predicate::FCMP_OGE;
22348fdc8d7SNagy Mostafa   case LLVM::FCmpPredicate::olt:
22448fdc8d7SNagy Mostafa     return llvm::CmpInst::Predicate::FCMP_OLT;
22548fdc8d7SNagy Mostafa   case LLVM::FCmpPredicate::ole:
22648fdc8d7SNagy Mostafa     return llvm::CmpInst::Predicate::FCMP_OLE;
22748fdc8d7SNagy Mostafa   case LLVM::FCmpPredicate::one:
22848fdc8d7SNagy Mostafa     return llvm::CmpInst::Predicate::FCMP_ONE;
22948fdc8d7SNagy Mostafa   case LLVM::FCmpPredicate::ord:
23048fdc8d7SNagy Mostafa     return llvm::CmpInst::Predicate::FCMP_ORD;
23148fdc8d7SNagy Mostafa   case LLVM::FCmpPredicate::ueq:
23248fdc8d7SNagy Mostafa     return llvm::CmpInst::Predicate::FCMP_UEQ;
23348fdc8d7SNagy Mostafa   case LLVM::FCmpPredicate::ugt:
23448fdc8d7SNagy Mostafa     return llvm::CmpInst::Predicate::FCMP_UGT;
23548fdc8d7SNagy Mostafa   case LLVM::FCmpPredicate::uge:
23648fdc8d7SNagy Mostafa     return llvm::CmpInst::Predicate::FCMP_UGE;
23748fdc8d7SNagy Mostafa   case LLVM::FCmpPredicate::ult:
23848fdc8d7SNagy Mostafa     return llvm::CmpInst::Predicate::FCMP_ULT;
23948fdc8d7SNagy Mostafa   case LLVM::FCmpPredicate::ule:
24048fdc8d7SNagy Mostafa     return llvm::CmpInst::Predicate::FCMP_ULE;
24148fdc8d7SNagy Mostafa   case LLVM::FCmpPredicate::une:
24248fdc8d7SNagy Mostafa     return llvm::CmpInst::Predicate::FCMP_UNE;
24348fdc8d7SNagy Mostafa   case LLVM::FCmpPredicate::uno:
24448fdc8d7SNagy Mostafa     return llvm::CmpInst::Predicate::FCMP_UNO;
24548fdc8d7SNagy Mostafa   case LLVM::FCmpPredicate::_true:
24648fdc8d7SNagy Mostafa     return llvm::CmpInst::Predicate::FCMP_TRUE;
24748fdc8d7SNagy Mostafa   }
248e6365f3dSJacques Pienaar   llvm_unreachable("incorrect comparison predicate");
24948fdc8d7SNagy Mostafa }
25048fdc8d7SNagy Mostafa 
25160a0c612SFrank Laub static llvm::AtomicRMWInst::BinOp getLLVMAtomicBinOp(AtomicBinOp op) {
25260a0c612SFrank Laub   switch (op) {
25360a0c612SFrank Laub   case LLVM::AtomicBinOp::xchg:
25460a0c612SFrank Laub     return llvm::AtomicRMWInst::BinOp::Xchg;
25560a0c612SFrank Laub   case LLVM::AtomicBinOp::add:
25660a0c612SFrank Laub     return llvm::AtomicRMWInst::BinOp::Add;
25760a0c612SFrank Laub   case LLVM::AtomicBinOp::sub:
25860a0c612SFrank Laub     return llvm::AtomicRMWInst::BinOp::Sub;
25960a0c612SFrank Laub   case LLVM::AtomicBinOp::_and:
26060a0c612SFrank Laub     return llvm::AtomicRMWInst::BinOp::And;
26160a0c612SFrank Laub   case LLVM::AtomicBinOp::nand:
26260a0c612SFrank Laub     return llvm::AtomicRMWInst::BinOp::Nand;
26360a0c612SFrank Laub   case LLVM::AtomicBinOp::_or:
26460a0c612SFrank Laub     return llvm::AtomicRMWInst::BinOp::Or;
26560a0c612SFrank Laub   case LLVM::AtomicBinOp::_xor:
26660a0c612SFrank Laub     return llvm::AtomicRMWInst::BinOp::Xor;
26760a0c612SFrank Laub   case LLVM::AtomicBinOp::max:
26860a0c612SFrank Laub     return llvm::AtomicRMWInst::BinOp::Max;
26960a0c612SFrank Laub   case LLVM::AtomicBinOp::min:
27060a0c612SFrank Laub     return llvm::AtomicRMWInst::BinOp::Min;
27160a0c612SFrank Laub   case LLVM::AtomicBinOp::umax:
27260a0c612SFrank Laub     return llvm::AtomicRMWInst::BinOp::UMax;
27360a0c612SFrank Laub   case LLVM::AtomicBinOp::umin:
27460a0c612SFrank Laub     return llvm::AtomicRMWInst::BinOp::UMin;
27560a0c612SFrank Laub   case LLVM::AtomicBinOp::fadd:
27660a0c612SFrank Laub     return llvm::AtomicRMWInst::BinOp::FAdd;
27760a0c612SFrank Laub   case LLVM::AtomicBinOp::fsub:
27860a0c612SFrank Laub     return llvm::AtomicRMWInst::BinOp::FSub;
27960a0c612SFrank Laub   }
28060a0c612SFrank Laub   llvm_unreachable("incorrect atomic binary operator");
28160a0c612SFrank Laub }
28260a0c612SFrank Laub 
28360a0c612SFrank Laub static llvm::AtomicOrdering getLLVMAtomicOrdering(AtomicOrdering ordering) {
28460a0c612SFrank Laub   switch (ordering) {
28560a0c612SFrank Laub   case LLVM::AtomicOrdering::not_atomic:
28660a0c612SFrank Laub     return llvm::AtomicOrdering::NotAtomic;
28760a0c612SFrank Laub   case LLVM::AtomicOrdering::unordered:
28860a0c612SFrank Laub     return llvm::AtomicOrdering::Unordered;
28960a0c612SFrank Laub   case LLVM::AtomicOrdering::monotonic:
29060a0c612SFrank Laub     return llvm::AtomicOrdering::Monotonic;
29160a0c612SFrank Laub   case LLVM::AtomicOrdering::acquire:
29260a0c612SFrank Laub     return llvm::AtomicOrdering::Acquire;
29360a0c612SFrank Laub   case LLVM::AtomicOrdering::release:
29460a0c612SFrank Laub     return llvm::AtomicOrdering::Release;
29560a0c612SFrank Laub   case LLVM::AtomicOrdering::acq_rel:
29660a0c612SFrank Laub     return llvm::AtomicOrdering::AcquireRelease;
29760a0c612SFrank Laub   case LLVM::AtomicOrdering::seq_cst:
29860a0c612SFrank Laub     return llvm::AtomicOrdering::SequentiallyConsistent;
29960a0c612SFrank Laub   }
30060a0c612SFrank Laub   llvm_unreachable("incorrect atomic ordering");
30160a0c612SFrank Laub }
30260a0c612SFrank Laub 
303c33d6970SRiver Riddle ModuleTranslation::ModuleTranslation(Operation *module,
304c33d6970SRiver Riddle                                      std::unique_ptr<llvm::Module> llvmModule)
305c33d6970SRiver Riddle     : mlirModule(module), llvmModule(std::move(llvmModule)),
306c33d6970SRiver Riddle       debugTranslation(
30792a295ebSKiran Chandramohan           std::make_unique<DebugTranslation>(module, *this->llvmModule)),
3089f9f89d4SMehdi Amini       ompDialect(module->getContext()->getLoadedDialect("omp")),
309b2ab375dSAlex Zinenko       typeTranslator(this->llvmModule->getContext()) {
310c33d6970SRiver Riddle   assert(satisfiesLLVMModule(mlirModule) &&
311c33d6970SRiver Riddle          "mlirModule should honor LLVM's module semantics.");
312c33d6970SRiver Riddle }
313d9067dcaSKiran Chandramohan ModuleTranslation::~ModuleTranslation() {
314d9067dcaSKiran Chandramohan   if (ompBuilder)
315d9067dcaSKiran Chandramohan     ompBuilder->finalize();
316d9067dcaSKiran Chandramohan }
317d9067dcaSKiran Chandramohan 
318d9067dcaSKiran Chandramohan /// Get the SSA value passed to the current block from the terminator operation
319d9067dcaSKiran Chandramohan /// of its predecessor.
320d9067dcaSKiran Chandramohan static Value getPHISourceValue(Block *current, Block *pred,
321d9067dcaSKiran Chandramohan                                unsigned numArguments, unsigned index) {
322d9067dcaSKiran Chandramohan   Operation &terminator = *pred->getTerminator();
323d9067dcaSKiran Chandramohan   if (isa<LLVM::BrOp>(terminator))
324d9067dcaSKiran Chandramohan     return terminator.getOperand(index);
325d9067dcaSKiran Chandramohan 
32614f24155SBrian Gesiak   SuccessorRange successors = terminator.getSuccessors();
32714f24155SBrian Gesiak   assert(std::adjacent_find(successors.begin(), successors.end()) ==
32814f24155SBrian Gesiak              successors.end() &&
32914f24155SBrian Gesiak          "successors with arguments in LLVM branches must be different blocks");
33058f2b765SChristian Sigg   (void)successors;
331d9067dcaSKiran Chandramohan 
33214f24155SBrian Gesiak   // For instructions that branch based on a condition value, we need to take
33314f24155SBrian Gesiak   // the operands for the branch that was taken.
33414f24155SBrian Gesiak   if (auto condBranchOp = dyn_cast<LLVM::CondBrOp>(terminator)) {
33514f24155SBrian Gesiak     // For conditional branches, we take the operands from either the "true" or
33614f24155SBrian Gesiak     // the "false" branch.
337d9067dcaSKiran Chandramohan     return condBranchOp.getSuccessor(0) == current
338d9067dcaSKiran Chandramohan                ? condBranchOp.trueDestOperands()[index]
339d9067dcaSKiran Chandramohan                : condBranchOp.falseDestOperands()[index];
34014f24155SBrian Gesiak   } else if (auto switchOp = dyn_cast<LLVM::SwitchOp>(terminator)) {
34114f24155SBrian Gesiak     // For switches, we take the operands from either the default case, or from
34214f24155SBrian Gesiak     // the case branch that was taken.
34314f24155SBrian Gesiak     if (switchOp.defaultDestination() == current)
34414f24155SBrian Gesiak       return switchOp.defaultOperands()[index];
34514f24155SBrian Gesiak     for (auto i : llvm::enumerate(switchOp.caseDestinations()))
34614f24155SBrian Gesiak       if (i.value() == current)
34714f24155SBrian Gesiak         return switchOp.getCaseOperands(i.index())[index];
34814f24155SBrian Gesiak   }
34914f24155SBrian Gesiak 
35014f24155SBrian Gesiak   llvm_unreachable("only branch or switch operations can be terminators of a "
35114f24155SBrian Gesiak                    "block that has successors");
352d9067dcaSKiran Chandramohan }
353d9067dcaSKiran Chandramohan 
354d9067dcaSKiran Chandramohan /// Connect the PHI nodes to the results of preceding blocks.
355d9067dcaSKiran Chandramohan template <typename T>
356db884dafSAlex Zinenko static void connectPHINodes(
357db884dafSAlex Zinenko     T &func, const DenseMap<Value, llvm::Value *> &valueMapping,
358db884dafSAlex Zinenko     const DenseMap<Block *, llvm::BasicBlock *> &blockMapping,
359db884dafSAlex Zinenko     const DenseMap<Operation *, llvm::Instruction *> &branchMapping) {
360d9067dcaSKiran Chandramohan   // Skip the first block, it cannot be branched to and its arguments correspond
361d9067dcaSKiran Chandramohan   // to the arguments of the LLVM function.
362d9067dcaSKiran Chandramohan   for (auto it = std::next(func.begin()), eit = func.end(); it != eit; ++it) {
363d9067dcaSKiran Chandramohan     Block *bb = &*it;
364d9067dcaSKiran Chandramohan     llvm::BasicBlock *llvmBB = blockMapping.lookup(bb);
365d9067dcaSKiran Chandramohan     auto phis = llvmBB->phis();
366d9067dcaSKiran Chandramohan     auto numArguments = bb->getNumArguments();
367d9067dcaSKiran Chandramohan     assert(numArguments == std::distance(phis.begin(), phis.end()));
368d9067dcaSKiran Chandramohan     for (auto &numberedPhiNode : llvm::enumerate(phis)) {
369d9067dcaSKiran Chandramohan       auto &phiNode = numberedPhiNode.value();
370d9067dcaSKiran Chandramohan       unsigned index = numberedPhiNode.index();
371d9067dcaSKiran Chandramohan       for (auto *pred : bb->getPredecessors()) {
372db884dafSAlex Zinenko         // Find the LLVM IR block that contains the converted terminator
373db884dafSAlex Zinenko         // instruction and use it in the PHI node. Note that this block is not
374db884dafSAlex Zinenko         // necessarily the same as blockMapping.lookup(pred), some operations
375db884dafSAlex Zinenko         // (in particular, OpenMP operations using OpenMPIRBuilder) may have
376db884dafSAlex Zinenko         // split the blocks.
377db884dafSAlex Zinenko         llvm::Instruction *terminator =
378db884dafSAlex Zinenko             branchMapping.lookup(pred->getTerminator());
379db884dafSAlex Zinenko         assert(terminator && "missing the mapping for a terminator");
380d9067dcaSKiran Chandramohan         phiNode.addIncoming(valueMapping.lookup(getPHISourceValue(
381d9067dcaSKiran Chandramohan                                 bb, pred, numArguments, index)),
382db884dafSAlex Zinenko                             terminator->getParent());
383d9067dcaSKiran Chandramohan       }
384d9067dcaSKiran Chandramohan     }
385d9067dcaSKiran Chandramohan   }
386d9067dcaSKiran Chandramohan }
387d9067dcaSKiran Chandramohan 
388d9067dcaSKiran Chandramohan /// Sort function blocks topologically.
389d9067dcaSKiran Chandramohan template <typename T>
390d9067dcaSKiran Chandramohan static llvm::SetVector<Block *> topologicalSort(T &f) {
391d4568ed7SGeorge Mitenkov   // For each block that has not been visited yet (i.e. that has no
392d4568ed7SGeorge Mitenkov   // predecessors), add it to the list as well as its successors.
393d9067dcaSKiran Chandramohan   llvm::SetVector<Block *> blocks;
394d9067dcaSKiran Chandramohan   for (Block &b : f) {
395d4568ed7SGeorge Mitenkov     if (blocks.count(&b) == 0) {
396d4568ed7SGeorge Mitenkov       llvm::ReversePostOrderTraversal<Block *> traversal(&b);
397d4568ed7SGeorge Mitenkov       blocks.insert(traversal.begin(), traversal.end());
398d4568ed7SGeorge Mitenkov     }
399d9067dcaSKiran Chandramohan   }
400d9067dcaSKiran Chandramohan   assert(blocks.size() == f.getBlocks().size() && "some blocks are not sorted");
401d9067dcaSKiran Chandramohan 
402d9067dcaSKiran Chandramohan   return blocks;
403d9067dcaSKiran Chandramohan }
404d9067dcaSKiran Chandramohan 
405d9067dcaSKiran Chandramohan /// Convert the OpenMP parallel Operation to LLVM IR.
406d9067dcaSKiran Chandramohan LogicalResult
407d9067dcaSKiran Chandramohan ModuleTranslation::convertOmpParallel(Operation &opInst,
408d9067dcaSKiran Chandramohan                                       llvm::IRBuilder<> &builder) {
409d9067dcaSKiran Chandramohan   using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy;
410c11d868aSSourabh Singh Tomar   // TODO: support error propagation in OpenMPIRBuilder and use it instead of
411c11d868aSSourabh Singh Tomar   // relying on captured variables.
412c11d868aSSourabh Singh Tomar   LogicalResult bodyGenStatus = success();
413d9067dcaSKiran Chandramohan 
414d9067dcaSKiran Chandramohan   auto bodyGenCB = [&](InsertPointTy allocaIP, InsertPointTy codeGenIP,
4154744478bSSourabh Singh Tomar                        llvm::BasicBlock &continuationBlock) {
41610164a2eSAlex Zinenko     // ParallelOp has only one region associated with it.
417793c29a2SSourabh Singh Tomar     auto &region = cast<omp::ParallelOp>(opInst).getRegion();
41810164a2eSAlex Zinenko     convertOmpOpRegions(region, "omp.par.region", valueMapping, blockMapping,
4194744478bSSourabh Singh Tomar                         *codeGenIP.getBlock(), continuationBlock, builder,
42010164a2eSAlex Zinenko                         bodyGenStatus);
421d9067dcaSKiran Chandramohan   };
422d9067dcaSKiran Chandramohan 
423d9067dcaSKiran Chandramohan   // TODO: Perform appropriate actions according to the data-sharing
424d9067dcaSKiran Chandramohan   // attribute (shared, private, firstprivate, ...) of variables.
425d9067dcaSKiran Chandramohan   // Currently defaults to shared.
426d9067dcaSKiran Chandramohan   auto privCB = [&](InsertPointTy allocaIP, InsertPointTy codeGenIP,
427240dd924SAlex Zinenko                     llvm::Value &, llvm::Value &vPtr,
428d9067dcaSKiran Chandramohan                     llvm::Value *&replacementValue) -> InsertPointTy {
429d9067dcaSKiran Chandramohan     replacementValue = &vPtr;
430d9067dcaSKiran Chandramohan 
431d9067dcaSKiran Chandramohan     return codeGenIP;
432d9067dcaSKiran Chandramohan   };
433d9067dcaSKiran Chandramohan 
434d9067dcaSKiran Chandramohan   // TODO: Perform finalization actions for variables. This has to be
435d9067dcaSKiran Chandramohan   // called for variables which have destructors/finalizers.
436d9067dcaSKiran Chandramohan   auto finiCB = [&](InsertPointTy codeGenIP) {};
437d9067dcaSKiran Chandramohan 
438d9067dcaSKiran Chandramohan   llvm::Value *ifCond = nullptr;
439660832c4SKiran Chandramohan   if (auto ifExprVar = cast<omp::ParallelOp>(opInst).if_expr_var())
440660832c4SKiran Chandramohan     ifCond = valueMapping.lookup(ifExprVar);
441d9067dcaSKiran Chandramohan   llvm::Value *numThreads = nullptr;
442660832c4SKiran Chandramohan   if (auto numThreadsVar = cast<omp::ParallelOp>(opInst).num_threads_var())
443660832c4SKiran Chandramohan     numThreads = valueMapping.lookup(numThreadsVar);
444e6c5e6efSKiran Chandramohan   llvm::omp::ProcBindKind pbKind = llvm::omp::OMP_PROC_BIND_default;
445e6c5e6efSKiran Chandramohan   if (auto bind = cast<omp::ParallelOp>(opInst).proc_bind_val())
446e6c5e6efSKiran Chandramohan     pbKind = llvm::omp::getProcBindKind(bind.getValue());
447660832c4SKiran Chandramohan   // TODO: Is the Parallel construct cancellable?
448d9067dcaSKiran Chandramohan   bool isCancellable = false;
4494d83aa47SJohannes Doerfert   // TODO: Determine the actual alloca insertion point, e.g., the function
4504d83aa47SJohannes Doerfert   // entry or the alloca insertion point as provided by the body callback
4514d83aa47SJohannes Doerfert   // above.
4524d83aa47SJohannes Doerfert   llvm::OpenMPIRBuilder::InsertPointTy allocaIP(builder.saveIP());
453c11d868aSSourabh Singh Tomar   if (failed(bodyGenStatus))
454c11d868aSSourabh Singh Tomar     return failure();
455e6c5e6efSKiran Chandramohan   builder.restoreIP(
456e5dba2d7SMichael Kruse       ompBuilder->createParallel(builder, allocaIP, bodyGenCB, privCB, finiCB,
457e6c5e6efSKiran Chandramohan                                  ifCond, numThreads, pbKind, isCancellable));
458d9067dcaSKiran Chandramohan   return success();
459d9067dcaSKiran Chandramohan }
460c33d6970SRiver Riddle 
461c11d868aSSourabh Singh Tomar void ModuleTranslation::convertOmpOpRegions(
46210164a2eSAlex Zinenko     Region &region, StringRef blockName,
46310164a2eSAlex Zinenko     DenseMap<Value, llvm::Value *> &valueMapping,
464c11d868aSSourabh Singh Tomar     DenseMap<Block *, llvm::BasicBlock *> &blockMapping,
46510164a2eSAlex Zinenko     llvm::BasicBlock &sourceBlock, llvm::BasicBlock &continuationBlock,
466c11d868aSSourabh Singh Tomar     llvm::IRBuilder<> &builder, LogicalResult &bodyGenStatus) {
46710164a2eSAlex Zinenko   llvm::LLVMContext &llvmContext = builder.getContext();
46810164a2eSAlex Zinenko   for (Block &bb : region) {
46910164a2eSAlex Zinenko     llvm::BasicBlock *llvmBB = llvm::BasicBlock::Create(
47010164a2eSAlex Zinenko         llvmContext, blockName, builder.GetInsertBlock()->getParent());
47110164a2eSAlex Zinenko     blockMapping[&bb] = llvmBB;
47210164a2eSAlex Zinenko   }
47310164a2eSAlex Zinenko 
47410164a2eSAlex Zinenko   llvm::Instruction *sourceTerminator = sourceBlock.getTerminator();
47510164a2eSAlex Zinenko 
476c11d868aSSourabh Singh Tomar   // Convert blocks one by one in topological order to ensure
477c11d868aSSourabh Singh Tomar   // defs are converted before uses.
478c11d868aSSourabh Singh Tomar   llvm::SetVector<Block *> blocks = topologicalSort(region);
47910164a2eSAlex Zinenko   for (Block *bb : blocks) {
48010164a2eSAlex Zinenko     llvm::BasicBlock *llvmBB = blockMapping[bb];
48110164a2eSAlex Zinenko     // Retarget the branch of the entry block to the entry block of the
48210164a2eSAlex Zinenko     // converted region (regions are single-entry).
483c11d868aSSourabh Singh Tomar     if (bb->isEntryBlock()) {
48410164a2eSAlex Zinenko       assert(sourceTerminator->getNumSuccessors() == 1 &&
48510164a2eSAlex Zinenko              "provided entry block has multiple successors");
48610164a2eSAlex Zinenko       assert(sourceTerminator->getSuccessor(0) == &continuationBlock &&
48710164a2eSAlex Zinenko              "ContinuationBlock is not the successor of the entry block");
48810164a2eSAlex Zinenko       sourceTerminator->setSuccessor(0, llvmBB);
489c11d868aSSourabh Singh Tomar     }
490c11d868aSSourabh Singh Tomar 
49110164a2eSAlex Zinenko     llvm::IRBuilder<>::InsertPointGuard guard(builder);
49210164a2eSAlex Zinenko     if (failed(convertBlock(*bb, bb->isEntryBlock(), builder))) {
493c11d868aSSourabh Singh Tomar       bodyGenStatus = failure();
494c11d868aSSourabh Singh Tomar       return;
495c11d868aSSourabh Singh Tomar     }
49610164a2eSAlex Zinenko 
49710164a2eSAlex Zinenko     // Special handling for `omp.yield` and `omp.terminator` (we may have more
49810164a2eSAlex Zinenko     // than one): they return the control to the parent OpenMP dialect operation
49910164a2eSAlex Zinenko     // so replace them with the branch to the continuation block. We handle this
50010164a2eSAlex Zinenko     // here to avoid relying inter-function communication through the
50110164a2eSAlex Zinenko     // ModuleTranslation class to set up the correct insertion point. This is
50210164a2eSAlex Zinenko     // also consistent with MLIR's idiom of handling special region terminators
50310164a2eSAlex Zinenko     // in the same code that handles the region-owning operation.
50410164a2eSAlex Zinenko     if (isa<omp::TerminatorOp, omp::YieldOp>(bb->getTerminator()))
50510164a2eSAlex Zinenko       builder.CreateBr(&continuationBlock);
506c11d868aSSourabh Singh Tomar   }
507c11d868aSSourabh Singh Tomar   // Finally, after all blocks have been traversed and values mapped,
508c11d868aSSourabh Singh Tomar   // connect the PHI nodes to the results of preceding blocks.
509db884dafSAlex Zinenko   connectPHINodes(region, valueMapping, blockMapping, branchMapping);
510c11d868aSSourabh Singh Tomar }
511c11d868aSSourabh Singh Tomar 
512c11d868aSSourabh Singh Tomar LogicalResult ModuleTranslation::convertOmpMaster(Operation &opInst,
513c11d868aSSourabh Singh Tomar                                                   llvm::IRBuilder<> &builder) {
514c11d868aSSourabh Singh Tomar   using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy;
515c11d868aSSourabh Singh Tomar   // TODO: support error propagation in OpenMPIRBuilder and use it instead of
516c11d868aSSourabh Singh Tomar   // relying on captured variables.
517c11d868aSSourabh Singh Tomar   LogicalResult bodyGenStatus = success();
518c11d868aSSourabh Singh Tomar 
519c11d868aSSourabh Singh Tomar   auto bodyGenCB = [&](InsertPointTy allocaIP, InsertPointTy codeGenIP,
5204744478bSSourabh Singh Tomar                        llvm::BasicBlock &continuationBlock) {
52110164a2eSAlex Zinenko     // MasterOp has only one region associated with it.
522c11d868aSSourabh Singh Tomar     auto &region = cast<omp::MasterOp>(opInst).getRegion();
52310164a2eSAlex Zinenko     convertOmpOpRegions(region, "omp.master.region", valueMapping, blockMapping,
5244744478bSSourabh Singh Tomar                         *codeGenIP.getBlock(), continuationBlock, builder,
52510164a2eSAlex Zinenko                         bodyGenStatus);
526c11d868aSSourabh Singh Tomar   };
527c11d868aSSourabh Singh Tomar 
528c11d868aSSourabh Singh Tomar   // TODO: Perform finalization actions for variables. This has to be
529c11d868aSSourabh Singh Tomar   // called for variables which have destructors/finalizers.
530c11d868aSSourabh Singh Tomar   auto finiCB = [&](InsertPointTy codeGenIP) {};
531c11d868aSSourabh Singh Tomar 
532c11d868aSSourabh Singh Tomar   builder.restoreIP(ompBuilder->createMaster(builder, bodyGenCB, finiCB));
533c11d868aSSourabh Singh Tomar   return success();
534c11d868aSSourabh Singh Tomar }
535c11d868aSSourabh Singh Tomar 
53632a884c9SAlex Zinenko /// Converts an OpenMP workshare loop into LLVM IR using OpenMPIRBuilder.
53732a884c9SAlex Zinenko LogicalResult ModuleTranslation::convertOmpWsLoop(Operation &opInst,
53832a884c9SAlex Zinenko                                                   llvm::IRBuilder<> &builder) {
53932a884c9SAlex Zinenko   auto loop = cast<omp::WsLoopOp>(opInst);
54032a884c9SAlex Zinenko   // TODO: this should be in the op verifier instead.
54132a884c9SAlex Zinenko   if (loop.lowerBound().empty())
54232a884c9SAlex Zinenko     return failure();
54332a884c9SAlex Zinenko 
54432a884c9SAlex Zinenko   if (loop.getNumLoops() != 1)
54532a884c9SAlex Zinenko     return opInst.emitOpError("collapsed loops not yet supported");
54632a884c9SAlex Zinenko 
54732a884c9SAlex Zinenko   if (loop.schedule_val().hasValue() &&
54832a884c9SAlex Zinenko       omp::symbolizeClauseScheduleKind(loop.schedule_val().getValue()) !=
54932a884c9SAlex Zinenko           omp::ClauseScheduleKind::Static)
55032a884c9SAlex Zinenko     return opInst.emitOpError(
55132a884c9SAlex Zinenko         "only static (default) loop schedule is currently supported");
55232a884c9SAlex Zinenko 
55332a884c9SAlex Zinenko   // Find the loop configuration.
55432a884c9SAlex Zinenko   llvm::Value *lowerBound = valueMapping.lookup(loop.lowerBound()[0]);
55532a884c9SAlex Zinenko   llvm::Value *upperBound = valueMapping.lookup(loop.upperBound()[0]);
55632a884c9SAlex Zinenko   llvm::Value *step = valueMapping.lookup(loop.step()[0]);
55732a884c9SAlex Zinenko   llvm::Type *ivType = step->getType();
55832a884c9SAlex Zinenko   llvm::Value *chunk = loop.schedule_chunk_var()
55932a884c9SAlex Zinenko                            ? valueMapping[loop.schedule_chunk_var()]
56032a884c9SAlex Zinenko                            : llvm::ConstantInt::get(ivType, 1);
56132a884c9SAlex Zinenko 
56232a884c9SAlex Zinenko   // Set up the source location value for OpenMP runtime.
56332a884c9SAlex Zinenko   llvm::DISubprogram *subprogram =
56432a884c9SAlex Zinenko       builder.GetInsertBlock()->getParent()->getSubprogram();
56532a884c9SAlex Zinenko   const llvm::DILocation *diLoc =
56632a884c9SAlex Zinenko       debugTranslation->translateLoc(opInst.getLoc(), subprogram);
56732a884c9SAlex Zinenko   llvm::OpenMPIRBuilder::LocationDescription ompLoc(builder.saveIP(),
56832a884c9SAlex Zinenko                                                     llvm::DebugLoc(diLoc));
56932a884c9SAlex Zinenko 
57032a884c9SAlex Zinenko   // Generator of the canonical loop body. Produces an SESE region of basic
57132a884c9SAlex Zinenko   // blocks.
57232a884c9SAlex Zinenko   // TODO: support error propagation in OpenMPIRBuilder and use it instead of
57332a884c9SAlex Zinenko   // relying on captured variables.
57432a884c9SAlex Zinenko   LogicalResult bodyGenStatus = success();
57532a884c9SAlex Zinenko   auto bodyGen = [&](llvm::OpenMPIRBuilder::InsertPointTy ip, llvm::Value *iv) {
57632a884c9SAlex Zinenko     llvm::IRBuilder<>::InsertPointGuard guard(builder);
57732a884c9SAlex Zinenko 
57832a884c9SAlex Zinenko     // Make sure further conversions know about the induction variable.
57932a884c9SAlex Zinenko     valueMapping[loop.getRegion().front().getArgument(0)] = iv;
58032a884c9SAlex Zinenko 
58132a884c9SAlex Zinenko     llvm::BasicBlock *entryBlock = ip.getBlock();
58232a884c9SAlex Zinenko     llvm::BasicBlock *exitBlock =
58332a884c9SAlex Zinenko         entryBlock->splitBasicBlock(ip.getPoint(), "omp.wsloop.exit");
58432a884c9SAlex Zinenko 
58532a884c9SAlex Zinenko     // Convert the body of the loop.
58610164a2eSAlex Zinenko     convertOmpOpRegions(loop.region(), "omp.wsloop.region", valueMapping,
58710164a2eSAlex Zinenko                         blockMapping, *entryBlock, *exitBlock, builder,
58810164a2eSAlex Zinenko                         bodyGenStatus);
58932a884c9SAlex Zinenko   };
59032a884c9SAlex Zinenko 
59132a884c9SAlex Zinenko   // Delegate actual loop construction to the OpenMP IRBuilder.
59232a884c9SAlex Zinenko   // TODO: this currently assumes WsLoop is semantically similar to SCF loop,
593268ff38aSKiran Chandramohan   // i.e. it has a positive step, uses signed integer semantics. Reconsider
594268ff38aSKiran Chandramohan   // this code when WsLoop clearly supports more cases.
59532a884c9SAlex Zinenko   llvm::BasicBlock *insertBlock = builder.GetInsertBlock();
59632a884c9SAlex Zinenko   llvm::CanonicalLoopInfo *loopInfo = ompBuilder->createCanonicalLoop(
59732a884c9SAlex Zinenko       ompLoc, bodyGen, lowerBound, upperBound, step, /*IsSigned=*/true,
598268ff38aSKiran Chandramohan       /*InclusiveStop=*/loop.inclusive());
59932a884c9SAlex Zinenko   if (failed(bodyGenStatus))
60032a884c9SAlex Zinenko     return failure();
60132a884c9SAlex Zinenko 
60232a884c9SAlex Zinenko   // TODO: get the alloca insertion point from the parallel operation builder.
60332a884c9SAlex Zinenko   // If we insert the at the top of the current function, they will be passed as
60432a884c9SAlex Zinenko   // extra arguments into the function the parallel operation builder outlines.
60532a884c9SAlex Zinenko   // Put them at the start of the current block for now.
60632a884c9SAlex Zinenko   llvm::OpenMPIRBuilder::InsertPointTy allocaIP(
60732a884c9SAlex Zinenko       insertBlock, insertBlock->getFirstInsertionPt());
608268ff38aSKiran Chandramohan   loopInfo = ompBuilder->createStaticWorkshareLoop(ompLoc, loopInfo, allocaIP,
609268ff38aSKiran Chandramohan                                                    !loop.nowait(), chunk);
61032a884c9SAlex Zinenko 
61132a884c9SAlex Zinenko   // Continue building IR after the loop.
61232a884c9SAlex Zinenko   builder.restoreIP(loopInfo->getAfterIP());
61332a884c9SAlex Zinenko   return success();
61432a884c9SAlex Zinenko }
61532a884c9SAlex Zinenko 
6167ecee63eSKiran Kumar T P /// Given an OpenMP MLIR operation, create the corresponding LLVM IR
6177ecee63eSKiran Kumar T P /// (including OpenMP runtime calls).
6187ecee63eSKiran Kumar T P LogicalResult
6197ecee63eSKiran Kumar T P ModuleTranslation::convertOmpOperation(Operation &opInst,
6207ecee63eSKiran Kumar T P                                        llvm::IRBuilder<> &builder) {
6217ecee63eSKiran Kumar T P   if (!ompBuilder) {
6227ecee63eSKiran Kumar T P     ompBuilder = std::make_unique<llvm::OpenMPIRBuilder>(*llvmModule);
6237ecee63eSKiran Kumar T P     ompBuilder->initialize();
6247ecee63eSKiran Kumar T P   }
625ebf190fcSRiver Riddle   return llvm::TypeSwitch<Operation *, LogicalResult>(&opInst)
6267ecee63eSKiran Kumar T P       .Case([&](omp::BarrierOp) {
627e5dba2d7SMichael Kruse         ompBuilder->createBarrier(builder.saveIP(), llvm::omp::OMPD_barrier);
6287ecee63eSKiran Kumar T P         return success();
6297ecee63eSKiran Kumar T P       })
6307ecee63eSKiran Kumar T P       .Case([&](omp::TaskwaitOp) {
631e5dba2d7SMichael Kruse         ompBuilder->createTaskwait(builder.saveIP());
6327ecee63eSKiran Kumar T P         return success();
6337ecee63eSKiran Kumar T P       })
6347ecee63eSKiran Kumar T P       .Case([&](omp::TaskyieldOp) {
635e5dba2d7SMichael Kruse         ompBuilder->createTaskyield(builder.saveIP());
6367ecee63eSKiran Kumar T P         return success();
6377ecee63eSKiran Kumar T P       })
638fa8fc9ffSKiran Kumar T P       .Case([&](omp::FlushOp) {
63941b09f4eSKazuaki Ishizaki         // No support in Openmp runtime function (__kmpc_flush) to accept
640fa8fc9ffSKiran Kumar T P         // the argument list.
641fa8fc9ffSKiran Kumar T P         // OpenMP standard states the following:
642fa8fc9ffSKiran Kumar T P         //  "An implementation may implement a flush with a list by ignoring
643fa8fc9ffSKiran Kumar T P         //   the list, and treating it the same as a flush without a list."
644fa8fc9ffSKiran Kumar T P         //
645fa8fc9ffSKiran Kumar T P         // The argument list is discarded so that, flush with a list is treated
646fa8fc9ffSKiran Kumar T P         // same as a flush without a list.
647e5dba2d7SMichael Kruse         ompBuilder->createFlush(builder.saveIP());
648fa8fc9ffSKiran Kumar T P         return success();
649fa8fc9ffSKiran Kumar T P       })
650d9067dcaSKiran Chandramohan       .Case(
651d9067dcaSKiran Chandramohan           [&](omp::ParallelOp) { return convertOmpParallel(opInst, builder); })
652c11d868aSSourabh Singh Tomar       .Case([&](omp::MasterOp) { return convertOmpMaster(opInst, builder); })
65332a884c9SAlex Zinenko       .Case([&](omp::WsLoopOp) { return convertOmpWsLoop(opInst, builder); })
65410164a2eSAlex Zinenko       .Case<omp::YieldOp, omp::TerminatorOp>([](auto op) {
65510164a2eSAlex Zinenko         // `yield` and `terminator` can be just omitted. The block structure was
65610164a2eSAlex Zinenko         // created in the function that handles their parent operation.
65710164a2eSAlex Zinenko         assert(op->getNumOperands() == 0 &&
65810164a2eSAlex Zinenko                "unexpected OpenMP terminator with operands");
65932a884c9SAlex Zinenko         return success();
66032a884c9SAlex Zinenko       })
6617ecee63eSKiran Kumar T P       .Default([&](Operation *inst) {
6627ecee63eSKiran Kumar T P         return inst->emitError("unsupported OpenMP operation: ")
6637ecee63eSKiran Kumar T P                << inst->getName();
6647ecee63eSKiran Kumar T P       });
6657ecee63eSKiran Kumar T P }
6667ecee63eSKiran Kumar T P 
667c1d58c2bSIvan Butygin static llvm::FastMathFlags getFastmathFlags(FastmathFlagsInterface &op) {
668c1d58c2bSIvan Butygin   using llvmFMF = llvm::FastMathFlags;
669c1d58c2bSIvan Butygin   using FuncT = void (llvmFMF::*)(bool);
670c1d58c2bSIvan Butygin   const std::pair<FastmathFlags, FuncT> handlers[] = {
671c1d58c2bSIvan Butygin       // clang-format off
672c1d58c2bSIvan Butygin       {FastmathFlags::nnan,     &llvmFMF::setNoNaNs},
673c1d58c2bSIvan Butygin       {FastmathFlags::ninf,     &llvmFMF::setNoInfs},
674c1d58c2bSIvan Butygin       {FastmathFlags::nsz,      &llvmFMF::setNoSignedZeros},
675c1d58c2bSIvan Butygin       {FastmathFlags::arcp,     &llvmFMF::setAllowReciprocal},
676c1d58c2bSIvan Butygin       {FastmathFlags::contract, &llvmFMF::setAllowContract},
677c1d58c2bSIvan Butygin       {FastmathFlags::afn,      &llvmFMF::setApproxFunc},
678c1d58c2bSIvan Butygin       {FastmathFlags::reassoc,  &llvmFMF::setAllowReassoc},
679c1d58c2bSIvan Butygin       {FastmathFlags::fast,     &llvmFMF::setFast},
680c1d58c2bSIvan Butygin       // clang-format on
681c1d58c2bSIvan Butygin   };
682c1d58c2bSIvan Butygin   llvm::FastMathFlags ret;
683c1d58c2bSIvan Butygin   auto fmf = op.fastmathFlags();
684c1d58c2bSIvan Butygin   for (auto it : handlers)
685c1d58c2bSIvan Butygin     if (bitEnumContains(fmf, it.first))
686c1d58c2bSIvan Butygin       (ret.*(it.second))(true);
687c1d58c2bSIvan Butygin   return ret;
688c1d58c2bSIvan Butygin }
689c1d58c2bSIvan Butygin 
6902666b973SRiver Riddle /// Given a single MLIR operation, create the corresponding LLVM IR operation
6912666b973SRiver Riddle /// using the `builder`.  LLVM IR Builder does not have a generic interface so
6922666b973SRiver Riddle /// this has to be a long chain of `if`s calling different functions with a
6932666b973SRiver Riddle /// different number of arguments.
694baa1ec22SAlex Zinenko LogicalResult ModuleTranslation::convertOperation(Operation &opInst,
6955d7231d8SStephan Herhut                                                   llvm::IRBuilder<> &builder) {
6965d7231d8SStephan Herhut   auto extractPosition = [](ArrayAttr attr) {
6975d7231d8SStephan Herhut     SmallVector<unsigned, 4> position;
6985d7231d8SStephan Herhut     position.reserve(attr.size());
6995d7231d8SStephan Herhut     for (Attribute v : attr)
7005d7231d8SStephan Herhut       position.push_back(v.cast<IntegerAttr>().getValue().getZExtValue());
7015d7231d8SStephan Herhut     return position;
7025d7231d8SStephan Herhut   };
7035d7231d8SStephan Herhut 
704c1d58c2bSIvan Butygin   llvm::IRBuilder<>::FastMathFlagGuard fmfGuard(builder);
705c1d58c2bSIvan Butygin   if (auto fmf = dyn_cast<FastmathFlagsInterface>(opInst))
706c1d58c2bSIvan Butygin     builder.setFastMathFlags(getFastmathFlags(fmf));
707c1d58c2bSIvan Butygin 
708ba0fa925SRiver Riddle #include "mlir/Dialect/LLVMIR/LLVMConversions.inc"
7095d7231d8SStephan Herhut 
7105d7231d8SStephan Herhut   // Emit function calls.  If the "callee" attribute is present, this is a
7115d7231d8SStephan Herhut   // direct function call and we also need to look up the remapped function
7125d7231d8SStephan Herhut   // itself.  Otherwise, this is an indirect call and the callee is the first
7135d7231d8SStephan Herhut   // operand, look it up as a normal value.  Return the llvm::Value representing
7145d7231d8SStephan Herhut   // the function result, which may be of llvm::VoidTy type.
7155d7231d8SStephan Herhut   auto convertCall = [this, &builder](Operation &op) -> llvm::Value * {
7165d7231d8SStephan Herhut     auto operands = lookupValues(op.getOperands());
7175d7231d8SStephan Herhut     ArrayRef<llvm::Value *> operandsRef(operands);
7189b9c647cSRiver Riddle     if (auto attr = op.getAttrOfType<FlatSymbolRefAttr>("callee")) {
7195d7231d8SStephan Herhut       return builder.CreateCall(functionMapping.lookup(attr.getValue()),
7205d7231d8SStephan Herhut                                 operandsRef);
7215d7231d8SStephan Herhut     } else {
722133049d0SEli Friedman       auto *calleePtrType =
723133049d0SEli Friedman           cast<llvm::PointerType>(operandsRef.front()->getType());
724133049d0SEli Friedman       auto *calleeType =
725133049d0SEli Friedman           cast<llvm::FunctionType>(calleePtrType->getElementType());
726133049d0SEli Friedman       return builder.CreateCall(calleeType, operandsRef.front(),
727133049d0SEli Friedman                                 operandsRef.drop_front());
7285d7231d8SStephan Herhut     }
7295d7231d8SStephan Herhut   };
7305d7231d8SStephan Herhut 
7315d7231d8SStephan Herhut   // Emit calls.  If the called function has a result, remap the corresponding
7325d7231d8SStephan Herhut   // value.  Note that LLVM IR dialect CallOp has either 0 or 1 result.
733d5b60ee8SRiver Riddle   if (isa<LLVM::CallOp>(opInst)) {
7345d7231d8SStephan Herhut     llvm::Value *result = convertCall(opInst);
7355d7231d8SStephan Herhut     if (opInst.getNumResults() != 0) {
7365d7231d8SStephan Herhut       valueMapping[opInst.getResult(0)] = result;
737baa1ec22SAlex Zinenko       return success();
7385d7231d8SStephan Herhut     }
7395d7231d8SStephan Herhut     // Check that LLVM call returns void for 0-result functions.
740baa1ec22SAlex Zinenko     return success(result->getType()->isVoidTy());
7415d7231d8SStephan Herhut   }
7425d7231d8SStephan Herhut 
743047400edSNicolas Vasilache   if (auto inlineAsmOp = dyn_cast<LLVM::InlineAsmOp>(opInst)) {
744047400edSNicolas Vasilache     // TODO: refactor function type creation which usually occurs in std-LLVM
745047400edSNicolas Vasilache     // conversion.
746c69c9e0fSAlex Zinenko     SmallVector<Type, 8> operandTypes;
747047400edSNicolas Vasilache     operandTypes.reserve(inlineAsmOp.operands().size());
748047400edSNicolas Vasilache     for (auto t : inlineAsmOp.operands().getTypes())
749c69c9e0fSAlex Zinenko       operandTypes.push_back(t);
750047400edSNicolas Vasilache 
751c69c9e0fSAlex Zinenko     Type resultType;
752047400edSNicolas Vasilache     if (inlineAsmOp.getNumResults() == 0) {
7537ed9cfc7SAlex Zinenko       resultType = LLVM::LLVMVoidType::get(mlirModule->getContext());
754047400edSNicolas Vasilache     } else {
755047400edSNicolas Vasilache       assert(inlineAsmOp.getNumResults() == 1);
756c69c9e0fSAlex Zinenko       resultType = inlineAsmOp.getResultTypes()[0];
757047400edSNicolas Vasilache     }
7587ed9cfc7SAlex Zinenko     auto ft = LLVM::LLVMFunctionType::get(resultType, operandTypes);
759047400edSNicolas Vasilache     llvm::InlineAsm *inlineAsmInst =
760047400edSNicolas Vasilache         inlineAsmOp.asm_dialect().hasValue()
761047400edSNicolas Vasilache             ? llvm::InlineAsm::get(
762047400edSNicolas Vasilache                   static_cast<llvm::FunctionType *>(convertType(ft)),
763047400edSNicolas Vasilache                   inlineAsmOp.asm_string(), inlineAsmOp.constraints(),
764047400edSNicolas Vasilache                   inlineAsmOp.has_side_effects(), inlineAsmOp.is_align_stack(),
765047400edSNicolas Vasilache                   convertAsmDialectToLLVM(*inlineAsmOp.asm_dialect()))
766047400edSNicolas Vasilache             : llvm::InlineAsm::get(
767047400edSNicolas Vasilache                   static_cast<llvm::FunctionType *>(convertType(ft)),
768047400edSNicolas Vasilache                   inlineAsmOp.asm_string(), inlineAsmOp.constraints(),
769047400edSNicolas Vasilache                   inlineAsmOp.has_side_effects(), inlineAsmOp.is_align_stack());
770047400edSNicolas Vasilache     llvm::Value *result =
771047400edSNicolas Vasilache         builder.CreateCall(inlineAsmInst, lookupValues(inlineAsmOp.operands()));
772047400edSNicolas Vasilache     if (opInst.getNumResults() != 0)
773047400edSNicolas Vasilache       valueMapping[opInst.getResult(0)] = result;
774047400edSNicolas Vasilache     return success();
775047400edSNicolas Vasilache   }
776047400edSNicolas Vasilache 
777d242aa24SShraiysh Vaishay   if (auto invOp = dyn_cast<LLVM::InvokeOp>(opInst)) {
778d242aa24SShraiysh Vaishay     auto operands = lookupValues(opInst.getOperands());
779d242aa24SShraiysh Vaishay     ArrayRef<llvm::Value *> operandsRef(operands);
780133049d0SEli Friedman     if (auto attr = opInst.getAttrOfType<FlatSymbolRefAttr>("callee")) {
781d242aa24SShraiysh Vaishay       builder.CreateInvoke(functionMapping.lookup(attr.getValue()),
782d242aa24SShraiysh Vaishay                            blockMapping[invOp.getSuccessor(0)],
783d242aa24SShraiysh Vaishay                            blockMapping[invOp.getSuccessor(1)], operandsRef);
784133049d0SEli Friedman     } else {
785133049d0SEli Friedman       auto *calleePtrType =
786133049d0SEli Friedman           cast<llvm::PointerType>(operandsRef.front()->getType());
787133049d0SEli Friedman       auto *calleeType =
788133049d0SEli Friedman           cast<llvm::FunctionType>(calleePtrType->getElementType());
789d242aa24SShraiysh Vaishay       builder.CreateInvoke(
790133049d0SEli Friedman           calleeType, operandsRef.front(), blockMapping[invOp.getSuccessor(0)],
791d242aa24SShraiysh Vaishay           blockMapping[invOp.getSuccessor(1)], operandsRef.drop_front());
792133049d0SEli Friedman     }
793d242aa24SShraiysh Vaishay     return success();
794d242aa24SShraiysh Vaishay   }
795d242aa24SShraiysh Vaishay 
796d242aa24SShraiysh Vaishay   if (auto lpOp = dyn_cast<LLVM::LandingpadOp>(opInst)) {
797c69c9e0fSAlex Zinenko     llvm::Type *ty = convertType(lpOp.getType());
798d242aa24SShraiysh Vaishay     llvm::LandingPadInst *lpi =
799d242aa24SShraiysh Vaishay         builder.CreateLandingPad(ty, lpOp.getNumOperands());
800d242aa24SShraiysh Vaishay 
801d242aa24SShraiysh Vaishay     // Add clauses
802d242aa24SShraiysh Vaishay     for (auto operand : lookupValues(lpOp.getOperands())) {
803d242aa24SShraiysh Vaishay       // All operands should be constant - checked by verifier
804d242aa24SShraiysh Vaishay       if (auto constOperand = dyn_cast<llvm::Constant>(operand))
805d242aa24SShraiysh Vaishay         lpi->addClause(constOperand);
806d242aa24SShraiysh Vaishay     }
807ff77397fSShraiysh Vaishay     valueMapping[lpOp.getResult()] = lpi;
808d242aa24SShraiysh Vaishay     return success();
809d242aa24SShraiysh Vaishay   }
810d242aa24SShraiysh Vaishay 
8115d7231d8SStephan Herhut   // Emit branches.  We need to look up the remapped blocks and ignore the block
8125d7231d8SStephan Herhut   // arguments that were transformed into PHI nodes.
813c5ecf991SRiver Riddle   if (auto brOp = dyn_cast<LLVM::BrOp>(opInst)) {
814db884dafSAlex Zinenko     llvm::BranchInst *branch =
815c0fd5e65SRiver Riddle         builder.CreateBr(blockMapping[brOp.getSuccessor()]);
816db884dafSAlex Zinenko     branchMapping.try_emplace(&opInst, branch);
817baa1ec22SAlex Zinenko     return success();
8185d7231d8SStephan Herhut   }
819c5ecf991SRiver Riddle   if (auto condbrOp = dyn_cast<LLVM::CondBrOp>(opInst)) {
82099d03f03SGeorge Mitenkov     auto weights = condbrOp.branch_weights();
82199d03f03SGeorge Mitenkov     llvm::MDNode *branchWeights = nullptr;
82299d03f03SGeorge Mitenkov     if (weights) {
82399d03f03SGeorge Mitenkov       // Map weight attributes to LLVM metadata.
82499d03f03SGeorge Mitenkov       auto trueWeight =
82599d03f03SGeorge Mitenkov           weights.getValue().getValue(0).cast<IntegerAttr>().getInt();
82699d03f03SGeorge Mitenkov       auto falseWeight =
82799d03f03SGeorge Mitenkov           weights.getValue().getValue(1).cast<IntegerAttr>().getInt();
82899d03f03SGeorge Mitenkov       branchWeights =
82999d03f03SGeorge Mitenkov           llvm::MDBuilder(llvmModule->getContext())
83099d03f03SGeorge Mitenkov               .createBranchWeights(static_cast<uint32_t>(trueWeight),
83199d03f03SGeorge Mitenkov                                    static_cast<uint32_t>(falseWeight));
83299d03f03SGeorge Mitenkov     }
833db884dafSAlex Zinenko     llvm::BranchInst *branch = builder.CreateCondBr(
834db884dafSAlex Zinenko         valueMapping.lookup(condbrOp.getOperand(0)),
8355d7231d8SStephan Herhut         blockMapping[condbrOp.getSuccessor(0)],
83699d03f03SGeorge Mitenkov         blockMapping[condbrOp.getSuccessor(1)], branchWeights);
837db884dafSAlex Zinenko     branchMapping.try_emplace(&opInst, branch);
838baa1ec22SAlex Zinenko     return success();
8395d7231d8SStephan Herhut   }
84014f24155SBrian Gesiak   if (auto switchOp = dyn_cast<LLVM::SwitchOp>(opInst)) {
84114f24155SBrian Gesiak     llvm::MDNode *branchWeights = nullptr;
84214f24155SBrian Gesiak     if (auto weights = switchOp.branch_weights()) {
84314f24155SBrian Gesiak       llvm::SmallVector<uint32_t> weightValues;
84414f24155SBrian Gesiak       weightValues.reserve(weights->size());
84514f24155SBrian Gesiak       for (llvm::APInt weight : weights->cast<DenseIntElementsAttr>())
84614f24155SBrian Gesiak         weightValues.push_back(weight.getLimitedValue());
84714f24155SBrian Gesiak       branchWeights = llvm::MDBuilder(llvmModule->getContext())
84814f24155SBrian Gesiak                           .createBranchWeights(weightValues);
84914f24155SBrian Gesiak     }
85014f24155SBrian Gesiak 
85114f24155SBrian Gesiak     llvm::SwitchInst *switchInst =
85214f24155SBrian Gesiak         builder.CreateSwitch(valueMapping[switchOp.value()],
85314f24155SBrian Gesiak                              blockMapping[switchOp.defaultDestination()],
85414f24155SBrian Gesiak                              switchOp.caseDestinations().size(), branchWeights);
85514f24155SBrian Gesiak 
856c69c9e0fSAlex Zinenko     auto *ty =
857c69c9e0fSAlex Zinenko         llvm::cast<llvm::IntegerType>(convertType(switchOp.value().getType()));
85814f24155SBrian Gesiak     for (auto i :
85914f24155SBrian Gesiak          llvm::zip(switchOp.case_values()->cast<DenseIntElementsAttr>(),
86014f24155SBrian Gesiak                    switchOp.caseDestinations()))
86114f24155SBrian Gesiak       switchInst->addCase(
86214f24155SBrian Gesiak           llvm::ConstantInt::get(ty, std::get<0>(i).getLimitedValue()),
86314f24155SBrian Gesiak           blockMapping[std::get<1>(i)]);
86414f24155SBrian Gesiak 
86514f24155SBrian Gesiak     branchMapping.try_emplace(&opInst, switchInst);
86614f24155SBrian Gesiak     return success();
86714f24155SBrian Gesiak   }
8685d7231d8SStephan Herhut 
8692dd38b09SAlex Zinenko   // Emit addressof.  We need to look up the global value referenced by the
8702dd38b09SAlex Zinenko   // operation and store it in the MLIR-to-LLVM value mapping.  This does not
8712dd38b09SAlex Zinenko   // emit any LLVM instruction.
8722dd38b09SAlex Zinenko   if (auto addressOfOp = dyn_cast<LLVM::AddressOfOp>(opInst)) {
8732dd38b09SAlex Zinenko     LLVM::GlobalOp global = addressOfOp.getGlobal();
874cba733edSAlex Zinenko     LLVM::LLVMFuncOp function = addressOfOp.getFunction();
8752dd38b09SAlex Zinenko 
876cba733edSAlex Zinenko     // The verifier should not have allowed this.
877cba733edSAlex Zinenko     assert((global || function) &&
878cba733edSAlex Zinenko            "referencing an undefined global or function");
879cba733edSAlex Zinenko 
880cba733edSAlex Zinenko     valueMapping[addressOfOp.getResult()] =
881cba733edSAlex Zinenko         global ? globalsMapping.lookup(global)
882cba733edSAlex Zinenko                : functionMapping.lookup(function.getName());
8832dd38b09SAlex Zinenko     return success();
8842dd38b09SAlex Zinenko   }
8852dd38b09SAlex Zinenko 
8869f9f89d4SMehdi Amini   if (ompDialect && opInst.getDialect() == ompDialect)
8877ecee63eSKiran Kumar T P     return convertOmpOperation(opInst, builder);
88892a295ebSKiran Chandramohan 
889baa1ec22SAlex Zinenko   return opInst.emitError("unsupported or non-LLVM operation: ")
890baa1ec22SAlex Zinenko          << opInst.getName();
8915d7231d8SStephan Herhut }
8925d7231d8SStephan Herhut 
8932666b973SRiver Riddle /// Convert block to LLVM IR.  Unless `ignoreArguments` is set, emit PHI nodes
8942666b973SRiver Riddle /// to define values corresponding to the MLIR block arguments.  These nodes
89510164a2eSAlex Zinenko /// are not connected to the source basic blocks, which may not exist yet.  Uses
89610164a2eSAlex Zinenko /// `builder` to construct the LLVM IR. Expects the LLVM IR basic block to have
89710164a2eSAlex Zinenko /// been created for `bb` and included in the block mapping.  Inserts new
89810164a2eSAlex Zinenko /// instructions at the end of the block and leaves `builder` in a state
89910164a2eSAlex Zinenko /// suitable for further insertion into the end of the block.
90010164a2eSAlex Zinenko LogicalResult ModuleTranslation::convertBlock(Block &bb, bool ignoreArguments,
90110164a2eSAlex Zinenko                                               llvm::IRBuilder<> &builder) {
90210164a2eSAlex Zinenko   builder.SetInsertPoint(blockMapping[&bb]);
903c33d6970SRiver Riddle   auto *subprogram = builder.GetInsertBlock()->getParent()->getSubprogram();
9045d7231d8SStephan Herhut 
9055d7231d8SStephan Herhut   // Before traversing operations, make block arguments available through
9065d7231d8SStephan Herhut   // value remapping and PHI nodes, but do not add incoming edges for the PHI
9075d7231d8SStephan Herhut   // nodes just yet: those values may be defined by this or following blocks.
9085d7231d8SStephan Herhut   // This step is omitted if "ignoreArguments" is set.  The arguments of the
9095d7231d8SStephan Herhut   // first block have been already made available through the remapping of
9105d7231d8SStephan Herhut   // LLVM function arguments.
9115d7231d8SStephan Herhut   if (!ignoreArguments) {
9125d7231d8SStephan Herhut     auto predecessors = bb.getPredecessors();
9135d7231d8SStephan Herhut     unsigned numPredecessors =
9145d7231d8SStephan Herhut         std::distance(predecessors.begin(), predecessors.end());
91535807bc4SRiver Riddle     for (auto arg : bb.getArguments()) {
916c69c9e0fSAlex Zinenko       auto wrappedType = arg.getType();
917c69c9e0fSAlex Zinenko       if (!isCompatibleType(wrappedType))
918baa1ec22SAlex Zinenko         return emitError(bb.front().getLoc(),
919a4c3a645SRiver Riddle                          "block argument does not have an LLVM type");
920aec38c61SAlex Zinenko       llvm::Type *type = convertType(wrappedType);
9215d7231d8SStephan Herhut       llvm::PHINode *phi = builder.CreatePHI(type, numPredecessors);
9225d7231d8SStephan Herhut       valueMapping[arg] = phi;
9235d7231d8SStephan Herhut     }
9245d7231d8SStephan Herhut   }
9255d7231d8SStephan Herhut 
9265d7231d8SStephan Herhut   // Traverse operations.
9275d7231d8SStephan Herhut   for (auto &op : bb) {
928c33d6970SRiver Riddle     // Set the current debug location within the builder.
929c33d6970SRiver Riddle     builder.SetCurrentDebugLocation(
930c33d6970SRiver Riddle         debugTranslation->translateLoc(op.getLoc(), subprogram));
931c33d6970SRiver Riddle 
932baa1ec22SAlex Zinenko     if (failed(convertOperation(op, builder)))
933baa1ec22SAlex Zinenko       return failure();
9345d7231d8SStephan Herhut   }
9355d7231d8SStephan Herhut 
936baa1ec22SAlex Zinenko   return success();
9375d7231d8SStephan Herhut }
9385d7231d8SStephan Herhut 
9392666b973SRiver Riddle /// Create named global variables that correspond to llvm.mlir.global
9402666b973SRiver Riddle /// definitions.
941efa2d533SAlex Zinenko LogicalResult ModuleTranslation::convertGlobals() {
94244fc7d72STres Popp   for (auto op : getModuleBody(mlirModule).getOps<LLVM::GlobalOp>()) {
943aec38c61SAlex Zinenko     llvm::Type *type = convertType(op.getType());
944250a11aeSJames Molloy     llvm::Constant *cst = llvm::UndefValue::get(type);
945250a11aeSJames Molloy     if (op.getValueOrNull()) {
94668451df2SAlex Zinenko       // String attributes are treated separately because they cannot appear as
94768451df2SAlex Zinenko       // in-function constants and are thus not supported by getLLVMConstant.
94833a3a91bSChristian Sigg       if (auto strAttr = op.getValueOrNull().dyn_cast_or_null<StringAttr>()) {
9492dd38b09SAlex Zinenko         cst = llvm::ConstantDataArray::getString(
95068451df2SAlex Zinenko             llvmModule->getContext(), strAttr.getValue(), /*AddNull=*/false);
9512dd38b09SAlex Zinenko         type = cst->getType();
952efa2d533SAlex Zinenko       } else if (!(cst = getLLVMConstant(type, op.getValueOrNull(),
953efa2d533SAlex Zinenko                                          op.getLoc()))) {
954efa2d533SAlex Zinenko         return failure();
95568451df2SAlex Zinenko       }
956250a11aeSJames Molloy     } else if (Block *initializer = op.getInitializerBlock()) {
957250a11aeSJames Molloy       llvm::IRBuilder<> builder(llvmModule->getContext());
958250a11aeSJames Molloy       for (auto &op : initializer->without_terminator()) {
959250a11aeSJames Molloy         if (failed(convertOperation(op, builder)) ||
960efa2d533SAlex Zinenko             !isa<llvm::Constant>(valueMapping.lookup(op.getResult(0))))
961efa2d533SAlex Zinenko           return emitError(op.getLoc(), "unemittable constant value");
962250a11aeSJames Molloy       }
963250a11aeSJames Molloy       ReturnOp ret = cast<ReturnOp>(initializer->getTerminator());
964250a11aeSJames Molloy       cst = cast<llvm::Constant>(valueMapping.lookup(ret.getOperand(0)));
965250a11aeSJames Molloy     }
96668451df2SAlex Zinenko 
967eb67bd78SAlex Zinenko     auto linkage = convertLinkageToLLVM(op.linkage());
968d5e627f8SAlex Zinenko     bool anyExternalLinkage =
9697b5d4669SEric Schweitz         ((linkage == llvm::GlobalVariable::ExternalLinkage &&
9707b5d4669SEric Schweitz           isa<llvm::UndefValue>(cst)) ||
971d5e627f8SAlex Zinenko          linkage == llvm::GlobalVariable::ExternalWeakLinkage);
972431bb8b3SRiver Riddle     auto addrSpace = op.addr_space();
973e79bfefbSMLIR Team     auto *var = new llvm::GlobalVariable(
974d5e627f8SAlex Zinenko         *llvmModule, type, op.constant(), linkage,
975d5e627f8SAlex Zinenko         anyExternalLinkage ? nullptr : cst, op.sym_name(),
976d5e627f8SAlex Zinenko         /*InsertBefore=*/nullptr, llvm::GlobalValue::NotThreadLocal, addrSpace);
977e79bfefbSMLIR Team 
9782dd38b09SAlex Zinenko     globalsMapping.try_emplace(op, var);
979b9ff2dd8SAlex Zinenko   }
980efa2d533SAlex Zinenko 
981efa2d533SAlex Zinenko   return success();
982b9ff2dd8SAlex Zinenko }
983b9ff2dd8SAlex Zinenko 
9840a2131b7SAlex Zinenko /// Attempts to add an attribute identified by `key`, optionally with the given
9850a2131b7SAlex Zinenko /// `value` to LLVM function `llvmFunc`. Reports errors at `loc` if any. If the
9860a2131b7SAlex Zinenko /// attribute has a kind known to LLVM IR, create the attribute of this kind,
9870a2131b7SAlex Zinenko /// otherwise keep it as a string attribute. Performs additional checks for
9880a2131b7SAlex Zinenko /// attributes known to have or not have a value in order to avoid assertions
9890a2131b7SAlex Zinenko /// inside LLVM upon construction.
9900a2131b7SAlex Zinenko static LogicalResult checkedAddLLVMFnAttribute(Location loc,
9910a2131b7SAlex Zinenko                                                llvm::Function *llvmFunc,
9920a2131b7SAlex Zinenko                                                StringRef key,
9930a2131b7SAlex Zinenko                                                StringRef value = StringRef()) {
9940a2131b7SAlex Zinenko   auto kind = llvm::Attribute::getAttrKindFromName(key);
9950a2131b7SAlex Zinenko   if (kind == llvm::Attribute::None) {
9960a2131b7SAlex Zinenko     llvmFunc->addFnAttr(key, value);
9970a2131b7SAlex Zinenko     return success();
9980a2131b7SAlex Zinenko   }
9990a2131b7SAlex Zinenko 
10000a2131b7SAlex Zinenko   if (llvm::Attribute::doesAttrKindHaveArgument(kind)) {
10010a2131b7SAlex Zinenko     if (value.empty())
10020a2131b7SAlex Zinenko       return emitError(loc) << "LLVM attribute '" << key << "' expects a value";
10030a2131b7SAlex Zinenko 
10040a2131b7SAlex Zinenko     int result;
10050a2131b7SAlex Zinenko     if (!value.getAsInteger(/*Radix=*/0, result))
10060a2131b7SAlex Zinenko       llvmFunc->addFnAttr(
10070a2131b7SAlex Zinenko           llvm::Attribute::get(llvmFunc->getContext(), kind, result));
10080a2131b7SAlex Zinenko     else
10090a2131b7SAlex Zinenko       llvmFunc->addFnAttr(key, value);
10100a2131b7SAlex Zinenko     return success();
10110a2131b7SAlex Zinenko   }
10120a2131b7SAlex Zinenko 
10130a2131b7SAlex Zinenko   if (!value.empty())
10140a2131b7SAlex Zinenko     return emitError(loc) << "LLVM attribute '" << key
10150a2131b7SAlex Zinenko                           << "' does not expect a value, found '" << value
10160a2131b7SAlex Zinenko                           << "'";
10170a2131b7SAlex Zinenko 
10180a2131b7SAlex Zinenko   llvmFunc->addFnAttr(kind);
10190a2131b7SAlex Zinenko   return success();
10200a2131b7SAlex Zinenko }
10210a2131b7SAlex Zinenko 
10220a2131b7SAlex Zinenko /// Attaches the attributes listed in the given array attribute to `llvmFunc`.
10230a2131b7SAlex Zinenko /// Reports error to `loc` if any and returns immediately. Expects `attributes`
10240a2131b7SAlex Zinenko /// to be an array attribute containing either string attributes, treated as
10250a2131b7SAlex Zinenko /// value-less LLVM attributes, or array attributes containing two string
10260a2131b7SAlex Zinenko /// attributes, with the first string being the name of the corresponding LLVM
10270a2131b7SAlex Zinenko /// attribute and the second string beings its value. Note that even integer
10280a2131b7SAlex Zinenko /// attributes are expected to have their values expressed as strings.
10290a2131b7SAlex Zinenko static LogicalResult
10300a2131b7SAlex Zinenko forwardPassthroughAttributes(Location loc, Optional<ArrayAttr> attributes,
10310a2131b7SAlex Zinenko                              llvm::Function *llvmFunc) {
10320a2131b7SAlex Zinenko   if (!attributes)
10330a2131b7SAlex Zinenko     return success();
10340a2131b7SAlex Zinenko 
10350a2131b7SAlex Zinenko   for (Attribute attr : *attributes) {
10360a2131b7SAlex Zinenko     if (auto stringAttr = attr.dyn_cast<StringAttr>()) {
10370a2131b7SAlex Zinenko       if (failed(
10380a2131b7SAlex Zinenko               checkedAddLLVMFnAttribute(loc, llvmFunc, stringAttr.getValue())))
10390a2131b7SAlex Zinenko         return failure();
10400a2131b7SAlex Zinenko       continue;
10410a2131b7SAlex Zinenko     }
10420a2131b7SAlex Zinenko 
10430a2131b7SAlex Zinenko     auto arrayAttr = attr.dyn_cast<ArrayAttr>();
10440a2131b7SAlex Zinenko     if (!arrayAttr || arrayAttr.size() != 2)
10450a2131b7SAlex Zinenko       return emitError(loc)
10460a2131b7SAlex Zinenko              << "expected 'passthrough' to contain string or array attributes";
10470a2131b7SAlex Zinenko 
10480a2131b7SAlex Zinenko     auto keyAttr = arrayAttr[0].dyn_cast<StringAttr>();
10490a2131b7SAlex Zinenko     auto valueAttr = arrayAttr[1].dyn_cast<StringAttr>();
10500a2131b7SAlex Zinenko     if (!keyAttr || !valueAttr)
10510a2131b7SAlex Zinenko       return emitError(loc)
10520a2131b7SAlex Zinenko              << "expected arrays within 'passthrough' to contain two strings";
10530a2131b7SAlex Zinenko 
10540a2131b7SAlex Zinenko     if (failed(checkedAddLLVMFnAttribute(loc, llvmFunc, keyAttr.getValue(),
10550a2131b7SAlex Zinenko                                          valueAttr.getValue())))
10560a2131b7SAlex Zinenko       return failure();
10570a2131b7SAlex Zinenko   }
10580a2131b7SAlex Zinenko   return success();
10590a2131b7SAlex Zinenko }
10600a2131b7SAlex Zinenko 
10615e7959a3SAlex Zinenko LogicalResult ModuleTranslation::convertOneFunction(LLVMFuncOp func) {
1062db884dafSAlex Zinenko   // Clear the block, branch value mappings, they are only relevant within one
10635d7231d8SStephan Herhut   // function.
10645d7231d8SStephan Herhut   blockMapping.clear();
10655d7231d8SStephan Herhut   valueMapping.clear();
1066db884dafSAlex Zinenko   branchMapping.clear();
1067c33862b0SRiver Riddle   llvm::Function *llvmFunc = functionMapping.lookup(func.getName());
1068c33d6970SRiver Riddle 
1069c33d6970SRiver Riddle   // Translate the debug information for this function.
1070c33d6970SRiver Riddle   debugTranslation->translate(func, *llvmFunc);
1071c33d6970SRiver Riddle 
10725d7231d8SStephan Herhut   // Add function arguments to the value remapping table.
10735d7231d8SStephan Herhut   // If there was noalias info then we decorate each argument accordingly.
10745d7231d8SStephan Herhut   unsigned int argIdx = 0;
1075eeef50b1SFangrui Song   for (auto kvp : llvm::zip(func.getArguments(), llvmFunc->args())) {
10765d7231d8SStephan Herhut     llvm::Argument &llvmArg = std::get<1>(kvp);
1077e62a6956SRiver Riddle     BlockArgument mlirArg = std::get<0>(kvp);
10785d7231d8SStephan Herhut 
107967cc5cecSStephan Herhut     if (auto attr = func.getArgAttrOfType<BoolAttr>(
108067cc5cecSStephan Herhut             argIdx, LLVMDialect::getNoAliasAttrName())) {
10815d7231d8SStephan Herhut       // NB: Attribute already verified to be boolean, so check if we can indeed
10825d7231d8SStephan Herhut       // attach the attribute to this argument, based on its type.
1083c69c9e0fSAlex Zinenko       auto argTy = mlirArg.getType();
10848de43b92SAlex Zinenko       if (!argTy.isa<LLVM::LLVMPointerType>())
1085baa1ec22SAlex Zinenko         return func.emitError(
10865d7231d8SStephan Herhut             "llvm.noalias attribute attached to LLVM non-pointer argument");
10875d7231d8SStephan Herhut       if (attr.getValue())
10885d7231d8SStephan Herhut         llvmArg.addAttr(llvm::Attribute::AttrKind::NoAlias);
10895d7231d8SStephan Herhut     }
10902416e28cSStephan Herhut 
109167cc5cecSStephan Herhut     if (auto attr = func.getArgAttrOfType<IntegerAttr>(
109267cc5cecSStephan Herhut             argIdx, LLVMDialect::getAlignAttrName())) {
10932416e28cSStephan Herhut       // NB: Attribute already verified to be int, so check if we can indeed
10942416e28cSStephan Herhut       // attach the attribute to this argument, based on its type.
1095c69c9e0fSAlex Zinenko       auto argTy = mlirArg.getType();
10968de43b92SAlex Zinenko       if (!argTy.isa<LLVM::LLVMPointerType>())
10972416e28cSStephan Herhut         return func.emitError(
10982416e28cSStephan Herhut             "llvm.align attribute attached to LLVM non-pointer argument");
10992416e28cSStephan Herhut       llvmArg.addAttrs(
11002416e28cSStephan Herhut           llvm::AttrBuilder().addAlignmentAttr(llvm::Align(attr.getInt())));
11012416e28cSStephan Herhut     }
11022416e28cSStephan Herhut 
110370b841acSEric Schweitz     if (auto attr = func.getArgAttrOfType<UnitAttr>(argIdx, "llvm.sret")) {
110470b841acSEric Schweitz       auto argTy = mlirArg.getType();
110570b841acSEric Schweitz       if (!argTy.isa<LLVM::LLVMPointerType>())
110670b841acSEric Schweitz         return func.emitError(
110770b841acSEric Schweitz             "llvm.sret attribute attached to LLVM non-pointer argument");
11081d6df1fcSEric Schweitz       llvmArg.addAttrs(llvm::AttrBuilder().addStructRetAttr(
11091d6df1fcSEric Schweitz           llvmArg.getType()->getPointerElementType()));
111070b841acSEric Schweitz     }
111170b841acSEric Schweitz 
111270b841acSEric Schweitz     if (auto attr = func.getArgAttrOfType<UnitAttr>(argIdx, "llvm.byval")) {
111370b841acSEric Schweitz       auto argTy = mlirArg.getType();
111470b841acSEric Schweitz       if (!argTy.isa<LLVM::LLVMPointerType>())
111570b841acSEric Schweitz         return func.emitError(
111670b841acSEric Schweitz             "llvm.byval attribute attached to LLVM non-pointer argument");
11171d6df1fcSEric Schweitz       llvmArg.addAttrs(llvm::AttrBuilder().addByValAttr(
11181d6df1fcSEric Schweitz           llvmArg.getType()->getPointerElementType()));
111970b841acSEric Schweitz     }
112070b841acSEric Schweitz 
11215d7231d8SStephan Herhut     valueMapping[mlirArg] = &llvmArg;
11225d7231d8SStephan Herhut     argIdx++;
11235d7231d8SStephan Herhut   }
11245d7231d8SStephan Herhut 
1125ff77397fSShraiysh Vaishay   // Check the personality and set it.
1126ff77397fSShraiysh Vaishay   if (func.personality().hasValue()) {
1127ff77397fSShraiysh Vaishay     llvm::Type *ty = llvm::Type::getInt8PtrTy(llvmFunc->getContext());
1128ff77397fSShraiysh Vaishay     if (llvm::Constant *pfunc =
1129ff77397fSShraiysh Vaishay             getLLVMConstant(ty, func.personalityAttr(), func.getLoc()))
1130ff77397fSShraiysh Vaishay       llvmFunc->setPersonalityFn(pfunc);
1131ff77397fSShraiysh Vaishay   }
1132ff77397fSShraiysh Vaishay 
11335d7231d8SStephan Herhut   // First, create all blocks so we can jump to them.
11345d7231d8SStephan Herhut   llvm::LLVMContext &llvmContext = llvmFunc->getContext();
11355d7231d8SStephan Herhut   for (auto &bb : func) {
11365d7231d8SStephan Herhut     auto *llvmBB = llvm::BasicBlock::Create(llvmContext);
11375d7231d8SStephan Herhut     llvmBB->insertInto(llvmFunc);
11385d7231d8SStephan Herhut     blockMapping[&bb] = llvmBB;
11395d7231d8SStephan Herhut   }
11405d7231d8SStephan Herhut 
11415d7231d8SStephan Herhut   // Then, convert blocks one by one in topological order to ensure defs are
11425d7231d8SStephan Herhut   // converted before uses.
11435d7231d8SStephan Herhut   auto blocks = topologicalSort(func);
114410164a2eSAlex Zinenko   for (Block *bb : blocks) {
114510164a2eSAlex Zinenko     llvm::IRBuilder<> builder(llvmContext);
114610164a2eSAlex Zinenko     if (failed(convertBlock(*bb, bb->isEntryBlock(), builder)))
1147baa1ec22SAlex Zinenko       return failure();
11485d7231d8SStephan Herhut   }
11495d7231d8SStephan Herhut 
11505d7231d8SStephan Herhut   // Finally, after all blocks have been traversed and values mapped, connect
11515d7231d8SStephan Herhut   // the PHI nodes to the results of preceding blocks.
1152db884dafSAlex Zinenko   connectPHINodes(func, valueMapping, blockMapping, branchMapping);
1153baa1ec22SAlex Zinenko   return success();
11545d7231d8SStephan Herhut }
11555d7231d8SStephan Herhut 
115644fc7d72STres Popp LogicalResult ModuleTranslation::checkSupportedModuleOps(Operation *m) {
115744fc7d72STres Popp   for (Operation &o : getModuleBody(m).getOperations())
1158*fe7c0d90SRiver Riddle     if (!isa<LLVM::LLVMFuncOp, LLVM::GlobalOp>(&o) &&
1159*fe7c0d90SRiver Riddle         !o.hasTrait<OpTrait::IsTerminator>())
11604dde19f0SAlex Zinenko       return o.emitOpError("unsupported module-level operation");
11614dde19f0SAlex Zinenko   return success();
11624dde19f0SAlex Zinenko }
11634dde19f0SAlex Zinenko 
1164a084b94fSSean Silva LogicalResult ModuleTranslation::convertFunctionSignatures() {
11655d7231d8SStephan Herhut   // Declare all functions first because there may be function calls that form a
1166a084b94fSSean Silva   // call graph with cycles, or global initializers that reference functions.
116744fc7d72STres Popp   for (auto function : getModuleBody(mlirModule).getOps<LLVMFuncOp>()) {
11685e7959a3SAlex Zinenko     llvm::FunctionCallee llvmFuncCst = llvmModule->getOrInsertFunction(
11695e7959a3SAlex Zinenko         function.getName(),
1170aec38c61SAlex Zinenko         cast<llvm::FunctionType>(convertType(function.getType())));
11710a2131b7SAlex Zinenko     llvm::Function *llvmFunc = cast<llvm::Function>(llvmFuncCst.getCallee());
1172ebbdecddSAlex Zinenko     llvmFunc->setLinkage(convertLinkageToLLVM(function.linkage()));
11730a2131b7SAlex Zinenko     functionMapping[function.getName()] = llvmFunc;
11740a2131b7SAlex Zinenko 
11750a2131b7SAlex Zinenko     // Forward the pass-through attributes to LLVM.
11760a2131b7SAlex Zinenko     if (failed(forwardPassthroughAttributes(function.getLoc(),
11770a2131b7SAlex Zinenko                                             function.passthrough(), llvmFunc)))
11780a2131b7SAlex Zinenko       return failure();
11795d7231d8SStephan Herhut   }
11805d7231d8SStephan Herhut 
1181a084b94fSSean Silva   return success();
1182a084b94fSSean Silva }
1183a084b94fSSean Silva 
1184a084b94fSSean Silva LogicalResult ModuleTranslation::convertFunctions() {
11855d7231d8SStephan Herhut   // Convert functions.
118644fc7d72STres Popp   for (auto function : getModuleBody(mlirModule).getOps<LLVMFuncOp>()) {
11875d7231d8SStephan Herhut     // Ignore external functions.
11885d7231d8SStephan Herhut     if (function.isExternal())
11895d7231d8SStephan Herhut       continue;
11905d7231d8SStephan Herhut 
1191baa1ec22SAlex Zinenko     if (failed(convertOneFunction(function)))
1192baa1ec22SAlex Zinenko       return failure();
11935d7231d8SStephan Herhut   }
11945d7231d8SStephan Herhut 
1195baa1ec22SAlex Zinenko   return success();
11965d7231d8SStephan Herhut }
11975d7231d8SStephan Herhut 
1198c69c9e0fSAlex Zinenko llvm::Type *ModuleTranslation::convertType(Type type) {
1199b2ab375dSAlex Zinenko   return typeTranslator.translateType(type);
1200aec38c61SAlex Zinenko }
1201aec38c61SAlex Zinenko 
1202efadb6b8SAlex Zinenko /// A helper to look up remapped operands in the value remapping table.`
1203efadb6b8SAlex Zinenko SmallVector<llvm::Value *, 8>
1204efadb6b8SAlex Zinenko ModuleTranslation::lookupValues(ValueRange values) {
1205efadb6b8SAlex Zinenko   SmallVector<llvm::Value *, 8> remapped;
1206efadb6b8SAlex Zinenko   remapped.reserve(values.size());
1207ff77397fSShraiysh Vaishay   for (Value v : values) {
1208ff77397fSShraiysh Vaishay     assert(valueMapping.count(v) && "referencing undefined value");
1209efadb6b8SAlex Zinenko     remapped.push_back(valueMapping.lookup(v));
1210ff77397fSShraiysh Vaishay   }
1211efadb6b8SAlex Zinenko   return remapped;
1212efadb6b8SAlex Zinenko }
1213efadb6b8SAlex Zinenko 
1214db1c197bSAlex Zinenko std::unique_ptr<llvm::Module> ModuleTranslation::prepareLLVMModule(
1215db1c197bSAlex Zinenko     Operation *m, llvm::LLVMContext &llvmContext, StringRef name) {
1216f9dc2b70SMehdi Amini   m->getContext()->getOrLoadDialect<LLVM::LLVMDialect>();
1217db1c197bSAlex Zinenko   auto llvmModule = std::make_unique<llvm::Module>(name, llvmContext);
1218168213f9SAlex Zinenko   if (auto dataLayoutAttr =
1219168213f9SAlex Zinenko           m->getAttr(LLVM::LLVMDialect::getDataLayoutAttrName()))
1220168213f9SAlex Zinenko     llvmModule->setDataLayout(dataLayoutAttr.cast<StringAttr>().getValue());
12215dd5a083SNicolas Vasilache   if (auto targetTripleAttr =
12225dd5a083SNicolas Vasilache           m->getAttr(LLVM::LLVMDialect::getTargetTripleAttrName()))
12235dd5a083SNicolas Vasilache     llvmModule->setTargetTriple(targetTripleAttr.cast<StringAttr>().getValue());
12245d7231d8SStephan Herhut 
12255d7231d8SStephan Herhut   // Inject declarations for `malloc` and `free` functions that can be used in
12265d7231d8SStephan Herhut   // memref allocation/deallocation coming from standard ops lowering.
1227db1c197bSAlex Zinenko   llvm::IRBuilder<> builder(llvmContext);
12285d7231d8SStephan Herhut   llvmModule->getOrInsertFunction("malloc", builder.getInt8PtrTy(),
12295d7231d8SStephan Herhut                                   builder.getInt64Ty());
12305d7231d8SStephan Herhut   llvmModule->getOrInsertFunction("free", builder.getVoidTy(),
12315d7231d8SStephan Herhut                                   builder.getInt8PtrTy());
12325d7231d8SStephan Herhut 
12335d7231d8SStephan Herhut   return llvmModule;
12345d7231d8SStephan Herhut }
1235