github.com/johnnyeven/libtools@v0.0.0-20191126065708-61829c1adf46/third_party/mlir/lib/Target/LLVMIR/ModuleTranslation.cpp (about)

     1  //===- ModuleTranslation.cpp - MLIR to LLVM conversion --------------------===//
     2  //
     3  // Copyright 2019 The MLIR Authors.
     4  //
     5  // Licensed under the Apache License, Version 2.0 (the "License");
     6  // you may not use this file except in compliance with the License.
     7  // You may obtain a copy of the License at
     8  //
     9  //   http://www.apache.org/licenses/LICENSE-2.0
    10  //
    11  // Unless required by applicable law or agreed to in writing, software
    12  // distributed under the License is distributed on an "AS IS" BASIS,
    13  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    14  // See the License for the specific language governing permissions and
    15  // limitations under the License.
    16  // =============================================================================
    17  //
    18  // This file implements the translation between an MLIR LLVM dialect module and
    19  // the corresponding LLVMIR module. It only handles core LLVM IR operations.
    20  //
    21  //===----------------------------------------------------------------------===//
    22  
    23  #include "mlir/Target/LLVMIR/ModuleTranslation.h"
    24  
    25  #include "mlir/Dialect/LLVMIR/LLVMDialect.h"
    26  #include "mlir/IR/Attributes.h"
    27  #include "mlir/IR/Module.h"
    28  #include "mlir/Support/LLVM.h"
    29  
    30  #include "llvm/ADT/SetVector.h"
    31  #include "llvm/IR/BasicBlock.h"
    32  #include "llvm/IR/Constants.h"
    33  #include "llvm/IR/DerivedTypes.h"
    34  #include "llvm/IR/IRBuilder.h"
    35  #include "llvm/IR/LLVMContext.h"
    36  #include "llvm/IR/Module.h"
    37  #include "llvm/Transforms/Utils/Cloning.h"
    38  
    39  namespace mlir {
    40  namespace LLVM {
    41  
    42  // Convert an MLIR function type to LLVM IR.  Arguments of the function must of
    43  // MLIR LLVM IR dialect types.  Use `loc` as a location when reporting errors.
    44  // Return nullptr on errors.
    45  static llvm::FunctionType *convertFunctionType(llvm::LLVMContext &llvmContext,
    46                                                 FunctionType type, Location loc,
    47                                                 bool isVarArgs) {
    48    assert(type && "expected non-null type");
    49    if (type.getNumResults() > 1)
    50      return emitError(loc, "LLVM functions can only have 0 or 1 result"),
    51             nullptr;
    52  
    53    SmallVector<llvm::Type *, 8> argTypes;
    54    argTypes.reserve(type.getNumInputs());
    55    for (auto t : type.getInputs()) {
    56      auto wrappedLLVMType = t.dyn_cast<LLVM::LLVMType>();
    57      if (!wrappedLLVMType)
    58        return emitError(loc, "non-LLVM function argument type"), nullptr;
    59      argTypes.push_back(wrappedLLVMType.getUnderlyingType());
    60    }
    61  
    62    if (type.getNumResults() == 0)
    63      return llvm::FunctionType::get(llvm::Type::getVoidTy(llvmContext), argTypes,
    64                                     isVarArgs);
    65  
    66    auto wrappedResultType = type.getResult(0).dyn_cast<LLVM::LLVMType>();
    67    if (!wrappedResultType)
    68      return emitError(loc, "non-LLVM function result"), nullptr;
    69  
    70    return llvm::FunctionType::get(wrappedResultType.getUnderlyingType(),
    71                                   argTypes, isVarArgs);
    72  }
    73  
    74  // Create an LLVM IR constant of `llvmType` from the MLIR attribute `attr`.
    75  // This currently supports integer, floating point, splat and dense element
    76  // attributes and combinations thereof.  In case of error, report it to `loc`
    77  // and return nullptr.
    78  llvm::Constant *ModuleTranslation::getLLVMConstant(llvm::Type *llvmType,
    79                                                     Attribute attr,
    80                                                     Location loc) {
    81    if (auto intAttr = attr.dyn_cast<IntegerAttr>())
    82      return llvm::ConstantInt::get(llvmType, intAttr.getValue());
    83    if (auto floatAttr = attr.dyn_cast<FloatAttr>())
    84      return llvm::ConstantFP::get(llvmType, floatAttr.getValue());
    85    if (auto funcAttr = attr.dyn_cast<SymbolRefAttr>())
    86      return functionMapping.lookup(funcAttr.getValue());
    87    if (auto splatAttr = attr.dyn_cast<SplatElementsAttr>()) {
    88      auto *vectorType = cast<llvm::VectorType>(llvmType);
    89      auto *child = getLLVMConstant(vectorType->getElementType(),
    90                                    splatAttr.getSplatValue(), loc);
    91      return llvm::ConstantVector::getSplat(vectorType->getNumElements(), child);
    92    }
    93    if (auto elementsAttr = attr.dyn_cast<ElementsAttr>()) {
    94      auto *vectorType = cast<llvm::VectorType>(llvmType);
    95      SmallVector<llvm::Constant *, 8> constants;
    96      uint64_t numElements = vectorType->getNumElements();
    97      constants.reserve(numElements);
    98      for (auto n : elementsAttr.getValues<Attribute>()) {
    99        constants.push_back(
   100            getLLVMConstant(vectorType->getElementType(), n, loc));
   101        if (!constants.back())
   102          return nullptr;
   103      }
   104      return llvm::ConstantVector::get(constants);
   105    }
   106    if (auto stringAttr = attr.dyn_cast<StringAttr>()) {
   107      return llvm::ConstantDataArray::get(
   108          llvmModule->getContext(), ArrayRef<char>{stringAttr.getValue().data(),
   109                                                   stringAttr.getValue().size()});
   110    }
   111    emitError(loc, "unsupported constant value");
   112    return nullptr;
   113  }
   114  
   115  // Convert MLIR integer comparison predicate to LLVM IR comparison predicate.
   116  static llvm::CmpInst::Predicate getLLVMCmpPredicate(ICmpPredicate p) {
   117    switch (p) {
   118    case LLVM::ICmpPredicate::eq:
   119      return llvm::CmpInst::Predicate::ICMP_EQ;
   120    case LLVM::ICmpPredicate::ne:
   121      return llvm::CmpInst::Predicate::ICMP_NE;
   122    case LLVM::ICmpPredicate::slt:
   123      return llvm::CmpInst::Predicate::ICMP_SLT;
   124    case LLVM::ICmpPredicate::sle:
   125      return llvm::CmpInst::Predicate::ICMP_SLE;
   126    case LLVM::ICmpPredicate::sgt:
   127      return llvm::CmpInst::Predicate::ICMP_SGT;
   128    case LLVM::ICmpPredicate::sge:
   129      return llvm::CmpInst::Predicate::ICMP_SGE;
   130    case LLVM::ICmpPredicate::ult:
   131      return llvm::CmpInst::Predicate::ICMP_ULT;
   132    case LLVM::ICmpPredicate::ule:
   133      return llvm::CmpInst::Predicate::ICMP_ULE;
   134    case LLVM::ICmpPredicate::ugt:
   135      return llvm::CmpInst::Predicate::ICMP_UGT;
   136    case LLVM::ICmpPredicate::uge:
   137      return llvm::CmpInst::Predicate::ICMP_UGE;
   138    }
   139    llvm_unreachable("incorrect comparison predicate");
   140  }
   141  
   142  static llvm::CmpInst::Predicate getLLVMCmpPredicate(FCmpPredicate p) {
   143    switch (p) {
   144    case LLVM::FCmpPredicate::_false:
   145      return llvm::CmpInst::Predicate::FCMP_FALSE;
   146    case LLVM::FCmpPredicate::oeq:
   147      return llvm::CmpInst::Predicate::FCMP_OEQ;
   148    case LLVM::FCmpPredicate::ogt:
   149      return llvm::CmpInst::Predicate::FCMP_OGT;
   150    case LLVM::FCmpPredicate::oge:
   151      return llvm::CmpInst::Predicate::FCMP_OGE;
   152    case LLVM::FCmpPredicate::olt:
   153      return llvm::CmpInst::Predicate::FCMP_OLT;
   154    case LLVM::FCmpPredicate::ole:
   155      return llvm::CmpInst::Predicate::FCMP_OLE;
   156    case LLVM::FCmpPredicate::one:
   157      return llvm::CmpInst::Predicate::FCMP_ONE;
   158    case LLVM::FCmpPredicate::ord:
   159      return llvm::CmpInst::Predicate::FCMP_ORD;
   160    case LLVM::FCmpPredicate::ueq:
   161      return llvm::CmpInst::Predicate::FCMP_UEQ;
   162    case LLVM::FCmpPredicate::ugt:
   163      return llvm::CmpInst::Predicate::FCMP_UGT;
   164    case LLVM::FCmpPredicate::uge:
   165      return llvm::CmpInst::Predicate::FCMP_UGE;
   166    case LLVM::FCmpPredicate::ult:
   167      return llvm::CmpInst::Predicate::FCMP_ULT;
   168    case LLVM::FCmpPredicate::ule:
   169      return llvm::CmpInst::Predicate::FCMP_ULE;
   170    case LLVM::FCmpPredicate::une:
   171      return llvm::CmpInst::Predicate::FCMP_UNE;
   172    case LLVM::FCmpPredicate::uno:
   173      return llvm::CmpInst::Predicate::FCMP_UNO;
   174    case LLVM::FCmpPredicate::_true:
   175      return llvm::CmpInst::Predicate::FCMP_TRUE;
   176    }
   177    llvm_unreachable("incorrect comparison predicate");
   178  }
   179  
   180  // A helper to look up remapped operands in the value remapping table.
   181  template <typename Range>
   182  SmallVector<llvm::Value *, 8> ModuleTranslation::lookupValues(Range &&values) {
   183    SmallVector<llvm::Value *, 8> remapped;
   184    remapped.reserve(llvm::size(values));
   185    for (Value *v : values) {
   186      remapped.push_back(valueMapping.lookup(v));
   187    }
   188    return remapped;
   189  }
   190  
   191  // Given a single MLIR operation, create the corresponding LLVM IR operation
   192  // using the `builder`.  LLVM IR Builder does not have a generic interface so
   193  // this has to be a long chain of `if`s calling different functions with a
   194  // different number of arguments.
   195  LogicalResult ModuleTranslation::convertOperation(Operation &opInst,
   196                                                    llvm::IRBuilder<> &builder) {
   197    auto extractPosition = [](ArrayAttr attr) {
   198      SmallVector<unsigned, 4> position;
   199      position.reserve(attr.size());
   200      for (Attribute v : attr)
   201        position.push_back(v.cast<IntegerAttr>().getValue().getZExtValue());
   202      return position;
   203    };
   204  
   205  #include "mlir/Dialect/LLVMIR/LLVMConversions.inc"
   206  
   207    // Emit function calls.  If the "callee" attribute is present, this is a
   208    // direct function call and we also need to look up the remapped function
   209    // itself.  Otherwise, this is an indirect call and the callee is the first
   210    // operand, look it up as a normal value.  Return the llvm::Value representing
   211    // the function result, which may be of llvm::VoidTy type.
   212    auto convertCall = [this, &builder](Operation &op) -> llvm::Value * {
   213      auto operands = lookupValues(op.getOperands());
   214      ArrayRef<llvm::Value *> operandsRef(operands);
   215      if (auto attr = op.getAttrOfType<SymbolRefAttr>("callee")) {
   216        return builder.CreateCall(functionMapping.lookup(attr.getValue()),
   217                                  operandsRef);
   218      } else {
   219        return builder.CreateCall(operandsRef.front(), operandsRef.drop_front());
   220      }
   221    };
   222  
   223    // Emit calls.  If the called function has a result, remap the corresponding
   224    // value.  Note that LLVM IR dialect CallOp has either 0 or 1 result.
   225    if (isa<LLVM::CallOp>(opInst)) {
   226      llvm::Value *result = convertCall(opInst);
   227      if (opInst.getNumResults() != 0) {
   228        valueMapping[opInst.getResult(0)] = result;
   229        return success();
   230      }
   231      // Check that LLVM call returns void for 0-result functions.
   232      return success(result->getType()->isVoidTy());
   233    }
   234  
   235    // Emit branches.  We need to look up the remapped blocks and ignore the block
   236    // arguments that were transformed into PHI nodes.
   237    if (auto brOp = dyn_cast<LLVM::BrOp>(opInst)) {
   238      builder.CreateBr(blockMapping[brOp.getSuccessor(0)]);
   239      return success();
   240    }
   241    if (auto condbrOp = dyn_cast<LLVM::CondBrOp>(opInst)) {
   242      builder.CreateCondBr(valueMapping.lookup(condbrOp.getOperand(0)),
   243                           blockMapping[condbrOp.getSuccessor(0)],
   244                           blockMapping[condbrOp.getSuccessor(1)]);
   245      return success();
   246    }
   247  
   248    // Emit addressof.  We need to look up the global value referenced by the
   249    // operation and store it in the MLIR-to-LLVM value mapping.  This does not
   250    // emit any LLVM instruction.
   251    if (auto addressOfOp = dyn_cast<LLVM::AddressOfOp>(opInst)) {
   252      LLVM::GlobalOp global = addressOfOp.getGlobal();
   253      // The verifier should not have allowed this.
   254      assert(global && "referencing an undefined global");
   255  
   256      valueMapping[addressOfOp.getResult()] = globalsMapping.lookup(global);
   257      return success();
   258    }
   259  
   260    return opInst.emitError("unsupported or non-LLVM operation: ")
   261           << opInst.getName();
   262  }
   263  
   264  // Convert block to LLVM IR.  Unless `ignoreArguments` is set, emit PHI nodes
   265  // to define values corresponding to the MLIR block arguments.  These nodes
   266  // are not connected to the source basic blocks, which may not exist yet.
   267  LogicalResult ModuleTranslation::convertBlock(Block &bb, bool ignoreArguments) {
   268    llvm::IRBuilder<> builder(blockMapping[&bb]);
   269  
   270    // Before traversing operations, make block arguments available through
   271    // value remapping and PHI nodes, but do not add incoming edges for the PHI
   272    // nodes just yet: those values may be defined by this or following blocks.
   273    // This step is omitted if "ignoreArguments" is set.  The arguments of the
   274    // first block have been already made available through the remapping of
   275    // LLVM function arguments.
   276    if (!ignoreArguments) {
   277      auto predecessors = bb.getPredecessors();
   278      unsigned numPredecessors =
   279          std::distance(predecessors.begin(), predecessors.end());
   280      for (auto *arg : bb.getArguments()) {
   281        auto wrappedType = arg->getType().dyn_cast<LLVM::LLVMType>();
   282        if (!wrappedType)
   283          return emitError(bb.front().getLoc(),
   284                           "block argument does not have an LLVM type");
   285        llvm::Type *type = wrappedType.getUnderlyingType();
   286        llvm::PHINode *phi = builder.CreatePHI(type, numPredecessors);
   287        valueMapping[arg] = phi;
   288      }
   289    }
   290  
   291    // Traverse operations.
   292    for (auto &op : bb) {
   293      if (failed(convertOperation(op, builder)))
   294        return failure();
   295    }
   296  
   297    return success();
   298  }
   299  
   300  // Create named global variables that correspond to llvm.global definitions.
   301  void ModuleTranslation::convertGlobals() {
   302    for (auto op : mlirModule.getOps<LLVM::GlobalOp>()) {
   303      llvm::Constant *cst;
   304      llvm::Type *type;
   305      // String attributes are treated separately because they cannot appear as
   306      // in-function constants and are thus not supported by getLLVMConstant.
   307      if (auto strAttr = op.value().dyn_cast<StringAttr>()) {
   308        cst = llvm::ConstantDataArray::getString(
   309            llvmModule->getContext(), strAttr.getValue(), /*AddNull=*/false);
   310        type = cst->getType();
   311      } else {
   312        type = op.getType().getUnderlyingType();
   313        cst = getLLVMConstant(type, op.value(), op.getLoc());
   314      }
   315  
   316      auto *var = new llvm::GlobalVariable(*llvmModule, type, op.constant(),
   317                                           llvm::GlobalValue::InternalLinkage,
   318                                           cst, op.sym_name());
   319      globalsMapping.try_emplace(op, var);
   320    }
   321  }
   322  
   323  // Get the SSA value passed to the current block from the terminator operation
   324  // of its predecessor.
   325  static Value *getPHISourceValue(Block *current, Block *pred,
   326                                  unsigned numArguments, unsigned index) {
   327    auto &terminator = *pred->getTerminator();
   328    if (isa<LLVM::BrOp>(terminator)) {
   329      return terminator.getOperand(index);
   330    }
   331  
   332    // For conditional branches, we need to check if the current block is reached
   333    // through the "true" or the "false" branch and take the relevant operands.
   334    auto condBranchOp = dyn_cast<LLVM::CondBrOp>(terminator);
   335    assert(condBranchOp &&
   336           "only branch operations can be terminators of a block that "
   337           "has successors");
   338    assert((condBranchOp.getSuccessor(0) != condBranchOp.getSuccessor(1)) &&
   339           "successors with arguments in LLVM conditional branches must be "
   340           "different blocks");
   341  
   342    return condBranchOp.getSuccessor(0) == current
   343               ? terminator.getSuccessorOperand(0, index)
   344               : terminator.getSuccessorOperand(1, index);
   345  }
   346  
   347  void ModuleTranslation::connectPHINodes(FuncOp func) {
   348    // Skip the first block, it cannot be branched to and its arguments correspond
   349    // to the arguments of the LLVM function.
   350    for (auto it = std::next(func.begin()), eit = func.end(); it != eit; ++it) {
   351      Block *bb = &*it;
   352      llvm::BasicBlock *llvmBB = blockMapping.lookup(bb);
   353      auto phis = llvmBB->phis();
   354      auto numArguments = bb->getNumArguments();
   355      assert(numArguments == std::distance(phis.begin(), phis.end()));
   356      for (auto &numberedPhiNode : llvm::enumerate(phis)) {
   357        auto &phiNode = numberedPhiNode.value();
   358        unsigned index = numberedPhiNode.index();
   359        for (auto *pred : bb->getPredecessors()) {
   360          phiNode.addIncoming(valueMapping.lookup(getPHISourceValue(
   361                                  bb, pred, numArguments, index)),
   362                              blockMapping.lookup(pred));
   363        }
   364      }
   365    }
   366  }
   367  
   368  // TODO(mlir-team): implement an iterative version
   369  static void topologicalSortImpl(llvm::SetVector<Block *> &blocks, Block *b) {
   370    blocks.insert(b);
   371    for (Block *bb : b->getSuccessors()) {
   372      if (blocks.count(bb) == 0)
   373        topologicalSortImpl(blocks, bb);
   374    }
   375  }
   376  
   377  // Sort function blocks topologically.
   378  static llvm::SetVector<Block *> topologicalSort(FuncOp f) {
   379    // For each blocks that has not been visited yet (i.e. that has no
   380    // predecessors), add it to the list and traverse its successors in DFS
   381    // preorder.
   382    llvm::SetVector<Block *> blocks;
   383    for (Block &b : f.getBlocks()) {
   384      if (blocks.count(&b) == 0)
   385        topologicalSortImpl(blocks, &b);
   386    }
   387    assert(blocks.size() == f.getBlocks().size() && "some blocks are not sorted");
   388  
   389    return blocks;
   390  }
   391  
   392  LogicalResult ModuleTranslation::convertOneFunction(FuncOp func) {
   393    // Clear the block and value mappings, they are only relevant within one
   394    // function.
   395    blockMapping.clear();
   396    valueMapping.clear();
   397    llvm::Function *llvmFunc = functionMapping.lookup(func.getName());
   398    // Add function arguments to the value remapping table.
   399    // If there was noalias info then we decorate each argument accordingly.
   400    unsigned int argIdx = 0;
   401    for (const auto &kvp : llvm::zip(func.getArguments(), llvmFunc->args())) {
   402      llvm::Argument &llvmArg = std::get<1>(kvp);
   403      BlockArgument *mlirArg = std::get<0>(kvp);
   404  
   405      if (auto attr = func.getArgAttrOfType<BoolAttr>(argIdx, "llvm.noalias")) {
   406        // NB: Attribute already verified to be boolean, so check if we can indeed
   407        // attach the attribute to this argument, based on its type.
   408        auto argTy = mlirArg->getType().dyn_cast<LLVM::LLVMType>();
   409        if (!argTy.getUnderlyingType()->isPointerTy())
   410          return func.emitError(
   411              "llvm.noalias attribute attached to LLVM non-pointer argument");
   412        if (attr.getValue())
   413          llvmArg.addAttr(llvm::Attribute::AttrKind::NoAlias);
   414      }
   415      valueMapping[mlirArg] = &llvmArg;
   416      argIdx++;
   417    }
   418  
   419    // First, create all blocks so we can jump to them.
   420    llvm::LLVMContext &llvmContext = llvmFunc->getContext();
   421    for (auto &bb : func) {
   422      auto *llvmBB = llvm::BasicBlock::Create(llvmContext);
   423      llvmBB->insertInto(llvmFunc);
   424      blockMapping[&bb] = llvmBB;
   425    }
   426  
   427    // Then, convert blocks one by one in topological order to ensure defs are
   428    // converted before uses.
   429    auto blocks = topologicalSort(func);
   430    for (auto indexedBB : llvm::enumerate(blocks)) {
   431      auto *bb = indexedBB.value();
   432      if (failed(convertBlock(*bb, /*ignoreArguments=*/indexedBB.index() == 0)))
   433        return failure();
   434    }
   435  
   436    // Finally, after all blocks have been traversed and values mapped, connect
   437    // the PHI nodes to the results of preceding blocks.
   438    connectPHINodes(func);
   439    return success();
   440  }
   441  
   442  LogicalResult ModuleTranslation::convertFunctions() {
   443    // Declare all functions first because there may be function calls that form a
   444    // call graph with cycles.
   445    for (FuncOp function : mlirModule.getOps<FuncOp>()) {
   446      mlir::BoolAttr isVarArgsAttr =
   447          function.getAttrOfType<BoolAttr>("std.varargs");
   448      bool isVarArgs = isVarArgsAttr && isVarArgsAttr.getValue();
   449      llvm::FunctionType *functionType =
   450          convertFunctionType(llvmModule->getContext(), function.getType(),
   451                              function.getLoc(), isVarArgs);
   452      if (!functionType)
   453        return failure();
   454      llvm::FunctionCallee llvmFuncCst =
   455          llvmModule->getOrInsertFunction(function.getName(), functionType);
   456      assert(isa<llvm::Function>(llvmFuncCst.getCallee()));
   457      functionMapping[function.getName()] =
   458          cast<llvm::Function>(llvmFuncCst.getCallee());
   459    }
   460  
   461    // Convert functions.
   462    for (FuncOp function : mlirModule.getOps<FuncOp>()) {
   463      // Ignore external functions.
   464      if (function.isExternal())
   465        continue;
   466  
   467      if (failed(convertOneFunction(function)))
   468        return failure();
   469    }
   470  
   471    return success();
   472  }
   473  
   474  std::unique_ptr<llvm::Module> ModuleTranslation::prepareLLVMModule(ModuleOp m) {
   475    auto *dialect = m.getContext()->getRegisteredDialect<LLVM::LLVMDialect>();
   476    assert(dialect && "LLVM dialect must be registered");
   477  
   478    auto llvmModule = llvm::CloneModule(dialect->getLLVMModule());
   479    if (!llvmModule)
   480      return nullptr;
   481  
   482    llvm::LLVMContext &llvmContext = llvmModule->getContext();
   483    llvm::IRBuilder<> builder(llvmContext);
   484  
   485    // Inject declarations for `malloc` and `free` functions that can be used in
   486    // memref allocation/deallocation coming from standard ops lowering.
   487    llvmModule->getOrInsertFunction("malloc", builder.getInt8PtrTy(),
   488                                    builder.getInt64Ty());
   489    llvmModule->getOrInsertFunction("free", builder.getVoidTy(),
   490                                    builder.getInt8PtrTy());
   491  
   492    return llvmModule;
   493  }
   494  
   495  } // namespace LLVM
   496  } // namespace mlir