type.cpp 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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/type.h"
  5. #include "toolchain/sem_ir/file.h"
  6. namespace Carbon::SemIR {
  7. auto TypeStore::GetInstId(TypeId type_id) const -> InstId {
  8. return file_->constant_values().GetInstId(GetConstantId(type_id));
  9. }
  10. auto TypeStore::GetAsInst(TypeId type_id) const -> Inst {
  11. return file_->insts().Get(GetInstId(type_id));
  12. }
  13. auto TypeStore::GetObjectRepr(TypeId type_id) const -> TypeId {
  14. type_id = GetUnqualifiedType(type_id);
  15. auto class_type = TryGetAs<ClassType>(type_id);
  16. if (!class_type) {
  17. return type_id;
  18. }
  19. const auto& class_info = file_->classes().Get(class_type->class_id);
  20. if (!class_info.is_defined()) {
  21. return TypeId::Invalid;
  22. }
  23. return class_info.GetObjectRepr(*file_, class_type->specific_id);
  24. }
  25. auto TypeStore::GetUnqualifiedType(TypeId type_id) const -> TypeId {
  26. if (auto const_type = TryGetAs<ConstType>(type_id)) {
  27. return const_type->inner_id;
  28. }
  29. return type_id;
  30. }
  31. static auto TryGetIntTypeInfo(const File& file, TypeId type_id)
  32. -> std::optional<TypeStore::IntTypeInfo> {
  33. auto object_repr_id = file.types().GetObjectRepr(type_id);
  34. if (!object_repr_id.is_valid()) {
  35. return std::nullopt;
  36. }
  37. auto inst_id = file.types().GetInstId(object_repr_id);
  38. if (inst_id == IntLiteralType::SingletonInstId) {
  39. // `Core.IntLiteral` has an unknown bit-width.
  40. return TypeStore::IntTypeInfo{.is_signed = true,
  41. .bit_width = IntId::Invalid};
  42. }
  43. auto int_type = file.insts().TryGetAs<IntType>(inst_id);
  44. if (!int_type) {
  45. return std::nullopt;
  46. }
  47. auto bit_width_inst = file.insts().TryGetAs<IntValue>(int_type->bit_width_id);
  48. return TypeStore::IntTypeInfo{
  49. .is_signed = int_type->int_kind.is_signed(),
  50. .bit_width = bit_width_inst ? bit_width_inst->int_id : IntId::Invalid};
  51. }
  52. auto TypeStore::IsSignedInt(TypeId int_type_id) const -> bool {
  53. auto int_info = TryGetIntTypeInfo(*file_, int_type_id);
  54. return int_info && int_info->is_signed;
  55. }
  56. auto TypeStore::GetIntTypeInfo(TypeId int_type_id) const -> IntTypeInfo {
  57. auto int_info = TryGetIntTypeInfo(*file_, int_type_id);
  58. CARBON_CHECK(int_info, "Type {0} is not an integer type", int_type_id);
  59. return *int_info;
  60. }
  61. } // namespace Carbon::SemIR