semantics_node.h 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512
  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_SEMANTICS_SEMANTICS_NODE_H_
  5. #define CARBON_TOOLCHAIN_SEMANTICS_SEMANTICS_NODE_H_
  6. #include <cstdint>
  7. #include "common/check.h"
  8. #include "common/ostream.h"
  9. #include "toolchain/common/index_base.h"
  10. #include "toolchain/parser/parse_tree.h"
  11. #include "toolchain/semantics/semantics_builtin_kind.h"
  12. #include "toolchain/semantics/semantics_node_kind.h"
  13. namespace Carbon {
  14. // The ID of a node.
  15. struct SemanticsNodeId : public IndexBase {
  16. // An explicitly invalid node ID.
  17. static const SemanticsNodeId Invalid;
  18. // Builtin node IDs.
  19. #define CARBON_SEMANTICS_BUILTIN_KIND_NAME(Name) \
  20. static const SemanticsNodeId Builtin##Name;
  21. #include "toolchain/semantics/semantics_builtin_kind.def"
  22. using IndexBase::IndexBase;
  23. auto Print(llvm::raw_ostream& out) const -> void {
  24. out << "node";
  25. if (!is_valid()) {
  26. IndexBase::Print(out);
  27. } else if (index < SemanticsBuiltinKind::ValidCount) {
  28. out << SemanticsBuiltinKind::FromInt(index);
  29. } else {
  30. // Use the `+` as a small reminder that this is a delta, rather than an
  31. // absolute index.
  32. out << "+" << index - SemanticsBuiltinKind::ValidCount;
  33. }
  34. }
  35. };
  36. constexpr SemanticsNodeId SemanticsNodeId::Invalid =
  37. SemanticsNodeId(SemanticsNodeId::InvalidIndex);
  38. // Uses the cross-reference node ID for a builtin. This relies on SemanticsIR
  39. // guarantees for builtin cross-reference placement.
  40. #define CARBON_SEMANTICS_BUILTIN_KIND_NAME(Name) \
  41. constexpr SemanticsNodeId SemanticsNodeId::Builtin##Name = \
  42. SemanticsNodeId(SemanticsBuiltinKind::Name.AsInt());
  43. #include "toolchain/semantics/semantics_builtin_kind.def"
  44. // The ID of a function.
  45. struct SemanticsFunctionId : public IndexBase {
  46. using IndexBase::IndexBase;
  47. auto Print(llvm::raw_ostream& out) const -> void {
  48. out << "function";
  49. IndexBase::Print(out);
  50. }
  51. };
  52. // The ID of a cross-referenced IR.
  53. struct SemanticsCrossReferenceIRId : public IndexBase {
  54. using IndexBase::IndexBase;
  55. auto Print(llvm::raw_ostream& out) const -> void {
  56. out << "ir";
  57. IndexBase::Print(out);
  58. }
  59. };
  60. // A boolean value.
  61. struct SemanticsBoolValue : public IndexBase {
  62. static const SemanticsBoolValue False;
  63. static const SemanticsBoolValue True;
  64. using IndexBase::IndexBase;
  65. auto Print(llvm::raw_ostream& out) const -> void {
  66. switch (index) {
  67. case 0:
  68. out << "false";
  69. break;
  70. case 1:
  71. out << "true";
  72. break;
  73. default:
  74. CARBON_FATAL() << "Invalid bool value " << index;
  75. }
  76. }
  77. };
  78. constexpr SemanticsBoolValue SemanticsBoolValue::False = SemanticsBoolValue(0);
  79. constexpr SemanticsBoolValue SemanticsBoolValue::True = SemanticsBoolValue(1);
  80. // The ID of an integer literal.
  81. struct SemanticsIntegerLiteralId : public IndexBase {
  82. using IndexBase::IndexBase;
  83. auto Print(llvm::raw_ostream& out) const -> void {
  84. out << "int";
  85. IndexBase::Print(out);
  86. }
  87. };
  88. // The ID of a name scope.
  89. struct SemanticsNameScopeId : public IndexBase {
  90. // An explicitly invalid ID.
  91. static const SemanticsNameScopeId Invalid;
  92. using IndexBase::IndexBase;
  93. auto Print(llvm::raw_ostream& out) const -> void {
  94. out << "name_scope";
  95. IndexBase::Print(out);
  96. }
  97. };
  98. constexpr SemanticsNameScopeId SemanticsNameScopeId::Invalid =
  99. SemanticsNameScopeId(SemanticsNameScopeId::InvalidIndex);
  100. // The ID of a node block.
  101. struct SemanticsNodeBlockId : public IndexBase {
  102. // All SemanticsIR instances must provide the 0th node block as empty.
  103. static const SemanticsNodeBlockId Empty;
  104. // An explicitly invalid ID.
  105. static const SemanticsNodeBlockId Invalid;
  106. // An ID for unreachable code.
  107. static const SemanticsNodeBlockId Unreachable;
  108. using IndexBase::IndexBase;
  109. auto Print(llvm::raw_ostream& out) const -> void {
  110. if (index == Unreachable.index) {
  111. out << "unreachable";
  112. } else {
  113. out << "block";
  114. IndexBase::Print(out);
  115. }
  116. }
  117. };
  118. constexpr SemanticsNodeBlockId SemanticsNodeBlockId::Empty =
  119. SemanticsNodeBlockId(0);
  120. constexpr SemanticsNodeBlockId SemanticsNodeBlockId::Invalid =
  121. SemanticsNodeBlockId(SemanticsNodeBlockId::InvalidIndex);
  122. constexpr SemanticsNodeBlockId SemanticsNodeBlockId::Unreachable =
  123. SemanticsNodeBlockId(SemanticsNodeBlockId::InvalidIndex - 1);
  124. // The ID of a real literal.
  125. struct SemanticsRealLiteralId : public IndexBase {
  126. using IndexBase::IndexBase;
  127. auto Print(llvm::raw_ostream& out) const -> void {
  128. out << "real";
  129. IndexBase::Print(out);
  130. }
  131. };
  132. // The ID of a string.
  133. struct SemanticsStringId : public IndexBase {
  134. using IndexBase::IndexBase;
  135. auto Print(llvm::raw_ostream& out) const -> void {
  136. out << "str";
  137. IndexBase::Print(out);
  138. }
  139. };
  140. // The ID of a node block.
  141. struct SemanticsTypeId : public IndexBase {
  142. // The builtin TypeType.
  143. static const SemanticsTypeId TypeType;
  144. // The builtin Error.
  145. static const SemanticsTypeId Error;
  146. // An explicitly invalid ID.
  147. static const SemanticsTypeId Invalid;
  148. using IndexBase::IndexBase;
  149. auto Print(llvm::raw_ostream& out) const -> void {
  150. out << "type";
  151. if (index == TypeType.index) {
  152. out << "TypeType";
  153. } else if (index == Error.index) {
  154. out << "Error";
  155. } else {
  156. IndexBase::Print(out);
  157. }
  158. }
  159. };
  160. constexpr SemanticsTypeId SemanticsTypeId::TypeType =
  161. SemanticsTypeId(SemanticsTypeId::InvalidIndex - 2);
  162. constexpr SemanticsTypeId SemanticsTypeId::Error =
  163. SemanticsTypeId(SemanticsTypeId::InvalidIndex - 1);
  164. constexpr SemanticsTypeId SemanticsTypeId::Invalid =
  165. SemanticsTypeId(SemanticsTypeId::InvalidIndex);
  166. // The ID of a type block.
  167. struct SemanticsTypeBlockId : public IndexBase {
  168. using IndexBase::IndexBase;
  169. auto Print(llvm::raw_ostream& out) const -> void {
  170. out << "typeBlock";
  171. IndexBase::Print(out);
  172. }
  173. };
  174. // An index for member access.
  175. struct SemanticsMemberIndex : public IndexBase {
  176. using IndexBase::IndexBase;
  177. auto Print(llvm::raw_ostream& out) const -> void {
  178. out << "member";
  179. IndexBase::Print(out);
  180. }
  181. };
  182. // The standard structure for SemanticsNode. This is trying to provide a minimal
  183. // amount of information for a node:
  184. //
  185. // - parse_node for error placement.
  186. // - kind for run-time logic when the input Kind is unknown.
  187. // - type_id for quick type checking.
  188. // - Up to two Kind-specific members.
  189. //
  190. // For each Kind in SemanticsNodeKind, a typical flow looks like:
  191. //
  192. // - Create a `SemanticsNode` using `SemanticsNode::Kind::Make()`
  193. // - Access cross-Kind members using `node.type_id()` and similar.
  194. // - Access Kind-specific members using `node.GetAsKind()`, which depending on
  195. // the number of members will return one of NoArgs, a single value, or a
  196. // `std::pair` of values.
  197. // - Using the wrong `node.GetAsKind()` is a programming error, and should
  198. // CHECK-fail in debug modes (opt may too, but it's not an API guarantee).
  199. //
  200. // Internally, each Kind uses the `Factory*` types to provide a boilerplate
  201. // `Make` and `Get` methods.
  202. class SemanticsNode {
  203. public:
  204. struct NoArgs {};
  205. // Factory base classes are private, then used for public classes. This class
  206. // has two public and two private sections to prevent accidents.
  207. private:
  208. // Factory templates need to use the raw enum instead of the class wrapper.
  209. using KindTemplateEnum = Internal::SemanticsNodeKindRawEnum;
  210. // Provides Make and Get to support 0, 1, or 2 arguments for a SemanticsNode.
  211. // These are protected so that child factories can opt in to what pieces they
  212. // want to use.
  213. template <KindTemplateEnum Kind, typename... ArgTypes>
  214. class FactoryBase {
  215. protected:
  216. static auto Make(ParseTree::Node parse_node, SemanticsTypeId type_id,
  217. ArgTypes... arg_ids) -> SemanticsNode {
  218. return SemanticsNode(parse_node, SemanticsNodeKind::Create(Kind), type_id,
  219. arg_ids.index...);
  220. }
  221. static auto Get(SemanticsNode node) {
  222. struct Unused {};
  223. return GetImpl<ArgTypes..., Unused>(node);
  224. }
  225. private:
  226. // GetImpl handles the different return types based on ArgTypes.
  227. template <typename Arg0Type, typename Arg1Type, typename>
  228. static auto GetImpl(SemanticsNode node) -> std::pair<Arg0Type, Arg1Type> {
  229. CARBON_CHECK(node.kind() == Kind);
  230. return {Arg0Type(node.arg0_), Arg1Type(node.arg1_)};
  231. }
  232. template <typename Arg0Type, typename>
  233. static auto GetImpl(SemanticsNode node) -> Arg0Type {
  234. CARBON_CHECK(node.kind() == Kind);
  235. return Arg0Type(node.arg0_);
  236. }
  237. template <typename>
  238. static auto GetImpl(SemanticsNode node) -> NoArgs {
  239. CARBON_CHECK(node.kind() == Kind);
  240. return NoArgs();
  241. }
  242. };
  243. // Provide Get along with a Make that requires a type.
  244. template <KindTemplateEnum Kind, typename... ArgTypes>
  245. class Factory : public FactoryBase<Kind, ArgTypes...> {
  246. public:
  247. using FactoryBase<Kind, ArgTypes...>::Make;
  248. using FactoryBase<Kind, ArgTypes...>::Get;
  249. };
  250. // Provides Get along with a Make that assumes the node doesn't produce a
  251. // typed value.
  252. template <KindTemplateEnum Kind, typename... ArgTypes>
  253. class FactoryNoType : public FactoryBase<Kind, ArgTypes...> {
  254. public:
  255. static auto Make(ParseTree::Node parse_node, ArgTypes... args) {
  256. return FactoryBase<Kind, ArgTypes...>::Make(
  257. parse_node, SemanticsTypeId::Invalid, args...);
  258. }
  259. using FactoryBase<Kind, ArgTypes...>::Get;
  260. };
  261. public:
  262. // Invalid is in the SemanticsNodeKind enum, but should never be used.
  263. class Invalid {
  264. public:
  265. static auto Get(SemanticsNode /*node*/) -> SemanticsNode::NoArgs {
  266. CARBON_FATAL() << "Invalid access";
  267. }
  268. };
  269. using Assign = SemanticsNode::FactoryNoType<SemanticsNodeKind::Assign,
  270. SemanticsNodeId /*lhs_id*/,
  271. SemanticsNodeId /*rhs_id*/>;
  272. using BinaryOperatorAdd =
  273. SemanticsNode::Factory<SemanticsNodeKind::BinaryOperatorAdd,
  274. SemanticsNodeId /*lhs_id*/,
  275. SemanticsNodeId /*rhs_id*/>;
  276. using BindName = SemanticsNode::Factory<SemanticsNodeKind::BindName,
  277. SemanticsStringId /*name_id*/,
  278. SemanticsNodeId /*node_id*/>;
  279. using BlockArg =
  280. Factory<SemanticsNodeKind::BlockArg, SemanticsNodeBlockId /*block_id*/>;
  281. using BoolLiteral =
  282. Factory<SemanticsNodeKind::BoolLiteral, SemanticsBoolValue /*value*/>;
  283. using Branch = FactoryNoType<SemanticsNodeKind::Branch,
  284. SemanticsNodeBlockId /*target_id*/>;
  285. using BranchIf = FactoryNoType<SemanticsNodeKind::BranchIf,
  286. SemanticsNodeBlockId /*target_id*/,
  287. SemanticsNodeId /*cond_id*/>;
  288. using BranchWithArg = FactoryNoType<SemanticsNodeKind::BranchWithArg,
  289. SemanticsNodeBlockId /*target_id*/,
  290. SemanticsNodeId /*arg*/>;
  291. class Builtin {
  292. public:
  293. static auto Make(SemanticsBuiltinKind builtin_kind, SemanticsTypeId type_id)
  294. -> SemanticsNode {
  295. // Builtins won't have a ParseTree node associated, so we provide the
  296. // default invalid one.
  297. // This can't use the standard Make function because of the `AsInt()` cast
  298. // instead of `.index`.
  299. return SemanticsNode(ParseTree::Node::Invalid, SemanticsNodeKind::Builtin,
  300. type_id, builtin_kind.AsInt());
  301. }
  302. static auto Get(SemanticsNode node) -> SemanticsBuiltinKind {
  303. return SemanticsBuiltinKind::FromInt(node.arg0_);
  304. }
  305. };
  306. using Call =
  307. Factory<SemanticsNodeKind::Call, SemanticsNodeBlockId /*refs_id*/,
  308. SemanticsFunctionId /*function_id*/>;
  309. using ConstType =
  310. Factory<SemanticsNodeKind::ConstType, SemanticsTypeId /*inner_id*/>;
  311. class CrossReference
  312. : public FactoryBase<SemanticsNodeKind::CrossReference,
  313. SemanticsCrossReferenceIRId /*ir_id*/,
  314. SemanticsNodeId /*node_id*/> {
  315. public:
  316. static auto Make(SemanticsTypeId type_id, SemanticsCrossReferenceIRId ir_id,
  317. SemanticsNodeId node_id) -> SemanticsNode {
  318. // A node's parse tree node must refer to a node in the current parse
  319. // tree. This cannot use the cross-referenced node's parse tree node
  320. // because it will be in a different parse tree.
  321. return FactoryBase::Make(ParseTree::Node::Invalid, type_id, ir_id,
  322. node_id);
  323. }
  324. using FactoryBase::Get;
  325. };
  326. using FunctionDeclaration =
  327. FactoryNoType<SemanticsNodeKind::FunctionDeclaration,
  328. SemanticsFunctionId /*function_id*/>;
  329. using IntegerLiteral = Factory<SemanticsNodeKind::IntegerLiteral,
  330. SemanticsIntegerLiteralId /*integer_id*/>;
  331. using Namespace = FactoryNoType<SemanticsNodeKind::Namespace,
  332. SemanticsNameScopeId /*name_scope_id*/>;
  333. using PointerType =
  334. Factory<SemanticsNodeKind::PointerType, SemanticsTypeId /*pointee_id*/>;
  335. using RealLiteral = Factory<SemanticsNodeKind::RealLiteral,
  336. SemanticsRealLiteralId /*real_id*/>;
  337. using Return = FactoryNoType<SemanticsNodeKind::Return>;
  338. using ReturnExpression = FactoryNoType<SemanticsNodeKind::ReturnExpression,
  339. SemanticsNodeId /*expr_id*/>;
  340. using StringLiteral = Factory<SemanticsNodeKind::StringLiteral,
  341. SemanticsStringId /*string_id*/>;
  342. using StructMemberAccess = Factory<SemanticsNodeKind::StructMemberAccess,
  343. SemanticsNodeId /*struct_id*/,
  344. SemanticsMemberIndex /*ref_index*/>;
  345. using StructType =
  346. Factory<SemanticsNodeKind::StructType, SemanticsNodeBlockId /*refs_id*/>;
  347. using StructTypeField =
  348. FactoryNoType<SemanticsNodeKind::StructTypeField,
  349. SemanticsStringId /*name_id*/, SemanticsTypeId /*type_id*/>;
  350. using StructValue =
  351. Factory<SemanticsNodeKind::StructValue, SemanticsNodeBlockId /*refs_id*/>;
  352. using StubReference =
  353. Factory<SemanticsNodeKind::StubReference, SemanticsNodeId /*node_id*/>;
  354. using TupleType =
  355. Factory<SemanticsNodeKind::TupleType, SemanticsTypeBlockId /*refs_id*/>;
  356. using TupleValue =
  357. Factory<SemanticsNodeKind::TupleValue, SemanticsNodeBlockId /*refs_id*/>;
  358. using UnaryOperatorNot = Factory<SemanticsNodeKind::UnaryOperatorNot,
  359. SemanticsNodeId /*operand_id*/>;
  360. using VarStorage = Factory<SemanticsNodeKind::VarStorage>;
  361. SemanticsNode()
  362. : SemanticsNode(ParseTree::Node::Invalid, SemanticsNodeKind::Invalid,
  363. SemanticsTypeId::Invalid) {}
  364. // Provide `node.GetAsKind()` as an instance method for all kinds, essentially
  365. // an alias for`SemanticsNode::Kind::Get(node)`.
  366. #define CARBON_SEMANTICS_NODE_KIND(Name) \
  367. auto GetAs##Name() const { return Name::Get(*this); }
  368. #include "toolchain/semantics/semantics_node_kind.def"
  369. auto parse_node() const -> ParseTree::Node { return parse_node_; }
  370. auto kind() const -> SemanticsNodeKind { return kind_; }
  371. // Gets the type of the value produced by evaluating this node.
  372. auto type_id() const -> SemanticsTypeId { return type_id_; }
  373. auto Print(llvm::raw_ostream& out) const -> void;
  374. private:
  375. // Builtins have peculiar construction, so they are a friend rather than using
  376. // a factory base class.
  377. friend struct SemanticsNodeForBuiltin;
  378. explicit SemanticsNode(ParseTree::Node parse_node, SemanticsNodeKind kind,
  379. SemanticsTypeId type_id,
  380. int32_t arg0 = SemanticsNodeId::InvalidIndex,
  381. int32_t arg1 = SemanticsNodeId::InvalidIndex)
  382. : parse_node_(parse_node),
  383. kind_(kind),
  384. type_id_(type_id),
  385. arg0_(arg0),
  386. arg1_(arg1) {}
  387. ParseTree::Node parse_node_;
  388. SemanticsNodeKind kind_;
  389. SemanticsTypeId type_id_;
  390. // Use GetAsKind to access arg0 and arg1.
  391. int32_t arg0_;
  392. int32_t arg1_;
  393. };
  394. // TODO: This is currently 20 bytes because we sometimes have 2 arguments for a
  395. // pair of SemanticsNodes. However, SemanticsNodeKind is 1 byte; if args
  396. // were 3.5 bytes, we could potentially shrink SemanticsNode by 4 bytes. This
  397. // may be worth investigating further.
  398. static_assert(sizeof(SemanticsNode) == 20, "Unexpected SemanticsNode size");
  399. // Provides base support for use of Id types as DenseMap/DenseSet keys.
  400. // Instantiated below.
  401. template <typename Id>
  402. struct SemanticsIdMapInfo {
  403. static inline auto getEmptyKey() -> Id {
  404. return Id(llvm::DenseMapInfo<int32_t>::getEmptyKey());
  405. }
  406. static inline auto getTombstoneKey() -> Id {
  407. return Id(llvm::DenseMapInfo<int32_t>::getTombstoneKey());
  408. }
  409. static auto getHashValue(const Id& val) -> unsigned {
  410. return llvm::DenseMapInfo<int32_t>::getHashValue(val.index);
  411. }
  412. static auto isEqual(const Id& lhs, const Id& rhs) -> bool {
  413. return lhs == rhs;
  414. }
  415. };
  416. } // namespace Carbon
  417. // Support use of Id types as DenseMap/DenseSet keys.
  418. template <>
  419. struct llvm::DenseMapInfo<Carbon::SemanticsNodeBlockId>
  420. : public Carbon::SemanticsIdMapInfo<Carbon::SemanticsNodeBlockId> {};
  421. template <>
  422. struct llvm::DenseMapInfo<Carbon::SemanticsNodeId>
  423. : public Carbon::SemanticsIdMapInfo<Carbon::SemanticsNodeId> {};
  424. template <>
  425. struct llvm::DenseMapInfo<Carbon::SemanticsStringId>
  426. : public Carbon::SemanticsIdMapInfo<Carbon::SemanticsStringId> {};
  427. #endif // CARBON_TOOLCHAIN_SEMANTICS_SEMANTICS_NODE_H_