semantics_ir.h 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  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. // Adds a callable, returning an ID to reference it.
  73. auto AddFunction(SemanticsFunction function) -> SemanticsFunctionId {
  74. SemanticsFunctionId id(functions_.size());
  75. functions_.push_back(function);
  76. return id;
  77. }
  78. // Returns the requested callable.
  79. auto GetFunction(SemanticsFunctionId function_id) const -> SemanticsFunction {
  80. return functions_[function_id.index];
  81. }
  82. // Returns the requested callable.
  83. auto GetFunction(SemanticsFunctionId function_id) -> SemanticsFunction& {
  84. return functions_[function_id.index];
  85. }
  86. // Adds an integer literal, returning an ID to reference it.
  87. auto AddIntegerLiteral(llvm::APInt integer_literal)
  88. -> SemanticsIntegerLiteralId {
  89. SemanticsIntegerLiteralId id(integer_literals_.size());
  90. integer_literals_.push_back(integer_literal);
  91. return id;
  92. }
  93. // Returns the requested integer literal.
  94. auto GetIntegerLiteral(SemanticsIntegerLiteralId int_id) const
  95. -> const llvm::APInt& {
  96. return integer_literals_[int_id.index];
  97. }
  98. // Adds a name scope, returning an ID to reference it.
  99. auto AddNameScope() -> SemanticsNameScopeId {
  100. SemanticsNameScopeId name_scopes_id(name_scopes_.size());
  101. name_scopes_.resize(name_scopes_id.index + 1);
  102. return name_scopes_id;
  103. }
  104. // Adds an entry to a name scope. Returns true on success, false on
  105. // duplicates.
  106. auto AddNameScopeEntry(SemanticsNameScopeId scope_id,
  107. SemanticsStringId name_id, SemanticsNodeId target_id)
  108. -> bool {
  109. return name_scopes_[scope_id.index].insert({name_id, target_id}).second;
  110. }
  111. // Returns the requested name scope.
  112. auto GetNameScope(SemanticsNameScopeId scope_id)
  113. -> const llvm::DenseMap<SemanticsStringId, SemanticsNodeId>& {
  114. return name_scopes_[scope_id.index];
  115. }
  116. // Adds a node to a specified block, returning an ID to reference the node.
  117. auto AddNode(SemanticsNodeBlockId block_id, SemanticsNode node)
  118. -> SemanticsNodeId {
  119. SemanticsNodeId node_id(nodes_.size());
  120. nodes_.push_back(node);
  121. if (block_id != SemanticsNodeBlockId::Unreachable) {
  122. node_blocks_[block_id.index].push_back(node_id);
  123. }
  124. return node_id;
  125. }
  126. // Returns the requested node.
  127. auto GetNode(SemanticsNodeId node_id) const -> SemanticsNode {
  128. return nodes_[node_id.index];
  129. }
  130. // Adds an empty node block, returning an ID to reference it.
  131. auto AddNodeBlock() -> SemanticsNodeBlockId {
  132. SemanticsNodeBlockId id(node_blocks_.size());
  133. node_blocks_.push_back({});
  134. return id;
  135. }
  136. // Returns the requested node block.
  137. auto GetNodeBlock(SemanticsNodeBlockId block_id) const
  138. -> const llvm::SmallVector<SemanticsNodeId>& {
  139. CARBON_CHECK(block_id != SemanticsNodeBlockId::Unreachable);
  140. return node_blocks_[block_id.index];
  141. }
  142. // Returns the requested node block.
  143. auto GetNodeBlock(SemanticsNodeBlockId block_id)
  144. -> llvm::SmallVector<SemanticsNodeId>& {
  145. CARBON_CHECK(block_id != SemanticsNodeBlockId::Unreachable);
  146. return node_blocks_[block_id.index];
  147. }
  148. // Adds a real literal, returning an ID to reference it.
  149. auto AddRealLiteral(SemanticsRealLiteral real_literal)
  150. -> SemanticsRealLiteralId {
  151. SemanticsRealLiteralId id(real_literals_.size());
  152. real_literals_.push_back(real_literal);
  153. return id;
  154. }
  155. // Returns the requested real literal.
  156. auto GetRealLiteral(SemanticsRealLiteralId int_id) const
  157. -> const SemanticsRealLiteral& {
  158. return real_literals_[int_id.index];
  159. }
  160. // Adds an string, returning an ID to reference it.
  161. auto AddString(llvm::StringRef str) -> SemanticsStringId {
  162. // If the string has already been stored, return the corresponding ID.
  163. if (auto existing_id = GetStringID(str)) {
  164. return *existing_id;
  165. }
  166. // Allocate the string and store it in the map.
  167. SemanticsStringId id(strings_.size());
  168. strings_.push_back(str);
  169. CARBON_CHECK(string_to_id_.insert({str, id}).second);
  170. return id;
  171. }
  172. // Returns the requested string.
  173. auto GetString(SemanticsStringId string_id) const -> llvm::StringRef {
  174. return strings_[string_id.index];
  175. }
  176. // Returns an ID for the string if it's previously been stored.
  177. auto GetStringID(llvm::StringRef str) -> std::optional<SemanticsStringId> {
  178. auto str_find = string_to_id_.find(str);
  179. if (str_find != string_to_id_.end()) {
  180. return str_find->second;
  181. }
  182. return std::nullopt;
  183. }
  184. // Adds a type, returning an ID to reference it.
  185. auto AddType(SemanticsNodeId node_id) -> SemanticsTypeId {
  186. SemanticsTypeId type_id(types_.size());
  187. types_.push_back(node_id);
  188. return type_id;
  189. }
  190. // Gets the node ID for a type. This doesn't handle TypeType or InvalidType in
  191. // order to avoid a check; callers that need that should use
  192. // GetTypeAllowBuiltinTypes.
  193. auto GetType(SemanticsTypeId type_id) const -> SemanticsNodeId {
  194. // Double-check it's not called with TypeType or InvalidType.
  195. CARBON_CHECK(type_id.index >= 0)
  196. << "Invalid argument for GetType: " << type_id;
  197. return types_[type_id.index];
  198. }
  199. auto GetTypeAllowBuiltinTypes(SemanticsTypeId type_id) const
  200. -> SemanticsNodeId {
  201. if (type_id == SemanticsTypeId::TypeType) {
  202. return SemanticsNodeId::BuiltinTypeType;
  203. } else if (type_id == SemanticsTypeId::Error) {
  204. return SemanticsNodeId::BuiltinError;
  205. } else {
  206. return GetType(type_id);
  207. }
  208. }
  209. // Adds an empty type block, returning an ID to reference it.
  210. auto AddTypeBlock() -> SemanticsTypeBlockId {
  211. SemanticsTypeBlockId id(type_blocks_.size());
  212. type_blocks_.push_back({});
  213. return id;
  214. }
  215. // Returns the requested type block.
  216. auto GetTypeBlock(SemanticsTypeBlockId block_id) const
  217. -> const llvm::SmallVector<SemanticsTypeId>& {
  218. return type_blocks_[block_id.index];
  219. }
  220. // Returns the requested type block.
  221. auto GetTypeBlock(SemanticsTypeBlockId block_id)
  222. -> llvm::SmallVector<SemanticsTypeId>& {
  223. return type_blocks_[block_id.index];
  224. }
  225. // Produces a string version of a type.
  226. auto StringifyType(SemanticsTypeId type_id) -> std::string;
  227. auto functions_size() const -> int { return functions_.size(); }
  228. auto nodes_size() const -> int { return nodes_.size(); }
  229. auto types() const -> const llvm::SmallVector<SemanticsNodeId>& {
  230. return types_;
  231. }
  232. // The node blocks, for direct mutation.
  233. auto node_blocks() -> llvm::SmallVector<llvm::SmallVector<SemanticsNodeId>>& {
  234. return node_blocks_;
  235. }
  236. auto top_node_block_id() const -> SemanticsNodeBlockId {
  237. return top_node_block_id_;
  238. }
  239. // Returns true if there were errors creating the semantics IR.
  240. auto has_errors() const -> bool { return has_errors_; }
  241. private:
  242. explicit SemanticsIR(const SemanticsIR* builtin_ir)
  243. : cross_reference_irs_({builtin_ir == nullptr ? this : builtin_ir}) {
  244. // For SemanticsNodeBlockId::Empty.
  245. node_blocks_.resize(1);
  246. }
  247. bool has_errors_ = false;
  248. // Storage for callable objects.
  249. llvm::SmallVector<SemanticsFunction> functions_;
  250. // Related IRs. There will always be at least 2 entries, the builtin IR (used
  251. // for references of builtins) followed by the current IR (used for references
  252. // crossing node blocks).
  253. llvm::SmallVector<const SemanticsIR*> cross_reference_irs_;
  254. // Storage for integer literals.
  255. llvm::SmallVector<llvm::APInt> integer_literals_;
  256. // Storage for name scopes.
  257. llvm::SmallVector<llvm::DenseMap<SemanticsStringId, SemanticsNodeId>>
  258. name_scopes_;
  259. // Storage for real literals.
  260. llvm::SmallVector<SemanticsRealLiteral> real_literals_;
  261. // Storage for strings. strings_ provides a list of allocated strings, while
  262. // string_to_id_ provides a mapping to identify strings.
  263. llvm::StringMap<SemanticsStringId> string_to_id_;
  264. llvm::SmallVector<llvm::StringRef> strings_;
  265. // Nodes which correspond to in-use types. Stored separately for easy access
  266. // by lowering.
  267. llvm::SmallVector<SemanticsNodeId> types_;
  268. // Storage for blocks within the IR. These reference entries in types_.
  269. llvm::SmallVector<llvm::SmallVector<SemanticsTypeId>> type_blocks_;
  270. // All nodes. The first entries will always be cross-references to builtins,
  271. // at indices matching SemanticsBuiltinKind ordering.
  272. llvm::SmallVector<SemanticsNode> nodes_;
  273. // Storage for blocks within the IR. These reference entries in nodes_.
  274. llvm::SmallVector<llvm::SmallVector<SemanticsNodeId>> node_blocks_;
  275. // The top node block ID.
  276. SemanticsNodeBlockId top_node_block_id_ = SemanticsNodeBlockId::Invalid;
  277. };
  278. } // namespace Carbon
  279. #endif // CARBON_TOOLCHAIN_SEMANTICS_SEMANTICS_IR_H_