inst.h 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484
  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/struct_reflection.h"
  12. #include "toolchain/base/index_base.h"
  13. #include "toolchain/sem_ir/block_value_store.h"
  14. #include "toolchain/sem_ir/builtin_inst_kind.h"
  15. #include "toolchain/sem_ir/id_kind.h"
  16. #include "toolchain/sem_ir/inst_kind.h"
  17. #include "toolchain/sem_ir/typed_insts.h"
  18. namespace Carbon::SemIR {
  19. // InstLikeTypeInfo is an implementation detail, and not public API.
  20. namespace Internal {
  21. // Information about an instruction-like type, which is a type that an Inst can
  22. // be converted to and from. The `Enabled` parameter is used to check
  23. // requirements on the type in the specializations of this template.
  24. template <typename InstLikeType>
  25. struct InstLikeTypeInfo;
  26. // A helper base class for instruction-like types that are structs.
  27. template <typename InstLikeType>
  28. struct InstLikeTypeInfoBase {
  29. // A corresponding std::tuple<...> type.
  30. using Tuple =
  31. decltype(StructReflection::AsTuple(std::declval<InstLikeType>()));
  32. static constexpr int FirstArgField =
  33. HasKindMemberAsField<InstLikeType> + HasTypeIdMember<InstLikeType>;
  34. static constexpr int NumArgs = std::tuple_size_v<Tuple> - FirstArgField;
  35. static_assert(NumArgs <= 2,
  36. "Unsupported: typed inst has more than two data fields");
  37. template <int N>
  38. using ArgType = std::tuple_element_t<FirstArgField + N, Tuple>;
  39. template <int N>
  40. static auto Get(InstLikeType inst) -> ArgType<N> {
  41. return std::get<FirstArgField + N>(StructReflection::AsTuple(inst));
  42. }
  43. };
  44. // A particular type of instruction is instruction-like.
  45. template <typename TypedInst>
  46. requires std::same_as<const InstKind::Definition<
  47. typename decltype(TypedInst::Kind)::TypedNodeId>,
  48. decltype(TypedInst::Kind)>
  49. struct InstLikeTypeInfo<TypedInst> : InstLikeTypeInfoBase<TypedInst> {
  50. static_assert(!HasKindMemberAsField<TypedInst>,
  51. "Instruction type should not have a kind field");
  52. static auto GetKind(TypedInst /*inst*/) -> InstKind {
  53. return TypedInst::Kind;
  54. }
  55. static auto IsKind(InstKind kind) -> bool { return kind == TypedInst::Kind; }
  56. // A name that can be streamed to an llvm::raw_ostream.
  57. static auto DebugName() -> InstKind { return TypedInst::Kind; }
  58. };
  59. // An instruction category is instruction-like.
  60. template <typename InstCat>
  61. requires std::same_as<const InstKind&, decltype(InstCat::Kinds[0])>
  62. struct InstLikeTypeInfo<InstCat> : InstLikeTypeInfoBase<InstCat> {
  63. static_assert(HasKindMemberAsField<InstCat>,
  64. "Instruction category should have a kind field");
  65. static auto GetKind(InstCat cat) -> InstKind { return cat.kind; }
  66. static auto IsKind(InstKind kind) -> bool {
  67. for (InstKind k : InstCat::Kinds) {
  68. if (k == kind) {
  69. return true;
  70. }
  71. }
  72. return false;
  73. }
  74. // A name that can be streamed to an llvm::raw_ostream.
  75. static auto DebugName() -> std::string {
  76. std::string str;
  77. llvm::raw_string_ostream out(str);
  78. out << "{";
  79. llvm::ListSeparator sep;
  80. for (auto kind : InstCat::Kinds) {
  81. out << sep << kind;
  82. }
  83. out << "}";
  84. return out.str();
  85. }
  86. };
  87. // A type is InstLike if InstLikeTypeInfo is defined for it.
  88. template <typename T>
  89. concept InstLikeType = requires { sizeof(InstLikeTypeInfo<T>); };
  90. } // namespace Internal
  91. // A type-erased representation of a SemIR instruction, that may be constructed
  92. // from the specific kinds of instruction defined in `typed_insts.h`. This
  93. // provides access to common fields present on most or all kinds of
  94. // instructions:
  95. //
  96. // - `kind` for run-time logic when the input Kind is unknown.
  97. // - `type_id` for quick type checking.
  98. //
  99. // In addition, kind-specific data can be accessed by casting to the specific
  100. // kind of instruction:
  101. //
  102. // - Use `inst.kind()` or `Is<InstLikeType>` to determine what kind of
  103. // instruction it is.
  104. // - Cast to a specific type using `inst.As<InstLikeType>()`
  105. // - Using the wrong kind in `inst.As<InstLikeType>()` is a programming error,
  106. // and will CHECK-fail in debug modes (opt may too, but it's not an API
  107. // guarantee).
  108. // - Use `inst.TryAs<InstLikeType>()` to safely access type-specific instruction
  109. // data where the instruction's kind is not known.
  110. class Inst : public Printable<Inst> {
  111. public:
  112. template <typename TypedInst>
  113. requires Internal::InstLikeType<TypedInst>
  114. // NOLINTNEXTLINE(google-explicit-constructor)
  115. Inst(TypedInst typed_inst)
  116. // kind_ is always overwritten below.
  117. : kind_(),
  118. type_id_(TypeId::Invalid),
  119. arg0_(InstId::InvalidIndex),
  120. arg1_(InstId::InvalidIndex) {
  121. if constexpr (Internal::HasKindMemberAsField<TypedInst>) {
  122. kind_ = typed_inst.kind.AsInt();
  123. } else {
  124. kind_ = TypedInst::Kind.AsInt();
  125. }
  126. if constexpr (Internal::HasTypeIdMember<TypedInst>) {
  127. type_id_ = typed_inst.type_id;
  128. }
  129. using Info = Internal::InstLikeTypeInfo<TypedInst>;
  130. if constexpr (Info::NumArgs > 0) {
  131. arg0_ = ToRaw(Info::template Get<0>(typed_inst));
  132. }
  133. if constexpr (Info::NumArgs > 1) {
  134. arg1_ = ToRaw(Info::template Get<1>(typed_inst));
  135. }
  136. }
  137. // Returns whether this instruction has the specified type.
  138. template <typename TypedInst>
  139. requires Internal::InstLikeType<TypedInst>
  140. auto Is() const -> bool {
  141. return Internal::InstLikeTypeInfo<TypedInst>::IsKind(kind());
  142. }
  143. // Casts this instruction to the given typed instruction, which must match the
  144. // instruction's kind, and returns the typed instruction.
  145. template <typename TypedInst>
  146. requires Internal::InstLikeType<TypedInst>
  147. auto As() const -> TypedInst {
  148. using Info = Internal::InstLikeTypeInfo<TypedInst>;
  149. CARBON_CHECK(Is<TypedInst>(), "Casting inst of kind {0} to wrong kind {1}",
  150. kind(), Info::DebugName());
  151. auto build_with_type_id_onwards = [&](auto... type_id_onwards) {
  152. if constexpr (Internal::HasKindMemberAsField<TypedInst>) {
  153. return TypedInst{kind(), type_id_onwards...};
  154. } else {
  155. return TypedInst{type_id_onwards...};
  156. }
  157. };
  158. auto build_with_args = [&](auto... args) {
  159. if constexpr (Internal::HasTypeIdMember<TypedInst>) {
  160. return build_with_type_id_onwards(type_id(), args...);
  161. } else {
  162. return build_with_type_id_onwards(args...);
  163. }
  164. };
  165. if constexpr (Info::NumArgs == 0) {
  166. return build_with_args();
  167. } else if constexpr (Info::NumArgs == 1) {
  168. return build_with_args(
  169. FromRaw<typename Info::template ArgType<0>>(arg0_));
  170. } else if constexpr (Info::NumArgs == 2) {
  171. return build_with_args(
  172. FromRaw<typename Info::template ArgType<0>>(arg0_),
  173. FromRaw<typename Info::template ArgType<1>>(arg1_));
  174. }
  175. }
  176. // If this instruction is the given kind, returns a typed instruction,
  177. // otherwise returns nullopt.
  178. template <typename TypedInst>
  179. requires Internal::InstLikeType<TypedInst>
  180. auto TryAs() const -> std::optional<TypedInst> {
  181. if (Is<TypedInst>()) {
  182. return As<TypedInst>();
  183. } else {
  184. return std::nullopt;
  185. }
  186. }
  187. auto kind() const -> InstKind {
  188. return InstKind::Make(static_cast<InstKind::RawEnumType>(kind_));
  189. }
  190. // Gets the type of the value produced by evaluating this instruction.
  191. auto type_id() const -> TypeId { return type_id_; }
  192. // Gets the kinds of IDs used for arg0 and arg1 of the specified kind of
  193. // instruction.
  194. //
  195. // TODO: This would ideally live on InstKind, but can't be there for layering
  196. // reasons.
  197. static auto ArgKinds(InstKind kind) -> std::pair<IdKind, IdKind> {
  198. return ArgKindTable[kind.AsInt()];
  199. }
  200. // Gets the kinds of IDs used for arg0 and arg1 of this instruction.
  201. auto ArgKinds() const -> std::pair<IdKind, IdKind> {
  202. return ArgKinds(kind());
  203. }
  204. // Gets the first argument of the instruction. InvalidIndex if there is no
  205. // such argument.
  206. auto arg0() const -> int32_t { return arg0_; }
  207. // Gets the second argument of the instruction. InvalidIndex if there is no
  208. // such argument.
  209. auto arg1() const -> int32_t { return arg1_; }
  210. // Sets the type of this instruction.
  211. auto SetType(TypeId type_id) -> void { type_id_ = type_id; }
  212. // Sets the arguments of this instruction.
  213. auto SetArgs(int32_t arg0, int32_t arg1) {
  214. arg0_ = arg0;
  215. arg1_ = arg1;
  216. }
  217. auto Print(llvm::raw_ostream& out) const -> void;
  218. friend auto operator==(Inst lhs, Inst rhs) -> bool {
  219. return std::memcmp(&lhs, &rhs, sizeof(Inst)) == 0;
  220. }
  221. private:
  222. friend class InstTestHelper;
  223. // Table mapping instruction kinds to their argument kinds.
  224. static const std::pair<IdKind, IdKind> ArgKindTable[];
  225. // Raw constructor, used for testing.
  226. explicit Inst(InstKind kind, TypeId type_id, int32_t arg0, int32_t arg1)
  227. : Inst(kind.AsInt(), type_id, arg0, arg1) {}
  228. explicit Inst(int32_t kind, TypeId type_id, int32_t arg0, int32_t arg1)
  229. : kind_(kind), type_id_(type_id), arg0_(arg0), arg1_(arg1) {}
  230. // Convert a field to its raw representation, used as `arg0_` / `arg1_`.
  231. static constexpr auto ToRaw(IdBase base) -> int32_t { return base.index; }
  232. static constexpr auto ToRaw(BuiltinInstKind kind) -> int32_t {
  233. return kind.AsInt();
  234. }
  235. // Convert a field from its raw representation.
  236. template <typename T>
  237. static constexpr auto FromRaw(int32_t raw) -> T {
  238. return T(raw);
  239. }
  240. template <>
  241. constexpr auto FromRaw<BuiltinInstKind>(int32_t raw) -> BuiltinInstKind {
  242. return BuiltinInstKind::FromInt(raw);
  243. }
  244. int32_t kind_;
  245. TypeId type_id_;
  246. // Use `As` to access arg0 and arg1.
  247. int32_t arg0_;
  248. int32_t arg1_;
  249. };
  250. // TODO: This is currently 16 bytes because we sometimes have 2 arguments for a
  251. // pair of Insts. However, InstKind is 1 byte; if args were 3.5 bytes, we could
  252. // potentially shrink Inst by 4 bytes. This may be worth investigating further.
  253. // Note though that 16 bytes is an ideal size for registers, we may want more
  254. // flags, and 12 bytes would be a more marginal improvement.
  255. static_assert(sizeof(Inst) == 16, "Unexpected Inst size");
  256. // Instruction-like types can be printed by converting them to instructions.
  257. template <typename TypedInst>
  258. requires Internal::InstLikeType<TypedInst>
  259. inline auto operator<<(llvm::raw_ostream& out, TypedInst inst)
  260. -> llvm::raw_ostream& {
  261. Inst(inst).Print(out);
  262. return out;
  263. }
  264. // Associates a LocId and Inst in order to provide type-checking that the
  265. // TypedNodeId corresponds to the InstT.
  266. struct LocIdAndInst {
  267. // Constructs a LocIdAndInst with no associated location. This should be used
  268. // very sparingly: only when it doesn't make sense to store a location even
  269. // when the instruction kind usually has one, such as for instructions in the
  270. // constants block.
  271. template <typename InstT>
  272. static auto NoLoc(InstT inst) -> LocIdAndInst {
  273. return LocIdAndInst(LocId::Invalid, inst, /*is_unchecked=*/true);
  274. }
  275. // Unsafely form a pair of a location and an instruction. Used in the cases
  276. // where we can't statically enforce the type matches.
  277. static auto UncheckedLoc(LocId loc_id, Inst inst) -> LocIdAndInst {
  278. return LocIdAndInst(loc_id, inst, /*is_unchecked=*/true);
  279. }
  280. // Construction for the common case with a typed node.
  281. template <typename InstT>
  282. requires(Internal::HasNodeId<InstT>)
  283. LocIdAndInst(decltype(InstT::Kind)::TypedNodeId node_id, InstT inst)
  284. : loc_id(node_id), inst(inst) {}
  285. // Construction for the case where the instruction can have any associated
  286. // node.
  287. template <typename InstT>
  288. requires(Internal::HasUntypedNodeId<InstT>)
  289. LocIdAndInst(SemIR::LocId loc_id, InstT inst) : loc_id(loc_id), inst(inst) {}
  290. LocId loc_id;
  291. Inst inst;
  292. private:
  293. // Note `is_unchecked` serves to disambiguate from public constructors.
  294. explicit LocIdAndInst(LocId loc_id, Inst inst, bool /*is_unchecked*/)
  295. : loc_id(loc_id), inst(inst) {}
  296. };
  297. // Provides a ValueStore wrapper for an API specific to instructions.
  298. class InstStore {
  299. public:
  300. // Adds an instruction to the instruction list, returning an ID to reference
  301. // the instruction. Note that this doesn't add the instruction to any
  302. // instruction block. Check::Context::AddInst or InstBlockStack::AddInst
  303. // should usually be used instead, to add the instruction to the current
  304. // block.
  305. auto AddInNoBlock(LocIdAndInst loc_id_and_inst) -> InstId {
  306. loc_ids_.push_back(loc_id_and_inst.loc_id);
  307. return values_.Add(loc_id_and_inst.inst);
  308. }
  309. // Returns the requested instruction.
  310. auto Get(InstId inst_id) const -> Inst { return values_.Get(inst_id); }
  311. // Returns the requested instruction and its location ID.
  312. auto GetWithLocId(InstId inst_id) const -> LocIdAndInst {
  313. return LocIdAndInst::UncheckedLoc(GetLocId(inst_id), Get(inst_id));
  314. }
  315. // Returns whether the requested instruction is the specified type.
  316. template <typename InstT>
  317. auto Is(InstId inst_id) const -> bool {
  318. return Get(inst_id).Is<InstT>();
  319. }
  320. // Returns the requested instruction, which is known to have the specified
  321. // type.
  322. template <typename InstT>
  323. auto GetAs(InstId inst_id) const -> InstT {
  324. return Get(inst_id).As<InstT>();
  325. }
  326. // Returns the requested instruction as the specified type, if it is of that
  327. // type.
  328. template <typename InstT>
  329. auto TryGetAs(InstId inst_id) const -> std::optional<InstT> {
  330. return Get(inst_id).TryAs<InstT>();
  331. }
  332. // Returns the requested instruction as the specified type, if it is valid and
  333. // of that type. Otherwise returns nullopt.
  334. template <typename InstT>
  335. auto TryGetAsIfValid(InstId inst_id) const -> std::optional<InstT> {
  336. if (!inst_id.is_valid()) {
  337. return std::nullopt;
  338. }
  339. return TryGetAs<InstT>(inst_id);
  340. }
  341. auto GetLocId(InstId inst_id) const -> LocId {
  342. CARBON_CHECK(inst_id.index >= 0, "{0}", inst_id.index);
  343. CARBON_CHECK(inst_id.index < (int)loc_ids_.size(), "{0} {1}", inst_id.index,
  344. loc_ids_.size());
  345. return loc_ids_[inst_id.index];
  346. }
  347. // Overwrites a given instruction with a new value.
  348. auto Set(InstId inst_id, Inst inst) -> void { values_.Get(inst_id) = inst; }
  349. // Overwrites a given instruction's location with a new value.
  350. auto SetLocId(InstId inst_id, LocId loc_id) -> void {
  351. loc_ids_[inst_id.index] = loc_id;
  352. }
  353. // Overwrites a given instruction and location ID with a new value.
  354. auto SetLocIdAndInst(InstId inst_id, LocIdAndInst loc_id_and_inst) -> void {
  355. Set(inst_id, loc_id_and_inst.inst);
  356. SetLocId(inst_id, loc_id_and_inst.loc_id);
  357. }
  358. // Reserves space.
  359. auto Reserve(size_t size) -> void {
  360. loc_ids_.reserve(size);
  361. values_.Reserve(size);
  362. }
  363. // Collects memory usage of members.
  364. auto CollectMemUsage(MemUsage& mem_usage, llvm::StringRef label) const
  365. -> void {
  366. mem_usage.Add(MemUsage::ConcatLabel(label, "loc_ids_"), loc_ids_);
  367. mem_usage.Collect(MemUsage::ConcatLabel(label, "values_"), values_);
  368. }
  369. auto array_ref() const -> llvm::ArrayRef<Inst> { return values_.array_ref(); }
  370. auto size() const -> int { return values_.size(); }
  371. private:
  372. llvm::SmallVector<LocId> loc_ids_;
  373. ValueStore<InstId> values_;
  374. };
  375. // Adapts BlockValueStore for instruction blocks.
  376. class InstBlockStore : public BlockValueStore<InstBlockId> {
  377. public:
  378. using BaseType = BlockValueStore<InstBlockId>;
  379. using BaseType::AddDefaultValue;
  380. using BaseType::AddUninitialized;
  381. explicit InstBlockStore(llvm::BumpPtrAllocator& allocator)
  382. : BaseType(allocator) {
  383. auto empty_id = AddCanonical({});
  384. CARBON_CHECK(empty_id == InstBlockId::Empty);
  385. auto exports_id = AddDefaultValue();
  386. CARBON_CHECK(exports_id == InstBlockId::Exports);
  387. auto import_refs_id = AddDefaultValue();
  388. CARBON_CHECK(import_refs_id == InstBlockId::ImportRefs);
  389. auto global_init_id = AddDefaultValue();
  390. CARBON_CHECK(global_init_id == InstBlockId::GlobalInit);
  391. }
  392. // Adds a block with the given content, returning an ID to reference it.
  393. // Returns Empty rather than creating a unique ID if the block is empty.
  394. auto AddOrEmpty(llvm::ArrayRef<ElementType> content) -> InstBlockId {
  395. return content.empty() ? InstBlockId::Empty : Add(content);
  396. }
  397. auto Set(InstBlockId block_id, llvm::ArrayRef<InstId> content) -> void {
  398. CARBON_CHECK(block_id != InstBlockId::Unreachable);
  399. BlockValueStore<InstBlockId>::SetContent(block_id, content);
  400. }
  401. // Returns the contents of the specified block, or an empty array if the block
  402. // is invalid.
  403. auto GetOrEmpty(InstBlockId block_id) const -> llvm::ArrayRef<InstId> {
  404. return block_id.is_valid() ? Get(block_id) : llvm::ArrayRef<InstId>();
  405. }
  406. };
  407. // See common/hashing.h.
  408. inline auto CarbonHashValue(const Inst& value, uint64_t seed) -> HashCode {
  409. Hasher hasher(seed);
  410. hasher.HashRaw(value);
  411. return static_cast<HashCode>(hasher);
  412. }
  413. } // namespace Carbon::SemIR
  414. #endif // CARBON_TOOLCHAIN_SEM_IR_INST_H_