singleton_insts.h 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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, InstKind::AutoType,
  13. InstKind::BoolType, InstKind::BoundMethodType,
  14. InstKind::CharLiteralType, InstKind::ErrorInst,
  15. InstKind::FloatLiteralType, InstKind::ImplWitnessTablePlaceholder,
  16. InstKind::InstType, InstKind::IntLiteralType,
  17. InstKind::NamespaceType, InstKind::SpecificFunctionType,
  18. InstKind::VtableType, InstKind::WitnessType,
  19. };
  20. // Returns true if the InstKind is a singleton.
  21. constexpr auto IsSingletonInstKind(InstKind kind) -> bool;
  22. // Provides the TypeInstId for singleton instructions. These are exposed as
  23. // `InstT::TypeInstId` in `typed_insts.h`.
  24. template <InstKind::RawEnumType Kind>
  25. requires(IsSingletonInstKind(InstKind::Make(Kind)))
  26. constexpr auto MakeSingletonTypeInstId() -> TypeInstId;
  27. // Returns true if the InstId corresponds to a singleton inst.
  28. constexpr auto IsSingletonInstId(InstId id) -> bool {
  29. return id.index >= 0 &&
  30. id.index < static_cast<int32_t>(SingletonInstKinds.size());
  31. }
  32. // Only implementation details are below.
  33. namespace Internal {
  34. // Returns the index for a singleton instruction, or -1 if it's not a singleton.
  35. constexpr auto GetSingletonInstIndex(InstKind kind) -> int32_t {
  36. for (int32_t i = 0; i < static_cast<int32_t>(SingletonInstKinds.size());
  37. ++i) {
  38. if (SingletonInstKinds[i] == kind) {
  39. return i;
  40. }
  41. }
  42. return -1;
  43. }
  44. } // namespace Internal
  45. constexpr auto IsSingletonInstKind(InstKind kind) -> bool {
  46. return Internal::GetSingletonInstIndex(kind) >= 0;
  47. }
  48. template <InstKind::RawEnumType Kind>
  49. requires(IsSingletonInstKind(InstKind::Make(Kind)))
  50. constexpr auto MakeSingletonTypeInstId() -> TypeInstId {
  51. auto index = Internal::GetSingletonInstIndex(InstKind::Make(Kind));
  52. return TypeInstId(index);
  53. }
  54. } // namespace Carbon::SemIR
  55. #endif // CARBON_TOOLCHAIN_SEM_IR_SINGLETON_INSTS_H_