ids.h 29 KB

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