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 .Case([&](omp::FlushOp) { 334 // No support in Openmp runtime funciton (__kmpc_flush) to accept 335 // the argument list. 336 // OpenMP standard states the following: 337 // "An implementation may implement a flush with a list by ignoring 338 // the list, and treating it the same as a flush without a list." 339 // 340 // The argument list is discarded so that, flush with a list is treated 341 // same as a flush without a list. 342 ompBuilder->CreateFlush(builder.saveIP()); 343 return success(); 344 }) 345 .Default([&](Operation *inst) { 346 return inst->emitError("unsupported OpenMP operation: ") 347 << inst->getName(); 348 }); 349 } 350 351 /// Given a single MLIR operation, create the corresponding LLVM IR operation 352 /// using the `builder`. LLVM IR Builder does not have a generic interface so 353 /// this has to be a long chain of `if`s calling different functions with a 354 /// different number of arguments. 355 LogicalResult ModuleTranslation::convertOperation(Operation &opInst, 356 llvm::IRBuilder<> &builder) { 357 auto extractPosition = [](ArrayAttr attr) { 358 SmallVector<unsigned, 4> position; 359 position.reserve(attr.size()); 360 for (Attribute v : attr) 361 position.push_back(v.cast<IntegerAttr>().getValue().getZExtValue()); 362 return position; 363 }; 364 365 #include "mlir/Dialect/LLVMIR/LLVMConversions.inc" 366 367 // Emit function calls. If the "callee" attribute is present, this is a 368 // direct function call and we also need to look up the remapped function 369 // itself. Otherwise, this is an indirect call and the callee is the first 370 // operand, look it up as a normal value. Return the llvm::Value representing 371 // the function result, which may be of llvm::VoidTy type. 372 auto convertCall = [this, &builder](Operation &op) -> llvm::Value * { 373 auto operands = lookupValues(op.getOperands()); 374 ArrayRef<llvm::Value *> operandsRef(operands); 375 if (auto attr = op.getAttrOfType<FlatSymbolRefAttr>("callee")) { 376 return builder.CreateCall(functionMapping.lookup(attr.getValue()), 377 operandsRef); 378 } else { 379 auto *calleePtrType = 380 cast<llvm::PointerType>(operandsRef.front()->getType()); 381 auto *calleeType = 382 cast<llvm::FunctionType>(calleePtrType->getElementType()); 383 return builder.CreateCall(calleeType, operandsRef.front(), 384 operandsRef.drop_front()); 385 } 386 }; 387 388 // Emit calls. If the called function has a result, remap the corresponding 389 // value. Note that LLVM IR dialect CallOp has either 0 or 1 result. 390 if (isa<LLVM::CallOp>(opInst)) { 391 llvm::Value *result = convertCall(opInst); 392 if (opInst.getNumResults() != 0) { 393 valueMapping[opInst.getResult(0)] = result; 394 return success(); 395 } 396 // Check that LLVM call returns void for 0-result functions. 397 return success(result->getType()->isVoidTy()); 398 } 399 400 if (auto invOp = dyn_cast<LLVM::InvokeOp>(opInst)) { 401 auto operands = lookupValues(opInst.getOperands()); 402 ArrayRef<llvm::Value *> operandsRef(operands); 403 if (auto attr = opInst.getAttrOfType<FlatSymbolRefAttr>("callee")) { 404 builder.CreateInvoke(functionMapping.lookup(attr.getValue()), 405 blockMapping[invOp.getSuccessor(0)], 406 blockMapping[invOp.getSuccessor(1)], operandsRef); 407 } else { 408 auto *calleePtrType = 409 cast<llvm::PointerType>(operandsRef.front()->getType()); 410 auto *calleeType = 411 cast<llvm::FunctionType>(calleePtrType->getElementType()); 412 builder.CreateInvoke( 413 calleeType, operandsRef.front(), blockMapping[invOp.getSuccessor(0)], 414 blockMapping[invOp.getSuccessor(1)], operandsRef.drop_front()); 415 } 416 return success(); 417 } 418 419 if (auto lpOp = dyn_cast<LLVM::LandingpadOp>(opInst)) { 420 llvm::Type *ty = lpOp.getType().dyn_cast<LLVMType>().getUnderlyingType(); 421 llvm::LandingPadInst *lpi = 422 builder.CreateLandingPad(ty, lpOp.getNumOperands()); 423 424 // Add clauses 425 for (auto operand : lookupValues(lpOp.getOperands())) { 426 // All operands should be constant - checked by verifier 427 if (auto constOperand = dyn_cast<llvm::Constant>(operand)) 428 lpi->addClause(constOperand); 429 } 430 valueMapping[lpOp.getResult()] = lpi; 431 return success(); 432 } 433 434 // Emit branches. We need to look up the remapped blocks and ignore the block 435 // arguments that were transformed into PHI nodes. 436 if (auto brOp = dyn_cast<LLVM::BrOp>(opInst)) { 437 builder.CreateBr(blockMapping[brOp.getSuccessor()]); 438 return success(); 439 } 440 if (auto condbrOp = dyn_cast<LLVM::CondBrOp>(opInst)) { 441 builder.CreateCondBr(valueMapping.lookup(condbrOp.getOperand(0)), 442 blockMapping[condbrOp.getSuccessor(0)], 443 blockMapping[condbrOp.getSuccessor(1)]); 444 return success(); 445 } 446 447 // Emit addressof. We need to look up the global value referenced by the 448 // operation and store it in the MLIR-to-LLVM value mapping. This does not 449 // emit any LLVM instruction. 450 if (auto addressOfOp = dyn_cast<LLVM::AddressOfOp>(opInst)) { 451 LLVM::GlobalOp global = addressOfOp.getGlobal(); 452 // The verifier should not have allowed this. 453 assert(global && "referencing an undefined global"); 454 455 valueMapping[addressOfOp.getResult()] = globalsMapping.lookup(global); 456 return success(); 457 } 458 459 if (opInst.getDialect() == ompDialect) { 460 return convertOmpOperation(opInst, builder); 461 } 462 463 return opInst.emitError("unsupported or non-LLVM operation: ") 464 << opInst.getName(); 465 } 466 467 /// Convert block to LLVM IR. Unless `ignoreArguments` is set, emit PHI nodes 468 /// to define values corresponding to the MLIR block arguments. These nodes 469 /// are not connected to the source basic blocks, which may not exist yet. 470 LogicalResult ModuleTranslation::convertBlock(Block &bb, bool ignoreArguments) { 471 llvm::IRBuilder<> builder(blockMapping[&bb]); 472 auto *subprogram = builder.GetInsertBlock()->getParent()->getSubprogram(); 473 474 // Before traversing operations, make block arguments available through 475 // value remapping and PHI nodes, but do not add incoming edges for the PHI 476 // nodes just yet: those values may be defined by this or following blocks. 477 // This step is omitted if "ignoreArguments" is set. The arguments of the 478 // first block have been already made available through the remapping of 479 // LLVM function arguments. 480 if (!ignoreArguments) { 481 auto predecessors = bb.getPredecessors(); 482 unsigned numPredecessors = 483 std::distance(predecessors.begin(), predecessors.end()); 484 for (auto arg : bb.getArguments()) { 485 auto wrappedType = arg.getType().dyn_cast<LLVM::LLVMType>(); 486 if (!wrappedType) 487 return emitError(bb.front().getLoc(), 488 "block argument does not have an LLVM type"); 489 llvm::Type *type = wrappedType.getUnderlyingType(); 490 llvm::PHINode *phi = builder.CreatePHI(type, numPredecessors); 491 valueMapping[arg] = phi; 492 } 493 } 494 495 // Traverse operations. 496 for (auto &op : bb) { 497 // Set the current debug location within the builder. 498 builder.SetCurrentDebugLocation( 499 debugTranslation->translateLoc(op.getLoc(), subprogram)); 500 501 if (failed(convertOperation(op, builder))) 502 return failure(); 503 } 504 505 return success(); 506 } 507 508 /// Create named global variables that correspond to llvm.mlir.global 509 /// definitions. 510 LogicalResult ModuleTranslation::convertGlobals() { 511 // Lock access to the llvm context. 512 llvm::sys::SmartScopedLock<true> scopedLock( 513 llvmDialect->getLLVMContextMutex()); 514 for (auto op : getModuleBody(mlirModule).getOps<LLVM::GlobalOp>()) { 515 llvm::Type *type = op.getType().getUnderlyingType(); 516 llvm::Constant *cst = llvm::UndefValue::get(type); 517 if (op.getValueOrNull()) { 518 // String attributes are treated separately because they cannot appear as 519 // in-function constants and are thus not supported by getLLVMConstant. 520 if (auto strAttr = op.getValueOrNull().dyn_cast_or_null<StringAttr>()) { 521 cst = llvm::ConstantDataArray::getString( 522 llvmModule->getContext(), strAttr.getValue(), /*AddNull=*/false); 523 type = cst->getType(); 524 } else if (!(cst = getLLVMConstant(type, op.getValueOrNull(), 525 op.getLoc()))) { 526 return failure(); 527 } 528 } else if (Block *initializer = op.getInitializerBlock()) { 529 llvm::IRBuilder<> builder(llvmModule->getContext()); 530 for (auto &op : initializer->without_terminator()) { 531 if (failed(convertOperation(op, builder)) || 532 !isa<llvm::Constant>(valueMapping.lookup(op.getResult(0)))) 533 return emitError(op.getLoc(), "unemittable constant value"); 534 } 535 ReturnOp ret = cast<ReturnOp>(initializer->getTerminator()); 536 cst = cast<llvm::Constant>(valueMapping.lookup(ret.getOperand(0))); 537 } 538 539 auto linkage = convertLinkageToLLVM(op.linkage()); 540 bool anyExternalLinkage = 541 ((linkage == llvm::GlobalVariable::ExternalLinkage && 542 isa<llvm::UndefValue>(cst)) || 543 linkage == llvm::GlobalVariable::ExternalWeakLinkage); 544 auto addrSpace = op.addr_space().getLimitedValue(); 545 auto *var = new llvm::GlobalVariable( 546 *llvmModule, type, op.constant(), linkage, 547 anyExternalLinkage ? nullptr : cst, op.sym_name(), 548 /*InsertBefore=*/nullptr, llvm::GlobalValue::NotThreadLocal, addrSpace); 549 550 globalsMapping.try_emplace(op, var); 551 } 552 553 return success(); 554 } 555 556 /// Get the SSA value passed to the current block from the terminator operation 557 /// of its predecessor. 558 static Value getPHISourceValue(Block *current, Block *pred, 559 unsigned numArguments, unsigned index) { 560 auto &terminator = *pred->getTerminator(); 561 if (isa<LLVM::BrOp>(terminator)) { 562 return terminator.getOperand(index); 563 } 564 565 // For conditional branches, we need to check if the current block is reached 566 // through the "true" or the "false" branch and take the relevant operands. 567 auto condBranchOp = dyn_cast<LLVM::CondBrOp>(terminator); 568 assert(condBranchOp && 569 "only branch operations can be terminators of a block that " 570 "has successors"); 571 assert((condBranchOp.getSuccessor(0) != condBranchOp.getSuccessor(1)) && 572 "successors with arguments in LLVM conditional branches must be " 573 "different blocks"); 574 575 return condBranchOp.getSuccessor(0) == current 576 ? condBranchOp.trueDestOperands()[index] 577 : condBranchOp.falseDestOperands()[index]; 578 } 579 580 void ModuleTranslation::connectPHINodes(LLVMFuncOp func) { 581 // Skip the first block, it cannot be branched to and its arguments correspond 582 // to the arguments of the LLVM function. 583 for (auto it = std::next(func.begin()), eit = func.end(); it != eit; ++it) { 584 Block *bb = &*it; 585 llvm::BasicBlock *llvmBB = blockMapping.lookup(bb); 586 auto phis = llvmBB->phis(); 587 auto numArguments = bb->getNumArguments(); 588 assert(numArguments == std::distance(phis.begin(), phis.end())); 589 for (auto &numberedPhiNode : llvm::enumerate(phis)) { 590 auto &phiNode = numberedPhiNode.value(); 591 unsigned index = numberedPhiNode.index(); 592 for (auto *pred : bb->getPredecessors()) { 593 phiNode.addIncoming(valueMapping.lookup(getPHISourceValue( 594 bb, pred, numArguments, index)), 595 blockMapping.lookup(pred)); 596 } 597 } 598 } 599 } 600 601 // TODO(mlir-team): implement an iterative version 602 static void topologicalSortImpl(llvm::SetVector<Block *> &blocks, Block *b) { 603 blocks.insert(b); 604 for (Block *bb : b->getSuccessors()) { 605 if (blocks.count(bb) == 0) 606 topologicalSortImpl(blocks, bb); 607 } 608 } 609 610 /// Sort function blocks topologically. 611 static llvm::SetVector<Block *> topologicalSort(LLVMFuncOp f) { 612 // For each blocks that has not been visited yet (i.e. that has no 613 // predecessors), add it to the list and traverse its successors in DFS 614 // preorder. 615 llvm::SetVector<Block *> blocks; 616 for (Block &b : f.getBlocks()) { 617 if (blocks.count(&b) == 0) 618 topologicalSortImpl(blocks, &b); 619 } 620 assert(blocks.size() == f.getBlocks().size() && "some blocks are not sorted"); 621 622 return blocks; 623 } 624 625 /// Attempts to add an attribute identified by `key`, optionally with the given 626 /// `value` to LLVM function `llvmFunc`. Reports errors at `loc` if any. If the 627 /// attribute has a kind known to LLVM IR, create the attribute of this kind, 628 /// otherwise keep it as a string attribute. Performs additional checks for 629 /// attributes known to have or not have a value in order to avoid assertions 630 /// inside LLVM upon construction. 631 static LogicalResult checkedAddLLVMFnAttribute(Location loc, 632 llvm::Function *llvmFunc, 633 StringRef key, 634 StringRef value = StringRef()) { 635 auto kind = llvm::Attribute::getAttrKindFromName(key); 636 if (kind == llvm::Attribute::None) { 637 llvmFunc->addFnAttr(key, value); 638 return success(); 639 } 640 641 if (llvm::Attribute::doesAttrKindHaveArgument(kind)) { 642 if (value.empty()) 643 return emitError(loc) << "LLVM attribute '" << key << "' expects a value"; 644 645 int result; 646 if (!value.getAsInteger(/*Radix=*/0, result)) 647 llvmFunc->addFnAttr( 648 llvm::Attribute::get(llvmFunc->getContext(), kind, result)); 649 else 650 llvmFunc->addFnAttr(key, value); 651 return success(); 652 } 653 654 if (!value.empty()) 655 return emitError(loc) << "LLVM attribute '" << key 656 << "' does not expect a value, found '" << value 657 << "'"; 658 659 llvmFunc->addFnAttr(kind); 660 return success(); 661 } 662 663 /// Attaches the attributes listed in the given array attribute to `llvmFunc`. 664 /// Reports error to `loc` if any and returns immediately. Expects `attributes` 665 /// to be an array attribute containing either string attributes, treated as 666 /// value-less LLVM attributes, or array attributes containing two string 667 /// attributes, with the first string being the name of the corresponding LLVM 668 /// attribute and the second string beings its value. Note that even integer 669 /// attributes are expected to have their values expressed as strings. 670 static LogicalResult 671 forwardPassthroughAttributes(Location loc, Optional<ArrayAttr> attributes, 672 llvm::Function *llvmFunc) { 673 if (!attributes) 674 return success(); 675 676 for (Attribute attr : *attributes) { 677 if (auto stringAttr = attr.dyn_cast<StringAttr>()) { 678 if (failed( 679 checkedAddLLVMFnAttribute(loc, llvmFunc, stringAttr.getValue()))) 680 return failure(); 681 continue; 682 } 683 684 auto arrayAttr = attr.dyn_cast<ArrayAttr>(); 685 if (!arrayAttr || arrayAttr.size() != 2) 686 return emitError(loc) 687 << "expected 'passthrough' to contain string or array attributes"; 688 689 auto keyAttr = arrayAttr[0].dyn_cast<StringAttr>(); 690 auto valueAttr = arrayAttr[1].dyn_cast<StringAttr>(); 691 if (!keyAttr || !valueAttr) 692 return emitError(loc) 693 << "expected arrays within 'passthrough' to contain two strings"; 694 695 if (failed(checkedAddLLVMFnAttribute(loc, llvmFunc, keyAttr.getValue(), 696 valueAttr.getValue()))) 697 return failure(); 698 } 699 return success(); 700 } 701 702 LogicalResult ModuleTranslation::convertOneFunction(LLVMFuncOp func) { 703 // Clear the block and value mappings, they are only relevant within one 704 // function. 705 blockMapping.clear(); 706 valueMapping.clear(); 707 llvm::Function *llvmFunc = functionMapping.lookup(func.getName()); 708 709 // Translate the debug information for this function. 710 debugTranslation->translate(func, *llvmFunc); 711 712 // Add function arguments to the value remapping table. 713 // If there was noalias info then we decorate each argument accordingly. 714 unsigned int argIdx = 0; 715 for (auto kvp : llvm::zip(func.getArguments(), llvmFunc->args())) { 716 llvm::Argument &llvmArg = std::get<1>(kvp); 717 BlockArgument mlirArg = std::get<0>(kvp); 718 719 if (auto attr = func.getArgAttrOfType<BoolAttr>(argIdx, "llvm.noalias")) { 720 // NB: Attribute already verified to be boolean, so check if we can indeed 721 // attach the attribute to this argument, based on its type. 722 auto argTy = mlirArg.getType().dyn_cast<LLVM::LLVMType>(); 723 if (!argTy.getUnderlyingType()->isPointerTy()) 724 return func.emitError( 725 "llvm.noalias attribute attached to LLVM non-pointer argument"); 726 if (attr.getValue()) 727 llvmArg.addAttr(llvm::Attribute::AttrKind::NoAlias); 728 } 729 valueMapping[mlirArg] = &llvmArg; 730 argIdx++; 731 } 732 733 // Check the personality and set it. 734 if (func.personality().hasValue()) { 735 llvm::Type *ty = llvm::Type::getInt8PtrTy(llvmFunc->getContext()); 736 if (llvm::Constant *pfunc = 737 getLLVMConstant(ty, func.personalityAttr(), func.getLoc())) 738 llvmFunc->setPersonalityFn(pfunc); 739 } 740 741 // First, create all blocks so we can jump to them. 742 llvm::LLVMContext &llvmContext = llvmFunc->getContext(); 743 for (auto &bb : func) { 744 auto *llvmBB = llvm::BasicBlock::Create(llvmContext); 745 llvmBB->insertInto(llvmFunc); 746 blockMapping[&bb] = llvmBB; 747 } 748 749 // Then, convert blocks one by one in topological order to ensure defs are 750 // converted before uses. 751 auto blocks = topologicalSort(func); 752 for (auto indexedBB : llvm::enumerate(blocks)) { 753 auto *bb = indexedBB.value(); 754 if (failed(convertBlock(*bb, /*ignoreArguments=*/indexedBB.index() == 0))) 755 return failure(); 756 } 757 758 // Finally, after all blocks have been traversed and values mapped, connect 759 // the PHI nodes to the results of preceding blocks. 760 connectPHINodes(func); 761 return success(); 762 } 763 764 LogicalResult ModuleTranslation::checkSupportedModuleOps(Operation *m) { 765 for (Operation &o : getModuleBody(m).getOperations()) 766 if (!isa<LLVM::LLVMFuncOp>(&o) && !isa<LLVM::GlobalOp>(&o) && 767 !o.isKnownTerminator()) 768 return o.emitOpError("unsupported module-level operation"); 769 return success(); 770 } 771 772 LogicalResult ModuleTranslation::convertFunctions() { 773 // Lock access to the llvm context. 774 llvm::sys::SmartScopedLock<true> scopedLock( 775 llvmDialect->getLLVMContextMutex()); 776 // Declare all functions first because there may be function calls that form a 777 // call graph with cycles. 778 for (auto function : getModuleBody(mlirModule).getOps<LLVMFuncOp>()) { 779 llvm::FunctionCallee llvmFuncCst = llvmModule->getOrInsertFunction( 780 function.getName(), 781 cast<llvm::FunctionType>(function.getType().getUnderlyingType())); 782 llvm::Function *llvmFunc = cast<llvm::Function>(llvmFuncCst.getCallee()); 783 functionMapping[function.getName()] = llvmFunc; 784 785 // Forward the pass-through attributes to LLVM. 786 if (failed(forwardPassthroughAttributes(function.getLoc(), 787 function.passthrough(), llvmFunc))) 788 return failure(); 789 } 790 791 // Convert functions. 792 for (auto function : getModuleBody(mlirModule).getOps<LLVMFuncOp>()) { 793 // Ignore external functions. 794 if (function.isExternal()) 795 continue; 796 797 if (failed(convertOneFunction(function))) 798 return failure(); 799 } 800 801 return success(); 802 } 803 804 /// A helper to look up remapped operands in the value remapping table.` 805 SmallVector<llvm::Value *, 8> 806 ModuleTranslation::lookupValues(ValueRange values) { 807 SmallVector<llvm::Value *, 8> remapped; 808 remapped.reserve(values.size()); 809 for (Value v : values) { 810 assert(valueMapping.count(v) && "referencing undefined value"); 811 remapped.push_back(valueMapping.lookup(v)); 812 } 813 return remapped; 814 } 815 816 std::unique_ptr<llvm::Module> 817 ModuleTranslation::prepareLLVMModule(Operation *m) { 818 auto *dialect = m->getContext()->getRegisteredDialect<LLVM::LLVMDialect>(); 819 assert(dialect && "LLVM dialect must be registered"); 820 // Lock the LLVM context as we might create new types here. 821 llvm::sys::SmartScopedLock<true> scopedLock(dialect->getLLVMContextMutex()); 822 823 auto llvmModule = llvm::CloneModule(dialect->getLLVMModule()); 824 if (!llvmModule) 825 return nullptr; 826 827 llvm::LLVMContext &llvmContext = llvmModule->getContext(); 828 llvm::IRBuilder<> builder(llvmContext); 829 830 // Inject declarations for `malloc` and `free` functions that can be used in 831 // memref allocation/deallocation coming from standard ops lowering. 832 llvmModule->getOrInsertFunction("malloc", builder.getInt8PtrTy(), 833 builder.getInt64Ty()); 834 llvmModule->getOrInsertFunction("free", builder.getVoidTy(), 835 builder.getInt8PtrTy()); 836 837 return llvmModule; 838 } 839