ids.h 40 KB

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