block_value_store.h 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161
  1. // Part of the Carbon Language project, under the Apache License v2.0 with LLVM
  2. // Exceptions. See /LICENSE for license information.
  3. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. #ifndef CARBON_TOOLCHAIN_BASE_BLOCK_VALUE_STORE_H_
  5. #define CARBON_TOOLCHAIN_BASE_BLOCK_VALUE_STORE_H_
  6. #include <type_traits>
  7. #include "common/check.h"
  8. #include "common/set.h"
  9. #include "llvm/Support/Allocator.h"
  10. #include "toolchain/base/id_tag.h"
  11. #include "toolchain/base/mem_usage.h"
  12. #include "toolchain/base/value_store.h"
  13. #include "toolchain/base/yaml.h"
  14. namespace Carbon::SemIR {
  15. // Provides a block-based ValueStore, which uses slab allocation of added
  16. // blocks. This allows references to values to outlast vector resizes that might
  17. // otherwise invalidate references.
  18. //
  19. // BlockValueStore is used as-is, but there are also children that expose the
  20. // protected members for type-specific functionality.
  21. template <typename IdT, typename ElementT, typename TagIdT = Untagged>
  22. class BlockValueStore
  23. : public Yaml::Printable<BlockValueStore<IdT, ElementT, TagIdT>> {
  24. public:
  25. using IdType = IdT;
  26. using IdTagType = IdTag<IdT, TagIdT>;
  27. using ElementType = ElementT;
  28. using RefType = llvm::MutableArrayRef<ElementT>;
  29. using ConstRefType = llvm::ArrayRef<ElementT>;
  30. explicit BlockValueStore(llvm::BumpPtrAllocator& allocator,
  31. IdTagType::TagIdType tag_id,
  32. int32_t initial_reserved_ids = 0)
  33. requires(!IdTagIsUntagged<IdTagType>)
  34. : allocator_(&allocator), values_(tag_id, initial_reserved_ids) {
  35. auto empty = RefType();
  36. auto empty_val = canonical_blocks_.Insert(
  37. empty, [&] { return values_.Add(empty); }, KeyContext(this));
  38. CARBON_CHECK(empty_val.key() == IdT::Empty);
  39. }
  40. // Adds a block with the given content, returning an ID to reference it.
  41. auto Add(ConstRefType content) -> IdT {
  42. if (content.empty()) {
  43. return IdT::Empty;
  44. }
  45. return values_.Add(AllocateCopy(content));
  46. }
  47. // Returns the requested block.
  48. auto Get(IdT id) const -> ConstRefType { return values_.Get(id); }
  49. // Returns a mutable view of the requested block. This operation should be
  50. // avoided where possible; we generally want blocks to be immutable once
  51. // created.
  52. auto GetMutable(IdT id) -> RefType { return values_.Get(id); }
  53. // Returns a new block formed by applying `transform(elem_id)` to each element
  54. // in the specified block.
  55. template <typename TransformFnT>
  56. auto Transform(IdT id, TransformFnT transform) -> IdT {
  57. llvm::SmallVector<ElementType> block(llvm::map_range(Get(id), transform));
  58. return Add(block);
  59. }
  60. // Adds a block or finds an existing canonical block with the given content,
  61. // and returns an ID to reference it.
  62. auto AddCanonical(ConstRefType content) -> IdT {
  63. if (content.empty()) {
  64. return IdT::Empty;
  65. }
  66. auto result = canonical_blocks_.Insert(
  67. content, [&] { return Add(content); }, KeyContext(this));
  68. return result.key();
  69. }
  70. // Promotes an existing block ID to a canonical block ID, or returns an
  71. // existing canonical block ID if the block was already added. The specified
  72. // block must not be modified after this point.
  73. auto MakeCanonical(IdT id) -> IdT {
  74. // Get the content first so that we don't have unnecessary translation of
  75. // the `id` into the content during insertion.
  76. auto result = canonical_blocks_.Insert(
  77. Get(id), [id] { return id; }, KeyContext(this));
  78. return result.key();
  79. }
  80. auto OutputYaml() const -> Yaml::OutputMapping {
  81. return Yaml::OutputMapping([&](Yaml::OutputMapping::Map map) {
  82. for (auto [block_id, block] : values_.enumerate()) {
  83. map.Add(PrintToString(block_id),
  84. Yaml::OutputMapping([&](Yaml::OutputMapping::Map map) {
  85. for (auto [i, elem_id] : llvm::enumerate(block)) {
  86. map.Add(llvm::itostr(i), Yaml::OutputScalar(elem_id));
  87. }
  88. }));
  89. }
  90. });
  91. }
  92. // Collects memory usage of members.
  93. auto CollectMemUsage(MemUsage& mem_usage, llvm::StringRef label) const
  94. -> void {
  95. mem_usage.Collect(MemUsage::ConcatLabel(label, "values_"), values_);
  96. mem_usage.Collect(MemUsage::ConcatLabel(label, "canonical_blocks_"),
  97. canonical_blocks_, KeyContext(this));
  98. }
  99. auto size() const -> int { return values_.size(); }
  100. auto GetRawIndex(IdT id) const -> int { return values_.GetRawIndex(id); }
  101. protected:
  102. // Allocates a copy of the given data using our slab allocator.
  103. auto AllocateCopy(ConstRefType data) -> RefType {
  104. auto result = AllocateUninitialized(data.size());
  105. std::uninitialized_copy(data.begin(), data.end(), result.begin());
  106. return result;
  107. }
  108. // Allocates an uninitialized array using our slab allocator.
  109. auto AllocateUninitialized(size_t size) -> RefType {
  110. // We're not going to run a destructor, so ensure that's OK.
  111. static_assert(std::is_trivially_destructible_v<ElementType>);
  112. auto storage = static_cast<ElementType*>(
  113. allocator_->Allocate(size * sizeof(ElementType), alignof(ElementType)));
  114. return RefType(storage, size);
  115. }
  116. // Allow children to have more complex value handling.
  117. auto values() -> ValueStore<IdT, RefType, TagIdT>& { return values_; }
  118. private:
  119. class KeyContext;
  120. llvm::BumpPtrAllocator* allocator_;
  121. ValueStore<IdT, RefType, TagIdT> values_;
  122. Set<IdT, /*SmallSize=*/0, KeyContext> canonical_blocks_;
  123. };
  124. template <typename IdT, typename ElementT, typename TagIdT>
  125. class BlockValueStore<IdT, ElementT, TagIdT>::KeyContext
  126. : public TranslatingKeyContext<KeyContext> {
  127. public:
  128. explicit KeyContext(const BlockValueStore* store) : store_(store) {}
  129. auto TranslateKey(IdT id) const -> ConstRefType { return store_->Get(id); }
  130. private:
  131. const BlockValueStore* store_;
  132. };
  133. } // namespace Carbon::SemIR
  134. #endif // CARBON_TOOLCHAIN_BASE_BLOCK_VALUE_STORE_H_