1 //===- SPIRVConversion.cpp - SPIR-V Conversion Utilities ------------------===// 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 utilities used to lower to SPIR-V dialect. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "mlir/Dialect/SPIRV/Transforms/SPIRVConversion.h" 14 #include "mlir/Dialect/SPIRV/IR/SPIRVDialect.h" 15 #include "mlir/Dialect/SPIRV/IR/SPIRVOps.h" 16 #include "llvm/ADT/Sequence.h" 17 #include "llvm/ADT/StringExtras.h" 18 #include "llvm/Support/Debug.h" 19 20 #include <functional> 21 22 #define DEBUG_TYPE "mlir-spirv-conversion" 23 24 using namespace mlir; 25 26 //===----------------------------------------------------------------------===// 27 // Utility functions 28 //===----------------------------------------------------------------------===// 29 30 /// Checks that `candidates` extension requirements are possible to be satisfied 31 /// with the given `targetEnv`. 32 /// 33 /// `candidates` is a vector of vector for extension requirements following 34 /// ((Extension::A OR Extension::B) AND (Extension::C OR Extension::D)) 35 /// convention. 36 template <typename LabelT> 37 static LogicalResult checkExtensionRequirements( 38 LabelT label, const spirv::TargetEnv &targetEnv, 39 const spirv::SPIRVType::ExtensionArrayRefVector &candidates) { 40 for (const auto &ors : candidates) { 41 if (targetEnv.allows(ors)) 42 continue; 43 44 SmallVector<StringRef, 4> extStrings; 45 for (spirv::Extension ext : ors) 46 extStrings.push_back(spirv::stringifyExtension(ext)); 47 48 LLVM_DEBUG(llvm::dbgs() 49 << label << " illegal: requires at least one extension in [" 50 << llvm::join(extStrings, ", ") 51 << "] but none allowed in target environment\n"); 52 return failure(); 53 } 54 return success(); 55 } 56 57 /// Checks that `candidates`capability requirements are possible to be satisfied 58 /// with the given `isAllowedFn`. 59 /// 60 /// `candidates` is a vector of vector for capability requirements following 61 /// ((Capability::A OR Capability::B) AND (Capability::C OR Capability::D)) 62 /// convention. 63 template <typename LabelT> 64 static LogicalResult checkCapabilityRequirements( 65 LabelT label, const spirv::TargetEnv &targetEnv, 66 const spirv::SPIRVType::CapabilityArrayRefVector &candidates) { 67 for (const auto &ors : candidates) { 68 if (targetEnv.allows(ors)) 69 continue; 70 71 SmallVector<StringRef, 4> capStrings; 72 for (spirv::Capability cap : ors) 73 capStrings.push_back(spirv::stringifyCapability(cap)); 74 75 LLVM_DEBUG(llvm::dbgs() 76 << label << " illegal: requires at least one capability in [" 77 << llvm::join(capStrings, ", ") 78 << "] but none allowed in target environment\n"); 79 return failure(); 80 } 81 return success(); 82 } 83 84 //===----------------------------------------------------------------------===// 85 // Type Conversion 86 //===----------------------------------------------------------------------===// 87 88 Type SPIRVTypeConverter::getIndexType(MLIRContext *context) { 89 // Convert to 32-bit integers for now. Might need a way to control this in 90 // future. 91 // TODO: It is probably better to make it 64-bit integers. To 92 // this some support is needed in SPIR-V dialect for Conversion 93 // instructions. The Vulkan spec requires the builtins like 94 // GlobalInvocationID, etc. to be 32-bit (unsigned) integers which should be 95 // SExtended to 64-bit for index computations. 96 return IntegerType::get(32, context); 97 } 98 99 /// Mapping between SPIR-V storage classes to memref memory spaces. 100 /// 101 /// Note: memref does not have a defined semantics for each memory space; it 102 /// depends on the context where it is used. There are no particular reasons 103 /// behind the number assignments; we try to follow NVVM conventions and largely 104 /// give common storage classes a smaller number. The hope is use symbolic 105 /// memory space representation eventually after memref supports it. 106 // TODO: swap Generic and StorageBuffer assignment to be more akin 107 // to NVVM. 108 #define STORAGE_SPACE_MAP_LIST(MAP_FN) \ 109 MAP_FN(spirv::StorageClass::Generic, 1) \ 110 MAP_FN(spirv::StorageClass::StorageBuffer, 0) \ 111 MAP_FN(spirv::StorageClass::Workgroup, 3) \ 112 MAP_FN(spirv::StorageClass::Uniform, 4) \ 113 MAP_FN(spirv::StorageClass::Private, 5) \ 114 MAP_FN(spirv::StorageClass::Function, 6) \ 115 MAP_FN(spirv::StorageClass::PushConstant, 7) \ 116 MAP_FN(spirv::StorageClass::UniformConstant, 8) \ 117 MAP_FN(spirv::StorageClass::Input, 9) \ 118 MAP_FN(spirv::StorageClass::Output, 10) \ 119 MAP_FN(spirv::StorageClass::CrossWorkgroup, 11) \ 120 MAP_FN(spirv::StorageClass::AtomicCounter, 12) \ 121 MAP_FN(spirv::StorageClass::Image, 13) \ 122 MAP_FN(spirv::StorageClass::CallableDataNV, 14) \ 123 MAP_FN(spirv::StorageClass::IncomingCallableDataNV, 15) \ 124 MAP_FN(spirv::StorageClass::RayPayloadNV, 16) \ 125 MAP_FN(spirv::StorageClass::HitAttributeNV, 17) \ 126 MAP_FN(spirv::StorageClass::IncomingRayPayloadNV, 18) \ 127 MAP_FN(spirv::StorageClass::ShaderRecordBufferNV, 19) \ 128 MAP_FN(spirv::StorageClass::PhysicalStorageBuffer, 20) 129 130 unsigned 131 SPIRVTypeConverter::getMemorySpaceForStorageClass(spirv::StorageClass storage) { 132 #define STORAGE_SPACE_MAP_FN(storage, space) \ 133 case storage: \ 134 return space; 135 136 switch (storage) { STORAGE_SPACE_MAP_LIST(STORAGE_SPACE_MAP_FN) } 137 #undef STORAGE_SPACE_MAP_FN 138 llvm_unreachable("unhandled storage class!"); 139 } 140 141 Optional<spirv::StorageClass> 142 SPIRVTypeConverter::getStorageClassForMemorySpace(unsigned space) { 143 #define STORAGE_SPACE_MAP_FN(storage, space) \ 144 case space: \ 145 return storage; 146 147 switch (space) { 148 STORAGE_SPACE_MAP_LIST(STORAGE_SPACE_MAP_FN) 149 default: 150 return llvm::None; 151 } 152 #undef STORAGE_SPACE_MAP_FN 153 } 154 155 #undef STORAGE_SPACE_MAP_LIST 156 157 // TODO: This is a utility function that should probably be 158 // exposed by the SPIR-V dialect. Keeping it local till the use case arises. 159 static Optional<int64_t> getTypeNumBytes(Type t) { 160 if (t.isa<spirv::ScalarType>()) { 161 auto bitWidth = t.getIntOrFloatBitWidth(); 162 // According to the SPIR-V spec: 163 // "There is no physical size or bit pattern defined for values with boolean 164 // type. If they are stored (in conjunction with OpVariable), they can only 165 // be used with logical addressing operations, not physical, and only with 166 // non-externally visible shader Storage Classes: Workgroup, CrossWorkgroup, 167 // Private, Function, Input, and Output." 168 if (bitWidth == 1) { 169 return llvm::None; 170 } 171 return bitWidth / 8; 172 } 173 if (auto vecType = t.dyn_cast<VectorType>()) { 174 auto elementSize = getTypeNumBytes(vecType.getElementType()); 175 if (!elementSize) 176 return llvm::None; 177 return vecType.getNumElements() * *elementSize; 178 } 179 if (auto memRefType = t.dyn_cast<MemRefType>()) { 180 // TODO: Layout should also be controlled by the ABI attributes. For now 181 // using the layout from MemRef. 182 int64_t offset; 183 SmallVector<int64_t, 4> strides; 184 if (!memRefType.hasStaticShape() || 185 failed(getStridesAndOffset(memRefType, strides, offset))) { 186 return llvm::None; 187 } 188 // To get the size of the memref object in memory, the total size is the 189 // max(stride * dimension-size) computed for all dimensions times the size 190 // of the element. 191 auto elementSize = getTypeNumBytes(memRefType.getElementType()); 192 if (!elementSize) { 193 return llvm::None; 194 } 195 if (memRefType.getRank() == 0) { 196 return elementSize; 197 } 198 auto dims = memRefType.getShape(); 199 if (llvm::is_contained(dims, ShapedType::kDynamicSize) || 200 offset == MemRefType::getDynamicStrideOrOffset() || 201 llvm::is_contained(strides, MemRefType::getDynamicStrideOrOffset())) { 202 return llvm::None; 203 } 204 int64_t memrefSize = -1; 205 for (auto shape : enumerate(dims)) { 206 memrefSize = std::max(memrefSize, shape.value() * strides[shape.index()]); 207 } 208 return (offset + memrefSize) * elementSize.getValue(); 209 } else if (auto tensorType = t.dyn_cast<TensorType>()) { 210 if (!tensorType.hasStaticShape()) { 211 return llvm::None; 212 } 213 auto elementSize = getTypeNumBytes(tensorType.getElementType()); 214 if (!elementSize) { 215 return llvm::None; 216 } 217 int64_t size = elementSize.getValue(); 218 for (auto shape : tensorType.getShape()) { 219 size *= shape; 220 } 221 return size; 222 } 223 // TODO: Add size computation for other types. 224 return llvm::None; 225 } 226 227 Optional<int64_t> SPIRVTypeConverter::getConvertedTypeNumBytes(Type t) { 228 return getTypeNumBytes(t); 229 } 230 231 /// Converts a scalar `type` to a suitable type under the given `targetEnv`. 232 static Optional<Type> 233 convertScalarType(const spirv::TargetEnv &targetEnv, spirv::ScalarType type, 234 Optional<spirv::StorageClass> storageClass = {}) { 235 // Get extension and capability requirements for the given type. 236 SmallVector<ArrayRef<spirv::Extension>, 1> extensions; 237 SmallVector<ArrayRef<spirv::Capability>, 2> capabilities; 238 type.getExtensions(extensions, storageClass); 239 type.getCapabilities(capabilities, storageClass); 240 241 // If all requirements are met, then we can accept this type as-is. 242 if (succeeded(checkCapabilityRequirements(type, targetEnv, capabilities)) && 243 succeeded(checkExtensionRequirements(type, targetEnv, extensions))) 244 return type; 245 246 // Otherwise we need to adjust the type, which really means adjusting the 247 // bitwidth given this is a scalar type. 248 // TODO: We are unconditionally converting the bitwidth here, 249 // this might be okay for non-interface types (i.e., types used in 250 // Private/Function storage classes), but not for interface types (i.e., 251 // types used in StorageBuffer/Uniform/PushConstant/etc. storage classes). 252 // This is because the later actually affects the ABI contract with the 253 // runtime. So we may want to expose a control on SPIRVTypeConverter to fail 254 // conversion if we cannot change there. 255 256 if (auto floatType = type.dyn_cast<FloatType>()) { 257 LLVM_DEBUG(llvm::dbgs() << type << " converted to 32-bit for SPIR-V\n"); 258 return Builder(targetEnv.getContext()).getF32Type(); 259 } 260 261 auto intType = type.cast<IntegerType>(); 262 LLVM_DEBUG(llvm::dbgs() << type << " converted to 32-bit for SPIR-V\n"); 263 return IntegerType::get(/*width=*/32, intType.getSignedness(), 264 targetEnv.getContext()); 265 } 266 267 /// Converts a vector `type` to a suitable type under the given `targetEnv`. 268 static Optional<Type> 269 convertVectorType(const spirv::TargetEnv &targetEnv, VectorType type, 270 Optional<spirv::StorageClass> storageClass = {}) { 271 if (!spirv::CompositeType::isValid(type)) { 272 // TODO: One-element vector types can be translated into scalar 273 // types. Vector types with more than four elements can be translated into 274 // array types. 275 LLVM_DEBUG(llvm::dbgs() 276 << type << " illegal: 1- and > 4-element unimplemented\n"); 277 return llvm::None; 278 } 279 280 // Get extension and capability requirements for the given type. 281 SmallVector<ArrayRef<spirv::Extension>, 1> extensions; 282 SmallVector<ArrayRef<spirv::Capability>, 2> capabilities; 283 type.cast<spirv::CompositeType>().getExtensions(extensions, storageClass); 284 type.cast<spirv::CompositeType>().getCapabilities(capabilities, storageClass); 285 286 // If all requirements are met, then we can accept this type as-is. 287 if (succeeded(checkCapabilityRequirements(type, targetEnv, capabilities)) && 288 succeeded(checkExtensionRequirements(type, targetEnv, extensions))) 289 return type; 290 291 auto elementType = convertScalarType( 292 targetEnv, type.getElementType().cast<spirv::ScalarType>(), storageClass); 293 if (elementType) 294 return VectorType::get(type.getShape(), *elementType); 295 return llvm::None; 296 } 297 298 /// Converts a tensor `type` to a suitable type under the given `targetEnv`. 299 /// 300 /// Note that this is mainly for lowering constant tensors.In SPIR-V one can 301 /// create composite constants with OpConstantComposite to embed relative large 302 /// constant values and use OpCompositeExtract and OpCompositeInsert to 303 /// manipulate, like what we do for vectors. 304 static Optional<Type> convertTensorType(const spirv::TargetEnv &targetEnv, 305 TensorType type) { 306 // TODO: Handle dynamic shapes. 307 if (!type.hasStaticShape()) { 308 LLVM_DEBUG(llvm::dbgs() 309 << type << " illegal: dynamic shape unimplemented\n"); 310 return llvm::None; 311 } 312 313 auto scalarType = type.getElementType().dyn_cast<spirv::ScalarType>(); 314 if (!scalarType) { 315 LLVM_DEBUG(llvm::dbgs() 316 << type << " illegal: cannot convert non-scalar element type\n"); 317 return llvm::None; 318 } 319 320 Optional<int64_t> scalarSize = getTypeNumBytes(scalarType); 321 Optional<int64_t> tensorSize = getTypeNumBytes(type); 322 if (!scalarSize || !tensorSize) { 323 LLVM_DEBUG(llvm::dbgs() 324 << type << " illegal: cannot deduce element count\n"); 325 return llvm::None; 326 } 327 328 auto arrayElemCount = *tensorSize / *scalarSize; 329 auto arrayElemType = convertScalarType(targetEnv, scalarType); 330 if (!arrayElemType) 331 return llvm::None; 332 Optional<int64_t> arrayElemSize = getTypeNumBytes(*arrayElemType); 333 if (!arrayElemSize) { 334 LLVM_DEBUG(llvm::dbgs() 335 << type << " illegal: cannot deduce converted element size\n"); 336 return llvm::None; 337 } 338 339 return spirv::ArrayType::get(*arrayElemType, arrayElemCount, *arrayElemSize); 340 } 341 342 static Optional<Type> convertMemrefType(const spirv::TargetEnv &targetEnv, 343 MemRefType type) { 344 Optional<spirv::StorageClass> storageClass = 345 SPIRVTypeConverter::getStorageClassForMemorySpace(type.getMemorySpace()); 346 if (!storageClass) { 347 LLVM_DEBUG(llvm::dbgs() 348 << type << " illegal: cannot convert memory space\n"); 349 return llvm::None; 350 } 351 352 Optional<Type> arrayElemType; 353 Type elementType = type.getElementType(); 354 if (auto vecType = elementType.dyn_cast<VectorType>()) { 355 arrayElemType = convertVectorType(targetEnv, vecType, storageClass); 356 } else if (auto scalarType = elementType.dyn_cast<spirv::ScalarType>()) { 357 arrayElemType = convertScalarType(targetEnv, scalarType, storageClass); 358 } else { 359 LLVM_DEBUG( 360 llvm::dbgs() 361 << type 362 << " unhandled: can only convert scalar or vector element type\n"); 363 return llvm::None; 364 } 365 if (!arrayElemType) 366 return llvm::None; 367 368 Optional<int64_t> elementSize = getTypeNumBytes(elementType); 369 if (!elementSize) { 370 LLVM_DEBUG(llvm::dbgs() 371 << type << " illegal: cannot deduce element size\n"); 372 return llvm::None; 373 } 374 375 if (!type.hasStaticShape()) { 376 auto arrayType = spirv::RuntimeArrayType::get(*arrayElemType, *elementSize); 377 // Wrap in a struct to satisfy Vulkan interface requirements. 378 auto structType = spirv::StructType::get(arrayType, 0); 379 return spirv::PointerType::get(structType, *storageClass); 380 } 381 382 Optional<int64_t> memrefSize = getTypeNumBytes(type); 383 if (!memrefSize) { 384 LLVM_DEBUG(llvm::dbgs() 385 << type << " illegal: cannot deduce element count\n"); 386 return llvm::None; 387 } 388 389 auto arrayElemCount = *memrefSize / *elementSize; 390 391 Optional<int64_t> arrayElemSize = getTypeNumBytes(*arrayElemType); 392 if (!arrayElemSize) { 393 LLVM_DEBUG(llvm::dbgs() 394 << type << " illegal: cannot deduce converted element size\n"); 395 return llvm::None; 396 } 397 398 auto arrayType = 399 spirv::ArrayType::get(*arrayElemType, arrayElemCount, *arrayElemSize); 400 401 // Wrap in a struct to satisfy Vulkan interface requirements. Memrefs with 402 // workgroup storage class do not need the struct to be laid out explicitly. 403 auto structType = *storageClass == spirv::StorageClass::Workgroup 404 ? spirv::StructType::get(arrayType) 405 : spirv::StructType::get(arrayType, 0); 406 return spirv::PointerType::get(structType, *storageClass); 407 } 408 409 SPIRVTypeConverter::SPIRVTypeConverter(spirv::TargetEnvAttr targetAttr) 410 : targetEnv(targetAttr) { 411 // Add conversions. The order matters here: later ones will be tried earlier. 412 413 // All other cases failed. Then we cannot convert this type. 414 addConversion([](Type type) { return llvm::None; }); 415 416 // Allow all SPIR-V dialect specific types. This assumes all builtin types 417 // adopted in the SPIR-V dialect (i.e., IntegerType, FloatType, VectorType) 418 // were tried before. 419 // 420 // TODO: this assumes that the SPIR-V types are valid to use in 421 // the given target environment, which should be the case if the whole 422 // pipeline is driven by the same target environment. Still, we probably still 423 // want to validate and convert to be safe. 424 addConversion([](spirv::SPIRVType type) { return type; }); 425 426 addConversion([](IndexType indexType) { 427 return SPIRVTypeConverter::getIndexType(indexType.getContext()); 428 }); 429 430 addConversion([this](IntegerType intType) -> Optional<Type> { 431 if (auto scalarType = intType.dyn_cast<spirv::ScalarType>()) 432 return convertScalarType(targetEnv, scalarType); 433 return llvm::None; 434 }); 435 436 addConversion([this](FloatType floatType) -> Optional<Type> { 437 if (auto scalarType = floatType.dyn_cast<spirv::ScalarType>()) 438 return convertScalarType(targetEnv, scalarType); 439 return llvm::None; 440 }); 441 442 addConversion([this](VectorType vectorType) { 443 return convertVectorType(targetEnv, vectorType); 444 }); 445 446 addConversion([this](TensorType tensorType) { 447 return convertTensorType(targetEnv, tensorType); 448 }); 449 450 addConversion([this](MemRefType memRefType) { 451 return convertMemrefType(targetEnv, memRefType); 452 }); 453 } 454 455 //===----------------------------------------------------------------------===// 456 // FuncOp Conversion Patterns 457 //===----------------------------------------------------------------------===// 458 459 namespace { 460 /// A pattern for rewriting function signature to convert arguments of functions 461 /// to be of valid SPIR-V types. 462 class FuncOpConversion final : public SPIRVOpLowering<FuncOp> { 463 public: 464 using SPIRVOpLowering<FuncOp>::SPIRVOpLowering; 465 466 LogicalResult 467 matchAndRewrite(FuncOp funcOp, ArrayRef<Value> operands, 468 ConversionPatternRewriter &rewriter) const override; 469 }; 470 } // namespace 471 472 LogicalResult 473 FuncOpConversion::matchAndRewrite(FuncOp funcOp, ArrayRef<Value> operands, 474 ConversionPatternRewriter &rewriter) const { 475 auto fnType = funcOp.getType(); 476 // TODO: support converting functions with one result. 477 if (fnType.getNumResults()) 478 return failure(); 479 480 TypeConverter::SignatureConversion signatureConverter(fnType.getNumInputs()); 481 for (auto argType : enumerate(funcOp.getType().getInputs())) { 482 auto convertedType = typeConverter.convertType(argType.value()); 483 if (!convertedType) 484 return failure(); 485 signatureConverter.addInputs(argType.index(), convertedType); 486 } 487 488 // Create the converted spv.func op. 489 auto newFuncOp = rewriter.create<spirv::FuncOp>( 490 funcOp.getLoc(), funcOp.getName(), 491 rewriter.getFunctionType(signatureConverter.getConvertedTypes(), 492 llvm::None)); 493 494 // Copy over all attributes other than the function name and type. 495 for (const auto &namedAttr : funcOp.getAttrs()) { 496 if (namedAttr.first != impl::getTypeAttrName() && 497 namedAttr.first != SymbolTable::getSymbolAttrName()) 498 newFuncOp->setAttr(namedAttr.first, namedAttr.second); 499 } 500 501 rewriter.inlineRegionBefore(funcOp.getBody(), newFuncOp.getBody(), 502 newFuncOp.end()); 503 if (failed(rewriter.convertRegionTypes(&newFuncOp.getBody(), typeConverter, 504 &signatureConverter))) 505 return failure(); 506 rewriter.eraseOp(funcOp); 507 return success(); 508 } 509 510 void mlir::populateBuiltinFuncToSPIRVPatterns( 511 MLIRContext *context, SPIRVTypeConverter &typeConverter, 512 OwningRewritePatternList &patterns) { 513 patterns.insert<FuncOpConversion>(context, typeConverter); 514 } 515 516 //===----------------------------------------------------------------------===// 517 // Builtin Variables 518 //===----------------------------------------------------------------------===// 519 520 static spirv::GlobalVariableOp getBuiltinVariable(Block &body, 521 spirv::BuiltIn builtin) { 522 // Look through all global variables in the given `body` block and check if 523 // there is a spv.globalVariable that has the same `builtin` attribute. 524 for (auto varOp : body.getOps<spirv::GlobalVariableOp>()) { 525 if (auto builtinAttr = varOp->getAttrOfType<StringAttr>( 526 spirv::SPIRVDialect::getAttributeName( 527 spirv::Decoration::BuiltIn))) { 528 auto varBuiltIn = spirv::symbolizeBuiltIn(builtinAttr.getValue()); 529 if (varBuiltIn && varBuiltIn.getValue() == builtin) { 530 return varOp; 531 } 532 } 533 } 534 return nullptr; 535 } 536 537 /// Gets name of global variable for a builtin. 538 static std::string getBuiltinVarName(spirv::BuiltIn builtin) { 539 return std::string("__builtin_var_") + stringifyBuiltIn(builtin).str() + "__"; 540 } 541 542 /// Gets or inserts a global variable for a builtin within `body` block. 543 static spirv::GlobalVariableOp 544 getOrInsertBuiltinVariable(Block &body, Location loc, spirv::BuiltIn builtin, 545 OpBuilder &builder) { 546 if (auto varOp = getBuiltinVariable(body, builtin)) 547 return varOp; 548 549 OpBuilder::InsertionGuard guard(builder); 550 builder.setInsertionPointToStart(&body); 551 552 spirv::GlobalVariableOp newVarOp; 553 switch (builtin) { 554 case spirv::BuiltIn::NumWorkgroups: 555 case spirv::BuiltIn::WorkgroupSize: 556 case spirv::BuiltIn::WorkgroupId: 557 case spirv::BuiltIn::LocalInvocationId: 558 case spirv::BuiltIn::GlobalInvocationId: { 559 auto ptrType = spirv::PointerType::get( 560 VectorType::get({3}, builder.getIntegerType(32)), 561 spirv::StorageClass::Input); 562 std::string name = getBuiltinVarName(builtin); 563 newVarOp = 564 builder.create<spirv::GlobalVariableOp>(loc, ptrType, name, builtin); 565 break; 566 } 567 case spirv::BuiltIn::SubgroupId: 568 case spirv::BuiltIn::NumSubgroups: 569 case spirv::BuiltIn::SubgroupSize: { 570 auto ptrType = spirv::PointerType::get(builder.getIntegerType(32), 571 spirv::StorageClass::Input); 572 std::string name = getBuiltinVarName(builtin); 573 newVarOp = 574 builder.create<spirv::GlobalVariableOp>(loc, ptrType, name, builtin); 575 break; 576 } 577 default: 578 emitError(loc, "unimplemented builtin variable generation for ") 579 << stringifyBuiltIn(builtin); 580 } 581 return newVarOp; 582 } 583 584 Value mlir::spirv::getBuiltinVariableValue(Operation *op, 585 spirv::BuiltIn builtin, 586 OpBuilder &builder) { 587 Operation *parent = SymbolTable::getNearestSymbolTable(op->getParentOp()); 588 if (!parent) { 589 op->emitError("expected operation to be within a module-like op"); 590 return nullptr; 591 } 592 593 spirv::GlobalVariableOp varOp = getOrInsertBuiltinVariable( 594 *parent->getRegion(0).begin(), op->getLoc(), builtin, builder); 595 Value ptr = builder.create<spirv::AddressOfOp>(op->getLoc(), varOp); 596 return builder.create<spirv::LoadOp>(op->getLoc(), ptr); 597 } 598 599 //===----------------------------------------------------------------------===// 600 // Index calculation 601 //===----------------------------------------------------------------------===// 602 603 spirv::AccessChainOp mlir::spirv::getElementPtr( 604 SPIRVTypeConverter &typeConverter, MemRefType baseType, Value basePtr, 605 ValueRange indices, Location loc, OpBuilder &builder) { 606 // Get base and offset of the MemRefType and verify they are static. 607 608 int64_t offset; 609 SmallVector<int64_t, 4> strides; 610 if (failed(getStridesAndOffset(baseType, strides, offset)) || 611 llvm::is_contained(strides, MemRefType::getDynamicStrideOrOffset()) || 612 offset == MemRefType::getDynamicStrideOrOffset()) { 613 return nullptr; 614 } 615 616 auto indexType = typeConverter.getIndexType(builder.getContext()); 617 618 SmallVector<Value, 2> linearizedIndices; 619 // Add a '0' at the start to index into the struct. 620 auto zero = spirv::ConstantOp::getZero(indexType, loc, builder); 621 linearizedIndices.push_back(zero); 622 623 if (baseType.getRank() == 0) { 624 linearizedIndices.push_back(zero); 625 } else { 626 // TODO: Instead of this logic, use affine.apply and add patterns for 627 // lowering affine.apply to standard ops. These will get lowered to SPIR-V 628 // ops by the DialectConversion framework. 629 Value ptrLoc = builder.create<spirv::ConstantOp>( 630 loc, indexType, IntegerAttr::get(indexType, offset)); 631 assert(indices.size() == strides.size() && 632 "must provide indices for all dimensions"); 633 for (auto index : llvm::enumerate(indices)) { 634 Value strideVal = builder.create<spirv::ConstantOp>( 635 loc, indexType, IntegerAttr::get(indexType, strides[index.index()])); 636 Value update = 637 builder.create<spirv::IMulOp>(loc, strideVal, index.value()); 638 ptrLoc = builder.create<spirv::IAddOp>(loc, ptrLoc, update); 639 } 640 linearizedIndices.push_back(ptrLoc); 641 } 642 return builder.create<spirv::AccessChainOp>(loc, basePtr, linearizedIndices); 643 } 644 645 //===----------------------------------------------------------------------===// 646 // Set ABI attributes for lowering entry functions. 647 //===----------------------------------------------------------------------===// 648 649 LogicalResult 650 mlir::spirv::setABIAttrs(spirv::FuncOp funcOp, 651 spirv::EntryPointABIAttr entryPointInfo, 652 ArrayRef<spirv::InterfaceVarABIAttr> argABIInfo) { 653 // Set the attributes for argument and the function. 654 StringRef argABIAttrName = spirv::getInterfaceVarABIAttrName(); 655 for (auto argIndex : llvm::seq<unsigned>(0, argABIInfo.size())) { 656 funcOp.setArgAttr(argIndex, argABIAttrName, argABIInfo[argIndex]); 657 } 658 funcOp->setAttr(spirv::getEntryPointABIAttrName(), entryPointInfo); 659 return success(); 660 } 661 662 //===----------------------------------------------------------------------===// 663 // SPIR-V ConversionTarget 664 //===----------------------------------------------------------------------===// 665 666 std::unique_ptr<spirv::SPIRVConversionTarget> 667 spirv::SPIRVConversionTarget::get(spirv::TargetEnvAttr targetAttr) { 668 std::unique_ptr<SPIRVConversionTarget> target( 669 // std::make_unique does not work here because the constructor is private. 670 new SPIRVConversionTarget(targetAttr)); 671 SPIRVConversionTarget *targetPtr = target.get(); 672 target->addDynamicallyLegalDialect<SPIRVDialect>( 673 // We need to capture the raw pointer here because it is stable: 674 // target will be destroyed once this function is returned. 675 [targetPtr](Operation *op) { return targetPtr->isLegalOp(op); }); 676 return target; 677 } 678 679 spirv::SPIRVConversionTarget::SPIRVConversionTarget( 680 spirv::TargetEnvAttr targetAttr) 681 : ConversionTarget(*targetAttr.getContext()), targetEnv(targetAttr) {} 682 683 bool spirv::SPIRVConversionTarget::isLegalOp(Operation *op) { 684 // Make sure this op is available at the given version. Ops not implementing 685 // QueryMinVersionInterface/QueryMaxVersionInterface are available to all 686 // SPIR-V versions. 687 if (auto minVersion = dyn_cast<spirv::QueryMinVersionInterface>(op)) 688 if (minVersion.getMinVersion() > this->targetEnv.getVersion()) { 689 LLVM_DEBUG(llvm::dbgs() 690 << op->getName() << " illegal: requiring min version " 691 << spirv::stringifyVersion(minVersion.getMinVersion()) 692 << "\n"); 693 return false; 694 } 695 if (auto maxVersion = dyn_cast<spirv::QueryMaxVersionInterface>(op)) 696 if (maxVersion.getMaxVersion() < this->targetEnv.getVersion()) { 697 LLVM_DEBUG(llvm::dbgs() 698 << op->getName() << " illegal: requiring max version " 699 << spirv::stringifyVersion(maxVersion.getMaxVersion()) 700 << "\n"); 701 return false; 702 } 703 704 // Make sure this op's required extensions are allowed to use. Ops not 705 // implementing QueryExtensionInterface do not require extensions to be 706 // available. 707 if (auto extensions = dyn_cast<spirv::QueryExtensionInterface>(op)) 708 if (failed(checkExtensionRequirements(op->getName(), this->targetEnv, 709 extensions.getExtensions()))) 710 return false; 711 712 // Make sure this op's required extensions are allowed to use. Ops not 713 // implementing QueryCapabilityInterface do not require capabilities to be 714 // available. 715 if (auto capabilities = dyn_cast<spirv::QueryCapabilityInterface>(op)) 716 if (failed(checkCapabilityRequirements(op->getName(), this->targetEnv, 717 capabilities.getCapabilities()))) 718 return false; 719 720 SmallVector<Type, 4> valueTypes; 721 valueTypes.append(op->operand_type_begin(), op->operand_type_end()); 722 valueTypes.append(op->result_type_begin(), op->result_type_end()); 723 724 // Special treatment for global variables, whose type requirements are 725 // conveyed by type attributes. 726 if (auto globalVar = dyn_cast<spirv::GlobalVariableOp>(op)) 727 valueTypes.push_back(globalVar.type()); 728 729 // Make sure the op's operands/results use types that are allowed by the 730 // target environment. 731 SmallVector<ArrayRef<spirv::Extension>, 4> typeExtensions; 732 SmallVector<ArrayRef<spirv::Capability>, 8> typeCapabilities; 733 for (Type valueType : valueTypes) { 734 typeExtensions.clear(); 735 valueType.cast<spirv::SPIRVType>().getExtensions(typeExtensions); 736 if (failed(checkExtensionRequirements(op->getName(), this->targetEnv, 737 typeExtensions))) 738 return false; 739 740 typeCapabilities.clear(); 741 valueType.cast<spirv::SPIRVType>().getCapabilities(typeCapabilities); 742 if (failed(checkCapabilityRequirements(op->getName(), this->targetEnv, 743 typeCapabilities))) 744 return false; 745 } 746 747 return true; 748 } 749