singleton_insts.h 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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_SEM_IR_SINGLETON_INSTS_H_
  5. #define CARBON_TOOLCHAIN_SEM_IR_SINGLETON_INSTS_H_
  6. #include "toolchain/sem_ir/ids.h"
  7. #include "toolchain/sem_ir/inst_kind.h"
  8. namespace Carbon::SemIR {
  9. // The canonical list of singleton kinds. The order of `TypeType` is
  10. // significant because other singletons use it as a type.
  11. static constexpr std::array SingletonInstKinds = {
  12. InstKind::TypeType,
  13. InstKind::AutoType,
  14. InstKind::BoolType,
  15. InstKind::BoundMethodType,
  16. InstKind::ErrorInst,
  17. InstKind::ImplWitnessTablePlaceholder,
  18. InstKind::InstType,
  19. InstKind::IntLiteralType,
  20. InstKind::LegacyFloatType,
  21. InstKind::NamespaceType,
  22. InstKind::SpecificFunctionType,
  23. InstKind::StringType,
  24. InstKind::VtableType,
  25. InstKind::WitnessType,
  26. };
  27. // Returns true if the InstKind is a singleton.
  28. constexpr auto IsSingletonInstKind(InstKind kind) -> bool;
  29. // Provides the TypeInstId for singleton instructions. These are exposed as
  30. // `InstT::TypeInstId` in `typed_insts.h`.
  31. template <InstKind::RawEnumType Kind>
  32. requires(IsSingletonInstKind(InstKind::Make(Kind)))
  33. constexpr auto MakeSingletonTypeInstId() -> TypeInstId;
  34. // Returns true if the InstId corresponds to a singleton inst.
  35. constexpr auto IsSingletonInstId(InstId id) -> bool {
  36. return id.index >= 0 &&
  37. id.index < static_cast<int32_t>(SingletonInstKinds.size());
  38. }
  39. // Only implementation details are below.
  40. namespace Internal {
  41. // Returns the index for a singleton instruction, or -1 if it's not a singleton.
  42. constexpr auto GetSingletonInstIndex(InstKind kind) -> int32_t {
  43. for (int32_t i = 0; i < static_cast<int32_t>(SingletonInstKinds.size());
  44. ++i) {
  45. if (SingletonInstKinds[i] == kind) {
  46. return i;
  47. }
  48. }
  49. return -1;
  50. }
  51. } // namespace Internal
  52. constexpr auto IsSingletonInstKind(InstKind kind) -> bool {
  53. return Internal::GetSingletonInstIndex(kind) >= 0;
  54. }
  55. template <InstKind::RawEnumType Kind>
  56. requires(IsSingletonInstKind(InstKind::Make(Kind)))
  57. constexpr auto MakeSingletonTypeInstId() -> TypeInstId {
  58. auto index = Internal::GetSingletonInstIndex(InstKind::Make(Kind));
  59. return TypeInstId(index);
  60. }
  61. } // namespace Carbon::SemIR
  62. #endif // CARBON_TOOLCHAIN_SEM_IR_SINGLETON_INSTS_H_