inst.h 24 KB

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