ids.h 38 KB

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