type_completion.cpp 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007
  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/check/type_completion.h"
  5. #include "common/concepts.h"
  6. #include "llvm/ADT/SmallVector.h"
  7. #include "toolchain/base/kind_switch.h"
  8. #include "toolchain/check/cpp/import.h"
  9. #include "toolchain/check/facet_type.h"
  10. #include "toolchain/check/generic.h"
  11. #include "toolchain/check/inst.h"
  12. #include "toolchain/check/literal.h"
  13. #include "toolchain/check/require_impls.h"
  14. #include "toolchain/check/type.h"
  15. #include "toolchain/diagnostics/format_providers.h"
  16. #include "toolchain/sem_ir/constant.h"
  17. #include "toolchain/sem_ir/facet_type_info.h"
  18. #include "toolchain/sem_ir/generic.h"
  19. #include "toolchain/sem_ir/ids.h"
  20. #include "toolchain/sem_ir/specific_interface.h"
  21. #include "toolchain/sem_ir/specific_named_constraint.h"
  22. #include "toolchain/sem_ir/type_info.h"
  23. #include "toolchain/sem_ir/typed_insts.h"
  24. namespace Carbon::Check {
  25. auto NoteIncompleteClass(Context& context, SemIR::ClassId class_id,
  26. DiagnosticBuilder& builder) -> void {
  27. const auto& class_info = context.classes().Get(class_id);
  28. CARBON_CHECK(!class_info.is_complete(), "Class is not incomplete");
  29. if (class_info.has_definition_started()) {
  30. CARBON_DIAGNOSTIC(ClassIncompleteWithinDefinition, Note,
  31. "class is incomplete within its definition");
  32. builder.Note(class_info.definition_id, ClassIncompleteWithinDefinition);
  33. } else {
  34. CARBON_DIAGNOSTIC(ClassForwardDeclaredHere, Note,
  35. "class was forward declared here");
  36. builder.Note(class_info.latest_decl_id(), ClassForwardDeclaredHere);
  37. }
  38. }
  39. auto NoteIncompleteInterface(Context& context, SemIR::InterfaceId interface_id,
  40. DiagnosticBuilder& builder) -> void {
  41. const auto& interface_info = context.interfaces().Get(interface_id);
  42. CARBON_CHECK(!interface_info.is_complete(), "Interface is not incomplete");
  43. if (interface_info.is_being_defined()) {
  44. CARBON_DIAGNOSTIC(InterfaceIncompleteWithinDefinition, Note,
  45. "interface is currently being defined");
  46. builder.Note(interface_info.definition_id,
  47. InterfaceIncompleteWithinDefinition);
  48. } else {
  49. CARBON_DIAGNOSTIC(InterfaceForwardDeclaredHere, Note,
  50. "interface was forward declared here");
  51. builder.Note(interface_info.latest_decl_id(), InterfaceForwardDeclaredHere);
  52. }
  53. }
  54. auto NoteAbstractClass(Context& context, SemIR::ClassId class_id,
  55. bool direct_use, DiagnosticBuilder& builder) -> void {
  56. const auto& class_info = context.classes().Get(class_id);
  57. CARBON_CHECK(
  58. class_info.inheritance_kind == SemIR::Class::InheritanceKind::Abstract,
  59. "Class is not abstract");
  60. CARBON_DIAGNOSTIC(
  61. ClassAbstractHere, Note,
  62. "{0:=0:uses class that|=1:class} was declared abstract here",
  63. Diagnostics::IntAsSelect);
  64. builder.Note(class_info.definition_id, ClassAbstractHere,
  65. static_cast<int>(direct_use));
  66. }
  67. static auto NoteIncompleteNamedConstraint(
  68. Context& context, SemIR::NamedConstraintId named_constraint_id,
  69. DiagnosticBuilder& builder) -> void {
  70. const auto& constraint = context.named_constraints().Get(named_constraint_id);
  71. CARBON_CHECK(!constraint.is_complete(), "Named constraint is not incomplete");
  72. if (constraint.is_being_defined()) {
  73. CARBON_DIAGNOSTIC(NamedConstraintIncompleteWithinDefinition, Note,
  74. "constraint is currently being defined");
  75. builder.Note(constraint.definition_id,
  76. NamedConstraintIncompleteWithinDefinition);
  77. } else {
  78. CARBON_DIAGNOSTIC(NamedConstraintForwardDeclaredHere, Note,
  79. "constraint was forward declared here");
  80. builder.Note(constraint.latest_decl_id(),
  81. NamedConstraintForwardDeclaredHere);
  82. }
  83. }
  84. static auto RequireCompleteFacetType(Context& context, SemIR::LocId loc_id,
  85. const SemIR::FacetType& facet_type,
  86. MakeDiagnosticBuilderFn diagnoser)
  87. -> bool {
  88. const auto& facet_type_info =
  89. context.facet_types().Get(facet_type.facet_type_id);
  90. for (auto extends : facet_type_info.extend_constraints) {
  91. auto interface_id = extends.interface_id;
  92. const auto& interface = context.interfaces().Get(interface_id);
  93. if (!interface.is_complete()) {
  94. if (diagnoser) {
  95. auto builder = diagnoser();
  96. NoteIncompleteInterface(context, interface_id, builder);
  97. builder.Emit();
  98. }
  99. return false;
  100. }
  101. if (interface.generic_id.has_value()) {
  102. ResolveSpecificDefinition(context, loc_id, extends.specific_id);
  103. }
  104. }
  105. for (auto extends : facet_type_info.extend_named_constraints) {
  106. auto named_constraint_id = extends.named_constraint_id;
  107. const auto& constraint =
  108. context.named_constraints().Get(named_constraint_id);
  109. if (!constraint.is_complete()) {
  110. if (diagnoser) {
  111. auto builder = diagnoser();
  112. NoteIncompleteNamedConstraint(context, named_constraint_id, builder);
  113. builder.Emit();
  114. }
  115. return false;
  116. }
  117. if (constraint.generic_id.has_value()) {
  118. ResolveSpecificDefinition(context, loc_id, extends.specific_id);
  119. }
  120. }
  121. return true;
  122. }
  123. namespace {
  124. // Worklist-based type completion mechanism.
  125. //
  126. // When attempting to complete a type, we may find other types that also need to
  127. // be completed: types nested within that type, and the value representation of
  128. // the type. In order to complete a type without recursing arbitrarily deeply,
  129. // we use a worklist of tasks:
  130. //
  131. // - An `AddNestedIncompleteTypes` step adds a task for all incomplete types
  132. // nested within a type to the work list.
  133. // - A `BuildInfo` step computes the `CompleteTypeInfo` for a type, once all of
  134. // its nested types are complete, and marks the type as complete.
  135. class TypeCompleter {
  136. public:
  137. // `context` mut not be null.
  138. TypeCompleter(Context* context, SemIR::LocId loc_id,
  139. MakeDiagnosticBuilderFn diagnoser)
  140. : context_(context), loc_id_(loc_id), diagnoser_(diagnoser) {}
  141. // Attempts to complete the given type. Returns true if it is now complete,
  142. // false if it could not be completed.
  143. auto Complete(SemIR::TypeId type_id) -> bool;
  144. private:
  145. enum class Phase : int8_t {
  146. // The next step is to add nested types to the list of types to complete.
  147. AddNestedIncompleteTypes,
  148. // The next step is to build the `CompleteTypeInfo` for the type.
  149. BuildInfo,
  150. };
  151. struct WorkItem {
  152. SemIR::TypeId type_id;
  153. Phase phase;
  154. };
  155. // Adds `type_id` to the work list, if it's not already complete.
  156. auto Push(SemIR::TypeId type_id) -> void;
  157. // Runs the next step.
  158. auto ProcessStep() -> bool;
  159. // Adds any types nested within `type_inst` that need to be complete for
  160. // `type_inst` to be complete to our work list.
  161. auto AddNestedIncompleteTypes(SemIR::Inst type_inst) -> bool;
  162. // Makes an empty value representation, which is used for types that have no
  163. // state, such as empty structs and tuples.
  164. auto MakeEmptyValueRepr() const -> SemIR::ValueRepr;
  165. // Makes a dependent value representation, which is used for symbolic types.
  166. auto MakeDependentValueRepr(SemIR::TypeId type_id) const -> SemIR::ValueRepr;
  167. // Makes a value representation that uses pass-by-copy, copying the given
  168. // type.
  169. auto MakeCopyValueRepr(SemIR::TypeId rep_id,
  170. SemIR::ValueRepr::AggregateKind aggregate_kind =
  171. SemIR::ValueRepr::NotAggregate) const
  172. -> SemIR::ValueRepr;
  173. // Makes a value representation that uses pass-by-address with the given
  174. // pointee type.
  175. auto MakePointerValueRepr(SemIR::TypeId pointee_id,
  176. SemIR::ValueRepr::AggregateKind aggregate_kind =
  177. SemIR::ValueRepr::NotAggregate) const
  178. -> SemIR::ValueRepr;
  179. // Gets the value representation of a nested type, which should already be
  180. // complete.
  181. auto GetNestedInfo(SemIR::TypeId nested_type_id) const
  182. -> SemIR::CompleteTypeInfo;
  183. template <typename InstT>
  184. requires(InstT::Kind.template IsAnyOf<
  185. SemIR::AutoType, SemIR::BoolType, SemIR::BoundMethodType,
  186. SemIR::CharLiteralType, SemIR::ErrorInst, SemIR::FacetType,
  187. SemIR::FloatLiteralType, SemIR::FloatType, SemIR::FormType,
  188. SemIR::IntType, SemIR::IntLiteralType, SemIR::NamespaceType,
  189. SemIR::PatternType, SemIR::PointerType,
  190. SemIR::RequireSpecificDefinitionType, SemIR::SpecificFunctionType,
  191. SemIR::TypeType, SemIR::VtableType, SemIR::WitnessType>())
  192. auto BuildInfoForInst(SemIR::TypeId type_id, InstT /*inst*/) const
  193. -> SemIR::CompleteTypeInfo {
  194. return {.value_repr = MakeCopyValueRepr(type_id)};
  195. }
  196. auto BuildStructOrTupleValueRepr(size_t num_elements,
  197. SemIR::TypeId elementwise_rep,
  198. bool same_as_object_rep) const
  199. -> SemIR::ValueRepr;
  200. auto BuildInfoForInst(SemIR::TypeId type_id,
  201. SemIR::StructType struct_type) const
  202. -> SemIR::CompleteTypeInfo;
  203. auto BuildInfoForInst(SemIR::TypeId type_id,
  204. SemIR::TupleType tuple_type) const
  205. -> SemIR::CompleteTypeInfo;
  206. auto BuildInfoForInst(SemIR::TypeId type_id, SemIR::ArrayType /*inst*/) const
  207. -> SemIR::CompleteTypeInfo;
  208. auto BuildInfoForInst(SemIR::TypeId /*type_id*/, SemIR::ClassType inst) const
  209. -> SemIR::CompleteTypeInfo;
  210. template <typename InstT>
  211. requires(InstT::Kind.template IsAnyOf<
  212. SemIR::AssociatedEntityType, SemIR::CppOverloadSetType,
  213. SemIR::CppTemplateNameType, SemIR::FunctionType,
  214. SemIR::FunctionTypeWithSelfType, SemIR::GenericClassType,
  215. SemIR::GenericInterfaceType, SemIR::GenericNamedConstraintType,
  216. SemIR::InstType, SemIR::UnboundElementType, SemIR::WhereExpr>())
  217. auto BuildInfoForInst(SemIR::TypeId /*type_id*/, InstT /*inst*/) const
  218. -> SemIR::CompleteTypeInfo {
  219. // These types have no runtime operations, so we use an empty value
  220. // representation.
  221. //
  222. // TODO: There is information we could model here:
  223. // - For an interface, we could use a witness.
  224. // - For an associated entity, we could use an index into the witness.
  225. // - For an unbound element, we could use an index or offset.
  226. return {.value_repr = MakeEmptyValueRepr()};
  227. }
  228. auto BuildInfoForInst(SemIR::TypeId /*type_id*/, SemIR::ConstType inst) const
  229. -> SemIR::CompleteTypeInfo;
  230. auto BuildInfoForInst(SemIR::TypeId type_id,
  231. SemIR::CustomLayoutType inst) const
  232. -> SemIR::CompleteTypeInfo;
  233. auto BuildInfoForInst(SemIR::TypeId /*type_id*/,
  234. SemIR::MaybeUnformedType inst) const
  235. -> SemIR::CompleteTypeInfo;
  236. auto BuildInfoForInst(SemIR::TypeId /*type_id*/,
  237. SemIR::PartialType inst) const
  238. -> SemIR::CompleteTypeInfo;
  239. auto BuildInfoForInst(SemIR::TypeId /*type_id*/,
  240. SemIR::ImplWitnessAssociatedConstant inst) const
  241. -> SemIR::CompleteTypeInfo;
  242. template <typename InstT>
  243. requires(InstT::Kind.is_type() == SemIR::InstIsType::Never)
  244. auto BuildInfoForInst(SemIR::TypeId /*type_id*/, InstT inst) const
  245. -> SemIR::CompleteTypeInfo {
  246. CARBON_FATAL("Type refers to non-type inst {0}", inst);
  247. }
  248. template <typename InstT>
  249. requires(InstT::Kind.is_symbolic_when_type())
  250. auto BuildInfoForInst(SemIR::TypeId type_id, InstT /*inst*/) const
  251. -> SemIR::CompleteTypeInfo {
  252. return {.value_repr = MakeDependentValueRepr(type_id)};
  253. }
  254. // Builds and returns the `CompleteTypeInfo` for the given type. All nested
  255. // types, as found by AddNestedIncompleteTypes, are known to be complete.
  256. auto BuildInfo(SemIR::TypeId type_id, SemIR::Inst inst) const
  257. -> SemIR::CompleteTypeInfo;
  258. Context* context_;
  259. llvm::SmallVector<WorkItem> work_list_;
  260. SemIR::LocId loc_id_;
  261. MakeDiagnosticBuilderFn diagnoser_;
  262. };
  263. } // namespace
  264. auto TypeCompleter::Complete(SemIR::TypeId type_id) -> bool {
  265. Push(type_id);
  266. while (!work_list_.empty()) {
  267. if (!ProcessStep()) {
  268. return false;
  269. }
  270. }
  271. return true;
  272. }
  273. auto TypeCompleter::Push(SemIR::TypeId type_id) -> void {
  274. if (!context_->types().IsComplete(type_id)) {
  275. work_list_.push_back(
  276. {.type_id = type_id, .phase = Phase::AddNestedIncompleteTypes});
  277. }
  278. }
  279. auto TypeCompleter::ProcessStep() -> bool {
  280. auto [type_id, phase] = work_list_.back();
  281. // We might have enqueued the same type more than once. Just skip the
  282. // type if it's already complete.
  283. if (context_->types().IsComplete(type_id)) {
  284. work_list_.pop_back();
  285. return true;
  286. }
  287. auto inst_id = context_->types().GetTypeInstId(type_id);
  288. auto inst = context_->insts().Get(inst_id);
  289. auto old_work_list_size = work_list_.size();
  290. switch (phase) {
  291. case Phase::AddNestedIncompleteTypes:
  292. if (!AddNestedIncompleteTypes(inst)) {
  293. return false;
  294. }
  295. CARBON_CHECK(work_list_.size() >= old_work_list_size,
  296. "AddNestedIncompleteTypes should not remove work items");
  297. work_list_[old_work_list_size - 1].phase = Phase::BuildInfo;
  298. break;
  299. case Phase::BuildInfo: {
  300. auto info = BuildInfo(type_id, inst);
  301. context_->types().SetComplete(type_id, info);
  302. CARBON_CHECK(old_work_list_size == work_list_.size(),
  303. "BuildInfo should not change work items");
  304. work_list_.pop_back();
  305. // Also complete the value representation type, if necessary. This
  306. // should never fail: the value representation shouldn't require any
  307. // additional nested types to be complete.
  308. if (!context_->types().IsComplete(info.value_repr.type_id)) {
  309. work_list_.push_back(
  310. {.type_id = info.value_repr.type_id, .phase = Phase::BuildInfo});
  311. }
  312. // For a pointer representation, the pointee also needs to be complete.
  313. if (info.value_repr.kind == SemIR::ValueRepr::Pointer) {
  314. if (info.value_repr.type_id == SemIR::ErrorInst::TypeId) {
  315. break;
  316. }
  317. auto pointee_type_id =
  318. context_->sem_ir().GetPointeeType(info.value_repr.type_id);
  319. if (!context_->types().IsComplete(pointee_type_id)) {
  320. work_list_.push_back(
  321. {.type_id = pointee_type_id, .phase = Phase::BuildInfo});
  322. }
  323. }
  324. break;
  325. }
  326. }
  327. return true;
  328. }
  329. auto TypeCompleter::AddNestedIncompleteTypes(SemIR::Inst type_inst) -> bool {
  330. CARBON_KIND_SWITCH(type_inst) {
  331. case CARBON_KIND(SemIR::ArrayType inst): {
  332. Push(context_->types().GetTypeIdForTypeInstId(inst.element_type_inst_id));
  333. break;
  334. }
  335. case CARBON_KIND(SemIR::StructType inst): {
  336. for (auto field : context_->struct_type_fields().Get(inst.fields_id)) {
  337. Push(context_->types().GetTypeIdForTypeInstId(field.type_inst_id));
  338. }
  339. break;
  340. }
  341. case CARBON_KIND(SemIR::TupleType inst): {
  342. for (auto element_type_id : context_->types().GetBlockAsTypeIds(
  343. context_->inst_blocks().Get(inst.type_elements_id))) {
  344. Push(element_type_id);
  345. }
  346. break;
  347. }
  348. case CARBON_KIND(SemIR::ClassType inst): {
  349. auto& class_info = context_->classes().Get(inst.class_id);
  350. // If the class was imported from C++, ask Clang to try to complete it.
  351. if (!class_info.is_complete() && class_info.scope_id.has_value()) {
  352. auto& scope = context_->name_scopes().Get(class_info.scope_id);
  353. if (scope.clang_decl_context_id().has_value()) {
  354. if (!ImportClassDefinitionForClangDecl(
  355. *context_, loc_id_, inst.class_id,
  356. scope.clang_decl_context_id())) {
  357. // Clang produced a diagnostic. Don't produce one of our own.
  358. return false;
  359. }
  360. }
  361. }
  362. if (!class_info.is_complete()) {
  363. if (diagnoser_) {
  364. auto builder = diagnoser_();
  365. NoteIncompleteClass(*context_, inst.class_id, builder);
  366. builder.Emit();
  367. }
  368. return false;
  369. }
  370. if (inst.specific_id.has_value()) {
  371. ResolveSpecificDefinition(*context_, loc_id_, inst.specific_id);
  372. }
  373. if (auto adapted_type_id =
  374. class_info.GetAdaptedType(context_->sem_ir(), inst.specific_id);
  375. adapted_type_id.has_value()) {
  376. Push(adapted_type_id);
  377. } else {
  378. Push(class_info.GetObjectRepr(context_->sem_ir(), inst.specific_id));
  379. }
  380. break;
  381. }
  382. case CARBON_KIND(SemIR::ConstType inst): {
  383. Push(context_->types().GetTypeIdForTypeInstId(inst.inner_id));
  384. break;
  385. }
  386. case CARBON_KIND(SemIR::CustomLayoutType inst): {
  387. for (auto field : context_->struct_type_fields().Get(inst.fields_id)) {
  388. Push(context_->types().GetTypeIdForTypeInstId(field.type_inst_id));
  389. }
  390. break;
  391. }
  392. case CARBON_KIND(SemIR::MaybeUnformedType inst): {
  393. Push(context_->types().GetTypeIdForTypeInstId(inst.inner_id));
  394. break;
  395. }
  396. case CARBON_KIND(SemIR::PartialType inst): {
  397. Push(context_->types().GetTypeIdForTypeInstId(inst.inner_id));
  398. break;
  399. }
  400. case CARBON_KIND(SemIR::FacetType inst): {
  401. if (!RequireCompleteFacetType(*context_, loc_id_, inst, diagnoser_)) {
  402. return false;
  403. }
  404. break;
  405. }
  406. default:
  407. break;
  408. }
  409. return true;
  410. }
  411. auto TypeCompleter::MakeEmptyValueRepr() const -> SemIR::ValueRepr {
  412. return {.kind = SemIR::ValueRepr::None,
  413. .type_id = GetTupleType(*context_, {})};
  414. }
  415. auto TypeCompleter::MakeDependentValueRepr(SemIR::TypeId type_id) const
  416. -> SemIR::ValueRepr {
  417. return {.kind = SemIR::ValueRepr::Dependent, .type_id = type_id};
  418. }
  419. auto TypeCompleter::MakeCopyValueRepr(
  420. SemIR::TypeId rep_id, SemIR::ValueRepr::AggregateKind aggregate_kind) const
  421. -> SemIR::ValueRepr {
  422. return {.kind = SemIR::ValueRepr::Copy,
  423. .aggregate_kind = aggregate_kind,
  424. .type_id = rep_id};
  425. }
  426. auto TypeCompleter::MakePointerValueRepr(
  427. SemIR::TypeId pointee_id,
  428. SemIR::ValueRepr::AggregateKind aggregate_kind) const -> SemIR::ValueRepr {
  429. // TODO: Should we add `const` qualification to `pointee_id`?
  430. return {.kind = SemIR::ValueRepr::Pointer,
  431. .aggregate_kind = aggregate_kind,
  432. .type_id = GetPointerType(
  433. *context_, context_->types().GetTypeInstId(pointee_id))};
  434. }
  435. auto TypeCompleter::GetNestedInfo(SemIR::TypeId nested_type_id) const
  436. -> SemIR::CompleteTypeInfo {
  437. CARBON_CHECK(context_->types().IsComplete(nested_type_id),
  438. "Nested type should already be complete");
  439. auto info = context_->types().GetCompleteTypeInfo(nested_type_id);
  440. CARBON_CHECK(info.value_repr.kind != SemIR::ValueRepr::Unknown,
  441. "Complete type should have a value representation");
  442. return info;
  443. }
  444. auto TypeCompleter::BuildStructOrTupleValueRepr(size_t num_elements,
  445. SemIR::TypeId elementwise_rep,
  446. bool same_as_object_rep) const
  447. -> SemIR::ValueRepr {
  448. SemIR::ValueRepr::AggregateKind aggregate_kind =
  449. same_as_object_rep ? SemIR::ValueRepr::ValueAndObjectAggregate
  450. : SemIR::ValueRepr::ValueAggregate;
  451. if (num_elements == 1) {
  452. // The value representation for a struct or tuple with a single element
  453. // is a struct or tuple containing the value representation of the
  454. // element.
  455. // TODO: Consider doing the same whenever `elementwise_rep` is
  456. // sufficiently small.
  457. return MakeCopyValueRepr(elementwise_rep, aggregate_kind);
  458. }
  459. // For a struct or tuple with multiple fields, we use a pointer
  460. // to the elementwise value representation.
  461. return MakePointerValueRepr(elementwise_rep, aggregate_kind);
  462. }
  463. auto TypeCompleter::BuildInfoForInst(SemIR::TypeId type_id,
  464. SemIR::StructType struct_type) const
  465. -> SemIR::CompleteTypeInfo {
  466. auto fields = context_->struct_type_fields().Get(struct_type.fields_id);
  467. if (fields.empty()) {
  468. return {.value_repr = MakeEmptyValueRepr()};
  469. }
  470. // Find the value representation for each field, and construct a struct
  471. // of value representations.
  472. llvm::SmallVector<SemIR::StructTypeField> value_rep_fields;
  473. value_rep_fields.reserve(fields.size());
  474. bool same_as_object_rep = true;
  475. SemIR::ClassId abstract_class_id = SemIR::ClassId::None;
  476. for (auto field : fields) {
  477. auto field_type_id =
  478. context_->types().GetTypeIdForTypeInstId(field.type_inst_id);
  479. auto field_info = GetNestedInfo(field_type_id);
  480. if (!field_info.value_repr.IsCopyOfObjectRepr(context_->sem_ir(),
  481. field_type_id)) {
  482. same_as_object_rep = false;
  483. field.type_inst_id =
  484. context_->types().GetTypeInstId(field_info.value_repr.type_id);
  485. }
  486. value_rep_fields.push_back(field);
  487. // Take the first non-None abstract_class_id, if any.
  488. if (field_info.abstract_class_id.has_value() &&
  489. !abstract_class_id.has_value()) {
  490. abstract_class_id = field_info.abstract_class_id;
  491. }
  492. }
  493. auto value_rep =
  494. same_as_object_rep
  495. ? type_id
  496. : GetStructType(
  497. *context_,
  498. context_->struct_type_fields().AddCanonical(value_rep_fields));
  499. return {.value_repr = BuildStructOrTupleValueRepr(fields.size(), value_rep,
  500. same_as_object_rep),
  501. .abstract_class_id = abstract_class_id};
  502. }
  503. auto TypeCompleter::BuildInfoForInst(SemIR::TypeId type_id,
  504. SemIR::TupleType tuple_type) const
  505. -> SemIR::CompleteTypeInfo {
  506. // TODO: Share more code with structs.
  507. auto elements = context_->inst_blocks().Get(tuple_type.type_elements_id);
  508. if (elements.empty()) {
  509. return {.value_repr = MakeEmptyValueRepr()};
  510. }
  511. // Find the value representation for each element, and construct a tuple
  512. // of value representations.
  513. llvm::SmallVector<SemIR::InstId> value_rep_elements;
  514. value_rep_elements.reserve(elements.size());
  515. bool same_as_object_rep = true;
  516. SemIR::ClassId abstract_class_id = SemIR::ClassId::None;
  517. for (auto element_type_id : context_->types().GetBlockAsTypeIds(elements)) {
  518. auto element_info = GetNestedInfo(element_type_id);
  519. if (!element_info.value_repr.IsCopyOfObjectRepr(context_->sem_ir(),
  520. element_type_id)) {
  521. same_as_object_rep = false;
  522. }
  523. value_rep_elements.push_back(
  524. context_->types().GetTypeInstId(element_info.value_repr.type_id));
  525. // Take the first non-None abstract_class_id, if any.
  526. if (element_info.abstract_class_id.has_value() &&
  527. !abstract_class_id.has_value()) {
  528. abstract_class_id = element_info.abstract_class_id;
  529. }
  530. }
  531. auto value_rep = same_as_object_rep
  532. ? type_id
  533. : GetTupleType(*context_, value_rep_elements);
  534. return {.value_repr = BuildStructOrTupleValueRepr(elements.size(), value_rep,
  535. same_as_object_rep),
  536. .abstract_class_id = abstract_class_id};
  537. }
  538. auto TypeCompleter::BuildInfoForInst(SemIR::TypeId type_id,
  539. SemIR::ArrayType /*inst*/) const
  540. -> SemIR::CompleteTypeInfo {
  541. // For arrays, it's convenient to always use a pointer representation,
  542. // even when the array has zero or one element, in order to support
  543. // indexing.
  544. return {.value_repr =
  545. MakePointerValueRepr(type_id, SemIR::ValueRepr::ObjectAggregate)};
  546. }
  547. auto TypeCompleter::BuildInfoForInst(SemIR::TypeId /*type_id*/,
  548. SemIR::ClassType inst) const
  549. -> SemIR::CompleteTypeInfo {
  550. auto& class_info = context_->classes().Get(inst.class_id);
  551. auto abstract_class_id =
  552. class_info.inheritance_kind == SemIR::Class::InheritanceKind::Abstract
  553. ? inst.class_id
  554. : SemIR::ClassId::None;
  555. // The value representation of an adapter is the value representation of
  556. // its adapted type.
  557. if (auto adapted_type_id =
  558. class_info.GetAdaptedType(context_->sem_ir(), inst.specific_id);
  559. adapted_type_id.has_value()) {
  560. auto info = GetNestedInfo(adapted_type_id);
  561. info.abstract_class_id = abstract_class_id;
  562. return info;
  563. }
  564. // Otherwise, the value representation for a class is a pointer to the
  565. // object representation.
  566. // TODO: Support customized value representations for classes.
  567. // TODO: Pick a better value representation when possible.
  568. return {.value_repr = MakePointerValueRepr(
  569. class_info.GetObjectRepr(context_->sem_ir(), inst.specific_id),
  570. SemIR::ValueRepr::ObjectAggregate),
  571. .abstract_class_id = abstract_class_id};
  572. }
  573. auto TypeCompleter::BuildInfoForInst(SemIR::TypeId /*type_id*/,
  574. SemIR::ConstType inst) const
  575. -> SemIR::CompleteTypeInfo {
  576. // The value representation of `const T` is the same as that of `T`.
  577. // Objects are not modifiable through their value representations.
  578. return GetNestedInfo(context_->types().GetTypeIdForTypeInstId(inst.inner_id));
  579. }
  580. auto TypeCompleter::BuildInfoForInst(SemIR::TypeId type_id,
  581. SemIR::CustomLayoutType /*inst*/) const
  582. -> SemIR::CompleteTypeInfo {
  583. // TODO: Should we support other value representations for custom layout
  584. // types?
  585. return {.value_repr = MakePointerValueRepr(type_id)};
  586. }
  587. auto TypeCompleter::BuildInfoForInst(SemIR::TypeId type_id,
  588. SemIR::MaybeUnformedType inst) const
  589. -> SemIR::CompleteTypeInfo {
  590. // `MaybeUnformed(T)` has the same value representation as `T` if that value
  591. // representation preserves all the bytes of the value, including any padding
  592. // bits. Otherwise we need to use a different representation.
  593. auto inner_type_id = context_->types().GetTypeIdForTypeInstId(inst.inner_id);
  594. auto nested = GetNestedInfo(inner_type_id);
  595. if (nested.value_repr.kind == SemIR::ValueRepr::Custom) {
  596. nested.value_repr = MakePointerValueRepr(type_id);
  597. } else if (nested.value_repr.kind == SemIR::ValueRepr::Copy) {
  598. auto type_inst = context_->types().GetAsInst(nested.value_repr.type_id);
  599. // TODO: Should ValueRepr::IsCopyOfObjectRepr return false for `bool`?
  600. if (!nested.value_repr.IsCopyOfObjectRepr(context_->sem_ir(),
  601. inner_type_id) ||
  602. type_inst.Is<SemIR::BoolType>()) {
  603. nested.value_repr = MakePointerValueRepr(type_id);
  604. }
  605. // TODO: Handle any other types that we treat as having discarded padding
  606. // bits. For now there are no such types, as all class types and all structs
  607. // and tuples with more than one element are passed indirectly.
  608. }
  609. return nested;
  610. }
  611. auto TypeCompleter::BuildInfoForInst(SemIR::TypeId /*type_id*/,
  612. SemIR::PartialType inst) const
  613. -> SemIR::CompleteTypeInfo {
  614. // The value representation of `partial T` is the same as that of `T`.
  615. // Objects are not modifiable through their value representations.
  616. return GetNestedInfo(context_->types().GetTypeIdForTypeInstId(inst.inner_id));
  617. }
  618. auto TypeCompleter::BuildInfoForInst(
  619. SemIR::TypeId /*type_id*/, SemIR::ImplWitnessAssociatedConstant inst) const
  620. -> SemIR::CompleteTypeInfo {
  621. return GetNestedInfo(inst.type_id);
  622. }
  623. // Builds and returns the value representation for the given type. All nested
  624. // types, as found by AddNestedIncompleteTypes, are known to be complete.
  625. auto TypeCompleter::BuildInfo(SemIR::TypeId type_id, SemIR::Inst inst) const
  626. -> SemIR::CompleteTypeInfo {
  627. // Use overload resolution to select the implementation, producing compile
  628. // errors when BuildInfoForInst isn't defined for a given instruction.
  629. CARBON_KIND_SWITCH(inst) {
  630. #define CARBON_SEM_IR_INST_KIND(Name) \
  631. case CARBON_KIND(SemIR::Name typed_inst): { \
  632. return BuildInfoForInst(type_id, typed_inst); \
  633. }
  634. #include "toolchain/sem_ir/inst_kind.def"
  635. }
  636. }
  637. auto TryToCompleteType(Context& context, SemIR::TypeId type_id,
  638. SemIR::LocId loc_id, MakeDiagnosticBuilderFn diagnoser)
  639. -> bool {
  640. return TypeCompleter(&context, loc_id, diagnoser).Complete(type_id);
  641. }
  642. auto CompleteTypeOrCheckFail(Context& context, SemIR::TypeId type_id) -> void {
  643. bool complete =
  644. TypeCompleter(&context, SemIR::LocId::None, nullptr).Complete(type_id);
  645. CARBON_CHECK(complete, "Expected {0} to be a complete type",
  646. context.types().GetAsInst(type_id));
  647. }
  648. auto RequireCompleteType(Context& context, SemIR::TypeId type_id,
  649. SemIR::LocId loc_id, MakeDiagnosticBuilderFn diagnoser)
  650. -> bool {
  651. CARBON_CHECK(diagnoser);
  652. if (!TypeCompleter(&context, loc_id, diagnoser).Complete(type_id)) {
  653. return false;
  654. }
  655. // For a symbolic type, create an instruction to require the corresponding
  656. // specific type to be complete.
  657. if (type_id.is_symbolic()) {
  658. // TODO: Deduplicate these.
  659. AddInstInNoBlock(
  660. context, loc_id,
  661. SemIR::RequireCompleteType{
  662. .type_id =
  663. GetSingletonType(context, SemIR::WitnessType::TypeInstId),
  664. .complete_type_inst_id = context.types().GetTypeInstId(type_id)});
  665. }
  666. return true;
  667. }
  668. auto RequireConcreteType(Context& context, SemIR::TypeId type_id,
  669. SemIR::LocId loc_id, MakeDiagnosticBuilderFn diagnoser,
  670. MakeDiagnosticBuilderFn abstract_diagnoser) -> bool {
  671. // TODO: For symbolic types, should add an implicit constraint that they are
  672. // not abstract.
  673. CARBON_CHECK(abstract_diagnoser);
  674. // The representation of a facet type does not depend on its definition, so
  675. // they are considered "concrete" even when not complete.
  676. if (context.types().IsFacetType(type_id)) {
  677. return true;
  678. }
  679. if (!RequireCompleteType(context, type_id, loc_id, diagnoser)) {
  680. return false;
  681. }
  682. auto complete_info = context.types().GetCompleteTypeInfo(type_id);
  683. if (complete_info.abstract_class_id.has_value()) {
  684. auto builder = abstract_diagnoser();
  685. if (builder) {
  686. bool direct_use = false;
  687. if (auto inst = context.types().TryGetAs<SemIR::ClassType>(type_id)) {
  688. if (inst->class_id == complete_info.abstract_class_id) {
  689. direct_use = true;
  690. }
  691. }
  692. NoteAbstractClass(context, complete_info.abstract_class_id, direct_use,
  693. builder);
  694. builder.Emit();
  695. }
  696. return false;
  697. }
  698. return true;
  699. }
  700. // Require all named constraints in the facet type are identified. For a named
  701. // constraint, this means the constraint definition is complete.
  702. static auto RequireIdentifiedNamedConstraints(
  703. Context& context, const SemIR::FacetTypeInfo& facet_type_info,
  704. MakeDiagnosticBuilderFn diagnoser) -> bool {
  705. auto named_constraint_ids = llvm::map_range(
  706. llvm::concat<const SemIR::SpecificNamedConstraint>(
  707. facet_type_info.extend_named_constraints,
  708. facet_type_info.self_impls_named_constraints),
  709. [](SemIR::SpecificNamedConstraint s) { return s.named_constraint_id; });
  710. for (auto named_constraint_id : named_constraint_ids) {
  711. const auto& constraint =
  712. context.named_constraints().Get(named_constraint_id);
  713. if (!constraint.is_complete()) {
  714. if (diagnoser) {
  715. auto builder = diagnoser();
  716. NoteIncompleteNamedConstraint(context, named_constraint_id, builder);
  717. builder.Emit();
  718. }
  719. return false;
  720. }
  721. }
  722. return true;
  723. }
  724. static auto GetSelfFacetValue(Context& context, SemIR::ConstantId self_const_id)
  725. -> SemIR::ConstantId {
  726. if (self_const_id == SemIR::ErrorInst::ConstantId) {
  727. return SemIR::ErrorInst::ConstantId;
  728. }
  729. // Avoid wrapping a FacetAccessType(FacetValue) in another layer of
  730. // FacetValue. Just unwrap the FacetValue inside.
  731. self_const_id = GetCanonicalFacetOrTypeValue(context, self_const_id);
  732. auto self_inst_id = context.constant_values().GetInstId(self_const_id);
  733. auto type_id = context.insts().Get(self_inst_id).type_id();
  734. CARBON_CHECK(context.types().IsFacetType(type_id));
  735. if (context.types().Is<SemIR::FacetType>(type_id)) {
  736. return self_const_id;
  737. }
  738. return GetConstantFacetValueForType(
  739. context, context.types().GetAsTypeInstId(self_inst_id));
  740. }
  741. auto RequireIdentifiedFacetType(Context& context, SemIR::LocId loc_id,
  742. SemIR::ConstantId self_const_id,
  743. const SemIR::FacetType& facet_type,
  744. MakeDiagnosticBuilderFn diagnoser)
  745. -> SemIR::IdentifiedFacetTypeId {
  746. auto key =
  747. SemIR::IdentifiedFacetTypeKey{.facet_type_id = facet_type.facet_type_id,
  748. .self_const_id = self_const_id};
  749. if (auto identified_id = context.identified_facet_types().Lookup(key);
  750. identified_id.has_value()) {
  751. return identified_id;
  752. }
  753. struct SelfImplsFacetType {
  754. SemIR::ConstantId self;
  755. SemIR::FacetTypeId facet_type;
  756. };
  757. // Work queue.
  758. llvm::SmallVector<SelfImplsFacetType> extend_facet_types = {
  759. {self_const_id, facet_type.facet_type_id}};
  760. llvm::SmallVector<SelfImplsFacetType> impls_facet_types;
  761. // Outputs for the IdentifiedFacetType.
  762. llvm::SmallVector<SemIR::IdentifiedFacetType::RequiredImpl> extends;
  763. llvm::SmallVector<SemIR::IdentifiedFacetType::RequiredImpl> impls;
  764. while (true) {
  765. SelfImplsFacetType next_impls = {SemIR::ConstantId::None,
  766. SemIR::FacetTypeId::None};
  767. bool facet_type_extends = false;
  768. if (!extend_facet_types.empty()) {
  769. next_impls = extend_facet_types.pop_back_val();
  770. facet_type_extends = true;
  771. } else if (!impls_facet_types.empty()) {
  772. next_impls = impls_facet_types.pop_back_val();
  773. facet_type_extends = false;
  774. } else {
  775. break;
  776. }
  777. auto self_const_id = next_impls.self;
  778. const auto& facet_type_info =
  779. context.facet_types().Get(next_impls.facet_type);
  780. if (!RequireIdentifiedNamedConstraints(context, facet_type_info,
  781. diagnoser)) {
  782. return SemIR::IdentifiedFacetTypeId::None;
  783. }
  784. auto self_and_interface = [&](SemIR::SpecificInterface interface)
  785. -> SemIR::IdentifiedFacetType::RequiredImpl {
  786. return {self_const_id, interface};
  787. };
  788. if (facet_type_extends) {
  789. llvm::append_range(extends,
  790. llvm::map_range(facet_type_info.extend_constraints,
  791. self_and_interface));
  792. } else {
  793. llvm::append_range(impls,
  794. llvm::map_range(facet_type_info.extend_constraints,
  795. self_and_interface));
  796. }
  797. llvm::append_range(impls,
  798. llvm::map_range(facet_type_info.self_impls_constraints,
  799. self_and_interface));
  800. // Constructing specifics for `require` decls can produce monomorphization
  801. // errors, which we want to connect back to here.
  802. Diagnostics::AnnotationScope annotate_diagnostics(
  803. &context.emitter(), [&](auto& builder) {
  804. CARBON_DIAGNOSTIC(IdentifyingFacetTypeHere, Note,
  805. "identifying facet type {0} here",
  806. SemIR::FacetTypeId);
  807. builder.Note(loc_id, IdentifyingFacetTypeHere,
  808. facet_type.facet_type_id);
  809. });
  810. if (facet_type_info.extend_named_constraints.empty() &&
  811. facet_type_info.self_impls_named_constraints.empty()) {
  812. continue;
  813. }
  814. // The self may have type TypeType. But the `Self` in a generic require decl
  815. // has type FacetType, so we need something similar to replace it in the
  816. // specific.
  817. auto self_facet_value = GetSelfFacetValue(context, self_const_id);
  818. for (auto extends : facet_type_info.extend_named_constraints) {
  819. const auto& constraint =
  820. context.named_constraints().Get(extends.named_constraint_id);
  821. for (auto require_impls_id : context.require_impls_blocks().Get(
  822. constraint.require_impls_block_id)) {
  823. const auto& require = context.require_impls().Get(require_impls_id);
  824. auto require_specific =
  825. GetRequireImplsSpecificFromEnclosingSpecificWithSelfFacetValue(
  826. context, require, extends.specific_id, self_facet_value);
  827. auto require_self = GetConstantValueInRequireImplsSpecific(
  828. context, require_specific, require.self_id);
  829. auto require_facet_type = GetConstantValueInRequireImplsSpecific(
  830. context, require_specific, require.facet_type_inst_id);
  831. if (require_self == SemIR::ErrorInst::ConstantId ||
  832. require_facet_type == SemIR::ErrorInst::ConstantId) {
  833. return SemIR::IdentifiedFacetTypeId::None;
  834. }
  835. // TODO: Add and use constant_values().GetAs<SemIR::FacetType>().
  836. auto facet_type_inst_id =
  837. context.constant_values().GetInstId(require_facet_type);
  838. auto facet_type_id = context.insts()
  839. .GetAs<SemIR::FacetType>(facet_type_inst_id)
  840. .facet_type_id;
  841. if (facet_type_extends && require.extend_self) {
  842. extend_facet_types.push_back({require_self, facet_type_id});
  843. } else {
  844. impls_facet_types.push_back({require_self, facet_type_id});
  845. }
  846. }
  847. }
  848. for (auto impls : facet_type_info.self_impls_named_constraints) {
  849. const auto& constraint =
  850. context.named_constraints().Get(impls.named_constraint_id);
  851. for (auto require_impls_id : context.require_impls_blocks().Get(
  852. constraint.require_impls_block_id)) {
  853. const auto& require = context.require_impls().Get(require_impls_id);
  854. auto require_specific =
  855. GetRequireImplsSpecificFromEnclosingSpecificWithSelfFacetValue(
  856. context, require, impls.specific_id, self_facet_value);
  857. auto require_self = GetConstantValueInRequireImplsSpecific(
  858. context, require_specific, require.self_id);
  859. auto require_facet_type = GetConstantValueInRequireImplsSpecific(
  860. context, require_specific, require.facet_type_inst_id);
  861. if (require_self == SemIR::ErrorInst::ConstantId ||
  862. require_facet_type == SemIR::ErrorInst::ConstantId) {
  863. return SemIR::IdentifiedFacetTypeId::None;
  864. }
  865. // TODO: Add and use constant_values().GetAs<SemIR::FacetType>().
  866. auto facet_type_inst_id =
  867. context.constant_values().GetInstId(require_facet_type);
  868. auto facet_type_id = context.insts()
  869. .GetAs<SemIR::FacetType>(facet_type_inst_id)
  870. .facet_type_id;
  871. impls_facet_types.push_back({require_self, facet_type_id});
  872. }
  873. }
  874. }
  875. // TODO: Process other kinds of requirements.
  876. return context.identified_facet_types().Add({key, extends, impls});
  877. }
  878. auto AsCompleteType(Context& context, SemIR::TypeId type_id,
  879. SemIR::LocId loc_id, MakeDiagnosticBuilderFn diagnoser)
  880. -> SemIR::TypeId {
  881. return RequireCompleteType(context, type_id, loc_id, diagnoser)
  882. ? type_id
  883. : SemIR::ErrorInst::TypeId;
  884. }
  885. // Returns the type `type_id` if it is a concrete type, or produces an
  886. // incomplete or abstract type error and returns an error type. This is a
  887. // convenience wrapper around `RequireConcreteType`.
  888. auto AsConcreteType(Context& context, SemIR::TypeId type_id,
  889. SemIR::LocId loc_id, MakeDiagnosticBuilderFn diagnoser,
  890. MakeDiagnosticBuilderFn abstract_diagnoser)
  891. -> SemIR::TypeId {
  892. return RequireConcreteType(context, type_id, loc_id, diagnoser,
  893. abstract_diagnoser)
  894. ? type_id
  895. : SemIR::ErrorInst::TypeId;
  896. }
  897. } // namespace Carbon::Check