ids.h 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991
  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 <limits>
  7. #include "common/check.h"
  8. #include "common/ostream.h"
  9. #include "toolchain/base/index_base.h"
  10. #include "toolchain/base/value_ids.h"
  11. #include "toolchain/diagnostics/diagnostic_emitter.h"
  12. #include "toolchain/parse/node_ids.h"
  13. namespace Carbon::SemIR {
  14. // Forward declare indexed types, for integration with ValueStore.
  15. class File;
  16. class Inst;
  17. class NameScope;
  18. struct AssociatedConstant;
  19. struct Class;
  20. struct EntityName;
  21. struct ExprRegion;
  22. struct FacetTypeInfo;
  23. struct Function;
  24. struct Generic;
  25. struct IdentifiedFacetType;
  26. struct Specific;
  27. struct SpecificInterface;
  28. struct ImportCpp;
  29. struct ImportIR;
  30. struct ImportIRInst;
  31. struct Impl;
  32. struct Interface;
  33. struct StructTypeField;
  34. struct TypeInfo;
  35. // The ID of an instruction.
  36. struct InstId : public IdBase<InstId> {
  37. static constexpr llvm::StringLiteral Label = "inst";
  38. using ValueType = Inst;
  39. // The maximum ID, inclusive.
  40. static constexpr int Max = std::numeric_limits<int32_t>::max();
  41. // Represents the result of a name lookup that is temporarily disallowed
  42. // because the name is currently being initialized.
  43. static const InstId InitTombstone;
  44. using IdBase::IdBase;
  45. auto Print(llvm::raw_ostream& out) const -> void;
  46. };
  47. constexpr InstId InstId::InitTombstone = InstId(NoneIndex - 1);
  48. // And InstId whose value is a type. The fact it's a type is CHECKed on
  49. // construction, and this allows that check to be represented in the type
  50. // system.
  51. struct TypeInstId : public InstId {
  52. static const TypeInstId None;
  53. using InstId::InstId;
  54. static constexpr auto UnsafeMake(InstId id) -> TypeInstId {
  55. return TypeInstId(UnsafeCtor(), id);
  56. }
  57. private:
  58. struct UnsafeCtor {};
  59. explicit constexpr TypeInstId(UnsafeCtor /*unsafe*/, InstId id)
  60. : InstId(id) {}
  61. };
  62. constexpr TypeInstId TypeInstId::None = TypeInstId::UnsafeMake(InstId::None);
  63. // An ID of an instruction that is referenced absolutely by another instruction.
  64. // This should only be used as the type of a field within a typed instruction
  65. // class.
  66. //
  67. // When a typed instruction has a field of this type, that field represents an
  68. // absolute reference to another instruction that typically resides in a
  69. // different entity. This behaves in most respects like an InstId field, but
  70. // substitution into the typed instruction leaves the field unchanged rather
  71. // than substituting into it.
  72. class AbsoluteInstId : public InstId {
  73. public:
  74. // Support implicit conversion from InstId so that InstId and AbsoluteInstId
  75. // have the same interface.
  76. // NOLINTNEXTLINE(google-explicit-constructor)
  77. constexpr AbsoluteInstId(InstId inst_id) : InstId(inst_id) {}
  78. using InstId::InstId;
  79. };
  80. // An ID of an instruction that is used as the destination of an initializing
  81. // expression. This should only be used as the type of a field within a typed
  82. // instruction class.
  83. //
  84. // This behaves in most respects like an InstId field, but constant evaluation
  85. // of an instruction with a destination field will not evaluate this field, and
  86. // substitution will not substitute into it.
  87. //
  88. // TODO: Decide on how substitution should handle this. Multiple instructions
  89. // can refer to the same destination, so these don't have the tree structure
  90. // that substitution expects, but we might need to substitute into the result of
  91. // an instruction.
  92. class DestInstId : public InstId {
  93. public:
  94. // Support implicit conversion from InstId so that InstId and DestInstId
  95. // have the same interface.
  96. // NOLINTNEXTLINE(google-explicit-constructor)
  97. constexpr DestInstId(InstId inst_id) : InstId(inst_id) {}
  98. using InstId::InstId;
  99. };
  100. // An ID of an instruction that is referenced as a meta-operand of an action.
  101. // This should only be used as the type of a field within a typed instruction
  102. // class.
  103. //
  104. // This is used to model cases where an action's operand is not the value
  105. // produced by another instruction, but is the other instruction itself. This is
  106. // common for actions representing template instantiation.
  107. //
  108. // This behaves in most respects like an InstId field, but evaluation of the
  109. // instruction that has this field will not fail if the instruction does not
  110. // have a constant value. If the instruction has a constant value, it will still
  111. // be replaced by its constant value during evaluation like normal, but if it
  112. // has a non-constant value, the field is left unchanged by evaluation.
  113. class MetaInstId : public InstId {
  114. public:
  115. // Support implicit conversion from InstId so that InstId and MetaInstId
  116. // have the same interface.
  117. // NOLINTNEXTLINE(google-explicit-constructor)
  118. constexpr MetaInstId(InstId inst_id) : InstId(inst_id) {}
  119. using InstId::InstId;
  120. };
  121. // The ID of a constant value of an expression. An expression is either:
  122. //
  123. // - a concrete constant, whose value does not depend on any generic parameters,
  124. // such as `42` or `i32*` or `("hello", "world")`, or
  125. // - a symbolic constant, whose value includes a generic parameter, such as
  126. // `Vector(T*)`, or
  127. // - a runtime expression, such as `Print("hello")`.
  128. //
  129. // Concrete constants are a thin wrapper around the instruction ID of the
  130. // constant instruction that defines the constant. Symbolic constants are an
  131. // index into a separate table of `SymbolicConstant`s maintained by the constant
  132. // value store.
  133. struct ConstantId : public IdBase<ConstantId> {
  134. static constexpr llvm::StringLiteral Label = "constant";
  135. // An ID for an expression that is not constant.
  136. static const ConstantId NotConstant;
  137. // Returns the constant ID corresponding to a concrete constant, which should
  138. // either be in the `constants` block in the file or should be known to be
  139. // unique.
  140. static constexpr auto ForConcreteConstant(InstId const_id) -> ConstantId {
  141. return ConstantId(const_id.index);
  142. }
  143. // Returns the constant ID corresponding to a symbolic constant index.
  144. static constexpr auto ForSymbolicConstantIndex(int32_t symbolic_index)
  145. -> ConstantId {
  146. return ConstantId(FirstSymbolicIndex - symbolic_index);
  147. }
  148. using IdBase::IdBase;
  149. // Returns whether this represents a constant. Requires has_value.
  150. constexpr auto is_constant() const -> bool {
  151. CARBON_DCHECK(has_value());
  152. return *this != ConstantId::NotConstant;
  153. }
  154. // Returns whether this represents a symbolic constant. Requires has_value.
  155. constexpr auto is_symbolic() const -> bool {
  156. CARBON_DCHECK(has_value());
  157. return index <= FirstSymbolicIndex;
  158. }
  159. // Returns whether this represents a concrete constant. Requires has_value.
  160. constexpr auto is_concrete() const -> bool {
  161. CARBON_DCHECK(has_value());
  162. return index >= 0;
  163. }
  164. // Prints this ID to the given output stream. `disambiguate` indicates whether
  165. // concrete constants should be wrapped with "concrete_constant(...)" so that
  166. // they aren't printed the same as an InstId. This can be set to false if
  167. // there is no risk of ambiguity.
  168. auto Print(llvm::raw_ostream& out, bool disambiguate = true) const -> void;
  169. private:
  170. friend class ConstantValueStore;
  171. // TODO: C++23 makes std::abs constexpr, but until then we mirror std::abs
  172. // logic here. LLVM should still optimize this.
  173. static constexpr auto Abs(int32_t i) -> int32_t { return i > 0 ? i : -i; }
  174. // Returns the instruction that describes this concrete constant value.
  175. // Requires `is_concrete()`. Use `ConstantValueStore::GetInstId` to get the
  176. // instruction ID of a `ConstantId`.
  177. constexpr auto concrete_inst_id() const -> InstId {
  178. CARBON_DCHECK(is_concrete());
  179. return InstId(index);
  180. }
  181. // Returns the symbolic constant index that describes this symbolic constant
  182. // value. Requires `is_symbolic()`.
  183. constexpr auto symbolic_index() const -> int32_t {
  184. CARBON_DCHECK(is_symbolic());
  185. return FirstSymbolicIndex - index;
  186. }
  187. static constexpr int32_t NotConstantIndex = NoneIndex - 1;
  188. static constexpr int32_t FirstSymbolicIndex = NoneIndex - 2;
  189. };
  190. constexpr ConstantId ConstantId::NotConstant = ConstantId(NotConstantIndex);
  191. // The ID of a EntityName.
  192. struct EntityNameId : public IdBase<EntityNameId> {
  193. static constexpr llvm::StringLiteral Label = "entity_name";
  194. using ValueType = EntityName;
  195. using IdBase::IdBase;
  196. };
  197. // The index of a compile-time binding. This is the de Bruijn level for the
  198. // binding -- that is, this is the number of other compile time bindings whose
  199. // scope encloses this binding.
  200. struct CompileTimeBindIndex : public IndexBase<CompileTimeBindIndex> {
  201. static constexpr llvm::StringLiteral Label = "comp_time_bind";
  202. using IndexBase::IndexBase;
  203. };
  204. // The index of a `Call` parameter in a function. These are allocated
  205. // sequentially, left-to-right, to the function parameters that will have
  206. // arguments passed to them at runtime. In a `Call` instruction, a runtime
  207. // argument will have the position in the argument list corresponding to its
  208. // `Call` parameter index.
  209. struct CallParamIndex : public IndexBase<CallParamIndex> {
  210. static constexpr llvm::StringLiteral Label = "call_param";
  211. using IndexBase::IndexBase;
  212. };
  213. // The ID of a function.
  214. struct FunctionId : public IdBase<FunctionId> {
  215. static constexpr llvm::StringLiteral Label = "function";
  216. using ValueType = Function;
  217. using IdBase::IdBase;
  218. };
  219. // The ID of an IR within the set of all IRs being evaluated in the current
  220. // check execution.
  221. struct CheckIRId : public IdBase<CheckIRId> {
  222. static constexpr llvm::StringLiteral Label = "check_ir";
  223. using IdBase::IdBase;
  224. };
  225. // The ID of a class.
  226. struct ClassId : public IdBase<ClassId> {
  227. static constexpr llvm::StringLiteral Label = "class";
  228. using ValueType = Class;
  229. using IdBase::IdBase;
  230. };
  231. // The ID of an interface.
  232. struct InterfaceId : public IdBase<InterfaceId> {
  233. static constexpr llvm::StringLiteral Label = "interface";
  234. using ValueType = Interface;
  235. using IdBase::IdBase;
  236. };
  237. // The ID of an associated constant.
  238. struct AssociatedConstantId : public IdBase<AssociatedConstantId> {
  239. static constexpr llvm::StringLiteral Label = "assoc_const";
  240. using ValueType = AssociatedConstant;
  241. using IdBase::IdBase;
  242. };
  243. // The ID of an facet type value.
  244. struct FacetTypeId : public IdBase<FacetTypeId> {
  245. static constexpr llvm::StringLiteral Label = "facet_type";
  246. using ValueType = FacetTypeInfo;
  247. using IdBase::IdBase;
  248. };
  249. // The ID of an resolved facet type value.
  250. struct IdentifiedFacetTypeId : public IdBase<IdentifiedFacetTypeId> {
  251. static constexpr llvm::StringLiteral Label = "identified_facet_type";
  252. using ValueType = IdentifiedFacetType;
  253. using IdBase::IdBase;
  254. };
  255. // The ID of an impl.
  256. struct ImplId : public IdBase<ImplId> {
  257. static constexpr llvm::StringLiteral Label = "impl";
  258. using ValueType = Impl;
  259. using IdBase::IdBase;
  260. };
  261. // The ID of a generic.
  262. struct GenericId : public IdBase<GenericId> {
  263. static constexpr llvm::StringLiteral Label = "generic";
  264. using ValueType = Generic;
  265. using IdBase::IdBase;
  266. };
  267. // The ID of a specific, which is the result of specifying the generic arguments
  268. // for a generic.
  269. struct SpecificId : public IdBase<SpecificId> {
  270. using DiagnosticType = Diagnostics::TypeInfo<std::string>;
  271. static constexpr llvm::StringLiteral Label = "specific";
  272. using ValueType = Specific;
  273. using IdBase::IdBase;
  274. };
  275. // The ID of a SpecificInterface, which is an interface and a specific pair.
  276. struct SpecificInterfaceId : public IdBase<SpecificInterfaceId> {
  277. static constexpr llvm::StringLiteral Label = "specific_interface";
  278. using ValueType = SpecificInterface;
  279. using IdBase::IdBase;
  280. };
  281. // The index of an instruction that depends on generic parameters within a
  282. // region of a generic. A corresponding specific version of the instruction can
  283. // be found in each specific corresponding to that generic. This is a pair of a
  284. // region and an index, stored in 32 bits.
  285. struct GenericInstIndex : public IndexBase<GenericInstIndex> {
  286. // Where the value is first used within the generic.
  287. enum Region : uint8_t {
  288. // In the declaration.
  289. Declaration,
  290. // In the definition.
  291. Definition,
  292. };
  293. // An index with no value.
  294. static const GenericInstIndex None;
  295. explicit constexpr GenericInstIndex(Region region, int32_t index)
  296. : IndexBase(region == Declaration ? index
  297. : FirstDefinitionIndex - index) {
  298. CARBON_CHECK(index >= 0);
  299. }
  300. // Returns the index of the instruction within the region.
  301. auto index() const -> int32_t {
  302. CARBON_CHECK(has_value());
  303. return IndexBase::index >= 0 ? IndexBase::index
  304. : FirstDefinitionIndex - IndexBase::index;
  305. }
  306. // Returns the region within which this instruction was first used.
  307. auto region() const -> Region {
  308. CARBON_CHECK(has_value());
  309. return IndexBase::index >= 0 ? Declaration : Definition;
  310. }
  311. auto Print(llvm::raw_ostream& out) const -> void;
  312. private:
  313. static constexpr auto MakeNone() -> GenericInstIndex {
  314. GenericInstIndex result(Declaration, 0);
  315. result.IndexBase::index = NoneIndex;
  316. return result;
  317. }
  318. static constexpr int32_t FirstDefinitionIndex = NoneIndex - 1;
  319. };
  320. constexpr GenericInstIndex GenericInstIndex::None =
  321. GenericInstIndex::MakeNone();
  322. struct ImportCppId : public IdBase<ImportCppId> {
  323. static constexpr llvm::StringLiteral Label = "import_cpp";
  324. using ValueType = ImportCpp;
  325. using IdBase::IdBase;
  326. };
  327. // The ID of an IR within the set of imported IRs, both direct and indirect.
  328. struct ImportIRId : public IdBase<ImportIRId> {
  329. static constexpr llvm::StringLiteral Label = "ir";
  330. using ValueType = ImportIR;
  331. // The implicit `api` import, for an `impl` file. A null entry is added if
  332. // there is none, as in an `api`, in which case this ID should not show up in
  333. // instructions.
  334. static const ImportIRId ApiForImpl;
  335. using IdBase::IdBase;
  336. };
  337. constexpr ImportIRId ImportIRId::ApiForImpl = ImportIRId(0);
  338. // A boolean value.
  339. struct BoolValue : public IdBase<BoolValue> {
  340. // Not used by `Print`, but for `IdKind`.
  341. static constexpr llvm::StringLiteral Label = "bool";
  342. static const BoolValue False;
  343. static const BoolValue True;
  344. // Returns the `BoolValue` corresponding to `b`.
  345. static constexpr auto From(bool b) -> BoolValue { return b ? True : False; }
  346. // Returns the `bool` corresponding to this `BoolValue`.
  347. constexpr auto ToBool() -> bool {
  348. CARBON_CHECK(*this == False || *this == True, "Invalid bool value {0}",
  349. index);
  350. return *this != False;
  351. }
  352. using IdBase::IdBase;
  353. auto Print(llvm::raw_ostream& out) const -> void;
  354. };
  355. constexpr BoolValue BoolValue::False = BoolValue(0);
  356. constexpr BoolValue BoolValue::True = BoolValue(1);
  357. // An integer kind value -- either "signed" or "unsigned".
  358. //
  359. // This might eventually capture any other properties of an integer type that
  360. // affect its semantics, such as overflow behavior.
  361. struct IntKind : public IdBase<IntKind> {
  362. // Not used by `Print`, but for `IdKind`.
  363. static constexpr llvm::StringLiteral Label = "int_kind";
  364. static const IntKind Unsigned;
  365. static const IntKind Signed;
  366. using IdBase::IdBase;
  367. // Returns whether this type is signed.
  368. constexpr auto is_signed() -> bool { return *this == Signed; }
  369. auto Print(llvm::raw_ostream& out) const -> void;
  370. };
  371. constexpr IntKind IntKind::Unsigned = IntKind(0);
  372. constexpr IntKind IntKind::Signed = IntKind(1);
  373. // A float kind value.
  374. struct FloatKind : public IdBase<FloatKind> {
  375. // Not used by `Print`, but for `IdKind`.
  376. static constexpr llvm::StringLiteral Label = "float_kind";
  377. using IdBase::IdBase;
  378. auto Print(llvm::raw_ostream& out) const -> void { out << "float"; }
  379. };
  380. // An X-macro for special names. Uses should look like:
  381. //
  382. // #define CARBON_SPECIAL_NAME_ID_FOR_XYZ(Name) ...
  383. // CARBON_SPECIAL_NAME_ID(CARBON_SPECIAL_NAME_ID_FOR_XYZ)
  384. // #undef CARBON_SPECIAL_NAME_ID_FOR_XYZ
  385. #define CARBON_SPECIAL_NAME_ID(X) \
  386. /* The name of `base`. */ \
  387. X(Base) \
  388. /* The name of the discriminant field (if any) in a choice. */ \
  389. X(ChoiceDiscriminant) \
  390. /* The name of the package `Core`. */ \
  391. X(Core) \
  392. /* The name of `destroy`. */ \
  393. X(Destroy) \
  394. /* The name of `package`. */ \
  395. X(PackageNamespace) \
  396. /* The name of `.Self`. */ \
  397. X(PeriodSelf) \
  398. /* The name of the return slot in a function. */ \
  399. X(ReturnSlot) \
  400. /* The name of `Self`. */ \
  401. X(SelfType) \
  402. /* The name of `self`. */ \
  403. X(SelfValue) \
  404. /* The name of `_`. */ \
  405. X(Underscore) \
  406. /* The name of `vptr`. */ \
  407. X(Vptr)
  408. // The ID of a name. A name is either a string or a special name such as
  409. // `self`, `Self`, or `base`.
  410. struct NameId : public IdBase<NameId> {
  411. static constexpr llvm::StringLiteral Label = "name";
  412. // names().GetFormatted() is used for diagnostics.
  413. using DiagnosticType = Diagnostics::TypeInfo<std::string>;
  414. // An enum of special names.
  415. enum class SpecialNameId : uint8_t {
  416. #define CARBON_SPECIAL_NAME_ID_FOR_ENUM(Name) Name,
  417. CARBON_SPECIAL_NAME_ID(CARBON_SPECIAL_NAME_ID_FOR_ENUM)
  418. #undef CARBON_SPECIAL_NAME_ID_FOR_ENUM
  419. };
  420. // For each SpecialNameId, provide a matching `NameId` instance for
  421. // convenience.
  422. #define CARBON_SPECIAL_NAME_ID_FOR_DECL(Name) static const NameId Name;
  423. CARBON_SPECIAL_NAME_ID(CARBON_SPECIAL_NAME_ID_FOR_DECL)
  424. #undef CARBON_SPECIAL_NAME_ID_FOR_DECL
  425. // The number of non-index (<0) that exist, and will need storage in name
  426. // lookup.
  427. static const int NonIndexValueCount;
  428. // Returns the NameId corresponding to a particular IdentifierId.
  429. static auto ForIdentifier(IdentifierId id) -> NameId;
  430. // Returns the NameId corresponding to a particular PackageNameId. This is the
  431. // name that is declared when the package is imported.
  432. static auto ForPackageName(PackageNameId id) -> NameId;
  433. using IdBase::IdBase;
  434. // Returns the IdentifierId corresponding to this NameId, or `None` if this is
  435. // a special name.
  436. auto AsIdentifierId() const -> IdentifierId {
  437. return index >= 0 ? IdentifierId(index) : IdentifierId::None;
  438. }
  439. // Expose special names for `switch`.
  440. constexpr auto AsSpecialNameId() const -> std::optional<SpecialNameId> {
  441. if (index >= NoneIndex) {
  442. return std::nullopt;
  443. }
  444. return static_cast<SpecialNameId>(NoneIndex - 1 - index);
  445. }
  446. auto Print(llvm::raw_ostream& out) const -> void;
  447. };
  448. // Define the special `static const NameId` values.
  449. #define CARBON_SPECIAL_NAME_ID_FOR_DEF(Name) \
  450. constexpr NameId NameId::Name = \
  451. NameId(NoneIndex - 1 - static_cast<int>(NameId::SpecialNameId::Name));
  452. CARBON_SPECIAL_NAME_ID(CARBON_SPECIAL_NAME_ID_FOR_DEF)
  453. #undef CARBON_SPECIAL_NAME_ID_FOR_DEF
  454. // Count non-index values, including `None` and special names.
  455. #define CARBON_SPECIAL_NAME_ID_FOR_COUNT(...) +1
  456. constexpr int NameId::NonIndexValueCount =
  457. 1 CARBON_SPECIAL_NAME_ID(CARBON_SPECIAL_NAME_ID_FOR_COUNT);
  458. #undef CARBON_SPECIAL_NAME_ID_FOR_COUNT
  459. // The ID of a name scope.
  460. struct NameScopeId : public IdBase<NameScopeId> {
  461. static constexpr llvm::StringLiteral Label = "name_scope";
  462. using ValueType = NameScope;
  463. // The package (or file) name scope, guaranteed to be the first added.
  464. static const NameScopeId Package;
  465. using IdBase::IdBase;
  466. };
  467. constexpr NameScopeId NameScopeId::Package = NameScopeId(0);
  468. // The ID of an instruction block.
  469. struct InstBlockId : public IdBase<InstBlockId> {
  470. static constexpr llvm::StringLiteral Label = "inst_block";
  471. // Types for BlockValueStore<InstBlockId>.
  472. using ElementType = InstId;
  473. using ValueType = llvm::MutableArrayRef<ElementType>;
  474. // The canonical empty block, reused to avoid allocating empty vectors. Always
  475. // the 0-index block.
  476. static const InstBlockId Empty;
  477. // Exported instructions. Empty until the File is fully checked; intermediate
  478. // state is in the Check::Context.
  479. static const InstBlockId Exports;
  480. // ImportRef instructions. Empty until the File is fully checked; intermediate
  481. // state is in the Check::Context.
  482. static const InstBlockId ImportRefs;
  483. // Global declaration initialization instructions. Empty if none are present.
  484. // Otherwise, __global_init function will be generated and this block will
  485. // be inserted into it.
  486. static const InstBlockId GlobalInit;
  487. // An ID for unreachable code.
  488. static const InstBlockId Unreachable;
  489. using IdBase::IdBase;
  490. auto Print(llvm::raw_ostream& out) const -> void;
  491. };
  492. constexpr InstBlockId InstBlockId::Empty = InstBlockId(0);
  493. constexpr InstBlockId InstBlockId::Exports = InstBlockId(1);
  494. constexpr InstBlockId InstBlockId::ImportRefs = InstBlockId(2);
  495. constexpr InstBlockId InstBlockId::GlobalInit = InstBlockId(3);
  496. constexpr InstBlockId InstBlockId::Unreachable = InstBlockId(NoneIndex - 1);
  497. // Contains either an `InstBlockId` value, an error value, or
  498. // `InstBlockId::None`.
  499. //
  500. // Error values are treated as values, though they are not representable as an
  501. // `InstBlockId` (unlike for the singleton error `InstId`).
  502. class InstBlockIdOrError {
  503. public:
  504. // NOLINTNEXTLINE(google-explicit-constructor)
  505. InstBlockIdOrError(SemIR::InstBlockId inst_block_id)
  506. : InstBlockIdOrError(inst_block_id, false) {}
  507. static auto MakeError() -> InstBlockIdOrError {
  508. return {SemIR::InstBlockId::None, true};
  509. }
  510. // Returns whether this class contains either an InstBlockId (other than
  511. // `None`) or an error.
  512. //
  513. // An error is treated as a value (as same for the singleton error `InstId`),
  514. // but it can not actually be materialized as an error value outside of this
  515. // class.
  516. auto has_value() const -> bool {
  517. return has_error_value() || inst_block_id_.has_value();
  518. }
  519. // Returns whether this class contains an error value.
  520. auto has_error_value() const -> bool { return error_; }
  521. // Returns the id of a non-empty inst block, or `None` if `has_value()` is
  522. // false.
  523. //
  524. // Only valid to call if `has_error_value()` is false.
  525. auto inst_block_id() const -> SemIR::InstBlockId {
  526. CARBON_CHECK(!has_error_value());
  527. return inst_block_id_;
  528. }
  529. private:
  530. InstBlockIdOrError(SemIR::InstBlockId inst_block_id, bool error)
  531. : inst_block_id_(inst_block_id), error_(error) {}
  532. SemIR::InstBlockId inst_block_id_;
  533. bool error_;
  534. };
  535. // An ID of an instruction block that is referenced absolutely by an
  536. // instruction. This should only be used as the type of a field within a typed
  537. // instruction class. See AbsoluteInstId.
  538. class AbsoluteInstBlockId : public InstBlockId {
  539. public:
  540. // Support implicit conversion from InstBlockId so that InstBlockId and
  541. // AbsoluteInstBlockId have the same interface.
  542. // NOLINTNEXTLINE(google-explicit-constructor)
  543. constexpr AbsoluteInstBlockId(InstBlockId inst_block_id)
  544. : InstBlockId(inst_block_id) {}
  545. using InstBlockId::InstBlockId;
  546. };
  547. // An ID of an instruction block that is used as the declaration block within a
  548. // declaration instruction. This is a block that is nested within the
  549. // instruction, but doesn't contribute to its value. Such blocks are not
  550. // included in the fingerprint of the declaration. This should only be used as
  551. // the type of a field within a typed instruction class.
  552. class DeclInstBlockId : public InstBlockId {
  553. public:
  554. // Support implicit conversion from InstBlockId so that InstBlockId and
  555. // DeclInstBlockId have the same interface.
  556. // NOLINTNEXTLINE(google-explicit-constructor)
  557. constexpr DeclInstBlockId(InstBlockId inst_block_id)
  558. : InstBlockId(inst_block_id) {}
  559. using InstBlockId::InstBlockId;
  560. };
  561. // An ID of an instruction block that is used as a label in a branch instruction
  562. // or similar. This is a block that is not nested within the instruction, but
  563. // instead exists elsewhere in the enclosing executable region. This should
  564. // only be used as the type of a field within a typed instruction class.
  565. class LabelId : public InstBlockId {
  566. public:
  567. // Support implicit conversion from InstBlockId so that InstBlockId and
  568. // LabelId have the same interface.
  569. // NOLINTNEXTLINE(google-explicit-constructor)
  570. constexpr LabelId(InstBlockId inst_block_id) : InstBlockId(inst_block_id) {}
  571. using InstBlockId::InstBlockId;
  572. };
  573. // TODO: Move this out of sem_ir and into check, if we don't wind up using it
  574. // in the SemIR for expression patterns.
  575. struct ExprRegionId : public IdBase<ExprRegionId> {
  576. static constexpr llvm::StringLiteral Label = "region";
  577. using ValueType = ExprRegion;
  578. using IdBase::IdBase;
  579. };
  580. // The ID of a struct type field block.
  581. struct StructTypeFieldsId : public IdBase<StructTypeFieldsId> {
  582. static constexpr llvm::StringLiteral Label = "struct_type_fields";
  583. // Types for BlockValueStore<StructTypeFieldsId>.
  584. using ElementType = StructTypeField;
  585. using ValueType = llvm::MutableArrayRef<StructTypeField>;
  586. // The canonical empty block, reused to avoid allocating empty vectors. Always
  587. // the 0-index block.
  588. static const StructTypeFieldsId Empty;
  589. using IdBase::IdBase;
  590. };
  591. constexpr StructTypeFieldsId StructTypeFieldsId::Empty = StructTypeFieldsId(0);
  592. // The ID of a type.
  593. struct TypeId : public IdBase<TypeId> {
  594. static constexpr llvm::StringLiteral Label = "type";
  595. // `StringifyConstantInst` is used for diagnostics. However, where possible,
  596. // an `InstId` describing how the type was written should be preferred, using
  597. // `InstIdAsType` or `TypeOfInstId` as the diagnostic argument type.
  598. using DiagnosticType = Diagnostics::TypeInfo<std::string>;
  599. using IdBase::IdBase;
  600. // Returns the ID of the type corresponding to the constant `const_id`, which
  601. // must be of type `type`. As an exception, the type `Error` is of type
  602. // `Error`.
  603. static constexpr auto ForTypeConstant(ConstantId const_id) -> TypeId {
  604. return TypeId(const_id.index);
  605. }
  606. // Returns the constant ID that defines the type.
  607. auto AsConstantId() const -> ConstantId { return ConstantId(index); }
  608. // Returns whether this represents a symbolic type. Requires has_value.
  609. auto is_symbolic() const -> bool { return AsConstantId().is_symbolic(); }
  610. // Returns whether this represents a concrete type. Requires has_value.
  611. auto is_concrete() const -> bool { return AsConstantId().is_concrete(); }
  612. auto Print(llvm::raw_ostream& out) const -> void;
  613. };
  614. // An index for element access, for structs, tuples, and classes.
  615. struct ElementIndex : public IndexBase<ElementIndex> {
  616. static constexpr llvm::StringLiteral Label = "element";
  617. using IndexBase::IndexBase;
  618. };
  619. // The ID of a library name. This is either a string literal or `default`.
  620. struct LibraryNameId : public IdBase<LibraryNameId> {
  621. static constexpr llvm::StringLiteral Label = "library_name";
  622. using DiagnosticType = Diagnostics::TypeInfo<std::string>;
  623. // The name of `default`.
  624. static const LibraryNameId Default;
  625. // Track cases where the library name was set, but has been diagnosed and
  626. // shouldn't be used anymore.
  627. static const LibraryNameId Error;
  628. // Returns the LibraryNameId for a library name as a string literal.
  629. static auto ForStringLiteralValueId(StringLiteralValueId id) -> LibraryNameId;
  630. using IdBase::IdBase;
  631. // Converts a LibraryNameId back to a string literal.
  632. auto AsStringLiteralValueId() const -> StringLiteralValueId {
  633. CARBON_CHECK(index >= NoneIndex, "{0} must be handled directly", *this);
  634. return StringLiteralValueId(index);
  635. }
  636. auto Print(llvm::raw_ostream& out) const -> void;
  637. };
  638. constexpr LibraryNameId LibraryNameId::Default = LibraryNameId(NoneIndex - 1);
  639. constexpr LibraryNameId LibraryNameId::Error = LibraryNameId(NoneIndex - 2);
  640. // The ID of an ImportIRInst.
  641. struct ImportIRInstId : public IdBase<ImportIRInstId> {
  642. static constexpr llvm::StringLiteral Label = "import_ir_inst";
  643. using ValueType = ImportIRInst;
  644. // ImportIRInstId is restricted so that it can fit into LocId.
  645. static constexpr int32_t BitsWithNodeId = 29;
  646. // The maximum ID, non-inclusive.
  647. static constexpr int Max = (1 << BitsWithNodeId) - Parse::NodeId::Max - 2;
  648. constexpr explicit ImportIRInstId(int32_t index) : IdBase(index) {
  649. CARBON_DCHECK(index < Max, "Index out of range: {0}", index);
  650. }
  651. };
  652. // A SemIR location used as the location of instructions. This contains either a
  653. // InstId, NodeId, ImportIRInstId, or None. The intent is that any of these can
  654. // indicate the source of an instruction, and also be used to associate a line
  655. // in diagnostics.
  656. //
  657. // The structure is:
  658. // - None: The standard NoneIndex for all Id types, -1.
  659. // - InstId: positive values including zero; a full 31 bits.
  660. // - [0, 1 << 31)
  661. // - NodeId: negative values starting after None; the 24 bit NodeId range.
  662. // - [-2, -2 - (1 << 24))
  663. // - ImportIRInstId: remaining negative values; after NodeId, fills out negative
  664. // values to 29 bits.
  665. // - [-2 - (1 << 24), -(1 << 29))
  666. //
  667. // In addition, two bits are used for flags: `ImplicitBit` and `TokenOnlyBit`.
  668. // Note that these can only be used with negative, non-`InstId` values.
  669. struct LocId : public IdBase<LocId> {
  670. // The contained index kind.
  671. enum class Kind {
  672. None,
  673. ImportIRInstId,
  674. InstId,
  675. NodeId,
  676. };
  677. static constexpr llvm::StringLiteral Label = "loc";
  678. using IdBase::IdBase;
  679. // NOLINTNEXTLINE(google-explicit-constructor)
  680. constexpr LocId(ImportIRInstId import_ir_inst_id)
  681. : IdBase(import_ir_inst_id.has_value()
  682. ? FirstImportIRInstId - import_ir_inst_id.index
  683. : NoneIndex) {}
  684. // NOLINTNEXTLINE(google-explicit-constructor)
  685. constexpr LocId(InstId inst_id) : IdBase(inst_id.index) {}
  686. // NOLINTNEXTLINE(google-explicit-constructor)
  687. constexpr LocId(Parse::NoneNodeId /*none*/) : IdBase(NoneIndex) {}
  688. // NOLINTNEXTLINE(google-explicit-constructor)
  689. constexpr LocId(Parse::NodeId node_id)
  690. : IdBase(FirstNodeId - node_id.index) {}
  691. // Forms an equivalent LocId for a desugared location. Requires a
  692. // non-`InstId` location.
  693. // TODO: Rename to something like `ToDesugared`.
  694. auto ToImplicit() const -> LocId {
  695. // This should only be called for NodeId or ImportIRInstId, but we only set
  696. // the flag for NodeId.
  697. CARBON_CHECK(kind() != Kind::InstId);
  698. if (kind() == Kind::NodeId) {
  699. return LocId(index & ~ImplicitBit);
  700. }
  701. return *this;
  702. }
  703. // Forms an equivalent `LocId` for a token-only diagnostic location. Requires
  704. // a non-`InstId` location.
  705. auto ToTokenOnly() const -> LocId {
  706. CARBON_CHECK(kind() != Kind::InstId);
  707. if (has_value()) {
  708. return LocId(index & ~TokenOnlyBit);
  709. }
  710. return *this;
  711. }
  712. // Returns the kind of the `LocId`.
  713. auto kind() const -> Kind {
  714. if (!has_value()) {
  715. return Kind::None;
  716. }
  717. if (index >= 0) {
  718. return Kind::InstId;
  719. }
  720. if (index_without_flags() <= FirstImportIRInstId) {
  721. return Kind::ImportIRInstId;
  722. }
  723. return Kind::NodeId;
  724. }
  725. // Returns true if the location corresponds to desugared instructions.
  726. // Requires a non-`InstId` location.
  727. auto is_implicit() const -> bool {
  728. CARBON_CHECK(kind() != Kind::InstId);
  729. return (kind() == Kind::NodeId) && (index & ImplicitBit) == 0;
  730. }
  731. // Returns true if the location is token-only for diagnostics. Requires a
  732. // non-`InstId` location.
  733. auto is_token_only() const -> bool {
  734. CARBON_CHECK(kind() != Kind::InstId);
  735. return (index & TokenOnlyBit) == 0;
  736. }
  737. // Returns the equivalent `ImportIRInstId` when `kind()` matches or is `None`.
  738. auto import_ir_inst_id() const -> ImportIRInstId {
  739. if (!has_value()) {
  740. return ImportIRInstId::None;
  741. }
  742. CARBON_CHECK(kind() == Kind::ImportIRInstId, "{0}", index);
  743. return ImportIRInstId(FirstImportIRInstId - index_without_flags());
  744. }
  745. // Returns the equivalent `InstId` when `kind()` matches or is `None`.
  746. auto inst_id() const -> InstId {
  747. CARBON_CHECK(kind() == Kind::None || kind() == Kind::InstId, "{0}", index);
  748. return InstId(index);
  749. }
  750. // Returns the equivalent `NodeId` when `kind()` matches or is `None`.
  751. auto node_id() const -> Parse::NodeId {
  752. if (!has_value()) {
  753. return Parse::NodeId::None;
  754. }
  755. CARBON_CHECK(kind() == Kind::NodeId, "{0}", index);
  756. return Parse::NodeId(FirstNodeId - index_without_flags());
  757. }
  758. auto Print(llvm::raw_ostream& out) const -> void;
  759. private:
  760. // Whether a location corresponds to desugared instructions. This only applies
  761. // for `NodeId`.
  762. static constexpr int32_t ImplicitBit = 1 << 30;
  763. // See `token_only` for the use. This only applies for `NodeId` and
  764. // `ImportIRInstId`.
  765. static constexpr int32_t TokenOnlyBit = 1 << 29;
  766. // The value of the 0 index for each of `NodeId` and `ImportIRInstId`.
  767. static constexpr int32_t FirstNodeId = NoneIndex - 1;
  768. static constexpr int32_t FirstImportIRInstId =
  769. FirstNodeId - Parse::NodeId::Max;
  770. auto index_without_flags() const -> int32_t {
  771. CARBON_DCHECK(index < NoneIndex, "Only for NodeId and ImportIRInstId");
  772. return index | ImplicitBit | TokenOnlyBit;
  773. }
  774. };
  775. // Polymorphic id for fields in `Any[...]` typed instruction category. Used for
  776. // fields where the specific instruction structs have different field types in
  777. // that position or do not have a field in that position at all. Allows
  778. // conversion with `Inst::As<>` from the specific typed instruction to the
  779. // `Any[...]` instruction category.
  780. //
  781. // This type participates in `Inst::FromRaw` in order to convert from specific
  782. // instructions to an `Any[...]` instruction category:
  783. // - In the case the specific instruction has a field of some `IdKind` in the
  784. // same position, the `Any[...]` type will hold its raw value in the
  785. // `AnyRawId` field.
  786. // - In the case the specific instruction has no field in the same position, the
  787. // `Any[...]` type will hold a default constructed `AnyRawId` with a `None`
  788. // value.
  789. struct AnyRawId : public AnyIdBase {
  790. // For IdKind.
  791. static constexpr llvm::StringLiteral Label = "any_raw";
  792. constexpr explicit AnyRawId() : AnyIdBase(AnyIdBase::NoneIndex) {}
  793. constexpr explicit AnyRawId(int32_t id) : AnyIdBase(id) {}
  794. };
  795. // A pair of an interface and a specific for that interface.
  796. struct SpecificInterface {
  797. InterfaceId interface_id;
  798. SpecificId specific_id;
  799. static const SpecificInterface None;
  800. friend auto operator==(const SpecificInterface& lhs,
  801. const SpecificInterface& rhs) -> bool = default;
  802. };
  803. constexpr SpecificInterface SpecificInterface::None = {
  804. .interface_id = InterfaceId::None, .specific_id = SpecificId::None};
  805. } // namespace Carbon::SemIR
  806. #endif // CARBON_TOOLCHAIN_SEM_IR_IDS_H_