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