file.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  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. #include "toolchain/sem_ir/file.h"
  5. #include "common/check.h"
  6. #include "llvm/ADT/STLExtras.h"
  7. #include "llvm/ADT/SmallVector.h"
  8. #include "toolchain/base/kind_switch.h"
  9. #include "toolchain/base/shared_value_stores.h"
  10. #include "toolchain/base/yaml.h"
  11. #include "toolchain/parse/node_ids.h"
  12. #include "toolchain/sem_ir/builtin_inst_kind.h"
  13. #include "toolchain/sem_ir/ids.h"
  14. #include "toolchain/sem_ir/inst.h"
  15. #include "toolchain/sem_ir/inst_kind.h"
  16. #include "toolchain/sem_ir/typed_insts.h"
  17. namespace Carbon::SemIR {
  18. File::File(CheckIRId check_ir_id, IdentifierId package_id,
  19. LibraryNameId library_id, SharedValueStores& value_stores,
  20. std::string filename)
  21. : check_ir_id_(check_ir_id),
  22. package_id_(package_id),
  23. library_id_(library_id),
  24. value_stores_(&value_stores),
  25. filename_(std::move(filename)),
  26. impls_(*this),
  27. type_blocks_(allocator_),
  28. name_scopes_(&insts_),
  29. constant_values_(ConstantId::NotConstant),
  30. inst_blocks_(allocator_),
  31. constants_(this) {
  32. // `type` and the error type are both complete types.
  33. types_.SetValueRepr(TypeId::TypeType,
  34. {.kind = ValueRepr::Copy, .type_id = TypeId::TypeType});
  35. types_.SetValueRepr(TypeId::Error,
  36. {.kind = ValueRepr::Copy, .type_id = TypeId::Error});
  37. insts_.Reserve(BuiltinInstKind::ValidCount);
  38. // Error uses a self-referential type so that it's not accidentally treated as
  39. // a normal type. Every other builtin is a type, including the
  40. // self-referential TypeType.
  41. #define CARBON_SEM_IR_BUILTIN_INST_KIND(Name) \
  42. insts_.AddInNoBlock(LocIdAndInst::NoLoc<Name>( \
  43. {.type_id = BuiltinInstKind::Name == BuiltinInstKind::ErrorInst \
  44. ? TypeId::Error \
  45. : TypeId::TypeType}));
  46. #include "toolchain/sem_ir/inst_kind.def"
  47. CARBON_CHECK(insts_.size() == BuiltinInstKind::ValidCount,
  48. "Builtins should produce {0} insts, actual: {1}",
  49. BuiltinInstKind::ValidCount, insts_.size());
  50. for (auto i : llvm::seq(BuiltinInstKind::ValidCount)) {
  51. auto builtin_id = SemIR::InstId(i);
  52. constant_values_.Set(builtin_id,
  53. SemIR::ConstantId::ForTemplateConstant(builtin_id));
  54. }
  55. }
  56. auto File::Verify() const -> ErrorOr<Success> {
  57. // Invariants don't necessarily hold for invalid IR.
  58. if (has_errors_) {
  59. return Success();
  60. }
  61. // Check that every code block has a terminator sequence that appears at the
  62. // end of the block.
  63. for (const Function& function : functions_.array_ref()) {
  64. for (InstBlockId block_id : function.body_block_ids) {
  65. TerminatorKind prior_kind = TerminatorKind::NotTerminator;
  66. for (InstId inst_id : inst_blocks().Get(block_id)) {
  67. TerminatorKind inst_kind =
  68. insts().Get(inst_id).kind().terminator_kind();
  69. if (prior_kind == TerminatorKind::Terminator) {
  70. return Error(llvm::formatv("Inst {0} in block {1} follows terminator",
  71. inst_id, block_id));
  72. }
  73. if (prior_kind > inst_kind) {
  74. return Error(
  75. llvm::formatv("Non-terminator inst {0} in block {1} follows "
  76. "terminator sequence",
  77. inst_id, block_id));
  78. }
  79. prior_kind = inst_kind;
  80. }
  81. if (prior_kind != TerminatorKind::Terminator) {
  82. return Error(llvm::formatv("No terminator in block {0}", block_id));
  83. }
  84. }
  85. }
  86. // TODO: Check that an instruction only references other instructions that are
  87. // either global or that dominate it.
  88. return Success();
  89. }
  90. auto File::OutputYaml(bool include_builtins) const -> Yaml::OutputMapping {
  91. return Yaml::OutputMapping([this,
  92. include_builtins](Yaml::OutputMapping::Map map) {
  93. map.Add("filename", filename_);
  94. map.Add(
  95. "sem_ir", Yaml::OutputMapping([&](Yaml::OutputMapping::Map map) {
  96. map.Add("import_irs", import_irs_.OutputYaml());
  97. map.Add("import_ir_insts", import_ir_insts_.OutputYaml());
  98. map.Add("name_scopes", name_scopes_.OutputYaml());
  99. map.Add("entity_names", entity_names_.OutputYaml());
  100. map.Add("functions", functions_.OutputYaml());
  101. map.Add("classes", classes_.OutputYaml());
  102. map.Add("generics", generics_.OutputYaml());
  103. map.Add("specifics", specifics_.OutputYaml());
  104. map.Add("struct_type_fields", struct_type_fields_.OutputYaml());
  105. map.Add("types", types_.OutputYaml());
  106. map.Add("type_blocks", type_blocks_.OutputYaml());
  107. map.Add(
  108. "insts", Yaml::OutputMapping([&](Yaml::OutputMapping::Map map) {
  109. int start = include_builtins ? 0 : BuiltinInstKind::ValidCount;
  110. for (int i : llvm::seq(start, insts_.size())) {
  111. auto id = InstId(i);
  112. map.Add(PrintToString(id),
  113. Yaml::OutputScalar(insts_.Get(id)));
  114. }
  115. }));
  116. map.Add("constant_values",
  117. Yaml::OutputMapping([&](Yaml::OutputMapping::Map map) {
  118. int start =
  119. include_builtins ? 0 : BuiltinInstKind::ValidCount;
  120. for (int i : llvm::seq(start, insts_.size())) {
  121. auto id = InstId(i);
  122. auto value = constant_values_.Get(id);
  123. if (!value.is_valid() || value.is_constant()) {
  124. map.Add(PrintToString(id), Yaml::OutputScalar(value));
  125. }
  126. }
  127. }));
  128. map.Add(
  129. "symbolic_constants",
  130. Yaml::OutputMapping([&](Yaml::OutputMapping::Map map) {
  131. for (const auto& [i, symbolic] :
  132. llvm::enumerate(constant_values().symbolic_constants())) {
  133. map.Add(
  134. PrintToString(ConstantId::ForSymbolicConstantIndex(i)),
  135. Yaml::OutputScalar(symbolic));
  136. }
  137. }));
  138. map.Add("inst_blocks", inst_blocks_.OutputYaml());
  139. }));
  140. });
  141. }
  142. auto File::CollectMemUsage(MemUsage& mem_usage, llvm::StringRef label) const
  143. -> void {
  144. mem_usage.Collect(MemUsage::ConcatLabel(label, "allocator_"), allocator_);
  145. mem_usage.Collect(MemUsage::ConcatLabel(label, "entity_names_"),
  146. entity_names_);
  147. mem_usage.Collect(MemUsage::ConcatLabel(label, "functions_"), functions_);
  148. mem_usage.Collect(MemUsage::ConcatLabel(label, "classes_"), classes_);
  149. mem_usage.Collect(MemUsage::ConcatLabel(label, "interfaces_"), interfaces_);
  150. mem_usage.Collect(MemUsage::ConcatLabel(label, "impls_"), impls_);
  151. mem_usage.Collect(MemUsage::ConcatLabel(label, "generics_"), generics_);
  152. mem_usage.Collect(MemUsage::ConcatLabel(label, "specifics_"), specifics_);
  153. mem_usage.Collect(MemUsage::ConcatLabel(label, "import_irs_"), import_irs_);
  154. mem_usage.Collect(MemUsage::ConcatLabel(label, "import_ir_insts_"),
  155. import_ir_insts_);
  156. mem_usage.Collect(MemUsage::ConcatLabel(label, "struct_type_fields_"),
  157. struct_type_fields_);
  158. mem_usage.Collect(MemUsage::ConcatLabel(label, "type_blocks_"), type_blocks_);
  159. mem_usage.Collect(MemUsage::ConcatLabel(label, "insts_"), insts_);
  160. mem_usage.Collect(MemUsage::ConcatLabel(label, "name_scopes_"), name_scopes_);
  161. mem_usage.Collect(MemUsage::ConcatLabel(label, "constant_values_"),
  162. constant_values_);
  163. mem_usage.Collect(MemUsage::ConcatLabel(label, "inst_blocks_"), inst_blocks_);
  164. mem_usage.Collect(MemUsage::ConcatLabel(label, "constants_"), constants_);
  165. mem_usage.Collect(MemUsage::ConcatLabel(label, "types_"), types_);
  166. }
  167. auto GetExprCategory(const File& file, InstId inst_id) -> ExprCategory {
  168. const File* ir = &file;
  169. // The overall expression category if the current instruction is a value
  170. // expression.
  171. ExprCategory value_category = ExprCategory::Value;
  172. while (true) {
  173. auto untyped_inst = ir->insts().Get(inst_id);
  174. CARBON_KIND_SWITCH(untyped_inst) {
  175. case AdaptDecl::Kind:
  176. case AddrPattern::Kind:
  177. case Assign::Kind:
  178. case BaseDecl::Kind:
  179. case BindingPattern::Kind:
  180. case Branch::Kind:
  181. case BranchIf::Kind:
  182. case BranchWithArg::Kind:
  183. case FieldDecl::Kind:
  184. case FunctionDecl::Kind:
  185. case ImplDecl::Kind:
  186. case Namespace::Kind:
  187. case OutParamPattern::Kind:
  188. case RequirementEquivalent::Kind:
  189. case RequirementImpls::Kind:
  190. case RequirementRewrite::Kind:
  191. case Return::Kind:
  192. case ReturnSlotPattern::Kind:
  193. case ReturnExpr::Kind:
  194. return ExprCategory::NotExpr;
  195. case ImportRefUnloaded::Kind:
  196. case ImportRefLoaded::Kind: {
  197. auto import_ir_inst = ir->import_ir_insts().Get(
  198. untyped_inst.As<SemIR::AnyImportRef>().import_ir_inst_id);
  199. ir = ir->import_irs().Get(import_ir_inst.ir_id).sem_ir;
  200. inst_id = import_ir_inst.inst_id;
  201. continue;
  202. }
  203. case CARBON_KIND(AsCompatible inst): {
  204. inst_id = inst.source_id;
  205. continue;
  206. }
  207. case CARBON_KIND(BindAlias inst): {
  208. inst_id = inst.value_id;
  209. continue;
  210. }
  211. case CARBON_KIND(ExportDecl inst): {
  212. inst_id = inst.value_id;
  213. continue;
  214. }
  215. case CARBON_KIND(NameRef inst): {
  216. inst_id = inst.value_id;
  217. continue;
  218. }
  219. case CARBON_KIND(Converted inst): {
  220. inst_id = inst.result_id;
  221. continue;
  222. }
  223. case CARBON_KIND(SpecificConstant inst): {
  224. inst_id = inst.inst_id;
  225. continue;
  226. }
  227. case AddrOf::Kind:
  228. case ArrayType::Kind:
  229. case AssociatedConstantDecl::Kind:
  230. case AssociatedEntity::Kind:
  231. case AssociatedEntityType::Kind:
  232. case AutoType::Kind:
  233. case BindSymbolicName::Kind:
  234. case BindValue::Kind:
  235. case BlockArg::Kind:
  236. case BoolLiteral::Kind:
  237. case BoolType::Kind:
  238. case BoundMethod::Kind:
  239. case BoundMethodType::Kind:
  240. case ClassDecl::Kind:
  241. case ClassType::Kind:
  242. case CompleteTypeWitness::Kind:
  243. case ConstType::Kind:
  244. case FacetAccessType::Kind:
  245. case FacetType::Kind:
  246. case FacetValue::Kind:
  247. case FloatLiteral::Kind:
  248. case FloatType::Kind:
  249. case FunctionType::Kind:
  250. case GenericClassType::Kind:
  251. case GenericInterfaceType::Kind:
  252. case ImportDecl::Kind:
  253. case IntLiteralType::Kind:
  254. case IntType::Kind:
  255. case IntValue::Kind:
  256. case InterfaceDecl::Kind:
  257. case InterfaceWitness::Kind:
  258. case InterfaceWitnessAccess::Kind:
  259. case LegacyFloatType::Kind:
  260. case NamespaceType::Kind:
  261. case PointerType::Kind:
  262. case SpecificFunction::Kind:
  263. case SpecificFunctionType::Kind:
  264. case StringLiteral::Kind:
  265. case StringType::Kind:
  266. case StructType::Kind:
  267. case StructValue::Kind:
  268. case SymbolicBindingPattern::Kind:
  269. case TupleType::Kind:
  270. case TupleValue::Kind:
  271. case TypeType::Kind:
  272. case UnaryOperatorNot::Kind:
  273. case UnboundElementType::Kind:
  274. case ValueOfInitializer::Kind:
  275. case ValueParam::Kind:
  276. case ValueParamPattern::Kind:
  277. case VtableType::Kind:
  278. case WhereExpr::Kind:
  279. case WitnessType::Kind:
  280. return value_category;
  281. case ErrorInst::Kind:
  282. return ExprCategory::Error;
  283. case CARBON_KIND(BindName inst): {
  284. // TODO: Don't rely on value_id for expression category, since it may
  285. // not be valid yet. This workaround only works because we don't support
  286. // `var` in function signatures yet.
  287. if (!inst.value_id.is_valid()) {
  288. return value_category;
  289. }
  290. inst_id = inst.value_id;
  291. continue;
  292. }
  293. case CARBON_KIND(ArrayIndex inst): {
  294. inst_id = inst.array_id;
  295. continue;
  296. }
  297. case CARBON_KIND(ClassElementAccess inst): {
  298. inst_id = inst.base_id;
  299. // A value of class type is a pointer to an object representation.
  300. // Therefore, if the base is a value, the result is an ephemeral
  301. // reference.
  302. value_category = ExprCategory::EphemeralRef;
  303. continue;
  304. }
  305. case CARBON_KIND(StructAccess inst): {
  306. inst_id = inst.struct_id;
  307. continue;
  308. }
  309. case CARBON_KIND(TupleAccess inst): {
  310. inst_id = inst.tuple_id;
  311. continue;
  312. }
  313. case CARBON_KIND(SpliceBlock inst): {
  314. inst_id = inst.result_id;
  315. continue;
  316. }
  317. case StructLiteral::Kind:
  318. case TupleLiteral::Kind:
  319. return ExprCategory::Mixed;
  320. case ArrayInit::Kind:
  321. case Call::Kind:
  322. case InitializeFrom::Kind:
  323. case ClassInit::Kind:
  324. case StructInit::Kind:
  325. case TupleInit::Kind:
  326. return ExprCategory::Initializing;
  327. case Deref::Kind:
  328. case VarStorage::Kind:
  329. case ReturnSlot::Kind:
  330. return ExprCategory::DurableRef;
  331. case Temporary::Kind:
  332. case TemporaryStorage::Kind:
  333. case ValueAsRef::Kind:
  334. return ExprCategory::EphemeralRef;
  335. case OutParam::Kind:
  336. // TODO: Consider introducing a separate category for OutParam:
  337. // unlike other DurableRefs, it permits initialization.
  338. return ExprCategory::DurableRef;
  339. }
  340. }
  341. }
  342. } // namespace Carbon::SemIR