Files
carbon-lang/toolchain/sem_ir/dump.cpp
T
Dana JansensandJon Ross-Perkins 53c98a8619 Support specialization in impl lookup with a symbolic query/impl. (#5169)
Add a new instruction called ImplSymbolicWitness which represents a
search for an impl declaration given a self type and an interface to
find implemented for the self type. The self type is stored as a
constant instruction id, rather than as a ConstantId, as instructions
don't currently support holding ConstantId. The interface is stored as a
SpecificInterface but we can't fit all of it directly into the
instruction. So we add a new id to refer to the SpecificInterface as
follows.

Add a new SpecificInterfaceId which indexes into a canonical value store
on SemIR::File. This tracks all `SpecificInterface`s stored in an
instruction - specifically the ImplSymbolicWitness instruction.

The SpecificInterface on Impl is still stored there as a value, not as
an id, and no id is eagerly constructed for it. We wait until an id is
needed to make one. Since they are canonical, a new id is only create
when a new SpecificInterface value is seen.

When doing impl lookup, and the query is not concrete, and the impl is
not effectively final, the query needs to consider future impls that may
specialize either the self type or the constaint to make a more precise
match and replace the found impl declaration. Instead of returning the
ImplWitness instruction from the found impl, we generate a
ImplSymbolicWitness instruction, storing the query so that it can be
replayed later. This instruction is added to the generic eval block and
thus will be re-evaluated later with a SpecificId that may make the
query more concrete. When evaluating the instruction and replaying the
query, the lookup has the same conditions and if it does not decide to
use the found impl concretely, then the same instruction is returned
from eval, leaving it as symbolic.

--- Impl lookup changes ---

Impl lookup gets a little more interesting now. It continues to look in
the facet value for a witness if the self type is a facet value. Then
falls back to looking for an impl declaration. This step is no longer
done directly. Instead, we construct a ImplSymbolicWitness instruction
and evaluate it immediately for each interface that are in the query
facet type.

The ImplSymbolicWitness instruction, when evaluated, calls back to the
impl lookup code, with a query specific interface. There we resume back
into the same code path as from before, finding a witness in an impl
declaration. But we may return "found a non-final impl" instead of a
concrete witness. If eval receives this back, it evaluates to the
current ImplSymbolicWitness instruction as the resulting constant value.

To pass lookup failures back through eval, a result of InstId::None from
the second step of impl lookup will result in a non-constant value,
which is used as a signal back up the stack to the original impl lookup
function that the lookup failed. Using a non-constant value here would
break evaluation of the generic eval block if impl lookup could fail
there, however we know it will not since we only leave behind an
ImplSymbolicWitness instruction in the eval block if we found at least
one matching impl already, and we just want to look for a better match
with a more specific query.

We must take care to not store a reference into any value store across
computation in impl lookup, since impl lookup can recurse into itself
invalidate those stores. That includes the SpecificInterface obtained
from a SpecificInterfaceId, which impl lookup also inserts into the
store.

--- The long tail ---

Adding a new instruction and a new id type requires a myriad of changes
to support them:

We add Dump() support for SpecificInterfaceId. And fix a crash in Dump
for SpecificId::None. We also add MakeSpecificInterfaceId() for dumping
arbitrary ids.

The type of ImplSymbolicWitness is a new singleton builtin type
instruction called WitnessSymbolicType (like WitnessType is the type for
an ImplWitness).

Both ImplSymbolicWitness and WitnessSymbolicType are given `Value` as
their expression category as they are builtin constant values. And
BuildInfo() in TypeCompleter is taught about them both, returning a
`ValueRepr::Copy`.

WitnessSymbolicType is added to the set of SingletonInstKinds, so that
it can have a singleton instrution id as a static member.

Lower's BuildTypeForInst() is taught to make an empty struct for
WitnessSymbolicType, similar to WitnessType.

Instruction formatter (FormatterImpl) grows support for printing a
SpecificInterfaceId so that it can print both arguments of
ImplSymbolicWitness on the RHS when printing the SemIR instruction. To
print a SpecificInterfaceId, it prints both the interface id and the
specific id (if there is one). For example, for a query on a generic
interface `Z` with one parameter, the RHS includes the query, interface,
and specific:
```
%Z.impl_symbolic_witness: <symbolic witness> = impl_symbolic_witness %U, @Z, @Z(%U.as_type) [symbolic]
```

IdKind is extended to include SpecificInterfaceId.

InstFingerprinter is taught to look through SpecificInterfaceId and use
the interface and specific ids in the fingerprint.

InstNamer is taught about SpecificInterfaceId, counting the interfaces
when building an index. It is also tought about ImplSymbolicWitness,
using the name of the interface within and the `.impl_symbolic_witness`
suffix. For example, here the LHS is named after the interface in the
query:
```
%Z.impl_symbolic_witness: <symbolic witness> = impl_symbolic_witness %U, @Z, @Z(%U.as_type) [symbolic]
```

StringifyTypeExpr is taught about WitnessSymbolicType, which uses its IR
name since it's a singleton. And about ImplSymbolicWitness which uses
its constant value. The handling of ImplWitnessAccess also needed to be
adjusted, since it assumed that ImplWitnessAccess::witness_id would
always be a FacetAccessWitness, but it can now also be an
ImplSymbolicWitness. (It seems that the witness_id is also assigned
ImplWitness instructions, but those ImplWitnessAccess instructions don't
ever seem to get stringified in a diagnostic at this time.) At the
moment the ImplWitnessAccess with a symbolic witness is just stringified
as "<symbolic>", such as in:
```
x.carbon:1:2: error: cannot implicitly convert value of type `()` to `<symbolic>` [ConversionFailure]
  let a: C(D).(Z.X) = ();
                      ^~
```

There is a TODO left behind to include more information there.

The TypeStructure builder is made to handle WitnessSymbolicType and
WitnessType. These come up now in deduce where a generic impl will have
a ImplSymbolicWitness in a FacetValue for a generic self type. The query
may have a concrete ImplWitness in the same position. Since deduce tries
to deduce through the FacetValue, it tries to convert ImplWitness to
ImplSymbolicWitness, tries to do an impl lookup for `impl ImplWitness as
ImplicitAs(ImplSymbolicWitness)` and causes us to build type structures
with each of these.

Subst is updated to handle pushing and popping SpecificInterfaceId.
Without this, when finishing a generic's eval block, we would walk into
the ImplSymbolicWitness instruction, and its arguments, and fail to
recurse down into the SpecificInterfaceId. Then any specifics inside
would be left as "orphaned" without any generic id attached to them, and
we would never update the instructions in the SpecificInterface's
instructions (inside its own SpecificId) with new constant values when
evaluating the generic eval block against a specific. To do this we push
the specific_id inside the SpecificInterface, and when popping we pop
the specific_id then construct a new canonical SpecificInterface with it
and return that id.

We add support for importing ImplSymbolicWitness by importing its self
constant instruction and specific interface id. However we also had to
add import support for SpecificImplFunction, which can now appear in the
generic eval block for a generic impl declaration, and thus must be
imported with the declaration. This is done very similarly to
SpecificFunction, except the `type_id` is a singleton value.

---------

Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2025-03-26 15:10:23 +00:00

368 lines
12 KiB
C++

// Part of the Carbon Language project, under the Apache License v2.0 with LLVM
// Exceptions. See /LICENSE for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
#ifndef NDEBUG
#include "toolchain/sem_ir/dump.h"
#include "common/ostream.h"
#include "toolchain/sem_ir/stringify_type.h"
namespace Carbon::SemIR {
static auto DumpNameIfValid(const File& file, NameId name_id) -> void {
if (name_id.has_value()) {
llvm::errs() << " `" << file.names().GetFormatted(name_id) << "`";
}
}
static auto DumpNoNewline(const File& file, ConstantId const_id) -> void {
llvm::errs() << const_id;
if (const_id.is_symbolic()) {
llvm::errs() << ": "
<< file.constant_values().GetSymbolicConstant(const_id);
} else if (const_id.is_concrete()) {
llvm::errs() << ": "
<< file.insts().Get(
file.constant_values().GetInstId(const_id));
}
}
static auto DumpNoNewline(const File& file, InstId inst_id) -> void {
llvm::errs() << inst_id;
if (inst_id.has_value()) {
llvm::errs() << ": " << file.insts().Get(inst_id);
}
}
static auto DumpNoNewline(const File& file, InterfaceId interface_id) -> void {
llvm::errs() << interface_id;
if (interface_id.has_value()) {
const auto& interface = file.interfaces().Get(interface_id);
llvm::errs() << ": " << interface;
DumpNameIfValid(file, interface.name_id);
}
}
static auto DumpNoNewline(const File& file, SpecificId specific_id) -> void {
llvm::errs() << specific_id;
if (specific_id.has_value()) {
llvm::errs() << ": " << file.specifics().Get(specific_id);
}
}
LLVM_DUMP_METHOD auto Dump(const File& file, ClassId class_id) -> void {
llvm::errs() << class_id;
if (class_id.has_value()) {
const auto& class_obj = file.classes().Get(class_id);
llvm::errs() << ": " << class_obj;
DumpNameIfValid(file, class_obj.name_id);
}
llvm::errs() << '\n';
}
LLVM_DUMP_METHOD auto Dump(const File& file, ConstantId const_id) -> void {
DumpNoNewline(file, const_id);
llvm::errs() << '\n';
}
LLVM_DUMP_METHOD auto Dump(const File& file, EntityNameId entity_name_id)
-> void {
llvm::errs() << entity_name_id;
if (entity_name_id.has_value()) {
auto entity_name = file.entity_names().Get(entity_name_id);
llvm::errs() << ": " << entity_name;
DumpNameIfValid(file, entity_name.name_id);
}
llvm::errs() << '\n';
}
LLVM_DUMP_METHOD auto Dump(const File& file, FacetTypeId facet_type_id)
-> void {
llvm::errs() << facet_type_id;
if (facet_type_id.has_value()) {
const auto& facet_type = file.facet_types().Get(facet_type_id);
llvm::errs() << ": " << facet_type << '\n';
for (auto impls : facet_type.impls_constraints) {
llvm::errs() << " - ";
DumpNoNewline(file, impls.interface_id);
if (impls.specific_id.has_value()) {
llvm::errs() << "; ";
DumpNoNewline(file, impls.specific_id);
}
llvm::errs() << '\n';
}
for (auto rewrite : facet_type.rewrite_constraints) {
llvm::errs() << " - ";
Dump(file, rewrite.lhs_const_id);
llvm::errs() << " - ";
Dump(file, rewrite.rhs_const_id);
}
if (auto complete_id = file.complete_facet_types().TryGetId(facet_type_id);
complete_id.has_value()) {
llvm::errs() << "complete: ";
Dump(file, complete_id);
}
} else {
llvm::errs() << '\n';
}
}
LLVM_DUMP_METHOD auto Dump(const File& file, FunctionId function_id) -> void {
llvm::errs() << function_id;
if (function_id.has_value()) {
const auto& function = file.functions().Get(function_id);
llvm::errs() << ": " << function;
DumpNameIfValid(file, function.name_id);
}
llvm::errs() << '\n';
}
LLVM_DUMP_METHOD auto Dump(const File& file, GenericId generic_id) -> void {
llvm::errs() << generic_id;
if (generic_id.has_value()) {
llvm::errs() << ": " << file.generics().Get(generic_id);
}
llvm::errs() << '\n';
}
LLVM_DUMP_METHOD auto Dump(const File& file, ImplId impl_id) -> void {
llvm::errs() << impl_id;
if (impl_id.has_value()) {
llvm::errs() << ": " << file.impls().Get(impl_id);
}
llvm::errs() << '\n';
}
LLVM_DUMP_METHOD auto Dump(const File& file, InstBlockId inst_block_id)
-> void {
llvm::errs() << inst_block_id;
if (inst_block_id.has_value()) {
llvm::errs() << ":";
auto inst_block = file.inst_blocks().Get(inst_block_id);
for (auto inst_id : inst_block) {
llvm::errs() << "\n - ";
DumpNoNewline(file, inst_id);
}
}
llvm::errs() << '\n';
}
LLVM_DUMP_METHOD auto Dump(const File& file, InstId inst_id) -> void {
DumpNoNewline(file, inst_id);
llvm::errs() << '\n';
if (inst_id.has_value()) {
Inst inst = file.insts().Get(inst_id);
if (inst.type_id().has_value()) {
llvm::errs() << " - type ";
Dump(file, inst.type_id());
}
ConstantId const_id = file.constant_values().Get(inst_id);
if (const_id.has_value()) {
InstId const_inst_id = file.constant_values().GetInstId(const_id);
llvm::errs() << " - value ";
if (const_inst_id == inst_id) {
llvm::errs() << const_id << '\n';
} else {
Dump(file, const_id);
}
}
}
}
LLVM_DUMP_METHOD auto Dump(const File& file, InterfaceId interface_id) -> void {
DumpNoNewline(file, interface_id);
llvm::errs() << '\n';
}
LLVM_DUMP_METHOD auto Dump(const File& file, NameId name_id) -> void {
llvm::errs() << name_id;
DumpNameIfValid(file, name_id);
llvm::errs() << '\n';
}
LLVM_DUMP_METHOD auto Dump(const File& file, NameScopeId name_scope_id)
-> void {
llvm::errs() << name_scope_id;
if (name_scope_id.has_value()) {
const auto& name_scope = file.name_scopes().Get(name_scope_id);
llvm::errs() << ": " << name_scope;
if (name_scope.inst_id().has_value()) {
llvm::errs() << " " << file.insts().Get(name_scope.inst_id());
}
DumpNameIfValid(file, name_scope.name_id());
llvm::errs() << '\n';
for (const auto& entry : name_scope.entries()) {
llvm::errs() << " - " << entry.name_id;
DumpNameIfValid(file, entry.name_id);
llvm::errs() << ": ";
if (entry.result.is_poisoned()) {
llvm::errs() << "<poisoned>\n";
} else if (entry.result.is_found()) {
switch (entry.result.access_kind()) {
case AccessKind::Public:
llvm::errs() << "public ";
break;
case AccessKind::Protected:
llvm::errs() << "protected ";
break;
case AccessKind::Private:
llvm::errs() << "private ";
break;
}
DumpNoNewline(file, entry.result.target_inst_id());
llvm::errs() << "\n";
} else {
llvm::errs() << "<not-found>\n";
}
}
} else {
llvm::errs() << '\n';
}
}
LLVM_DUMP_METHOD auto Dump(const File& file,
CompleteFacetTypeId complete_facet_type_id) -> void {
llvm::errs() << complete_facet_type_id << "\n";
if (complete_facet_type_id.has_value()) {
const auto& complete_facet_type =
file.complete_facet_types().Get(complete_facet_type_id);
for (auto [i, req_interface] :
llvm::enumerate(complete_facet_type.required_interfaces)) {
llvm::errs() << " - ";
DumpNoNewline(file, req_interface.interface_id);
if (req_interface.specific_id.has_value()) {
llvm::errs() << "; ";
DumpNoNewline(file, req_interface.specific_id);
}
if (static_cast<int>(i) < complete_facet_type.num_to_impl) {
llvm::errs() << " (to impl)";
}
llvm::errs() << '\n';
}
}
}
LLVM_DUMP_METHOD auto Dump(const File& file, SpecificId specific_id) -> void {
DumpNoNewline(file, specific_id);
llvm::errs() << '\n';
if (specific_id.has_value()) {
Dump(file, file.specifics().Get(specific_id).args_id);
}
}
LLVM_DUMP_METHOD auto Dump(const File& file,
SpecificInterfaceId specific_interface_id) -> void {
const auto& interface = file.specific_interfaces().Get(specific_interface_id);
llvm::errs() << specific_interface_id << '\n';
llvm::errs() << " - interface: ";
DumpNoNewline(file, interface.interface_id);
llvm::errs() << '\n';
llvm::errs() << " - specific_id: ";
Dump(file, interface.specific_id);
}
LLVM_DUMP_METHOD auto Dump(const File& file,
StructTypeFieldsId struct_type_fields_id) -> void {
llvm::errs() << struct_type_fields_id;
if (struct_type_fields_id.has_value()) {
llvm::errs() << ":";
auto block = file.struct_type_fields().Get(struct_type_fields_id);
for (auto field : block) {
llvm::errs() << "\n - " << field;
DumpNameIfValid(file, field.name_id);
if (field.type_id.has_value()) {
InstId inst_id =
file.constant_values().GetInstId(field.type_id.AsConstantId());
llvm::errs() << ": " << StringifyTypeExpr(file, inst_id);
}
}
}
llvm::errs() << '\n';
}
LLVM_DUMP_METHOD auto Dump(const File& file, TypeBlockId type_block_id)
-> void {
llvm::errs() << type_block_id;
if (type_block_id.has_value()) {
llvm::errs() << ":\n";
auto type_block = file.type_blocks().Get(type_block_id);
for (auto type_id : type_block) {
llvm::errs() << " - ";
Dump(file, type_id);
}
} else {
llvm::errs() << '\n';
}
}
LLVM_DUMP_METHOD auto Dump(const File& file, TypeId type_id) -> void {
llvm::errs() << type_id;
if (type_id.has_value()) {
InstId inst_id = file.constant_values().GetInstId(type_id.AsConstantId());
llvm::errs() << ": " << StringifyTypeExpr(file, inst_id) << "; "
<< file.insts().Get(inst_id);
}
llvm::errs() << '\n';
}
// Functions that can be used instead of the corresponding constructor, which is
// unavailable during debugging.
LLVM_DUMP_METHOD static auto MakeClassId(int id) -> ClassId {
return ClassId(id);
}
LLVM_DUMP_METHOD static auto MakeConstantId(int id) -> ConstantId {
return ConstantId(id);
}
LLVM_DUMP_METHOD static auto MakeSymbolicConstantId(int id) -> ConstantId {
return ConstantId::ForSymbolicConstantIndex(id);
}
LLVM_DUMP_METHOD static auto MakeEntityNameId(int id) -> EntityNameId {
return EntityNameId(id);
}
LLVM_DUMP_METHOD static auto MakeFacetTypeId(int id) -> FacetTypeId {
return FacetTypeId(id);
}
LLVM_DUMP_METHOD static auto MakeFunctionId(int id) -> FunctionId {
return FunctionId(id);
}
LLVM_DUMP_METHOD static auto MakeGenericId(int id) -> GenericId {
return GenericId(id);
}
LLVM_DUMP_METHOD static auto MakeImplId(int id) -> ImplId { return ImplId(id); }
LLVM_DUMP_METHOD static auto MakeInstBlockId(int id) -> InstBlockId {
return InstBlockId(id);
}
LLVM_DUMP_METHOD static auto MakeInstId(int id) -> InstId { return InstId(id); }
LLVM_DUMP_METHOD static auto MakeInterfaceId(int id) -> InterfaceId {
return InterfaceId(id);
}
LLVM_DUMP_METHOD static auto MakeNameId(int id) -> NameId { return NameId(id); }
LLVM_DUMP_METHOD static auto MakeNameScopeId(int id) -> NameScopeId {
return NameScopeId(id);
}
LLVM_DUMP_METHOD static auto MakeCompleteFacetTypeId(int id)
-> CompleteFacetTypeId {
return CompleteFacetTypeId(id);
}
LLVM_DUMP_METHOD static auto MakeSpecificId(int id) -> SpecificId {
return SpecificId(id);
}
LLVM_DUMP_METHOD static auto MakeSpecificInterfaceId(int id)
-> SpecificInterfaceId {
return SpecificInterfaceId(id);
}
LLVM_DUMP_METHOD static auto MakeStructTypeFieldsId(int id)
-> StructTypeFieldsId {
return StructTypeFieldsId(id);
}
LLVM_DUMP_METHOD static auto MakeTypeBlockId(int id) -> TypeBlockId {
return TypeBlockId(id);
}
LLVM_DUMP_METHOD static auto MakeTypeId(int id) -> TypeId { return TypeId(id); }
} // namespace Carbon::SemIR
#endif // NDEBUG