custom_witness.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473
  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/custom_witness.h"
  5. #include "toolchain/base/kind_switch.h"
  6. #include "toolchain/check/facet_type.h"
  7. #include "toolchain/check/function.h"
  8. #include "toolchain/check/generic.h"
  9. #include "toolchain/check/impl.h"
  10. #include "toolchain/check/impl_lookup.h"
  11. #include "toolchain/check/import_ref.h"
  12. #include "toolchain/check/inst.h"
  13. #include "toolchain/check/name_lookup.h"
  14. #include "toolchain/check/type.h"
  15. #include "toolchain/check/type_completion.h"
  16. #include "toolchain/sem_ir/builtin_function_kind.h"
  17. #include "toolchain/sem_ir/ids.h"
  18. #include "toolchain/sem_ir/typed_insts.h"
  19. namespace Carbon::Check {
  20. // Given a value whose type `IsFacetTypeOrError`, returns the corresponding
  21. // type.
  22. static auto GetFacetAsType(Context& context,
  23. SemIR::ConstantId facet_or_type_const_id)
  24. -> SemIR::TypeId {
  25. auto facet_or_type_id =
  26. context.constant_values().GetInstId(facet_or_type_const_id);
  27. auto type_type_id = context.insts().Get(facet_or_type_id).type_id();
  28. CARBON_CHECK(context.types().IsFacetTypeOrError(type_type_id));
  29. if (context.types().Is<SemIR::FacetType>(type_type_id)) {
  30. // It's a facet; access its type.
  31. facet_or_type_id = context.types().GetTypeInstId(
  32. GetFacetAccessType(context, facet_or_type_id));
  33. }
  34. return context.types().GetTypeIdForTypeInstId(facet_or_type_id);
  35. }
  36. // Returns the body for `Destroy.Op`. This will return `None` if using the
  37. // builtin `NoOp` is appropriate.
  38. //
  39. // TODO: This is a placeholder still not actually destroying things, intended to
  40. // maintain mostly-consistent behavior with current logic while working. That
  41. // also means using `self`.
  42. // TODO: This mirrors `TypeCanDestroy` below, think about ways to share what's
  43. // handled.
  44. static auto MakeDestroyOpBody(Context& context, SemIR::LocId loc_id,
  45. SemIR::TypeId self_type_id)
  46. -> SemIR::InstBlockId {
  47. context.inst_block_stack().Push();
  48. auto inst = context.types().GetAsInst(self_type_id);
  49. while (auto class_type = inst.TryAs<SemIR::ClassType>()) {
  50. // Switch to looking at the object representation.
  51. auto class_info = context.classes().Get(class_type->class_id);
  52. CARBON_CHECK(class_info.is_complete());
  53. inst = context.types().GetAsInst(
  54. class_info.GetObjectRepr(context.sem_ir(), class_type->specific_id));
  55. }
  56. CARBON_KIND_SWITCH(inst) {
  57. case SemIR::ArrayType::Kind:
  58. case SemIR::ConstType::Kind:
  59. case SemIR::MaybeUnformedType::Kind:
  60. case SemIR::PartialType::Kind:
  61. case SemIR::StructType::Kind:
  62. case SemIR::TupleType::Kind:
  63. // TODO: Implement iterative destruction of types.
  64. break;
  65. case SemIR::BoolType::Kind:
  66. case SemIR::FloatType::Kind:
  67. case SemIR::IntType::Kind:
  68. case SemIR::PointerType::Kind:
  69. // For trivially destructible types, we don't generate anything, so that
  70. // this can collapse to a noop implementation when possible.
  71. break;
  72. case SemIR::ErrorInst::Kind:
  73. // Errors can't be destroyed, but we'll still try to generate calls for
  74. // other members.
  75. break;
  76. default:
  77. CARBON_FATAL("Unexpected type for destroy: {0}", inst);
  78. }
  79. if (context.inst_block_stack().PeekCurrentBlockContents().empty()) {
  80. context.inst_block_stack().PopAndDiscard();
  81. return SemIR::InstBlockId::None;
  82. }
  83. AddInst(context, loc_id, SemIR::Return{});
  84. return context.inst_block_stack().Pop();
  85. }
  86. // Returns a manufactured `Destroy.Op` function with the `self` parameter typed
  87. // to `self_type_id`.
  88. static auto MakeDestroyOpFunction(Context& context, SemIR::LocId loc_id,
  89. SemIR::TypeId self_type_id,
  90. SemIR::NameScopeId parent_scope_id)
  91. -> SemIR::InstId {
  92. auto name_id = context.core_identifiers().AddNameId(CoreIdentifier::Op);
  93. auto [decl_id, function_id] =
  94. MakeGeneratedFunctionDecl(context, loc_id,
  95. {.parent_scope_id = parent_scope_id,
  96. .name_id = name_id,
  97. .self_type_id = self_type_id});
  98. auto& function = context.functions().Get(function_id);
  99. auto body_id = MakeDestroyOpBody(context, loc_id, self_type_id);
  100. if (body_id.has_value()) {
  101. function.SetCoreWitness();
  102. function.body_block_ids.push_back(body_id);
  103. } else {
  104. function.SetCoreWitness(SemIR::BuiltinFunctionKind::NoOp);
  105. }
  106. return decl_id;
  107. }
  108. static auto MakeCustomWitnessConstantInst(
  109. Context& context, SemIR::LocId loc_id,
  110. SemIR::SpecificInterfaceId query_specific_interface_id,
  111. SemIR::InstBlockId associated_entities_block_id) -> SemIR::InstId {
  112. // The witness is a CustomWitness of the query interface with a table that
  113. // contains each associated entity.
  114. auto const_id = EvalOrAddInst<SemIR::CustomWitness>(
  115. context, loc_id,
  116. {.type_id = GetSingletonType(context, SemIR::WitnessType::TypeInstId),
  117. .elements_id = associated_entities_block_id,
  118. .query_specific_interface_id = query_specific_interface_id});
  119. return context.constant_values().GetInstId(const_id);
  120. }
  121. struct TypesForSelfFacet {
  122. // A FacetType that contains only the query interface.
  123. SemIR::TypeId facet_type_for_query_specific_interface;
  124. // The query self as a type, which involves a conversion if it was a facet.
  125. SemIR::TypeId query_self_as_type_id;
  126. };
  127. static auto GetTypesForSelfFacet(
  128. Context& context, SemIR::LocId loc_id,
  129. SemIR::ConstantId query_self_const_id,
  130. SemIR::SpecificInterfaceId query_specific_interface_id)
  131. -> TypesForSelfFacet {
  132. const auto query_specific_interface =
  133. context.specific_interfaces().Get(query_specific_interface_id);
  134. // The Self facet will have type FacetType, for the query interface.
  135. auto facet_type_for_query_specific_interface =
  136. context.types().GetTypeIdForTypeConstantId(
  137. EvalOrAddInst<SemIR::FacetType>(
  138. context, loc_id,
  139. FacetTypeFromInterface(context,
  140. query_specific_interface.interface_id,
  141. query_specific_interface.specific_id)));
  142. // The Self facet needs to point to a type value. If it's not one already,
  143. // convert to type.
  144. auto query_self_as_type_id = GetFacetAsType(context, query_self_const_id);
  145. return {facet_type_for_query_specific_interface, query_self_as_type_id};
  146. }
  147. // Build a new facet from the query self, using a CustomWitness for the query
  148. // interface with an entry for each associated entity so far.
  149. static auto MakeSelfFacetWithCustomWitness(
  150. Context& context, SemIR::LocId loc_id, TypesForSelfFacet query_types,
  151. SemIR::SpecificInterfaceId query_specific_interface_id,
  152. SemIR::InstBlockId associated_entities_block_id) -> SemIR::ConstantId {
  153. // We are building a facet value for a single interface, so the witness block
  154. // is a single witness for that interface.
  155. auto witnesses_block_id =
  156. context.inst_blocks().Add({MakeCustomWitnessConstantInst(
  157. context, loc_id, query_specific_interface_id,
  158. associated_entities_block_id)});
  159. return EvalOrAddInst<SemIR::FacetValue>(
  160. context, loc_id,
  161. {.type_id = query_types.facet_type_for_query_specific_interface,
  162. .type_inst_id =
  163. context.types().GetTypeInstId(query_types.query_self_as_type_id),
  164. .witnesses_block_id = witnesses_block_id});
  165. }
  166. auto BuildCustomWitness(Context& context, SemIR::LocId loc_id,
  167. SemIR::ConstantId query_self_const_id,
  168. SemIR::SpecificInterfaceId query_specific_interface_id,
  169. llvm::ArrayRef<SemIR::InstId> values) -> SemIR::InstId {
  170. const auto query_specific_interface =
  171. context.specific_interfaces().Get(query_specific_interface_id);
  172. const auto& interface =
  173. context.interfaces().Get(query_specific_interface.interface_id);
  174. auto assoc_entities =
  175. context.inst_blocks().GetOrEmpty(interface.associated_entities_id);
  176. if (assoc_entities.size() != values.size()) {
  177. context.TODO(loc_id, ("Unsupported definition of interface " +
  178. context.names().GetFormatted(interface.name_id))
  179. .str());
  180. return SemIR::ErrorInst::InstId;
  181. }
  182. auto query_types_for_self_facet = GetTypesForSelfFacet(
  183. context, loc_id, query_self_const_id, query_specific_interface_id);
  184. // The values that will go in the witness table.
  185. llvm::SmallVector<SemIR::InstId> entries;
  186. // Fill in the witness table.
  187. for (const auto& [assoc_entity_id, value_id] :
  188. llvm::zip_equal(assoc_entities, values)) {
  189. LoadImportRef(context, assoc_entity_id);
  190. // Build a witness with the current contents of the witness table. This will
  191. // grow as we progress through the impl. In theory this will build O(n^2)
  192. // table entries, but in practice n <= 2, so that's OK.
  193. //
  194. // This is necessary because later associated entities may refer to earlier
  195. // associated entities in their signatures. In particular, an associated
  196. // result type may be used as the return type of an associated function.
  197. auto self_facet = MakeSelfFacetWithCustomWitness(
  198. context, loc_id, query_types_for_self_facet,
  199. query_specific_interface_id, context.inst_blocks().Add(entries));
  200. auto interface_with_self_specific_id = MakeSpecificWithInnerSelf(
  201. context, loc_id, interface.generic_id, interface.generic_with_self_id,
  202. query_specific_interface.specific_id, self_facet);
  203. auto decl_id =
  204. context.constant_values().GetInstId(SemIR::GetConstantValueInSpecific(
  205. context.sem_ir(), interface_with_self_specific_id,
  206. assoc_entity_id));
  207. CARBON_CHECK(decl_id.has_value(), "Non-constant associated entity");
  208. auto decl = context.insts().Get(decl_id);
  209. CARBON_KIND_SWITCH(decl) {
  210. case CARBON_KIND(SemIR::StructValue struct_value): {
  211. if (struct_value.type_id == SemIR::ErrorInst::TypeId) {
  212. return SemIR::ErrorInst::InstId;
  213. }
  214. // TODO: If a thunk is needed, this will build a different value each
  215. // time it's called, so we won't properly deduplicate repeated
  216. // witnesses.
  217. entries.push_back(CheckAssociatedFunctionImplementation(
  218. context,
  219. context.types().GetAs<SemIR::FunctionType>(struct_value.type_id),
  220. query_specific_interface.specific_id, value_id,
  221. /*defer_thunk_definition=*/false));
  222. break;
  223. }
  224. case SemIR::AssociatedConstantDecl::Kind: {
  225. context.TODO(loc_id,
  226. "Associated constant in interface with synthesized impl");
  227. return SemIR::ErrorInst::InstId;
  228. }
  229. default:
  230. CARBON_CHECK(decl_id == SemIR::ErrorInst::InstId,
  231. "Unexpected kind of associated entity {0}", decl);
  232. return SemIR::ErrorInst::InstId;
  233. }
  234. }
  235. // TODO: Consider building one witness after all associated constants, and
  236. // then a second after all associated functions, rather than building one in
  237. // each `StructValue`. Right now the code is written assuming at most one
  238. // function, though this CHECK can be removed as a temporary workaround.
  239. CARBON_CHECK(entries.size() <= 1,
  240. "TODO: Support multiple associated functions");
  241. return MakeCustomWitnessConstantInst(context, loc_id,
  242. query_specific_interface_id,
  243. context.inst_blocks().Add(entries));
  244. }
  245. auto GetCoreInterface(Context& context, SemIR::InterfaceId interface_id)
  246. -> CoreInterface {
  247. const auto& interface = context.interfaces().Get(interface_id);
  248. if (!context.name_scopes().IsCorePackage(interface.parent_scope_id) ||
  249. !interface.name_id.AsIdentifierId().has_value()) {
  250. return CoreInterface::Unknown;
  251. }
  252. constexpr auto CoreIdentifiersToInterfaces = std::array{
  253. std::pair{CoreIdentifier::Copy, CoreInterface::Copy},
  254. std::pair{CoreIdentifier::Destroy, CoreInterface::Destroy},
  255. std::pair{CoreIdentifier::IntFitsIn, CoreInterface::IntFitsIn},
  256. std::pair{CoreIdentifier::CppUnsafeDeref, CoreInterface::CppUnsafeDeref}};
  257. for (auto [core_identifier, core_interface] : CoreIdentifiersToInterfaces) {
  258. if (interface.name_id ==
  259. context.core_identifiers().AddNameId(core_identifier)) {
  260. return core_interface;
  261. }
  262. }
  263. return CoreInterface::Unknown;
  264. }
  265. // Returns true if the `Self` should impl `Destroy`.
  266. static auto TypeCanDestroy(Context& context,
  267. SemIR::ConstantId query_self_const_id,
  268. SemIR::InterfaceId destroy_interface_id) -> bool {
  269. auto inst = context.insts().Get(context.constant_values().GetInstId(
  270. GetCanonicalFacetOrTypeValue(context, query_self_const_id)));
  271. // For facet values, look if the FacetType provides the same.
  272. if (auto facet_type =
  273. context.types().TryGetAs<SemIR::FacetType>(inst.type_id())) {
  274. const auto& info = context.facet_types().Get(facet_type->facet_type_id);
  275. for (auto interface : info.extend_constraints) {
  276. if (interface.interface_id == destroy_interface_id) {
  277. return true;
  278. }
  279. }
  280. }
  281. CARBON_KIND_SWITCH(inst) {
  282. case CARBON_KIND(SemIR::ClassType class_type): {
  283. auto class_info = context.classes().Get(class_type.class_id);
  284. // Incomplete and abstract classes can't be destroyed.
  285. if (!class_info.is_complete() ||
  286. class_info.inheritance_kind ==
  287. SemIR::Class::InheritanceKind::Abstract) {
  288. return false;
  289. }
  290. // `LookupCppImpl` handles C++ types.
  291. if (context.name_scopes().Get(class_info.scope_id).is_cpp_scope()) {
  292. return false;
  293. }
  294. // TODO: Return false if the object repr doesn't impl `Destroy`.
  295. return true;
  296. }
  297. case SemIR::ArrayType::Kind:
  298. case SemIR::ConstType::Kind:
  299. case SemIR::MaybeUnformedType::Kind:
  300. case SemIR::PartialType::Kind:
  301. case SemIR::StructType::Kind:
  302. case SemIR::TupleType::Kind:
  303. // TODO: Return false for types that indirectly reference a type that
  304. // doesn't impl `Destroy`.
  305. return true;
  306. case SemIR::BoolType::Kind:
  307. case SemIR::FloatType::Kind:
  308. case SemIR::IntType::Kind:
  309. case SemIR::PointerType::Kind:
  310. // Trivially destructible.
  311. return true;
  312. default:
  313. return false;
  314. }
  315. }
  316. static auto MakeDestroyWitness(
  317. Context& context, SemIR::LocId loc_id,
  318. SemIR::ConstantId query_self_const_id,
  319. SemIR::SpecificInterfaceId query_specific_interface_id)
  320. -> std::optional<SemIR::InstId> {
  321. auto query_specific_interface =
  322. context.specific_interfaces().Get(query_specific_interface_id);
  323. if (!TypeCanDestroy(context, query_self_const_id,
  324. query_specific_interface.interface_id)) {
  325. return std::nullopt;
  326. }
  327. if (query_self_const_id.is_symbolic()) {
  328. return SemIR::InstId::None;
  329. }
  330. // Mark functions with the interface's scope as a hint to mangling. This does
  331. // not add them to the scope.
  332. auto parent_scope_id = context.interfaces()
  333. .Get(query_specific_interface.interface_id)
  334. .scope_without_self_id;
  335. auto self_type_id = GetFacetAsType(context, query_self_const_id);
  336. auto op_id =
  337. MakeDestroyOpFunction(context, loc_id, self_type_id, parent_scope_id);
  338. return BuildCustomWitness(context, loc_id, query_self_const_id,
  339. query_specific_interface_id, {op_id});
  340. }
  341. static auto MakeIntFitsInWitness(
  342. Context& context, SemIR::LocId loc_id,
  343. SemIR::ConstantId query_self_const_id,
  344. SemIR::SpecificInterfaceId query_specific_interface_id)
  345. -> std::optional<SemIR::InstId> {
  346. auto query_specific_interface =
  347. context.specific_interfaces().Get(query_specific_interface_id);
  348. auto args_id = query_specific_interface.specific_id;
  349. if (!args_id.has_value()) {
  350. return std::nullopt;
  351. }
  352. auto args_block_id = context.specifics().Get(args_id).args_id;
  353. auto args_block = context.inst_blocks().Get(args_block_id);
  354. if (args_block.size() != 1) {
  355. return std::nullopt;
  356. }
  357. auto dest_const_id = context.constant_values().Get(args_block[0]);
  358. if (!dest_const_id.is_constant()) {
  359. return std::nullopt;
  360. }
  361. auto src_type_id = GetFacetAsType(context, query_self_const_id);
  362. auto dest_type_id = GetFacetAsType(context, dest_const_id);
  363. auto context_fn = [](DiagnosticContextBuilder& /*builder*/) -> void {};
  364. if (!RequireCompleteType(context, src_type_id, loc_id, context_fn) ||
  365. !RequireCompleteType(context, dest_type_id, loc_id, context_fn)) {
  366. return std::nullopt;
  367. }
  368. auto src_info = context.types().TryGetIntTypeInfo(src_type_id);
  369. auto dest_info = context.types().TryGetIntTypeInfo(dest_type_id);
  370. if (!src_info || !dest_info) {
  371. return std::nullopt;
  372. }
  373. // If the bit width is unknown (e.g., due to symbolic evaluation), we cannot
  374. // determine whether it fits yet.
  375. if (src_info->bit_width == IntId::None ||
  376. dest_info->bit_width == IntId::None) {
  377. return std::nullopt;
  378. }
  379. const auto& src_width = context.ints().Get(src_info->bit_width);
  380. const auto& dest_width = context.ints().Get(dest_info->bit_width);
  381. bool fits = false;
  382. if (src_info->is_signed && !dest_info->is_signed) {
  383. // Signed -> unsigned: would truncate the sign bit.
  384. fits = false;
  385. } else if (src_info->is_signed == dest_info->is_signed) {
  386. // Signed -> signed or unsigned -> unsigned: allow widening or preserving
  387. // width.
  388. fits = src_width.sle(dest_width);
  389. } else {
  390. // Unsigned -> signed: strict widening required.
  391. fits = src_width.slt(dest_width);
  392. }
  393. if (!fits) {
  394. return std::nullopt;
  395. }
  396. return BuildCustomWitness(context, loc_id, query_self_const_id,
  397. query_specific_interface_id, {});
  398. }
  399. auto LookupCustomWitness(Context& context, SemIR::LocId loc_id,
  400. CoreInterface core_interface,
  401. SemIR::ConstantId query_self_const_id,
  402. SemIR::SpecificInterfaceId query_specific_interface_id)
  403. -> std::optional<SemIR::InstId> {
  404. switch (core_interface) {
  405. case CoreInterface::Destroy:
  406. return MakeDestroyWitness(context, loc_id, query_self_const_id,
  407. query_specific_interface_id);
  408. case CoreInterface::IntFitsIn:
  409. return MakeIntFitsInWitness(context, loc_id, query_self_const_id,
  410. query_specific_interface_id);
  411. case CoreInterface::CppUnsafeDeref:
  412. case CoreInterface::Copy:
  413. case CoreInterface::Unknown:
  414. // TODO: Handle more interfaces, particularly copy, move, and conversion.
  415. return std::nullopt;
  416. }
  417. }
  418. } // namespace Carbon::Check