generic.cpp 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  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. #include "toolchain/sem_ir/generic.h"
  5. namespace Carbon::SemIR {
  6. class GenericInstanceStore::KeyContext {
  7. public:
  8. // A lookup key for a generic instance.
  9. struct Key {
  10. GenericId generic_id;
  11. InstBlockId args_id;
  12. friend auto operator==(const Key&, const Key&) -> bool = default;
  13. };
  14. explicit KeyContext(llvm::ArrayRef<GenericInstance> instances)
  15. : instances_(instances) {}
  16. auto AsKey(GenericInstanceId id) const -> Key {
  17. const auto& instance = instances_[id.index];
  18. return {.generic_id = instance.generic_id, .args_id = instance.args_id};
  19. }
  20. static auto AsKey(Key key) -> Key { return key; }
  21. template <typename KeyT>
  22. auto HashKey(KeyT key, uint64_t seed) const -> HashCode {
  23. return HashValue(AsKey(key), seed);
  24. }
  25. template <typename LHSKeyT, typename RHSKeyT>
  26. auto KeyEq(const LHSKeyT& lhs_key, const RHSKeyT& rhs_key) const -> bool {
  27. return AsKey(lhs_key) == AsKey(rhs_key);
  28. }
  29. private:
  30. llvm::ArrayRef<GenericInstance> instances_;
  31. };
  32. auto GenericInstanceStore::GetOrAdd(GenericId generic_id, InstBlockId args_id)
  33. -> GenericInstanceId {
  34. return lookup_table_
  35. .Insert(
  36. KeyContext::Key{.generic_id = generic_id, .args_id = args_id},
  37. [&] {
  38. return generic_instances_.Add(
  39. {.generic_id = generic_id, .args_id = args_id});
  40. },
  41. KeyContext(generic_instances_.array_ref()))
  42. .key();
  43. }
  44. } // namespace Carbon::SemIR