semantics_ir.h 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  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_IR_H_
  5. #define CARBON_TOOLCHAIN_SEMANTICS_SEMANTICS_IR_H_
  6. #include "llvm/ADT/SmallVector.h"
  7. #include "llvm/ADT/StringMap.h"
  8. #include "llvm/ADT/iterator_range.h"
  9. #include "llvm/Support/FormatVariadic.h"
  10. #include "toolchain/parser/parse_tree.h"
  11. #include "toolchain/semantics/semantics_node.h"
  12. namespace Carbon {
  13. // A function.
  14. struct SemanticsFunction {
  15. auto Print(llvm::raw_ostream& out) const -> void {
  16. out << "{name: " << name_id << ", "
  17. << "param_refs: " << param_refs_id;
  18. if (return_type_id.is_valid()) {
  19. out << ", return_type: " << return_type_id;
  20. }
  21. if (!body_block_ids.empty()) {
  22. out << llvm::formatv(
  23. ", body: [{0}]",
  24. llvm::make_range(body_block_ids.begin(), body_block_ids.end()));
  25. }
  26. out << "}";
  27. }
  28. // The function name.
  29. SemanticsStringId name_id;
  30. // A block containing a single reference node per parameter.
  31. SemanticsNodeBlockId param_refs_id;
  32. // The return type. This will be invalid if the return type wasn't specified.
  33. SemanticsTypeId return_type_id;
  34. // A list of the statically reachable code blocks in the body of the
  35. // function, in lexical order. The first block is the entry block. This will
  36. // be empty for declarations that don't have a visible definition.
  37. llvm::SmallVector<SemanticsNodeBlockId> body_block_ids;
  38. };
  39. struct SemanticsRealLiteral {
  40. auto Print(llvm::raw_ostream& out) const -> void {
  41. out << "{mantissa: " << mantissa << ", exponent: " << exponent
  42. << ", is_decimal: " << is_decimal << "}";
  43. }
  44. llvm::APInt mantissa;
  45. llvm::APInt exponent;
  46. // If false, the value is mantissa * 2^exponent.
  47. // If true, the value is mantissa * 10^exponent.
  48. bool is_decimal;
  49. };
  50. // Provides semantic analysis on a ParseTree.
  51. class SemanticsIR {
  52. public:
  53. // Produces the builtins.
  54. static auto MakeBuiltinIR() -> SemanticsIR;
  55. // Adds the IR for the provided ParseTree.
  56. static auto MakeFromParseTree(const SemanticsIR& builtin_ir,
  57. const TokenizedBuffer& tokens,
  58. const ParseTree& parse_tree,
  59. DiagnosticConsumer& consumer,
  60. llvm::raw_ostream* vlog_stream) -> SemanticsIR;
  61. // Verifies that invariants of the semantics IR hold.
  62. auto Verify() const -> ErrorOr<Success>;
  63. // Prints the full IR. Allow omitting builtins so that unrelated changes are
  64. // less likely to alternate test golden files.
  65. // TODO: In the future, the things to print may change, for example by adding
  66. // preludes. We may then want the ability to omit other things similar to
  67. // builtins.
  68. auto Print(llvm::raw_ostream& out) const -> void {
  69. Print(out, /*include_builtins=*/false);
  70. }
  71. auto Print(llvm::raw_ostream& out, bool include_builtins) const -> void;
  72. // Returns array bound value from the bound node.
  73. auto GetArrayBoundValue(SemanticsNodeId bound_id) const -> uint64_t {
  74. return GetIntegerLiteral(GetNode(bound_id).GetAsIntegerLiteral())
  75. .getZExtValue();
  76. }
  77. // Returns the requested IR.
  78. auto GetCrossReferenceIR(SemanticsCrossReferenceIRId xref_id) const
  79. -> const SemanticsIR& {
  80. return *cross_reference_irs_[xref_id.index];
  81. }
  82. // Adds a callable, returning an ID to reference it.
  83. auto AddFunction(SemanticsFunction function) -> SemanticsFunctionId {
  84. SemanticsFunctionId id(functions_.size());
  85. functions_.push_back(function);
  86. return id;
  87. }
  88. // Returns the requested callable.
  89. auto GetFunction(SemanticsFunctionId function_id) const
  90. -> const SemanticsFunction& {
  91. return functions_[function_id.index];
  92. }
  93. // Returns the requested callable.
  94. auto GetFunction(SemanticsFunctionId function_id) -> SemanticsFunction& {
  95. return functions_[function_id.index];
  96. }
  97. // Adds an integer literal, returning an ID to reference it.
  98. auto AddIntegerLiteral(llvm::APInt integer_literal)
  99. -> SemanticsIntegerLiteralId {
  100. SemanticsIntegerLiteralId id(integer_literals_.size());
  101. integer_literals_.push_back(integer_literal);
  102. return id;
  103. }
  104. // Returns the requested integer literal.
  105. auto GetIntegerLiteral(SemanticsIntegerLiteralId int_id) const
  106. -> const llvm::APInt& {
  107. return integer_literals_[int_id.index];
  108. }
  109. // Adds a name scope, returning an ID to reference it.
  110. auto AddNameScope() -> SemanticsNameScopeId {
  111. SemanticsNameScopeId name_scopes_id(name_scopes_.size());
  112. name_scopes_.resize(name_scopes_id.index + 1);
  113. return name_scopes_id;
  114. }
  115. // Adds an entry to a name scope. Returns true on success, false on
  116. // duplicates.
  117. auto AddNameScopeEntry(SemanticsNameScopeId scope_id,
  118. SemanticsStringId name_id, SemanticsNodeId target_id)
  119. -> bool {
  120. return name_scopes_[scope_id.index].insert({name_id, target_id}).second;
  121. }
  122. // Returns the requested name scope.
  123. auto GetNameScope(SemanticsNameScopeId scope_id) const
  124. -> const llvm::DenseMap<SemanticsStringId, SemanticsNodeId>& {
  125. return name_scopes_[scope_id.index];
  126. }
  127. // Adds a node to a specified block, returning an ID to reference the node.
  128. auto AddNode(SemanticsNodeBlockId block_id, SemanticsNode node)
  129. -> SemanticsNodeId {
  130. SemanticsNodeId node_id(nodes_.size());
  131. nodes_.push_back(node);
  132. if (block_id != SemanticsNodeBlockId::Unreachable) {
  133. node_blocks_[block_id.index].push_back(node_id);
  134. }
  135. return node_id;
  136. }
  137. // Returns the requested node.
  138. auto GetNode(SemanticsNodeId node_id) const -> SemanticsNode {
  139. return nodes_[node_id.index];
  140. }
  141. // Adds an empty node block, returning an ID to reference it.
  142. auto AddNodeBlock() -> SemanticsNodeBlockId {
  143. SemanticsNodeBlockId id(node_blocks_.size());
  144. node_blocks_.push_back({});
  145. return id;
  146. }
  147. // Returns the requested node block.
  148. auto GetNodeBlock(SemanticsNodeBlockId block_id) const
  149. -> const llvm::SmallVector<SemanticsNodeId>& {
  150. CARBON_CHECK(block_id != SemanticsNodeBlockId::Unreachable);
  151. return node_blocks_[block_id.index];
  152. }
  153. // Returns the requested node block.
  154. auto GetNodeBlock(SemanticsNodeBlockId block_id)
  155. -> llvm::SmallVector<SemanticsNodeId>& {
  156. CARBON_CHECK(block_id != SemanticsNodeBlockId::Unreachable);
  157. return node_blocks_[block_id.index];
  158. }
  159. // Adds a real literal, returning an ID to reference it.
  160. auto AddRealLiteral(SemanticsRealLiteral real_literal)
  161. -> SemanticsRealLiteralId {
  162. SemanticsRealLiteralId id(real_literals_.size());
  163. real_literals_.push_back(real_literal);
  164. return id;
  165. }
  166. // Returns the requested real literal.
  167. auto GetRealLiteral(SemanticsRealLiteralId int_id) const
  168. -> const SemanticsRealLiteral& {
  169. return real_literals_[int_id.index];
  170. }
  171. // Adds an string, returning an ID to reference it.
  172. auto AddString(llvm::StringRef str) -> SemanticsStringId {
  173. // Look up the string, or add it if it's new.
  174. SemanticsStringId next_id(strings_.size());
  175. auto [it, added] = string_to_id_.insert({str, next_id});
  176. if (added) {
  177. // Update the reverse mapping from IDs to strings.
  178. CARBON_CHECK(it->second == next_id);
  179. strings_.push_back(it->first());
  180. }
  181. return it->second;
  182. }
  183. // Returns the requested string.
  184. auto GetString(SemanticsStringId string_id) const -> llvm::StringRef {
  185. return strings_[string_id.index];
  186. }
  187. // Adds a type, returning an ID to reference it.
  188. auto AddType(SemanticsNodeId node_id) -> SemanticsTypeId {
  189. SemanticsTypeId type_id(types_.size());
  190. types_.push_back(node_id);
  191. return type_id;
  192. }
  193. // Gets the node ID for a type. This doesn't handle TypeType or InvalidType in
  194. // order to avoid a check; callers that need that should use
  195. // GetTypeAllowBuiltinTypes.
  196. auto GetType(SemanticsTypeId type_id) const -> SemanticsNodeId {
  197. // Double-check it's not called with TypeType or InvalidType.
  198. CARBON_CHECK(type_id.index >= 0)
  199. << "Invalid argument for GetType: " << type_id;
  200. return types_[type_id.index];
  201. }
  202. auto GetTypeAllowBuiltinTypes(SemanticsTypeId type_id) const
  203. -> SemanticsNodeId {
  204. if (type_id == SemanticsTypeId::TypeType) {
  205. return SemanticsNodeId::BuiltinTypeType;
  206. } else if (type_id == SemanticsTypeId::Error) {
  207. return SemanticsNodeId::BuiltinError;
  208. } else {
  209. return GetType(type_id);
  210. }
  211. }
  212. // Adds an empty type block, returning an ID to reference it.
  213. auto AddTypeBlock() -> SemanticsTypeBlockId {
  214. SemanticsTypeBlockId id(type_blocks_.size());
  215. type_blocks_.push_back({});
  216. return id;
  217. }
  218. // Returns the requested type block.
  219. auto GetTypeBlock(SemanticsTypeBlockId block_id) const
  220. -> const llvm::SmallVector<SemanticsTypeId>& {
  221. return type_blocks_[block_id.index];
  222. }
  223. // Returns the requested type block.
  224. auto GetTypeBlock(SemanticsTypeBlockId block_id)
  225. -> llvm::SmallVector<SemanticsTypeId>& {
  226. return type_blocks_[block_id.index];
  227. }
  228. // Produces a string version of a type. If `in_type_context` is false, an
  229. // explicit conversion to type `type` will be added in cases where the type
  230. // expression would otherwise have a different type, such as a tuple or
  231. // struct type.
  232. auto StringifyType(SemanticsTypeId type_id,
  233. bool in_type_context = false) const -> std::string;
  234. auto functions_size() const -> int { return functions_.size(); }
  235. auto nodes_size() const -> int { return nodes_.size(); }
  236. auto node_blocks_size() const -> int { return node_blocks_.size(); }
  237. auto types() const -> const llvm::SmallVector<SemanticsNodeId>& {
  238. return types_;
  239. }
  240. // The node blocks, for direct mutation.
  241. auto node_blocks() -> llvm::SmallVector<llvm::SmallVector<SemanticsNodeId>>& {
  242. return node_blocks_;
  243. }
  244. auto top_node_block_id() const -> SemanticsNodeBlockId {
  245. return top_node_block_id_;
  246. }
  247. // Returns true if there were errors creating the semantics IR.
  248. auto has_errors() const -> bool { return has_errors_; }
  249. private:
  250. explicit SemanticsIR(const SemanticsIR* builtin_ir)
  251. : cross_reference_irs_({builtin_ir == nullptr ? this : builtin_ir}) {
  252. // For SemanticsNodeBlockId::Empty.
  253. node_blocks_.resize(1);
  254. }
  255. bool has_errors_ = false;
  256. // Storage for callable objects.
  257. llvm::SmallVector<SemanticsFunction> functions_;
  258. // Related IRs. There will always be at least 2 entries, the builtin IR (used
  259. // for references of builtins) followed by the current IR (used for references
  260. // crossing node blocks).
  261. llvm::SmallVector<const SemanticsIR*> cross_reference_irs_;
  262. // Storage for integer literals.
  263. llvm::SmallVector<llvm::APInt> integer_literals_;
  264. // Storage for name scopes.
  265. llvm::SmallVector<llvm::DenseMap<SemanticsStringId, SemanticsNodeId>>
  266. name_scopes_;
  267. // Storage for real literals.
  268. llvm::SmallVector<SemanticsRealLiteral> real_literals_;
  269. // Storage for strings. strings_ provides a list of allocated strings, while
  270. // string_to_id_ provides a mapping to identify strings.
  271. llvm::StringMap<SemanticsStringId> string_to_id_;
  272. llvm::SmallVector<llvm::StringRef> strings_;
  273. // Nodes which correspond to in-use types. Stored separately for easy access
  274. // by lowering.
  275. llvm::SmallVector<SemanticsNodeId> types_;
  276. // Storage for blocks within the IR. These reference entries in types_.
  277. llvm::SmallVector<llvm::SmallVector<SemanticsTypeId>> type_blocks_;
  278. // All nodes. The first entries will always be cross-references to builtins,
  279. // at indices matching SemanticsBuiltinKind ordering.
  280. llvm::SmallVector<SemanticsNode> nodes_;
  281. // Storage for blocks within the IR. These reference entries in nodes_.
  282. llvm::SmallVector<llvm::SmallVector<SemanticsNodeId>> node_blocks_;
  283. // The top node block ID.
  284. SemanticsNodeBlockId top_node_block_id_ = SemanticsNodeBlockId::Invalid;
  285. };
  286. // The expression category of a semantics node. See /docs/design/values.md for
  287. // details.
  288. enum class SemanticsExpressionCategory {
  289. // This node does not correspond to an expression, and as such has no
  290. // category.
  291. NotExpression,
  292. // This node represents a value expression.
  293. Value,
  294. // This node represents a durable reference expression, that denotes an
  295. // object that outlives the current full expression context.
  296. DurableReference,
  297. // This node represents an ephemeral reference expression, that denotes an
  298. // object that does not outlive the current full expression context.
  299. EphemeralReference,
  300. // This node represents an initializing expression, that describes how to
  301. // initialize an object.
  302. Initializing,
  303. };
  304. // Returns the expression category for a node.
  305. auto GetSemanticsExpressionCategory(const SemanticsIR& semantics_ir,
  306. SemanticsNodeId node_id)
  307. -> SemanticsExpressionCategory;
  308. } // namespace Carbon
  309. #endif // CARBON_TOOLCHAIN_SEMANTICS_SEMANTICS_IR_H_