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_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. CARBON_CHECK(kind_ >= 0)
  127. << "Negative kind values are reserved for DenseMapInfo.";
  128. if constexpr (Internal::HasTypeIdMember<TypedInst>) {
  129. type_id_ = typed_inst.type_id;
  130. }
  131. using Info = Internal::InstLikeTypeInfo<TypedInst>;
  132. if constexpr (Info::NumArgs > 0) {
  133. arg0_ = ToRaw(Info::template Get<0>(typed_inst));
  134. }
  135. if constexpr (Info::NumArgs > 1) {
  136. arg1_ = ToRaw(Info::template Get<1>(typed_inst));
  137. }
  138. }
  139. // Returns whether this instruction has the specified type.
  140. template <typename TypedInst>
  141. requires Internal::InstLikeType<TypedInst>
  142. auto Is() const -> bool {
  143. return Internal::InstLikeTypeInfo<TypedInst>::IsKind(kind());
  144. }
  145. // Casts this instruction to the given typed instruction, which must match the
  146. // instruction's kind, and returns the typed instruction.
  147. template <typename TypedInst>
  148. requires Internal::InstLikeType<TypedInst>
  149. auto As() const -> TypedInst {
  150. using Info = Internal::InstLikeTypeInfo<TypedInst>;
  151. CARBON_CHECK(Is<TypedInst>()) << "Casting inst of kind " << kind()
  152. << " to wrong kind " << Info::DebugName();
  153. auto build_with_type_id_onwards = [&](auto... type_id_onwards) {
  154. if constexpr (Internal::HasKindMemberAsField<TypedInst>) {
  155. return TypedInst{kind(), type_id_onwards...};
  156. } else {
  157. return TypedInst{type_id_onwards...};
  158. }
  159. };
  160. auto build_with_args = [&](auto... args) {
  161. if constexpr (Internal::HasTypeIdMember<TypedInst>) {
  162. return build_with_type_id_onwards(type_id(), args...);
  163. } else {
  164. return build_with_type_id_onwards(args...);
  165. }
  166. };
  167. if constexpr (Info::NumArgs == 0) {
  168. return build_with_args();
  169. } else if constexpr (Info::NumArgs == 1) {
  170. return build_with_args(
  171. FromRaw<typename Info::template ArgType<0>>(arg0_));
  172. } else if constexpr (Info::NumArgs == 2) {
  173. return build_with_args(
  174. FromRaw<typename Info::template ArgType<0>>(arg0_),
  175. FromRaw<typename Info::template ArgType<1>>(arg1_));
  176. }
  177. }
  178. // If this instruction is the given kind, returns a typed instruction,
  179. // otherwise returns nullopt.
  180. template <typename TypedInst>
  181. requires Internal::InstLikeType<TypedInst>
  182. auto TryAs() const -> std::optional<TypedInst> {
  183. if (Is<TypedInst>()) {
  184. return As<TypedInst>();
  185. } else {
  186. return std::nullopt;
  187. }
  188. }
  189. auto kind() const -> InstKind {
  190. return InstKind::Make(static_cast<InstKind::RawEnumType>(kind_));
  191. }
  192. // Gets the type of the value produced by evaluating this instruction.
  193. auto type_id() const -> TypeId { return type_id_; }
  194. // Gets the kinds of IDs used for arg0 and arg1 of the specified kind of
  195. // instruction.
  196. //
  197. // TODO: This would ideally live on InstKind, but can't be there for layering
  198. // reasons.
  199. static auto ArgKinds(InstKind kind) -> std::pair<IdKind, IdKind> {
  200. return ArgKindTable[kind.AsInt()];
  201. }
  202. // Gets the kinds of IDs used for arg0 and arg1 of this instruction.
  203. auto ArgKinds() const -> std::pair<IdKind, IdKind> {
  204. return ArgKinds(kind());
  205. }
  206. // Gets the first argument of the instruction. InvalidIndex if there is no
  207. // such argument.
  208. auto arg0() const -> int32_t { return arg0_; }
  209. // Gets the second argument of the instruction. InvalidIndex if there is no
  210. // such argument.
  211. auto arg1() const -> int32_t { return arg1_; }
  212. // Sets the type of this instruction.
  213. auto SetType(TypeId type_id) -> void { type_id_ = type_id; }
  214. // Sets the arguments of this instruction.
  215. auto SetArgs(int32_t arg0, int32_t arg1) {
  216. arg0_ = arg0;
  217. arg1_ = arg1;
  218. }
  219. auto Print(llvm::raw_ostream& out) const -> void;
  220. private:
  221. friend class InstTestHelper;
  222. friend struct llvm::DenseMapInfo<Carbon::SemIR::Inst>;
  223. // Table mapping instruction kinds to their argument kinds.
  224. static const std::pair<IdKind, IdKind> ArgKindTable[];
  225. // Raw constructor, used for testing and by DenseMapInfo.
  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(BuiltinKind 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<BuiltinKind>(int32_t raw) -> BuiltinKind {
  242. return BuiltinKind::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. template <typename InstT>
  268. static auto NoLoc(InstT inst) -> LocIdAndInst {
  269. return LocIdAndInst(LocId::Invalid, inst, /*is_untyped=*/true);
  270. }
  271. // Construction for the common case with a typed node.
  272. template <typename InstT>
  273. requires(Internal::HasNodeId<InstT>)
  274. LocIdAndInst(decltype(InstT::Kind)::TypedNodeId node_id, InstT inst)
  275. : loc_id(node_id), inst(inst) {}
  276. // If TypedNodeId is Parse::NodeId, allow construction with a LocId.
  277. // TODO: This is somewhat historical due to fetching the NodeId from insts()
  278. // for things like Temporary; should we require Untyped in these cases?
  279. template <typename InstT>
  280. requires(std::same_as<typename decltype(InstT::Kind)::TypedNodeId,
  281. Parse::NodeId>)
  282. LocIdAndInst(LocId loc_id, InstT inst) : loc_id(loc_id), inst(inst) {}
  283. // Imports can pass an ImportIRInstId instead of another location.
  284. template <typename InstT>
  285. LocIdAndInst(ImportIRInstId import_ir_inst_id, InstT inst)
  286. : loc_id(import_ir_inst_id), inst(inst) {}
  287. LocId loc_id;
  288. Inst inst;
  289. private:
  290. // Expose the internal constructor for GetWithLocId.
  291. friend class InstStore;
  292. // Note `is_untyped` serves to disambiguate from public constructors.
  293. explicit LocIdAndInst(LocId loc_id, Inst inst, bool /*is_untyped*/)
  294. : loc_id(loc_id), inst(inst) {}
  295. };
  296. // Provides a ValueStore wrapper for an API specific to instructions.
  297. class InstStore {
  298. public:
  299. // Adds an instruction to the instruction list, returning an ID to reference
  300. // the instruction. Note that this doesn't add the instruction to any
  301. // instruction block. Check::Context::AddInst or InstBlockStack::AddInst
  302. // should usually be used instead, to add the instruction to the current
  303. // block.
  304. auto AddInNoBlock(LocIdAndInst loc_id_and_inst) -> InstId {
  305. loc_ids_.push_back(loc_id_and_inst.loc_id);
  306. return values_.Add(loc_id_and_inst.inst);
  307. }
  308. // Returns the requested instruction.
  309. auto Get(InstId inst_id) const -> Inst { return values_.Get(inst_id); }
  310. // Returns the requested instruction and its location ID.
  311. auto GetWithLocId(InstId inst_id) const -> LocIdAndInst {
  312. return LocIdAndInst(GetLocId(inst_id), Get(inst_id), /*is_untyped=*/true);
  313. }
  314. // Returns whether the requested instruction is the specified type.
  315. template <typename InstT>
  316. auto Is(InstId inst_id) const -> bool {
  317. return Get(inst_id).Is<InstT>();
  318. }
  319. // Returns the requested instruction, which is known to have the specified
  320. // type.
  321. template <typename InstT>
  322. auto GetAs(InstId inst_id) const -> InstT {
  323. return Get(inst_id).As<InstT>();
  324. }
  325. // Returns the requested instruction as the specified type, if it is of that
  326. // type.
  327. template <typename InstT>
  328. auto TryGetAs(InstId inst_id) const -> std::optional<InstT> {
  329. return Get(inst_id).TryAs<InstT>();
  330. }
  331. // Returns the requested instruction as the specified type, if it is valid and
  332. // of that type. Otherwise returns nullopt.
  333. template <typename InstT>
  334. auto TryGetAsIfValid(InstId inst_id) const -> std::optional<InstT> {
  335. if (!inst_id.is_valid()) {
  336. return std::nullopt;
  337. }
  338. return TryGetAs<InstT>(inst_id);
  339. }
  340. auto GetLocId(InstId inst_id) const -> LocId {
  341. CARBON_CHECK(inst_id.index >= 0) << inst_id.index;
  342. CARBON_CHECK(inst_id.index < (int)loc_ids_.size())
  343. << inst_id.index << " " << loc_ids_.size();
  344. return loc_ids_[inst_id.index];
  345. }
  346. // Overwrites a given instruction with a new value.
  347. auto Set(InstId inst_id, Inst inst) -> void { values_.Get(inst_id) = inst; }
  348. // Overwrites a given instruction's location with a new value.
  349. auto SetLocId(InstId inst_id, LocId loc_id) -> void {
  350. loc_ids_[inst_id.index] = loc_id;
  351. }
  352. // Overwrites a given instruction and location ID with a new value.
  353. auto SetLocIdAndInst(InstId inst_id, LocIdAndInst loc_id_and_inst) -> void {
  354. Set(inst_id, loc_id_and_inst.inst);
  355. SetLocId(inst_id, loc_id_and_inst.loc_id);
  356. }
  357. // Reserves space.
  358. auto Reserve(size_t size) -> void {
  359. loc_ids_.reserve(size);
  360. values_.Reserve(size);
  361. }
  362. auto array_ref() const -> llvm::ArrayRef<Inst> { return values_.array_ref(); }
  363. auto size() const -> int { return values_.size(); }
  364. private:
  365. llvm::SmallVector<LocId> loc_ids_;
  366. ValueStore<InstId> values_;
  367. };
  368. // Adapts BlockValueStore for instruction blocks.
  369. class InstBlockStore : public BlockValueStore<InstBlockId> {
  370. public:
  371. using BaseType = BlockValueStore<InstBlockId>;
  372. using BaseType::AddDefaultValue;
  373. using BaseType::AddUninitialized;
  374. explicit InstBlockStore(llvm::BumpPtrAllocator& allocator)
  375. : BaseType(allocator) {
  376. auto empty_id = AddDefaultValue();
  377. CARBON_CHECK(empty_id == InstBlockId::Empty);
  378. auto exports_id = AddDefaultValue();
  379. CARBON_CHECK(exports_id == InstBlockId::Exports);
  380. auto global_init_id = AddDefaultValue();
  381. CARBON_CHECK(global_init_id == InstBlockId::GlobalInit);
  382. }
  383. auto Set(InstBlockId block_id, llvm::ArrayRef<InstId> content) -> void {
  384. CARBON_CHECK(block_id != InstBlockId::Unreachable);
  385. BlockValueStore<InstBlockId>::Set(block_id, content);
  386. }
  387. // Returns the contents of the specified block, or an empty array if the block
  388. // is empty.
  389. auto GetOrEmpty(InstBlockId block_id) const -> llvm::ArrayRef<InstId> {
  390. return block_id.is_valid() ? Get(block_id) : llvm::ArrayRef<InstId>();
  391. }
  392. };
  393. // See common/hashing.h.
  394. inline auto CarbonHashValue(const Inst& value, uint64_t seed) -> HashCode {
  395. Hasher hasher(seed);
  396. hasher.HashRaw(value);
  397. return static_cast<HashCode>(hasher);
  398. }
  399. } // namespace Carbon::SemIR
  400. template <>
  401. struct llvm::DenseMapInfo<Carbon::SemIR::Inst> {
  402. using Inst = Carbon::SemIR::Inst;
  403. static auto getEmptyKey() -> Inst {
  404. return Inst(-1, Carbon::SemIR::TypeId::Invalid, 0, 0);
  405. }
  406. static auto getTombstoneKey() -> Inst {
  407. return Inst(-2, Carbon::SemIR::TypeId::Invalid, 0, 0);
  408. }
  409. static auto getHashValue(const Inst& val) -> unsigned {
  410. return static_cast<uint64_t>(Carbon::HashValue(val));
  411. }
  412. static auto isEqual(const Inst& lhs, const Inst& rhs) -> bool {
  413. return std::memcmp(&lhs, &rhs, sizeof(Inst)) == 0;
  414. }
  415. };
  416. #endif // CARBON_TOOLCHAIN_SEM_IR_INST_H_