file.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  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 "clang/Frontend/ASTUnit.h"
  7. #include "common/error.h"
  8. #include "llvm/ADT/SmallVector.h"
  9. #include "llvm/ADT/iterator_range.h"
  10. #include "llvm/Support/Allocator.h"
  11. #include "llvm/Support/FormatVariadic.h"
  12. #include "toolchain/base/canonical_value_store.h"
  13. #include "toolchain/base/int.h"
  14. #include "toolchain/base/relational_value_store.h"
  15. #include "toolchain/base/shared_value_stores.h"
  16. #include "toolchain/base/value_store.h"
  17. #include "toolchain/base/yaml.h"
  18. #include "toolchain/parse/tree.h"
  19. #include "toolchain/sem_ir/associated_constant.h"
  20. #include "toolchain/sem_ir/class.h"
  21. #include "toolchain/sem_ir/constant.h"
  22. #include "toolchain/sem_ir/cpp_overload_set.h"
  23. #include "toolchain/sem_ir/entity_name.h"
  24. #include "toolchain/sem_ir/facet_type_info.h"
  25. #include "toolchain/sem_ir/function.h"
  26. #include "toolchain/sem_ir/generic.h"
  27. #include "toolchain/sem_ir/ids.h"
  28. #include "toolchain/sem_ir/impl.h"
  29. #include "toolchain/sem_ir/import_cpp.h"
  30. #include "toolchain/sem_ir/import_ir.h"
  31. #include "toolchain/sem_ir/inst.h"
  32. #include "toolchain/sem_ir/interface.h"
  33. #include "toolchain/sem_ir/name.h"
  34. #include "toolchain/sem_ir/name_scope.h"
  35. #include "toolchain/sem_ir/singleton_insts.h"
  36. #include "toolchain/sem_ir/specific_interface.h"
  37. #include "toolchain/sem_ir/struct_type_field.h"
  38. #include "toolchain/sem_ir/type.h"
  39. #include "toolchain/sem_ir/type_info.h"
  40. #include "toolchain/sem_ir/vtable.h"
  41. namespace Carbon::SemIR {
  42. // An expression that may contain control flow, represented as a
  43. // single-entry/single-exit region. `block_ids` are the blocks that are part of
  44. // evaluation of the expression, and `result_id` represents the result of
  45. // evaluating the expression. `block_ids` consists of all blocks that are
  46. // dominated by `block_ids.front()` and post-dominated by `block_ids.back()`,
  47. // and should be in lexical order. `result_id` will be in `block_ids.back()` or
  48. // some block that dominates it.
  49. //
  50. // `block_ids` cannot be empty. If it has a single element, then the region
  51. // should be used via a `SpliceBlock` inst. Otherwise, the region should be used
  52. // by branching to the entry block, and the last inst in the exit block will
  53. // likewise be a branch.
  54. struct ExprRegion {
  55. llvm::SmallVector<InstBlockId> block_ids;
  56. InstId result_id;
  57. };
  58. using ExprRegionStore = ValueStore<ExprRegionId, ExprRegion>;
  59. using CustomLayoutStore = BlockValueStore<CustomLayoutId, uint64_t>;
  60. // The semantic IR for a single file.
  61. class File : public Printable<File> {
  62. public:
  63. using IdentifiedFacetTypeStore =
  64. RelationalValueStore<FacetTypeId, IdentifiedFacetTypeId,
  65. IdentifiedFacetType>;
  66. // Starts a new file for Check::CheckParseTree.
  67. explicit File(const Parse::Tree* parse_tree, CheckIRId check_ir_id,
  68. const std::optional<Parse::Tree::PackagingDecl>& packaging_decl,
  69. SharedValueStores& value_stores, std::string filename);
  70. File(const File&) = delete;
  71. ~File();
  72. auto operator=(const File&) -> File& = delete;
  73. // Verifies that invariants of the semantics IR hold.
  74. auto Verify() const -> ErrorOr<Success>;
  75. // Prints the full IR. Allow omitting singletons so that changes to the list
  76. // of singletons won't churn golden test file content.
  77. auto Print(llvm::raw_ostream& out, bool include_singletons = false) const
  78. -> void {
  79. Yaml::Print(out, OutputYaml(include_singletons));
  80. }
  81. auto OutputYaml(bool include_singletons) const -> Yaml::OutputMapping;
  82. // Collects memory usage of members.
  83. auto CollectMemUsage(MemUsage& mem_usage, llvm::StringRef label) const
  84. -> void;
  85. // Returns array bound value from the bound instruction.
  86. // TODO: Move this function elsewhere.
  87. auto GetArrayBoundValue(InstId bound_id) const -> std::optional<uint64_t> {
  88. if (auto bound = insts().TryGetAs<IntValue>(
  89. constant_values().GetConstantInstId(bound_id))) {
  90. return ints().Get(bound->int_id).getZExtValue();
  91. }
  92. return std::nullopt;
  93. }
  94. // Gets the pointee type of the given type, which must be a pointer type.
  95. // TODO: Move this function elsewhere.
  96. auto GetPointeeType(TypeId pointer_id) const -> TypeId {
  97. return types().GetTypeIdForTypeInstId(
  98. types().GetAs<PointerType>(pointer_id).pointee_id);
  99. }
  100. // Returns true if this file is an `impl`.
  101. auto is_impl() -> bool {
  102. return import_irs().Get(ImportIRId::ApiForImpl).sem_ir != nullptr;
  103. }
  104. auto check_ir_id() const -> CheckIRId { return check_ir_id_; }
  105. auto package_id() const -> PackageNameId { return package_id_; }
  106. auto library_id() const -> LibraryNameId { return library_id_; }
  107. // Directly expose SharedValueStores members.
  108. auto identifiers() -> SharedValueStores::IdentifierStore& {
  109. return value_stores_->identifiers();
  110. }
  111. auto identifiers() const -> const SharedValueStores::IdentifierStore& {
  112. return value_stores_->identifiers();
  113. }
  114. auto ints() -> SharedValueStores::IntStore& { return value_stores_->ints(); }
  115. auto ints() const -> const SharedValueStores::IntStore& {
  116. return value_stores_->ints();
  117. }
  118. auto reals() -> SharedValueStores::RealStore& {
  119. return value_stores_->reals();
  120. }
  121. auto reals() const -> const SharedValueStores::RealStore& {
  122. return value_stores_->reals();
  123. }
  124. auto floats() -> SharedValueStores::FloatStore& {
  125. return value_stores_->floats();
  126. }
  127. auto floats() const -> const SharedValueStores::FloatStore& {
  128. return value_stores_->floats();
  129. }
  130. auto string_literal_values() -> SharedValueStores::StringLiteralStore& {
  131. return value_stores_->string_literal_values();
  132. }
  133. auto string_literal_values() const
  134. -> const SharedValueStores::StringLiteralStore& {
  135. return value_stores_->string_literal_values();
  136. }
  137. auto entity_names() -> EntityNameStore& { return entity_names_; }
  138. auto entity_names() const -> const EntityNameStore& { return entity_names_; }
  139. auto functions() -> FunctionStore& { return functions_; }
  140. auto functions() const -> const FunctionStore& { return functions_; }
  141. auto cpp_overload_sets() -> CppOverloadSetStore& {
  142. return cpp_overload_sets_;
  143. }
  144. auto cpp_overload_sets() const -> const CppOverloadSetStore& {
  145. return cpp_overload_sets_;
  146. }
  147. auto classes() -> ClassStore& { return classes_; }
  148. auto classes() const -> const ClassStore& { return classes_; }
  149. auto interfaces() -> InterfaceStore& { return interfaces_; }
  150. auto interfaces() const -> const InterfaceStore& { return interfaces_; }
  151. auto associated_constants() -> AssociatedConstantStore& {
  152. return associated_constants_;
  153. }
  154. auto associated_constants() const -> const AssociatedConstantStore& {
  155. return associated_constants_;
  156. }
  157. // TODO: Rename these to `facet_type_infos`.
  158. auto facet_types() -> FacetTypeInfoStore& { return facet_types_; }
  159. auto facet_types() const -> const FacetTypeInfoStore& { return facet_types_; }
  160. auto identified_facet_types() -> IdentifiedFacetTypeStore& {
  161. return identified_facet_types_;
  162. }
  163. auto identified_facet_types() const -> const IdentifiedFacetTypeStore& {
  164. return identified_facet_types_;
  165. }
  166. auto impls() -> ImplStore& { return impls_; }
  167. auto impls() const -> const ImplStore& { return impls_; }
  168. auto specific_interfaces() -> SpecificInterfaceStore& {
  169. return specific_interfaces_;
  170. }
  171. auto specific_interfaces() const -> const SpecificInterfaceStore& {
  172. return specific_interfaces_;
  173. }
  174. auto generics() -> GenericStore& { return generics_; }
  175. auto generics() const -> const GenericStore& { return generics_; }
  176. auto specifics() -> SpecificStore& { return specifics_; }
  177. auto specifics() const -> const SpecificStore& { return specifics_; }
  178. auto import_irs() -> ImportIRStore& { return import_irs_; }
  179. auto import_irs() const -> const ImportIRStore& { return import_irs_; }
  180. auto import_ir_insts() -> ImportIRInstStore& { return import_ir_insts_; }
  181. auto import_ir_insts() const -> const ImportIRInstStore& {
  182. return import_ir_insts_;
  183. }
  184. auto import_cpps() -> ImportCppStore& { return import_cpps_; }
  185. auto import_cpps() const -> const ImportCppStore& { return import_cpps_; }
  186. auto clang_ast_unit() -> clang::ASTUnit* { return clang_ast_unit_; }
  187. auto clang_ast_unit() const -> const clang::ASTUnit* {
  188. return clang_ast_unit_;
  189. }
  190. // TODO: When the AST can be created before creating `File`, initialize the
  191. // pointer in the constructor and remove this function. This is part of
  192. // https://github.com/carbon-language/carbon-lang/issues/4666
  193. auto set_clang_ast_unit(clang::ASTUnit* clang_ast_unit) -> void;
  194. auto clang_mangle_context() -> clang::MangleContext* {
  195. return clang_mangle_context_.get();
  196. }
  197. auto clang_decls() -> ClangDeclStore& { return clang_decls_; }
  198. auto clang_decls() const -> const ClangDeclStore& { return clang_decls_; }
  199. auto names() const -> NameStoreWrapper {
  200. return NameStoreWrapper(&identifiers());
  201. }
  202. auto name_scopes() -> NameScopeStore& { return name_scopes_; }
  203. auto name_scopes() const -> const NameScopeStore& { return name_scopes_; }
  204. auto struct_type_fields() -> StructTypeFieldsStore& {
  205. return struct_type_fields_;
  206. }
  207. auto struct_type_fields() const -> const StructTypeFieldsStore& {
  208. return struct_type_fields_;
  209. }
  210. auto custom_layouts() -> CustomLayoutStore& { return custom_layouts_; }
  211. auto custom_layouts() const -> const CustomLayoutStore& {
  212. return custom_layouts_;
  213. }
  214. auto types() -> TypeStore& { return types_; }
  215. auto types() const -> const TypeStore& { return types_; }
  216. auto insts() -> InstStore& { return insts_; }
  217. auto insts() const -> const InstStore& { return insts_; }
  218. auto vtables() -> VtableStore& { return vtables_; }
  219. auto vtables() const -> const VtableStore& { return vtables_; }
  220. auto constant_values() -> ConstantValueStore& { return constant_values_; }
  221. auto constant_values() const -> const ConstantValueStore& {
  222. return constant_values_;
  223. }
  224. auto inst_blocks() -> InstBlockStore& { return inst_blocks_; }
  225. auto inst_blocks() const -> const InstBlockStore& { return inst_blocks_; }
  226. auto constants() -> ConstantStore& { return constants_; }
  227. auto constants() const -> const ConstantStore& { return constants_; }
  228. auto expr_regions() -> ExprRegionStore& { return expr_regions_; }
  229. auto expr_regions() const -> const ExprRegionStore& { return expr_regions_; }
  230. using ClangSourceLocStore =
  231. ValueStore<ClangSourceLocId, clang::SourceLocation>;
  232. auto clang_source_locs() -> ClangSourceLocStore& {
  233. return clang_source_locs_;
  234. }
  235. auto clang_source_locs() const -> const ClangSourceLocStore& {
  236. return clang_source_locs_;
  237. }
  238. auto top_inst_block_id() const -> InstBlockId { return top_inst_block_id_; }
  239. auto set_top_inst_block_id(InstBlockId block_id) -> void {
  240. top_inst_block_id_ = block_id;
  241. }
  242. auto global_ctor_id() const -> FunctionId { return global_ctor_id_; }
  243. auto set_global_ctor_id(FunctionId function_id) -> void {
  244. global_ctor_id_ = function_id;
  245. }
  246. // Returns true if there were errors creating the semantics IR.
  247. auto has_errors() const -> bool { return has_errors_; }
  248. auto set_has_errors(bool has_errors) -> void { has_errors_ = has_errors; }
  249. auto filename() const -> llvm::StringRef { return filename_; }
  250. auto parse_tree() const -> const Parse::Tree& { return *parse_tree_; }
  251. private:
  252. const Parse::Tree* parse_tree_;
  253. // True if parts of the IR may be invalid.
  254. bool has_errors_ = false;
  255. // The file's ID.
  256. CheckIRId check_ir_id_;
  257. // The file's package.
  258. PackageNameId package_id_ = PackageNameId::None;
  259. // The file's library.
  260. LibraryNameId library_id_ = LibraryNameId::None;
  261. // Shared, compile-scoped values.
  262. SharedValueStores* value_stores_;
  263. // Slab allocator, used to allocate instruction and type blocks.
  264. llvm::BumpPtrAllocator allocator_;
  265. // The associated filename.
  266. // TODO: If SemIR starts linking back to tokens, reuse its filename.
  267. std::string filename_;
  268. // Storage for EntityNames.
  269. EntityNameStore entity_names_;
  270. // Storage for callable objects.
  271. FunctionStore functions_;
  272. // Storage for CppOverloadSet.
  273. CppOverloadSetStore cpp_overload_sets_;
  274. // Storage for classes.
  275. ClassStore classes_;
  276. // Storage for interfaces.
  277. InterfaceStore interfaces_;
  278. // Storage for associated constants.
  279. AssociatedConstantStore associated_constants_;
  280. // Storage for facet types.
  281. FacetTypeInfoStore facet_types_;
  282. // Storage for identified facet types.
  283. IdentifiedFacetTypeStore identified_facet_types_;
  284. // Storage for impls.
  285. ImplStore impls_;
  286. // Storage for specific interfaces, which are an individual unit of impl
  287. // lookup for a single interface.
  288. SpecificInterfaceStore specific_interfaces_;
  289. // Storage for generics.
  290. GenericStore generics_;
  291. // Storage for specifics.
  292. SpecificStore specifics_;
  293. // Related IRs. There are some fixed entries at the start; see ImportIRId.
  294. ImportIRStore import_irs_;
  295. // Related IR instructions. These are created for LocIds for instructions
  296. // that are import-related.
  297. ImportIRInstStore import_ir_insts_;
  298. // List of Cpp imports.
  299. ImportCppStore import_cpps_;
  300. // The Clang AST to use when looking up `Cpp` names. Null if there are no
  301. // `Cpp` imports.
  302. clang::ASTUnit* clang_ast_unit_ = nullptr;
  303. // The Clang mangle context for the target in the ASTContext. Initialized
  304. // together with `clang_ast_unit_`.
  305. std::unique_ptr<clang::MangleContext> clang_mangle_context_;
  306. // Clang AST declarations pointing to the AST and their mapped Carbon
  307. // instructions. When calling `Lookup()`, `inst_id` is ignored. `Add()` will
  308. // not add multiple entries with the same `decl` and different `inst_id`.
  309. ClangDeclStore clang_decls_;
  310. // All instructions. The first entries will always be the singleton
  311. // instructions.
  312. InstStore insts_;
  313. VtableStore vtables_;
  314. // Storage for name scopes.
  315. NameScopeStore name_scopes_ = NameScopeStore(this);
  316. // Constant values for instructions.
  317. ConstantValueStore constant_values_;
  318. // Instruction blocks within the IR. These reference entries in
  319. // insts_. Storage for the data is provided by allocator_.
  320. InstBlockStore inst_blocks_;
  321. // The top instruction block ID.
  322. InstBlockId top_inst_block_id_ = InstBlockId::None;
  323. // The global constructor function id.
  324. FunctionId global_ctor_id_ = FunctionId::None;
  325. // Storage for instructions that represent computed global constants, such as
  326. // types.
  327. ConstantStore constants_;
  328. // Storage for StructTypeField lists.
  329. StructTypeFieldsStore struct_type_fields_ = StructTypeFieldsStore(allocator_);
  330. // Storage for custom layouts.
  331. CustomLayoutStore custom_layouts_ = CustomLayoutStore(allocator_);
  332. // Descriptions of types used in this file.
  333. TypeStore types_ = TypeStore(this);
  334. // Single-entry/single-exit regions that are referenced as units, e.g. because
  335. // they represent expressions.
  336. ExprRegionStore expr_regions_;
  337. // C++ source locations for C++ interop.
  338. ClangSourceLocStore clang_source_locs_;
  339. };
  340. } // namespace Carbon::SemIR
  341. #endif // CARBON_TOOLCHAIN_SEM_IR_FILE_H_