ids.h 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568
  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_IDS_H_
  5. #define CARBON_TOOLCHAIN_SEM_IR_IDS_H_
  6. #include "common/check.h"
  7. #include "common/ostream.h"
  8. #include "toolchain/base/index_base.h"
  9. #include "toolchain/base/value_store.h"
  10. #include "toolchain/diagnostics/diagnostic_emitter.h"
  11. #include "toolchain/parse/node_ids.h"
  12. #include "toolchain/sem_ir/builtin_kind.h"
  13. namespace Carbon::SemIR {
  14. // Forward declare indexed types, for integration with ValueStore.
  15. class File;
  16. class Inst;
  17. struct BindNameInfo;
  18. struct Class;
  19. struct Function;
  20. struct ImportIR;
  21. struct ImportIRInst;
  22. struct Interface;
  23. struct Impl;
  24. struct NameScope;
  25. struct TypeInfo;
  26. // The ID of an instruction.
  27. struct InstId : public IdBase, public Printable<InstId> {
  28. using ValueType = Inst;
  29. // An explicitly invalid instruction ID.
  30. static const InstId Invalid;
  31. // Builtin instruction IDs.
  32. #define CARBON_SEM_IR_BUILTIN_KIND_NAME(Name) static const InstId Builtin##Name;
  33. #include "toolchain/sem_ir/builtin_kind.def"
  34. // The namespace for a `package` expression.
  35. static const InstId PackageNamespace;
  36. // Returns the instruction ID for a builtin. This relies on File guarantees
  37. // for builtin ImportRefUsed placement.
  38. static constexpr auto ForBuiltin(BuiltinKind kind) -> InstId {
  39. return InstId(kind.AsInt());
  40. }
  41. using IdBase::IdBase;
  42. // Returns true if the instruction is a builtin. Requires is_valid.
  43. auto is_builtin() const -> bool {
  44. CARBON_CHECK(is_valid());
  45. return index < BuiltinKind::ValidCount;
  46. }
  47. // Returns the BuiltinKind. Requires is_builtin.
  48. auto builtin_kind() const -> BuiltinKind {
  49. CARBON_CHECK(is_builtin());
  50. return BuiltinKind::FromInt(index);
  51. }
  52. auto Print(llvm::raw_ostream& out) const -> void {
  53. out << "inst";
  54. if (!is_valid()) {
  55. IdBase::Print(out);
  56. } else if (is_builtin()) {
  57. out << builtin_kind();
  58. } else {
  59. // Use the `+` as a small reminder that this is a delta, rather than an
  60. // absolute index.
  61. out << "+" << index - BuiltinKind::ValidCount;
  62. }
  63. }
  64. };
  65. constexpr InstId InstId::Invalid = InstId(InvalidIndex);
  66. #define CARBON_SEM_IR_BUILTIN_KIND_NAME(Name) \
  67. constexpr InstId InstId::Builtin##Name = \
  68. InstId::ForBuiltin(BuiltinKind::Name);
  69. #include "toolchain/sem_ir/builtin_kind.def"
  70. // The package namespace will be the instruction after builtins.
  71. constexpr InstId InstId::PackageNamespace = InstId(BuiltinKind::ValidCount);
  72. // The ID of a constant value of an expression. An expression is either:
  73. //
  74. // - a template constant, with an immediate value, such as `42` or `i32*` or
  75. // `("hello", "world")`, or
  76. // - a symbolic constant, whose value includes a symbolic parameter, such as
  77. // `Vector(T*)`, or
  78. // - a runtime expression, such as `Print("hello")`.
  79. struct ConstantId : public IdBase, public Printable<ConstantId> {
  80. // An ID for an expression that is not constant.
  81. static const ConstantId NotConstant;
  82. // An ID for an expression whose phase cannot be determined because it
  83. // contains an error. This is always modeled as a template constant.
  84. static const ConstantId Error;
  85. // An explicitly invalid ID.
  86. static const ConstantId Invalid;
  87. // Returns the constant ID corresponding to a template constant, which should
  88. // either be in the `constants` block in the file or should be known to be
  89. // unique.
  90. static constexpr auto ForTemplateConstant(InstId const_id) -> ConstantId {
  91. return ConstantId(const_id.index + IndexOffset);
  92. }
  93. // Returns the constant ID corresponding to a symbolic constant, which should
  94. // either be in the `constants` block in the file or should be known to be
  95. // unique.
  96. static constexpr auto ForSymbolicConstant(InstId const_id) -> ConstantId {
  97. return ConstantId(-const_id.index - IndexOffset);
  98. }
  99. using IdBase::IdBase;
  100. // Returns whether this represents a constant. Requires is_valid.
  101. auto is_constant() const -> bool {
  102. CARBON_CHECK(is_valid());
  103. return *this != ConstantId::NotConstant;
  104. }
  105. // Returns whether this represents a symbolic constant. Requires is_valid.
  106. auto is_symbolic() const -> bool {
  107. CARBON_CHECK(is_valid());
  108. return index <= -IndexOffset;
  109. }
  110. // Returns whether this represents a template constant. Requires is_valid.
  111. auto is_template() const -> bool {
  112. CARBON_CHECK(is_valid());
  113. return index >= IndexOffset;
  114. }
  115. // Returns the instruction that describes this constant value, or
  116. // InstId::Invalid for a runtime value. Requires is_valid.
  117. constexpr auto inst_id() const -> InstId {
  118. CARBON_CHECK(is_valid());
  119. return InstId(Abs(index) - IndexOffset);
  120. }
  121. auto Print(llvm::raw_ostream& out) const -> void {
  122. if (!is_valid()) {
  123. IdBase::Print(out);
  124. } else if (is_template()) {
  125. out << "template " << inst_id();
  126. } else if (is_symbolic()) {
  127. out << "symbolic " << inst_id();
  128. } else {
  129. out << "runtime";
  130. }
  131. }
  132. private:
  133. // TODO: C++23 makes std::abs constexpr, but until then we mirror std::abs
  134. // logic here. LLVM should still optimize this.
  135. static constexpr auto Abs(int32_t i) -> int32_t { return i > 0 ? i : -i; }
  136. static constexpr int32_t NotConstantIndex = InvalidIndex - 1;
  137. // The offset of InstId indices to ConstantId indices.
  138. static constexpr int32_t IndexOffset = -NotConstantIndex + 1;
  139. };
  140. constexpr ConstantId ConstantId::NotConstant = ConstantId(NotConstantIndex);
  141. static_assert(ConstantId::NotConstant.inst_id() == InstId::Invalid);
  142. constexpr ConstantId ConstantId::Error =
  143. ConstantId::ForTemplateConstant(InstId::BuiltinError);
  144. constexpr ConstantId ConstantId::Invalid = ConstantId(InvalidIndex);
  145. // The ID of a bind name.
  146. struct BindNameId : public IdBase, public Printable<BindNameId> {
  147. using ValueType = BindNameInfo;
  148. // An explicitly invalid function ID.
  149. static const BindNameId Invalid;
  150. using IdBase::IdBase;
  151. auto Print(llvm::raw_ostream& out) const -> void {
  152. out << "bindName";
  153. IdBase::Print(out);
  154. }
  155. };
  156. constexpr BindNameId BindNameId::Invalid = BindNameId(InvalidIndex);
  157. // The ID of a function.
  158. struct FunctionId : public IdBase, public Printable<FunctionId> {
  159. using ValueType = Function;
  160. // An explicitly invalid function ID.
  161. static const FunctionId Invalid;
  162. using IdBase::IdBase;
  163. auto Print(llvm::raw_ostream& out) const -> void {
  164. out << "function";
  165. IdBase::Print(out);
  166. }
  167. };
  168. constexpr FunctionId FunctionId::Invalid = FunctionId(InvalidIndex);
  169. // The ID of a class.
  170. struct ClassId : public IdBase, public Printable<ClassId> {
  171. using ValueType = Class;
  172. // An explicitly invalid class ID.
  173. static const ClassId Invalid;
  174. using IdBase::IdBase;
  175. auto Print(llvm::raw_ostream& out) const -> void {
  176. out << "class";
  177. IdBase::Print(out);
  178. }
  179. };
  180. constexpr ClassId ClassId::Invalid = ClassId(InvalidIndex);
  181. // The ID of an interface.
  182. struct InterfaceId : public IdBase, public Printable<InterfaceId> {
  183. using ValueType = Interface;
  184. // An explicitly invalid interface ID.
  185. static const InterfaceId Invalid;
  186. using IdBase::IdBase;
  187. auto Print(llvm::raw_ostream& out) const -> void {
  188. out << "interface";
  189. IdBase::Print(out);
  190. }
  191. };
  192. constexpr InterfaceId InterfaceId::Invalid = InterfaceId(InvalidIndex);
  193. // The ID of an impl.
  194. struct ImplId : public IdBase, public Printable<ImplId> {
  195. using ValueType = Impl;
  196. // An explicitly invalid interface ID.
  197. static const ImplId Invalid;
  198. using IdBase::IdBase;
  199. auto Print(llvm::raw_ostream& out) const -> void {
  200. out << "impl";
  201. IdBase::Print(out);
  202. }
  203. };
  204. constexpr ImplId ImplId::Invalid = ImplId(InvalidIndex);
  205. // The ID of an imported IR.
  206. struct ImportIRId : public IdBase, public Printable<ImportIRId> {
  207. using ValueType = ImportIR;
  208. static const ImportIRId Builtins;
  209. using IdBase::IdBase;
  210. auto Print(llvm::raw_ostream& out) const -> void {
  211. out << "ir";
  212. IdBase::Print(out);
  213. }
  214. };
  215. constexpr ImportIRId ImportIRId::Builtins = ImportIRId(0);
  216. // A boolean value.
  217. struct BoolValue : public IdBase, public Printable<BoolValue> {
  218. static const BoolValue False;
  219. static const BoolValue True;
  220. // Returns the `BoolValue` corresponding to `b`.
  221. static constexpr auto From(bool b) -> BoolValue { return b ? True : False; }
  222. // Returns the `bool` corresponding to this `BoolValue`.
  223. constexpr auto ToBool() -> bool {
  224. CARBON_CHECK(*this == False || *this == True)
  225. << "Invalid bool value " << index;
  226. return *this != False;
  227. }
  228. using IdBase::IdBase;
  229. auto Print(llvm::raw_ostream& out) const -> void {
  230. if (*this == False) {
  231. out << "false";
  232. } else if (*this == True) {
  233. out << "true";
  234. } else {
  235. CARBON_FATAL() << "Invalid bool value " << index;
  236. }
  237. }
  238. };
  239. constexpr BoolValue BoolValue::False = BoolValue(0);
  240. constexpr BoolValue BoolValue::True = BoolValue(1);
  241. // The ID of a name. A name is either a string or a special name such as
  242. // `self`, `Self`, or `base`.
  243. struct NameId : public IdBase, public Printable<NameId> {
  244. // names().GetFormatted() is used for diagnostics.
  245. using DiagnosticType = DiagnosticTypeInfo<std::string>;
  246. // An explicitly invalid ID.
  247. static const NameId Invalid;
  248. // The name of `self`.
  249. static const NameId SelfValue;
  250. // The name of `Self`.
  251. static const NameId SelfType;
  252. // The name of the return slot in a function.
  253. static const NameId ReturnSlot;
  254. // The name of `package`.
  255. static const NameId PackageNamespace;
  256. // The name of `base`.
  257. static const NameId Base;
  258. // The number of non-index (<0) that exist, and will need storage in name
  259. // lookup.
  260. static const int NonIndexValueCount;
  261. // Returns the NameId corresponding to a particular IdentifierId.
  262. static auto ForIdentifier(IdentifierId id) -> NameId {
  263. if (id.index >= 0) {
  264. return NameId(id.index);
  265. } else if (!id.is_valid()) {
  266. return NameId::Invalid;
  267. } else {
  268. CARBON_FATAL() << "Unexpected identifier ID " << id;
  269. }
  270. }
  271. using IdBase::IdBase;
  272. // Returns the IdentifierId corresponding to this NameId, or an invalid
  273. // IdentifierId if this is a special name.
  274. auto AsIdentifierId() const -> IdentifierId {
  275. return index >= 0 ? IdentifierId(index) : IdentifierId::Invalid;
  276. }
  277. auto Print(llvm::raw_ostream& out) const -> void {
  278. out << "name";
  279. if (*this == SelfValue) {
  280. out << "SelfValue";
  281. } else if (*this == SelfType) {
  282. out << "SelfType";
  283. } else if (*this == ReturnSlot) {
  284. out << "ReturnSlot";
  285. } else if (*this == PackageNamespace) {
  286. out << "PackageNamespace";
  287. } else if (*this == Base) {
  288. out << "Base";
  289. } else {
  290. CARBON_CHECK(!is_valid() || index >= 0) << "Unknown index " << index;
  291. IdBase::Print(out);
  292. }
  293. }
  294. };
  295. constexpr NameId NameId::Invalid = NameId(InvalidIndex);
  296. constexpr NameId NameId::SelfValue = NameId(InvalidIndex - 1);
  297. constexpr NameId NameId::SelfType = NameId(InvalidIndex - 2);
  298. constexpr NameId NameId::ReturnSlot = NameId(InvalidIndex - 3);
  299. constexpr NameId NameId::PackageNamespace = NameId(InvalidIndex - 4);
  300. constexpr NameId NameId::Base = NameId(InvalidIndex - 5);
  301. constexpr int NameId::NonIndexValueCount = 6;
  302. // Enforce the link between SpecialValueCount and the last special value.
  303. static_assert(NameId::NonIndexValueCount == -NameId::Base.index);
  304. // The ID of a name scope.
  305. struct NameScopeId : public IdBase, public Printable<NameScopeId> {
  306. using ValueType = NameScope;
  307. // An explicitly invalid ID.
  308. static const NameScopeId Invalid;
  309. // The package (or file) name scope, guaranteed to be the first added.
  310. static const NameScopeId Package;
  311. using IdBase::IdBase;
  312. auto Print(llvm::raw_ostream& out) const -> void {
  313. out << "name_scope";
  314. IdBase::Print(out);
  315. }
  316. };
  317. constexpr NameScopeId NameScopeId::Invalid = NameScopeId(InvalidIndex);
  318. constexpr NameScopeId NameScopeId::Package = NameScopeId(0);
  319. // The ID of an instruction block.
  320. struct InstBlockId : public IdBase, public Printable<InstBlockId> {
  321. using ElementType = InstId;
  322. using ValueType = llvm::MutableArrayRef<ElementType>;
  323. // An empty block, reused to avoid allocating empty vectors. Always the
  324. // 0-index block.
  325. static const InstBlockId Empty;
  326. // Exported instructions. Always the 1-index block. Empty until the File is
  327. // fully checked; intermediate state is in the Check::Context.
  328. static const InstBlockId Exports;
  329. // Global declaration initialization instructions. Empty if none are present.
  330. // Otherwise, __global_init function will be generated and this block will
  331. // be inserted into it.
  332. static const InstBlockId GlobalInit;
  333. // An explicitly invalid ID.
  334. static const InstBlockId Invalid;
  335. // An ID for unreachable code.
  336. static const InstBlockId Unreachable;
  337. using IdBase::IdBase;
  338. auto Print(llvm::raw_ostream& out) const -> void {
  339. if (*this == Unreachable) {
  340. out << "unreachable";
  341. } else if (*this == Empty) {
  342. out << "empty";
  343. } else if (*this == Exports) {
  344. out << "exports";
  345. } else if (*this == GlobalInit) {
  346. out << "global_init";
  347. } else {
  348. out << "block";
  349. IdBase::Print(out);
  350. }
  351. }
  352. };
  353. constexpr InstBlockId InstBlockId::Empty = InstBlockId(0);
  354. constexpr InstBlockId InstBlockId::Exports = InstBlockId(1);
  355. constexpr InstBlockId InstBlockId::Invalid = InstBlockId(InvalidIndex);
  356. constexpr InstBlockId InstBlockId::Unreachable = InstBlockId(InvalidIndex - 1);
  357. constexpr InstBlockId InstBlockId::GlobalInit = InstBlockId(2);
  358. // The ID of a type.
  359. struct TypeId : public IdBase, public Printable<TypeId> {
  360. using ValueType = TypeInfo;
  361. // StringifyType() is used for diagnostics.
  362. using DiagnosticType = DiagnosticTypeInfo<std::string>;
  363. // The builtin TypeType.
  364. static const TypeId TypeType;
  365. // The builtin Error.
  366. static const TypeId Error;
  367. // An explicitly invalid ID.
  368. static const TypeId Invalid;
  369. using IdBase::IdBase;
  370. auto Print(llvm::raw_ostream& out) const -> void {
  371. out << "type";
  372. if (*this == TypeType) {
  373. out << "TypeType";
  374. } else if (*this == Error) {
  375. out << "Error";
  376. } else {
  377. IdBase::Print(out);
  378. }
  379. }
  380. };
  381. constexpr TypeId TypeId::TypeType = TypeId(InvalidIndex - 2);
  382. constexpr TypeId TypeId::Error = TypeId(InvalidIndex - 1);
  383. constexpr TypeId TypeId::Invalid = TypeId(InvalidIndex);
  384. // The ID of a type block.
  385. struct TypeBlockId : public IdBase, public Printable<TypeBlockId> {
  386. using ElementType = TypeId;
  387. using ValueType = llvm::MutableArrayRef<ElementType>;
  388. using IdBase::IdBase;
  389. auto Print(llvm::raw_ostream& out) const -> void {
  390. out << "typeBlock";
  391. IdBase::Print(out);
  392. }
  393. };
  394. // An index for element access, for structs, tuples, and classes.
  395. struct ElementIndex : public IndexBase, public Printable<ElementIndex> {
  396. using IndexBase::IndexBase;
  397. auto Print(llvm::raw_ostream& out) const -> void {
  398. out << "element";
  399. IndexBase::Print(out);
  400. }
  401. };
  402. // The ID of an ImportIRInst.
  403. struct ImportIRInstId : public IdBase, public Printable<InstId> {
  404. using ValueType = ImportIRInst;
  405. using IdBase::IdBase;
  406. };
  407. // A SemIR location used exclusively for diagnostic locations.
  408. //
  409. // Contents:
  410. // - index > Invalid: A Parse::NodeId in the current IR.
  411. // - index < Invalid: An ImportIRInstId.
  412. // - index == Invalid: Can be used for either.
  413. struct LocId : public IdBase, public Printable<FunctionId> {
  414. // An explicitly invalid function ID.
  415. static const LocId Invalid;
  416. // NOLINTNEXTLINE(google-explicit-constructor)
  417. constexpr LocId(Parse::InvalidNodeId /*invalid*/) : IdBase(InvalidIndex) {}
  418. // NOLINTNEXTLINE(google-explicit-constructor)
  419. constexpr LocId(Parse::NodeId node_id) : IdBase(node_id.index) {
  420. CARBON_CHECK(node_id.is_valid() == is_valid());
  421. }
  422. // NOLINTNEXTLINE(google-explicit-constructor)
  423. constexpr LocId(ImportIRInstId inst_id)
  424. : IdBase(InvalidIndex + ImportIRInstId::InvalidIndex - inst_id.index) {
  425. CARBON_CHECK(inst_id.is_valid() == is_valid());
  426. }
  427. auto is_node_id() const -> bool { return index > InvalidIndex; }
  428. auto is_import_ir_inst_id() const -> bool { return index < InvalidIndex; }
  429. // This is allowed to return an invalid NodeId, but should never be used for a
  430. // valid InstId.
  431. auto node_id() const -> Parse::NodeId {
  432. CARBON_CHECK(is_node_id() || !is_valid());
  433. return Parse::NodeId(index);
  434. }
  435. // This is allowed to return an invalid InstId, but should never be used for a
  436. // valid NodeId.
  437. auto import_ir_inst_id() const -> ImportIRInstId {
  438. CARBON_CHECK(is_import_ir_inst_id() || !is_valid());
  439. return ImportIRInstId(InvalidIndex + ImportIRInstId::InvalidIndex - index);
  440. }
  441. auto Print(llvm::raw_ostream& out) const -> void {
  442. out << "loc_";
  443. if (is_node_id() || !is_valid()) {
  444. out << node_id();
  445. } else {
  446. out << import_ir_inst_id();
  447. }
  448. }
  449. };
  450. constexpr LocId LocId::Invalid = LocId(Parse::NodeId::Invalid);
  451. } // namespace Carbon::SemIR
  452. // Support use of Id types as DenseMap/DenseSet keys.
  453. template <>
  454. struct llvm::DenseMapInfo<Carbon::SemIR::ConstantId>
  455. : public Carbon::IndexMapInfo<Carbon::SemIR::ConstantId> {};
  456. template <>
  457. struct llvm::DenseMapInfo<Carbon::SemIR::InstBlockId>
  458. : public Carbon::IndexMapInfo<Carbon::SemIR::InstBlockId> {};
  459. template <>
  460. struct llvm::DenseMapInfo<Carbon::SemIR::InstId>
  461. : public Carbon::IndexMapInfo<Carbon::SemIR::InstId> {};
  462. template <>
  463. struct llvm::DenseMapInfo<Carbon::SemIR::NameId>
  464. : public Carbon::IndexMapInfo<Carbon::SemIR::NameId> {};
  465. template <>
  466. struct llvm::DenseMapInfo<Carbon::SemIR::NameScopeId>
  467. : public Carbon::IndexMapInfo<Carbon::SemIR::NameScopeId> {};
  468. template <>
  469. struct llvm::DenseMapInfo<Carbon::SemIR::TypeId>
  470. : public Carbon::IndexMapInfo<Carbon::SemIR::TypeId> {};
  471. #endif // CARBON_TOOLCHAIN_SEM_IR_IDS_H_