inst.h 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400
  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/ostream.h"
  10. #include "common/struct_reflection.h"
  11. #include "toolchain/base/index_base.h"
  12. #include "toolchain/sem_ir/block_value_store.h"
  13. #include "toolchain/sem_ir/builtin_kind.h"
  14. #include "toolchain/sem_ir/inst_kind.h"
  15. #include "toolchain/sem_ir/typed_insts.h"
  16. namespace Carbon::SemIR {
  17. // InstLikeTypeInfo is an implementation detail, and not public API.
  18. namespace Internal {
  19. // Information about an instruction-like type, which is a type that an Inst can
  20. // be converted to and from. The `Enabled` parameter is used to check
  21. // requirements on the type in the specializations of this template.
  22. template <typename InstLikeType>
  23. struct InstLikeTypeInfo;
  24. // A helper base class for instruction-like types that are structs.
  25. template <typename InstLikeType>
  26. struct InstLikeTypeInfoBase {
  27. // A corresponding std::tuple<...> type.
  28. using Tuple =
  29. decltype(StructReflection::AsTuple(std::declval<InstLikeType>()));
  30. static constexpr int FirstArgField =
  31. HasKindMemberAsField<InstLikeType> + HasTypeIdMember<InstLikeType>;
  32. static constexpr int NumArgs = std::tuple_size_v<Tuple> - FirstArgField;
  33. static_assert(NumArgs <= 2,
  34. "Unsupported: typed inst has more than two data fields");
  35. template <int N>
  36. using ArgType = std::tuple_element_t<FirstArgField + N, Tuple>;
  37. template <int N>
  38. static auto Get(InstLikeType inst) -> ArgType<N> {
  39. return std::get<FirstArgField + N>(StructReflection::AsTuple(inst));
  40. }
  41. };
  42. // A particular type of instruction is instruction-like.
  43. template <typename TypedInst>
  44. requires std::same_as<const InstKind::Definition<
  45. typename decltype(TypedInst::Kind)::TypedNodeId>,
  46. decltype(TypedInst::Kind)>
  47. struct InstLikeTypeInfo<TypedInst> : InstLikeTypeInfoBase<TypedInst> {
  48. static_assert(!HasKindMemberAsField<TypedInst>,
  49. "Instruction type should not have a kind field");
  50. static auto GetKind(TypedInst /*inst*/) -> InstKind {
  51. return TypedInst::Kind;
  52. }
  53. static auto IsKind(InstKind kind) -> bool { return kind == TypedInst::Kind; }
  54. // A name that can be streamed to an llvm::raw_ostream.
  55. static auto DebugName() -> InstKind { return TypedInst::Kind; }
  56. };
  57. // An instruction category is instruction-like.
  58. template <typename InstCat>
  59. requires std::same_as<const InstKind&, decltype(InstCat::Kinds[0])>
  60. struct InstLikeTypeInfo<InstCat> : InstLikeTypeInfoBase<InstCat> {
  61. static_assert(HasKindMemberAsField<InstCat>,
  62. "Instruction category should have a kind field");
  63. static auto GetKind(InstCat cat) -> InstKind { return cat.kind; }
  64. static auto IsKind(InstKind kind) -> bool {
  65. for (InstKind k : InstCat::Kinds) {
  66. if (k == kind) {
  67. return true;
  68. }
  69. }
  70. return false;
  71. }
  72. // A name that can be streamed to an llvm::raw_ostream.
  73. static auto DebugName() -> std::string {
  74. std::string str;
  75. llvm::raw_string_ostream out(str);
  76. out << "{";
  77. llvm::ListSeparator sep;
  78. for (auto kind : InstCat::Kinds) {
  79. out << sep << kind;
  80. }
  81. out << "}";
  82. return out.str();
  83. }
  84. };
  85. // A type is InstLike if InstLikeTypeInfo is defined for it.
  86. template <typename T>
  87. concept InstLikeType = requires { sizeof(InstLikeTypeInfo<T>); };
  88. } // namespace Internal
  89. // A type-erased representation of a SemIR instruction, that may be constructed
  90. // from the specific kinds of instruction defined in `typed_insts.h`. This
  91. // provides access to common fields present on most or all kinds of
  92. // instructions:
  93. //
  94. // - `kind` for run-time logic when the input Kind is unknown.
  95. // - `type_id` for quick type checking.
  96. //
  97. // In addition, kind-specific data can be accessed by casting to the specific
  98. // kind of instruction:
  99. //
  100. // - Use `inst.kind()` or `Is<InstLikeType>` to determine what kind of
  101. // instruction it is.
  102. // - Cast to a specific type using `inst.As<InstLikeType>()`
  103. // - Using the wrong kind in `inst.As<InstLikeType>()` is a programming error,
  104. // and will CHECK-fail in debug modes (opt may too, but it's not an API
  105. // guarantee).
  106. // - Use `inst.TryAs<InstLikeType>()` to safely access type-specific instruction
  107. // data where the instruction's kind is not known.
  108. class Inst : public Printable<Inst> {
  109. public:
  110. template <typename TypedInst>
  111. requires Internal::InstLikeType<TypedInst>
  112. // NOLINTNEXTLINE(google-explicit-constructor)
  113. Inst(TypedInst typed_inst)
  114. // kind_ is always overwritten below.
  115. : kind_(InstKind::Make({})),
  116. type_id_(TypeId::Invalid),
  117. arg0_(InstId::InvalidIndex),
  118. arg1_(InstId::InvalidIndex) {
  119. if constexpr (Internal::HasKindMemberAsField<TypedInst>) {
  120. kind_ = typed_inst.kind;
  121. } else {
  122. kind_ = TypedInst::Kind;
  123. }
  124. if constexpr (Internal::HasTypeIdMember<TypedInst>) {
  125. type_id_ = typed_inst.type_id;
  126. }
  127. using Info = Internal::InstLikeTypeInfo<TypedInst>;
  128. if constexpr (Info::NumArgs > 0) {
  129. arg0_ = ToRaw(Info::template Get<0>(typed_inst));
  130. }
  131. if constexpr (Info::NumArgs > 1) {
  132. arg1_ = ToRaw(Info::template Get<1>(typed_inst));
  133. }
  134. }
  135. // Returns whether this instruction has the specified type.
  136. template <typename TypedInst>
  137. requires Internal::InstLikeType<TypedInst>
  138. auto Is() const -> bool {
  139. return Internal::InstLikeTypeInfo<TypedInst>::IsKind(kind());
  140. }
  141. // Casts this instruction to the given typed instruction, which must match the
  142. // instruction's kind, and returns the typed instruction.
  143. template <typename TypedInst>
  144. requires Internal::InstLikeType<TypedInst>
  145. auto As() const -> TypedInst {
  146. using Info = Internal::InstLikeTypeInfo<TypedInst>;
  147. CARBON_CHECK(Is<TypedInst>()) << "Casting inst of kind " << kind()
  148. << " to wrong kind " << Info::DebugName();
  149. auto build_with_type_id_onwards = [&](auto... type_id_onwards) {
  150. if constexpr (Internal::HasKindMemberAsField<TypedInst>) {
  151. return TypedInst{kind(), type_id_onwards...};
  152. } else {
  153. return TypedInst{type_id_onwards...};
  154. }
  155. };
  156. auto build_with_args = [&](auto... args) {
  157. if constexpr (Internal::HasTypeIdMember<TypedInst>) {
  158. return build_with_type_id_onwards(type_id(), args...);
  159. } else {
  160. return build_with_type_id_onwards(args...);
  161. }
  162. };
  163. if constexpr (Info::NumArgs == 0) {
  164. return build_with_args();
  165. } else if constexpr (Info::NumArgs == 1) {
  166. return build_with_args(
  167. FromRaw<typename Info::template ArgType<0>>(arg0_));
  168. } else if constexpr (Info::NumArgs == 2) {
  169. return build_with_args(
  170. FromRaw<typename Info::template ArgType<0>>(arg0_),
  171. FromRaw<typename Info::template ArgType<1>>(arg1_));
  172. }
  173. }
  174. // If this instruction is the given kind, returns a typed instruction,
  175. // otherwise returns nullopt.
  176. template <typename TypedInst>
  177. requires Internal::InstLikeType<TypedInst>
  178. auto TryAs() const -> std::optional<TypedInst> {
  179. if (Is<TypedInst>()) {
  180. return As<TypedInst>();
  181. } else {
  182. return std::nullopt;
  183. }
  184. }
  185. auto kind() const -> InstKind { return kind_; }
  186. // Gets the type of the value produced by evaluating this instruction.
  187. auto type_id() const -> TypeId { return type_id_; }
  188. // Gets the first argument of the instruction. InvalidIndex if there is no
  189. // such argument.
  190. auto arg0() const -> int32_t { return arg0_; }
  191. // Gets the second argument of the instruction. InvalidIndex if there is no
  192. // such argument.
  193. auto arg1() const -> int32_t { return arg1_; }
  194. auto Print(llvm::raw_ostream& out) const -> void;
  195. private:
  196. friend class InstTestHelper;
  197. // Raw constructor, used for testing.
  198. explicit Inst(InstKind kind, TypeId type_id, int32_t arg0, int32_t arg1)
  199. : kind_(kind), type_id_(type_id), arg0_(arg0), arg1_(arg1) {}
  200. // Convert a field to its raw representation, used as `arg0_` / `arg1_`.
  201. static constexpr auto ToRaw(IdBase base) -> int32_t { return base.index; }
  202. static constexpr auto ToRaw(BuiltinKind kind) -> int32_t {
  203. return kind.AsInt();
  204. }
  205. // Convert a field from its raw representation.
  206. template <typename T>
  207. static constexpr auto FromRaw(int32_t raw) -> T {
  208. return T(raw);
  209. }
  210. template <>
  211. constexpr auto FromRaw<BuiltinKind>(int32_t raw) -> BuiltinKind {
  212. return BuiltinKind::FromInt(raw);
  213. }
  214. InstKind kind_;
  215. TypeId type_id_;
  216. // Use `As` to access arg0 and arg1.
  217. int32_t arg0_;
  218. int32_t arg1_;
  219. };
  220. // TODO: This is currently 16 bytes because we sometimes have 2 arguments for a
  221. // pair of Insts. However, InstKind is 1 byte; if args were 3.5 bytes, we could
  222. // potentially shrink Inst by 4 bytes. This may be worth investigating further.
  223. // Note though that 16 bytes is an ideal size for registers, we may want more
  224. // flags, and 12 bytes would be a more marginal improvement.
  225. static_assert(sizeof(Inst) == 16, "Unexpected Inst size");
  226. // Instruction-like types can be printed by converting them to instructions.
  227. template <typename TypedInst>
  228. requires Internal::InstLikeType<TypedInst>
  229. inline auto operator<<(llvm::raw_ostream& out, TypedInst inst)
  230. -> llvm::raw_ostream& {
  231. Inst(inst).Print(out);
  232. return out;
  233. }
  234. // Associates a NodeId and Inst in order to provide type-checking that the
  235. // TypedNodeId corresponds to the InstT.
  236. struct ParseNodeAndInst {
  237. // In cases where the NodeId is untyped or the InstT is unknown, the check
  238. // can't be done at compile time.
  239. // TODO: Consider runtime validation that InstT::Kind::TypedNodeId
  240. // corresponds.
  241. static auto Untyped(Parse::NodeId parse_node, Inst inst) -> ParseNodeAndInst {
  242. return ParseNodeAndInst(parse_node, inst, /*is_untyped=*/true);
  243. }
  244. // For the common case, support construction as:
  245. // context.AddInst({parse_node, SemIR::MyInst{...}});
  246. template <typename InstT>
  247. requires(Internal::HasParseNode<InstT>)
  248. // NOLINTNEXTLINE(google-explicit-constructor)
  249. ParseNodeAndInst(decltype(InstT::Kind)::TypedNodeId parse_node, InstT inst)
  250. : parse_node(parse_node), inst(inst) {}
  251. // For cases with no parse node, support construction as:
  252. // context.AddInst({SemIR::MyInst{...}});
  253. template <typename InstT>
  254. requires(!Internal::HasParseNode<InstT>)
  255. // NOLINTNEXTLINE(google-explicit-constructor)
  256. ParseNodeAndInst(InstT inst)
  257. : parse_node(Parse::NodeId::Invalid), inst(inst) {}
  258. Parse::NodeId parse_node;
  259. Inst inst;
  260. private:
  261. explicit ParseNodeAndInst(Parse::NodeId parse_node, Inst inst,
  262. bool /*is_untyped*/)
  263. : parse_node(parse_node), inst(inst) {}
  264. };
  265. // Provides a ValueStore wrapper for an API specific to instructions.
  266. class InstStore {
  267. public:
  268. // Adds an instruction to the instruction list, returning an ID to reference
  269. // the instruction. Note that this doesn't add the instruction to any
  270. // instruction block. Check::Context::AddInst or InstBlockStack::AddInst
  271. // should usually be used instead, to add the instruction to the current
  272. // block.
  273. auto AddInNoBlock(ParseNodeAndInst parse_node_and_inst) -> InstId {
  274. parse_nodes_.push_back(parse_node_and_inst.parse_node);
  275. return values_.Add(parse_node_and_inst.inst);
  276. }
  277. // Returns the requested instruction.
  278. auto Get(InstId inst_id) const -> Inst { return values_.Get(inst_id); }
  279. // Returns the requested instruction and its parse node.
  280. auto GetWithParseNode(InstId inst_id) const -> ParseNodeAndInst {
  281. return ParseNodeAndInst::Untyped(GetParseNode(inst_id), Get(inst_id));
  282. }
  283. // Returns whether the requested instruction is the specified type.
  284. template <typename InstT>
  285. auto Is(InstId inst_id) const -> bool {
  286. return Get(inst_id).Is<InstT>();
  287. }
  288. // Returns the requested instruction, which is known to have the specified
  289. // type.
  290. template <typename InstT>
  291. auto GetAs(InstId inst_id) const -> InstT {
  292. return Get(inst_id).As<InstT>();
  293. }
  294. // Returns the requested instruction as the specified type, if it is of that
  295. // type.
  296. template <typename InstT>
  297. auto TryGetAs(InstId inst_id) const -> std::optional<InstT> {
  298. return Get(inst_id).TryAs<InstT>();
  299. }
  300. auto GetParseNode(InstId inst_id) const -> Parse::NodeId {
  301. return parse_nodes_[inst_id.index];
  302. }
  303. // Overwrites a given instruction and parse node with a new value.
  304. auto Set(InstId inst_id, ParseNodeAndInst parse_node_and_inst) -> void {
  305. values_.Get(inst_id) = parse_node_and_inst.inst;
  306. parse_nodes_[inst_id.index] = parse_node_and_inst.parse_node;
  307. }
  308. auto SetParseNode(InstId inst_id, Parse::NodeId parse_node) -> void {
  309. parse_nodes_[inst_id.index] = parse_node;
  310. }
  311. // Reserves space.
  312. auto Reserve(size_t size) -> void {
  313. parse_nodes_.reserve(size);
  314. values_.Reserve(size);
  315. }
  316. auto array_ref() const -> llvm::ArrayRef<Inst> { return values_.array_ref(); }
  317. auto size() const -> int { return values_.size(); }
  318. private:
  319. llvm::SmallVector<Parse::NodeId> parse_nodes_;
  320. ValueStore<InstId> values_;
  321. };
  322. // Adapts BlockValueStore for instruction blocks.
  323. class InstBlockStore : public BlockValueStore<InstBlockId> {
  324. public:
  325. using BaseType = BlockValueStore<InstBlockId>;
  326. using BaseType::AddDefaultValue;
  327. using BaseType::AddUninitialized;
  328. explicit InstBlockStore(llvm::BumpPtrAllocator& allocator)
  329. : BaseType(allocator) {
  330. auto empty_id = AddDefaultValue();
  331. CARBON_CHECK(empty_id == InstBlockId::Empty);
  332. auto exports_id = AddDefaultValue();
  333. CARBON_CHECK(exports_id == InstBlockId::Exports);
  334. auto global_init_id = AddDefaultValue();
  335. CARBON_CHECK(global_init_id == InstBlockId::GlobalInit);
  336. }
  337. auto Set(InstBlockId block_id, llvm::ArrayRef<InstId> content) -> void {
  338. CARBON_CHECK(block_id != InstBlockId::Unreachable);
  339. BlockValueStore<InstBlockId>::Set(block_id, content);
  340. }
  341. };
  342. } // namespace Carbon::SemIR
  343. #endif // CARBON_TOOLCHAIN_SEM_IR_INST_H_