ids.h 37 KB

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