| 463 | // |
| 464 | namespace { |
| 465 | struct ConstantManager { |
| 466 | LogicalResult addConstant(Attribute attr, uint64_t &index) { |
| 467 | auto it = constantsMap.find(attr); |
| 468 | if (it != constantsMap.end()) { |
| 469 | index = std::distance(constantsMap.begin(), it); |
| 470 | return success(); |
| 471 | } |
| 472 | SmallVector<char> data; |
| 473 | llvm::raw_svector_ostream dataStream(data); |
| 474 | EncodingWriter writer(dataStream); |
| 475 | if (failed(serializeAttribute(attr, writer))) |
| 476 | return emitError(UnknownLoc::get(attr.getContext()), |
| 477 | "failed to serialize attribute"); |
| 478 | index = constantsMap.size(); |
| 479 | constantsMap[attr] = std::move(data); |
| 480 | return success(); |
| 481 | } |
| 482 | |
| 483 | // Look up a constant by attribute without adding it |
| 484 | LogicalResult getConstantIndex(Attribute attr, uint64_t &index) const { |
| 485 | auto it = constantsMap.find(attr); |
| 486 | if (it != constantsMap.end()) { |
| 487 | index = std::distance(constantsMap.begin(), it); |
| 488 | return success(); |
| 489 | } |
| 490 | return failure(); |
| 491 | } |
| 492 | |
| 493 | // Provide access to the constant map |
| 494 | const llvm::MapVector<Attribute, SmallVector<char>> &getConstantsMap() const { |
| 495 | return constantsMap; |
| 496 | } |
| 497 | |
| 498 | /// Serializes a single MLIR attribute into its raw byte representation. |
| 499 | /// This function handles different attribute types, focusing on scalar |
| 500 | /// and dense element attributes suitable for the constant pool. |
| 501 | LogicalResult serializeAttribute(Attribute attr, EncodingWriter &writer) { |
| 502 | if (auto denseAttr = dyn_cast<DenseElementsAttr>(attr)) { |
| 503 | // Get the raw data buffer in little-endian format. |
| 504 | ArrayRef<char> rawData = denseAttr.getRawData(); |
| 505 | // Write the size of the raw buffer. |
| 506 | writer.writeVarInt(rawData.size()); |
| 507 | // Write the raw buffer content. |
| 508 | writer.write(rawData.data(), rawData.size()); |
| 509 | return success(); |
| 510 | } else if (auto intAttr = dyn_cast<IntegerAttr>(attr)) { |
| 511 | APInt value = intAttr.getValue(); |
| 512 | writer.writeLE<uint64_t>(value.getZExtValue()); |
| 513 | return success(); |
| 514 | } else if (auto boolAttr = dyn_cast<BoolAttr>(attr)) { |
| 515 | uint8_t boolValue = boolAttr.getValue() ? 0x01 : 0x00; |
| 516 | writer.writeByte(boolValue); |
| 517 | return success(); |
| 518 | } else if (auto floatAttr = dyn_cast<FloatAttr>(attr)) { |
| 519 | writeAPFloatRepresentation(floatAttr.getValue(), writer); |
| 520 | return success(); |
| 521 | } |
| 522 | return emitError(UnknownLoc::get(attr.getContext()), |
nothing calls this directly
no outgoing calls
no test coverage detected