1 //===- ModuleTranslation.cpp - MLIR to LLVM conversion --------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the translation between an MLIR LLVM dialect module and
10 // the corresponding LLVMIR module. It only handles core LLVM IR operations.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "mlir/Target/LLVMIR/ModuleTranslation.h"
15 
16 #include "DebugTranslation.h"
17 #include "mlir/Dialect/LLVMIR/LLVMDialect.h"
18 #include "mlir/Dialect/OpenMP/OpenMPDialect.h"
19 #include "mlir/IR/Attributes.h"
20 #include "mlir/IR/Module.h"
21 #include "mlir/IR/StandardTypes.h"
22 #include "mlir/Support/LLVM.h"
23 #include "llvm/ADT/TypeSwitch.h"
24 
25 #include "llvm/ADT/SetVector.h"
26 #include "llvm/Frontend/OpenMP/OMPIRBuilder.h"
27 #include "llvm/IR/BasicBlock.h"
28 #include "llvm/IR/Constants.h"
29 #include "llvm/IR/DerivedTypes.h"
30 #include "llvm/IR/IRBuilder.h"
31 #include "llvm/IR/LLVMContext.h"
32 #include "llvm/IR/Module.h"
33 #include "llvm/Transforms/Utils/Cloning.h"
34 
35 using namespace mlir;
36 using namespace mlir::LLVM;
37 using namespace mlir::LLVM::detail;
38 
39 #include "mlir/Dialect/LLVMIR/LLVMConversionEnumsToLLVM.inc"
40 
41 /// Builds a constant of a sequential LLVM type `type`, potentially containing
42 /// other sequential types recursively, from the individual constant values
43 /// provided in `constants`. `shape` contains the number of elements in nested
44 /// sequential types. Reports errors at `loc` and returns nullptr on error.
45 static llvm::Constant *
46 buildSequentialConstant(ArrayRef<llvm::Constant *> &constants,
47                         ArrayRef<int64_t> shape, llvm::Type *type,
48                         Location loc) {
49   if (shape.empty()) {
50     llvm::Constant *result = constants.front();
51     constants = constants.drop_front();
52     return result;
53   }
54 
55   llvm::Type *elementType;
56   if (auto *arrayTy = dyn_cast<llvm::ArrayType>(type)) {
57     elementType = arrayTy->getElementType();
58   } else if (auto *vectorTy = dyn_cast<llvm::VectorType>(type)) {
59     elementType = vectorTy->getElementType();
60   } else {
61     emitError(loc) << "expected sequential LLVM types wrapping a scalar";
62     return nullptr;
63   }
64 
65   SmallVector<llvm::Constant *, 8> nested;
66   nested.reserve(shape.front());
67   for (int64_t i = 0; i < shape.front(); ++i) {
68     nested.push_back(buildSequentialConstant(constants, shape.drop_front(),
69                                              elementType, loc));
70     if (!nested.back())
71       return nullptr;
72   }
73 
74   if (shape.size() == 1 && type->isVectorTy())
75     return llvm::ConstantVector::get(nested);
76   return llvm::ConstantArray::get(
77       llvm::ArrayType::get(elementType, shape.front()), nested);
78 }
79 
80 /// Returns the first non-sequential type nested in sequential types.
81 static llvm::Type *getInnermostElementType(llvm::Type *type) {
82   do {
83     if (auto *arrayTy = dyn_cast<llvm::ArrayType>(type)) {
84       type = arrayTy->getElementType();
85     } else if (auto *vectorTy = dyn_cast<llvm::VectorType>(type)) {
86       type = vectorTy->getElementType();
87     } else {
88       return type;
89     }
90   } while (1);
91 }
92 
93 /// Create an LLVM IR constant of `llvmType` from the MLIR attribute `attr`.
94 /// This currently supports integer, floating point, splat and dense element
95 /// attributes and combinations thereof.  In case of error, report it to `loc`
96 /// and return nullptr.
97 llvm::Constant *ModuleTranslation::getLLVMConstant(llvm::Type *llvmType,
98                                                    Attribute attr,
99                                                    Location loc) {
100   if (!attr)
101     return llvm::UndefValue::get(llvmType);
102   if (llvmType->isStructTy()) {
103     emitError(loc, "struct types are not supported in constants");
104     return nullptr;
105   }
106   // For integer types, we allow a mismatch in sizes as the index type in
107   // MLIR might have a different size than the index type in the LLVM module.
108   if (auto intAttr = attr.dyn_cast<IntegerAttr>())
109     return llvm::ConstantInt::get(
110         llvmType,
111         intAttr.getValue().sextOrTrunc(llvmType->getIntegerBitWidth()));
112   if (auto boolAttr = attr.dyn_cast<BoolAttr>())
113     return llvm::ConstantInt::get(llvmType, boolAttr.getValue());
114   if (auto floatAttr = attr.dyn_cast<FloatAttr>())
115     return llvm::ConstantFP::get(llvmType, floatAttr.getValue());
116   if (auto funcAttr = attr.dyn_cast<FlatSymbolRefAttr>())
117     return llvm::ConstantExpr::getBitCast(
118         functionMapping.lookup(funcAttr.getValue()), llvmType);
119   if (auto splatAttr = attr.dyn_cast<SplatElementsAttr>()) {
120     llvm::Type *elementType;
121     uint64_t numElements;
122     if (auto *arrayTy = dyn_cast<llvm::ArrayType>(llvmType)) {
123       elementType = arrayTy->getElementType();
124       numElements = arrayTy->getNumElements();
125     } else {
126       auto *vectorTy = cast<llvm::VectorType>(llvmType);
127       elementType = vectorTy->getElementType();
128       numElements = vectorTy->getNumElements();
129     }
130     // Splat value is a scalar. Extract it only if the element type is not
131     // another sequence type. The recursion terminates because each step removes
132     // one outer sequential type.
133     bool elementTypeSequential =
134         isa<llvm::ArrayType>(elementType) || isa<llvm::VectorType>(elementType);
135     llvm::Constant *child = getLLVMConstant(
136         elementType,
137         elementTypeSequential ? splatAttr : splatAttr.getSplatValue(), loc);
138     if (!child)
139       return nullptr;
140     if (llvmType->isVectorTy())
141       return llvm::ConstantVector::getSplat(
142           llvm::ElementCount(numElements, /*Scalable=*/false), child);
143     if (llvmType->isArrayTy()) {
144       auto *arrayType = llvm::ArrayType::get(elementType, numElements);
145       SmallVector<llvm::Constant *, 8> constants(numElements, child);
146       return llvm::ConstantArray::get(arrayType, constants);
147     }
148   }
149 
150   if (auto elementsAttr = attr.dyn_cast<ElementsAttr>()) {
151     assert(elementsAttr.getType().hasStaticShape());
152     assert(elementsAttr.getNumElements() != 0 &&
153            "unexpected empty elements attribute");
154     assert(!elementsAttr.getType().getShape().empty() &&
155            "unexpected empty elements attribute shape");
156 
157     SmallVector<llvm::Constant *, 8> constants;
158     constants.reserve(elementsAttr.getNumElements());
159     llvm::Type *innermostType = getInnermostElementType(llvmType);
160     for (auto n : elementsAttr.getValues<Attribute>()) {
161       constants.push_back(getLLVMConstant(innermostType, n, loc));
162       if (!constants.back())
163         return nullptr;
164     }
165     ArrayRef<llvm::Constant *> constantsRef = constants;
166     llvm::Constant *result = buildSequentialConstant(
167         constantsRef, elementsAttr.getType().getShape(), llvmType, loc);
168     assert(constantsRef.empty() && "did not consume all elemental constants");
169     return result;
170   }
171 
172   if (auto stringAttr = attr.dyn_cast<StringAttr>()) {
173     return llvm::ConstantDataArray::get(
174         llvmModule->getContext(), ArrayRef<char>{stringAttr.getValue().data(),
175                                                  stringAttr.getValue().size()});
176   }
177   emitError(loc, "unsupported constant value");
178   return nullptr;
179 }
180 
181 /// Convert MLIR integer comparison predicate to LLVM IR comparison predicate.
182 static llvm::CmpInst::Predicate getLLVMCmpPredicate(ICmpPredicate p) {
183   switch (p) {
184   case LLVM::ICmpPredicate::eq:
185     return llvm::CmpInst::Predicate::ICMP_EQ;
186   case LLVM::ICmpPredicate::ne:
187     return llvm::CmpInst::Predicate::ICMP_NE;
188   case LLVM::ICmpPredicate::slt:
189     return llvm::CmpInst::Predicate::ICMP_SLT;
190   case LLVM::ICmpPredicate::sle:
191     return llvm::CmpInst::Predicate::ICMP_SLE;
192   case LLVM::ICmpPredicate::sgt:
193     return llvm::CmpInst::Predicate::ICMP_SGT;
194   case LLVM::ICmpPredicate::sge:
195     return llvm::CmpInst::Predicate::ICMP_SGE;
196   case LLVM::ICmpPredicate::ult:
197     return llvm::CmpInst::Predicate::ICMP_ULT;
198   case LLVM::ICmpPredicate::ule:
199     return llvm::CmpInst::Predicate::ICMP_ULE;
200   case LLVM::ICmpPredicate::ugt:
201     return llvm::CmpInst::Predicate::ICMP_UGT;
202   case LLVM::ICmpPredicate::uge:
203     return llvm::CmpInst::Predicate::ICMP_UGE;
204   }
205   llvm_unreachable("incorrect comparison predicate");
206 }
207 
208 static llvm::CmpInst::Predicate getLLVMCmpPredicate(FCmpPredicate p) {
209   switch (p) {
210   case LLVM::FCmpPredicate::_false:
211     return llvm::CmpInst::Predicate::FCMP_FALSE;
212   case LLVM::FCmpPredicate::oeq:
213     return llvm::CmpInst::Predicate::FCMP_OEQ;
214   case LLVM::FCmpPredicate::ogt:
215     return llvm::CmpInst::Predicate::FCMP_OGT;
216   case LLVM::FCmpPredicate::oge:
217     return llvm::CmpInst::Predicate::FCMP_OGE;
218   case LLVM::FCmpPredicate::olt:
219     return llvm::CmpInst::Predicate::FCMP_OLT;
220   case LLVM::FCmpPredicate::ole:
221     return llvm::CmpInst::Predicate::FCMP_OLE;
222   case LLVM::FCmpPredicate::one:
223     return llvm::CmpInst::Predicate::FCMP_ONE;
224   case LLVM::FCmpPredicate::ord:
225     return llvm::CmpInst::Predicate::FCMP_ORD;
226   case LLVM::FCmpPredicate::ueq:
227     return llvm::CmpInst::Predicate::FCMP_UEQ;
228   case LLVM::FCmpPredicate::ugt:
229     return llvm::CmpInst::Predicate::FCMP_UGT;
230   case LLVM::FCmpPredicate::uge:
231     return llvm::CmpInst::Predicate::FCMP_UGE;
232   case LLVM::FCmpPredicate::ult:
233     return llvm::CmpInst::Predicate::FCMP_ULT;
234   case LLVM::FCmpPredicate::ule:
235     return llvm::CmpInst::Predicate::FCMP_ULE;
236   case LLVM::FCmpPredicate::une:
237     return llvm::CmpInst::Predicate::FCMP_UNE;
238   case LLVM::FCmpPredicate::uno:
239     return llvm::CmpInst::Predicate::FCMP_UNO;
240   case LLVM::FCmpPredicate::_true:
241     return llvm::CmpInst::Predicate::FCMP_TRUE;
242   }
243   llvm_unreachable("incorrect comparison predicate");
244 }
245 
246 static llvm::AtomicRMWInst::BinOp getLLVMAtomicBinOp(AtomicBinOp op) {
247   switch (op) {
248   case LLVM::AtomicBinOp::xchg:
249     return llvm::AtomicRMWInst::BinOp::Xchg;
250   case LLVM::AtomicBinOp::add:
251     return llvm::AtomicRMWInst::BinOp::Add;
252   case LLVM::AtomicBinOp::sub:
253     return llvm::AtomicRMWInst::BinOp::Sub;
254   case LLVM::AtomicBinOp::_and:
255     return llvm::AtomicRMWInst::BinOp::And;
256   case LLVM::AtomicBinOp::nand:
257     return llvm::AtomicRMWInst::BinOp::Nand;
258   case LLVM::AtomicBinOp::_or:
259     return llvm::AtomicRMWInst::BinOp::Or;
260   case LLVM::AtomicBinOp::_xor:
261     return llvm::AtomicRMWInst::BinOp::Xor;
262   case LLVM::AtomicBinOp::max:
263     return llvm::AtomicRMWInst::BinOp::Max;
264   case LLVM::AtomicBinOp::min:
265     return llvm::AtomicRMWInst::BinOp::Min;
266   case LLVM::AtomicBinOp::umax:
267     return llvm::AtomicRMWInst::BinOp::UMax;
268   case LLVM::AtomicBinOp::umin:
269     return llvm::AtomicRMWInst::BinOp::UMin;
270   case LLVM::AtomicBinOp::fadd:
271     return llvm::AtomicRMWInst::BinOp::FAdd;
272   case LLVM::AtomicBinOp::fsub:
273     return llvm::AtomicRMWInst::BinOp::FSub;
274   }
275   llvm_unreachable("incorrect atomic binary operator");
276 }
277 
278 static llvm::AtomicOrdering getLLVMAtomicOrdering(AtomicOrdering ordering) {
279   switch (ordering) {
280   case LLVM::AtomicOrdering::not_atomic:
281     return llvm::AtomicOrdering::NotAtomic;
282   case LLVM::AtomicOrdering::unordered:
283     return llvm::AtomicOrdering::Unordered;
284   case LLVM::AtomicOrdering::monotonic:
285     return llvm::AtomicOrdering::Monotonic;
286   case LLVM::AtomicOrdering::acquire:
287     return llvm::AtomicOrdering::Acquire;
288   case LLVM::AtomicOrdering::release:
289     return llvm::AtomicOrdering::Release;
290   case LLVM::AtomicOrdering::acq_rel:
291     return llvm::AtomicOrdering::AcquireRelease;
292   case LLVM::AtomicOrdering::seq_cst:
293     return llvm::AtomicOrdering::SequentiallyConsistent;
294   }
295   llvm_unreachable("incorrect atomic ordering");
296 }
297 
298 ModuleTranslation::ModuleTranslation(Operation *module,
299                                      std::unique_ptr<llvm::Module> llvmModule)
300     : mlirModule(module), llvmModule(std::move(llvmModule)),
301       debugTranslation(
302           std::make_unique<DebugTranslation>(module, *this->llvmModule)),
303       ompDialect(
304           module->getContext()->getRegisteredDialect<omp::OpenMPDialect>()),
305       llvmDialect(module->getContext()->getRegisteredDialect<LLVMDialect>()) {
306   assert(satisfiesLLVMModule(mlirModule) &&
307          "mlirModule should honor LLVM's module semantics.");
308 }
309 ModuleTranslation::~ModuleTranslation() {}
310 
311 /// Given an OpenMP MLIR operation, create the corresponding LLVM IR
312 /// (including OpenMP runtime calls).
313 LogicalResult
314 ModuleTranslation::convertOmpOperation(Operation &opInst,
315                                        llvm::IRBuilder<> &builder) {
316   if (!ompBuilder) {
317     ompBuilder = std::make_unique<llvm::OpenMPIRBuilder>(*llvmModule);
318     ompBuilder->initialize();
319   }
320   return llvm::TypeSwitch<Operation *, LogicalResult>(&opInst)
321       .Case([&](omp::BarrierOp) {
322         ompBuilder->CreateBarrier(builder.saveIP(), llvm::omp::OMPD_barrier);
323         return success();
324       })
325       .Case([&](omp::TaskwaitOp) {
326         ompBuilder->CreateTaskwait(builder.saveIP());
327         return success();
328       })
329       .Case([&](omp::TaskyieldOp) {
330         ompBuilder->CreateTaskyield(builder.saveIP());
331         return success();
332       })
333       .Default([&](Operation *inst) {
334         return inst->emitError("unsupported OpenMP operation: ")
335                << inst->getName();
336       });
337 }
338 
339 /// Given a single MLIR operation, create the corresponding LLVM IR operation
340 /// using the `builder`.  LLVM IR Builder does not have a generic interface so
341 /// this has to be a long chain of `if`s calling different functions with a
342 /// different number of arguments.
343 LogicalResult ModuleTranslation::convertOperation(Operation &opInst,
344                                                   llvm::IRBuilder<> &builder) {
345   auto extractPosition = [](ArrayAttr attr) {
346     SmallVector<unsigned, 4> position;
347     position.reserve(attr.size());
348     for (Attribute v : attr)
349       position.push_back(v.cast<IntegerAttr>().getValue().getZExtValue());
350     return position;
351   };
352 
353 #include "mlir/Dialect/LLVMIR/LLVMConversions.inc"
354 
355   // Emit function calls.  If the "callee" attribute is present, this is a
356   // direct function call and we also need to look up the remapped function
357   // itself.  Otherwise, this is an indirect call and the callee is the first
358   // operand, look it up as a normal value.  Return the llvm::Value representing
359   // the function result, which may be of llvm::VoidTy type.
360   auto convertCall = [this, &builder](Operation &op) -> llvm::Value * {
361     auto operands = lookupValues(op.getOperands());
362     ArrayRef<llvm::Value *> operandsRef(operands);
363     if (auto attr = op.getAttrOfType<FlatSymbolRefAttr>("callee")) {
364       return builder.CreateCall(functionMapping.lookup(attr.getValue()),
365                                 operandsRef);
366     } else {
367       auto *calleePtrType =
368           cast<llvm::PointerType>(operandsRef.front()->getType());
369       auto *calleeType =
370           cast<llvm::FunctionType>(calleePtrType->getElementType());
371       return builder.CreateCall(calleeType, operandsRef.front(),
372                                 operandsRef.drop_front());
373     }
374   };
375 
376   // Emit calls.  If the called function has a result, remap the corresponding
377   // value.  Note that LLVM IR dialect CallOp has either 0 or 1 result.
378   if (isa<LLVM::CallOp>(opInst)) {
379     llvm::Value *result = convertCall(opInst);
380     if (opInst.getNumResults() != 0) {
381       valueMapping[opInst.getResult(0)] = result;
382       return success();
383     }
384     // Check that LLVM call returns void for 0-result functions.
385     return success(result->getType()->isVoidTy());
386   }
387 
388   if (auto invOp = dyn_cast<LLVM::InvokeOp>(opInst)) {
389     auto operands = lookupValues(opInst.getOperands());
390     ArrayRef<llvm::Value *> operandsRef(operands);
391     if (auto attr = opInst.getAttrOfType<FlatSymbolRefAttr>("callee")) {
392       builder.CreateInvoke(functionMapping.lookup(attr.getValue()),
393                            blockMapping[invOp.getSuccessor(0)],
394                            blockMapping[invOp.getSuccessor(1)], operandsRef);
395     } else {
396       auto *calleePtrType =
397           cast<llvm::PointerType>(operandsRef.front()->getType());
398       auto *calleeType =
399           cast<llvm::FunctionType>(calleePtrType->getElementType());
400       builder.CreateInvoke(
401           calleeType, operandsRef.front(), blockMapping[invOp.getSuccessor(0)],
402           blockMapping[invOp.getSuccessor(1)], operandsRef.drop_front());
403     }
404     return success();
405   }
406 
407   if (auto lpOp = dyn_cast<LLVM::LandingpadOp>(opInst)) {
408     llvm::Type *ty = lpOp.getType().dyn_cast<LLVMType>().getUnderlyingType();
409     llvm::LandingPadInst *lpi =
410         builder.CreateLandingPad(ty, lpOp.getNumOperands());
411 
412     // Add clauses
413     for (auto operand : lookupValues(lpOp.getOperands())) {
414       // All operands should be constant - checked by verifier
415       if (auto constOperand = dyn_cast<llvm::Constant>(operand))
416         lpi->addClause(constOperand);
417     }
418     valueMapping[lpOp.getResult()] = lpi;
419     return success();
420   }
421 
422   // Emit branches.  We need to look up the remapped blocks and ignore the block
423   // arguments that were transformed into PHI nodes.
424   if (auto brOp = dyn_cast<LLVM::BrOp>(opInst)) {
425     builder.CreateBr(blockMapping[brOp.getSuccessor()]);
426     return success();
427   }
428   if (auto condbrOp = dyn_cast<LLVM::CondBrOp>(opInst)) {
429     builder.CreateCondBr(valueMapping.lookup(condbrOp.getOperand(0)),
430                          blockMapping[condbrOp.getSuccessor(0)],
431                          blockMapping[condbrOp.getSuccessor(1)]);
432     return success();
433   }
434 
435   // Emit addressof.  We need to look up the global value referenced by the
436   // operation and store it in the MLIR-to-LLVM value mapping.  This does not
437   // emit any LLVM instruction.
438   if (auto addressOfOp = dyn_cast<LLVM::AddressOfOp>(opInst)) {
439     LLVM::GlobalOp global = addressOfOp.getGlobal();
440     // The verifier should not have allowed this.
441     assert(global && "referencing an undefined global");
442 
443     valueMapping[addressOfOp.getResult()] = globalsMapping.lookup(global);
444     return success();
445   }
446 
447   if (opInst.getDialect() == ompDialect) {
448     return convertOmpOperation(opInst, builder);
449   }
450 
451   return opInst.emitError("unsupported or non-LLVM operation: ")
452          << opInst.getName();
453 }
454 
455 /// Convert block to LLVM IR.  Unless `ignoreArguments` is set, emit PHI nodes
456 /// to define values corresponding to the MLIR block arguments.  These nodes
457 /// are not connected to the source basic blocks, which may not exist yet.
458 LogicalResult ModuleTranslation::convertBlock(Block &bb, bool ignoreArguments) {
459   llvm::IRBuilder<> builder(blockMapping[&bb]);
460   auto *subprogram = builder.GetInsertBlock()->getParent()->getSubprogram();
461 
462   // Before traversing operations, make block arguments available through
463   // value remapping and PHI nodes, but do not add incoming edges for the PHI
464   // nodes just yet: those values may be defined by this or following blocks.
465   // This step is omitted if "ignoreArguments" is set.  The arguments of the
466   // first block have been already made available through the remapping of
467   // LLVM function arguments.
468   if (!ignoreArguments) {
469     auto predecessors = bb.getPredecessors();
470     unsigned numPredecessors =
471         std::distance(predecessors.begin(), predecessors.end());
472     for (auto arg : bb.getArguments()) {
473       auto wrappedType = arg.getType().dyn_cast<LLVM::LLVMType>();
474       if (!wrappedType)
475         return emitError(bb.front().getLoc(),
476                          "block argument does not have an LLVM type");
477       llvm::Type *type = wrappedType.getUnderlyingType();
478       llvm::PHINode *phi = builder.CreatePHI(type, numPredecessors);
479       valueMapping[arg] = phi;
480     }
481   }
482 
483   // Traverse operations.
484   for (auto &op : bb) {
485     // Set the current debug location within the builder.
486     builder.SetCurrentDebugLocation(
487         debugTranslation->translateLoc(op.getLoc(), subprogram));
488 
489     if (failed(convertOperation(op, builder)))
490       return failure();
491   }
492 
493   return success();
494 }
495 
496 /// Create named global variables that correspond to llvm.mlir.global
497 /// definitions.
498 LogicalResult ModuleTranslation::convertGlobals() {
499   // Lock access to the llvm context.
500   llvm::sys::SmartScopedLock<true> scopedLock(
501       llvmDialect->getLLVMContextMutex());
502   for (auto op : getModuleBody(mlirModule).getOps<LLVM::GlobalOp>()) {
503     llvm::Type *type = op.getType().getUnderlyingType();
504     llvm::Constant *cst = llvm::UndefValue::get(type);
505     if (op.getValueOrNull()) {
506       // String attributes are treated separately because they cannot appear as
507       // in-function constants and are thus not supported by getLLVMConstant.
508       if (auto strAttr = op.getValueOrNull().dyn_cast_or_null<StringAttr>()) {
509         cst = llvm::ConstantDataArray::getString(
510             llvmModule->getContext(), strAttr.getValue(), /*AddNull=*/false);
511         type = cst->getType();
512       } else if (!(cst = getLLVMConstant(type, op.getValueOrNull(),
513                                          op.getLoc()))) {
514         return failure();
515       }
516     } else if (Block *initializer = op.getInitializerBlock()) {
517       llvm::IRBuilder<> builder(llvmModule->getContext());
518       for (auto &op : initializer->without_terminator()) {
519         if (failed(convertOperation(op, builder)) ||
520             !isa<llvm::Constant>(valueMapping.lookup(op.getResult(0))))
521           return emitError(op.getLoc(), "unemittable constant value");
522       }
523       ReturnOp ret = cast<ReturnOp>(initializer->getTerminator());
524       cst = cast<llvm::Constant>(valueMapping.lookup(ret.getOperand(0)));
525     }
526 
527     auto linkage = convertLinkageToLLVM(op.linkage());
528     bool anyExternalLinkage =
529         ((linkage == llvm::GlobalVariable::ExternalLinkage &&
530           isa<llvm::UndefValue>(cst)) ||
531          linkage == llvm::GlobalVariable::ExternalWeakLinkage);
532     auto addrSpace = op.addr_space().getLimitedValue();
533     auto *var = new llvm::GlobalVariable(
534         *llvmModule, type, op.constant(), linkage,
535         anyExternalLinkage ? nullptr : cst, op.sym_name(),
536         /*InsertBefore=*/nullptr, llvm::GlobalValue::NotThreadLocal, addrSpace);
537 
538     globalsMapping.try_emplace(op, var);
539   }
540 
541   return success();
542 }
543 
544 /// Get the SSA value passed to the current block from the terminator operation
545 /// of its predecessor.
546 static Value getPHISourceValue(Block *current, Block *pred,
547                                unsigned numArguments, unsigned index) {
548   auto &terminator = *pred->getTerminator();
549   if (isa<LLVM::BrOp>(terminator)) {
550     return terminator.getOperand(index);
551   }
552 
553   // For conditional branches, we need to check if the current block is reached
554   // through the "true" or the "false" branch and take the relevant operands.
555   auto condBranchOp = dyn_cast<LLVM::CondBrOp>(terminator);
556   assert(condBranchOp &&
557          "only branch operations can be terminators of a block that "
558          "has successors");
559   assert((condBranchOp.getSuccessor(0) != condBranchOp.getSuccessor(1)) &&
560          "successors with arguments in LLVM conditional branches must be "
561          "different blocks");
562 
563   return condBranchOp.getSuccessor(0) == current
564              ? condBranchOp.trueDestOperands()[index]
565              : condBranchOp.falseDestOperands()[index];
566 }
567 
568 void ModuleTranslation::connectPHINodes(LLVMFuncOp func) {
569   // Skip the first block, it cannot be branched to and its arguments correspond
570   // to the arguments of the LLVM function.
571   for (auto it = std::next(func.begin()), eit = func.end(); it != eit; ++it) {
572     Block *bb = &*it;
573     llvm::BasicBlock *llvmBB = blockMapping.lookup(bb);
574     auto phis = llvmBB->phis();
575     auto numArguments = bb->getNumArguments();
576     assert(numArguments == std::distance(phis.begin(), phis.end()));
577     for (auto &numberedPhiNode : llvm::enumerate(phis)) {
578       auto &phiNode = numberedPhiNode.value();
579       unsigned index = numberedPhiNode.index();
580       for (auto *pred : bb->getPredecessors()) {
581         phiNode.addIncoming(valueMapping.lookup(getPHISourceValue(
582                                 bb, pred, numArguments, index)),
583                             blockMapping.lookup(pred));
584       }
585     }
586   }
587 }
588 
589 // TODO(mlir-team): implement an iterative version
590 static void topologicalSortImpl(llvm::SetVector<Block *> &blocks, Block *b) {
591   blocks.insert(b);
592   for (Block *bb : b->getSuccessors()) {
593     if (blocks.count(bb) == 0)
594       topologicalSortImpl(blocks, bb);
595   }
596 }
597 
598 /// Sort function blocks topologically.
599 static llvm::SetVector<Block *> topologicalSort(LLVMFuncOp f) {
600   // For each blocks that has not been visited yet (i.e. that has no
601   // predecessors), add it to the list and traverse its successors in DFS
602   // preorder.
603   llvm::SetVector<Block *> blocks;
604   for (Block &b : f.getBlocks()) {
605     if (blocks.count(&b) == 0)
606       topologicalSortImpl(blocks, &b);
607   }
608   assert(blocks.size() == f.getBlocks().size() && "some blocks are not sorted");
609 
610   return blocks;
611 }
612 
613 /// Attempts to add an attribute identified by `key`, optionally with the given
614 /// `value` to LLVM function `llvmFunc`. Reports errors at `loc` if any. If the
615 /// attribute has a kind known to LLVM IR, create the attribute of this kind,
616 /// otherwise keep it as a string attribute. Performs additional checks for
617 /// attributes known to have or not have a value in order to avoid assertions
618 /// inside LLVM upon construction.
619 static LogicalResult checkedAddLLVMFnAttribute(Location loc,
620                                                llvm::Function *llvmFunc,
621                                                StringRef key,
622                                                StringRef value = StringRef()) {
623   auto kind = llvm::Attribute::getAttrKindFromName(key);
624   if (kind == llvm::Attribute::None) {
625     llvmFunc->addFnAttr(key, value);
626     return success();
627   }
628 
629   if (llvm::Attribute::doesAttrKindHaveArgument(kind)) {
630     if (value.empty())
631       return emitError(loc) << "LLVM attribute '" << key << "' expects a value";
632 
633     int result;
634     if (!value.getAsInteger(/*Radix=*/0, result))
635       llvmFunc->addFnAttr(
636           llvm::Attribute::get(llvmFunc->getContext(), kind, result));
637     else
638       llvmFunc->addFnAttr(key, value);
639     return success();
640   }
641 
642   if (!value.empty())
643     return emitError(loc) << "LLVM attribute '" << key
644                           << "' does not expect a value, found '" << value
645                           << "'";
646 
647   llvmFunc->addFnAttr(kind);
648   return success();
649 }
650 
651 /// Attaches the attributes listed in the given array attribute to `llvmFunc`.
652 /// Reports error to `loc` if any and returns immediately. Expects `attributes`
653 /// to be an array attribute containing either string attributes, treated as
654 /// value-less LLVM attributes, or array attributes containing two string
655 /// attributes, with the first string being the name of the corresponding LLVM
656 /// attribute and the second string beings its value. Note that even integer
657 /// attributes are expected to have their values expressed as strings.
658 static LogicalResult
659 forwardPassthroughAttributes(Location loc, Optional<ArrayAttr> attributes,
660                              llvm::Function *llvmFunc) {
661   if (!attributes)
662     return success();
663 
664   for (Attribute attr : *attributes) {
665     if (auto stringAttr = attr.dyn_cast<StringAttr>()) {
666       if (failed(
667               checkedAddLLVMFnAttribute(loc, llvmFunc, stringAttr.getValue())))
668         return failure();
669       continue;
670     }
671 
672     auto arrayAttr = attr.dyn_cast<ArrayAttr>();
673     if (!arrayAttr || arrayAttr.size() != 2)
674       return emitError(loc)
675              << "expected 'passthrough' to contain string or array attributes";
676 
677     auto keyAttr = arrayAttr[0].dyn_cast<StringAttr>();
678     auto valueAttr = arrayAttr[1].dyn_cast<StringAttr>();
679     if (!keyAttr || !valueAttr)
680       return emitError(loc)
681              << "expected arrays within 'passthrough' to contain two strings";
682 
683     if (failed(checkedAddLLVMFnAttribute(loc, llvmFunc, keyAttr.getValue(),
684                                          valueAttr.getValue())))
685       return failure();
686   }
687   return success();
688 }
689 
690 LogicalResult ModuleTranslation::convertOneFunction(LLVMFuncOp func) {
691   // Clear the block and value mappings, they are only relevant within one
692   // function.
693   blockMapping.clear();
694   valueMapping.clear();
695   llvm::Function *llvmFunc = functionMapping.lookup(func.getName());
696 
697   // Translate the debug information for this function.
698   debugTranslation->translate(func, *llvmFunc);
699 
700   // Add function arguments to the value remapping table.
701   // If there was noalias info then we decorate each argument accordingly.
702   unsigned int argIdx = 0;
703   for (auto kvp : llvm::zip(func.getArguments(), llvmFunc->args())) {
704     llvm::Argument &llvmArg = std::get<1>(kvp);
705     BlockArgument mlirArg = std::get<0>(kvp);
706 
707     if (auto attr = func.getArgAttrOfType<BoolAttr>(argIdx, "llvm.noalias")) {
708       // NB: Attribute already verified to be boolean, so check if we can indeed
709       // attach the attribute to this argument, based on its type.
710       auto argTy = mlirArg.getType().dyn_cast<LLVM::LLVMType>();
711       if (!argTy.getUnderlyingType()->isPointerTy())
712         return func.emitError(
713             "llvm.noalias attribute attached to LLVM non-pointer argument");
714       if (attr.getValue())
715         llvmArg.addAttr(llvm::Attribute::AttrKind::NoAlias);
716     }
717     valueMapping[mlirArg] = &llvmArg;
718     argIdx++;
719   }
720 
721   // Check the personality and set it.
722   if (func.personality().hasValue()) {
723     llvm::Type *ty = llvm::Type::getInt8PtrTy(llvmFunc->getContext());
724     if (llvm::Constant *pfunc =
725             getLLVMConstant(ty, func.personalityAttr(), func.getLoc()))
726       llvmFunc->setPersonalityFn(pfunc);
727   }
728 
729   // First, create all blocks so we can jump to them.
730   llvm::LLVMContext &llvmContext = llvmFunc->getContext();
731   for (auto &bb : func) {
732     auto *llvmBB = llvm::BasicBlock::Create(llvmContext);
733     llvmBB->insertInto(llvmFunc);
734     blockMapping[&bb] = llvmBB;
735   }
736 
737   // Then, convert blocks one by one in topological order to ensure defs are
738   // converted before uses.
739   auto blocks = topologicalSort(func);
740   for (auto indexedBB : llvm::enumerate(blocks)) {
741     auto *bb = indexedBB.value();
742     if (failed(convertBlock(*bb, /*ignoreArguments=*/indexedBB.index() == 0)))
743       return failure();
744   }
745 
746   // Finally, after all blocks have been traversed and values mapped, connect
747   // the PHI nodes to the results of preceding blocks.
748   connectPHINodes(func);
749   return success();
750 }
751 
752 LogicalResult ModuleTranslation::checkSupportedModuleOps(Operation *m) {
753   for (Operation &o : getModuleBody(m).getOperations())
754     if (!isa<LLVM::LLVMFuncOp>(&o) && !isa<LLVM::GlobalOp>(&o) &&
755         !o.isKnownTerminator())
756       return o.emitOpError("unsupported module-level operation");
757   return success();
758 }
759 
760 LogicalResult ModuleTranslation::convertFunctions() {
761   // Lock access to the llvm context.
762   llvm::sys::SmartScopedLock<true> scopedLock(
763       llvmDialect->getLLVMContextMutex());
764   // Declare all functions first because there may be function calls that form a
765   // call graph with cycles.
766   for (auto function : getModuleBody(mlirModule).getOps<LLVMFuncOp>()) {
767     llvm::FunctionCallee llvmFuncCst = llvmModule->getOrInsertFunction(
768         function.getName(),
769         cast<llvm::FunctionType>(function.getType().getUnderlyingType()));
770     llvm::Function *llvmFunc = cast<llvm::Function>(llvmFuncCst.getCallee());
771     functionMapping[function.getName()] = llvmFunc;
772 
773     // Forward the pass-through attributes to LLVM.
774     if (failed(forwardPassthroughAttributes(function.getLoc(),
775                                             function.passthrough(), llvmFunc)))
776       return failure();
777   }
778 
779   // Convert functions.
780   for (auto function : getModuleBody(mlirModule).getOps<LLVMFuncOp>()) {
781     // Ignore external functions.
782     if (function.isExternal())
783       continue;
784 
785     if (failed(convertOneFunction(function)))
786       return failure();
787   }
788 
789   return success();
790 }
791 
792 /// A helper to look up remapped operands in the value remapping table.`
793 SmallVector<llvm::Value *, 8>
794 ModuleTranslation::lookupValues(ValueRange values) {
795   SmallVector<llvm::Value *, 8> remapped;
796   remapped.reserve(values.size());
797   for (Value v : values) {
798     assert(valueMapping.count(v) && "referencing undefined value");
799     remapped.push_back(valueMapping.lookup(v));
800   }
801   return remapped;
802 }
803 
804 std::unique_ptr<llvm::Module>
805 ModuleTranslation::prepareLLVMModule(Operation *m) {
806   auto *dialect = m->getContext()->getRegisteredDialect<LLVM::LLVMDialect>();
807   assert(dialect && "LLVM dialect must be registered");
808   // Lock the LLVM context as we might create new types here.
809   llvm::sys::SmartScopedLock<true> scopedLock(dialect->getLLVMContextMutex());
810 
811   auto llvmModule = llvm::CloneModule(dialect->getLLVMModule());
812   if (!llvmModule)
813     return nullptr;
814 
815   llvm::LLVMContext &llvmContext = llvmModule->getContext();
816   llvm::IRBuilder<> builder(llvmContext);
817 
818   // Inject declarations for `malloc` and `free` functions that can be used in
819   // memref allocation/deallocation coming from standard ops lowering.
820   llvmModule->getOrInsertFunction("malloc", builder.getInt8PtrTy(),
821                                   builder.getInt64Ty());
822   llvmModule->getOrInsertFunction("free", builder.getVoidTy(),
823                                   builder.getInt8PtrTy());
824 
825   return llvmModule;
826 }
827