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,
415d9067dcaSKiran Chandramohan                        llvm::BasicBlock &continuationIP) {
416d9067dcaSKiran Chandramohan     llvm::LLVMContext &llvmContext = llvmModule->getContext();
417d9067dcaSKiran Chandramohan 
418d9067dcaSKiran Chandramohan     llvm::BasicBlock *codeGenIPBB = codeGenIP.getBlock();
419d9067dcaSKiran Chandramohan     llvm::Instruction *codeGenIPBBTI = codeGenIPBB->getTerminator();
420a71a0d6dSKiran Chandramohan     ompContinuationIPStack.push_back(&continuationIP);
421d9067dcaSKiran Chandramohan 
422793c29a2SSourabh Singh Tomar     // ParallelOp has only `1` region associated with it.
423793c29a2SSourabh Singh Tomar     auto &region = cast<omp::ParallelOp>(opInst).getRegion();
424d9067dcaSKiran Chandramohan     for (auto &bb : region) {
425d9067dcaSKiran Chandramohan       auto *llvmBB = llvm::BasicBlock::Create(
426d9067dcaSKiran Chandramohan           llvmContext, "omp.par.region", codeGenIP.getBlock()->getParent());
427d9067dcaSKiran Chandramohan       blockMapping[&bb] = llvmBB;
428d9067dcaSKiran Chandramohan     }
429d9067dcaSKiran Chandramohan 
430c11d868aSSourabh Singh Tomar     convertOmpOpRegions(region, valueMapping, blockMapping, codeGenIPBBTI,
431c11d868aSSourabh Singh Tomar                         continuationIP, builder, bodyGenStatus);
432a71a0d6dSKiran Chandramohan     ompContinuationIPStack.pop_back();
433a71a0d6dSKiran Chandramohan 
434d9067dcaSKiran Chandramohan   };
435d9067dcaSKiran Chandramohan 
436d9067dcaSKiran Chandramohan   // TODO: Perform appropriate actions according to the data-sharing
437d9067dcaSKiran Chandramohan   // attribute (shared, private, firstprivate, ...) of variables.
438d9067dcaSKiran Chandramohan   // Currently defaults to shared.
439d9067dcaSKiran Chandramohan   auto privCB = [&](InsertPointTy allocaIP, InsertPointTy codeGenIP,
440240dd924SAlex Zinenko                     llvm::Value &, llvm::Value &vPtr,
441d9067dcaSKiran Chandramohan                     llvm::Value *&replacementValue) -> InsertPointTy {
442d9067dcaSKiran Chandramohan     replacementValue = &vPtr;
443d9067dcaSKiran Chandramohan 
444d9067dcaSKiran Chandramohan     return codeGenIP;
445d9067dcaSKiran Chandramohan   };
446d9067dcaSKiran Chandramohan 
447d9067dcaSKiran Chandramohan   // TODO: Perform finalization actions for variables. This has to be
448d9067dcaSKiran Chandramohan   // called for variables which have destructors/finalizers.
449d9067dcaSKiran Chandramohan   auto finiCB = [&](InsertPointTy codeGenIP) {};
450d9067dcaSKiran Chandramohan 
451d9067dcaSKiran Chandramohan   llvm::Value *ifCond = nullptr;
452660832c4SKiran Chandramohan   if (auto ifExprVar = cast<omp::ParallelOp>(opInst).if_expr_var())
453660832c4SKiran Chandramohan     ifCond = valueMapping.lookup(ifExprVar);
454d9067dcaSKiran Chandramohan   llvm::Value *numThreads = nullptr;
455660832c4SKiran Chandramohan   if (auto numThreadsVar = cast<omp::ParallelOp>(opInst).num_threads_var())
456660832c4SKiran Chandramohan     numThreads = valueMapping.lookup(numThreadsVar);
457e6c5e6efSKiran Chandramohan   llvm::omp::ProcBindKind pbKind = llvm::omp::OMP_PROC_BIND_default;
458e6c5e6efSKiran Chandramohan   if (auto bind = cast<omp::ParallelOp>(opInst).proc_bind_val())
459e6c5e6efSKiran Chandramohan     pbKind = llvm::omp::getProcBindKind(bind.getValue());
460660832c4SKiran Chandramohan   // TODO: Is the Parallel construct cancellable?
461d9067dcaSKiran Chandramohan   bool isCancellable = false;
4624d83aa47SJohannes Doerfert   // TODO: Determine the actual alloca insertion point, e.g., the function
4634d83aa47SJohannes Doerfert   // entry or the alloca insertion point as provided by the body callback
4644d83aa47SJohannes Doerfert   // above.
4654d83aa47SJohannes Doerfert   llvm::OpenMPIRBuilder::InsertPointTy allocaIP(builder.saveIP());
466c11d868aSSourabh Singh Tomar   if (failed(bodyGenStatus))
467c11d868aSSourabh Singh Tomar     return failure();
468e6c5e6efSKiran Chandramohan   builder.restoreIP(
469e5dba2d7SMichael Kruse       ompBuilder->createParallel(builder, allocaIP, bodyGenCB, privCB, finiCB,
470e6c5e6efSKiran Chandramohan                                  ifCond, numThreads, pbKind, isCancellable));
471d9067dcaSKiran Chandramohan   return success();
472d9067dcaSKiran Chandramohan }
473c33d6970SRiver Riddle 
474c11d868aSSourabh Singh Tomar void ModuleTranslation::convertOmpOpRegions(
475c11d868aSSourabh Singh Tomar     Region &region, DenseMap<Value, llvm::Value *> &valueMapping,
476c11d868aSSourabh Singh Tomar     DenseMap<Block *, llvm::BasicBlock *> &blockMapping,
477c11d868aSSourabh Singh Tomar     llvm::Instruction *codeGenIPBBTI, llvm::BasicBlock &continuationIP,
478c11d868aSSourabh Singh Tomar     llvm::IRBuilder<> &builder, LogicalResult &bodyGenStatus) {
479c11d868aSSourabh Singh Tomar   // Convert blocks one by one in topological order to ensure
480c11d868aSSourabh Singh Tomar   // defs are converted before uses.
481c11d868aSSourabh Singh Tomar   llvm::SetVector<Block *> blocks = topologicalSort(region);
482c11d868aSSourabh Singh Tomar   for (auto indexedBB : llvm::enumerate(blocks)) {
483c11d868aSSourabh Singh Tomar     Block *bb = indexedBB.value();
484c11d868aSSourabh Singh Tomar     llvm::BasicBlock *curLLVMBB = blockMapping[bb];
485c11d868aSSourabh Singh Tomar     if (bb->isEntryBlock()) {
486c11d868aSSourabh Singh Tomar       assert(codeGenIPBBTI->getNumSuccessors() == 1 &&
487c11d868aSSourabh Singh Tomar              "OpenMPIRBuilder provided entry block has multiple successors");
488c11d868aSSourabh Singh Tomar       assert(codeGenIPBBTI->getSuccessor(0) == &continuationIP &&
489c11d868aSSourabh Singh Tomar              "ContinuationIP is not the successor of OpenMPIRBuilder "
490c11d868aSSourabh Singh Tomar              "provided entry block");
491c11d868aSSourabh Singh Tomar       codeGenIPBBTI->setSuccessor(0, curLLVMBB);
492c11d868aSSourabh Singh Tomar     }
493c11d868aSSourabh Singh Tomar 
494c11d868aSSourabh Singh Tomar     if (failed(convertBlock(*bb, /*ignoreArguments=*/indexedBB.index() == 0))) {
495c11d868aSSourabh Singh Tomar       bodyGenStatus = failure();
496c11d868aSSourabh Singh Tomar       return;
497c11d868aSSourabh Singh Tomar     }
498c11d868aSSourabh Singh Tomar   }
499c11d868aSSourabh Singh Tomar   // Finally, after all blocks have been traversed and values mapped,
500c11d868aSSourabh Singh Tomar   // connect the PHI nodes to the results of preceding blocks.
501db884dafSAlex Zinenko   connectPHINodes(region, valueMapping, blockMapping, branchMapping);
502c11d868aSSourabh Singh Tomar }
503c11d868aSSourabh Singh Tomar 
504c11d868aSSourabh Singh Tomar LogicalResult ModuleTranslation::convertOmpMaster(Operation &opInst,
505c11d868aSSourabh Singh Tomar                                                   llvm::IRBuilder<> &builder) {
506c11d868aSSourabh Singh Tomar   using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy;
507c11d868aSSourabh Singh Tomar   // TODO: support error propagation in OpenMPIRBuilder and use it instead of
508c11d868aSSourabh Singh Tomar   // relying on captured variables.
509c11d868aSSourabh Singh Tomar   LogicalResult bodyGenStatus = success();
510c11d868aSSourabh Singh Tomar 
511c11d868aSSourabh Singh Tomar   auto bodyGenCB = [&](InsertPointTy allocaIP, InsertPointTy codeGenIP,
512c11d868aSSourabh Singh Tomar                        llvm::BasicBlock &continuationIP) {
513c11d868aSSourabh Singh Tomar     llvm::LLVMContext &llvmContext = llvmModule->getContext();
514c11d868aSSourabh Singh Tomar 
515c11d868aSSourabh Singh Tomar     llvm::BasicBlock *codeGenIPBB = codeGenIP.getBlock();
516c11d868aSSourabh Singh Tomar     llvm::Instruction *codeGenIPBBTI = codeGenIPBB->getTerminator();
517c11d868aSSourabh Singh Tomar     ompContinuationIPStack.push_back(&continuationIP);
518c11d868aSSourabh Singh Tomar 
519c11d868aSSourabh Singh Tomar     // MasterOp has only `1` region associated with it.
520c11d868aSSourabh Singh Tomar     auto &region = cast<omp::MasterOp>(opInst).getRegion();
521c11d868aSSourabh Singh Tomar     for (auto &bb : region) {
522c11d868aSSourabh Singh Tomar       auto *llvmBB = llvm::BasicBlock::Create(
523c11d868aSSourabh Singh Tomar           llvmContext, "omp.master.region", codeGenIP.getBlock()->getParent());
524c11d868aSSourabh Singh Tomar       blockMapping[&bb] = llvmBB;
525c11d868aSSourabh Singh Tomar     }
526c11d868aSSourabh Singh Tomar     convertOmpOpRegions(region, valueMapping, blockMapping, codeGenIPBBTI,
527c11d868aSSourabh Singh Tomar                         continuationIP, builder, bodyGenStatus);
528c11d868aSSourabh Singh Tomar     ompContinuationIPStack.pop_back();
529c11d868aSSourabh Singh Tomar   };
530c11d868aSSourabh Singh Tomar 
531c11d868aSSourabh Singh Tomar   // TODO: Perform finalization actions for variables. This has to be
532c11d868aSSourabh Singh Tomar   // called for variables which have destructors/finalizers.
533c11d868aSSourabh Singh Tomar   auto finiCB = [&](InsertPointTy codeGenIP) {};
534c11d868aSSourabh Singh Tomar 
535c11d868aSSourabh Singh Tomar   builder.restoreIP(ompBuilder->createMaster(builder, bodyGenCB, finiCB));
536c11d868aSSourabh Singh Tomar   return success();
537c11d868aSSourabh Singh Tomar }
538c11d868aSSourabh Singh Tomar 
53932a884c9SAlex Zinenko /// Converts an OpenMP workshare loop into LLVM IR using OpenMPIRBuilder.
54032a884c9SAlex Zinenko LogicalResult ModuleTranslation::convertOmpWsLoop(Operation &opInst,
54132a884c9SAlex Zinenko                                                   llvm::IRBuilder<> &builder) {
54232a884c9SAlex Zinenko   auto loop = cast<omp::WsLoopOp>(opInst);
54332a884c9SAlex Zinenko   // TODO: this should be in the op verifier instead.
54432a884c9SAlex Zinenko   if (loop.lowerBound().empty())
54532a884c9SAlex Zinenko     return failure();
54632a884c9SAlex Zinenko 
54732a884c9SAlex Zinenko   if (loop.getNumLoops() != 1)
54832a884c9SAlex Zinenko     return opInst.emitOpError("collapsed loops not yet supported");
54932a884c9SAlex Zinenko 
55032a884c9SAlex Zinenko   if (loop.schedule_val().hasValue() &&
55132a884c9SAlex Zinenko       omp::symbolizeClauseScheduleKind(loop.schedule_val().getValue()) !=
55232a884c9SAlex Zinenko           omp::ClauseScheduleKind::Static)
55332a884c9SAlex Zinenko     return opInst.emitOpError(
55432a884c9SAlex Zinenko         "only static (default) loop schedule is currently supported");
55532a884c9SAlex Zinenko 
55632a884c9SAlex Zinenko   llvm::Function *func = builder.GetInsertBlock()->getParent();
55732a884c9SAlex Zinenko   llvm::LLVMContext &llvmContext = llvmModule->getContext();
55832a884c9SAlex Zinenko 
55932a884c9SAlex Zinenko   // Find the loop configuration.
56032a884c9SAlex Zinenko   llvm::Value *lowerBound = valueMapping.lookup(loop.lowerBound()[0]);
56132a884c9SAlex Zinenko   llvm::Value *upperBound = valueMapping.lookup(loop.upperBound()[0]);
56232a884c9SAlex Zinenko   llvm::Value *step = valueMapping.lookup(loop.step()[0]);
56332a884c9SAlex Zinenko   llvm::Type *ivType = step->getType();
56432a884c9SAlex Zinenko   llvm::Value *chunk = loop.schedule_chunk_var()
56532a884c9SAlex Zinenko                            ? valueMapping[loop.schedule_chunk_var()]
56632a884c9SAlex Zinenko                            : llvm::ConstantInt::get(ivType, 1);
56732a884c9SAlex Zinenko 
56832a884c9SAlex Zinenko   // Set up the source location value for OpenMP runtime.
56932a884c9SAlex Zinenko   llvm::DISubprogram *subprogram =
57032a884c9SAlex Zinenko       builder.GetInsertBlock()->getParent()->getSubprogram();
57132a884c9SAlex Zinenko   const llvm::DILocation *diLoc =
57232a884c9SAlex Zinenko       debugTranslation->translateLoc(opInst.getLoc(), subprogram);
57332a884c9SAlex Zinenko   llvm::OpenMPIRBuilder::LocationDescription ompLoc(builder.saveIP(),
57432a884c9SAlex Zinenko                                                     llvm::DebugLoc(diLoc));
57532a884c9SAlex Zinenko 
57632a884c9SAlex Zinenko   // Generator of the canonical loop body. Produces an SESE region of basic
57732a884c9SAlex Zinenko   // blocks.
57832a884c9SAlex Zinenko   // TODO: support error propagation in OpenMPIRBuilder and use it instead of
57932a884c9SAlex Zinenko   // relying on captured variables.
58032a884c9SAlex Zinenko   LogicalResult bodyGenStatus = success();
58132a884c9SAlex Zinenko   auto bodyGen = [&](llvm::OpenMPIRBuilder::InsertPointTy ip, llvm::Value *iv) {
58232a884c9SAlex Zinenko     llvm::IRBuilder<>::InsertPointGuard guard(builder);
58332a884c9SAlex Zinenko 
58432a884c9SAlex Zinenko     // Make sure further conversions know about the induction variable.
58532a884c9SAlex Zinenko     valueMapping[loop.getRegion().front().getArgument(0)] = iv;
58632a884c9SAlex Zinenko 
58732a884c9SAlex Zinenko     llvm::BasicBlock *entryBlock = ip.getBlock();
58832a884c9SAlex Zinenko     llvm::BasicBlock *exitBlock =
58932a884c9SAlex Zinenko         entryBlock->splitBasicBlock(ip.getPoint(), "omp.wsloop.exit");
59032a884c9SAlex Zinenko 
59132a884c9SAlex Zinenko     // Convert the body of the loop.
59232a884c9SAlex Zinenko     Region &region = loop.region();
59332a884c9SAlex Zinenko     for (Block &bb : region) {
59432a884c9SAlex Zinenko       llvm::BasicBlock *llvmBB =
59532a884c9SAlex Zinenko           llvm::BasicBlock::Create(llvmContext, "omp.wsloop.region", func);
59632a884c9SAlex Zinenko       blockMapping[&bb] = llvmBB;
59732a884c9SAlex Zinenko 
59832a884c9SAlex Zinenko       // Retarget the branch of the entry block to the entry block of the
59932a884c9SAlex Zinenko       // converted region (regions are single-entry).
60032a884c9SAlex Zinenko       if (bb.isEntryBlock()) {
60132a884c9SAlex Zinenko         auto *branch = cast<llvm::BranchInst>(entryBlock->getTerminator());
60232a884c9SAlex Zinenko         branch->setSuccessor(0, llvmBB);
60332a884c9SAlex Zinenko       }
60432a884c9SAlex Zinenko     }
60532a884c9SAlex Zinenko 
60632a884c9SAlex Zinenko     // Block conversion creates a new IRBuilder every time so need not bother
60732a884c9SAlex Zinenko     // about maintaining the insertion point.
60832a884c9SAlex Zinenko     llvm::SetVector<Block *> blocks = topologicalSort(region);
60932a884c9SAlex Zinenko     for (Block *bb : blocks) {
61032a884c9SAlex Zinenko       if (failed(convertBlock(*bb, bb->isEntryBlock()))) {
61132a884c9SAlex Zinenko         bodyGenStatus = failure();
61232a884c9SAlex Zinenko         return;
61332a884c9SAlex Zinenko       }
61432a884c9SAlex Zinenko 
61532a884c9SAlex Zinenko       // Special handling for `omp.yield` terminators (we may have more than
61632a884c9SAlex Zinenko       // one): they return the control to the parent WsLoop operation so replace
61732a884c9SAlex Zinenko       // them with the branch to the exit block. We handle this here to avoid
61832a884c9SAlex Zinenko       // relying inter-function communication through the ModuleTranslation
61932a884c9SAlex Zinenko       // class to set up the correct insertion point. This is also consistent
62032a884c9SAlex Zinenko       // with MLIR's idiom of handling special region terminators in the same
62132a884c9SAlex Zinenko       // code that handles the region-owning operation.
62232a884c9SAlex Zinenko       if (isa<omp::YieldOp>(bb->getTerminator())) {
62332a884c9SAlex Zinenko         llvm::BasicBlock *llvmBB = blockMapping[bb];
62432a884c9SAlex Zinenko         builder.SetInsertPoint(llvmBB, llvmBB->end());
62532a884c9SAlex Zinenko         builder.CreateBr(exitBlock);
62632a884c9SAlex Zinenko       }
62732a884c9SAlex Zinenko     }
62832a884c9SAlex Zinenko 
62932a884c9SAlex Zinenko     connectPHINodes(region, valueMapping, blockMapping, branchMapping);
63032a884c9SAlex Zinenko   };
63132a884c9SAlex Zinenko 
63232a884c9SAlex Zinenko   // Delegate actual loop construction to the OpenMP IRBuilder.
63332a884c9SAlex Zinenko   // TODO: this currently assumes WsLoop is semantically similar to SCF loop,
63432a884c9SAlex Zinenko   // i.e. it has a positive step, uses signed integer semantics, and its upper
63532a884c9SAlex Zinenko   // bound is not included. Reconsider this code when WsLoop clearly supports
63632a884c9SAlex Zinenko   // more cases.
63732a884c9SAlex Zinenko   llvm::BasicBlock *insertBlock = builder.GetInsertBlock();
63832a884c9SAlex Zinenko   llvm::CanonicalLoopInfo *loopInfo = ompBuilder->createCanonicalLoop(
63932a884c9SAlex Zinenko       ompLoc, bodyGen, lowerBound, upperBound, step, /*IsSigned=*/true,
64032a884c9SAlex Zinenko       /*InclusiveStop=*/false);
64132a884c9SAlex Zinenko   if (failed(bodyGenStatus))
64232a884c9SAlex Zinenko     return failure();
64332a884c9SAlex Zinenko 
64432a884c9SAlex Zinenko   // TODO: get the alloca insertion point from the parallel operation builder.
64532a884c9SAlex Zinenko   // If we insert the at the top of the current function, they will be passed as
64632a884c9SAlex Zinenko   // extra arguments into the function the parallel operation builder outlines.
64732a884c9SAlex Zinenko   // Put them at the start of the current block for now.
64832a884c9SAlex Zinenko   llvm::OpenMPIRBuilder::InsertPointTy allocaIP(
64932a884c9SAlex Zinenko       insertBlock, insertBlock->getFirstInsertionPt());
65032a884c9SAlex Zinenko   loopInfo = ompBuilder->createStaticWorkshareLoop(
65132a884c9SAlex Zinenko       ompLoc, loopInfo, allocaIP,
65232a884c9SAlex Zinenko       !loop.nowait().hasValue() || loop.nowait().getValue(), chunk);
65332a884c9SAlex Zinenko 
65432a884c9SAlex Zinenko   // Continue building IR after the loop.
65532a884c9SAlex Zinenko   builder.restoreIP(loopInfo->getAfterIP());
65632a884c9SAlex Zinenko   return success();
65732a884c9SAlex Zinenko }
65832a884c9SAlex Zinenko 
6597ecee63eSKiran Kumar T P /// Given an OpenMP MLIR operation, create the corresponding LLVM IR
6607ecee63eSKiran Kumar T P /// (including OpenMP runtime calls).
6617ecee63eSKiran Kumar T P LogicalResult
6627ecee63eSKiran Kumar T P ModuleTranslation::convertOmpOperation(Operation &opInst,
6637ecee63eSKiran Kumar T P                                        llvm::IRBuilder<> &builder) {
6647ecee63eSKiran Kumar T P   if (!ompBuilder) {
6657ecee63eSKiran Kumar T P     ompBuilder = std::make_unique<llvm::OpenMPIRBuilder>(*llvmModule);
6667ecee63eSKiran Kumar T P     ompBuilder->initialize();
6677ecee63eSKiran Kumar T P   }
668ebf190fcSRiver Riddle   return llvm::TypeSwitch<Operation *, LogicalResult>(&opInst)
6697ecee63eSKiran Kumar T P       .Case([&](omp::BarrierOp) {
670e5dba2d7SMichael Kruse         ompBuilder->createBarrier(builder.saveIP(), llvm::omp::OMPD_barrier);
6717ecee63eSKiran Kumar T P         return success();
6727ecee63eSKiran Kumar T P       })
6737ecee63eSKiran Kumar T P       .Case([&](omp::TaskwaitOp) {
674e5dba2d7SMichael Kruse         ompBuilder->createTaskwait(builder.saveIP());
6757ecee63eSKiran Kumar T P         return success();
6767ecee63eSKiran Kumar T P       })
6777ecee63eSKiran Kumar T P       .Case([&](omp::TaskyieldOp) {
678e5dba2d7SMichael Kruse         ompBuilder->createTaskyield(builder.saveIP());
6797ecee63eSKiran Kumar T P         return success();
6807ecee63eSKiran Kumar T P       })
681fa8fc9ffSKiran Kumar T P       .Case([&](omp::FlushOp) {
68241b09f4eSKazuaki Ishizaki         // No support in Openmp runtime function (__kmpc_flush) to accept
683fa8fc9ffSKiran Kumar T P         // the argument list.
684fa8fc9ffSKiran Kumar T P         // OpenMP standard states the following:
685fa8fc9ffSKiran Kumar T P         //  "An implementation may implement a flush with a list by ignoring
686fa8fc9ffSKiran Kumar T P         //   the list, and treating it the same as a flush without a list."
687fa8fc9ffSKiran Kumar T P         //
688fa8fc9ffSKiran Kumar T P         // The argument list is discarded so that, flush with a list is treated
689fa8fc9ffSKiran Kumar T P         // same as a flush without a list.
690e5dba2d7SMichael Kruse         ompBuilder->createFlush(builder.saveIP());
691fa8fc9ffSKiran Kumar T P         return success();
692fa8fc9ffSKiran Kumar T P       })
693a71a0d6dSKiran Chandramohan       .Case([&](omp::TerminatorOp) {
694a71a0d6dSKiran Chandramohan         builder.CreateBr(ompContinuationIPStack.back());
695a71a0d6dSKiran Chandramohan         return success();
696a71a0d6dSKiran Chandramohan       })
697d9067dcaSKiran Chandramohan       .Case(
698d9067dcaSKiran Chandramohan           [&](omp::ParallelOp) { return convertOmpParallel(opInst, builder); })
699c11d868aSSourabh Singh Tomar       .Case([&](omp::MasterOp) { return convertOmpMaster(opInst, builder); })
70032a884c9SAlex Zinenko       .Case([&](omp::WsLoopOp) { return convertOmpWsLoop(opInst, builder); })
70132a884c9SAlex Zinenko       .Case([&](omp::YieldOp op) {
70232a884c9SAlex Zinenko         // Yields are loop terminators that can be just omitted. The loop
70332a884c9SAlex Zinenko         // structure was created in the function that handles WsLoopOp.
70432a884c9SAlex Zinenko         assert(op.getNumOperands() == 0 && "unexpected yield with operands");
70532a884c9SAlex Zinenko         return success();
70632a884c9SAlex Zinenko       })
7077ecee63eSKiran Kumar T P       .Default([&](Operation *inst) {
7087ecee63eSKiran Kumar T P         return inst->emitError("unsupported OpenMP operation: ")
7097ecee63eSKiran Kumar T P                << inst->getName();
7107ecee63eSKiran Kumar T P       });
7117ecee63eSKiran Kumar T P }
7127ecee63eSKiran Kumar T P 
7132666b973SRiver Riddle /// Given a single MLIR operation, create the corresponding LLVM IR operation
7142666b973SRiver Riddle /// using the `builder`.  LLVM IR Builder does not have a generic interface so
7152666b973SRiver Riddle /// this has to be a long chain of `if`s calling different functions with a
7162666b973SRiver Riddle /// different number of arguments.
717baa1ec22SAlex Zinenko LogicalResult ModuleTranslation::convertOperation(Operation &opInst,
7185d7231d8SStephan Herhut                                                   llvm::IRBuilder<> &builder) {
7195d7231d8SStephan Herhut   auto extractPosition = [](ArrayAttr attr) {
7205d7231d8SStephan Herhut     SmallVector<unsigned, 4> position;
7215d7231d8SStephan Herhut     position.reserve(attr.size());
7225d7231d8SStephan Herhut     for (Attribute v : attr)
7235d7231d8SStephan Herhut       position.push_back(v.cast<IntegerAttr>().getValue().getZExtValue());
7245d7231d8SStephan Herhut     return position;
7255d7231d8SStephan Herhut   };
7265d7231d8SStephan Herhut 
727ba0fa925SRiver Riddle #include "mlir/Dialect/LLVMIR/LLVMConversions.inc"
7285d7231d8SStephan Herhut 
7295d7231d8SStephan Herhut   // Emit function calls.  If the "callee" attribute is present, this is a
7305d7231d8SStephan Herhut   // direct function call and we also need to look up the remapped function
7315d7231d8SStephan Herhut   // itself.  Otherwise, this is an indirect call and the callee is the first
7325d7231d8SStephan Herhut   // operand, look it up as a normal value.  Return the llvm::Value representing
7335d7231d8SStephan Herhut   // the function result, which may be of llvm::VoidTy type.
7345d7231d8SStephan Herhut   auto convertCall = [this, &builder](Operation &op) -> llvm::Value * {
7355d7231d8SStephan Herhut     auto operands = lookupValues(op.getOperands());
7365d7231d8SStephan Herhut     ArrayRef<llvm::Value *> operandsRef(operands);
7379b9c647cSRiver Riddle     if (auto attr = op.getAttrOfType<FlatSymbolRefAttr>("callee")) {
7385d7231d8SStephan Herhut       return builder.CreateCall(functionMapping.lookup(attr.getValue()),
7395d7231d8SStephan Herhut                                 operandsRef);
7405d7231d8SStephan Herhut     } else {
741133049d0SEli Friedman       auto *calleePtrType =
742133049d0SEli Friedman           cast<llvm::PointerType>(operandsRef.front()->getType());
743133049d0SEli Friedman       auto *calleeType =
744133049d0SEli Friedman           cast<llvm::FunctionType>(calleePtrType->getElementType());
745133049d0SEli Friedman       return builder.CreateCall(calleeType, operandsRef.front(),
746133049d0SEli Friedman                                 operandsRef.drop_front());
7475d7231d8SStephan Herhut     }
7485d7231d8SStephan Herhut   };
7495d7231d8SStephan Herhut 
7505d7231d8SStephan Herhut   // Emit calls.  If the called function has a result, remap the corresponding
7515d7231d8SStephan Herhut   // value.  Note that LLVM IR dialect CallOp has either 0 or 1 result.
752d5b60ee8SRiver Riddle   if (isa<LLVM::CallOp>(opInst)) {
7535d7231d8SStephan Herhut     llvm::Value *result = convertCall(opInst);
7545d7231d8SStephan Herhut     if (opInst.getNumResults() != 0) {
7555d7231d8SStephan Herhut       valueMapping[opInst.getResult(0)] = result;
756baa1ec22SAlex Zinenko       return success();
7575d7231d8SStephan Herhut     }
7585d7231d8SStephan Herhut     // Check that LLVM call returns void for 0-result functions.
759baa1ec22SAlex Zinenko     return success(result->getType()->isVoidTy());
7605d7231d8SStephan Herhut   }
7615d7231d8SStephan Herhut 
762047400edSNicolas Vasilache   if (auto inlineAsmOp = dyn_cast<LLVM::InlineAsmOp>(opInst)) {
763047400edSNicolas Vasilache     // TODO: refactor function type creation which usually occurs in std-LLVM
764047400edSNicolas Vasilache     // conversion.
765047400edSNicolas Vasilache     SmallVector<LLVM::LLVMType, 8> operandTypes;
766047400edSNicolas Vasilache     operandTypes.reserve(inlineAsmOp.operands().size());
767047400edSNicolas Vasilache     for (auto t : inlineAsmOp.operands().getTypes())
768047400edSNicolas Vasilache       operandTypes.push_back(t.cast<LLVM::LLVMType>());
769047400edSNicolas Vasilache 
770047400edSNicolas Vasilache     LLVM::LLVMType resultType;
771047400edSNicolas Vasilache     if (inlineAsmOp.getNumResults() == 0) {
772*7ed9cfc7SAlex Zinenko       resultType = LLVM::LLVMVoidType::get(mlirModule->getContext());
773047400edSNicolas Vasilache     } else {
774047400edSNicolas Vasilache       assert(inlineAsmOp.getNumResults() == 1);
775047400edSNicolas Vasilache       resultType = inlineAsmOp.getResultTypes()[0].cast<LLVM::LLVMType>();
776047400edSNicolas Vasilache     }
777*7ed9cfc7SAlex Zinenko     auto ft = LLVM::LLVMFunctionType::get(resultType, operandTypes);
778047400edSNicolas Vasilache     llvm::InlineAsm *inlineAsmInst =
779047400edSNicolas Vasilache         inlineAsmOp.asm_dialect().hasValue()
780047400edSNicolas Vasilache             ? llvm::InlineAsm::get(
781047400edSNicolas Vasilache                   static_cast<llvm::FunctionType *>(convertType(ft)),
782047400edSNicolas Vasilache                   inlineAsmOp.asm_string(), inlineAsmOp.constraints(),
783047400edSNicolas Vasilache                   inlineAsmOp.has_side_effects(), inlineAsmOp.is_align_stack(),
784047400edSNicolas Vasilache                   convertAsmDialectToLLVM(*inlineAsmOp.asm_dialect()))
785047400edSNicolas Vasilache             : llvm::InlineAsm::get(
786047400edSNicolas Vasilache                   static_cast<llvm::FunctionType *>(convertType(ft)),
787047400edSNicolas Vasilache                   inlineAsmOp.asm_string(), inlineAsmOp.constraints(),
788047400edSNicolas Vasilache                   inlineAsmOp.has_side_effects(), inlineAsmOp.is_align_stack());
789047400edSNicolas Vasilache     llvm::Value *result =
790047400edSNicolas Vasilache         builder.CreateCall(inlineAsmInst, lookupValues(inlineAsmOp.operands()));
791047400edSNicolas Vasilache     if (opInst.getNumResults() != 0)
792047400edSNicolas Vasilache       valueMapping[opInst.getResult(0)] = result;
793047400edSNicolas Vasilache     return success();
794047400edSNicolas Vasilache   }
795047400edSNicolas Vasilache 
796d242aa24SShraiysh Vaishay   if (auto invOp = dyn_cast<LLVM::InvokeOp>(opInst)) {
797d242aa24SShraiysh Vaishay     auto operands = lookupValues(opInst.getOperands());
798d242aa24SShraiysh Vaishay     ArrayRef<llvm::Value *> operandsRef(operands);
799133049d0SEli Friedman     if (auto attr = opInst.getAttrOfType<FlatSymbolRefAttr>("callee")) {
800d242aa24SShraiysh Vaishay       builder.CreateInvoke(functionMapping.lookup(attr.getValue()),
801d242aa24SShraiysh Vaishay                            blockMapping[invOp.getSuccessor(0)],
802d242aa24SShraiysh Vaishay                            blockMapping[invOp.getSuccessor(1)], operandsRef);
803133049d0SEli Friedman     } else {
804133049d0SEli Friedman       auto *calleePtrType =
805133049d0SEli Friedman           cast<llvm::PointerType>(operandsRef.front()->getType());
806133049d0SEli Friedman       auto *calleeType =
807133049d0SEli Friedman           cast<llvm::FunctionType>(calleePtrType->getElementType());
808d242aa24SShraiysh Vaishay       builder.CreateInvoke(
809133049d0SEli Friedman           calleeType, operandsRef.front(), blockMapping[invOp.getSuccessor(0)],
810d242aa24SShraiysh Vaishay           blockMapping[invOp.getSuccessor(1)], operandsRef.drop_front());
811133049d0SEli Friedman     }
812d242aa24SShraiysh Vaishay     return success();
813d242aa24SShraiysh Vaishay   }
814d242aa24SShraiysh Vaishay 
815d242aa24SShraiysh Vaishay   if (auto lpOp = dyn_cast<LLVM::LandingpadOp>(opInst)) {
816aec38c61SAlex Zinenko     llvm::Type *ty = convertType(lpOp.getType().cast<LLVMType>());
817d242aa24SShraiysh Vaishay     llvm::LandingPadInst *lpi =
818d242aa24SShraiysh Vaishay         builder.CreateLandingPad(ty, lpOp.getNumOperands());
819d242aa24SShraiysh Vaishay 
820d242aa24SShraiysh Vaishay     // Add clauses
821d242aa24SShraiysh Vaishay     for (auto operand : lookupValues(lpOp.getOperands())) {
822d242aa24SShraiysh Vaishay       // All operands should be constant - checked by verifier
823d242aa24SShraiysh Vaishay       if (auto constOperand = dyn_cast<llvm::Constant>(operand))
824d242aa24SShraiysh Vaishay         lpi->addClause(constOperand);
825d242aa24SShraiysh Vaishay     }
826ff77397fSShraiysh Vaishay     valueMapping[lpOp.getResult()] = lpi;
827d242aa24SShraiysh Vaishay     return success();
828d242aa24SShraiysh Vaishay   }
829d242aa24SShraiysh Vaishay 
8305d7231d8SStephan Herhut   // Emit branches.  We need to look up the remapped blocks and ignore the block
8315d7231d8SStephan Herhut   // arguments that were transformed into PHI nodes.
832c5ecf991SRiver Riddle   if (auto brOp = dyn_cast<LLVM::BrOp>(opInst)) {
833db884dafSAlex Zinenko     llvm::BranchInst *branch =
834c0fd5e65SRiver Riddle         builder.CreateBr(blockMapping[brOp.getSuccessor()]);
835db884dafSAlex Zinenko     branchMapping.try_emplace(&opInst, branch);
836baa1ec22SAlex Zinenko     return success();
8375d7231d8SStephan Herhut   }
838c5ecf991SRiver Riddle   if (auto condbrOp = dyn_cast<LLVM::CondBrOp>(opInst)) {
83999d03f03SGeorge Mitenkov     auto weights = condbrOp.branch_weights();
84099d03f03SGeorge Mitenkov     llvm::MDNode *branchWeights = nullptr;
84199d03f03SGeorge Mitenkov     if (weights) {
84299d03f03SGeorge Mitenkov       // Map weight attributes to LLVM metadata.
84399d03f03SGeorge Mitenkov       auto trueWeight =
84499d03f03SGeorge Mitenkov           weights.getValue().getValue(0).cast<IntegerAttr>().getInt();
84599d03f03SGeorge Mitenkov       auto falseWeight =
84699d03f03SGeorge Mitenkov           weights.getValue().getValue(1).cast<IntegerAttr>().getInt();
84799d03f03SGeorge Mitenkov       branchWeights =
84899d03f03SGeorge Mitenkov           llvm::MDBuilder(llvmModule->getContext())
84999d03f03SGeorge Mitenkov               .createBranchWeights(static_cast<uint32_t>(trueWeight),
85099d03f03SGeorge Mitenkov                                    static_cast<uint32_t>(falseWeight));
85199d03f03SGeorge Mitenkov     }
852db884dafSAlex Zinenko     llvm::BranchInst *branch = builder.CreateCondBr(
853db884dafSAlex Zinenko         valueMapping.lookup(condbrOp.getOperand(0)),
8545d7231d8SStephan Herhut         blockMapping[condbrOp.getSuccessor(0)],
85599d03f03SGeorge Mitenkov         blockMapping[condbrOp.getSuccessor(1)], branchWeights);
856db884dafSAlex Zinenko     branchMapping.try_emplace(&opInst, branch);
857baa1ec22SAlex Zinenko     return success();
8585d7231d8SStephan Herhut   }
85914f24155SBrian Gesiak   if (auto switchOp = dyn_cast<LLVM::SwitchOp>(opInst)) {
86014f24155SBrian Gesiak     llvm::MDNode *branchWeights = nullptr;
86114f24155SBrian Gesiak     if (auto weights = switchOp.branch_weights()) {
86214f24155SBrian Gesiak       llvm::SmallVector<uint32_t> weightValues;
86314f24155SBrian Gesiak       weightValues.reserve(weights->size());
86414f24155SBrian Gesiak       for (llvm::APInt weight : weights->cast<DenseIntElementsAttr>())
86514f24155SBrian Gesiak         weightValues.push_back(weight.getLimitedValue());
86614f24155SBrian Gesiak       branchWeights = llvm::MDBuilder(llvmModule->getContext())
86714f24155SBrian Gesiak                           .createBranchWeights(weightValues);
86814f24155SBrian Gesiak     }
86914f24155SBrian Gesiak 
87014f24155SBrian Gesiak     llvm::SwitchInst *switchInst =
87114f24155SBrian Gesiak         builder.CreateSwitch(valueMapping[switchOp.value()],
87214f24155SBrian Gesiak                              blockMapping[switchOp.defaultDestination()],
87314f24155SBrian Gesiak                              switchOp.caseDestinations().size(), branchWeights);
87414f24155SBrian Gesiak 
87514f24155SBrian Gesiak     auto *ty = llvm::cast<llvm::IntegerType>(
87614f24155SBrian Gesiak         convertType(switchOp.value().getType().cast<LLVMType>()));
87714f24155SBrian Gesiak     for (auto i :
87814f24155SBrian Gesiak          llvm::zip(switchOp.case_values()->cast<DenseIntElementsAttr>(),
87914f24155SBrian Gesiak                    switchOp.caseDestinations()))
88014f24155SBrian Gesiak       switchInst->addCase(
88114f24155SBrian Gesiak           llvm::ConstantInt::get(ty, std::get<0>(i).getLimitedValue()),
88214f24155SBrian Gesiak           blockMapping[std::get<1>(i)]);
88314f24155SBrian Gesiak 
88414f24155SBrian Gesiak     branchMapping.try_emplace(&opInst, switchInst);
88514f24155SBrian Gesiak     return success();
88614f24155SBrian Gesiak   }
8875d7231d8SStephan Herhut 
8882dd38b09SAlex Zinenko   // Emit addressof.  We need to look up the global value referenced by the
8892dd38b09SAlex Zinenko   // operation and store it in the MLIR-to-LLVM value mapping.  This does not
8902dd38b09SAlex Zinenko   // emit any LLVM instruction.
8912dd38b09SAlex Zinenko   if (auto addressOfOp = dyn_cast<LLVM::AddressOfOp>(opInst)) {
8922dd38b09SAlex Zinenko     LLVM::GlobalOp global = addressOfOp.getGlobal();
893cba733edSAlex Zinenko     LLVM::LLVMFuncOp function = addressOfOp.getFunction();
8942dd38b09SAlex Zinenko 
895cba733edSAlex Zinenko     // The verifier should not have allowed this.
896cba733edSAlex Zinenko     assert((global || function) &&
897cba733edSAlex Zinenko            "referencing an undefined global or function");
898cba733edSAlex Zinenko 
899cba733edSAlex Zinenko     valueMapping[addressOfOp.getResult()] =
900cba733edSAlex Zinenko         global ? globalsMapping.lookup(global)
901cba733edSAlex Zinenko                : functionMapping.lookup(function.getName());
9022dd38b09SAlex Zinenko     return success();
9032dd38b09SAlex Zinenko   }
9042dd38b09SAlex Zinenko 
9059f9f89d4SMehdi Amini   if (ompDialect && opInst.getDialect() == ompDialect)
9067ecee63eSKiran Kumar T P     return convertOmpOperation(opInst, builder);
90792a295ebSKiran Chandramohan 
908baa1ec22SAlex Zinenko   return opInst.emitError("unsupported or non-LLVM operation: ")
909baa1ec22SAlex Zinenko          << opInst.getName();
9105d7231d8SStephan Herhut }
9115d7231d8SStephan Herhut 
9122666b973SRiver Riddle /// Convert block to LLVM IR.  Unless `ignoreArguments` is set, emit PHI nodes
9132666b973SRiver Riddle /// to define values corresponding to the MLIR block arguments.  These nodes
9142666b973SRiver Riddle /// are not connected to the source basic blocks, which may not exist yet.
915baa1ec22SAlex Zinenko LogicalResult ModuleTranslation::convertBlock(Block &bb, bool ignoreArguments) {
9165d7231d8SStephan Herhut   llvm::IRBuilder<> builder(blockMapping[&bb]);
917c33d6970SRiver Riddle   auto *subprogram = builder.GetInsertBlock()->getParent()->getSubprogram();
9185d7231d8SStephan Herhut 
9195d7231d8SStephan Herhut   // Before traversing operations, make block arguments available through
9205d7231d8SStephan Herhut   // value remapping and PHI nodes, but do not add incoming edges for the PHI
9215d7231d8SStephan Herhut   // nodes just yet: those values may be defined by this or following blocks.
9225d7231d8SStephan Herhut   // This step is omitted if "ignoreArguments" is set.  The arguments of the
9235d7231d8SStephan Herhut   // first block have been already made available through the remapping of
9245d7231d8SStephan Herhut   // LLVM function arguments.
9255d7231d8SStephan Herhut   if (!ignoreArguments) {
9265d7231d8SStephan Herhut     auto predecessors = bb.getPredecessors();
9275d7231d8SStephan Herhut     unsigned numPredecessors =
9285d7231d8SStephan Herhut         std::distance(predecessors.begin(), predecessors.end());
92935807bc4SRiver Riddle     for (auto arg : bb.getArguments()) {
9302bdf33ccSRiver Riddle       auto wrappedType = arg.getType().dyn_cast<LLVM::LLVMType>();
931baa1ec22SAlex Zinenko       if (!wrappedType)
932baa1ec22SAlex Zinenko         return emitError(bb.front().getLoc(),
933a4c3a645SRiver Riddle                          "block argument does not have an LLVM type");
934aec38c61SAlex Zinenko       llvm::Type *type = convertType(wrappedType);
9355d7231d8SStephan Herhut       llvm::PHINode *phi = builder.CreatePHI(type, numPredecessors);
9365d7231d8SStephan Herhut       valueMapping[arg] = phi;
9375d7231d8SStephan Herhut     }
9385d7231d8SStephan Herhut   }
9395d7231d8SStephan Herhut 
9405d7231d8SStephan Herhut   // Traverse operations.
9415d7231d8SStephan Herhut   for (auto &op : bb) {
942c33d6970SRiver Riddle     // Set the current debug location within the builder.
943c33d6970SRiver Riddle     builder.SetCurrentDebugLocation(
944c33d6970SRiver Riddle         debugTranslation->translateLoc(op.getLoc(), subprogram));
945c33d6970SRiver Riddle 
946baa1ec22SAlex Zinenko     if (failed(convertOperation(op, builder)))
947baa1ec22SAlex Zinenko       return failure();
9485d7231d8SStephan Herhut   }
9495d7231d8SStephan Herhut 
950baa1ec22SAlex Zinenko   return success();
9515d7231d8SStephan Herhut }
9525d7231d8SStephan Herhut 
9532666b973SRiver Riddle /// Create named global variables that correspond to llvm.mlir.global
9542666b973SRiver Riddle /// definitions.
955efa2d533SAlex Zinenko LogicalResult ModuleTranslation::convertGlobals() {
95644fc7d72STres Popp   for (auto op : getModuleBody(mlirModule).getOps<LLVM::GlobalOp>()) {
957aec38c61SAlex Zinenko     llvm::Type *type = convertType(op.getType());
958250a11aeSJames Molloy     llvm::Constant *cst = llvm::UndefValue::get(type);
959250a11aeSJames Molloy     if (op.getValueOrNull()) {
96068451df2SAlex Zinenko       // String attributes are treated separately because they cannot appear as
96168451df2SAlex Zinenko       // in-function constants and are thus not supported by getLLVMConstant.
96233a3a91bSChristian Sigg       if (auto strAttr = op.getValueOrNull().dyn_cast_or_null<StringAttr>()) {
9632dd38b09SAlex Zinenko         cst = llvm::ConstantDataArray::getString(
96468451df2SAlex Zinenko             llvmModule->getContext(), strAttr.getValue(), /*AddNull=*/false);
9652dd38b09SAlex Zinenko         type = cst->getType();
966efa2d533SAlex Zinenko       } else if (!(cst = getLLVMConstant(type, op.getValueOrNull(),
967efa2d533SAlex Zinenko                                          op.getLoc()))) {
968efa2d533SAlex Zinenko         return failure();
96968451df2SAlex Zinenko       }
970250a11aeSJames Molloy     } else if (Block *initializer = op.getInitializerBlock()) {
971250a11aeSJames Molloy       llvm::IRBuilder<> builder(llvmModule->getContext());
972250a11aeSJames Molloy       for (auto &op : initializer->without_terminator()) {
973250a11aeSJames Molloy         if (failed(convertOperation(op, builder)) ||
974efa2d533SAlex Zinenko             !isa<llvm::Constant>(valueMapping.lookup(op.getResult(0))))
975efa2d533SAlex Zinenko           return emitError(op.getLoc(), "unemittable constant value");
976250a11aeSJames Molloy       }
977250a11aeSJames Molloy       ReturnOp ret = cast<ReturnOp>(initializer->getTerminator());
978250a11aeSJames Molloy       cst = cast<llvm::Constant>(valueMapping.lookup(ret.getOperand(0)));
979250a11aeSJames Molloy     }
98068451df2SAlex Zinenko 
981eb67bd78SAlex Zinenko     auto linkage = convertLinkageToLLVM(op.linkage());
982d5e627f8SAlex Zinenko     bool anyExternalLinkage =
9837b5d4669SEric Schweitz         ((linkage == llvm::GlobalVariable::ExternalLinkage &&
9847b5d4669SEric Schweitz           isa<llvm::UndefValue>(cst)) ||
985d5e627f8SAlex Zinenko          linkage == llvm::GlobalVariable::ExternalWeakLinkage);
986431bb8b3SRiver Riddle     auto addrSpace = op.addr_space();
987e79bfefbSMLIR Team     auto *var = new llvm::GlobalVariable(
988d5e627f8SAlex Zinenko         *llvmModule, type, op.constant(), linkage,
989d5e627f8SAlex Zinenko         anyExternalLinkage ? nullptr : cst, op.sym_name(),
990d5e627f8SAlex Zinenko         /*InsertBefore=*/nullptr, llvm::GlobalValue::NotThreadLocal, addrSpace);
991e79bfefbSMLIR Team 
9922dd38b09SAlex Zinenko     globalsMapping.try_emplace(op, var);
993b9ff2dd8SAlex Zinenko   }
994efa2d533SAlex Zinenko 
995efa2d533SAlex Zinenko   return success();
996b9ff2dd8SAlex Zinenko }
997b9ff2dd8SAlex Zinenko 
9980a2131b7SAlex Zinenko /// Attempts to add an attribute identified by `key`, optionally with the given
9990a2131b7SAlex Zinenko /// `value` to LLVM function `llvmFunc`. Reports errors at `loc` if any. If the
10000a2131b7SAlex Zinenko /// attribute has a kind known to LLVM IR, create the attribute of this kind,
10010a2131b7SAlex Zinenko /// otherwise keep it as a string attribute. Performs additional checks for
10020a2131b7SAlex Zinenko /// attributes known to have or not have a value in order to avoid assertions
10030a2131b7SAlex Zinenko /// inside LLVM upon construction.
10040a2131b7SAlex Zinenko static LogicalResult checkedAddLLVMFnAttribute(Location loc,
10050a2131b7SAlex Zinenko                                                llvm::Function *llvmFunc,
10060a2131b7SAlex Zinenko                                                StringRef key,
10070a2131b7SAlex Zinenko                                                StringRef value = StringRef()) {
10080a2131b7SAlex Zinenko   auto kind = llvm::Attribute::getAttrKindFromName(key);
10090a2131b7SAlex Zinenko   if (kind == llvm::Attribute::None) {
10100a2131b7SAlex Zinenko     llvmFunc->addFnAttr(key, value);
10110a2131b7SAlex Zinenko     return success();
10120a2131b7SAlex Zinenko   }
10130a2131b7SAlex Zinenko 
10140a2131b7SAlex Zinenko   if (llvm::Attribute::doesAttrKindHaveArgument(kind)) {
10150a2131b7SAlex Zinenko     if (value.empty())
10160a2131b7SAlex Zinenko       return emitError(loc) << "LLVM attribute '" << key << "' expects a value";
10170a2131b7SAlex Zinenko 
10180a2131b7SAlex Zinenko     int result;
10190a2131b7SAlex Zinenko     if (!value.getAsInteger(/*Radix=*/0, result))
10200a2131b7SAlex Zinenko       llvmFunc->addFnAttr(
10210a2131b7SAlex Zinenko           llvm::Attribute::get(llvmFunc->getContext(), kind, result));
10220a2131b7SAlex Zinenko     else
10230a2131b7SAlex Zinenko       llvmFunc->addFnAttr(key, value);
10240a2131b7SAlex Zinenko     return success();
10250a2131b7SAlex Zinenko   }
10260a2131b7SAlex Zinenko 
10270a2131b7SAlex Zinenko   if (!value.empty())
10280a2131b7SAlex Zinenko     return emitError(loc) << "LLVM attribute '" << key
10290a2131b7SAlex Zinenko                           << "' does not expect a value, found '" << value
10300a2131b7SAlex Zinenko                           << "'";
10310a2131b7SAlex Zinenko 
10320a2131b7SAlex Zinenko   llvmFunc->addFnAttr(kind);
10330a2131b7SAlex Zinenko   return success();
10340a2131b7SAlex Zinenko }
10350a2131b7SAlex Zinenko 
10360a2131b7SAlex Zinenko /// Attaches the attributes listed in the given array attribute to `llvmFunc`.
10370a2131b7SAlex Zinenko /// Reports error to `loc` if any and returns immediately. Expects `attributes`
10380a2131b7SAlex Zinenko /// to be an array attribute containing either string attributes, treated as
10390a2131b7SAlex Zinenko /// value-less LLVM attributes, or array attributes containing two string
10400a2131b7SAlex Zinenko /// attributes, with the first string being the name of the corresponding LLVM
10410a2131b7SAlex Zinenko /// attribute and the second string beings its value. Note that even integer
10420a2131b7SAlex Zinenko /// attributes are expected to have their values expressed as strings.
10430a2131b7SAlex Zinenko static LogicalResult
10440a2131b7SAlex Zinenko forwardPassthroughAttributes(Location loc, Optional<ArrayAttr> attributes,
10450a2131b7SAlex Zinenko                              llvm::Function *llvmFunc) {
10460a2131b7SAlex Zinenko   if (!attributes)
10470a2131b7SAlex Zinenko     return success();
10480a2131b7SAlex Zinenko 
10490a2131b7SAlex Zinenko   for (Attribute attr : *attributes) {
10500a2131b7SAlex Zinenko     if (auto stringAttr = attr.dyn_cast<StringAttr>()) {
10510a2131b7SAlex Zinenko       if (failed(
10520a2131b7SAlex Zinenko               checkedAddLLVMFnAttribute(loc, llvmFunc, stringAttr.getValue())))
10530a2131b7SAlex Zinenko         return failure();
10540a2131b7SAlex Zinenko       continue;
10550a2131b7SAlex Zinenko     }
10560a2131b7SAlex Zinenko 
10570a2131b7SAlex Zinenko     auto arrayAttr = attr.dyn_cast<ArrayAttr>();
10580a2131b7SAlex Zinenko     if (!arrayAttr || arrayAttr.size() != 2)
10590a2131b7SAlex Zinenko       return emitError(loc)
10600a2131b7SAlex Zinenko              << "expected 'passthrough' to contain string or array attributes";
10610a2131b7SAlex Zinenko 
10620a2131b7SAlex Zinenko     auto keyAttr = arrayAttr[0].dyn_cast<StringAttr>();
10630a2131b7SAlex Zinenko     auto valueAttr = arrayAttr[1].dyn_cast<StringAttr>();
10640a2131b7SAlex Zinenko     if (!keyAttr || !valueAttr)
10650a2131b7SAlex Zinenko       return emitError(loc)
10660a2131b7SAlex Zinenko              << "expected arrays within 'passthrough' to contain two strings";
10670a2131b7SAlex Zinenko 
10680a2131b7SAlex Zinenko     if (failed(checkedAddLLVMFnAttribute(loc, llvmFunc, keyAttr.getValue(),
10690a2131b7SAlex Zinenko                                          valueAttr.getValue())))
10700a2131b7SAlex Zinenko       return failure();
10710a2131b7SAlex Zinenko   }
10720a2131b7SAlex Zinenko   return success();
10730a2131b7SAlex Zinenko }
10740a2131b7SAlex Zinenko 
10755e7959a3SAlex Zinenko LogicalResult ModuleTranslation::convertOneFunction(LLVMFuncOp func) {
1076db884dafSAlex Zinenko   // Clear the block, branch value mappings, they are only relevant within one
10775d7231d8SStephan Herhut   // function.
10785d7231d8SStephan Herhut   blockMapping.clear();
10795d7231d8SStephan Herhut   valueMapping.clear();
1080db884dafSAlex Zinenko   branchMapping.clear();
1081c33862b0SRiver Riddle   llvm::Function *llvmFunc = functionMapping.lookup(func.getName());
1082c33d6970SRiver Riddle 
1083c33d6970SRiver Riddle   // Translate the debug information for this function.
1084c33d6970SRiver Riddle   debugTranslation->translate(func, *llvmFunc);
1085c33d6970SRiver Riddle 
10865d7231d8SStephan Herhut   // Add function arguments to the value remapping table.
10875d7231d8SStephan Herhut   // If there was noalias info then we decorate each argument accordingly.
10885d7231d8SStephan Herhut   unsigned int argIdx = 0;
1089eeef50b1SFangrui Song   for (auto kvp : llvm::zip(func.getArguments(), llvmFunc->args())) {
10905d7231d8SStephan Herhut     llvm::Argument &llvmArg = std::get<1>(kvp);
1091e62a6956SRiver Riddle     BlockArgument mlirArg = std::get<0>(kvp);
10925d7231d8SStephan Herhut 
109367cc5cecSStephan Herhut     if (auto attr = func.getArgAttrOfType<BoolAttr>(
109467cc5cecSStephan Herhut             argIdx, LLVMDialect::getNoAliasAttrName())) {
10955d7231d8SStephan Herhut       // NB: Attribute already verified to be boolean, so check if we can indeed
10965d7231d8SStephan Herhut       // attach the attribute to this argument, based on its type.
10972bdf33ccSRiver Riddle       auto argTy = mlirArg.getType().dyn_cast<LLVM::LLVMType>();
10988de43b92SAlex Zinenko       if (!argTy.isa<LLVM::LLVMPointerType>())
1099baa1ec22SAlex Zinenko         return func.emitError(
11005d7231d8SStephan Herhut             "llvm.noalias attribute attached to LLVM non-pointer argument");
11015d7231d8SStephan Herhut       if (attr.getValue())
11025d7231d8SStephan Herhut         llvmArg.addAttr(llvm::Attribute::AttrKind::NoAlias);
11035d7231d8SStephan Herhut     }
11042416e28cSStephan Herhut 
110567cc5cecSStephan Herhut     if (auto attr = func.getArgAttrOfType<IntegerAttr>(
110667cc5cecSStephan Herhut             argIdx, LLVMDialect::getAlignAttrName())) {
11072416e28cSStephan Herhut       // NB: Attribute already verified to be int, so check if we can indeed
11082416e28cSStephan Herhut       // attach the attribute to this argument, based on its type.
11092416e28cSStephan Herhut       auto argTy = mlirArg.getType().dyn_cast<LLVM::LLVMType>();
11108de43b92SAlex Zinenko       if (!argTy.isa<LLVM::LLVMPointerType>())
11112416e28cSStephan Herhut         return func.emitError(
11122416e28cSStephan Herhut             "llvm.align attribute attached to LLVM non-pointer argument");
11132416e28cSStephan Herhut       llvmArg.addAttrs(
11142416e28cSStephan Herhut           llvm::AttrBuilder().addAlignmentAttr(llvm::Align(attr.getInt())));
11152416e28cSStephan Herhut     }
11162416e28cSStephan Herhut 
11175d7231d8SStephan Herhut     valueMapping[mlirArg] = &llvmArg;
11185d7231d8SStephan Herhut     argIdx++;
11195d7231d8SStephan Herhut   }
11205d7231d8SStephan Herhut 
1121ff77397fSShraiysh Vaishay   // Check the personality and set it.
1122ff77397fSShraiysh Vaishay   if (func.personality().hasValue()) {
1123ff77397fSShraiysh Vaishay     llvm::Type *ty = llvm::Type::getInt8PtrTy(llvmFunc->getContext());
1124ff77397fSShraiysh Vaishay     if (llvm::Constant *pfunc =
1125ff77397fSShraiysh Vaishay             getLLVMConstant(ty, func.personalityAttr(), func.getLoc()))
1126ff77397fSShraiysh Vaishay       llvmFunc->setPersonalityFn(pfunc);
1127ff77397fSShraiysh Vaishay   }
1128ff77397fSShraiysh Vaishay 
11295d7231d8SStephan Herhut   // First, create all blocks so we can jump to them.
11305d7231d8SStephan Herhut   llvm::LLVMContext &llvmContext = llvmFunc->getContext();
11315d7231d8SStephan Herhut   for (auto &bb : func) {
11325d7231d8SStephan Herhut     auto *llvmBB = llvm::BasicBlock::Create(llvmContext);
11335d7231d8SStephan Herhut     llvmBB->insertInto(llvmFunc);
11345d7231d8SStephan Herhut     blockMapping[&bb] = llvmBB;
11355d7231d8SStephan Herhut   }
11365d7231d8SStephan Herhut 
11375d7231d8SStephan Herhut   // Then, convert blocks one by one in topological order to ensure defs are
11385d7231d8SStephan Herhut   // converted before uses.
11395d7231d8SStephan Herhut   auto blocks = topologicalSort(func);
11405d7231d8SStephan Herhut   for (auto indexedBB : llvm::enumerate(blocks)) {
11415d7231d8SStephan Herhut     auto *bb = indexedBB.value();
1142baa1ec22SAlex Zinenko     if (failed(convertBlock(*bb, /*ignoreArguments=*/indexedBB.index() == 0)))
1143baa1ec22SAlex Zinenko       return failure();
11445d7231d8SStephan Herhut   }
11455d7231d8SStephan Herhut 
11465d7231d8SStephan Herhut   // Finally, after all blocks have been traversed and values mapped, connect
11475d7231d8SStephan Herhut   // the PHI nodes to the results of preceding blocks.
1148db884dafSAlex Zinenko   connectPHINodes(func, valueMapping, blockMapping, branchMapping);
1149baa1ec22SAlex Zinenko   return success();
11505d7231d8SStephan Herhut }
11515d7231d8SStephan Herhut 
115244fc7d72STres Popp LogicalResult ModuleTranslation::checkSupportedModuleOps(Operation *m) {
115344fc7d72STres Popp   for (Operation &o : getModuleBody(m).getOperations())
1154ee394e68SRahul Joshi     if (!isa<LLVM::LLVMFuncOp, LLVM::GlobalOp>(&o) && !o.isKnownTerminator())
11554dde19f0SAlex Zinenko       return o.emitOpError("unsupported module-level operation");
11564dde19f0SAlex Zinenko   return success();
11574dde19f0SAlex Zinenko }
11584dde19f0SAlex Zinenko 
1159a084b94fSSean Silva LogicalResult ModuleTranslation::convertFunctionSignatures() {
11605d7231d8SStephan Herhut   // Declare all functions first because there may be function calls that form a
1161a084b94fSSean Silva   // call graph with cycles, or global initializers that reference functions.
116244fc7d72STres Popp   for (auto function : getModuleBody(mlirModule).getOps<LLVMFuncOp>()) {
11635e7959a3SAlex Zinenko     llvm::FunctionCallee llvmFuncCst = llvmModule->getOrInsertFunction(
11645e7959a3SAlex Zinenko         function.getName(),
1165aec38c61SAlex Zinenko         cast<llvm::FunctionType>(convertType(function.getType())));
11660a2131b7SAlex Zinenko     llvm::Function *llvmFunc = cast<llvm::Function>(llvmFuncCst.getCallee());
1167ebbdecddSAlex Zinenko     llvmFunc->setLinkage(convertLinkageToLLVM(function.linkage()));
11680a2131b7SAlex Zinenko     functionMapping[function.getName()] = llvmFunc;
11690a2131b7SAlex Zinenko 
11700a2131b7SAlex Zinenko     // Forward the pass-through attributes to LLVM.
11710a2131b7SAlex Zinenko     if (failed(forwardPassthroughAttributes(function.getLoc(),
11720a2131b7SAlex Zinenko                                             function.passthrough(), llvmFunc)))
11730a2131b7SAlex Zinenko       return failure();
11745d7231d8SStephan Herhut   }
11755d7231d8SStephan Herhut 
1176a084b94fSSean Silva   return success();
1177a084b94fSSean Silva }
1178a084b94fSSean Silva 
1179a084b94fSSean Silva LogicalResult ModuleTranslation::convertFunctions() {
11805d7231d8SStephan Herhut   // Convert functions.
118144fc7d72STres Popp   for (auto function : getModuleBody(mlirModule).getOps<LLVMFuncOp>()) {
11825d7231d8SStephan Herhut     // Ignore external functions.
11835d7231d8SStephan Herhut     if (function.isExternal())
11845d7231d8SStephan Herhut       continue;
11855d7231d8SStephan Herhut 
1186baa1ec22SAlex Zinenko     if (failed(convertOneFunction(function)))
1187baa1ec22SAlex Zinenko       return failure();
11885d7231d8SStephan Herhut   }
11895d7231d8SStephan Herhut 
1190baa1ec22SAlex Zinenko   return success();
11915d7231d8SStephan Herhut }
11925d7231d8SStephan Herhut 
1193aec38c61SAlex Zinenko llvm::Type *ModuleTranslation::convertType(LLVMType type) {
1194b2ab375dSAlex Zinenko   return typeTranslator.translateType(type);
1195aec38c61SAlex Zinenko }
1196aec38c61SAlex Zinenko 
1197efadb6b8SAlex Zinenko /// A helper to look up remapped operands in the value remapping table.`
1198efadb6b8SAlex Zinenko SmallVector<llvm::Value *, 8>
1199efadb6b8SAlex Zinenko ModuleTranslation::lookupValues(ValueRange values) {
1200efadb6b8SAlex Zinenko   SmallVector<llvm::Value *, 8> remapped;
1201efadb6b8SAlex Zinenko   remapped.reserve(values.size());
1202ff77397fSShraiysh Vaishay   for (Value v : values) {
1203ff77397fSShraiysh Vaishay     assert(valueMapping.count(v) && "referencing undefined value");
1204efadb6b8SAlex Zinenko     remapped.push_back(valueMapping.lookup(v));
1205ff77397fSShraiysh Vaishay   }
1206efadb6b8SAlex Zinenko   return remapped;
1207efadb6b8SAlex Zinenko }
1208efadb6b8SAlex Zinenko 
1209db1c197bSAlex Zinenko std::unique_ptr<llvm::Module> ModuleTranslation::prepareLLVMModule(
1210db1c197bSAlex Zinenko     Operation *m, llvm::LLVMContext &llvmContext, StringRef name) {
1211f9dc2b70SMehdi Amini   m->getContext()->getOrLoadDialect<LLVM::LLVMDialect>();
1212db1c197bSAlex Zinenko   auto llvmModule = std::make_unique<llvm::Module>(name, llvmContext);
1213168213f9SAlex Zinenko   if (auto dataLayoutAttr =
1214168213f9SAlex Zinenko           m->getAttr(LLVM::LLVMDialect::getDataLayoutAttrName()))
1215168213f9SAlex Zinenko     llvmModule->setDataLayout(dataLayoutAttr.cast<StringAttr>().getValue());
12165dd5a083SNicolas Vasilache   if (auto targetTripleAttr =
12175dd5a083SNicolas Vasilache           m->getAttr(LLVM::LLVMDialect::getTargetTripleAttrName()))
12185dd5a083SNicolas Vasilache     llvmModule->setTargetTriple(targetTripleAttr.cast<StringAttr>().getValue());
12195d7231d8SStephan Herhut 
12205d7231d8SStephan Herhut   // Inject declarations for `malloc` and `free` functions that can be used in
12215d7231d8SStephan Herhut   // memref allocation/deallocation coming from standard ops lowering.
1222db1c197bSAlex Zinenko   llvm::IRBuilder<> builder(llvmContext);
12235d7231d8SStephan Herhut   llvmModule->getOrInsertFunction("malloc", builder.getInt8PtrTy(),
12245d7231d8SStephan Herhut                                   builder.getInt64Ty());
12255d7231d8SStephan Herhut   llvmModule->getOrInsertFunction("free", builder.getVoidTy(),
12265d7231d8SStephan Herhut                                   builder.getInt8PtrTy());
12275d7231d8SStephan Herhut 
12285d7231d8SStephan Herhut   return llvmModule;
12295d7231d8SStephan Herhut }
1230