semantics_ir.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426
  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::SemIR {
  13. // A function.
  14. struct Function {
  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 (return_slot_id.is_valid()) {
  22. out << ", return_slot: " << return_slot_id;
  23. }
  24. if (!body_block_ids.empty()) {
  25. out << llvm::formatv(
  26. ", body: [{0}]",
  27. llvm::make_range(body_block_ids.begin(), body_block_ids.end()));
  28. }
  29. out << "}";
  30. }
  31. LLVM_DUMP_METHOD void Dump() const { llvm::errs() << *this; }
  32. // The function name.
  33. StringId name_id;
  34. // A block containing a single reference node per parameter.
  35. NodeBlockId param_refs_id;
  36. // The return type. This will be invalid if the return type wasn't specified.
  37. TypeId return_type_id;
  38. // The storage for the return value, which is a reference expression whose
  39. // type is the return type of the function. Will be invalid if the function
  40. // doesn't have a return slot. If this is valid, a call to the function is
  41. // expected to have an additional final argument corresponding to the return
  42. // slot.
  43. NodeId return_slot_id;
  44. // A list of the statically reachable code blocks in the body of the
  45. // function, in lexical order. The first block is the entry block. This will
  46. // be empty for declarations that don't have a visible definition.
  47. llvm::SmallVector<NodeBlockId> body_block_ids;
  48. };
  49. struct RealLiteral {
  50. auto Print(llvm::raw_ostream& out) const -> void {
  51. out << "{mantissa: " << mantissa << ", exponent: " << exponent
  52. << ", is_decimal: " << is_decimal << "}";
  53. }
  54. LLVM_DUMP_METHOD void Dump() const { llvm::errs() << *this; }
  55. llvm::APInt mantissa;
  56. llvm::APInt exponent;
  57. // If false, the value is mantissa * 2^exponent.
  58. // If true, the value is mantissa * 10^exponent.
  59. bool is_decimal;
  60. };
  61. // Provides semantic analysis on a ParseTree.
  62. class File {
  63. public:
  64. // Produces the builtins.
  65. static auto MakeBuiltinIR() -> File;
  66. // Adds the IR for the provided ParseTree.
  67. static auto MakeFromParseTree(const File& builtin_ir,
  68. const TokenizedBuffer& tokens,
  69. const ParseTree& parse_tree,
  70. DiagnosticConsumer& consumer,
  71. llvm::raw_ostream* vlog_stream) -> File;
  72. // Verifies that invariants of the semantics IR hold.
  73. auto Verify() const -> ErrorOr<Success>;
  74. // Prints the full IR. Allow omitting builtins so that unrelated changes are
  75. // less likely to alternate test golden files.
  76. // TODO: In the future, the things to print may change, for example by adding
  77. // preludes. We may then want the ability to omit other things similar to
  78. // builtins.
  79. auto Print(llvm::raw_ostream& out, bool include_builtins) const -> void;
  80. auto Print(llvm::raw_ostream& out) const -> void {
  81. Print(out, /*include_builtins=*/false);
  82. }
  83. // Returns array bound value from the bound node.
  84. auto GetArrayBoundValue(NodeId bound_id) const -> uint64_t {
  85. return GetIntegerLiteral(GetNode(bound_id).GetAsIntegerLiteral())
  86. .getZExtValue();
  87. }
  88. // Returns the requested IR.
  89. auto GetCrossReferenceIR(CrossReferenceIRId xref_id) const -> const File& {
  90. return *cross_reference_irs_[xref_id.index];
  91. }
  92. // Adds a callable, returning an ID to reference it.
  93. auto AddFunction(Function function) -> FunctionId {
  94. FunctionId id(functions_.size());
  95. functions_.push_back(function);
  96. return id;
  97. }
  98. // Returns the requested callable.
  99. auto GetFunction(FunctionId function_id) const -> const Function& {
  100. return functions_[function_id.index];
  101. }
  102. // Returns the requested callable.
  103. auto GetFunction(FunctionId function_id) -> Function& {
  104. return functions_[function_id.index];
  105. }
  106. // Adds an integer literal, returning an ID to reference it.
  107. auto AddIntegerLiteral(llvm::APInt integer_literal) -> IntegerLiteralId {
  108. IntegerLiteralId id(integer_literals_.size());
  109. integer_literals_.push_back(integer_literal);
  110. return id;
  111. }
  112. // Returns the requested integer literal.
  113. auto GetIntegerLiteral(IntegerLiteralId int_id) const -> const llvm::APInt& {
  114. return integer_literals_[int_id.index];
  115. }
  116. // Adds a name scope, returning an ID to reference it.
  117. auto AddNameScope() -> NameScopeId {
  118. NameScopeId name_scopes_id(name_scopes_.size());
  119. name_scopes_.resize(name_scopes_id.index + 1);
  120. return name_scopes_id;
  121. }
  122. // Adds an entry to a name scope. Returns true on success, false on
  123. // duplicates.
  124. auto AddNameScopeEntry(NameScopeId scope_id, StringId name_id,
  125. NodeId target_id) -> bool {
  126. return name_scopes_[scope_id.index].insert({name_id, target_id}).second;
  127. }
  128. // Returns the requested name scope.
  129. auto GetNameScope(NameScopeId scope_id) const
  130. -> const llvm::DenseMap<StringId, NodeId>& {
  131. return name_scopes_[scope_id.index];
  132. }
  133. // Adds a node to a specified block, returning an ID to reference the node.
  134. auto AddNode(NodeBlockId block_id, Node node) -> NodeId {
  135. NodeId node_id(nodes_.size());
  136. nodes_.push_back(node);
  137. if (block_id != NodeBlockId::Unreachable) {
  138. node_blocks_[block_id.index].push_back(node_id);
  139. }
  140. return node_id;
  141. }
  142. // Overwrites a given node with a new value.
  143. auto ReplaceNode(NodeId node_id, Node node) -> void {
  144. nodes_[node_id.index] = node;
  145. }
  146. // Returns the requested node.
  147. auto GetNode(NodeId node_id) const -> Node { return nodes_[node_id.index]; }
  148. // Adds an empty node block, returning an ID to reference it.
  149. auto AddNodeBlock() -> NodeBlockId {
  150. NodeBlockId id(node_blocks_.size());
  151. node_blocks_.push_back({});
  152. return id;
  153. }
  154. // Returns the requested node block.
  155. auto GetNodeBlock(NodeBlockId block_id) const
  156. -> const llvm::SmallVector<NodeId>& {
  157. CARBON_CHECK(block_id != NodeBlockId::Unreachable);
  158. return node_blocks_[block_id.index];
  159. }
  160. // Returns the requested node block.
  161. auto GetNodeBlock(NodeBlockId block_id) -> llvm::SmallVector<NodeId>& {
  162. CARBON_CHECK(block_id != NodeBlockId::Unreachable);
  163. return node_blocks_[block_id.index];
  164. }
  165. // Adds a real literal, returning an ID to reference it.
  166. auto AddRealLiteral(RealLiteral real_literal) -> RealLiteralId {
  167. RealLiteralId id(real_literals_.size());
  168. real_literals_.push_back(real_literal);
  169. return id;
  170. }
  171. // Returns the requested real literal.
  172. auto GetRealLiteral(RealLiteralId int_id) const -> const RealLiteral& {
  173. return real_literals_[int_id.index];
  174. }
  175. // Adds an string, returning an ID to reference it.
  176. auto AddString(llvm::StringRef str) -> StringId {
  177. // Look up the string, or add it if it's new.
  178. StringId next_id(strings_.size());
  179. auto [it, added] = string_to_id_.insert({str, next_id});
  180. if (added) {
  181. // Update the reverse mapping from IDs to strings.
  182. CARBON_CHECK(it->second == next_id);
  183. strings_.push_back(it->first());
  184. }
  185. return it->second;
  186. }
  187. // Returns the requested string.
  188. auto GetString(StringId string_id) const -> llvm::StringRef {
  189. return strings_[string_id.index];
  190. }
  191. // Adds a type, returning an ID to reference it.
  192. auto AddType(NodeId node_id) -> TypeId {
  193. TypeId type_id(types_.size());
  194. types_.push_back(node_id);
  195. return type_id;
  196. }
  197. // Gets the node ID for a type. This doesn't handle TypeType or InvalidType in
  198. // order to avoid a check; callers that need that should use
  199. // GetTypeAllowBuiltinTypes.
  200. auto GetType(TypeId type_id) const -> NodeId {
  201. // Double-check it's not called with TypeType or InvalidType.
  202. CARBON_CHECK(type_id.index >= 0)
  203. << "Invalid argument for GetType: " << type_id;
  204. return types_[type_id.index];
  205. }
  206. auto GetTypeAllowBuiltinTypes(TypeId type_id) const -> NodeId {
  207. if (type_id == TypeId::TypeType) {
  208. return NodeId::BuiltinTypeType;
  209. } else if (type_id == TypeId::Error) {
  210. return NodeId::BuiltinError;
  211. } else {
  212. return GetType(type_id);
  213. }
  214. }
  215. // Adds an empty type block, returning an ID to reference it.
  216. auto AddTypeBlock() -> TypeBlockId {
  217. TypeBlockId id(type_blocks_.size());
  218. type_blocks_.push_back({});
  219. return id;
  220. }
  221. // Returns the requested type block.
  222. auto GetTypeBlock(TypeBlockId block_id) const
  223. -> const llvm::SmallVector<TypeId>& {
  224. return type_blocks_[block_id.index];
  225. }
  226. // Returns the requested type block.
  227. auto GetTypeBlock(TypeBlockId block_id) -> llvm::SmallVector<TypeId>& {
  228. return type_blocks_[block_id.index];
  229. }
  230. // Produces a string version of a type. If `in_type_context` is false, an
  231. // explicit conversion to type `type` will be added in cases where the type
  232. // expression would otherwise have a different type, such as a tuple or
  233. // struct type.
  234. auto StringifyType(TypeId type_id, bool in_type_context = false) const
  235. -> std::string;
  236. auto functions_size() const -> int { return functions_.size(); }
  237. auto nodes_size() const -> int { return nodes_.size(); }
  238. auto node_blocks_size() const -> int { return node_blocks_.size(); }
  239. auto types() const -> const llvm::SmallVector<NodeId>& { return types_; }
  240. // The node blocks, for direct mutation.
  241. auto node_blocks() -> llvm::SmallVector<llvm::SmallVector<NodeId>>& {
  242. return node_blocks_;
  243. }
  244. auto top_node_block_id() const -> NodeBlockId { return top_node_block_id_; }
  245. // Returns true if there were errors creating the semantics IR.
  246. auto has_errors() const -> bool { return has_errors_; }
  247. private:
  248. explicit File(const File* builtin_ir)
  249. : cross_reference_irs_({builtin_ir == nullptr ? this : builtin_ir}) {
  250. // For NodeBlockId::Empty.
  251. node_blocks_.resize(1);
  252. }
  253. bool has_errors_ = false;
  254. // Storage for callable objects.
  255. llvm::SmallVector<Function> functions_;
  256. // Related IRs. There will always be at least 2 entries, the builtin IR (used
  257. // for references of builtins) followed by the current IR (used for references
  258. // crossing node blocks).
  259. llvm::SmallVector<const File*> cross_reference_irs_;
  260. // Storage for integer literals.
  261. llvm::SmallVector<llvm::APInt> integer_literals_;
  262. // Storage for name scopes.
  263. llvm::SmallVector<llvm::DenseMap<StringId, NodeId>> name_scopes_;
  264. // Storage for real literals.
  265. llvm::SmallVector<RealLiteral> real_literals_;
  266. // Storage for strings. strings_ provides a list of allocated strings, while
  267. // string_to_id_ provides a mapping to identify strings.
  268. llvm::StringMap<StringId> string_to_id_;
  269. llvm::SmallVector<llvm::StringRef> strings_;
  270. // Nodes which correspond to in-use types. Stored separately for easy access
  271. // by lowering.
  272. llvm::SmallVector<NodeId> types_;
  273. // Storage for blocks within the IR. These reference entries in types_.
  274. llvm::SmallVector<llvm::SmallVector<TypeId>> type_blocks_;
  275. // All nodes. The first entries will always be cross-references to builtins,
  276. // at indices matching BuiltinKind ordering.
  277. llvm::SmallVector<Node> nodes_;
  278. // Storage for blocks within the IR. These reference entries in nodes_.
  279. llvm::SmallVector<llvm::SmallVector<NodeId>> node_blocks_;
  280. // The top node block ID.
  281. NodeBlockId top_node_block_id_ = NodeBlockId::Invalid;
  282. };
  283. // The expression category of a semantics node. See /docs/design/values.md for
  284. // details.
  285. enum class ExpressionCategory : int8_t {
  286. // This node does not correspond to an expression, and as such has no
  287. // category.
  288. NotExpression,
  289. // This node represents a value expression.
  290. Value,
  291. // This node represents a durable reference expression, that denotes an
  292. // object that outlives the current full expression context.
  293. DurableReference,
  294. // This node represents an ephemeral reference expression, that denotes an
  295. // object that does not outlive the current full expression context.
  296. EphemeralReference,
  297. // This node represents an initializing expression, that describes how to
  298. // initialize an object.
  299. Initializing,
  300. };
  301. // Returns the expression category for a node.
  302. auto GetExpressionCategory(const File& file, NodeId node_id)
  303. -> ExpressionCategory;
  304. // The value representation to use when passing by value.
  305. struct ValueRepresentation {
  306. enum Kind : int8_t {
  307. // The type has no value representation. This is used for empty types, such
  308. // as `()`, where there is no value.
  309. None,
  310. // The value representation is a copy of the value. On call boundaries, the
  311. // value itself will be passed. `type` is the value type.
  312. // TODO: `type` should be `const`-qualified, but is currently not.
  313. Copy,
  314. // The value representation is a pointer to an object. When used as a
  315. // parameter, the argument is a reference expression. `type` is the pointee
  316. // type.
  317. // TODO: `type` should be `const`-qualified, but is currently not.
  318. Pointer,
  319. // The value representation has been customized, and has the same behavior
  320. // as the value representation of some other type.
  321. // TODO: This is not implemented or used yet.
  322. Custom,
  323. };
  324. // The kind of value representation used by this type.
  325. Kind kind;
  326. // The type used to model the value representation.
  327. TypeId type;
  328. };
  329. // Returns information about the value representation to use for a type.
  330. auto GetValueRepresentation(const File& file, TypeId type_id)
  331. -> ValueRepresentation;
  332. // The initializing representation to use when returning by value.
  333. struct InitializingRepresentation {
  334. enum Kind : int8_t {
  335. // The type has no initializing representation. This is used for empty
  336. // types, where no initialization is necessary.
  337. None,
  338. // An initializing expression produces a value, which is copied into the
  339. // initialized object.
  340. ByCopy,
  341. // An initializing expression takes a location as input, which is
  342. // initialized as a side effect of evaluating the expression.
  343. InPlace,
  344. // TODO: Consider adding a kind where the expression takes an advisory
  345. // location and returns a value plus an indicator of whether the location
  346. // was actually initialized.
  347. };
  348. // The kind of initializing representation used by this type.
  349. Kind kind;
  350. // Returns whether a return slot is used when returning this type.
  351. auto has_return_slot() const -> bool { return kind == InPlace; }
  352. };
  353. // Returns information about the initializing representation to use for a type.
  354. auto GetInitializingRepresentation(const File& file, TypeId type_id)
  355. -> InitializingRepresentation;
  356. } // namespace Carbon::SemIR
  357. #endif // CARBON_TOOLCHAIN_SEMANTICS_SEMANTICS_IR_H_