ids.h 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913
  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_inst_kind.h"
  13. namespace Carbon::SemIR {
  14. // Forward declare indexed types, for integration with ValueStore.
  15. class File;
  16. class Inst;
  17. struct EntityName;
  18. struct Class;
  19. struct Function;
  20. struct Generic;
  21. struct Specific;
  22. struct ImportIR;
  23. struct ImportIRInst;
  24. struct Interface;
  25. struct Impl;
  26. struct NameScope;
  27. struct TypeInfo;
  28. // The ID of an instruction.
  29. struct InstId : public IdBase, public Printable<InstId> {
  30. using ValueType = Inst;
  31. // An explicitly invalid ID.
  32. static const InstId Invalid;
  33. // BuiltinInst IDs.
  34. #define CARBON_SEM_IR_BUILTIN_INST_KIND_NAME(Name) \
  35. static const InstId Builtin##Name;
  36. #include "toolchain/sem_ir/builtin_inst_kind.def"
  37. // The namespace for a `package` expression.
  38. static const InstId PackageNamespace;
  39. // Returns the instruction ID for a builtin. This relies on File guarantees
  40. // for builtin placement.
  41. static constexpr auto ForBuiltin(BuiltinInstKind kind) -> InstId {
  42. return InstId(kind.AsInt());
  43. }
  44. using IdBase::IdBase;
  45. // Returns true if the instruction is a builtin. Requires is_valid.
  46. auto is_builtin() const -> bool {
  47. CARBON_CHECK(is_valid());
  48. return index < BuiltinInstKind::ValidCount;
  49. }
  50. // Returns the BuiltinInstKind. Requires is_builtin.
  51. auto builtin_inst_kind() const -> BuiltinInstKind {
  52. CARBON_CHECK(is_builtin());
  53. return BuiltinInstKind::FromInt(index);
  54. }
  55. auto Print(llvm::raw_ostream& out) const -> void {
  56. out << "inst";
  57. if (!is_valid()) {
  58. IdBase::Print(out);
  59. } else if (is_builtin()) {
  60. out << builtin_inst_kind();
  61. } else {
  62. // Use the `+` as a small reminder that this is a delta, rather than an
  63. // absolute index.
  64. out << "+" << index - BuiltinInstKind::ValidCount;
  65. }
  66. }
  67. };
  68. constexpr InstId InstId::Invalid = InstId(InvalidIndex);
  69. #define CARBON_SEM_IR_BUILTIN_INST_KIND_NAME(Name) \
  70. constexpr InstId InstId::Builtin##Name = \
  71. InstId::ForBuiltin(BuiltinInstKind::Name);
  72. #include "toolchain/sem_ir/builtin_inst_kind.def"
  73. // An ID of an instruction that is referenced absolutely by another instruction.
  74. // This should only be used as the type of a field within a typed instruction
  75. // class.
  76. //
  77. // When a typed instruction has a field of this type, that field represents an
  78. // absolute reference to another instruction that typically resides in a
  79. // different entity. This behaves in most respects like an InstId field, but
  80. // substitution into the typed instruction leaves the field unchanged rather
  81. // than substituting into it.
  82. class AbsoluteInstId : public InstId {
  83. public:
  84. // Support implicit conversion from InstId so that InstId and AbsoluteInstId
  85. // have the same interface.
  86. // NOLINTNEXTLINE(google-explicit-constructor)
  87. constexpr AbsoluteInstId(InstId inst_id) : InstId(inst_id) {}
  88. using InstId::InstId;
  89. };
  90. // An ID of an instruction that is the pattern-match counterpart of a pattern
  91. // inst. This should only be used as the type of a field within a typed
  92. // instruction class that represents a pattern.
  93. //
  94. // In SemIR, a given pattern is represented by one or more pattern insts, which
  95. // describe the pattern itself, and typically by one or more pattern-match
  96. // insts, which describe the process of matching the pattern against the
  97. // scrutinee. The pattern insts are emitted while traversing the parse tree,
  98. // and then the pattern-match insts are emitted by traversing the pattern
  99. // insts, but in some cases it's necessary to precompute the pattern-match
  100. // insts during that first phase. In such a case, the precomputed inst is stored
  101. // as a MatchingInstId member of the pattern inst, so that it's available when
  102. // the pattern inst is later traversed.
  103. class MatchingInstId : public InstId {
  104. public:
  105. // Support implicit conversion from InstId so that InstId and MatchingInstId
  106. // have the same interface.
  107. // NOLINTNEXTLINE(google-explicit-constructor)
  108. constexpr MatchingInstId(InstId inst_id) : InstId(inst_id) {}
  109. using InstId::InstId;
  110. };
  111. // The package namespace will be the instruction after builtins.
  112. constexpr InstId InstId::PackageNamespace = InstId(BuiltinInstKind::ValidCount);
  113. // The ID of a constant value of an expression. An expression is either:
  114. //
  115. // - a template constant, with an immediate value, such as `42` or `i32*` or
  116. // `("hello", "world")`, or
  117. // - a symbolic constant, whose value includes a symbolic parameter, such as
  118. // `Vector(T*)`, or
  119. // - a runtime expression, such as `Print("hello")`.
  120. //
  121. // Template constants are a thin wrapper around the instruction ID of the
  122. // constant instruction that defines the constant. Symbolic constants are an
  123. // index into a separate table of `SymbolicConstant`s maintained by the constant
  124. // value store.
  125. struct ConstantId : public IdBase, public Printable<ConstantId> {
  126. // An ID for an expression that is not constant.
  127. static const ConstantId NotConstant;
  128. // An ID for an expression whose phase cannot be determined because it
  129. // contains an error. This is always modeled as a template constant.
  130. static const ConstantId Error;
  131. // An explicitly invalid ID.
  132. static const ConstantId Invalid;
  133. // Returns the constant ID corresponding to a template constant, which should
  134. // either be in the `constants` block in the file or should be known to be
  135. // unique.
  136. static constexpr auto ForTemplateConstant(InstId const_id) -> ConstantId {
  137. return ConstantId(const_id.index);
  138. }
  139. // Returns the constant ID corresponding to a symbolic constant index.
  140. static constexpr auto ForSymbolicConstantIndex(int32_t symbolic_index)
  141. -> ConstantId {
  142. return ConstantId(FirstSymbolicIndex - symbolic_index);
  143. }
  144. using IdBase::IdBase;
  145. // Returns whether this represents a constant. Requires is_valid.
  146. auto is_constant() const -> bool {
  147. CARBON_DCHECK(is_valid());
  148. return *this != ConstantId::NotConstant;
  149. }
  150. // Returns whether this represents a symbolic constant. Requires is_valid.
  151. auto is_symbolic() const -> bool {
  152. CARBON_DCHECK(is_valid());
  153. return index <= FirstSymbolicIndex;
  154. }
  155. // Returns whether this represents a template constant. Requires is_valid.
  156. auto is_template() const -> bool {
  157. CARBON_DCHECK(is_valid());
  158. return index >= 0;
  159. }
  160. // Prints this ID to the given output stream. `disambiguate` indicates whether
  161. // template constants should be wrapped with "templateConstant(...)" so that
  162. // they aren't printed the same as an InstId. This can be set to false if
  163. // there is no risk of ambiguity.
  164. auto Print(llvm::raw_ostream& out, bool disambiguate = true) const -> void {
  165. if (!is_valid()) {
  166. IdBase::Print(out);
  167. } else if (is_template()) {
  168. if (disambiguate) {
  169. out << "templateConstant(";
  170. }
  171. out << template_inst_id();
  172. if (disambiguate) {
  173. out << ")";
  174. }
  175. } else if (is_symbolic()) {
  176. out << "symbolicConstant" << symbolic_index();
  177. } else {
  178. out << "runtime";
  179. }
  180. }
  181. private:
  182. friend class ConstantValueStore;
  183. // TODO: C++23 makes std::abs constexpr, but until then we mirror std::abs
  184. // logic here. LLVM should still optimize this.
  185. static constexpr auto Abs(int32_t i) -> int32_t { return i > 0 ? i : -i; }
  186. // Returns the instruction that describes this template constant value.
  187. // Requires `is_template()`. Use `ConstantValueStore::GetInstId` to get the
  188. // instruction ID of a `ConstantId`.
  189. constexpr auto template_inst_id() const -> InstId {
  190. CARBON_DCHECK(is_template());
  191. return InstId(index);
  192. }
  193. // Returns the symbolic constant index that describes this symbolic constant
  194. // value. Requires `is_symbolic()`.
  195. constexpr auto symbolic_index() const -> int32_t {
  196. CARBON_DCHECK(is_symbolic());
  197. return FirstSymbolicIndex - index;
  198. }
  199. static constexpr int32_t NotConstantIndex = InvalidIndex - 1;
  200. static constexpr int32_t FirstSymbolicIndex = InvalidIndex - 2;
  201. };
  202. constexpr ConstantId ConstantId::NotConstant = ConstantId(NotConstantIndex);
  203. constexpr ConstantId ConstantId::Error =
  204. ConstantId::ForTemplateConstant(InstId::BuiltinError);
  205. constexpr ConstantId ConstantId::Invalid = ConstantId(InvalidIndex);
  206. // The ID of a EntityName.
  207. struct EntityNameId : public IdBase, public Printable<EntityNameId> {
  208. using ValueType = EntityName;
  209. // An explicitly invalid ID.
  210. static const EntityNameId Invalid;
  211. using IdBase::IdBase;
  212. auto Print(llvm::raw_ostream& out) const -> void {
  213. out << "entity_name";
  214. IdBase::Print(out);
  215. }
  216. };
  217. constexpr EntityNameId EntityNameId::Invalid = EntityNameId(InvalidIndex);
  218. // The index of a compile-time binding. This is the de Bruijn level for the
  219. // binding -- that is, this is the number of other compile time bindings whose
  220. // scope encloses this binding.
  221. struct CompileTimeBindIndex : public IndexBase,
  222. public Printable<CompileTimeBindIndex> {
  223. // An explicitly invalid index.
  224. static const CompileTimeBindIndex Invalid;
  225. using IndexBase::IndexBase;
  226. auto Print(llvm::raw_ostream& out) const -> void {
  227. out << "comp_time_bind";
  228. IndexBase::Print(out);
  229. }
  230. };
  231. constexpr CompileTimeBindIndex CompileTimeBindIndex::Invalid =
  232. CompileTimeBindIndex(InvalidIndex);
  233. // The index of a runtime parameter in a function. These are allocated
  234. // sequentially, left-to-right, to the function parameters that will have
  235. // arguments passed to them at runtime. In a `call` instruction, a runtime
  236. // argument will have the position in the argument list corresponding to its
  237. // runtime parameter index.
  238. struct RuntimeParamIndex : public IndexBase,
  239. public Printable<RuntimeParamIndex> {
  240. // An explicitly invalid index.
  241. static const RuntimeParamIndex Invalid;
  242. // An placeholder for index whose value is not yet known.
  243. static const RuntimeParamIndex Unknown;
  244. using IndexBase::IndexBase;
  245. auto Print(llvm::raw_ostream& out) const -> void {
  246. out << "runtime_param";
  247. if (*this == Unknown) {
  248. out << "<unknown>";
  249. } else {
  250. IndexBase::Print(out);
  251. }
  252. }
  253. };
  254. constexpr RuntimeParamIndex RuntimeParamIndex::Invalid =
  255. RuntimeParamIndex(InvalidIndex);
  256. constexpr RuntimeParamIndex RuntimeParamIndex::Unknown =
  257. RuntimeParamIndex(InvalidIndex - 1);
  258. // The ID of a function.
  259. struct FunctionId : public IdBase, public Printable<FunctionId> {
  260. using ValueType = Function;
  261. // An explicitly invalid ID.
  262. static const FunctionId Invalid;
  263. using IdBase::IdBase;
  264. auto Print(llvm::raw_ostream& out) const -> void {
  265. out << "function";
  266. IdBase::Print(out);
  267. }
  268. };
  269. constexpr FunctionId FunctionId::Invalid = FunctionId(InvalidIndex);
  270. // The ID of an IR within the set of all IRs being evaluated in the current
  271. // check execution.
  272. struct CheckIRId : public IdBase, public Printable<CheckIRId> {
  273. using IdBase::IdBase;
  274. auto Print(llvm::raw_ostream& out) const -> void {
  275. out << "check_ir";
  276. IdBase::Print(out);
  277. }
  278. };
  279. // The ID of a class.
  280. struct ClassId : public IdBase, public Printable<ClassId> {
  281. using ValueType = Class;
  282. // An explicitly invalid ID.
  283. static const ClassId Invalid;
  284. using IdBase::IdBase;
  285. auto Print(llvm::raw_ostream& out) const -> void {
  286. out << "class";
  287. IdBase::Print(out);
  288. }
  289. };
  290. constexpr ClassId ClassId::Invalid = ClassId(InvalidIndex);
  291. // The ID of an interface.
  292. struct InterfaceId : public IdBase, public Printable<InterfaceId> {
  293. using ValueType = Interface;
  294. // An explicitly invalid ID.
  295. static const InterfaceId Invalid;
  296. using IdBase::IdBase;
  297. auto Print(llvm::raw_ostream& out) const -> void {
  298. out << "interface";
  299. IdBase::Print(out);
  300. }
  301. };
  302. constexpr InterfaceId InterfaceId::Invalid = InterfaceId(InvalidIndex);
  303. // The ID of an impl.
  304. struct ImplId : public IdBase, public Printable<ImplId> {
  305. using ValueType = Impl;
  306. // An explicitly invalid ID.
  307. static const ImplId Invalid;
  308. using IdBase::IdBase;
  309. auto Print(llvm::raw_ostream& out) const -> void {
  310. out << "impl";
  311. IdBase::Print(out);
  312. }
  313. };
  314. constexpr ImplId ImplId::Invalid = ImplId(InvalidIndex);
  315. // The ID of a generic.
  316. struct GenericId : public IdBase, public Printable<GenericId> {
  317. using ValueType = Generic;
  318. // An explicitly invalid ID.
  319. static const GenericId Invalid;
  320. using IdBase::IdBase;
  321. auto Print(llvm::raw_ostream& out) const -> void {
  322. out << "generic";
  323. IdBase::Print(out);
  324. }
  325. };
  326. constexpr GenericId GenericId::Invalid = GenericId(InvalidIndex);
  327. // The ID of a specific, which is the result of specifying the generic arguments
  328. // for a generic.
  329. struct SpecificId : public IdBase, public Printable<SpecificId> {
  330. using ValueType = Specific;
  331. // An explicitly invalid ID. This is typically used to represent a non-generic
  332. // entity.
  333. static const SpecificId Invalid;
  334. using IdBase::IdBase;
  335. auto Print(llvm::raw_ostream& out) const -> void {
  336. out << "specific";
  337. IdBase::Print(out);
  338. }
  339. };
  340. constexpr SpecificId SpecificId::Invalid = SpecificId(InvalidIndex);
  341. // The index of an instruction that depends on generic parameters within a
  342. // region of a generic. A corresponding specific version of the instruction can
  343. // be found in each specific corresponding to that generic. This is a pair of a
  344. // region and an index, stored in 32 bits.
  345. struct GenericInstIndex : public IndexBase, public Printable<GenericInstIndex> {
  346. // Where the value is first used within the generic.
  347. enum Region : uint8_t {
  348. // In the declaration.
  349. Declaration,
  350. // In the definition.
  351. Definition,
  352. };
  353. // An explicitly invalid index.
  354. static const GenericInstIndex Invalid;
  355. explicit constexpr GenericInstIndex(Region region, int32_t index)
  356. : IndexBase(region == Declaration ? index
  357. : FirstDefinitionIndex - index) {
  358. CARBON_CHECK(index >= 0);
  359. }
  360. // Returns the index of the instruction within the region.
  361. auto index() const -> int32_t {
  362. CARBON_CHECK(is_valid());
  363. return IndexBase::index >= 0 ? IndexBase::index
  364. : FirstDefinitionIndex - IndexBase::index;
  365. }
  366. // Returns the region within which this instruction was first used.
  367. auto region() const -> Region {
  368. CARBON_CHECK(is_valid());
  369. return IndexBase::index >= 0 ? Declaration : Definition;
  370. }
  371. auto Print(llvm::raw_ostream& out) const -> void {
  372. out << "genericInst";
  373. if (is_valid()) {
  374. out << (region() == Declaration ? "InDecl" : "InDef") << index();
  375. } else {
  376. out << "<invalid>";
  377. }
  378. }
  379. private:
  380. static constexpr auto MakeInvalid() -> GenericInstIndex {
  381. GenericInstIndex result(Declaration, 0);
  382. result.IndexBase::index = InvalidIndex;
  383. return result;
  384. }
  385. static constexpr int32_t FirstDefinitionIndex = InvalidIndex - 1;
  386. };
  387. constexpr GenericInstIndex GenericInstIndex::Invalid =
  388. GenericInstIndex::MakeInvalid();
  389. // The ID of an IR within the set of imported IRs, both direct and indirect.
  390. struct ImportIRId : public IdBase, public Printable<ImportIRId> {
  391. using ValueType = ImportIR;
  392. // An explicitly invalid ID.
  393. static const ImportIRId Invalid;
  394. // The implicit `api` import, for an `impl` file. A null entry is added if
  395. // there is none, as in an `api`, in which case this ID should not show up in
  396. // instructions.
  397. static const ImportIRId ApiForImpl;
  398. using IdBase::IdBase;
  399. auto Print(llvm::raw_ostream& out) const -> void {
  400. out << "ir";
  401. IdBase::Print(out);
  402. }
  403. };
  404. constexpr ImportIRId ImportIRId::Invalid = ImportIRId(InvalidIndex);
  405. constexpr ImportIRId ImportIRId::ApiForImpl = ImportIRId(0);
  406. // A boolean value.
  407. struct BoolValue : public IdBase, public Printable<BoolValue> {
  408. static const BoolValue False;
  409. static const BoolValue True;
  410. // Returns the `BoolValue` corresponding to `b`.
  411. static constexpr auto From(bool b) -> BoolValue { return b ? True : False; }
  412. // Returns the `bool` corresponding to this `BoolValue`.
  413. constexpr auto ToBool() -> bool {
  414. CARBON_CHECK(*this == False || *this == True, "Invalid bool value {0}",
  415. index);
  416. return *this != False;
  417. }
  418. using IdBase::IdBase;
  419. auto Print(llvm::raw_ostream& out) const -> void {
  420. if (*this == False) {
  421. out << "false";
  422. } else if (*this == True) {
  423. out << "true";
  424. } else {
  425. CARBON_FATAL("Invalid bool value {0}", index);
  426. }
  427. }
  428. };
  429. constexpr BoolValue BoolValue::False = BoolValue(0);
  430. constexpr BoolValue BoolValue::True = BoolValue(1);
  431. // An integer kind value -- either "signed" or "unsigned".
  432. //
  433. // This might eventually capture any other properties of an integer type that
  434. // affect its semantics, such as overflow behavior.
  435. struct IntKind : public IdBase, public Printable<IntKind> {
  436. static const IntKind Unsigned;
  437. static const IntKind Signed;
  438. using IdBase::IdBase;
  439. // Returns whether this type is signed.
  440. constexpr auto is_signed() -> bool { return *this == Signed; }
  441. auto Print(llvm::raw_ostream& out) const -> void {
  442. if (*this == Unsigned) {
  443. out << "unsigned";
  444. } else if (*this == Signed) {
  445. out << "signed";
  446. } else {
  447. CARBON_FATAL("Invalid int kind value {0}", index);
  448. }
  449. }
  450. };
  451. constexpr IntKind IntKind::Unsigned = IntKind(0);
  452. constexpr IntKind IntKind::Signed = IntKind(1);
  453. // A float kind value
  454. struct FloatKind : public IdBase, public Printable<FloatKind> {
  455. using IdBase::IdBase;
  456. auto Print(llvm::raw_ostream& out) const -> void { out << "float"; }
  457. };
  458. // The ID of a name. A name is either a string or a special name such as
  459. // `self`, `Self`, or `base`.
  460. struct NameId : public IdBase, public Printable<NameId> {
  461. // names().GetFormatted() is used for diagnostics.
  462. using DiagnosticType = DiagnosticTypeInfo<std::string>;
  463. // An explicitly invalid ID.
  464. static const NameId Invalid;
  465. // The name of `self`.
  466. static const NameId SelfValue;
  467. // The name of `Self`.
  468. static const NameId SelfType;
  469. // The name of `.Self`.
  470. static const NameId PeriodSelf;
  471. // The name of the return slot in a function.
  472. static const NameId ReturnSlot;
  473. // The name of `package`.
  474. static const NameId PackageNamespace;
  475. // The name of `base`.
  476. static const NameId Base;
  477. // The name of `vptr`.
  478. static const NameId Vptr;
  479. // The number of non-index (<0) that exist, and will need storage in name
  480. // lookup.
  481. static const int NonIndexValueCount;
  482. // Returns the NameId corresponding to a particular IdentifierId.
  483. static auto ForIdentifier(IdentifierId id) -> NameId {
  484. if (id.index >= 0) {
  485. return NameId(id.index);
  486. } else if (!id.is_valid()) {
  487. return NameId::Invalid;
  488. } else {
  489. CARBON_FATAL("Unexpected identifier ID {0}", id);
  490. }
  491. }
  492. using IdBase::IdBase;
  493. // Returns the IdentifierId corresponding to this NameId, or an invalid
  494. // IdentifierId if this is a special name.
  495. auto AsIdentifierId() const -> IdentifierId {
  496. return index >= 0 ? IdentifierId(index) : IdentifierId::Invalid;
  497. }
  498. auto Print(llvm::raw_ostream& out) const -> void {
  499. out << "name";
  500. if (*this == SelfValue) {
  501. out << "SelfValue";
  502. } else if (*this == SelfType) {
  503. out << "SelfType";
  504. } else if (*this == PeriodSelf) {
  505. out << "PeriodSelf";
  506. } else if (*this == ReturnSlot) {
  507. out << "ReturnSlot";
  508. } else if (*this == PackageNamespace) {
  509. out << "PackageNamespace";
  510. } else if (*this == Base) {
  511. out << "Base";
  512. } else {
  513. CARBON_CHECK(!is_valid() || index >= 0, "Unknown index {0}", index);
  514. IdBase::Print(out);
  515. }
  516. }
  517. };
  518. constexpr NameId NameId::Invalid = NameId(InvalidIndex);
  519. constexpr NameId NameId::SelfValue = NameId(InvalidIndex - 1);
  520. constexpr NameId NameId::SelfType = NameId(InvalidIndex - 2);
  521. constexpr NameId NameId::PeriodSelf = NameId(InvalidIndex - 3);
  522. constexpr NameId NameId::ReturnSlot = NameId(InvalidIndex - 4);
  523. constexpr NameId NameId::PackageNamespace = NameId(InvalidIndex - 5);
  524. constexpr NameId NameId::Base = NameId(InvalidIndex - 6);
  525. constexpr NameId NameId::Vptr = NameId(InvalidIndex - 7);
  526. constexpr int NameId::NonIndexValueCount = 8;
  527. // Enforce the link between SpecialValueCount and the last special value.
  528. static_assert(NameId::NonIndexValueCount == -NameId::Vptr.index);
  529. // The ID of a name scope.
  530. struct NameScopeId : public IdBase, public Printable<NameScopeId> {
  531. using ValueType = NameScope;
  532. // An explicitly invalid ID.
  533. static const NameScopeId Invalid;
  534. // The package (or file) name scope, guaranteed to be the first added.
  535. static const NameScopeId Package;
  536. using IdBase::IdBase;
  537. auto Print(llvm::raw_ostream& out) const -> void {
  538. out << "name_scope";
  539. IdBase::Print(out);
  540. }
  541. };
  542. constexpr NameScopeId NameScopeId::Invalid = NameScopeId(InvalidIndex);
  543. constexpr NameScopeId NameScopeId::Package = NameScopeId(0);
  544. // The ID of an instruction block.
  545. struct InstBlockId : public IdBase, public Printable<InstBlockId> {
  546. using ElementType = InstId;
  547. using ValueType = llvm::MutableArrayRef<ElementType>;
  548. // The canonical empty block, reused to avoid allocating empty vectors. Always
  549. // the 0-index block.
  550. static const InstBlockId Empty;
  551. // Exported instructions. Empty until the File is fully checked; intermediate
  552. // state is in the Check::Context.
  553. static const InstBlockId Exports;
  554. // ImportRef instructions. Empty until the File is fully checked; intermediate
  555. // state is in the Check::Context.
  556. static const InstBlockId ImportRefs;
  557. // Global declaration initialization instructions. Empty if none are present.
  558. // Otherwise, __global_init function will be generated and this block will
  559. // be inserted into it.
  560. static const InstBlockId GlobalInit;
  561. // An explicitly invalid ID.
  562. static const InstBlockId Invalid;
  563. // An ID for unreachable code.
  564. static const InstBlockId Unreachable;
  565. using IdBase::IdBase;
  566. auto Print(llvm::raw_ostream& out) const -> void {
  567. if (*this == Unreachable) {
  568. out << "unreachable";
  569. } else if (*this == Empty) {
  570. out << "empty";
  571. } else if (*this == Exports) {
  572. out << "exports";
  573. } else if (*this == ImportRefs) {
  574. out << "import_refs";
  575. } else if (*this == GlobalInit) {
  576. out << "global_init";
  577. } else {
  578. out << "block";
  579. IdBase::Print(out);
  580. }
  581. }
  582. };
  583. constexpr InstBlockId InstBlockId::Empty = InstBlockId(0);
  584. constexpr InstBlockId InstBlockId::Exports = InstBlockId(1);
  585. constexpr InstBlockId InstBlockId::ImportRefs = InstBlockId(2);
  586. constexpr InstBlockId InstBlockId::GlobalInit = InstBlockId(3);
  587. constexpr InstBlockId InstBlockId::Invalid = InstBlockId(InvalidIndex);
  588. constexpr InstBlockId InstBlockId::Unreachable = InstBlockId(InvalidIndex - 1);
  589. // The ID of a type.
  590. struct TypeId : public IdBase, public Printable<TypeId> {
  591. // `StringifyTypeExpr` is used for diagnostics. However, where possible, an
  592. // `InstId` describing how the type was written should be preferred, using
  593. // `InstIdAsType` or `TypeOfInstId` as the diagnostic argument type.
  594. using DiagnosticType = DiagnosticTypeInfo<std::string>;
  595. // The builtin TypeType.
  596. static const TypeId TypeType;
  597. // The builtin placeholder type for patterns with deduced types.
  598. static const TypeId AutoType;
  599. // The builtin Error.
  600. static const TypeId Error;
  601. // An explicitly invalid ID.
  602. static const TypeId Invalid;
  603. using IdBase::IdBase;
  604. // Returns the ID of the type corresponding to the constant `const_id`, which
  605. // must be of type `type`. As an exception, the type `Error` is of type
  606. // `Error`.
  607. static constexpr auto ForTypeConstant(ConstantId const_id) -> TypeId {
  608. return TypeId(const_id.index);
  609. }
  610. // Returns the constant ID that defines the type.
  611. auto AsConstantId() const -> ConstantId { return ConstantId(index); }
  612. auto Print(llvm::raw_ostream& out) const -> void {
  613. out << "type";
  614. if (*this == TypeType) {
  615. out << "TypeType";
  616. } else if (*this == AutoType) {
  617. out << "AutoType";
  618. } else if (*this == Error) {
  619. out << "Error";
  620. } else {
  621. out << "(";
  622. AsConstantId().Print(out, /*disambiguate=*/false);
  623. out << ")";
  624. }
  625. }
  626. };
  627. constexpr TypeId TypeId::TypeType = TypeId::ForTypeConstant(
  628. ConstantId::ForTemplateConstant(InstId::BuiltinTypeType));
  629. constexpr TypeId TypeId::AutoType = TypeId::ForTypeConstant(
  630. ConstantId::ForTemplateConstant(InstId::BuiltinAutoType));
  631. constexpr TypeId TypeId::Error = TypeId::ForTypeConstant(ConstantId::Error);
  632. constexpr TypeId TypeId::Invalid = TypeId(InvalidIndex);
  633. // The ID of a type block.
  634. struct TypeBlockId : public IdBase, public Printable<TypeBlockId> {
  635. using ElementType = TypeId;
  636. using ValueType = llvm::MutableArrayRef<ElementType>;
  637. // An explicitly invalid ID.
  638. static const TypeBlockId Invalid;
  639. using IdBase::IdBase;
  640. auto Print(llvm::raw_ostream& out) const -> void {
  641. out << "type_block";
  642. IdBase::Print(out);
  643. }
  644. };
  645. constexpr TypeBlockId TypeBlockId::Invalid = TypeBlockId(InvalidIndex);
  646. // An index for element access, for structs, tuples, and classes.
  647. struct ElementIndex : public IndexBase, public Printable<ElementIndex> {
  648. using IndexBase::IndexBase;
  649. auto Print(llvm::raw_ostream& out) const -> void {
  650. out << "element";
  651. IndexBase::Print(out);
  652. }
  653. };
  654. // The ID of a library name. This is either a string literal or `default`.
  655. struct LibraryNameId : public IdBase, public Printable<NameId> {
  656. using DiagnosticType = DiagnosticTypeInfo<std::string>;
  657. // An explicitly invalid ID.
  658. static const LibraryNameId Invalid;
  659. // The name of `default`.
  660. static const LibraryNameId Default;
  661. // Track cases where the library name was set, but has been diagnosed and
  662. // shouldn't be used anymore.
  663. static const LibraryNameId Error;
  664. // Returns the LibraryNameId for a library name as a string literal.
  665. static auto ForStringLiteralValueId(StringLiteralValueId id)
  666. -> LibraryNameId {
  667. CARBON_CHECK(id.index >= InvalidIndex, "Unexpected library name ID {0}",
  668. id);
  669. if (id == StringLiteralValueId::Invalid) {
  670. // Prior to SemIR, we use invalid to indicate `default`.
  671. return LibraryNameId::Default;
  672. } else {
  673. return LibraryNameId(id.index);
  674. }
  675. }
  676. using IdBase::IdBase;
  677. // Converts a LibraryNameId back to a string literal.
  678. auto AsStringLiteralValueId() const -> StringLiteralValueId {
  679. CARBON_CHECK(index >= InvalidIndex, "{0} must be handled directly", *this);
  680. return StringLiteralValueId(index);
  681. }
  682. auto Print(llvm::raw_ostream& out) const -> void {
  683. out << "libraryName";
  684. if (*this == Default) {
  685. out << "Default";
  686. } else if (*this == Error) {
  687. out << "<error>";
  688. } else {
  689. IdBase::Print(out);
  690. }
  691. }
  692. };
  693. constexpr LibraryNameId LibraryNameId::Invalid = LibraryNameId(InvalidIndex);
  694. constexpr LibraryNameId LibraryNameId::Default =
  695. LibraryNameId(InvalidIndex - 1);
  696. constexpr LibraryNameId LibraryNameId::Error = LibraryNameId(InvalidIndex - 2);
  697. // The ID of an ImportIRInst.
  698. struct ImportIRInstId : public IdBase, public Printable<ImportIRInstId> {
  699. using ValueType = ImportIRInst;
  700. // An explicitly invalid ID.
  701. static const ImportIRInstId Invalid;
  702. using IdBase::IdBase;
  703. auto Print(llvm::raw_ostream& out) const -> void {
  704. out << "import_ir_inst";
  705. IdBase::Print(out);
  706. }
  707. };
  708. constexpr ImportIRInstId ImportIRInstId::Invalid = ImportIRInstId(InvalidIndex);
  709. // A SemIR location used exclusively for diagnostic locations.
  710. //
  711. // Contents:
  712. // - index > Invalid: A Parse::NodeId in the current IR.
  713. // - index < Invalid: An ImportIRInstId.
  714. // - index == Invalid: Can be used for either.
  715. struct LocId : public IdBase, public Printable<LocId> {
  716. // An explicitly invalid ID.
  717. static const LocId Invalid;
  718. using IdBase::IdBase;
  719. // NOLINTNEXTLINE(google-explicit-constructor)
  720. constexpr LocId(Parse::InvalidNodeId /*invalid*/) : IdBase(InvalidIndex) {}
  721. // NOLINTNEXTLINE(google-explicit-constructor)
  722. constexpr LocId(Parse::NodeId node_id) : IdBase(node_id.index) {
  723. CARBON_CHECK(node_id.is_valid() == is_valid());
  724. }
  725. // NOLINTNEXTLINE(google-explicit-constructor)
  726. constexpr LocId(ImportIRInstId inst_id)
  727. : IdBase(InvalidIndex + ImportIRInstId::InvalidIndex - inst_id.index) {
  728. CARBON_CHECK(inst_id.is_valid() == is_valid());
  729. }
  730. auto is_node_id() const -> bool { return index > InvalidIndex; }
  731. auto is_import_ir_inst_id() const -> bool { return index < InvalidIndex; }
  732. // This is allowed to return an invalid NodeId, but should never be used for a
  733. // valid InstId.
  734. auto node_id() const -> Parse::NodeId {
  735. CARBON_CHECK(is_node_id() || !is_valid());
  736. return Parse::NodeId(index);
  737. }
  738. // This is allowed to return an invalid InstId, but should never be used for a
  739. // valid NodeId.
  740. auto import_ir_inst_id() const -> ImportIRInstId {
  741. CARBON_CHECK(is_import_ir_inst_id() || !is_valid());
  742. return ImportIRInstId(InvalidIndex + ImportIRInstId::InvalidIndex - index);
  743. }
  744. auto Print(llvm::raw_ostream& out) const -> void {
  745. out << "loc_";
  746. if (is_node_id() || !is_valid()) {
  747. out << node_id();
  748. } else {
  749. out << import_ir_inst_id();
  750. }
  751. }
  752. };
  753. constexpr LocId LocId::Invalid = LocId(Parse::NodeId::Invalid);
  754. } // namespace Carbon::SemIR
  755. #endif // CARBON_TOOLCHAIN_SEM_IR_IDS_H_