file.h 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  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 "common/error.h"
  7. #include "llvm/ADT/SmallVector.h"
  8. #include "llvm/ADT/iterator_range.h"
  9. #include "llvm/Support/Allocator.h"
  10. #include "llvm/Support/FormatVariadic.h"
  11. #include "toolchain/base/value_store.h"
  12. #include "toolchain/base/yaml.h"
  13. #include "toolchain/sem_ir/class.h"
  14. #include "toolchain/sem_ir/constant.h"
  15. #include "toolchain/sem_ir/function.h"
  16. #include "toolchain/sem_ir/ids.h"
  17. #include "toolchain/sem_ir/impl.h"
  18. #include "toolchain/sem_ir/inst.h"
  19. #include "toolchain/sem_ir/interface.h"
  20. #include "toolchain/sem_ir/name.h"
  21. #include "toolchain/sem_ir/name_scope.h"
  22. #include "toolchain/sem_ir/type.h"
  23. #include "toolchain/sem_ir/type_info.h"
  24. namespace Carbon::SemIR {
  25. struct BindNameInfo : public Printable<BindNameInfo> {
  26. auto Print(llvm::raw_ostream& out) const -> void {
  27. out << "{name: " << name_id << ", enclosing_scope: " << enclosing_scope_id
  28. << "}";
  29. }
  30. // The name.
  31. NameId name_id;
  32. // The enclosing scope.
  33. NameScopeId enclosing_scope_id;
  34. };
  35. class File;
  36. struct ImportIR : public Printable<ImportIR> {
  37. auto Print(llvm::raw_ostream& out) const -> void { out << node_id; }
  38. // The node ID for the import.
  39. Parse::ImportDirectiveId node_id;
  40. // The imported IR.
  41. const File* sem_ir;
  42. };
  43. // Provides semantic analysis on a Parse::Tree.
  44. class File : public Printable<File> {
  45. public:
  46. // Produces a file for the builtins.
  47. explicit File(SharedValueStores& value_stores);
  48. // Starts a new file for Check::CheckParseTree. Builtins are required.
  49. explicit File(SharedValueStores& value_stores, std::string filename,
  50. const File* builtins);
  51. File(const File&) = delete;
  52. auto operator=(const File&) -> File& = delete;
  53. // Verifies that invariants of the semantics IR hold.
  54. auto Verify() const -> ErrorOr<Success>;
  55. // Prints the full IR. Allow omitting builtins so that unrelated changes are
  56. // less likely to alter test golden files.
  57. // TODO: In the future, the things to print may change, for example by adding
  58. // preludes. We may then want the ability to omit other things similar to
  59. // builtins.
  60. auto Print(llvm::raw_ostream& out, bool include_builtins = false) const
  61. -> void {
  62. Yaml::Print(out, OutputYaml(include_builtins));
  63. }
  64. auto OutputYaml(bool include_builtins) const -> Yaml::OutputMapping;
  65. // Returns array bound value from the bound instruction.
  66. auto GetArrayBoundValue(InstId bound_id) const -> uint64_t {
  67. return ints()
  68. .Get(insts().GetAs<IntLiteral>(bound_id).int_id)
  69. .getZExtValue();
  70. }
  71. // Marks a type as complete, and sets its value representation.
  72. auto CompleteType(TypeId object_type_id, ValueRepr value_repr) -> void {
  73. if (object_type_id.index < 0) {
  74. // We already know our builtin types are complete.
  75. return;
  76. }
  77. CARBON_CHECK(types().Get(object_type_id).value_repr.kind ==
  78. ValueRepr::Unknown)
  79. << "Type " << object_type_id << " completed more than once";
  80. types().Get(object_type_id).value_repr = value_repr;
  81. complete_types_.push_back(object_type_id);
  82. }
  83. // Gets the pointee type of the given type, which must be a pointer type.
  84. auto GetPointeeType(TypeId pointer_id) const -> TypeId {
  85. return types().GetAs<PointerType>(pointer_id).pointee_id;
  86. }
  87. // Produces a string version of a type.
  88. auto StringifyType(TypeId type_id) const -> std::string;
  89. // Same as `StringifyType`, but starting with an instruction representing a
  90. // type expression rather than a canonical type.
  91. auto StringifyTypeExpr(InstId outer_inst_id) const -> std::string;
  92. // Directly expose SharedValueStores members.
  93. auto identifiers() -> StringStoreWrapper<IdentifierId>& {
  94. return value_stores_->identifiers();
  95. }
  96. auto identifiers() const -> const StringStoreWrapper<IdentifierId>& {
  97. return value_stores_->identifiers();
  98. }
  99. auto ints() -> ValueStore<IntId>& { return value_stores_->ints(); }
  100. auto ints() const -> const ValueStore<IntId>& {
  101. return value_stores_->ints();
  102. }
  103. auto reals() -> ValueStore<RealId>& { return value_stores_->reals(); }
  104. auto reals() const -> const ValueStore<RealId>& {
  105. return value_stores_->reals();
  106. }
  107. auto string_literal_values() -> StringStoreWrapper<StringLiteralValueId>& {
  108. return value_stores_->string_literal_values();
  109. }
  110. auto string_literal_values() const
  111. -> const StringStoreWrapper<StringLiteralValueId>& {
  112. return value_stores_->string_literal_values();
  113. }
  114. auto bind_names() -> ValueStore<BindNameId>& { return bind_names_; }
  115. auto bind_names() const -> const ValueStore<BindNameId>& {
  116. return bind_names_;
  117. }
  118. auto functions() -> ValueStore<FunctionId>& { return functions_; }
  119. auto functions() const -> const ValueStore<FunctionId>& { return functions_; }
  120. auto classes() -> ValueStore<ClassId>& { return classes_; }
  121. auto classes() const -> const ValueStore<ClassId>& { return classes_; }
  122. auto interfaces() -> ValueStore<InterfaceId>& { return interfaces_; }
  123. auto interfaces() const -> const ValueStore<InterfaceId>& {
  124. return interfaces_;
  125. }
  126. auto impls() -> ImplStore& { return impls_; }
  127. auto impls() const -> const ImplStore& { return impls_; }
  128. auto import_irs() -> ValueStore<ImportIRId>& { return import_irs_; }
  129. auto import_irs() const -> const ValueStore<ImportIRId>& {
  130. return import_irs_;
  131. }
  132. auto names() const -> NameStoreWrapper {
  133. return NameStoreWrapper(&identifiers());
  134. }
  135. auto name_scopes() -> NameScopeStore& { return name_scopes_; }
  136. auto name_scopes() const -> const NameScopeStore& { return name_scopes_; }
  137. auto types() -> TypeStore& { return types_; }
  138. auto types() const -> const TypeStore& { return types_; }
  139. auto type_blocks() -> BlockValueStore<TypeBlockId>& { return type_blocks_; }
  140. auto type_blocks() const -> const BlockValueStore<TypeBlockId>& {
  141. return type_blocks_;
  142. }
  143. auto insts() -> InstStore& { return insts_; }
  144. auto insts() const -> const InstStore& { return insts_; }
  145. auto constant_values() -> ConstantValueStore& { return constant_values_; }
  146. auto constant_values() const -> const ConstantValueStore& {
  147. return constant_values_;
  148. }
  149. auto inst_blocks() -> InstBlockStore& { return inst_blocks_; }
  150. auto inst_blocks() const -> const InstBlockStore& { return inst_blocks_; }
  151. auto constants() -> ConstantStore& { return constants_; }
  152. auto constants() const -> const ConstantStore& { return constants_; }
  153. // A list of types that were completed in this file, in the order in which
  154. // they were completed. Earlier types in this list cannot contain instances of
  155. // later types.
  156. auto complete_types() const -> llvm::ArrayRef<TypeId> {
  157. return complete_types_;
  158. }
  159. auto top_inst_block_id() const -> InstBlockId { return top_inst_block_id_; }
  160. auto set_top_inst_block_id(InstBlockId block_id) -> void {
  161. top_inst_block_id_ = block_id;
  162. }
  163. // Returns true if there were errors creating the semantics IR.
  164. auto has_errors() const -> bool { return has_errors_; }
  165. auto set_has_errors(bool has_errors) -> void { has_errors_ = has_errors; }
  166. auto filename() const -> llvm::StringRef { return filename_; }
  167. private:
  168. // Common File initialization.
  169. explicit File(SharedValueStores& value_stores, std::string filename,
  170. const File* builtins, llvm::function_ref<void()> init_builtins);
  171. bool has_errors_ = false;
  172. // Shared, compile-scoped values.
  173. SharedValueStores* value_stores_;
  174. // Slab allocator, used to allocate instruction and type blocks.
  175. llvm::BumpPtrAllocator allocator_;
  176. // The associated filename.
  177. // TODO: If SemIR starts linking back to tokens, reuse its filename.
  178. std::string filename_;
  179. // Storage for bind names.
  180. ValueStore<BindNameId> bind_names_;
  181. // Storage for callable objects.
  182. ValueStore<FunctionId> functions_;
  183. // Storage for classes.
  184. ValueStore<ClassId> classes_;
  185. // Storage for interfaces.
  186. ValueStore<InterfaceId> interfaces_;
  187. // Storage for impls.
  188. ImplStore impls_;
  189. // Related IRs. There will always be at least one entry, the builtin IR (used
  190. // for references of builtins).
  191. ValueStore<ImportIRId> import_irs_;
  192. // Storage for name scopes.
  193. NameScopeStore name_scopes_;
  194. // Type blocks within the IR. These reference entries in types_. Storage for
  195. // the data is provided by allocator_.
  196. BlockValueStore<TypeBlockId> type_blocks_;
  197. // All instructions. The first entries will always be ImportRefs to builtins,
  198. // at indices matching BuiltinKind ordering.
  199. InstStore insts_;
  200. // Constant values for instructions.
  201. ConstantValueStore constant_values_;
  202. // Instruction blocks within the IR. These reference entries in
  203. // insts_. Storage for the data is provided by allocator_.
  204. InstBlockStore inst_blocks_;
  205. // The top instruction block ID.
  206. InstBlockId top_inst_block_id_ = InstBlockId::Invalid;
  207. // Storage for instructions that represent computed global constants, such as
  208. // types.
  209. ConstantStore constants_;
  210. // Descriptions of types used in this file.
  211. TypeStore types_ = TypeStore(&insts_);
  212. // Types that were completed in this file.
  213. llvm::SmallVector<TypeId> complete_types_;
  214. };
  215. // The expression category of a sem_ir instruction. See /docs/design/values.md
  216. // for details.
  217. enum class ExprCategory : int8_t {
  218. // This instruction does not correspond to an expression, and as such has no
  219. // category.
  220. NotExpr,
  221. // The category of this instruction is not known due to an error.
  222. Error,
  223. // This instruction represents a value expression.
  224. Value,
  225. // This instruction represents a durable reference expression, that denotes an
  226. // object that outlives the current full expression context.
  227. DurableRef,
  228. // This instruction represents an ephemeral reference expression, that denotes
  229. // an
  230. // object that does not outlive the current full expression context.
  231. EphemeralRef,
  232. // This instruction represents an initializing expression, that describes how
  233. // to
  234. // initialize an object.
  235. Initializing,
  236. // This instruction represents a syntactic combination of expressions that are
  237. // permitted to have different expression categories. This is used for tuple
  238. // and struct literals, where the subexpressions for different elements can
  239. // have different categories.
  240. Mixed,
  241. Last = Mixed
  242. };
  243. // Returns the expression category for an instruction.
  244. auto GetExprCategory(const File& file, InstId inst_id) -> ExprCategory;
  245. // Returns information about the value representation to use for a type.
  246. inline auto GetValueRepr(const File& file, TypeId type_id) -> ValueRepr {
  247. return file.types().GetValueRepr(type_id);
  248. }
  249. // The initializing representation to use when returning by value.
  250. struct InitRepr {
  251. enum Kind : int8_t {
  252. // The type has no initializing representation. This is used for empty
  253. // types, where no initialization is necessary.
  254. None,
  255. // An initializing expression produces an object representation by value,
  256. // which is copied into the initialized object.
  257. ByCopy,
  258. // An initializing expression takes a location as input, which is
  259. // initialized as a side effect of evaluating the expression.
  260. InPlace,
  261. // TODO: Consider adding a kind where the expression takes an advisory
  262. // location and returns a value plus an indicator of whether the location
  263. // was actually initialized.
  264. };
  265. // The kind of initializing representation used by this type.
  266. Kind kind;
  267. // Returns whether a return slot is used when returning this type.
  268. auto has_return_slot() const -> bool { return kind == InPlace; }
  269. };
  270. // Returns information about the initializing representation to use for a type.
  271. auto GetInitRepr(const File& file, TypeId type_id) -> InitRepr;
  272. } // namespace Carbon::SemIR
  273. #endif // CARBON_TOOLCHAIN_SEM_IR_FILE_H_