semantics_ir.h 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  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. // If the string has already been stored, return the corresponding ID.
  174. if (auto existing_id = GetStringID(str)) {
  175. return *existing_id;
  176. }
  177. // Allocate the string and store it in the map.
  178. SemanticsStringId id(strings_.size());
  179. strings_.push_back(str);
  180. CARBON_CHECK(string_to_id_.insert({str, id}).second);
  181. return id;
  182. }
  183. // Returns the requested string.
  184. auto GetString(SemanticsStringId string_id) const -> llvm::StringRef {
  185. return strings_[string_id.index];
  186. }
  187. // Returns an ID for the string if it's previously been stored.
  188. auto GetStringID(llvm::StringRef str) -> std::optional<SemanticsStringId> {
  189. auto str_find = string_to_id_.find(str);
  190. if (str_find != string_to_id_.end()) {
  191. return str_find->second;
  192. }
  193. return std::nullopt;
  194. }
  195. // Adds a type, returning an ID to reference it.
  196. auto AddType(SemanticsNodeId node_id) -> SemanticsTypeId {
  197. SemanticsTypeId type_id(types_.size());
  198. types_.push_back(node_id);
  199. return type_id;
  200. }
  201. // Gets the node ID for a type. This doesn't handle TypeType or InvalidType in
  202. // order to avoid a check; callers that need that should use
  203. // GetTypeAllowBuiltinTypes.
  204. auto GetType(SemanticsTypeId type_id) const -> SemanticsNodeId {
  205. // Double-check it's not called with TypeType or InvalidType.
  206. CARBON_CHECK(type_id.index >= 0)
  207. << "Invalid argument for GetType: " << type_id;
  208. return types_[type_id.index];
  209. }
  210. auto GetTypeAllowBuiltinTypes(SemanticsTypeId type_id) const
  211. -> SemanticsNodeId {
  212. if (type_id == SemanticsTypeId::TypeType) {
  213. return SemanticsNodeId::BuiltinTypeType;
  214. } else if (type_id == SemanticsTypeId::Error) {
  215. return SemanticsNodeId::BuiltinError;
  216. } else {
  217. return GetType(type_id);
  218. }
  219. }
  220. // Adds an empty type block, returning an ID to reference it.
  221. auto AddTypeBlock() -> SemanticsTypeBlockId {
  222. SemanticsTypeBlockId id(type_blocks_.size());
  223. type_blocks_.push_back({});
  224. return id;
  225. }
  226. // Returns the requested type block.
  227. auto GetTypeBlock(SemanticsTypeBlockId block_id) const
  228. -> const llvm::SmallVector<SemanticsTypeId>& {
  229. return type_blocks_[block_id.index];
  230. }
  231. // Returns the requested type block.
  232. auto GetTypeBlock(SemanticsTypeBlockId block_id)
  233. -> llvm::SmallVector<SemanticsTypeId>& {
  234. return type_blocks_[block_id.index];
  235. }
  236. // Produces a string version of a type. If `in_type_context` is false, an
  237. // explicit conversion to type `type` will be added in cases where the type
  238. // expression would otherwise have a different type, such as a tuple or
  239. // struct type.
  240. auto StringifyType(SemanticsTypeId type_id,
  241. bool in_type_context = false) const -> std::string;
  242. auto functions_size() const -> int { return functions_.size(); }
  243. auto nodes_size() const -> int { return nodes_.size(); }
  244. auto node_blocks_size() const -> int { return node_blocks_.size(); }
  245. auto types() const -> const llvm::SmallVector<SemanticsNodeId>& {
  246. return types_;
  247. }
  248. // The node blocks, for direct mutation.
  249. auto node_blocks() -> llvm::SmallVector<llvm::SmallVector<SemanticsNodeId>>& {
  250. return node_blocks_;
  251. }
  252. auto top_node_block_id() const -> SemanticsNodeBlockId {
  253. return top_node_block_id_;
  254. }
  255. // Returns true if there were errors creating the semantics IR.
  256. auto has_errors() const -> bool { return has_errors_; }
  257. private:
  258. explicit SemanticsIR(const SemanticsIR* builtin_ir)
  259. : cross_reference_irs_({builtin_ir == nullptr ? this : builtin_ir}) {
  260. // For SemanticsNodeBlockId::Empty.
  261. node_blocks_.resize(1);
  262. }
  263. bool has_errors_ = false;
  264. // Storage for callable objects.
  265. llvm::SmallVector<SemanticsFunction> functions_;
  266. // Related IRs. There will always be at least 2 entries, the builtin IR (used
  267. // for references of builtins) followed by the current IR (used for references
  268. // crossing node blocks).
  269. llvm::SmallVector<const SemanticsIR*> cross_reference_irs_;
  270. // Storage for integer literals.
  271. llvm::SmallVector<llvm::APInt> integer_literals_;
  272. // Storage for name scopes.
  273. llvm::SmallVector<llvm::DenseMap<SemanticsStringId, SemanticsNodeId>>
  274. name_scopes_;
  275. // Storage for real literals.
  276. llvm::SmallVector<SemanticsRealLiteral> real_literals_;
  277. // Storage for strings. strings_ provides a list of allocated strings, while
  278. // string_to_id_ provides a mapping to identify strings.
  279. llvm::StringMap<SemanticsStringId> string_to_id_;
  280. llvm::SmallVector<llvm::StringRef> strings_;
  281. // Nodes which correspond to in-use types. Stored separately for easy access
  282. // by lowering.
  283. llvm::SmallVector<SemanticsNodeId> types_;
  284. // Storage for blocks within the IR. These reference entries in types_.
  285. llvm::SmallVector<llvm::SmallVector<SemanticsTypeId>> type_blocks_;
  286. // All nodes. The first entries will always be cross-references to builtins,
  287. // at indices matching SemanticsBuiltinKind ordering.
  288. llvm::SmallVector<SemanticsNode> nodes_;
  289. // Storage for blocks within the IR. These reference entries in nodes_.
  290. llvm::SmallVector<llvm::SmallVector<SemanticsNodeId>> node_blocks_;
  291. // The top node block ID.
  292. SemanticsNodeBlockId top_node_block_id_ = SemanticsNodeBlockId::Invalid;
  293. };
  294. // The expression category of a semantics node. See /docs/design/values.md for
  295. // details.
  296. enum class SemanticsExpressionCategory {
  297. // This node does not correspond to an expression, and as such has no
  298. // category.
  299. NotExpression,
  300. // This node represents a value expression.
  301. Value,
  302. // This node represents a durable reference expression, that denotes an
  303. // object that outlives the current full expression context.
  304. DurableReference,
  305. // This node represents an ephemeral reference expression, that denotes an
  306. // object that does not outlive the current full expression context.
  307. EphemeralReference,
  308. // This node represents an initializing expression, that describes how to
  309. // initialize an object.
  310. Initializing,
  311. };
  312. // Returns the expression category for a node.
  313. auto GetSemanticsExpressionCategory(const SemanticsIR& semantics_ir,
  314. SemanticsNodeId node_id)
  315. -> SemanticsExpressionCategory;
  316. } // namespace Carbon
  317. #endif // CARBON_TOOLCHAIN_SEMANTICS_SEMANTICS_IR_H_