inst.h 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753
  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_INST_H_
  5. #define CARBON_TOOLCHAIN_SEM_IR_INST_H_
  6. #include <concepts>
  7. #include <cstdint>
  8. #include "common/check.h"
  9. #include "common/hashing.h"
  10. #include "common/ostream.h"
  11. #include "common/raw_string_ostream.h"
  12. #include "common/struct_reflection.h"
  13. #include "toolchain/base/block_value_store.h"
  14. #include "toolchain/base/index_base.h"
  15. #include "toolchain/base/int.h"
  16. #include "toolchain/base/value_store.h"
  17. #include "toolchain/sem_ir/id_kind.h"
  18. #include "toolchain/sem_ir/ids.h"
  19. #include "toolchain/sem_ir/inst_kind.h"
  20. #include "toolchain/sem_ir/singleton_insts.h"
  21. #include "toolchain/sem_ir/typed_insts.h"
  22. namespace Carbon::SemIR {
  23. template <typename... TypedInsts>
  24. struct CategoryOf;
  25. class File;
  26. // InstLikeTypeInfo is an implementation detail, and not public API.
  27. namespace Internal {
  28. // Information about an instruction-like type, which is a type that an Inst can
  29. // be converted to and from.
  30. template <typename InstLikeType>
  31. struct InstLikeTypeInfo;
  32. // A helper base class for instruction-like types that are structs.
  33. template <typename InstLikeType>
  34. struct InstLikeTypeInfoBase {
  35. // A corresponding std::tuple<...> type.
  36. using Tuple =
  37. decltype(StructReflection::AsTuple(std::declval<InstLikeType>()));
  38. static constexpr int FirstArgField =
  39. HasKindMemberAsField<InstLikeType> + HasTypeIdMember<InstLikeType>;
  40. static constexpr int NumArgs = std::tuple_size_v<Tuple> - FirstArgField;
  41. static_assert(NumArgs <= 2,
  42. "Unsupported: typed inst has more than two data fields");
  43. template <int N>
  44. using ArgType = std::tuple_element_t<FirstArgField + N, Tuple>;
  45. template <int N>
  46. static auto Get(InstLikeType inst) -> ArgType<N> {
  47. return std::get<FirstArgField + N>(StructReflection::AsTuple(inst));
  48. }
  49. };
  50. // A particular type of instruction is instruction-like.
  51. template <typename TypedInst>
  52. requires std::same_as<const InstKind::Definition<
  53. typename decltype(TypedInst::Kind)::TypedNodeId>,
  54. decltype(TypedInst::Kind)>
  55. struct InstLikeTypeInfo<TypedInst> : InstLikeTypeInfoBase<TypedInst> {
  56. static_assert(!HasKindMemberAsField<TypedInst>,
  57. "Instruction type should not have a kind field");
  58. static auto GetKind(TypedInst /*inst*/) -> InstKind {
  59. return TypedInst::Kind;
  60. }
  61. static constexpr auto IsKind(InstKind kind) -> bool {
  62. return kind == TypedInst::Kind;
  63. }
  64. // A name that can be streamed to an llvm::raw_ostream.
  65. static auto DebugName() -> InstKind { return TypedInst::Kind; }
  66. };
  67. // If `TypedInst` has an Nth field, validates that `CategoryInst` has a
  68. // corresponding field with a compatible type.
  69. template <typename CategoryInst, typename TypedInst, size_t N>
  70. static consteval auto ValidateCategoryFieldForTypedInst() -> void {
  71. if constexpr (InstLikeTypeInfoBase<TypedInst>::NumArgs > N) {
  72. if constexpr (!std::is_same_v<typename InstLikeTypeInfoBase<
  73. CategoryInst>::template ArgType<N>,
  74. AnyRawId>) {
  75. static_assert(
  76. std::is_same_v<
  77. typename InstLikeTypeInfoBase<CategoryInst>::template ArgType<N>,
  78. typename InstLikeTypeInfoBase<TypedInst>::template ArgType<N>>,
  79. "Inst category field should be the same type as the "
  80. "corresponding fields of its typed insts, or AnyRawId if "
  81. "they have different types");
  82. }
  83. }
  84. }
  85. // Validates that `CategoryInst` is compatible with `TypedInst`
  86. template <typename CategoryInst, typename TypedInst>
  87. static consteval auto ValidateCategoryForTypedInst() -> void {
  88. static_assert(Internal::HasKindMemberAsField<CategoryInst>,
  89. "Inst category should have an `InstKind` field");
  90. static_assert(!HasTypeIdMember<TypedInst> || HasTypeIdMember<CategoryInst>,
  91. "Inst category should have a `TypeId` field if any of its "
  92. "typed insts do");
  93. static_assert(InstLikeTypeInfoBase<CategoryInst>::NumArgs >=
  94. InstLikeTypeInfoBase<TypedInst>::NumArgs,
  95. "Inst category should have as many fields as any of its typed "
  96. "insts");
  97. ValidateCategoryFieldForTypedInst<CategoryInst, TypedInst, 0>();
  98. ValidateCategoryFieldForTypedInst<CategoryInst, TypedInst, 1>();
  99. }
  100. // Validates that `CategoryInst` is compatible with all of `TypedInsts`.
  101. // Always returns true; validation failure will cause build errors when
  102. // instantiating the function.
  103. template <typename CategoryInst, typename... TypedInsts>
  104. static consteval auto ValidateCategory(
  105. CategoryOf<TypedInsts...> /*category_info*/) -> bool {
  106. (ValidateCategoryForTypedInst<CategoryInst, TypedInsts>(), ...);
  107. return true;
  108. }
  109. // An instruction category is instruction-like.
  110. template <typename InstCat>
  111. requires requires { typename InstCat::CategoryInfo; }
  112. struct InstLikeTypeInfo<InstCat> : InstLikeTypeInfoBase<InstCat> {
  113. static auto GetKind(InstCat cat) -> InstKind { return cat.kind; }
  114. static constexpr auto IsKind(InstKind kind) -> bool {
  115. for (InstKind k : InstCat::CategoryInfo::Kinds) {
  116. if (k == kind) {
  117. return true;
  118. }
  119. }
  120. return false;
  121. }
  122. // A name that can be streamed to an llvm::raw_ostream.
  123. static auto DebugName() -> std::string {
  124. RawStringOstream out;
  125. out << "{";
  126. llvm::ListSeparator sep;
  127. for (auto kind : InstCat::CategoryInfo::Kinds) {
  128. out << sep << kind;
  129. }
  130. out << "}";
  131. return out.TakeStr();
  132. }
  133. private:
  134. // Trigger validation of `InstCat`.
  135. static_assert(ValidateCategory<InstCat>(typename InstCat::CategoryInfo()));
  136. };
  137. // HasInstCategory is true if T::Kind is an element of InstCat::Kinds.
  138. template <typename InstCat, typename T>
  139. concept HasInstCategory = InstLikeTypeInfo<InstCat>::IsKind(T::Kind);
  140. // A type is InstLike if InstLikeTypeInfo is defined for it.
  141. template <typename T>
  142. concept InstLikeType = requires { sizeof(InstLikeTypeInfo<T>); };
  143. } // namespace Internal
  144. // A type-erased representation of a SemIR instruction, that may be constructed
  145. // from the specific kinds of instruction defined in `typed_insts.h`. This
  146. // provides access to common fields present on most or all kinds of
  147. // instructions:
  148. //
  149. // - `kind` for run-time logic when the input Kind is unknown.
  150. // - `type_id` for quick type checking.
  151. //
  152. // In addition, kind-specific data can be accessed by casting to the specific
  153. // kind of instruction:
  154. //
  155. // - Use `inst.kind()` or `Is<InstLikeType>` to determine what kind of
  156. // instruction it is.
  157. // - Cast to a specific type using `inst.As<InstLikeType>()`
  158. // - Using the wrong kind in `inst.As<InstLikeType>()` is a programming error,
  159. // and will CHECK-fail in debug modes (opt may too, but it's not an API
  160. // guarantee).
  161. // - Use `inst.TryAs<InstLikeType>()` to safely access type-specific instruction
  162. // data where the instruction's kind is not known.
  163. class Inst : public Printable<Inst> {
  164. public:
  165. // Associates an argument (arg0 or arg1) with its IdKind.
  166. class ArgAndKind {
  167. public:
  168. explicit ArgAndKind(IdKind kind, int32_t value)
  169. : kind_(kind), value_(value) {}
  170. // Converts to `IdT`, validating the `kind` matches.
  171. template <typename IdT>
  172. auto As() const -> IdT {
  173. CARBON_DCHECK(kind_ == IdKind::For<IdT>);
  174. return IdT(value_);
  175. }
  176. // Converts to `IdT`, returning nullopt if the kind is incorrect.
  177. template <typename IdT>
  178. auto TryAs() const -> std::optional<IdT> {
  179. if (kind_ != IdKind::For<IdT>) {
  180. return std::nullopt;
  181. }
  182. return IdT(value_);
  183. }
  184. auto kind() const -> IdKind { return kind_; }
  185. auto value() const -> int32_t { return value_; }
  186. private:
  187. IdKind kind_;
  188. int32_t value_;
  189. };
  190. // Makes an instruction for a singleton. This exists to support simple
  191. // construction of all singletons by File.
  192. static auto MakeSingleton(InstKind kind) -> Inst {
  193. CARBON_CHECK(IsSingletonInstKind(kind));
  194. // Error uses a self-referential type so that it's not accidentally treated
  195. // as a normal type. Every other builtin is a type, including the
  196. // self-referential TypeType.
  197. auto type_id =
  198. kind == InstKind::ErrorInst ? ErrorInst::TypeId : TypeType::TypeId;
  199. return Inst(kind, type_id, InstId::NoneIndex, InstId::NoneIndex);
  200. }
  201. template <typename TypedInst>
  202. requires Internal::InstLikeType<TypedInst>
  203. explicit(false) Inst(TypedInst typed_inst)
  204. // kind_ is always overwritten below.
  205. : kind_(),
  206. type_id_(TypeId::None),
  207. arg0_(InstId::NoneIndex),
  208. arg1_(InstId::NoneIndex) {
  209. if constexpr (Internal::HasKindMemberAsField<TypedInst>) {
  210. kind_ = typed_inst.kind.AsInt();
  211. } else {
  212. kind_ = TypedInst::Kind.AsInt();
  213. }
  214. if constexpr (Internal::HasTypeIdMember<TypedInst>) {
  215. type_id_ = typed_inst.type_id;
  216. }
  217. using Info = Internal::InstLikeTypeInfo<TypedInst>;
  218. if constexpr (Info::NumArgs > 0) {
  219. arg0_ = ToRaw(Info::template Get<0>(typed_inst));
  220. }
  221. if constexpr (Info::NumArgs > 1) {
  222. arg1_ = ToRaw(Info::template Get<1>(typed_inst));
  223. }
  224. }
  225. // Returns whether this instruction has the specified type.
  226. template <typename TypedInst>
  227. requires Internal::InstLikeType<TypedInst>
  228. auto Is() const -> bool {
  229. return Internal::InstLikeTypeInfo<TypedInst>::IsKind(kind());
  230. }
  231. // Returns whether this instruction has one of the specified types.
  232. template <typename... TypedInsts>
  233. requires(... && Internal::InstLikeType<TypedInsts>)
  234. auto IsOneOf() const -> bool {
  235. return (... || Internal::InstLikeTypeInfo<TypedInsts>::IsKind(kind()));
  236. }
  237. // Casts this instruction to the given typed instruction, which must match the
  238. // instruction's kind, and returns the typed instruction.
  239. template <typename TypedInst>
  240. requires Internal::InstLikeType<TypedInst>
  241. auto As() const -> TypedInst {
  242. using Info = Internal::InstLikeTypeInfo<TypedInst>;
  243. CARBON_CHECK(Is<TypedInst>(), "Casting inst {0} to wrong kind {1}", *this,
  244. Info::DebugName());
  245. auto build_with_type_id_onwards = [&](auto... type_id_onwards) {
  246. if constexpr (Internal::HasKindMemberAsField<TypedInst>) {
  247. return TypedInst{kind(), type_id_onwards...};
  248. } else {
  249. return TypedInst{type_id_onwards...};
  250. }
  251. };
  252. auto build_with_args = [&](auto... args) {
  253. if constexpr (Internal::HasTypeIdMember<TypedInst>) {
  254. return build_with_type_id_onwards(type_id(), args...);
  255. } else {
  256. return build_with_type_id_onwards(args...);
  257. }
  258. };
  259. if constexpr (Info::NumArgs == 0) {
  260. return build_with_args();
  261. } else if constexpr (Info::NumArgs == 1) {
  262. return build_with_args(
  263. FromRaw<typename Info::template ArgType<0>>(arg0_));
  264. } else if constexpr (Info::NumArgs == 2) {
  265. return build_with_args(
  266. FromRaw<typename Info::template ArgType<0>>(arg0_),
  267. FromRaw<typename Info::template ArgType<1>>(arg1_));
  268. }
  269. }
  270. // If this instruction is the given kind, returns a typed instruction,
  271. // otherwise returns nullopt.
  272. template <typename TypedInst>
  273. requires Internal::InstLikeType<TypedInst>
  274. auto TryAs() const -> std::optional<TypedInst> {
  275. if (Is<TypedInst>()) {
  276. return As<TypedInst>();
  277. } else {
  278. return std::nullopt;
  279. }
  280. }
  281. auto kind() const -> InstKind { return InstKind::FromInt(kind_); }
  282. // Gets the type of the value produced by evaluating this instruction.
  283. auto type_id() const -> TypeId { return type_id_; }
  284. // Gets the first argument of the instruction. NoneIndex if there is no such
  285. // argument.
  286. auto arg0() const -> int32_t { return arg0_; }
  287. // Gets the second argument of the instruction. NoneIndex if there is no such
  288. // argument.
  289. auto arg1() const -> int32_t { return arg1_; }
  290. // Returns arguments with their IdKind.
  291. auto arg0_and_kind() const -> ArgAndKind {
  292. return ArgAndKind(ArgKindTable[kind_].first, arg0_);
  293. }
  294. auto arg1_and_kind() const -> ArgAndKind {
  295. return ArgAndKind(ArgKindTable[kind_].second, arg1_);
  296. }
  297. // Sets the type of this instruction.
  298. auto SetType(TypeId type_id) -> void { type_id_ = type_id; }
  299. // Sets the arguments of this instruction.
  300. auto SetArgs(int32_t arg0, int32_t arg1) -> void {
  301. arg0_ = arg0;
  302. arg1_ = arg1;
  303. }
  304. // Convert a field to its raw representation, used as `arg0_` / `arg1_`.
  305. static constexpr auto ToRaw(AnyIdBase base) -> int32_t { return base.index; }
  306. static constexpr auto ToRaw(IntId id) -> int32_t { return id.AsRaw(); }
  307. // Convert a field from its raw representation.
  308. template <typename T>
  309. requires IdKind::Contains<T>
  310. static constexpr auto FromRaw(int32_t raw) -> T {
  311. return T(raw);
  312. }
  313. template <>
  314. constexpr auto FromRaw<IntId>(int32_t raw) -> IntId {
  315. return IntId::MakeRaw(raw);
  316. }
  317. auto Print(llvm::raw_ostream& out) const -> void;
  318. friend auto operator==(Inst lhs, Inst rhs) -> bool {
  319. return std::memcmp(&lhs, &rhs, sizeof(Inst)) == 0;
  320. }
  321. private:
  322. friend class InstTestHelper;
  323. // Table mapping instruction kinds to their argument kinds.
  324. //
  325. // TODO: ArgKindTable would ideally live on InstKind, but can't be there for
  326. // layering reasons.
  327. static const std::pair<IdKind, IdKind> ArgKindTable[];
  328. // Raw constructor, used for testing.
  329. explicit Inst(InstKind kind, TypeId type_id, int32_t arg0, int32_t arg1)
  330. : Inst(kind.AsInt(), type_id, arg0, arg1) {}
  331. explicit constexpr Inst(int32_t kind, TypeId type_id, int32_t arg0,
  332. int32_t arg1)
  333. : kind_(kind), type_id_(type_id), arg0_(arg0), arg1_(arg1) {}
  334. int32_t kind_;
  335. TypeId type_id_;
  336. // Use `As` to access arg0 and arg1.
  337. int32_t arg0_;
  338. int32_t arg1_;
  339. };
  340. // TODO: This is currently 16 bytes because we sometimes have 2 arguments for a
  341. // pair of Insts. However, InstKind is 1 byte; if args were 3.5 bytes, we could
  342. // potentially shrink Inst by 4 bytes. This may be worth investigating further.
  343. // Note though that 16 bytes is an ideal size for registers, we may want more
  344. // flags, and 12 bytes would be a more marginal improvement.
  345. static_assert(sizeof(Inst) == 16, "Unexpected Inst size");
  346. // Instruction-like types can be printed by converting them to instructions.
  347. template <typename TypedInst>
  348. requires Internal::InstLikeType<TypedInst>
  349. inline auto operator<<(llvm::raw_ostream& out, TypedInst inst)
  350. -> llvm::raw_ostream& {
  351. Inst(inst).Print(out);
  352. return out;
  353. }
  354. // Associates a LocId and Inst in order to provide type-checking that the
  355. // TypedNodeId corresponds to the InstT.
  356. struct LocIdAndInst {
  357. // Constructs a LocIdAndInst with no associated location. This should be used
  358. // very sparingly: only when it doesn't make sense to store a location even
  359. // when the instruction kind usually has one, such as for instructions in the
  360. // constants block.
  361. template <typename InstT>
  362. static auto NoLoc(InstT inst) -> LocIdAndInst {
  363. return LocIdAndInst(LocId::None, inst, /*is_unchecked=*/true);
  364. }
  365. // Constructs a `LocIdAndInst` with a runtime verification of the location.
  366. //
  367. // Prefer `LocIdAndInst` constructors with compile-time verification,
  368. // or `AddInst` overloads which make use of those constructors.
  369. static auto RuntimeVerified(const File& file, LocId loc_id, Inst inst)
  370. -> LocIdAndInst;
  371. // Construction for the common case with a typed node.
  372. template <typename InstT>
  373. requires(Internal::HasNodeId<InstT>)
  374. LocIdAndInst(decltype(InstT::Kind)::TypedNodeId node_id, InstT inst)
  375. : loc_id(node_id), inst(inst) {}
  376. // Construction for the case where the instruction can have any associated
  377. // node.
  378. template <typename InstT>
  379. requires(Internal::HasUntypedNodeId<InstT>)
  380. LocIdAndInst(LocId loc_id, InstT inst) : loc_id(loc_id), inst(inst) {}
  381. // For `ImportIRInstId`, use `RuntimeVerified`.
  382. template <typename InstT>
  383. LocIdAndInst(ImportIRInstId loc_id, InstT inst) = delete;
  384. LocId loc_id;
  385. Inst inst;
  386. private:
  387. // For `InstStore::GetWithLocId` to construct unchecked values.
  388. friend class InstStore;
  389. // Note `is_unchecked` serves to disambiguate from public constructors.
  390. explicit LocIdAndInst(LocId loc_id, Inst inst, bool /*is_unchecked*/)
  391. : loc_id(loc_id), inst(inst) {}
  392. };
  393. // Provides a ValueStore wrapper for an API specific to instructions.
  394. //
  395. // InstIds in this store are tagged by an IdTag using the File's CheckIRId as
  396. // the tag value.
  397. class InstStore {
  398. public:
  399. using IdType = InstId;
  400. using IdTagType = IdTag<IdType, Tag<CheckIRId>>;
  401. explicit InstStore(File* file, int32_t reserved_inst_ids);
  402. // Adds an instruction to the instruction list, returning an ID to reference
  403. // the instruction. Note that this doesn't add the instruction to any
  404. // instruction block. Check::Context::AddInst or InstBlockStack::AddInst
  405. // should usually be used instead, to add the instruction to the current
  406. // block.
  407. auto AddInNoBlock(LocIdAndInst loc_id_and_inst) -> InstId {
  408. loc_ids_.push_back(loc_id_and_inst.loc_id);
  409. return values_.Add(loc_id_and_inst.inst);
  410. }
  411. // Returns the requested instruction. The returned instruction always has an
  412. // unattached type, even if an attached type is stored for it.
  413. auto Get(InstId inst_id) const -> Inst {
  414. Inst result = values_.Get(inst_id);
  415. auto type_id = result.type_id();
  416. if (type_id.has_value() && type_id.is_symbolic()) {
  417. result.SetType(GetUnattachedType(type_id));
  418. }
  419. return result;
  420. }
  421. // Returns the requested instruction, which is known to have the specified
  422. // type.
  423. template <typename InstT>
  424. auto Get(KnownInstId<InstT> inst_id) const -> InstT {
  425. return Get(static_cast<InstId>(inst_id)).As<InstT>();
  426. }
  427. // Returns the requested instruction, preserving its attached type.
  428. auto GetWithAttachedType(InstId inst_id) const -> Inst {
  429. return values_.Get(inst_id);
  430. }
  431. // Returns the type of the instruction as an attached type.
  432. auto GetAttachedType(InstId inst_id) const -> TypeId {
  433. return GetWithAttachedType(inst_id).type_id();
  434. }
  435. // Returns the requested instruction and its location ID.
  436. auto GetWithLocId(InstId inst_id) const -> LocIdAndInst {
  437. return LocIdAndInst(LocId(inst_id), Get(inst_id), /*is_unchecked=*/true);
  438. }
  439. // Returns whether the requested instruction is the specified type.
  440. template <typename InstT>
  441. auto Is(InstId inst_id) const -> bool {
  442. return Get(inst_id).Is<InstT>();
  443. }
  444. // Returns whether the requested instruction is one of the specified types.
  445. template <typename... InstTs>
  446. auto IsOneOf(InstId inst_id) const -> bool {
  447. return Get(inst_id).IsOneOf<InstTs...>();
  448. }
  449. // Returns the requested instruction, which is known to have the specified
  450. // type.
  451. template <typename InstT>
  452. auto GetAs(InstId inst_id) const -> InstT {
  453. return Get(inst_id).As<InstT>();
  454. }
  455. // Returns the requested instruction as the specified type, if it is of that
  456. // type.
  457. template <typename InstT>
  458. auto TryGetAs(InstId inst_id) const -> std::optional<InstT> {
  459. return Get(inst_id).TryAs<InstT>();
  460. }
  461. // Use `Get()` when the instruction type is known.
  462. template <typename InstT, typename KnownInstT>
  463. auto TryGetAs(KnownInstId<KnownInstT> inst_id) const = delete;
  464. // Returns the requested instruction as the specified type, if it is valid and
  465. // of that type. Otherwise returns nullopt.
  466. template <typename InstT>
  467. auto TryGetAsIfValid(InstId inst_id) const -> std::optional<InstT> {
  468. if (!inst_id.has_value()) {
  469. return std::nullopt;
  470. }
  471. return TryGetAs<InstT>(inst_id);
  472. }
  473. // Returns the `KnownInstId` form of `inst_id`. Requires a matching
  474. // instruction type.
  475. template <typename InstT>
  476. auto GetAsKnownInstId(InstId inst_id) const -> KnownInstId<InstT> {
  477. CARBON_CHECK(Is<InstT>(inst_id), "Casting inst {0} to wrong kind {1}",
  478. Get(inst_id), Internal::InstLikeTypeInfo<InstT>::DebugName());
  479. return KnownInstId<InstT>::UnsafeMake(inst_id);
  480. }
  481. template <typename InstT>
  482. struct GetAsWithIdResult {
  483. KnownInstId<InstT> inst_id;
  484. InstT inst;
  485. };
  486. // Returns the requested instruction, if it is of that type, along with the
  487. // original `InstId`, encoding the work of checking its type in a
  488. // `KnownInstId`.
  489. template <typename InstT>
  490. auto TryGetAsWithId(InstId inst_id) const
  491. -> std::optional<GetAsWithIdResult<InstT>> {
  492. auto inst = TryGetAs<InstT>(inst_id);
  493. if (!inst) {
  494. return std::nullopt;
  495. }
  496. return {
  497. {.inst_id = KnownInstId<InstT>::UnsafeMake(inst_id), .inst = *inst}};
  498. }
  499. // Attempts to convert the given instruction to the type that contains
  500. // `member`. If it can be converted, the instruction ID and instruction are
  501. // replaced by the unwrapped value of that member, and the converted wrapper
  502. // instruction and its ID are returned. Otherwise returns {nullopt, None}.
  503. template <typename InstT, typename InstIdT>
  504. requires std::derived_from<InstIdT, InstId>
  505. auto TryUnwrap(Inst& inst, InstId& inst_id, InstIdT InstT::* member) const
  506. -> std::pair<std::optional<InstT>, KnownInstId<InstT>> {
  507. if (auto wrapped_inst = inst.TryAs<InstT>()) {
  508. auto wrapped_inst_id = KnownInstId<InstT>::UnsafeMake(inst_id);
  509. inst_id = (*wrapped_inst).*member;
  510. inst = Get(inst_id);
  511. return {wrapped_inst, wrapped_inst_id};
  512. }
  513. return {std::nullopt, KnownInstId<InstT>::None};
  514. }
  515. // Returns a resolved LocId, which will point to a parse node, an import, or
  516. // be None.
  517. //
  518. // Unresolved LocIds can be backed by an InstId which may or may not have a
  519. // value after being resolved, so this operation needs to be done before using
  520. // most operations on LocId.
  521. auto GetCanonicalLocId(LocId loc_id) const -> LocId {
  522. while (loc_id.kind() == LocId::Kind::InstId) {
  523. loc_id = GetNonCanonicalLocId(loc_id.inst_id());
  524. }
  525. return loc_id;
  526. }
  527. // Gets the resolved LocId for an instruction. InstId can directly construct
  528. // an unresolved LocId. This skips that step when a resolved LocId is needed.
  529. auto GetCanonicalLocId(InstId inst_id) const -> LocId {
  530. return GetCanonicalLocId(GetNonCanonicalLocId(inst_id));
  531. }
  532. // Returns a virtual location to use for the desugaring of the code at the
  533. // specified location.
  534. auto GetLocIdForDesugaring(LocId loc_id) const -> LocId {
  535. return GetCanonicalLocId(loc_id).AsDesugared();
  536. }
  537. auto GetLocIdForDesugaring(InstId inst_id) const -> LocId {
  538. return GetCanonicalLocId(inst_id).AsDesugared();
  539. }
  540. // Returns the instruction that this instruction was imported from, or
  541. // ImportIRInstId::None if this instruction was not generated by importing
  542. // another instruction.
  543. auto GetImportSource(InstId inst_id) const -> ImportIRInstId {
  544. auto loc_id = GetNonCanonicalLocId(inst_id);
  545. return loc_id.kind() == LocId::Kind::ImportIRInstId
  546. ? loc_id.import_ir_inst_id()
  547. : ImportIRInstId::None;
  548. }
  549. // Overwrites a given instruction with a new value.
  550. auto Set(InstId inst_id, Inst inst) -> void { values_.Get(inst_id) = inst; }
  551. // Overwrites a given instruction's location with a new value.
  552. auto SetLocId(InstId inst_id, LocId loc_id) -> void {
  553. auto index = values_.GetRawIndex(inst_id);
  554. loc_ids_[index] = loc_id;
  555. }
  556. // Overwrites a given instruction and location ID with a new value.
  557. auto SetLocIdAndInst(InstId inst_id, LocIdAndInst loc_id_and_inst) -> void {
  558. Set(inst_id, loc_id_and_inst.inst);
  559. SetLocId(inst_id, loc_id_and_inst.loc_id);
  560. }
  561. // Reserves space.
  562. auto Reserve(size_t size) -> void {
  563. loc_ids_.reserve(size);
  564. values_.Reserve(size);
  565. }
  566. // Collects memory usage of members.
  567. auto CollectMemUsage(MemUsage& mem_usage, llvm::StringRef label) const
  568. -> void {
  569. mem_usage.Collect(MemUsage::ConcatLabel(label, "loc_ids_"), loc_ids_);
  570. mem_usage.Collect(MemUsage::ConcatLabel(label, "values_"), values_);
  571. }
  572. auto values() const [[clang::lifetimebound]]
  573. -> ValueStore<InstId, Inst, Tag<CheckIRId>>::Range {
  574. return values_.values();
  575. }
  576. auto size() const -> int { return values_.size(); }
  577. auto enumerate() const [[clang::lifetimebound]] -> auto {
  578. return values_.enumerate();
  579. }
  580. auto GetRawIndex(InstId id) const -> int32_t {
  581. return values_.GetRawIndex(id);
  582. }
  583. auto GetIdTag() const -> IdTagType { return values_.GetIdTag(); }
  584. private:
  585. // Given a symbolic type, get the corresponding unattached type.
  586. auto GetUnattachedType(TypeId type_id) const -> TypeId;
  587. // Gets the specified location for an instruction, without performing any
  588. // canonicalization.
  589. auto GetNonCanonicalLocId(InstId inst_id) const -> LocId {
  590. auto index = values_.GetRawIndex(inst_id);
  591. CARBON_CHECK(static_cast<size_t>(index) < loc_ids_.size(), "{0} {1}", index,
  592. loc_ids_.size());
  593. return loc_ids_[index];
  594. }
  595. File* file_;
  596. llvm::SmallVector<LocId> loc_ids_;
  597. ValueStore<InstId, Inst, Tag<CheckIRId>> values_;
  598. };
  599. // Adapts BlockValueStore for instruction blocks.
  600. class InstBlockStore
  601. : public BlockValueStore<InstBlockId, InstId, Tag<CheckIRId>> {
  602. public:
  603. using BaseType = BlockValueStore<InstBlockId, InstId, Tag<CheckIRId>>;
  604. explicit InstBlockStore(llvm::BumpPtrAllocator& allocator,
  605. CheckIRId check_ir_id = CheckIRId::None)
  606. : BaseType(allocator, check_ir_id, InstBlockId::ReservedIds.size()) {
  607. CARBON_CHECK(size() == 1, "Empty is added by `BlockValueStore`");
  608. for (auto reserved_id : InstBlockId::ReservedIds) {
  609. if (reserved_id == InstBlockId::Empty) {
  610. continue;
  611. }
  612. auto id = AddPlaceholder();
  613. CARBON_CHECK(id == reserved_id);
  614. }
  615. CARBON_CHECK(size() == InstBlockId::ReservedIds.size());
  616. }
  617. // Adds an uninitialized block of the given size. The caller is expected to
  618. // modify values.
  619. auto AddUninitialized(size_t size) -> InstBlockId {
  620. return values().Add(AllocateUninitialized(size));
  621. }
  622. // Reserves and returns a block ID. The contents of the block should be
  623. // specified by calling ReplacePlaceholder.
  624. auto AddPlaceholder() -> InstBlockId {
  625. return values().Add(llvm::MutableArrayRef<InstId>());
  626. }
  627. // Sets the contents of a placeholder block to the given content.
  628. auto ReplacePlaceholder(InstBlockId block_id, llvm::ArrayRef<InstId> content)
  629. -> void {
  630. CARBON_CHECK(block_id != InstBlockId::Empty);
  631. CARBON_CHECK(Get(block_id).empty(),
  632. "inst block content set more than once");
  633. values().Get(block_id) = AllocateCopy(content);
  634. }
  635. // Returns the contents of the specified block, or an empty array if the block
  636. // is invalid.
  637. auto GetOrEmpty(InstBlockId block_id) const -> llvm::ArrayRef<InstId> {
  638. return block_id.has_value() ? Get(block_id) : llvm::ArrayRef<InstId>();
  639. }
  640. };
  641. // See common/hashing.h.
  642. inline auto CarbonHashValue(const Inst& value, uint64_t seed) -> HashCode {
  643. Hasher hasher(seed);
  644. hasher.HashRaw(value);
  645. return static_cast<HashCode>(hasher);
  646. }
  647. } // namespace Carbon::SemIR
  648. #endif // CARBON_TOOLCHAIN_SEM_IR_INST_H_