file.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  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_SEM_IR_FILE_H_
  5. #define CARBON_TOOLCHAIN_SEM_IR_FILE_H_
  6. #include "llvm/ADT/SmallVector.h"
  7. #include "llvm/ADT/iterator_range.h"
  8. #include "llvm/Support/Allocator.h"
  9. #include "llvm/Support/FormatVariadic.h"
  10. #include "toolchain/base/value_store.h"
  11. #include "toolchain/base/yaml.h"
  12. #include "toolchain/sem_ir/ids.h"
  13. #include "toolchain/sem_ir/type_info.h"
  14. #include "toolchain/sem_ir/value_stores.h"
  15. namespace Carbon::SemIR {
  16. // A function.
  17. struct Function : public Printable<Function> {
  18. auto Print(llvm::raw_ostream& out) const -> void {
  19. out << "{name: " << name_id << ", "
  20. << "param_refs: " << param_refs_id;
  21. if (return_type_id.is_valid()) {
  22. out << ", return_type: " << return_type_id;
  23. }
  24. if (return_slot_id.is_valid()) {
  25. out << ", return_slot: " << return_slot_id;
  26. }
  27. if (!body_block_ids.empty()) {
  28. out << llvm::formatv(
  29. ", body: [{0}]",
  30. llvm::make_range(body_block_ids.begin(), body_block_ids.end()));
  31. }
  32. out << "}";
  33. }
  34. // The function name.
  35. NameId name_id;
  36. // The first declaration of the function. This is a FunctionDecl.
  37. InstId decl_id = InstId::Invalid;
  38. // The definition, if the function has been defined or is currently being
  39. // defined. This is a FunctionDecl.
  40. InstId definition_id = InstId::Invalid;
  41. // A block containing a single reference instruction per implicit parameter.
  42. InstBlockId implicit_param_refs_id;
  43. // A block containing a single reference instruction per parameter.
  44. InstBlockId param_refs_id;
  45. // The return type. This will be invalid if the return type wasn't specified.
  46. TypeId return_type_id;
  47. // The storage for the return value, which is a reference expression whose
  48. // type is the return type of the function. Will be invalid if the function
  49. // doesn't have a return slot. If this is valid, a call to the function is
  50. // expected to have an additional final argument corresponding to the return
  51. // slot.
  52. InstId return_slot_id;
  53. // A list of the statically reachable code blocks in the body of the
  54. // function, in lexical order. The first block is the entry block. This will
  55. // be empty for declarations that don't have a visible definition.
  56. llvm::SmallVector<InstBlockId> body_block_ids = {};
  57. };
  58. // A class.
  59. struct Class : public Printable<Class> {
  60. enum InheritanceKind : int8_t {
  61. // `abstract class`
  62. Abstract,
  63. // `base class`
  64. Base,
  65. // `class`
  66. Final,
  67. };
  68. auto Print(llvm::raw_ostream& out) const -> void {
  69. out << "{name: " << name_id;
  70. out << "}";
  71. }
  72. // Determines whether this class has been fully defined. This is false until
  73. // we reach the `}` of the class definition.
  74. auto is_defined() const -> bool { return object_repr_id.is_valid(); }
  75. // The following members always have values, and do not change throughout the
  76. // lifetime of the class.
  77. // The class name.
  78. NameId name_id;
  79. // The class type, which is the type of `Self` in the class definition.
  80. TypeId self_type_id;
  81. // The first declaration of the class. This is a ClassDecl.
  82. InstId decl_id = InstId::Invalid;
  83. // The kind of inheritance that this class supports.
  84. // TODO: The rules here are not yet decided. See #3384.
  85. InheritanceKind inheritance_kind;
  86. // The following members are set at the `{` of the class definition.
  87. // The definition of the class. This is a ClassDecl.
  88. InstId definition_id = InstId::Invalid;
  89. // The class scope.
  90. NameScopeId scope_id = NameScopeId::Invalid;
  91. // The first block of the class body.
  92. // TODO: Handle control flow in the class body, such as if-expressions.
  93. InstBlockId body_block_id = InstBlockId::Invalid;
  94. // The following members are accumulated throughout the class definition.
  95. // The base class declaration. Invalid if the class has no base class. This is
  96. // a BaseDecl instruction.
  97. InstId base_id = InstId::Invalid;
  98. // The following members are set at the `}` of the class definition.
  99. // The object representation type to use for this class. This is valid once
  100. // the class is defined.
  101. TypeId object_repr_id = TypeId::Invalid;
  102. };
  103. // An interface.
  104. struct Interface : public Printable<Interface> {
  105. auto Print(llvm::raw_ostream& out) const -> void {
  106. out << "{name: " << name_id;
  107. out << "}";
  108. }
  109. // Determines whether this interface has been fully defined. This is false
  110. // until we reach the `}` of the interface definition.
  111. auto is_defined() const -> bool { return defined; }
  112. // The following members always have values, and do not change throughout the
  113. // lifetime of the interface.
  114. // The interface name.
  115. NameId name_id;
  116. // TODO: TypeId self_type_id;
  117. // The first declaration of the interface. This is a InterfaceDecl.
  118. InstId decl_id = InstId::Invalid;
  119. // The following members are set at the `{` of the interface definition.
  120. // The definition of the interface. This is a InterfaceDecl.
  121. InstId definition_id = InstId::Invalid;
  122. // The interface scope.
  123. NameScopeId scope_id = NameScopeId::Invalid;
  124. // The first block of the interface body.
  125. // TODO: Handle control flow in the interface body, such as if-expressions.
  126. InstBlockId body_block_id = InstBlockId::Invalid;
  127. // The following members are set at the `}` of the class definition.
  128. bool defined = true;
  129. };
  130. // Provides semantic analysis on a Parse::Tree.
  131. class File : public Printable<File> {
  132. public:
  133. // Produces a file for the builtins.
  134. explicit File(SharedValueStores& value_stores);
  135. // Starts a new file for Check::CheckParseTree. Builtins are required.
  136. explicit File(SharedValueStores& value_stores, std::string filename,
  137. const File* builtins);
  138. File(const File&) = delete;
  139. File& operator=(const File&) = delete;
  140. // Verifies that invariants of the semantics IR hold.
  141. auto Verify() const -> ErrorOr<Success>;
  142. // Prints the full IR. Allow omitting builtins so that unrelated changes are
  143. // less likely to alter test golden files.
  144. // TODO: In the future, the things to print may change, for example by adding
  145. // preludes. We may then want the ability to omit other things similar to
  146. // builtins.
  147. auto Print(llvm::raw_ostream& out, bool include_builtins = false) const
  148. -> void {
  149. Yaml::Print(out, OutputYaml(include_builtins));
  150. }
  151. auto OutputYaml(bool include_builtins) const -> Yaml::OutputMapping;
  152. // Returns array bound value from the bound instruction.
  153. auto GetArrayBoundValue(InstId bound_id) const -> uint64_t {
  154. return ints()
  155. .Get(insts().GetAs<IntLiteral>(bound_id).int_id)
  156. .getZExtValue();
  157. }
  158. // Marks a type as complete, and sets its value representation.
  159. auto CompleteType(TypeId object_type_id, ValueRepr value_repr) -> void {
  160. if (object_type_id.index < 0) {
  161. // We already know our builtin types are complete.
  162. return;
  163. }
  164. CARBON_CHECK(types().Get(object_type_id).value_repr.kind ==
  165. ValueRepr::Unknown)
  166. << "Type " << object_type_id << " completed more than once";
  167. types().Get(object_type_id).value_repr = value_repr;
  168. complete_types_.push_back(object_type_id);
  169. }
  170. // Gets the pointee type of the given type, which must be a pointer type.
  171. auto GetPointeeType(TypeId pointer_id) const -> TypeId {
  172. return types().GetAs<PointerType>(pointer_id).pointee_id;
  173. }
  174. // Produces a string version of a type.
  175. auto StringifyType(TypeId type_id) const -> std::string;
  176. // Same as `StringifyType`, but starting with an instruction representing a
  177. // type expression rather than a canonical type.
  178. auto StringifyTypeExpr(InstId outer_inst_id) const -> std::string;
  179. // Directly expose SharedValueStores members.
  180. auto identifiers() -> StringStoreWrapper<IdentifierId>& {
  181. return value_stores_->identifiers();
  182. }
  183. auto identifiers() const -> const StringStoreWrapper<IdentifierId>& {
  184. return value_stores_->identifiers();
  185. }
  186. auto ints() -> ValueStore<IntId>& { return value_stores_->ints(); }
  187. auto ints() const -> const ValueStore<IntId>& {
  188. return value_stores_->ints();
  189. }
  190. auto reals() -> ValueStore<RealId>& { return value_stores_->reals(); }
  191. auto reals() const -> const ValueStore<RealId>& {
  192. return value_stores_->reals();
  193. }
  194. auto string_literals() -> StringStoreWrapper<StringLiteralId>& {
  195. return value_stores_->string_literals();
  196. }
  197. auto string_literals() const -> const StringStoreWrapper<StringLiteralId>& {
  198. return value_stores_->string_literals();
  199. }
  200. auto functions() -> ValueStore<FunctionId>& { return functions_; }
  201. auto functions() const -> const ValueStore<FunctionId>& { return functions_; }
  202. auto classes() -> ValueStore<ClassId>& { return classes_; }
  203. auto classes() const -> const ValueStore<ClassId>& { return classes_; }
  204. auto interfaces() -> ValueStore<InterfaceId>& { return interfaces_; }
  205. auto interfaces() const -> const ValueStore<InterfaceId>& {
  206. return interfaces_;
  207. }
  208. auto cross_ref_irs() -> ValueStore<CrossRefIRId>& { return cross_ref_irs_; }
  209. auto cross_ref_irs() const -> const ValueStore<CrossRefIRId>& {
  210. return cross_ref_irs_;
  211. }
  212. auto names() const -> NameStoreWrapper {
  213. return NameStoreWrapper(&identifiers());
  214. }
  215. auto name_scopes() -> NameScopeStore& { return name_scopes_; }
  216. auto name_scopes() const -> const NameScopeStore& { return name_scopes_; }
  217. auto types() -> TypeStore& { return types_; }
  218. auto types() const -> const TypeStore& { return types_; }
  219. auto type_blocks() -> BlockValueStore<TypeBlockId>& { return type_blocks_; }
  220. auto type_blocks() const -> const BlockValueStore<TypeBlockId>& {
  221. return type_blocks_;
  222. }
  223. auto insts() -> InstStore& { return insts_; }
  224. auto insts() const -> const InstStore& { return insts_; }
  225. auto inst_blocks() -> InstBlockStore& { return inst_blocks_; }
  226. auto inst_blocks() const -> const InstBlockStore& { return inst_blocks_; }
  227. auto constants() -> ConstantStore& { return constants_; }
  228. auto constants() const -> const ConstantStore& { return constants_; }
  229. // A list of types that were completed in this file, in the order in which
  230. // they were completed. Earlier types in this list cannot contain instances of
  231. // later types.
  232. auto complete_types() const -> llvm::ArrayRef<TypeId> {
  233. return complete_types_;
  234. }
  235. auto top_inst_block_id() const -> InstBlockId { return top_inst_block_id_; }
  236. auto set_top_inst_block_id(InstBlockId block_id) -> void {
  237. top_inst_block_id_ = block_id;
  238. }
  239. // Returns true if there were errors creating the semantics IR.
  240. auto has_errors() const -> bool { return has_errors_; }
  241. auto set_has_errors(bool has_errors) -> void { has_errors_ = has_errors; }
  242. auto filename() const -> llvm::StringRef { return filename_; }
  243. private:
  244. bool has_errors_ = false;
  245. // Shared, compile-scoped values.
  246. SharedValueStores* value_stores_;
  247. // Slab allocator, used to allocate instruction and type blocks.
  248. llvm::BumpPtrAllocator allocator_;
  249. // The associated filename.
  250. // TODO: If SemIR starts linking back to tokens, reuse its filename.
  251. std::string filename_;
  252. // Storage for callable objects.
  253. ValueStore<FunctionId> functions_;
  254. // Storage for classes.
  255. ValueStore<ClassId> classes_;
  256. // Storage for interfaces.
  257. ValueStore<InterfaceId> interfaces_;
  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 instruction blocks).
  261. ValueStore<CrossRefIRId> cross_ref_irs_;
  262. // Storage for name scopes.
  263. NameScopeStore name_scopes_;
  264. // Type blocks within the IR. These reference entries in types_. Storage for
  265. // the data is provided by allocator_.
  266. BlockValueStore<TypeBlockId> type_blocks_;
  267. // All instructions. The first entries will always be cross-references to
  268. // builtins, at indices matching BuiltinKind ordering.
  269. InstStore insts_;
  270. // Instruction blocks within the IR. These reference entries in
  271. // insts_. Storage for the data is provided by allocator_.
  272. InstBlockStore inst_blocks_;
  273. // The top instruction block ID.
  274. InstBlockId top_inst_block_id_ = InstBlockId::Invalid;
  275. // Storage for instructions that represent computed global constants, such as
  276. // types.
  277. ConstantStore constants_;
  278. // Descriptions of types used in this file.
  279. TypeStore types_ = TypeStore(&insts_);
  280. // Types that were completed in this file.
  281. llvm::SmallVector<TypeId> complete_types_;
  282. };
  283. // The expression category of a sem_ir instruction. See /docs/design/values.md
  284. // for details.
  285. enum class ExprCategory : int8_t {
  286. // This instruction does not correspond to an expression, and as such has no
  287. // category.
  288. NotExpr,
  289. // The category of this instruction is not known due to an error.
  290. Error,
  291. // This instruction represents a value expression.
  292. Value,
  293. // This instruction represents a durable reference expression, that denotes an
  294. // object that outlives the current full expression context.
  295. DurableRef,
  296. // This instruction represents an ephemeral reference expression, that denotes
  297. // an
  298. // object that does not outlive the current full expression context.
  299. EphemeralRef,
  300. // This instruction represents an initializing expression, that describes how
  301. // to
  302. // initialize an object.
  303. Initializing,
  304. // This instruction represents a syntactic combination of expressions that are
  305. // permitted to have different expression categories. This is used for tuple
  306. // and struct literals, where the subexpressions for different elements can
  307. // have different categories.
  308. Mixed,
  309. Last = Mixed
  310. };
  311. // Returns the expression category for an instruction.
  312. auto GetExprCategory(const File& file, InstId inst_id) -> ExprCategory;
  313. // Returns information about the value representation to use for a type.
  314. inline auto GetValueRepr(const File& file, TypeId type_id) -> ValueRepr {
  315. return file.types().GetValueRepr(type_id);
  316. }
  317. // The initializing representation to use when returning by value.
  318. struct InitRepr {
  319. enum Kind : int8_t {
  320. // The type has no initializing representation. This is used for empty
  321. // types, where no initialization is necessary.
  322. None,
  323. // An initializing expression produces an object representation by value,
  324. // which is copied into the initialized object.
  325. ByCopy,
  326. // An initializing expression takes a location as input, which is
  327. // initialized as a side effect of evaluating the expression.
  328. InPlace,
  329. // TODO: Consider adding a kind where the expression takes an advisory
  330. // location and returns a value plus an indicator of whether the location
  331. // was actually initialized.
  332. };
  333. // The kind of initializing representation used by this type.
  334. Kind kind;
  335. // Returns whether a return slot is used when returning this type.
  336. auto has_return_slot() const -> bool { return kind == InPlace; }
  337. };
  338. // Returns information about the initializing representation to use for a type.
  339. auto GetInitRepr(const File& file, TypeId type_id) -> InitRepr;
  340. } // namespace Carbon::SemIR
  341. #endif // CARBON_TOOLCHAIN_SEM_IR_FILE_H_