From e6634d240f559c0138bb43da9ce0c0850f90c4eb Mon Sep 17 00:00:00 2001 From: Jon Ross-Perkins Date: Tue, 24 Oct 2023 14:05:46 -0700 Subject: [PATCH] Make SemIR::File access more terse. (#3331) 1. In general, `semantics_ir` -> `sem_ir`, to match the directory name. 2. For the list of `ValueStore`-related accessors on `SemIR::File`, add them to `check`'s `Context` object, shortening access. --- toolchain/check/check.cpp | 22 ++- toolchain/check/context.cpp | 123 ++++++------- toolchain/check/context.h | 29 ++- toolchain/check/convert.cpp | 166 +++++++++--------- toolchain/check/declaration_name_stack.cpp | 17 +- toolchain/check/handle_array.cpp | 5 +- toolchain/check/handle_call_expression.cpp | 6 +- toolchain/check/handle_class.cpp | 24 +-- toolchain/check/handle_function.cpp | 45 ++--- toolchain/check/handle_if_expression.cpp | 3 +- toolchain/check/handle_index.cpp | 24 ++- toolchain/check/handle_let.cpp | 4 +- toolchain/check/handle_name.cpp | 44 ++--- toolchain/check/handle_namespace.cpp | 2 +- toolchain/check/handle_operator.cpp | 49 +++--- toolchain/check/handle_paren.cpp | 4 +- toolchain/check/handle_pattern_binding.cpp | 6 +- toolchain/check/handle_statement.cpp | 12 +- toolchain/check/handle_struct.cpp | 3 +- toolchain/check/handle_variable.cpp | 2 +- toolchain/check/node_block_stack.cpp | 6 +- toolchain/check/node_block_stack.h | 8 +- toolchain/check/pending_block.h | 13 +- toolchain/lower/file_context.cpp | 61 +++---- toolchain/lower/file_context.h | 7 +- toolchain/lower/function_context.cpp | 8 +- toolchain/lower/function_context.h | 10 +- toolchain/lower/handle.cpp | 95 +++++----- .../lower/handle_expression_category.cpp | 13 +- toolchain/lower/lower.cpp | 5 +- toolchain/lower/lower.h | 3 +- toolchain/sem_ir/file.h | 1 + toolchain/sem_ir/formatter.cpp | 120 ++++++------- toolchain/sem_ir/formatter.h | 2 +- 34 files changed, 433 insertions(+), 509 deletions(-) diff --git a/toolchain/check/check.cpp b/toolchain/check/check.cpp index 6b77447abe09..432658542016 100644 --- a/toolchain/check/check.cpp +++ b/toolchain/check/check.cpp @@ -16,15 +16,13 @@ auto CheckParseTree(SharedValueStores& value_stores, const Lex::TokenizedBuffer& tokens, const Parse::Tree& parse_tree, DiagnosticConsumer& consumer, llvm::raw_ostream* vlog_stream) -> SemIR::File { - auto semantics_ir = - SemIR::File(value_stores, tokens.filename().str(), &builtin_ir); + auto sem_ir = SemIR::File(value_stores, tokens.filename().str(), &builtin_ir); Parse::NodeLocationTranslator translator(&tokens, &parse_tree); ErrorTrackingDiagnosticConsumer err_tracker(consumer); DiagnosticEmitter emitter(translator, err_tracker); - Check::Context context(tokens, emitter, parse_tree, semantics_ir, - vlog_stream); + Check::Context context(tokens, emitter, parse_tree, sem_ir, vlog_stream); PrettyStackTraceFunction context_dumper( [&](llvm::raw_ostream& output) { context.PrintForStackDump(output); }); @@ -43,8 +41,8 @@ auto CheckParseTree(SharedValueStores& value_stores, if (!Check::Handle##Name(context, parse_node)) { \ CARBON_CHECK(err_tracker.seen_error()) \ << "Handle" #Name " returned false without printing a diagnostic"; \ - semantics_ir.set_has_errors(true); \ - return semantics_ir; \ + sem_ir.set_has_errors(true); \ + return sem_ir; \ } \ break; \ } @@ -53,21 +51,21 @@ auto CheckParseTree(SharedValueStores& value_stores, } // Pop information for the file-level scope. - semantics_ir.set_top_node_block_id(context.node_block_stack().Pop()); + sem_ir.set_top_node_block_id(context.node_block_stack().Pop()); context.PopScope(); context.VerifyOnFinish(); - semantics_ir.set_has_errors(err_tracker.seen_error()); + sem_ir.set_has_errors(err_tracker.seen_error()); #ifndef NDEBUG - if (auto verify = semantics_ir.Verify(); !verify.ok()) { - CARBON_FATAL() << semantics_ir - << "Built invalid semantics IR: " << verify.error() << "\n"; + if (auto verify = sem_ir.Verify(); !verify.ok()) { + CARBON_FATAL() << sem_ir << "Built invalid semantics IR: " << verify.error() + << "\n"; } #endif - return semantics_ir; + return sem_ir; } } // namespace Carbon::Check diff --git a/toolchain/check/context.cpp b/toolchain/check/context.cpp index 5a18ac27310f..b32d07b49167 100644 --- a/toolchain/check/context.cpp +++ b/toolchain/check/context.cpp @@ -21,17 +21,17 @@ namespace Carbon::Check { Context::Context(const Lex::TokenizedBuffer& tokens, DiagnosticEmitter& emitter, - const Parse::Tree& parse_tree, SemIR::File& semantics_ir, + const Parse::Tree& parse_tree, SemIR::File& sem_ir, llvm::raw_ostream* vlog_stream) : tokens_(&tokens), emitter_(&emitter), parse_tree_(&parse_tree), - semantics_ir_(&semantics_ir), + sem_ir_(&sem_ir), vlog_stream_(vlog_stream), node_stack_(parse_tree, vlog_stream), - node_block_stack_("node_block_stack_", semantics_ir, vlog_stream), - params_or_args_stack_("params_or_args_stack_", semantics_ir, vlog_stream), - args_type_info_stack_("args_type_info_stack_", semantics_ir, vlog_stream), + node_block_stack_("node_block_stack_", sem_ir, vlog_stream), + params_or_args_stack_("params_or_args_stack_", sem_ir, vlog_stream), + args_type_info_stack_("args_type_info_stack_", sem_ir, vlog_stream), declaration_name_stack_(this) { // Inserts the "Error" and "Type" types as "used types" so that // canonicalization can skip them. We don't emit either for lowering. @@ -75,7 +75,7 @@ auto Context::DiagnoseDuplicateName(Parse::Node parse_node, "Duplicate name being declared in the same scope."); CARBON_DIAGNOSTIC(NameDeclarationPrevious, Note, "Name is previously declared here."); - auto prev_def = semantics_ir_->nodes().Get(prev_def_id); + auto prev_def = nodes().Get(prev_def_id); emitter_->Build(parse_node, NameDeclarationDuplicate) .Note(prev_def.parse_node(), NameDeclarationPrevious) .Emit(); @@ -85,18 +85,16 @@ auto Context::DiagnoseNameNotFound(Parse::Node parse_node, StringId name_id) -> void { CARBON_DIAGNOSTIC(NameNotFound, Error, "Name `{0}` not found.", llvm::StringRef); - emitter_->Emit(parse_node, NameNotFound, - semantics_ir_->strings().Get(name_id)); + emitter_->Emit(parse_node, NameNotFound, strings().Get(name_id)); } auto Context::NoteIncompleteClass(SemIR::ClassId class_id, DiagnosticBuilder& builder) -> void { CARBON_DIAGNOSTIC(ClassForwardDeclaredHere, Note, "Class was forward declared here."); - const auto& class_info = semantics_ir().classes().Get(class_id); - builder.Note( - semantics_ir().nodes().Get(class_info.declaration_id).parse_node(), - ClassForwardDeclaredHere); + const auto& class_info = classes().Get(class_id); + builder.Note(nodes().Get(class_info.declaration_id).parse_node(), + ClassForwardDeclaredHere); } auto Context::AddNameToLookup(Parse::Node name_node, StringId name_id, @@ -120,12 +118,12 @@ auto Context::LookupName(Parse::Node parse_node, StringId name_id, return SemIR::NodeId::BuiltinError; } CARBON_CHECK(!it->second.empty()) - << "Should have been erased: " << semantics_ir_->strings().Get(name_id); + << "Should have been erased: " << strings().Get(name_id); // TODO: Check for ambiguous lookups. return it->second.back(); } else { - const auto& scope = semantics_ir_->name_scopes().Get(scope_id); + const auto& scope = name_scopes().Get(scope_id); auto it = scope.find(name_id); if (it == scope.end()) { if (print_diagnostics) { @@ -156,9 +154,7 @@ auto Context::PopScope() -> void { } auto Context::FollowNameReferences(SemIR::NodeId node_id) -> SemIR::NodeId { - while ( - auto name_ref = - semantics_ir().nodes().Get(node_id).TryAs()) { + while (auto name_ref = nodes().Get(node_id).TryAs()) { node_id = name_ref->value_id; } return node_id; @@ -171,7 +167,7 @@ static auto AddDominatedBlockAndBranchImpl(Context& context, if (!context.node_block_stack().is_current_block_reachable()) { return SemIR::NodeBlockId::Unreachable; } - auto block_id = context.semantics_ir().node_blocks().AddDefaultValue(); + auto block_id = context.node_blocks().AddDefaultValue(); context.AddNode(BranchNode{parse_node, block_id, args...}); return block_id; } @@ -203,7 +199,7 @@ auto Context::AddConvergenceBlockAndPush(Parse::Node parse_node, int num_blocks) for ([[maybe_unused]] auto _ : llvm::seq(num_blocks)) { if (node_block_stack().is_current_block_reachable()) { if (new_block_id == SemIR::NodeBlockId::Unreachable) { - new_block_id = semantics_ir().node_blocks().AddDefaultValue(); + new_block_id = node_blocks().AddDefaultValue(); } AddNode(SemIR::Branch{parse_node, new_block_id}); } @@ -221,7 +217,7 @@ auto Context::AddConvergenceBlockWithArgAndPush( for (auto arg_id : block_args) { if (node_block_stack().is_current_block_reachable()) { if (new_block_id == SemIR::NodeBlockId::Unreachable) { - new_block_id = semantics_ir().node_blocks().AddDefaultValue(); + new_block_id = node_blocks().AddDefaultValue(); } AddNode(SemIR::BranchWithArg{parse_node, new_block_id, arg_id}); } @@ -230,8 +226,7 @@ auto Context::AddConvergenceBlockWithArgAndPush( node_block_stack().Push(new_block_id); // Acquire the result value. - SemIR::TypeId result_type_id = - semantics_ir().nodes().Get(*block_args.begin()).type_id(); + SemIR::TypeId result_type_id = nodes().Get(*block_args.begin()).type_id(); return AddNode(SemIR::BlockArg{parse_node, result_type_id, new_block_id}); } @@ -246,12 +241,10 @@ auto Context::AddCurrentCodeBlockToFunction() -> void { } auto function_id = - semantics_ir() - .nodes() + nodes() .GetAs(return_scope_stack().back()) .function_id; - semantics_ir() - .functions() + functions() .Get(function_id) .body_block_ids.push_back(node_block_stack().PeekOrAdd()); } @@ -267,7 +260,7 @@ auto Context::is_current_position_reachable() -> bool { if (block_contents.empty()) { return true; } - const auto& last_node = semantics_ir().nodes().Get(block_contents.back()); + const auto& last_node = nodes().Get(block_contents.back()); return last_node.kind().terminator_kind() != SemIR::TerminatorKind::Terminator; } @@ -329,7 +322,7 @@ class TypeCompleter { private: // Adds `type_id` to the work list, if it's not already complete. auto Push(SemIR::TypeId type_id) -> void { - if (!context_.semantics_ir().IsTypeComplete(type_id)) { + if (!context_.sem_ir().IsTypeComplete(type_id)) { work_list_.push_back({type_id, Phase::AddNestedIncompleteTypes}); } } @@ -340,13 +333,13 @@ class TypeCompleter { // We might have enqueued the same type more than once. Just skip the // type if it's already complete. - if (context_.semantics_ir().IsTypeComplete(type_id)) { + if (context_.sem_ir().IsTypeComplete(type_id)) { work_list_.pop_back(); return true; } - auto node_id = context_.semantics_ir().GetTypeAllowBuiltinTypes(type_id); - auto node = context_.semantics_ir().nodes().Get(node_id); + auto node_id = context_.sem_ir().GetTypeAllowBuiltinTypes(type_id); + auto node = context_.nodes().Get(node_id); auto old_work_list_size = work_list_.size(); @@ -363,7 +356,7 @@ class TypeCompleter { case Phase::BuildValueRepresentation: { auto value_rep = BuildValueRepresentation(type_id, node); - context_.semantics_ir().CompleteType(type_id, value_rep); + context_.sem_ir().CompleteType(type_id, value_rep); CARBON_CHECK(old_work_list_size == work_list_.size()) << "BuildValueRepresentation should not change work items"; work_list_.pop_back(); @@ -371,15 +364,15 @@ class TypeCompleter { // Also complete the value representation type, if necessary. This // should never fail: the value representation shouldn't require any // additional nested types to be complete. - if (!context_.semantics_ir().IsTypeComplete(value_rep.type_id)) { + if (!context_.sem_ir().IsTypeComplete(value_rep.type_id)) { work_list_.push_back( {value_rep.type_id, Phase::BuildValueRepresentation}); } // For a pointer representation, the pointee also needs to be complete. if (value_rep.kind == SemIR::ValueRepresentation::Pointer) { auto pointee_type_id = - context_.semantics_ir().GetPointeeType(value_rep.type_id); - if (!context_.semantics_ir().IsTypeComplete(pointee_type_id)) { + context_.sem_ir().GetPointeeType(value_rep.type_id); + if (!context_.sem_ir().IsTypeComplete(pointee_type_id)) { work_list_.push_back( {pointee_type_id, Phase::BuildValueRepresentation}); } @@ -400,17 +393,16 @@ class TypeCompleter { break; case SemIR::StructType::Kind: - for (auto field_id : context_.semantics_ir().node_blocks().Get( + for (auto field_id : context_.node_blocks().Get( type_node.As().fields_id)) { - Push(context_.semantics_ir() - .nodes() + Push(context_.nodes() .GetAs(field_id) .field_type_id); } break; case SemIR::TupleType::Kind: - for (auto element_type_id : context_.semantics_ir().type_blocks().Get( + for (auto element_type_id : context_.type_blocks().Get( type_node.As().elements_id)) { Push(element_type_id); } @@ -465,10 +457,9 @@ class TypeCompleter { // Gets the value representation of a nested type, which should already be // complete. auto GetNestedValueRepresentation(SemIR::TypeId nested_type_id) const { - CARBON_CHECK(context_.semantics_ir().IsTypeComplete(nested_type_id)) + CARBON_CHECK(context_.sem_ir().IsTypeComplete(nested_type_id)) << "Nested type should already be complete"; - auto value_rep = - context_.semantics_ir().GetValueRepresentation(nested_type_id); + auto value_rep = context_.sem_ir().GetValueRepresentation(nested_type_id); CARBON_CHECK(value_rep.kind != SemIR::ValueRepresentation::Unknown) << "Complete type should have a value representation"; return value_rep; @@ -477,7 +468,7 @@ class TypeCompleter { auto BuildCrossReferenceValueRepresentation(SemIR::TypeId type_id, SemIR::CrossReference xref) const -> SemIR::ValueRepresentation { - auto xref_node = context_.semantics_ir() + auto xref_node = context_.sem_ir() .GetCrossReferenceIR(xref.ir_id) .nodes() .Get(xref.node_id); @@ -515,8 +506,7 @@ class TypeCompleter { SemIR::StructType struct_type) const -> SemIR::ValueRepresentation { // TODO: Share code with tuples. - auto fields = - context_.semantics_ir().node_blocks().Get(struct_type.fields_id); + auto fields = context_.node_blocks().Get(struct_type.fields_id); if (fields.empty()) { return MakeEmptyRepresentation(struct_type.parse_node); } @@ -527,9 +517,7 @@ class TypeCompleter { value_rep_fields.reserve(fields.size()); bool same_as_object_rep = true; for (auto field_id : fields) { - auto field = - context_.semantics_ir().nodes().GetAs( - field_id); + auto field = context_.nodes().GetAs(field_id); auto field_value_rep = GetNestedValueRepresentation(field.field_type_id); if (field_value_rep.type_id != field.field_type_id) { same_as_object_rep = false; @@ -539,12 +527,11 @@ class TypeCompleter { value_rep_fields.push_back(field_id); } - auto value_rep = - same_as_object_rep - ? type_id - : context_.CanonicalizeStructType( - struct_type.parse_node, - context_.semantics_ir().node_blocks().Add(value_rep_fields)); + auto value_rep = same_as_object_rep + ? type_id + : context_.CanonicalizeStructType( + struct_type.parse_node, + context_.node_blocks().Add(value_rep_fields)); if (fields.size() == 1) { // The value representation for a struct with a single field is a // struct containing the value representation of the field. @@ -560,8 +547,7 @@ class TypeCompleter { SemIR::TupleType tuple_type) const -> SemIR::ValueRepresentation { // TODO: Share code with structs. - auto elements = - context_.semantics_ir().type_blocks().Get(tuple_type.elements_id); + auto elements = context_.type_blocks().Get(tuple_type.elements_id); if (elements.empty()) { return MakeEmptyRepresentation(tuple_type.parse_node); } @@ -729,7 +715,7 @@ auto Context::CanonicalizeTypeImpl( } auto node_id = make_node(); - auto type_id = semantics_ir_->types().Add({.node_id = node_id}); + auto type_id = types().Add({.node_id = node_id}); CARBON_CHECK(canonical_types_.insert({node_id, type_id}).second); type_node_storage_.push_back( std::make_unique(canonical_id, type_id)); @@ -762,8 +748,7 @@ static auto ProfileType(Context& semantics_context, SemIR::Node node, case SemIR::ArrayType::Kind: { auto array_type = node.As(); canonical_id.AddInteger( - semantics_context.semantics_ir().GetArrayBoundValue( - array_type.bound_id)); + semantics_context.sem_ir().GetArrayBoundValue(array_type.bound_id)); canonical_id.AddInteger(array_type.element_type_id.index); break; } @@ -791,19 +776,18 @@ static auto ProfileType(Context& semantics_context, SemIR::Node node, canonical_id.AddInteger(node.As().pointee_id.index); break; case SemIR::StructType::Kind: { - auto fields = semantics_context.semantics_ir().node_blocks().Get( + auto fields = semantics_context.node_blocks().Get( node.As().fields_id); for (const auto& field_id : fields) { - auto field = semantics_context.semantics_ir() - .nodes() - .GetAs(field_id); + auto field = + semantics_context.nodes().GetAs(field_id); canonical_id.AddInteger(field.name_id.index); canonical_id.AddInteger(field.field_type_id.index); } break; } case SemIR::TupleType::Kind: - ProfileTupleType(semantics_context.semantics_ir().type_blocks().Get( + ProfileTupleType(semantics_context.type_blocks().Get( node.As().elements_id), canonical_id); break; @@ -829,7 +813,7 @@ auto Context::CanonicalizeType(SemIR::NodeId node_id) -> SemIR::TypeId { return it->second; } - auto node = semantics_ir_->nodes().Get(node_id); + auto node = nodes().Get(node_id); auto profile_node = [&](llvm::FoldingSetNodeID& canonical_id) { ProfileType(*this, node, canonical_id); }; @@ -852,9 +836,8 @@ auto Context::CanonicalizeTupleType(Parse::Node parse_node, ProfileTupleType(type_ids, canonical_id); }; auto make_tuple_node = [&] { - return AddNode( - SemIR::TupleType{parse_node, SemIR::TypeId::TypeType, - semantics_ir_->type_blocks().Add(type_ids)}); + return AddNode(SemIR::TupleType{parse_node, SemIR::TypeId::TypeType, + type_blocks().Add(type_ids)}); }; return CanonicalizeTypeImpl(SemIR::TupleType::Kind, profile_tuple, make_tuple_node); @@ -876,8 +859,8 @@ auto Context::GetPointerType(Parse::Node parse_node, } auto Context::GetUnqualifiedType(SemIR::TypeId type_id) -> SemIR::TypeId { - SemIR::Node type_node = semantics_ir_->nodes().Get( - semantics_ir_->GetTypeAllowBuiltinTypes(type_id)); + SemIR::Node type_node = + nodes().Get(sem_ir_->GetTypeAllowBuiltinTypes(type_id)); if (auto const_type = type_node.TryAs()) { return const_type->inner_id; } diff --git a/toolchain/check/context.h b/toolchain/check/context.h index fb140a7a0ddc..57a1b71cf120 100644 --- a/toolchain/check/context.h +++ b/toolchain/check/context.h @@ -202,7 +202,7 @@ class Context { auto parse_tree() -> const Parse::Tree& { return *parse_tree_; } - auto semantics_ir() -> SemIR::File& { return *semantics_ir_; } + auto sem_ir() -> SemIR::File& { return *sem_ir_; } auto node_stack() -> NodeStack& { return node_stack_; } @@ -224,6 +224,31 @@ class Context { return declaration_name_stack_; } + // Directly expose SemIR::File data accessors for brevity in calls. + auto integers() -> ValueStore& { return sem_ir().integers(); } + auto reals() -> ValueStore& { return sem_ir().reals(); } + auto strings() -> ValueStore& { return sem_ir().strings(); } + auto functions() -> ValueStore& { + return sem_ir().functions(); + } + auto classes() -> ValueStore& { + return sem_ir().classes(); + } + auto name_scopes() -> SemIR::NameScopeStore& { + return sem_ir().name_scopes(); + } + auto types() -> ValueStore& { + return sem_ir().types(); + } + auto type_blocks() + -> SemIR::BlockValueStore& { + return sem_ir().type_blocks(); + } + auto nodes() -> SemIR::NodeStore& { return sem_ir().nodes(); } + auto node_blocks() -> SemIR::NodeBlockStore& { + return sem_ir().node_blocks(); + } + private: // A FoldingSet node for a type. class TypeNode : public llvm::FastFoldingSetNode { @@ -283,7 +308,7 @@ class Context { const Parse::Tree* parse_tree_; // The SemIR::File being added to. - SemIR::File* semantics_ir_; + SemIR::File* sem_ir_; // Whether to print verbose output. llvm::raw_ostream* vlog_stream_; diff --git a/toolchain/check/convert.cpp b/toolchain/check/convert.cpp index 7e071e4f7957..689a2607782a 100644 --- a/toolchain/check/convert.cpp +++ b/toolchain/check/convert.cpp @@ -21,10 +21,10 @@ namespace Carbon::Check { // Given an initializing expression, find its return slot. Returns `Invalid` if // there is no return slot, because the initialization is not performed in // place. -static auto FindReturnSlotForInitializer(SemIR::File& semantics_ir, +static auto FindReturnSlotForInitializer(SemIR::File& sem_ir, SemIR::NodeId init_id) -> SemIR::NodeId { - SemIR::Node init = semantics_ir.nodes().Get(init_id); + SemIR::Node init = sem_ir.nodes().Get(init_id); switch (init.kind()) { default: CARBON_FATAL() << "Initialization from unexpected node " << init; @@ -42,15 +42,15 @@ static auto FindReturnSlotForInitializer(SemIR::File& semantics_ir, case SemIR::Call::Kind: { auto call = init.As(); - if (!SemIR::GetInitializingRepresentation(semantics_ir, call.type_id) + if (!SemIR::GetInitializingRepresentation(sem_ir, call.type_id) .has_return_slot()) { return SemIR::NodeId::Invalid; } - return semantics_ir.node_blocks().Get(call.args_id).back(); + return sem_ir.node_blocks().Get(call.args_id).back(); } case SemIR::ArrayInit::Kind: { - return semantics_ir.node_blocks() + return sem_ir.node_blocks() .Get(init.As().inits_and_return_slot_id) .back(); } @@ -58,17 +58,17 @@ static auto FindReturnSlotForInitializer(SemIR::File& semantics_ir, } // Marks the initializer `init_id` as initializing `target_id`. -static auto MarkInitializerFor(SemIR::File& semantics_ir, SemIR::NodeId init_id, +static auto MarkInitializerFor(SemIR::File& sem_ir, SemIR::NodeId init_id, SemIR::NodeId target_id, PendingBlock& target_block) -> void { - auto return_slot_id = FindReturnSlotForInitializer(semantics_ir, init_id); + auto return_slot_id = FindReturnSlotForInitializer(sem_ir, init_id); if (return_slot_id.is_valid()) { // Replace the temporary in the return slot with a reference to our target. - CARBON_CHECK(semantics_ir.nodes().Get(return_slot_id).kind() == + CARBON_CHECK(sem_ir.nodes().Get(return_slot_id).kind() == SemIR::TemporaryStorage::Kind) << "Return slot for initializer does not contain a temporary; " << "initialized multiple times? Have " - << semantics_ir.nodes().Get(return_slot_id); + << sem_ir.nodes().Get(return_slot_id); target_block.MergeReplacing(return_slot_id, target_id); } } @@ -80,16 +80,16 @@ static auto MarkInitializerFor(SemIR::File& semantics_ir, SemIR::NodeId init_id, // return value will be `SemIR::NodeId::Invalid`. static auto FinalizeTemporary(Context& context, SemIR::NodeId init_id, bool discarded) -> SemIR::NodeId { - auto& semantics_ir = context.semantics_ir(); - auto return_slot_id = FindReturnSlotForInitializer(semantics_ir, init_id); + auto& sem_ir = context.sem_ir(); + auto return_slot_id = FindReturnSlotForInitializer(sem_ir, init_id); if (return_slot_id.is_valid()) { // The return slot should already have a materialized temporary in it. - CARBON_CHECK(semantics_ir.nodes().Get(return_slot_id).kind() == + CARBON_CHECK(sem_ir.nodes().Get(return_slot_id).kind() == SemIR::TemporaryStorage::Kind) << "Return slot for initializer does not contain a temporary; " << "initialized multiple times? Have " - << semantics_ir.nodes().Get(return_slot_id); - auto init = semantics_ir.nodes().Get(init_id); + << sem_ir.nodes().Get(return_slot_id); + auto init = sem_ir.nodes().Get(init_id); return context.AddNode(SemIR::Temporary{init.parse_node(), init.type_id(), return_slot_id, init_id}); } @@ -104,7 +104,7 @@ static auto FinalizeTemporary(Context& context, SemIR::NodeId init_id, // TODO: Consider using an invalid ID to mean that we immediately // materialize and initialize a temporary, rather than two separate // nodes. - auto init = semantics_ir.nodes().Get(init_id); + auto init = sem_ir.nodes().Get(init_id); auto temporary_id = context.AddNode( SemIR::TemporaryStorage{init.parse_node(), init.type_id()}); return context.AddNode(SemIR::Temporary{init.parse_node(), init.type_id(), @@ -115,7 +115,7 @@ static auto FinalizeTemporary(Context& context, SemIR::NodeId init_id, // an initializing expression. static auto MaterializeIfInitializing(Context& context, SemIR::NodeId expr_id) -> SemIR::NodeId { - if (GetExpressionCategory(context.semantics_ir(), expr_id) == + if (GetExpressionCategory(context.sem_ir(), expr_id) == SemIR::ExpressionCategory::Initializing) { return FinalizeTemporary(context, expr_id, /*discarded=*/false); } @@ -134,7 +134,7 @@ static auto MakeElemAccessNode(Context& context, Parse::Node parse_node, // special case. auto index_id = block.AddNode(SemIR::IntegerLiteral{ parse_node, context.GetBuiltinType(SemIR::BuiltinKind::IntegerType), - context.semantics_ir().integers().Add(llvm::APInt(32, i))}); + context.sem_ir().integers().Add(llvm::APInt(32, i))}); return block.AddNode( AccessNodeT{parse_node, elem_type_id, aggregate_id, index_id}); } else { @@ -234,24 +234,23 @@ static auto ConvertTupleToArray(Context& context, SemIR::TupleType tuple_type, SemIR::ArrayType array_type, SemIR::NodeId value_id, ConversionTarget target) -> SemIR::NodeId { - auto& semantics_ir = context.semantics_ir(); - auto tuple_elem_types = - semantics_ir.type_blocks().Get(tuple_type.elements_id); + auto& sem_ir = context.sem_ir(); + auto tuple_elem_types = sem_ir.type_blocks().Get(tuple_type.elements_id); - auto value = semantics_ir.nodes().Get(value_id); + auto value = sem_ir.nodes().Get(value_id); // If we're initializing from a tuple literal, we will use its elements // directly. Otherwise, materialize a temporary if needed and index into the // result. llvm::ArrayRef literal_elems; if (auto tuple_literal = value.TryAs()) { - literal_elems = semantics_ir.node_blocks().Get(tuple_literal->elements_id); + literal_elems = sem_ir.node_blocks().Get(tuple_literal->elements_id); } else { value_id = MaterializeIfInitializing(context, value_id); } // Check that the tuple is the right size. - uint64_t array_bound = semantics_ir.GetArrayBoundValue(array_type.bound_id); + uint64_t array_bound = sem_ir.GetArrayBoundValue(array_type.bound_id); if (tuple_elem_types.size() != array_bound) { CARBON_DIAGNOSTIC( ArrayInitFromLiteralArgCountMismatch, Error, @@ -306,9 +305,9 @@ static auto ConvertTupleToArray(Context& context, SemIR::TupleType tuple_type, target_block->InsertHere(); inits.push_back(return_slot_id); - return context.AddNode( - SemIR::ArrayInit{value.parse_node(), target.type_id, value_id, - semantics_ir.node_blocks().Add(inits)}); + return context.AddNode(SemIR::ArrayInit{value.parse_node(), target.type_id, + value_id, + sem_ir.node_blocks().Add(inits)}); } // Performs a conversion from a tuple to a tuple type. Does not perform a @@ -317,11 +316,11 @@ static auto ConvertTupleToTuple(Context& context, SemIR::TupleType src_type, SemIR::TupleType dest_type, SemIR::NodeId value_id, ConversionTarget target) -> SemIR::NodeId { - auto& semantics_ir = context.semantics_ir(); - auto src_elem_types = semantics_ir.type_blocks().Get(src_type.elements_id); - auto dest_elem_types = semantics_ir.type_blocks().Get(dest_type.elements_id); + auto& sem_ir = context.sem_ir(); + auto src_elem_types = sem_ir.type_blocks().Get(src_type.elements_id); + auto dest_elem_types = sem_ir.type_blocks().Get(dest_type.elements_id); - auto value = semantics_ir.nodes().Get(value_id); + auto value = sem_ir.nodes().Get(value_id); // If we're initializing from a tuple literal, we will use its elements // directly. Otherwise, materialize a temporary if needed and index into the @@ -330,7 +329,7 @@ static auto ConvertTupleToTuple(Context& context, SemIR::TupleType src_type, auto literal_elems_id = SemIR::NodeBlockId::Invalid; if (auto tuple_literal = value.TryAs()) { literal_elems_id = tuple_literal->elements_id; - literal_elems = semantics_ir.node_blocks().Get(literal_elems_id); + literal_elems = sem_ir.node_blocks().Get(literal_elems_id); } else { value_id = MaterializeIfInitializing(context, value_id); } @@ -353,16 +352,15 @@ static auto ConvertTupleToTuple(Context& context, SemIR::TupleType src_type, bool is_init = target.is_initializer(); ConversionTarget::Kind inner_kind = !is_init ? ConversionTarget::Value - : SemIR::GetInitializingRepresentation(semantics_ir, target.type_id) - .kind == SemIR::InitializingRepresentation::InPlace + : SemIR::GetInitializingRepresentation(sem_ir, target.type_id).kind == + SemIR::InitializingRepresentation::InPlace ? ConversionTarget::FullInitializer : ConversionTarget::Initializer; // Initialize each element of the destination from the corresponding element // of the source. // TODO: Annotate diagnostics coming from here with the element index. - CopyOnWriteBlock new_block(semantics_ir, literal_elems_id, - src_elem_types.size()); + CopyOnWriteBlock new_block(sem_ir, literal_elems_id, src_elem_types.size()); for (auto [i, src_type_id, dest_type_id] : llvm::enumerate(src_elem_types, dest_elem_types)) { // TODO: This call recurses back into conversion. Switch to an iterative @@ -391,11 +389,11 @@ static auto ConvertStructToStruct(Context& context, SemIR::StructType src_type, SemIR::StructType dest_type, SemIR::NodeId value_id, ConversionTarget target) -> SemIR::NodeId { - auto& semantics_ir = context.semantics_ir(); - auto src_elem_fields = semantics_ir.node_blocks().Get(src_type.fields_id); - auto dest_elem_fields = semantics_ir.node_blocks().Get(dest_type.fields_id); + auto& sem_ir = context.sem_ir(); + auto src_elem_fields = sem_ir.node_blocks().Get(src_type.fields_id); + auto dest_elem_fields = sem_ir.node_blocks().Get(dest_type.fields_id); - auto value = semantics_ir.nodes().Get(value_id); + auto value = sem_ir.nodes().Get(value_id); // If we're initializing from a struct literal, we will use its elements // directly. Otherwise, materialize a temporary if needed and index into the @@ -404,7 +402,7 @@ static auto ConvertStructToStruct(Context& context, SemIR::StructType src_type, auto literal_elems_id = SemIR::NodeBlockId::Invalid; if (auto struct_literal = value.TryAs()) { literal_elems_id = struct_literal->elements_id; - literal_elems = semantics_ir.node_blocks().Get(literal_elems_id); + literal_elems = sem_ir.node_blocks().Get(literal_elems_id); } else { value_id = MaterializeIfInitializing(context, value_id); } @@ -429,22 +427,20 @@ static auto ConvertStructToStruct(Context& context, SemIR::StructType src_type, bool is_init = target.is_initializer(); ConversionTarget::Kind inner_kind = !is_init ? ConversionTarget::Value - : SemIR::GetInitializingRepresentation(semantics_ir, target.type_id) - .kind == SemIR::InitializingRepresentation::InPlace + : SemIR::GetInitializingRepresentation(sem_ir, target.type_id).kind == + SemIR::InitializingRepresentation::InPlace ? ConversionTarget::FullInitializer : ConversionTarget::Initializer; // Initialize each element of the destination from the corresponding element // of the source. // TODO: Annotate diagnostics coming from here with the element index. - CopyOnWriteBlock new_block(semantics_ir, literal_elems_id, - src_elem_fields.size()); + CopyOnWriteBlock new_block(sem_ir, literal_elems_id, src_elem_fields.size()); for (auto [i, src_field_id, dest_field_id] : llvm::enumerate(src_elem_fields, dest_elem_fields)) { - auto src_field = - semantics_ir.nodes().GetAs(src_field_id); + auto src_field = sem_ir.nodes().GetAs(src_field_id); auto dest_field = - semantics_ir.nodes().GetAs(dest_field_id); + sem_ir.nodes().GetAs(dest_field_id); if (src_field.name_id != dest_field.name_id) { CARBON_DIAGNOSTIC( StructInitFieldNameMismatch, Error, @@ -452,9 +448,8 @@ static auto ConvertStructToStruct(Context& context, SemIR::StructType src_type, "source has field name `{1}`, destination has field name `{2}`.", size_t, llvm::StringRef, llvm::StringRef); context.emitter().Emit(value.parse_node(), StructInitFieldNameMismatch, - i + 1, - semantics_ir.strings().Get(src_field.name_id), - semantics_ir.strings().Get(dest_field.name_id)); + i + 1, sem_ir.strings().Get(src_field.name_id), + sem_ir.strings().Get(dest_field.name_id)); return SemIR::NodeId::BuiltinError; } @@ -502,11 +497,11 @@ static bool IsValidExpressionCategoryForConversionTarget( static auto PerformBuiltinConversion(Context& context, Parse::Node parse_node, SemIR::NodeId value_id, ConversionTarget target) -> SemIR::NodeId { - auto& semantics_ir = context.semantics_ir(); - auto value = semantics_ir.nodes().Get(value_id); + auto& sem_ir = context.sem_ir(); + auto value = sem_ir.nodes().Get(value_id); auto value_type_id = value.type_id(); - auto target_type_node = semantics_ir.nodes().Get( - semantics_ir.GetTypeAllowBuiltinTypes(target.type_id)); + auto target_type_node = + sem_ir.nodes().Get(sem_ir.GetTypeAllowBuiltinTypes(target.type_id)); // Various forms of implicit conversion are supported as builtin conversions, // either in addition to or instead of `impl`s of `ImplicitAs` in the Carbon @@ -540,15 +535,15 @@ static auto PerformBuiltinConversion(Context& context, Parse::Node parse_node, // and structs, so it's important that we bail out early in this case. if (value_type_id == target.type_id && IsValidExpressionCategoryForConversionTarget( - SemIR::GetExpressionCategory(semantics_ir, value_id), target.kind)) { + SemIR::GetExpressionCategory(sem_ir, value_id), target.kind)) { return value_id; } // A tuple (T1, T2, ..., Tn) converts to (U1, U2, ..., Un) if each Ti // converts to Ui. if (auto target_tuple_type = target_type_node.TryAs()) { - auto value_type_node = semantics_ir.nodes().Get( - semantics_ir.GetTypeAllowBuiltinTypes(value_type_id)); + auto value_type_node = + sem_ir.nodes().Get(sem_ir.GetTypeAllowBuiltinTypes(value_type_id)); if (auto src_tuple_type = value_type_node.TryAs()) { return ConvertTupleToTuple(context, *src_tuple_type, *target_tuple_type, value_id, target); @@ -560,8 +555,8 @@ static auto PerformBuiltinConversion(Context& context, Parse::Node parse_node, // (p(1), ..., p(n)) is a permutation of (1, ..., n) and each Ti converts // to Ui. if (auto target_struct_type = target_type_node.TryAs()) { - auto value_type_node = semantics_ir.nodes().Get( - semantics_ir.GetTypeAllowBuiltinTypes(value_type_id)); + auto value_type_node = + sem_ir.nodes().Get(sem_ir.GetTypeAllowBuiltinTypes(value_type_id)); if (auto src_struct_type = value_type_node.TryAs()) { return ConvertStructToStruct(context, *src_struct_type, *target_struct_type, value_id, target); @@ -570,8 +565,8 @@ static auto PerformBuiltinConversion(Context& context, Parse::Node parse_node, // A tuple (T1, T2, ..., Tn) converts to [T; n] if each Ti converts to T. if (auto target_array_type = target_type_node.TryAs()) { - auto value_type_node = semantics_ir.nodes().Get( - semantics_ir.GetTypeAllowBuiltinTypes(value_type_id)); + auto value_type_node = + sem_ir.nodes().Get(sem_ir.GetTypeAllowBuiltinTypes(value_type_id)); if (auto src_tuple_type = value_type_node.TryAs()) { return ConvertTupleToArray(context, *src_tuple_type, *target_array_type, value_id, target); @@ -584,7 +579,7 @@ static auto PerformBuiltinConversion(Context& context, Parse::Node parse_node, if (auto tuple_literal = value.TryAs()) { llvm::SmallVector type_ids; for (auto tuple_node_id : - semantics_ir.node_blocks().Get(tuple_literal->elements_id)) { + sem_ir.node_blocks().Get(tuple_literal->elements_id)) { // TODO: This call recurses back into conversion. Switch to an // iterative approach. type_ids.push_back( @@ -592,7 +587,7 @@ static auto PerformBuiltinConversion(Context& context, Parse::Node parse_node, } auto tuple_type_id = context.CanonicalizeTupleType(parse_node, std::move(type_ids)); - return semantics_ir.GetTypeAllowBuiltinTypes(tuple_type_id); + return sem_ir.GetTypeAllowBuiltinTypes(tuple_type_id); } // `{}` converts to `{} as type`. @@ -601,7 +596,7 @@ static auto PerformBuiltinConversion(Context& context, Parse::Node parse_node, if (auto struct_literal = value.TryAs(); struct_literal && struct_literal->elements_id == SemIR::NodeBlockId::Empty) { - value_id = semantics_ir.GetTypeAllowBuiltinTypes(value_type_id); + value_id = sem_ir.GetTypeAllowBuiltinTypes(value_type_id); } } @@ -611,24 +606,24 @@ static auto PerformBuiltinConversion(Context& context, Parse::Node parse_node, auto Convert(Context& context, Parse::Node parse_node, SemIR::NodeId expr_id, ConversionTarget target) -> SemIR::NodeId { - auto& semantics_ir = context.semantics_ir(); + auto& sem_ir = context.sem_ir(); auto orig_expr_id = expr_id; // Start by making sure both sides are valid. If any part is invalid, the // result is invalid and we shouldn't error. - if (semantics_ir.nodes().Get(expr_id).type_id() == SemIR::TypeId::Error || + if (sem_ir.nodes().Get(expr_id).type_id() == SemIR::TypeId::Error || target.type_id == SemIR::TypeId::Error) { return SemIR::NodeId::BuiltinError; } - if (SemIR::GetExpressionCategory(semantics_ir, expr_id) == + if (SemIR::GetExpressionCategory(sem_ir, expr_id) == SemIR::ExpressionCategory::NotExpression) { // TODO: We currently encounter this for use of namespaces and functions. // We should provide a better diagnostic for inappropriate use of // namespace names, and allow use of functions as values. CARBON_DIAGNOSTIC(UseOfNonExpressionAsValue, Error, "Expression cannot be used as a value."); - context.emitter().Emit(semantics_ir.nodes().Get(expr_id).parse_node(), + context.emitter().Emit(sem_ir.nodes().Get(expr_id).parse_node(), UseOfNonExpressionAsValue); return SemIR::NodeId::BuiltinError; } @@ -649,7 +644,7 @@ auto Convert(Context& context, Parse::Node parse_node, SemIR::NodeId expr_id, : target.kind == ConversionTarget::Value ? IncompleteTypeInValueConversion : IncompleteTypeInConversion, - context.semantics_ir().StringifyType(target.type_id, true)); + context.sem_ir().StringifyType(target.type_id, true)); })) { return SemIR::NodeId::BuiltinError; } @@ -662,21 +657,21 @@ auto Convert(Context& context, Parse::Node parse_node, SemIR::NodeId expr_id, // If the types don't match at this point, we can't perform the conversion. // TODO: Look for an ImplicitAs impl. - SemIR::Node expr = semantics_ir.nodes().Get(expr_id); + SemIR::Node expr = sem_ir.nodes().Get(expr_id); if (expr.type_id() != target.type_id) { CARBON_DIAGNOSTIC(ImplicitAsConversionFailure, Error, "Cannot implicitly convert from `{0}` to `{1}`.", std::string, std::string); context.emitter() .Build(parse_node, ImplicitAsConversionFailure, - semantics_ir.StringifyType(expr.type_id()), - semantics_ir.StringifyType(target.type_id)) + sem_ir.StringifyType(expr.type_id()), + sem_ir.StringifyType(target.type_id)) .Emit(); return SemIR::NodeId::BuiltinError; } // Now perform any necessary value category conversions. - switch (SemIR::GetExpressionCategory(semantics_ir, expr_id)) { + switch (SemIR::GetExpressionCategory(sem_ir, expr_id)) { case SemIR::ExpressionCategory::NotExpression: case SemIR::ExpressionCategory::Mixed: CARBON_FATAL() << "Unexpected expression " << expr @@ -692,7 +687,7 @@ auto Convert(Context& context, Parse::Node parse_node, SemIR::NodeId expr_id, // a conversion. In that case, we will have created it with the // target already set. // TODO: Find a better way to track whether we need to do this. - MarkInitializerFor(semantics_ir, expr_id, target.init_id, + MarkInitializerFor(sem_ir, expr_id, target.init_id, *target.init_block); } break; @@ -725,7 +720,7 @@ auto Convert(Context& context, Parse::Node parse_node, SemIR::NodeId expr_id, // Perform a final destination store, if necessary. if (target.kind == ConversionTarget::FullInitializer) { if (auto init_rep = - SemIR::GetInitializingRepresentation(semantics_ir, target.type_id); + SemIR::GetInitializingRepresentation(sem_ir, target.type_id); init_rep.kind == SemIR::InitializingRepresentation::ByCopy) { target.init_block->InsertHere(); expr_id = context.AddNode(SemIR::InitializeFrom{ @@ -740,17 +735,16 @@ auto Initialize(Context& context, Parse::Node parse_node, SemIR::NodeId target_id, SemIR::NodeId value_id) -> SemIR::NodeId { PendingBlock target_block(context); - return Convert( - context, parse_node, value_id, - {.kind = ConversionTarget::Initializer, - .type_id = context.semantics_ir().nodes().Get(target_id).type_id(), - .init_id = target_id, - .init_block = &target_block}); + return Convert(context, parse_node, value_id, + {.kind = ConversionTarget::Initializer, + .type_id = context.sem_ir().nodes().Get(target_id).type_id(), + .init_id = target_id, + .init_block = &target_block}); } auto ConvertToValueExpression(Context& context, SemIR::NodeId expr_id) -> SemIR::NodeId { - auto expr = context.semantics_ir().nodes().Get(expr_id); + auto expr = context.sem_ir().nodes().Get(expr_id); return Convert(context, expr.parse_node(), expr_id, {.kind = ConversionTarget::Value, .type_id = expr.type_id()}); } @@ -758,7 +752,7 @@ auto ConvertToValueExpression(Context& context, SemIR::NodeId expr_id) auto ConvertToValueOrReferenceExpression(Context& context, SemIR::NodeId expr_id) -> SemIR::NodeId { - auto expr = context.semantics_ir().nodes().Get(expr_id); + auto expr = context.sem_ir().nodes().Get(expr_id); return Convert( context, expr.parse_node(), expr_id, {.kind = ConversionTarget::ValueOrReference, .type_id = expr.type_id()}); @@ -790,8 +784,8 @@ auto ConvertCallArgs(Context& context, Parse::Node call_parse_node, return true; } - auto arg_refs = context.semantics_ir().node_blocks().Get(arg_refs_id); - auto param_refs = context.semantics_ir().node_blocks().Get(param_refs_id); + auto arg_refs = context.sem_ir().node_blocks().Get(arg_refs_id); + auto param_refs = context.sem_ir().node_blocks().Get(param_refs_id); if (has_return_slot) { // There's no entry in the parameter block for the return slot, so ignore @@ -835,7 +829,7 @@ auto ConvertCallArgs(Context& context, Parse::Node call_parse_node, for (auto [i, value_id, param_ref] : llvm::enumerate(arg_refs, param_refs)) { diag_param_index = i; - auto as_type_id = context.semantics_ir().nodes().Get(param_ref).type_id(); + auto as_type_id = context.sem_ir().nodes().Get(param_ref).type_id(); // TODO: Convert to the proper expression category. For now, we assume // parameters are all `let` bindings. value_id = diff --git a/toolchain/check/declaration_name_stack.cpp b/toolchain/check/declaration_name_stack.cpp index 26094a4b1154..ea1e0f932c66 100644 --- a/toolchain/check/declaration_name_stack.cpp +++ b/toolchain/check/declaration_name_stack.cpp @@ -65,7 +65,7 @@ auto DeclarationNameStack::LookupOrAddName(NameContext name_context, } else { // TODO: Reject unless the scope is a namespace scope or the name is // unqualified. - bool success = context_->semantics_ir().name_scopes().AddEntry( + bool success = context_->name_scopes().AddEntry( name_context.target_scope_id, name_context.unresolved_name_id, target_id); CARBON_CHECK(success) @@ -121,11 +121,10 @@ auto DeclarationNameStack::UpdateScopeIfNeeded(NameContext& name_context) -> void { // This will only be reached for resolved nodes. We update the target // scope based on the resolved type. - auto resolved_node = - context_->semantics_ir().nodes().Get(name_context.resolved_node_id); + auto resolved_node = context_->nodes().Get(name_context.resolved_node_id); switch (resolved_node.kind()) { case SemIR::ClassDeclaration::Kind: { - const auto& class_info = context_->semantics_ir().classes().Get( + const auto& class_info = context_->classes().Get( resolved_node.As().class_id); // TODO: Check that the class is complete rather than that it has a scope. if (class_info.scope_id.is_valid()) { @@ -165,8 +164,7 @@ auto DeclarationNameStack::CanResolveQualifier(NameContext& name_context, case NameContext::State::ResolvedNonScope: { // Because more qualifiers were found, we diagnose that the earlier // qualifier didn't resolve to a scoped entity. - if (auto class_decl = context_->semantics_ir() - .nodes() + if (auto class_decl = context_->nodes() .Get(name_context.resolved_node_id) .TryAs()) { CARBON_DIAGNOSTIC(QualifiedDeclarationInIncompleteClassScope, Error, @@ -174,11 +172,8 @@ auto DeclarationNameStack::CanResolveQualifier(NameContext& name_context, std::string); auto builder = context_->emitter().Build( name_context.parse_node, QualifiedDeclarationInIncompleteClassScope, - context_->semantics_ir().StringifyType( - context_->semantics_ir() - .classes() - .Get(class_decl->class_id) - .self_type_id, + context_->sem_ir().StringifyType( + context_->classes().Get(class_decl->class_id).self_type_id, true)); context_->NoteIncompleteClass(class_decl->class_id, builder); builder.Emit(); diff --git a/toolchain/check/handle_array.cpp b/toolchain/check/handle_array.cpp index 94c024d9e9dd..b450ce4f7d8d 100644 --- a/toolchain/check/handle_array.cpp +++ b/toolchain/check/handle_array.cpp @@ -34,10 +34,9 @@ auto HandleArrayExpression(Context& context, Parse::Node parse_node) -> bool { context.node_stack() .PopAndDiscardSoloParseNode(); auto element_type_node_id = context.node_stack().PopExpression(); - auto bound_node = context.semantics_ir().nodes().Get(bound_node_id); + auto bound_node = context.nodes().Get(bound_node_id); if (auto literal = bound_node.TryAs()) { - const auto& bound_value = - context.semantics_ir().integers().Get(literal->integer_id); + const auto& bound_value = context.integers().Get(literal->integer_id); // TODO: Produce an error if the array type is too large. if (bound_value.getActiveBits() <= 64) { context.AddNodeAndPush( diff --git a/toolchain/check/handle_call_expression.cpp b/toolchain/check/handle_call_expression.cpp index 54d53003d764..ff1de50692ac 100644 --- a/toolchain/check/handle_call_expression.cpp +++ b/toolchain/check/handle_call_expression.cpp @@ -17,8 +17,8 @@ auto HandleCallExpression(Context& context, Parse::Node parse_node) -> bool { auto [call_expr_parse_node, callee_id] = context.node_stack() .PopWithParseNode(); - auto callee_node = context.semantics_ir().nodes().Get( - context.FollowNameReferences(callee_id)); + auto callee_node = + context.nodes().Get(context.FollowNameReferences(callee_id)); auto function_name = callee_node.TryAs(); if (!function_name) { // TODO: Work on error. @@ -29,7 +29,7 @@ auto HandleCallExpression(Context& context, Parse::Node parse_node) -> bool { } auto function_id = function_name->function_id; - const auto& callable = context.semantics_ir().functions().Get(function_id); + const auto& callable = context.functions().Get(function_id); // For functions with an implicit return type, the return type is the empty // tuple type. diff --git a/toolchain/check/handle_class.cpp b/toolchain/check/handle_class.cpp index a6d0b29e6539..7b84ef52ee6c 100644 --- a/toolchain/check/handle_class.cpp +++ b/toolchain/check/handle_class.cpp @@ -34,10 +34,8 @@ static auto BuildClassDeclaration(Context& context) auto existing_id = context.declaration_name_stack().LookupOrAddName( name_context, class_decl_id); if (existing_id.is_valid()) { - if (auto existing_class_decl = context.semantics_ir() - .nodes() - .Get(existing_id) - .TryAs()) { + if (auto existing_class_decl = + context.nodes().Get(existing_id).TryAs()) { // This is a redeclaration of an existing class. class_decl.class_id = existing_class_decl->class_id; } else { @@ -51,7 +49,7 @@ static auto BuildClassDeclaration(Context& context) // TODO: If this is an invalid redeclaration of a non-class entity or there // was an error in the qualifier, we will have lost track of the class name // here. We should keep track of it even if the name is invalid. - class_decl.class_id = context.semantics_ir().classes().Add( + class_decl.class_id = context.classes().Add( {.name_id = name_context.state == DeclarationNameStack::NameContext::State::Unresolved ? name_context.unresolved_name_id @@ -61,8 +59,7 @@ static auto BuildClassDeclaration(Context& context) .declaration_id = class_decl_id}); // Build the `Self` type. - auto& class_info = - context.semantics_ir().classes().Get(class_decl.class_id); + auto& class_info = context.classes().Get(class_decl.class_id); class_info.self_type_id = context.CanonicalizeType(context.AddNode(SemIR::ClassType{ class_keyword, context.GetBuiltinType(SemIR::BuiltinKind::TypeType), @@ -70,7 +67,7 @@ static auto BuildClassDeclaration(Context& context) } // Write the class ID into the ClassDeclaration. - context.semantics_ir().nodes().Set(class_decl_id, class_decl); + context.nodes().Set(class_decl_id, class_decl); return {class_decl.class_id, class_decl_id}; } @@ -84,7 +81,7 @@ auto HandleClassDeclaration(Context& context, Parse::Node /*parse_node*/) auto HandleClassDefinitionStart(Context& context, Parse::Node parse_node) -> bool { auto [class_id, class_decl_id] = BuildClassDeclaration(context); - auto& class_info = context.semantics_ir().classes().Get(class_id); + auto& class_info = context.classes().Get(class_id); // Track that this declaration is the definition. if (class_info.definition_id.is_valid()) { @@ -94,16 +91,13 @@ auto HandleClassDefinitionStart(Context& context, Parse::Node parse_node) "Previous definition was here."); context.emitter() .Build(parse_node, ClassRedefinition, - context.semantics_ir().strings().Get(class_info.name_id)) - .Note(context.semantics_ir() - .nodes() - .Get(class_info.definition_id) - .parse_node(), + context.strings().Get(class_info.name_id)) + .Note(context.nodes().Get(class_info.definition_id).parse_node(), ClassPreviousDefinition) .Emit(); } else { class_info.definition_id = class_decl_id; - class_info.scope_id = context.semantics_ir().name_scopes().Add(); + class_info.scope_id = context.name_scopes().Add(); // TODO: Introduce `Self`. } diff --git a/toolchain/check/handle_function.cpp b/toolchain/check/handle_function.cpp index 1b80e7375e68..8f4dfc2f0404 100644 --- a/toolchain/check/handle_function.cpp +++ b/toolchain/check/handle_function.cpp @@ -29,8 +29,7 @@ static auto BuildFunctionDeclaration(Context& context, bool is_definition) auto [return_node, return_storage_id] = context.node_stack().PopWithParseNode(); auto return_node_copy = return_node; - return_type_id = - context.semantics_ir().nodes().Get(return_storage_id).type_id(); + return_type_id = context.nodes().Get(return_storage_id).type_id(); if (!context.TryToCompleteType(return_type_id, [&] { CARBON_DIAGNOSTIC(IncompleteTypeInFunctionReturnType, Error, @@ -38,10 +37,10 @@ static auto BuildFunctionDeclaration(Context& context, bool is_definition) std::string); return context.emitter().Build( return_node_copy, IncompleteTypeInFunctionReturnType, - context.semantics_ir().StringifyType(return_type_id, true)); + context.sem_ir().StringifyType(return_type_id, true)); })) { return_type_id = SemIR::TypeId::Error; - } else if (!SemIR::GetInitializingRepresentation(context.semantics_ir(), + } else if (!SemIR::GetInitializingRepresentation(context.sem_ir(), return_type_id) .has_return_slot()) { // The function only has a return slot if it uses in-place initialization. @@ -68,8 +67,7 @@ static auto BuildFunctionDeclaration(Context& context, bool is_definition) name_context, function_decl_id); if (existing_id.is_valid()) { if (auto existing_function_decl = - context.semantics_ir() - .nodes() + context.nodes() .Get(existing_id) .TryAs()) { // This is a redeclaration of an existing function. @@ -81,7 +79,7 @@ static auto BuildFunctionDeclaration(Context& context, bool is_definition) // IDs in the signature. if (is_definition) { auto& function_info = - context.semantics_ir().functions().Get(function_decl.function_id); + context.functions().Get(function_decl.function_id); function_info.param_refs_id = param_refs_id; function_info.return_type_id = return_type_id; function_info.return_slot_id = return_slot_id; @@ -94,7 +92,7 @@ static auto BuildFunctionDeclaration(Context& context, bool is_definition) // Create a new function if this isn't a valid redeclaration. if (!function_decl.function_id.is_valid()) { - function_decl.function_id = context.semantics_ir().functions().Add( + function_decl.function_id = context.functions().Add( {.name_id = name_context.state == DeclarationNameStack::NameContext::State::Unresolved ? name_context.unresolved_name_id @@ -105,11 +103,11 @@ static auto BuildFunctionDeclaration(Context& context, bool is_definition) } // Write the function ID into the FunctionDeclaration. - context.semantics_ir().nodes().Set(function_decl_id, function_decl); + context.nodes().Set(function_decl_id, function_decl); - if (SemIR::IsEntryPoint(context.semantics_ir(), function_decl.function_id)) { + if (SemIR::IsEntryPoint(context.sem_ir(), function_decl.function_id)) { // TODO: Update this once valid signatures for the entry point are decided. - if (!context.semantics_ir().node_blocks().Get(param_refs_id).empty() || + if (!context.node_blocks().Get(param_refs_id).empty() || (return_slot_id.is_valid() && return_type_id != context.GetBuiltinType(SemIR::BuiltinKind::BoolType) && @@ -138,10 +136,7 @@ auto HandleFunctionDefinition(Context& context, Parse::Node parse_node) // If the `}` of the function is reachable, reject if we need a return value // and otherwise add an implicit `return;`. if (context.is_current_position_reachable()) { - if (context.semantics_ir() - .functions() - .Get(function_id) - .return_type_id.is_valid()) { + if (context.functions().Get(function_id).return_type_id.is_valid()) { CARBON_DIAGNOSTIC( MissingReturnStatement, Error, "Missing `return` at end of function with declared return type."); @@ -162,7 +157,7 @@ auto HandleFunctionDefinitionStart(Context& context, Parse::Node parse_node) // Process the declaration portion of the function. auto [function_id, decl_id] = BuildFunctionDeclaration(context, /*is_definition=*/true); - auto& function = context.semantics_ir().functions().Get(function_id); + auto& function = context.functions().Get(function_id); // Track that this declaration is the definition. if (function.definition_id.is_valid()) { @@ -172,11 +167,8 @@ auto HandleFunctionDefinitionStart(Context& context, Parse::Node parse_node) "Previous definition was here."); context.emitter() .Build(parse_node, FunctionRedefinition, - context.semantics_ir().strings().Get(function.name_id)) - .Note(context.semantics_ir() - .nodes() - .Get(function.definition_id) - .parse_node(), + context.strings().Get(function.name_id)) + .Note(context.nodes().Get(function.definition_id).parse_node(), FunctionPreviousDefinition) .Emit(); } else { @@ -190,10 +182,8 @@ auto HandleFunctionDefinitionStart(Context& context, Parse::Node parse_node) context.AddCurrentCodeBlockToFunction(); // Bring the parameters into scope. - for (auto param_id : - context.semantics_ir().node_blocks().Get(function.param_refs_id)) { - auto param = - context.semantics_ir().nodes().GetAs(param_id); + for (auto param_id : context.node_blocks().Get(function.param_refs_id)) { + auto param = context.nodes().GetAs(param_id); // The parameter types need to be complete. context.TryToCompleteType(param.type_id, [&] { @@ -203,7 +193,7 @@ auto HandleFunctionDefinitionStart(Context& context, Parse::Node parse_node) std::string); return context.emitter().Build( param.parse_node, IncompleteTypeInFunctionParam, - context.semantics_ir().StringifyType(param.type_id, true)); + context.sem_ir().StringifyType(param.type_id, true)); }); context.AddNameToLookup(param.parse_node, param.name_id, param_id); @@ -233,8 +223,7 @@ auto HandleReturnType(Context& context, Parse::Node parse_node) -> bool { // TODO: Use a dedicated node rather than VarStorage here. context.AddNodeAndPush( parse_node, - SemIR::VarStorage{parse_node, type_id, - context.semantics_ir().strings().Add("return")}); + SemIR::VarStorage{parse_node, type_id, context.strings().Add("return")}); return true; } diff --git a/toolchain/check/handle_if_expression.cpp b/toolchain/check/handle_if_expression.cpp index 0bf4adf216dc..ad1eb88afb4b 100644 --- a/toolchain/check/handle_if_expression.cpp +++ b/toolchain/check/handle_if_expression.cpp @@ -57,8 +57,7 @@ auto HandleIfExpressionElse(Context& context, Parse::Node parse_node) -> bool { // Convert the `else` value to the `then` value's type, and finish the `else` // block. // TODO: Find a common type, and convert both operands to it instead. - auto result_type_id = - context.semantics_ir().nodes().Get(then_value_id).type_id(); + auto result_type_id = context.nodes().Get(then_value_id).type_id(); else_value_id = ConvertToValueOfType(context, else_node, else_value_id, result_type_id); diff --git a/toolchain/check/handle_index.cpp b/toolchain/check/handle_index.cpp index 183e42fce8f5..6d97d9049727 100644 --- a/toolchain/check/handle_index.cpp +++ b/toolchain/check/handle_index.cpp @@ -23,8 +23,7 @@ static auto ValidateIntegerLiteralBound(Context& context, SemIR::Node operand_node, SemIR::IntegerLiteral index_node, int size) -> const llvm::APInt* { - const auto& index_val = - context.semantics_ir().integers().Get(index_node.integer_id); + const auto& index_val = context.integers().Get(index_node.integer_id); if (index_val.uge(size)) { CARBON_DIAGNOSTIC(IndexOutOfBounds, Error, "Index `{0}` is past the end of `{1}`.", llvm::APSInt, @@ -32,7 +31,7 @@ static auto ValidateIntegerLiteralBound(Context& context, context.emitter().Emit( parse_node, IndexOutOfBounds, llvm::APSInt(index_val, /*isUnsigned=*/true), - context.semantics_ir().StringifyType(operand_node.type_id())); + context.sem_ir().StringifyType(operand_node.type_id())); return nullptr; } return &index_val; @@ -40,14 +39,14 @@ static auto ValidateIntegerLiteralBound(Context& context, auto HandleIndexExpression(Context& context, Parse::Node parse_node) -> bool { auto index_node_id = context.node_stack().PopExpression(); - auto index_node = context.semantics_ir().nodes().Get(index_node_id); + auto index_node = context.nodes().Get(index_node_id); auto operand_node_id = context.node_stack().PopExpression(); operand_node_id = ConvertToValueOrReferenceExpression(context, operand_node_id); - auto operand_node = context.semantics_ir().nodes().Get(operand_node_id); + auto operand_node = context.nodes().Get(operand_node_id); auto operand_type_id = operand_node.type_id(); - auto operand_type_node = context.semantics_ir().nodes().Get( - context.semantics_ir().GetTypeAllowBuiltinTypes(operand_type_id)); + auto operand_type_node = context.nodes().Get( + context.sem_ir().GetTypeAllowBuiltinTypes(operand_type_id)); switch (operand_type_node.kind()) { case SemIR::ArrayType::Kind: { @@ -58,14 +57,14 @@ auto HandleIndexExpression(Context& context, Parse::Node parse_node) -> bool { index_literal && !ValidateIntegerLiteralBound( context, parse_node, operand_node, *index_literal, - context.semantics_ir().GetArrayBoundValue(array_type.bound_id))) { + context.sem_ir().GetArrayBoundValue(array_type.bound_id))) { index_node_id = SemIR::NodeId::BuiltinError; } auto cast_index_id = ConvertToValueOfType( context, index_node.parse_node(), index_node_id, context.GetBuiltinType(SemIR::BuiltinKind::IntegerType)); auto array_cat = - SemIR::GetExpressionCategory(context.semantics_ir(), operand_node_id); + SemIR::GetExpressionCategory(context.sem_ir(), operand_node_id); if (array_cat == SemIR::ExpressionCategory::Value) { // If the operand is an array value, convert it to an ephemeral // reference to an array so we can perform a primitive indexing into it. @@ -88,7 +87,7 @@ auto HandleIndexExpression(Context& context, Parse::Node parse_node) -> bool { case SemIR::TupleType::Kind: { SemIR::TypeId element_type_id = SemIR::TypeId::Error; if (auto index_literal = index_node.TryAs()) { - auto type_block = context.semantics_ir().type_blocks().Get( + auto type_block = context.type_blocks().Get( operand_type_node.As().elements_id); if (const auto* index_val = ValidateIntegerLiteralBound( context, parse_node, operand_node, *index_literal, @@ -112,9 +111,8 @@ auto HandleIndexExpression(Context& context, Parse::Node parse_node) -> bool { if (operand_type_id != SemIR::TypeId::Error) { CARBON_DIAGNOSTIC(TypeNotIndexable, Error, "`{0}` does not support indexing.", std::string); - context.emitter().Emit( - parse_node, TypeNotIndexable, - context.semantics_ir().StringifyType(operand_type_id)); + context.emitter().Emit(parse_node, TypeNotIndexable, + context.sem_ir().StringifyType(operand_type_id)); } context.node_stack().Push(parse_node, SemIR::NodeId::BuiltinError); return true; diff --git a/toolchain/check/handle_let.cpp b/toolchain/check/handle_let.cpp index b7a56dc53d24..76644b0a5e6a 100644 --- a/toolchain/check/handle_let.cpp +++ b/toolchain/check/handle_let.cpp @@ -16,7 +16,7 @@ auto HandleLetDeclaration(Context& context, Parse::Node parse_node) -> bool { .PopAndDiscardSoloParseNode(); // Convert the value to match the type of the pattern. - auto pattern = context.semantics_ir().nodes().Get(pattern_id); + auto pattern = context.nodes().Get(pattern_id); value_id = ConvertToValueOfType(context, parse_node, value_id, pattern.type_id()); @@ -27,7 +27,7 @@ auto HandleLetDeclaration(Context& context, Parse::Node parse_node) -> bool { CARBON_CHECK(!bind_name.value_id.is_valid()) << "Binding should not already have a value!"; bind_name.value_id = value_id; - context.semantics_ir().nodes().Set(pattern_id, bind_name); + context.nodes().Set(pattern_id, bind_name); context.node_block_stack().AddNodeId(pattern_id); // Add the name of the binding to the current scope. diff --git a/toolchain/check/handle_name.cpp b/toolchain/check/handle_name.cpp index 618209cc80d3..c3708dfa4c51 100644 --- a/toolchain/check/handle_name.cpp +++ b/toolchain/check/handle_name.cpp @@ -13,22 +13,20 @@ namespace Carbon::Check { // On invalid scopes, prints a diagnostic and still returns the scope. static auto GetAsNameScope(Context& context, SemIR::NodeId base_id) -> std::optional { - auto base = - context.semantics_ir().nodes().Get(context.FollowNameReferences(base_id)); + auto base = context.nodes().Get(context.FollowNameReferences(base_id)); if (auto base_as_namespace = base.TryAs()) { return base_as_namespace->name_scope_id; } if (auto base_as_class = base.TryAs()) { - auto& class_info = - context.semantics_ir().classes().Get(base_as_class->class_id); + auto& class_info = context.classes().Get(base_as_class->class_id); if (!class_info.scope_id.is_valid()) { CARBON_DIAGNOSTIC(QualifiedExpressionInIncompleteClassScope, Error, "Member access into incomplete class `{0}`.", std::string); auto builder = context.emitter().Build( - context.semantics_ir().nodes().Get(base_id).parse_node(), + context.nodes().Get(base_id).parse_node(), QualifiedExpressionInIncompleteClassScope, - context.semantics_ir().StringifyTypeExpression(base_id, true)); + context.sem_ir().StringifyTypeExpression(base_id, true)); context.NoteIncompleteClass(base_as_class->class_id, builder); builder.Emit(); } @@ -49,7 +47,7 @@ auto HandleMemberAccessExpression(Context& context, Parse::Node parse_node) ? context.LookupName(parse_node, name_id, *name_scope_id, /*print_diagnostics=*/true) : SemIR::NodeId::BuiltinError; - auto node = context.semantics_ir().nodes().Get(node_id); + auto node = context.nodes().Get(node_id); // TODO: Track that this node was named within `base_id`. context.AddNodeAndPush( parse_node, @@ -59,20 +57,18 @@ auto HandleMemberAccessExpression(Context& context, Parse::Node parse_node) // Materialize a temporary for the base expression if necessary. base_id = ConvertToValueOrReferenceExpression(context, base_id); - auto base_type_id = context.semantics_ir().nodes().Get(base_id).type_id(); + auto base_type_id = context.nodes().Get(base_id).type_id(); - auto base_type = context.semantics_ir().nodes().Get( - context.semantics_ir().GetTypeAllowBuiltinTypes(base_type_id)); + auto base_type = context.nodes().Get( + context.sem_ir().GetTypeAllowBuiltinTypes(base_type_id)); switch (base_type.kind()) { case SemIR::StructType::Kind: { - auto refs = context.semantics_ir().node_blocks().Get( + auto refs = context.node_blocks().Get( base_type.As().fields_id); // TODO: Do we need to optimize this with a lookup table for O(1)? for (auto [i, ref_id] : llvm::enumerate(refs)) { - auto field = - context.semantics_ir().nodes().GetAs( - ref_id); + auto field = context.nodes().GetAs(ref_id); if (name_id == field.name_id) { context.AddNodeAndPush( parse_node, SemIR::StructAccess{parse_node, field.field_type_id, @@ -84,8 +80,8 @@ auto HandleMemberAccessExpression(Context& context, Parse::Node parse_node) "Type `{0}` does not have a member `{1}`.", std::string, llvm::StringRef); context.emitter().Emit(parse_node, QualifiedExpressionNameNotFound, - context.semantics_ir().StringifyType(base_type_id), - context.semantics_ir().strings().Get(name_id)); + context.sem_ir().StringifyType(base_type_id), + context.strings().Get(name_id)); break; } default: { @@ -93,9 +89,8 @@ auto HandleMemberAccessExpression(Context& context, Parse::Node parse_node) CARBON_DIAGNOSTIC(QualifiedExpressionUnsupported, Error, "Type `{0}` does not support qualified expressions.", std::string); - context.emitter().Emit( - parse_node, QualifiedExpressionUnsupported, - context.semantics_ir().StringifyType(base_type_id)); + context.emitter().Emit(parse_node, QualifiedExpressionUnsupported, + context.sem_ir().StringifyType(base_type_id)); } break; } @@ -125,16 +120,13 @@ auto HandleNameExpression(Context& context, Parse::Node parse_node) -> bool { auto value_id = context.LookupName(parse_node, name_id, SemIR::NameScopeId::Invalid, /*print_diagnostics=*/true); - auto value = context.semantics_ir().nodes().Get(value_id); + auto value = context.nodes().Get(value_id); // If lookup finds a class declaration, the value is its `Self` type. if (auto class_decl = value.TryAs()) { - value_id = context.semantics_ir().GetTypeAllowBuiltinTypes( - context.semantics_ir() - .classes() - .Get(class_decl->class_id) - .self_type_id); - value = context.semantics_ir().nodes().Get(value_id); + value_id = context.sem_ir().GetTypeAllowBuiltinTypes( + context.classes().Get(class_decl->class_id).self_type_id); + value = context.nodes().Get(value_id); } CARBON_CHECK(value.kind().value_kind() == SemIR::NodeValueKind::Typed); diff --git a/toolchain/check/handle_namespace.cpp b/toolchain/check/handle_namespace.cpp index 74593588e1c4..4ccae6008c0a 100644 --- a/toolchain/check/handle_namespace.cpp +++ b/toolchain/check/handle_namespace.cpp @@ -17,7 +17,7 @@ auto HandleNamespace(Context& context, Parse::Node parse_node) -> bool { auto name_context = context.declaration_name_stack().Pop(); auto namespace_id = context.AddNode(SemIR::Namespace{ parse_node, context.GetBuiltinType(SemIR::BuiltinKind::NamespaceType), - context.semantics_ir().name_scopes().Add()}); + context.name_scopes().Add()}); context.declaration_name_stack().AddNameToLookup(name_context, namespace_id); return true; } diff --git a/toolchain/check/handle_operator.cpp b/toolchain/check/handle_operator.cpp index d002a9b01c77..f16ae7182ad9 100644 --- a/toolchain/check/handle_operator.cpp +++ b/toolchain/check/handle_operator.cpp @@ -17,16 +17,14 @@ auto HandleInfixOperator(Context& context, Parse::Node parse_node) -> bool { case Lex::TokenKind::Plus: // TODO: This should search for a compatible interface. For now, it's a // very trivial check of validity on the operation. - lhs_id = ConvertToValueOfType( - context, parse_node, lhs_id, - context.semantics_ir().nodes().Get(rhs_id).type_id()); + lhs_id = ConvertToValueOfType(context, parse_node, lhs_id, + context.nodes().Get(rhs_id).type_id()); rhs_id = ConvertToValueExpression(context, rhs_id); context.AddNodeAndPush( - parse_node, - SemIR::BinaryOperatorAdd{ - parse_node, context.semantics_ir().nodes().Get(lhs_id).type_id(), - lhs_id, rhs_id}); + parse_node, SemIR::BinaryOperatorAdd{ + parse_node, context.nodes().Get(lhs_id).type_id(), + lhs_id, rhs_id}); return true; case Lex::TokenKind::And: @@ -47,15 +45,13 @@ auto HandleInfixOperator(Context& context, Parse::Node parse_node) -> bool { // Collect the result from either the first or second operand. context.AddNodeAndPush( parse_node, - SemIR::BlockArg{parse_node, - context.semantics_ir().nodes().Get(rhs_id).type_id(), + SemIR::BlockArg{parse_node, context.nodes().Get(rhs_id).type_id(), resume_block_id}); return true; } case Lex::TokenKind::Equal: { // TODO: handle complex assignment expression such as `a += 1`. - if (auto lhs_cat = - SemIR::GetExpressionCategory(context.semantics_ir(), lhs_id); + if (auto lhs_cat = SemIR::GetExpressionCategory(context.sem_ir(), lhs_id); lhs_cat != SemIR::ExpressionCategory::DurableReference && lhs_cat != SemIR::ExpressionCategory::Error) { CARBON_DIAGNOSTIC(AssignmentToNonAssignable, Error, @@ -105,7 +101,7 @@ auto HandlePrefixOperator(Context& context, Parse::Node parse_node) -> bool { switch (auto token_kind = context.tokens().GetKind(token)) { case Lex::TokenKind::Amp: { // Only durable reference expressions can have their address taken. - switch (SemIR::GetExpressionCategory(context.semantics_ir(), value_id)) { + switch (SemIR::GetExpressionCategory(context.sem_ir(), value_id)) { case SemIR::ExpressionCategory::DurableReference: case SemIR::ExpressionCategory::Error: break; @@ -125,9 +121,8 @@ auto HandlePrefixOperator(Context& context, Parse::Node parse_node) -> bool { parse_node, SemIR::AddressOf{ parse_node, - context.GetPointerType( - parse_node, - context.semantics_ir().nodes().Get(value_id).type_id()), + context.GetPointerType(parse_node, + context.nodes().Get(value_id).type_id()), value_id}); return true; } @@ -136,8 +131,7 @@ auto HandlePrefixOperator(Context& context, Parse::Node parse_node) -> bool { // `const (const T)` is probably not what the developer intended. // TODO: Detect `const (const T)*` and suggest moving the `*` inside the // parentheses. - if (context.semantics_ir().nodes().Get(value_id).kind() == - SemIR::ConstType::Kind) { + if (context.nodes().Get(value_id).kind() == SemIR::ConstType::Kind) { CARBON_DIAGNOSTIC(RepeatedConst, Warning, "`const` applied repeatedly to the same type has no " "additional effect."); @@ -155,17 +149,15 @@ auto HandlePrefixOperator(Context& context, Parse::Node parse_node) -> bool { context.AddNodeAndPush( parse_node, SemIR::UnaryOperatorNot{ - parse_node, - context.semantics_ir().nodes().Get(value_id).type_id(), - value_id}); + parse_node, context.nodes().Get(value_id).type_id(), value_id}); return true; case Lex::TokenKind::Star: { value_id = ConvertToValueExpression(context, value_id); - auto type_id = context.GetUnqualifiedType( - context.semantics_ir().nodes().Get(value_id).type_id()); - auto type_node = context.semantics_ir().nodes().Get( - context.semantics_ir().GetTypeAllowBuiltinTypes(type_id)); + auto type_id = + context.GetUnqualifiedType(context.nodes().Get(value_id).type_id()); + auto type_node = context.nodes().Get( + context.sem_ir().GetTypeAllowBuiltinTypes(type_id)); auto result_type_id = SemIR::TypeId::Error; if (auto pointer_type = type_node.TryAs()) { result_type_id = pointer_type->pointee_id; @@ -174,9 +166,9 @@ auto HandlePrefixOperator(Context& context, Parse::Node parse_node) -> bool { DereferenceOfNonPointer, Error, "Cannot dereference operand of non-pointer type `{0}`.", std::string); - auto builder = context.emitter().Build( - parse_node, DereferenceOfNonPointer, - context.semantics_ir().StringifyType(type_id)); + auto builder = + context.emitter().Build(parse_node, DereferenceOfNonPointer, + context.sem_ir().StringifyType(type_id)); // TODO: Check for any facet here, rather than only a type. if (type_id == SemIR::TypeId::TypeType) { CARBON_DIAGNOSTIC( @@ -201,8 +193,7 @@ auto HandleShortCircuitOperand(Context& context, Parse::Node parse_node) // Convert the condition to `bool`. auto cond_value_id = context.node_stack().PopExpression(); cond_value_id = ConvertToBoolValue(context, parse_node, cond_value_id); - auto bool_type_id = - context.semantics_ir().nodes().Get(cond_value_id).type_id(); + auto bool_type_id = context.nodes().Get(cond_value_id).type_id(); // Compute the branch value: the condition for `and`, inverted for `or`. auto token = context.parse_tree().node_token(parse_node); diff --git a/toolchain/check/handle_paren.cpp b/toolchain/check/handle_paren.cpp index 163307e28d52..1e117b3927ff 100644 --- a/toolchain/check/handle_paren.cpp +++ b/toolchain/check/handle_paren.cpp @@ -40,11 +40,11 @@ auto HandleTupleLiteral(Context& context, Parse::Node parse_node) -> bool { context.node_stack() .PopAndDiscardSoloParseNode< Parse::NodeKind::ParenExpressionOrTupleLiteralStart>(); - const auto& node_block = context.semantics_ir().node_blocks().Get(refs_id); + const auto& node_block = context.node_blocks().Get(refs_id); llvm::SmallVector type_ids; type_ids.reserve(node_block.size()); for (auto node : node_block) { - type_ids.push_back(context.semantics_ir().nodes().Get(node).type_id()); + type_ids.push_back(context.nodes().Get(node).type_id()); } auto type_id = context.CanonicalizeTupleType(parse_node, std::move(type_ids)); diff --git a/toolchain/check/handle_pattern_binding.cpp b/toolchain/check/handle_pattern_binding.cpp index 3954db4ef716..bd83fa463cfa 100644 --- a/toolchain/check/handle_pattern_binding.cpp +++ b/toolchain/check/handle_pattern_binding.cpp @@ -39,7 +39,7 @@ auto HandlePatternBinding(Context& context, Parse::Node parse_node) -> bool { std::string); return context.emitter().Build( type_node_copy, IncompleteTypeInVarDeclaration, - context.semantics_ir().StringifyType(cast_type_id, true)); + context.sem_ir().StringifyType(cast_type_id, true)); })) { cast_type_id = SemIR::TypeId::Error; } @@ -61,7 +61,7 @@ auto HandlePatternBinding(Context& context, Parse::Node parse_node) -> bool { std::string); return context.emitter().Build( type_node_copy, IncompleteTypeInLetDeclaration, - context.semantics_ir().StringifyType(cast_type_id, true)); + context.sem_ir().StringifyType(cast_type_id, true)); })) { cast_type_id = SemIR::TypeId::Error; } @@ -71,7 +71,7 @@ auto HandlePatternBinding(Context& context, Parse::Node parse_node) -> bool { // the `let` pattern before we see the initializer. context.node_stack().Push( parse_node, - context.semantics_ir().nodes().AddInNoBlock(SemIR::BindName{ + context.nodes().AddInNoBlock(SemIR::BindName{ name_node, cast_type_id, name_id, SemIR::NodeId::Invalid})); break; diff --git a/toolchain/check/handle_statement.cpp b/toolchain/check/handle_statement.cpp index 8322d5687280..0a5f497bd157 100644 --- a/toolchain/check/handle_statement.cpp +++ b/toolchain/check/handle_statement.cpp @@ -14,7 +14,7 @@ static auto HandleDiscardedExpression(Context& context, SemIR::NodeId expr_id) -> void { // If we discard an initializing expression, convert it to a value or // reference so that it has something to initialize. - auto expr = context.semantics_ir().nodes().Get(expr_id); + auto expr = context.nodes().Get(expr_id); Convert(context, expr.parse_node(), expr_id, {.kind = ConversionTarget::Discarded, .type_id = expr.type_id()}); @@ -29,11 +29,9 @@ auto HandleExpressionStatement(Context& context, Parse::Node /*parse_node*/) auto HandleReturnStatement(Context& context, Parse::Node parse_node) -> bool { CARBON_CHECK(!context.return_scope_stack().empty()); - auto fn_node = - context.semantics_ir().nodes().GetAs( - context.return_scope_stack().back()); - const auto& callable = - context.semantics_ir().functions().Get(fn_node.function_id); + auto fn_node = context.nodes().GetAs( + context.return_scope_stack().back()); + const auto& callable = context.functions().Get(fn_node.function_id); if (context.parse_tree().node_kind(context.node_stack().PeekParseNode()) == Parse::NodeKind::ReturnStatementStart) { @@ -46,7 +44,7 @@ auto HandleReturnStatement(Context& context, Parse::Node parse_node) -> bool { "Must return a {0}.", std::string); context.emitter() .Build(parse_node, ReturnStatementMissingExpression, - context.semantics_ir().StringifyType(callable.return_type_id)) + context.sem_ir().StringifyType(callable.return_type_id)) .Emit(); } diff --git a/toolchain/check/handle_struct.cpp b/toolchain/check/handle_struct.cpp index 95fb058fcf28..5f8a764d6aea 100644 --- a/toolchain/check/handle_struct.cpp +++ b/toolchain/check/handle_struct.cpp @@ -45,8 +45,7 @@ auto HandleStructFieldValue(Context& context, Parse::Node parse_node) -> bool { // Store the name for the type. context.args_type_info_stack().AddNode(SemIR::StructTypeField{ - parse_node, name_id, - context.semantics_ir().nodes().Get(value_node_id).type_id()}); + parse_node, name_id, context.nodes().Get(value_node_id).type_id()}); // Push the value back on the stack as an argument. context.node_stack().Push(parse_node, value_node_id); diff --git a/toolchain/check/handle_variable.cpp b/toolchain/check/handle_variable.cpp index 5b75d06b2d15..80af833ca5f9 100644 --- a/toolchain/check/handle_variable.cpp +++ b/toolchain/check/handle_variable.cpp @@ -24,7 +24,7 @@ auto HandleVariableDeclaration(Context& context, Parse::Node parse_node) // Extract the name binding. SemIR::NodeId var_id = context.node_stack().Pop(); - auto var = context.semantics_ir().nodes().GetAs(var_id); + auto var = context.nodes().GetAs(var_id); // Form a corresponding name in the current context, and bind the name to the // variable. diff --git a/toolchain/check/node_block_stack.cpp b/toolchain/check/node_block_stack.cpp index 42683cdd24d2..a52ad3e62a08 100644 --- a/toolchain/check/node_block_stack.cpp +++ b/toolchain/check/node_block_stack.cpp @@ -27,7 +27,7 @@ auto NodeBlockStack::PeekOrAdd(int depth) -> SemIR::NodeBlockId { int index = size() - depth - 1; auto& slot = stack_[index]; if (!slot.id.is_valid()) { - slot.id = semantics_ir_->node_blocks().AddDefaultValue(); + slot.id = sem_ir_->node_blocks().AddDefaultValue(); } return slot.id; } @@ -40,9 +40,9 @@ auto NodeBlockStack::Pop() -> SemIR::NodeBlockId { // Finalize the block. if (!back.content.empty() && back.id != SemIR::NodeBlockId::Unreachable) { if (back.id.is_valid()) { - semantics_ir_->node_blocks().Set(back.id, back.content); + sem_ir_->node_blocks().Set(back.id, back.content); } else { - back.id = semantics_ir_->node_blocks().Add(back.content); + back.id = sem_ir_->node_blocks().Add(back.content); } } diff --git a/toolchain/check/node_block_stack.h b/toolchain/check/node_block_stack.h index 36e55c9bf18a..727b845290e4 100644 --- a/toolchain/check/node_block_stack.h +++ b/toolchain/check/node_block_stack.h @@ -19,9 +19,9 @@ namespace Carbon::Check { // All pushes and pops will be vlogged. class NodeBlockStack { public: - explicit NodeBlockStack(llvm::StringLiteral name, SemIR::File& semantics_ir, + explicit NodeBlockStack(llvm::StringLiteral name, SemIR::File& sem_ir, llvm::raw_ostream* vlog_stream) - : name_(name), semantics_ir_(&semantics_ir), vlog_stream_(vlog_stream) {} + : name_(name), sem_ir_(&sem_ir), vlog_stream_(vlog_stream) {} // Pushes an existing node block. auto Push(SemIR::NodeBlockId id) -> void; @@ -48,7 +48,7 @@ class NodeBlockStack { // Adds the given node to the block at the top of the stack and returns its // ID. auto AddNode(SemIR::Node node) -> SemIR::NodeId { - auto node_id = semantics_ir_->nodes().AddInNoBlock(node); + auto node_id = sem_ir_->nodes().AddInNoBlock(node); AddNodeId(node_id); return node_id; } @@ -102,7 +102,7 @@ class NodeBlockStack { llvm::StringLiteral name_; // The underlying SemIR::File instance. Always non-null. - SemIR::File* semantics_ir_; + SemIR::File* sem_ir_; // Whether to print verbose output. llvm::raw_ostream* vlog_stream_; diff --git a/toolchain/check/pending_block.h b/toolchain/check/pending_block.h index c8e75be4dc74..42a32b36f63f 100644 --- a/toolchain/check/pending_block.h +++ b/toolchain/check/pending_block.h @@ -40,7 +40,7 @@ class PendingBlock { }; auto AddNode(SemIR::Node node) -> SemIR::NodeId { - auto node_id = context_.semantics_ir().nodes().AddInNoBlock(node); + auto node_id = context_.nodes().AddInNoBlock(node); nodes_.push_back(node_id); return node_id; } @@ -56,27 +56,26 @@ class PendingBlock { // Replace the node at target_id with the nodes in this block. The new value // for target_id should be value_id. auto MergeReplacing(SemIR::NodeId target_id, SemIR::NodeId value_id) -> void { - auto value = context_.semantics_ir().nodes().Get(value_id); + auto value = context_.nodes().Get(value_id); // There are three cases here: if (nodes_.empty()) { // 1) The block is empty. Replace `target_id` with an empty splice // pointing at `value_id`. - context_.semantics_ir().nodes().Set( + context_.nodes().Set( target_id, SemIR::SpliceBlock{value.parse_node(), value.type_id(), SemIR::NodeBlockId::Empty, value_id}); } else if (nodes_.size() == 1 && nodes_[0] == value_id) { // 2) The block is {value_id}. Replace `target_id` with the node referred // to by `value_id`. This is intended to be the common case. - context_.semantics_ir().nodes().Set(target_id, value); + context_.nodes().Set(target_id, value); } else { // 3) Anything else: splice it into the IR, replacing `target_id`. - context_.semantics_ir().nodes().Set( + context_.nodes().Set( target_id, SemIR::SpliceBlock{value.parse_node(), value.type_id(), - context_.semantics_ir().node_blocks().Add(nodes_), - value_id}); + context_.node_blocks().Add(nodes_), value_id}); } // Prepare to stash more pending instructions. diff --git a/toolchain/lower/file_context.cpp b/toolchain/lower/file_context.cpp index 84c64fb9010a..cdd5c8fdb697 100644 --- a/toolchain/lower/file_context.cpp +++ b/toolchain/lower/file_context.cpp @@ -16,14 +16,13 @@ namespace Carbon::Lower { FileContext::FileContext(llvm::LLVMContext& llvm_context, - llvm::StringRef module_name, - const SemIR::File& semantics_ir, + llvm::StringRef module_name, const SemIR::File& sem_ir, llvm::raw_ostream* vlog_stream) : llvm_context_(&llvm_context), llvm_module_(std::make_unique(module_name, llvm_context)), - semantics_ir_(&semantics_ir), + sem_ir_(&sem_ir), vlog_stream_(vlog_stream) { - CARBON_CHECK(!semantics_ir.has_errors()) + CARBON_CHECK(!sem_ir.has_errors()) << "Generating LLVM IR from invalid SemIR::File is unsupported."; } @@ -34,22 +33,21 @@ auto FileContext::Run() -> std::unique_ptr { // Lower all types that were required to be complete. Note that this may // leave some entries in `types_` null, if those types were mentioned but not // used. - types_.resize(semantics_ir_->types().size()); - for (auto type_id : semantics_ir_->complete_types()) { - types_[type_id.index] = - BuildType(semantics_ir_->types().Get(type_id).node_id); + types_.resize(sem_ir_->types().size()); + for (auto type_id : sem_ir_->complete_types()) { + types_[type_id.index] = BuildType(sem_ir_->types().Get(type_id).node_id); } // Lower function declarations. - functions_.resize_for_overwrite(semantics_ir_->functions().size()); - for (auto i : llvm::seq(semantics_ir_->functions().size())) { + functions_.resize_for_overwrite(sem_ir_->functions().size()); + for (auto i : llvm::seq(sem_ir_->functions().size())) { functions_[i] = BuildFunctionDeclaration(SemIR::FunctionId(i)); } // TODO: Lower global variable declarations. // Lower function definitions. - for (auto i : llvm::seq(semantics_ir_->functions().size())) { + for (auto i : llvm::seq(sem_ir_->functions().size())) { BuildFunctionDefinition(SemIR::FunctionId(i)); } @@ -60,13 +58,13 @@ auto FileContext::Run() -> std::unique_ptr { auto FileContext::BuildFunctionDeclaration(SemIR::FunctionId function_id) -> llvm::Function* { - const auto& function = semantics_ir().functions().Get(function_id); + const auto& function = sem_ir().functions().Get(function_id); const bool has_return_slot = function.return_slot_id.is_valid(); - auto param_refs = semantics_ir().node_blocks().Get(function.param_refs_id); + auto param_refs = sem_ir().node_blocks().Get(function.param_refs_id); SemIR::InitializingRepresentation return_rep = function.return_type_id.is_valid() - ? SemIR::GetInitializingRepresentation(semantics_ir(), + ? SemIR::GetInitializingRepresentation(sem_ir(), function.return_type_id) : SemIR::InitializingRepresentation{ .kind = SemIR::InitializingRepresentation::None}; @@ -85,9 +83,9 @@ auto FileContext::BuildFunctionDeclaration(SemIR::FunctionId function_id) param_node_ids.push_back(function.return_slot_id); } for (auto param_ref_id : param_refs) { - auto param_type_id = semantics_ir().nodes().Get(param_ref_id).type_id(); + auto param_type_id = sem_ir().nodes().Get(param_ref_id).type_id(); switch (auto value_rep = - SemIR::GetValueRepresentation(semantics_ir(), param_type_id); + SemIR::GetValueRepresentation(sem_ir(), param_type_id); value_rep.kind) { case SemIR::ValueRepresentation::Unknown: CARBON_FATAL() @@ -111,12 +109,12 @@ auto FileContext::BuildFunctionDeclaration(SemIR::FunctionId function_id) : llvm::Type::getVoidTy(llvm_context()); std::string mangled_name; - if (SemIR::IsEntryPoint(semantics_ir(), function_id)) { + if (SemIR::IsEntryPoint(sem_ir(), function_id)) { // TODO: Add an implicit `return 0` if `Run` doesn't return `i32`. mangled_name = "main"; } else { // TODO: Decide on a name mangling scheme. - mangled_name = semantics_ir().strings().Get(function.name_id); + mangled_name = sem_ir().strings().Get(function.name_id); } llvm::FunctionType* function_type = @@ -133,8 +131,8 @@ auto FileContext::BuildFunctionDeclaration(SemIR::FunctionId function_id) arg.addAttr(llvm::Attribute::getWithStructRetType( llvm_context(), GetType(function.return_type_id))); } else { - arg.setName(semantics_ir().strings().Get( - semantics_ir().nodes().GetAs(node_id).name_id)); + arg.setName(sem_ir().strings().Get( + sem_ir().nodes().GetAs(node_id).name_id)); } } @@ -143,7 +141,7 @@ auto FileContext::BuildFunctionDeclaration(SemIR::FunctionId function_id) auto FileContext::BuildFunctionDefinition(SemIR::FunctionId function_id) -> void { - const auto& function = semantics_ir().functions().Get(function_id); + const auto& function = sem_ir().functions().Get(function_id); const auto& body_block_ids = function.body_block_ids; if (body_block_ids.empty()) { // Function is probably defined in another file; not an error. @@ -159,7 +157,7 @@ auto FileContext::BuildFunctionDefinition(SemIR::FunctionId function_id) // TODO: This duplicates the mapping between semantics nodes and LLVM // function parameters that was already computed in BuildFunctionDeclaration. // We should only do that once. - auto param_refs = semantics_ir().node_blocks().Get(function.param_refs_id); + auto param_refs = sem_ir().node_blocks().Get(function.param_refs_id); int param_index = 0; if (has_return_slot) { function_lowering.SetLocal(function.return_slot_id, @@ -167,8 +165,8 @@ auto FileContext::BuildFunctionDefinition(SemIR::FunctionId function_id) ++param_index; } for (auto param_ref_id : param_refs) { - auto param_type_id = semantics_ir().nodes().Get(param_ref_id).type_id(); - if (SemIR::GetValueRepresentation(semantics_ir(), param_type_id).kind == + auto param_type_id = sem_ir().nodes().Get(param_ref_id).type_id(); + if (SemIR::GetValueRepresentation(sem_ir(), param_type_id).kind == SemIR::ValueRepresentation::None) { function_lowering.SetLocal( param_ref_id, llvm::PoisonValue::get(GetType(param_type_id))); @@ -219,26 +217,25 @@ auto FileContext::BuildType(SemIR::NodeId node_id) -> llvm::Type* { break; } - auto node = semantics_ir_->nodes().Get(node_id); + auto node = sem_ir_->nodes().Get(node_id); switch (node.kind()) { case SemIR::ArrayType::Kind: { auto array_type = node.As(); return llvm::ArrayType::get( GetType(array_type.element_type_id), - semantics_ir_->GetArrayBoundValue(array_type.bound_id)); + sem_ir_->GetArrayBoundValue(array_type.bound_id)); } case SemIR::ConstType::Kind: return GetType(node.As().inner_id); case SemIR::PointerType::Kind: return llvm::PointerType::get(*llvm_context_, /*AddressSpace=*/0); case SemIR::StructType::Kind: { - auto fields = semantics_ir_->node_blocks().Get( - node.As().fields_id); + auto fields = + sem_ir_->node_blocks().Get(node.As().fields_id); llvm::SmallVector subtypes; subtypes.reserve(fields.size()); for (auto field_id : fields) { - auto field = - semantics_ir_->nodes().GetAs(field_id); + auto field = sem_ir_->nodes().GetAs(field_id); // TODO: Handle recursive types. The restriction for builtins prevents // recursion while still letting them cache. CARBON_CHECK(field.field_type_id.index < SemIR::BuiltinKind::ValidCount) @@ -252,8 +249,8 @@ auto FileContext::BuildType(SemIR::NodeId node_id) -> llvm::Type* { // can be collectively replaced with LLVM's void, particularly around // function returns. LLVM doesn't allow declaring variables with a void // type, so that may require significant special casing. - auto elements = semantics_ir_->type_blocks().Get( - node.As().elements_id); + auto elements = + sem_ir_->type_blocks().Get(node.As().elements_id); llvm::SmallVector subtypes; subtypes.reserve(elements.size()); for (auto element_id : elements) { diff --git a/toolchain/lower/file_context.h b/toolchain/lower/file_context.h index f60f2d123565..fb12a80a8954 100644 --- a/toolchain/lower/file_context.h +++ b/toolchain/lower/file_context.h @@ -17,8 +17,7 @@ namespace Carbon::Lower { class FileContext { public: explicit FileContext(llvm::LLVMContext& llvm_context, - llvm::StringRef module_name, - const SemIR::File& semantics_ir, + llvm::StringRef module_name, const SemIR::File& sem_ir, llvm::raw_ostream* vlog_stream); // Lowers the SemIR::File to LLVM IR. Should only be called once, and handles @@ -49,7 +48,7 @@ class FileContext { auto llvm_context() -> llvm::LLVMContext& { return *llvm_context_; } auto llvm_module() -> llvm::Module& { return *llvm_module_; } - auto semantics_ir() -> const SemIR::File& { return *semantics_ir_; } + auto sem_ir() -> const SemIR::File& { return *sem_ir_; } private: // Builds the declaration for the given function, which should then be cached @@ -79,7 +78,7 @@ class FileContext { std::unique_ptr llvm_module_; // The input SemIR. - const SemIR::File* const semantics_ir_; + const SemIR::File* const sem_ir_; // The optional vlog stream. llvm::raw_ostream* vlog_stream_; diff --git a/toolchain/lower/function_context.cpp b/toolchain/lower/function_context.cpp index fb68e07ea145..a4af95f4c9ce 100644 --- a/toolchain/lower/function_context.cpp +++ b/toolchain/lower/function_context.cpp @@ -38,8 +38,8 @@ auto FunctionContext::TryToReuseBlock(SemIR::NodeBlockId block_id, } auto FunctionContext::LowerBlock(SemIR::NodeBlockId block_id) -> void { - for (const auto& node_id : semantics_ir().node_blocks().Get(block_id)) { - auto node = semantics_ir().nodes().Get(node_id); + for (const auto& node_id : sem_ir().node_blocks().Get(block_id)) { + auto node = sem_ir().nodes().Get(node_id); CARBON_VLOG() << "Lowering " << node_id << ": " << node << "\n"; // clang warns on unhandled enum values; clang-tidy is incorrect here. // NOLINTNEXTLINE(bugprone-switch-missing-default-case) @@ -81,7 +81,7 @@ auto FunctionContext::CreateSyntheticBlock() -> llvm::BasicBlock* { auto FunctionContext::FinishInitialization(SemIR::TypeId type_id, SemIR::NodeId dest_id, SemIR::NodeId source_id) -> void { - switch (SemIR::GetInitializingRepresentation(semantics_ir(), type_id).kind) { + switch (SemIR::GetInitializingRepresentation(sem_ir(), type_id).kind) { case SemIR::InitializingRepresentation::None: case SemIR::InitializingRepresentation::InPlace: break; @@ -93,7 +93,7 @@ auto FunctionContext::FinishInitialization(SemIR::TypeId type_id, auto FunctionContext::CopyValue(SemIR::TypeId type_id, SemIR::NodeId source_id, SemIR::NodeId dest_id) -> void { - switch (auto rep = SemIR::GetValueRepresentation(semantics_ir(), type_id); + switch (auto rep = SemIR::GetValueRepresentation(sem_ir(), type_id); rep.kind) { case SemIR::ValueRepresentation::Unknown: CARBON_FATAL() << "Attempt to copy incomplete type"; diff --git a/toolchain/lower/function_context.h b/toolchain/lower/function_context.h index 3248dcb9f05b..e881f955bce1 100644 --- a/toolchain/lower/function_context.h +++ b/toolchain/lower/function_context.h @@ -47,8 +47,8 @@ class FunctionContext { } auto it = locals_.find(node_id); - CARBON_CHECK(it != locals_.end()) << "Missing local: " << node_id << " " - << semantics_ir().nodes().Get(node_id); + CARBON_CHECK(it != locals_.end()) + << "Missing local: " << node_id << " " << sem_ir().nodes().Get(node_id); return it->second; } @@ -56,7 +56,7 @@ class FunctionContext { auto SetLocal(SemIR::NodeId node_id, llvm::Value* value) { bool added = locals_.insert({node_id, value}).second; CARBON_CHECK(added) << "Duplicate local insert: " << node_id << " " - << semantics_ir().nodes().Get(node_id); + << sem_ir().nodes().Get(node_id); } // Gets a callable's function. @@ -97,9 +97,7 @@ class FunctionContext { } auto llvm_module() -> llvm::Module& { return file_context_->llvm_module(); } auto builder() -> llvm::IRBuilder<>& { return builder_; } - auto semantics_ir() -> const SemIR::File& { - return file_context_->semantics_ir(); - } + auto sem_ir() -> const SemIR::File& { return file_context_->sem_ir(); } private: // Emits a value copy for type `type_id` from `source_id` to `dest_id`. diff --git a/toolchain/lower/handle.cpp b/toolchain/lower/handle.cpp index 3308bd117a07..a52e5fa97952 100644 --- a/toolchain/lower/handle.cpp +++ b/toolchain/lower/handle.cpp @@ -24,8 +24,8 @@ auto HandleAddressOf(FunctionContext& context, SemIR::NodeId node_id, auto HandleArrayIndex(FunctionContext& context, SemIR::NodeId node_id, SemIR::ArrayIndex node) -> void { auto* array_value = context.GetLocal(node.array_id); - auto* llvm_type = context.GetType( - context.semantics_ir().nodes().Get(node.array_id).type_id()); + auto* llvm_type = + context.GetType(context.sem_ir().nodes().Get(node.array_id).type_id()); llvm::Value* indexes[2] = { llvm::ConstantInt::get(llvm::Type::getInt32Ty(context.llvm_context()), 0), context.GetLocal(node.index_id)}; @@ -38,7 +38,7 @@ auto HandleArrayInit(FunctionContext& context, SemIR::NodeId node_id, SemIR::ArrayInit node) -> void { // The result of initialization is the return slot of the initializer. context.SetLocal(node_id, - context.GetLocal(context.semantics_ir() + context.GetLocal(context.sem_ir() .node_blocks() .Get(node.inits_and_return_slot_id) .back())); @@ -46,8 +46,7 @@ auto HandleArrayInit(FunctionContext& context, SemIR::NodeId node_id, auto HandleAssign(FunctionContext& context, SemIR::NodeId /*node_id*/, SemIR::Assign node) -> void { - auto storage_type_id = - context.semantics_ir().nodes().Get(node.lhs_id).type_id(); + auto storage_type_id = context.sem_ir().nodes().Get(node.lhs_id).type_id(); context.FinishInitialization(storage_type_id, node.lhs_id, node.rhs_id); } @@ -101,7 +100,7 @@ auto HandleBranchWithArg(FunctionContext& context, SemIR::NodeId /*node_id*/, SemIR::BranchWithArg node) -> void { llvm::Value* arg = context.GetLocal(node.arg_id); SemIR::TypeId arg_type_id = - context.semantics_ir().nodes().Get(node.arg_id).type_id(); + context.sem_ir().nodes().Get(node.arg_id).type_id(); // Opportunistically avoid creating a BasicBlock that contains just a branch. // We only do this for a block that we know will only have a single @@ -135,18 +134,18 @@ auto HandleCall(FunctionContext& context, SemIR::NodeId node_id, std::vector args; llvm::ArrayRef arg_ids = - context.semantics_ir().node_blocks().Get(node.args_id); + context.sem_ir().node_blocks().Get(node.args_id); - if (SemIR::GetInitializingRepresentation(context.semantics_ir(), node.type_id) + if (SemIR::GetInitializingRepresentation(context.sem_ir(), node.type_id) .has_return_slot()) { args.push_back(context.GetLocal(arg_ids.back())); arg_ids = arg_ids.drop_back(); } for (auto arg_id : arg_ids) { - auto arg_type_id = context.semantics_ir().nodes().Get(arg_id).type_id(); - if (SemIR::GetValueRepresentation(context.semantics_ir(), arg_type_id) - .kind != SemIR::ValueRepresentation::None) { + auto arg_type_id = context.sem_ir().nodes().Get(arg_id).type_id(); + if (SemIR::GetValueRepresentation(context.sem_ir(), arg_type_id).kind != + SemIR::ValueRepresentation::None) { args.push_back(context.GetLocal(arg_id)); } } @@ -183,14 +182,13 @@ auto HandleFunctionDeclaration(FunctionContext& /*context*/, auto HandleInitializeFrom(FunctionContext& context, SemIR::NodeId /*node_id*/, SemIR::InitializeFrom node) -> void { - auto storage_type_id = - context.semantics_ir().nodes().Get(node.dest_id).type_id(); + auto storage_type_id = context.sem_ir().nodes().Get(node.dest_id).type_id(); context.FinishInitialization(storage_type_id, node.dest_id, node.src_id); } auto HandleIntegerLiteral(FunctionContext& context, SemIR::NodeId node_id, SemIR::IntegerLiteral node) -> void { - const llvm::APInt& i = context.semantics_ir().integers().Get(node.integer_id); + const llvm::APInt& i = context.sem_ir().integers().Get(node.integer_id); // TODO: This won't offer correct semantics, but seems close enough for now. llvm::Value* v = llvm::ConstantInt::get(context.builder().getInt32Ty(), i.getZExtValue()); @@ -199,13 +197,12 @@ auto HandleIntegerLiteral(FunctionContext& context, SemIR::NodeId node_id, auto HandleNameReference(FunctionContext& context, SemIR::NodeId node_id, SemIR::NameReference node) -> void { - auto type_node_id = - context.semantics_ir().GetTypeAllowBuiltinTypes(node.type_id); + auto type_node_id = context.sem_ir().GetTypeAllowBuiltinTypes(node.type_id); if (type_node_id == SemIR::NodeId::BuiltinNamespaceType) { return; } - auto target = context.semantics_ir().nodes().Get(node.value_id); + auto target = context.sem_ir().nodes().Get(node.value_id); if (auto function_decl = target.TryAs()) { context.SetLocal(node_id, context.GetFunction(function_decl->function_id)); } else { @@ -234,7 +231,7 @@ auto HandleParameter(FunctionContext& /*context*/, SemIR::NodeId /*node_id*/, auto HandleRealLiteral(FunctionContext& context, SemIR::NodeId node_id, SemIR::RealLiteral node) -> void { - const Real& real = context.semantics_ir().reals().Get(node.real_id); + const Real& real = context.sem_ir().reals().Get(node.real_id); // TODO: This will probably have overflow issues, and should be fixed. double val = real.mantissa.getZExtValue() * @@ -252,8 +249,8 @@ auto HandleReturn(FunctionContext& context, SemIR::NodeId /*node_id*/, auto HandleReturnExpression(FunctionContext& context, SemIR::NodeId /*node_id*/, SemIR::ReturnExpression node) -> void { switch (SemIR::GetInitializingRepresentation( - context.semantics_ir(), - context.semantics_ir().nodes().Get(node.expr_id).type_id()) + context.sem_ir(), + context.sem_ir().nodes().Get(node.expr_id).type_id()) .kind) { case SemIR::InitializingRepresentation::None: case SemIR::InitializingRepresentation::InPlace: @@ -286,10 +283,10 @@ static auto GetStructOrTupleElement(FunctionContext& context, SemIR::NodeId aggr_node_id, unsigned idx, SemIR::TypeId result_type_id, llvm::Twine name) -> llvm::Value* { - auto aggr_node = context.semantics_ir().nodes().Get(aggr_node_id); + auto aggr_node = context.sem_ir().nodes().Get(aggr_node_id); auto* aggr_value = context.GetLocal(aggr_node_id); - switch (SemIR::GetExpressionCategory(context.semantics_ir(), aggr_node_id)) { + switch (SemIR::GetExpressionCategory(context.sem_ir(), aggr_node_id)) { case SemIR::ExpressionCategory::Error: case SemIR::ExpressionCategory::NotExpression: case SemIR::ExpressionCategory::Initializing: @@ -297,8 +294,8 @@ static auto GetStructOrTupleElement(FunctionContext& context, CARBON_FATAL() << "Unexpected expression category for aggregate access"; case SemIR::ExpressionCategory::Value: { - auto value_rep = SemIR::GetValueRepresentation(context.semantics_ir(), - aggr_node.type_id()); + auto value_rep = + SemIR::GetValueRepresentation(context.sem_ir(), aggr_node.type_id()); switch (value_rep.kind) { case SemIR::ValueRepresentation::Unknown: CARBON_FATAL() << "Lowering access to incomplete aggregate type"; @@ -311,13 +308,12 @@ static auto GetStructOrTupleElement(FunctionContext& context, // The value representation is a pointer to an aggregate that we want // to index into. auto pointee_type_id = - context.semantics_ir().GetPointeeType(value_rep.type_id); + context.sem_ir().GetPointeeType(value_rep.type_id); auto* value_type = context.GetType(pointee_type_id); auto* elem_ptr = context.builder().CreateStructGEP( value_type, aggr_value, idx, name); auto result_value_type_id = - SemIR::GetValueRepresentation(context.semantics_ir(), - result_type_id) + SemIR::GetValueRepresentation(context.sem_ir(), result_type_id) .type_id; return context.builder().CreateLoad( context.GetType(result_value_type_id), elem_ptr, name + ".load"); @@ -340,19 +336,18 @@ static auto GetStructOrTupleElement(FunctionContext& context, auto HandleStructAccess(FunctionContext& context, SemIR::NodeId node_id, SemIR::StructAccess node) -> void { - auto struct_type_id = - context.semantics_ir().nodes().Get(node.struct_id).type_id(); + auto struct_type_id = context.sem_ir().nodes().Get(node.struct_id).type_id(); // Get type information for member names. - auto fields = context.semantics_ir().node_blocks().Get( - context.semantics_ir() + auto fields = context.sem_ir().node_blocks().Get( + context.sem_ir() .nodes() .GetAs( - context.semantics_ir().types().Get(struct_type_id).node_id) + context.sem_ir().types().Get(struct_type_id).node_id) .fields_id); - auto field = context.semantics_ir().nodes().GetAs( + auto field = context.sem_ir().nodes().GetAs( fields[node.index.index]); - auto member_name = context.semantics_ir().strings().Get(field.name_id); + auto member_name = context.sem_ir().strings().Get(field.name_id); context.SetLocal(node_id, GetStructOrTupleElement(context, node.struct_id, node.index.index, @@ -372,8 +367,7 @@ auto EmitStructOrTupleValueRepresentation(FunctionContext& context, SemIR::TypeId type_id, SemIR::NodeBlockId refs_id, llvm::Twine name) -> llvm::Value* { - auto value_rep = - SemIR::GetValueRepresentation(context.semantics_ir(), type_id); + auto value_rep = SemIR::GetValueRepresentation(context.sem_ir(), type_id); switch (value_rep.kind) { case SemIR::ValueRepresentation::Unknown: CARBON_FATAL() << "Incomplete aggregate type in lowering"; @@ -383,7 +377,7 @@ auto EmitStructOrTupleValueRepresentation(FunctionContext& context, return llvm::PoisonValue::get(context.GetType(value_rep.type_id)); case SemIR::ValueRepresentation::Copy: { - auto refs = context.semantics_ir().node_blocks().Get(refs_id); + auto refs = context.sem_ir().node_blocks().Get(refs_id); CARBON_CHECK(refs.size() == 1) << "Unexpected size for aggregate with by-copy value representation"; // TODO: Remove the LLVM StructType wrapper in this case, so we don't @@ -394,8 +388,7 @@ auto EmitStructOrTupleValueRepresentation(FunctionContext& context, } case SemIR::ValueRepresentation::Pointer: { - auto pointee_type_id = - context.semantics_ir().GetPointeeType(value_rep.type_id); + auto pointee_type_id = context.sem_ir().GetPointeeType(value_rep.type_id); auto* llvm_value_rep_type = context.GetType(pointee_type_id); // Write the value representation to a local alloca so we can produce a @@ -404,7 +397,7 @@ auto EmitStructOrTupleValueRepresentation(FunctionContext& context, context.builder().CreateAlloca(llvm_value_rep_type, /*ArraySize=*/nullptr, name); for (auto [i, ref] : - llvm::enumerate(context.semantics_ir().node_blocks().Get(refs_id))) { + llvm::enumerate(context.sem_ir().node_blocks().Get(refs_id))) { context.builder().CreateStore( context.GetLocal(ref), context.builder().CreateStructGEP(llvm_value_rep_type, alloca, i)); @@ -422,9 +415,8 @@ auto HandleStructInit(FunctionContext& context, SemIR::NodeId node_id, SemIR::StructInit node) -> void { auto* llvm_type = context.GetType(node.type_id); - switch ( - SemIR::GetInitializingRepresentation(context.semantics_ir(), node.type_id) - .kind) { + switch (SemIR::GetInitializingRepresentation(context.sem_ir(), node.type_id) + .kind) { case SemIR::InitializingRepresentation::None: case SemIR::InitializingRepresentation::InPlace: // TODO: Add a helper to poison a value slot. @@ -462,12 +454,10 @@ auto HandleTupleAccess(FunctionContext& context, SemIR::NodeId node_id, auto HandleTupleIndex(FunctionContext& context, SemIR::NodeId node_id, SemIR::TupleIndex node) -> void { - auto index_node = context.semantics_ir().nodes().GetAs( - node.index_id); - auto index = context.semantics_ir() - .integers() - .Get(index_node.integer_id) - .getZExtValue(); + auto index_node = + context.sem_ir().nodes().GetAs(node.index_id); + auto index = + context.sem_ir().integers().Get(index_node.integer_id).getZExtValue(); context.SetLocal(node_id, GetStructOrTupleElement(context, node.tuple_id, index, node.type_id, "tuple.index")); @@ -483,9 +473,8 @@ auto HandleTupleInit(FunctionContext& context, SemIR::NodeId node_id, SemIR::TupleInit node) -> void { auto* llvm_type = context.GetType(node.type_id); - switch ( - SemIR::GetInitializingRepresentation(context.semantics_ir(), node.type_id) - .kind) { + switch (SemIR::GetInitializingRepresentation(context.sem_ir(), node.type_id) + .kind) { case SemIR::InitializingRepresentation::None: case SemIR::InitializingRepresentation::InPlace: // TODO: Add a helper to poison a value slot. @@ -519,7 +508,7 @@ auto HandleVarStorage(FunctionContext& context, SemIR::NodeId node_id, // TODO: Eventually this name will be optional, and we'll want to provide // something like `var` as a default. However, that's not possible right now // so cannot be tested. - auto name = context.semantics_ir().strings().Get(node.name_id); + auto name = context.sem_ir().strings().Get(node.name_id); auto* alloca = context.builder().CreateAlloca(context.GetType(node.type_id), /*ArraySize=*/nullptr, name); context.SetLocal(node_id, alloca); diff --git a/toolchain/lower/handle_expression_category.cpp b/toolchain/lower/handle_expression_category.cpp index 01c0c9668cc5..a5300bf6f581 100644 --- a/toolchain/lower/handle_expression_category.cpp +++ b/toolchain/lower/handle_expression_category.cpp @@ -9,8 +9,8 @@ namespace Carbon::Lower { auto HandleBindValue(FunctionContext& context, SemIR::NodeId node_id, SemIR::BindValue node) -> void { - switch (auto rep = SemIR::GetValueRepresentation(context.semantics_ir(), - node.type_id); + switch (auto rep = + SemIR::GetValueRepresentation(context.sem_ir(), node.type_id); rep.kind) { case SemIR::ValueRepresentation::Unknown: CARBON_FATAL() @@ -50,12 +50,11 @@ auto HandleTemporaryStorage(FunctionContext& context, SemIR::NodeId node_id, auto HandleValueAsReference(FunctionContext& context, SemIR::NodeId node_id, SemIR::ValueAsReference node) -> void { + CARBON_CHECK(SemIR::GetExpressionCategory(context.sem_ir(), node.value_id) == + SemIR::ExpressionCategory::Value); CARBON_CHECK( - SemIR::GetExpressionCategory(context.semantics_ir(), node.value_id) == - SemIR::ExpressionCategory::Value); - CARBON_CHECK( - SemIR::GetValueRepresentation(context.semantics_ir(), node.type_id) - .kind == SemIR::ValueRepresentation::Pointer); + SemIR::GetValueRepresentation(context.sem_ir(), node.type_id).kind == + SemIR::ValueRepresentation::Pointer); context.SetLocal(node_id, context.GetLocal(node.value_id)); } diff --git a/toolchain/lower/lower.cpp b/toolchain/lower/lower.cpp index 07b5d3e8bfc8..f11f2ff4a34a 100644 --- a/toolchain/lower/lower.cpp +++ b/toolchain/lower/lower.cpp @@ -9,10 +9,9 @@ namespace Carbon::Lower { auto LowerToLLVM(llvm::LLVMContext& llvm_context, llvm::StringRef module_name, - const SemIR::File& semantics_ir, - llvm::raw_ostream* vlog_stream) + const SemIR::File& sem_ir, llvm::raw_ostream* vlog_stream) -> std::unique_ptr { - FileContext context(llvm_context, module_name, semantics_ir, vlog_stream); + FileContext context(llvm_context, module_name, sem_ir, vlog_stream); return context.Run(); } diff --git a/toolchain/lower/lower.h b/toolchain/lower/lower.h index 20b7fedce746..16345a18e999 100644 --- a/toolchain/lower/lower.h +++ b/toolchain/lower/lower.h @@ -13,8 +13,7 @@ namespace Carbon::Lower { // Lowers SemIR to LLVM IR. auto LowerToLLVM(llvm::LLVMContext& llvm_context, llvm::StringRef module_name, - const SemIR::File& semantics_ir, - llvm::raw_ostream* vlog_stream) + const SemIR::File& sem_ir, llvm::raw_ostream* vlog_stream) -> std::unique_ptr; } // namespace Carbon::Lower diff --git a/toolchain/sem_ir/file.h b/toolchain/sem_ir/file.h index 84b8b91684bf..f240dd9b60f3 100644 --- a/toolchain/sem_ir/file.h +++ b/toolchain/sem_ir/file.h @@ -223,6 +223,7 @@ class File : public Printable { auto integers() const -> const ValueStore& { return value_stores_->integers(); } + auto reals() -> ValueStore& { return value_stores_->reals(); } auto reals() const -> const ValueStore& { return value_stores_->reals(); } diff --git a/toolchain/sem_ir/formatter.cpp b/toolchain/sem_ir/formatter.cpp index 3cf41ffda383..25644495362d 100644 --- a/toolchain/sem_ir/formatter.cpp +++ b/toolchain/sem_ir/formatter.cpp @@ -32,22 +32,21 @@ class NodeNamer { static_assert(sizeof(ScopeIndex) == sizeof(FunctionId)); NodeNamer(const Lex::TokenizedBuffer& tokenized_buffer, - const Parse::Tree& parse_tree, const File& semantics_ir) + const Parse::Tree& parse_tree, const File& sem_ir) : tokenized_buffer_(tokenized_buffer), parse_tree_(parse_tree), - semantics_ir_(semantics_ir) { - nodes.resize(semantics_ir.nodes().size()); - labels.resize(semantics_ir.node_blocks().size()); - scopes.resize(1 + semantics_ir.functions().size() + - semantics_ir.classes().size()); + sem_ir_(sem_ir) { + nodes.resize(sem_ir.nodes().size()); + labels.resize(sem_ir.node_blocks().size()); + scopes.resize(1 + sem_ir.functions().size() + sem_ir.classes().size()); // Build the package scope. GetScopeInfo(ScopeIndex::Package).name = globals.AddNameUnchecked("package"); - CollectNamesInBlock(ScopeIndex::Package, semantics_ir.top_node_block_id()); + CollectNamesInBlock(ScopeIndex::Package, sem_ir.top_node_block_id()); // Build each function scope. - for (auto [i, fn] : llvm::enumerate(semantics_ir.functions().array_ref())) { + for (auto [i, fn] : llvm::enumerate(sem_ir.functions().array_ref())) { auto fn_id = FunctionId(i); auto fn_scope = GetScopeFor(fn_id); // TODO: Provide a location for the function for use as a @@ -55,14 +54,13 @@ class NodeNamer { auto fn_loc = Parse::Node::Invalid; GetScopeInfo(fn_scope).name = globals.AllocateName( *this, fn_loc, - fn.name_id.is_valid() ? semantics_ir.strings().Get(fn.name_id).str() - : ""); + fn.name_id.is_valid() ? sem_ir.strings().Get(fn.name_id).str() : ""); CollectNamesInBlock(fn_scope, fn.param_refs_id); if (fn.return_slot_id.is_valid()) { nodes[fn.return_slot_id.index] = { fn_scope, GetScopeInfo(fn_scope).nodes.AllocateName( - *this, semantics_ir.nodes().Get(fn.return_slot_id).parse_node(), + *this, sem_ir.nodes().Get(fn.return_slot_id).parse_node(), "return")}; } if (!fn.body_block_ids.empty()) { @@ -77,8 +75,7 @@ class NodeNamer { } // Build each class scope. - for (auto [i, class_info] : - llvm::enumerate(semantics_ir.classes().array_ref())) { + for (auto [i, class_info] : llvm::enumerate(sem_ir.classes().array_ref())) { auto class_id = ClassId(i); auto class_scope = GetScopeFor(class_id); // TODO: Provide a location for the class for use as a @@ -87,7 +84,7 @@ class NodeNamer { GetScopeInfo(class_scope).name = globals.AllocateName( *this, class_loc, class_info.name_id.is_valid() - ? semantics_ir.strings().Get(class_info.name_id).str() + ? sem_ir.strings().Get(class_info.name_id).str() : ""); AddBlockLabel(class_scope, class_info.body_block_id, "class", class_loc); CollectNamesInBlock(class_scope, class_info.body_block_id); @@ -101,7 +98,7 @@ class NodeNamer { // Returns the scope index corresponding to a class. auto GetScopeFor(ClassId class_id) -> ScopeIndex { - return static_cast(1 + semantics_ir_.functions().size() + + return static_cast(1 + sem_ir_.functions().size() + class_id.index); } @@ -288,9 +285,9 @@ class NodeNamer { } if (parse_node == Parse::Node::Invalid) { - if (const auto& block = semantics_ir_.node_blocks().Get(block_id); + if (const auto& block = sem_ir_.node_blocks().Get(block_id); !block.empty()) { - parse_node = semantics_ir_.nodes().Get(block.front()).parse_node(); + parse_node = sem_ir_.nodes().Get(block.front()).parse_node(); } } @@ -379,19 +376,19 @@ class NodeNamer { Scope& scope = GetScopeInfo(scope_idx); // Use bound names where available. Otherwise, assign a backup name. - for (auto node_id : semantics_ir_.node_blocks().Get(block_id)) { + for (auto node_id : sem_ir_.node_blocks().Get(block_id)) { if (!node_id.is_valid()) { continue; } - auto node = semantics_ir_.nodes().Get(node_id); + auto node = sem_ir_.nodes().Get(node_id); auto add_node_name = [&](std::string name) { nodes[node_id.index] = {scope_idx, scope.nodes.AllocateName( *this, node.parse_node(), name)}; }; auto add_node_name_id = [&](StringId name_id) { if (name_id.is_valid()) { - add_node_name(semantics_ir_.strings().Get(name_id).str()); + add_node_name(sem_ir_.strings().Get(name_id).str()); } else { add_node_name(""); } @@ -419,22 +416,20 @@ class NodeNamer { continue; } case FunctionDeclaration::Kind: { - add_node_name_id(semantics_ir_.functions() + add_node_name_id(sem_ir_.functions() .Get(node.As().function_id) .name_id); continue; } case ClassType::Kind: { - add_node_name_id(semantics_ir_.classes() - .Get(node.As().class_id) - .name_id); + add_node_name_id( + sem_ir_.classes().Get(node.As().class_id).name_id); continue; } case NameReference::Kind: { - add_node_name(semantics_ir_.strings() - .Get(node.As().name_id) - .str() + - ".ref"); + add_node_name( + sem_ir_.strings().Get(node.As().name_id).str() + + ".ref"); continue; } case Parameter::Kind: { @@ -462,7 +457,7 @@ class NodeNamer { const Lex::TokenizedBuffer& tokenized_buffer_; const Parse::Tree& parse_tree_; - const File& semantics_ir_; + const File& sem_ir_; Namespace globals = {.prefix = "@"}; std::vector> nodes; @@ -475,38 +470,37 @@ class NodeNamer { class Formatter { public: explicit Formatter(const Lex::TokenizedBuffer& tokenized_buffer, - const Parse::Tree& parse_tree, const File& semantics_ir, + const Parse::Tree& parse_tree, const File& sem_ir, llvm::raw_ostream& out) - : semantics_ir_(semantics_ir), + : sem_ir_(sem_ir), out_(out), - node_namer_(tokenized_buffer, parse_tree, semantics_ir) {} + node_namer_(tokenized_buffer, parse_tree, sem_ir) {} auto Format() -> void { - out_ << "file \"" << semantics_ir_.filename() << "\" {\n"; + out_ << "file \"" << sem_ir_.filename() << "\" {\n"; // TODO: Include information from the package declaration, once we // fully support it. // TODO: Handle the case where there are multiple top-level node blocks. // For example, there may be branching in the initializer of a global or a // type expression. - if (auto block_id = semantics_ir_.top_node_block_id(); - block_id.is_valid()) { + if (auto block_id = sem_ir_.top_node_block_id(); block_id.is_valid()) { llvm::SaveAndRestore package_scope(scope_, NodeNamer::ScopeIndex::Package); FormatCodeBlock(block_id); } out_ << "}\n"; - for (int i : llvm::seq(semantics_ir_.classes().size())) { + for (int i : llvm::seq(sem_ir_.classes().size())) { FormatClass(ClassId(i)); } - for (int i : llvm::seq(semantics_ir_.functions().size())) { + for (int i : llvm::seq(sem_ir_.functions().size())) { FormatFunction(FunctionId(i)); } } auto FormatClass(ClassId id) -> void { - const Class& class_info = semantics_ir_.classes().Get(id); + const Class& class_info = sem_ir_.classes().Get(id); out_ << "\nclass "; FormatClassName(id); @@ -525,7 +519,7 @@ class Formatter { } auto FormatFunction(FunctionId id) -> void { - const Function& fn = semantics_ir_.functions().Get(id); + const Function& fn = sem_ir_.functions().Get(id); out_ << "\nfn "; FormatFunctionName(id); @@ -534,8 +528,7 @@ class Formatter { llvm::SaveAndRestore function_scope(scope_, node_namer_.GetScopeFor(id)); llvm::ListSeparator sep; - for (const NodeId param_id : - semantics_ir_.node_blocks().Get(fn.param_refs_id)) { + for (const NodeId param_id : sem_ir_.node_blocks().Get(fn.param_refs_id)) { out_ << sep; if (!param_id.is_valid()) { out_ << "invalid"; @@ -543,7 +536,7 @@ class Formatter { } FormatNodeName(param_id); out_ << ": "; - FormatType(semantics_ir_.nodes().Get(param_id).type_id()); + FormatType(sem_ir_.nodes().Get(param_id).type_id()); } out_ << ")"; if (fn.return_type_id.is_valid()) { @@ -578,7 +571,7 @@ class Formatter { return; } - for (const NodeId node_id : semantics_ir_.node_blocks().Get(block_id)) { + for (const NodeId node_id : sem_ir_.node_blocks().Get(block_id)) { FormatInstruction(node_id); } } @@ -588,7 +581,7 @@ class Formatter { // Name scopes aren't kept in any particular order. Sort the entries before // we print them for stability and consistency. llvm::SmallVector> entries; - for (auto [name_id, node_id] : semantics_ir_.name_scopes().Get(id)) { + for (auto [name_id, node_id] : sem_ir_.name_scopes().Get(id)) { entries.push_back({node_id, name_id}); } llvm::sort(entries, @@ -610,7 +603,7 @@ class Formatter { return; } - FormatInstruction(node_id, semantics_ir_.nodes().Get(node_id)); + FormatInstruction(node_id, sem_ir_.nodes().Get(node_id)); } auto FormatInstruction(NodeId node_id, Node node) -> void { @@ -641,7 +634,7 @@ class Formatter { case NodeValueKind::Typed: FormatNodeName(node_id); out_ << ": "; - switch (GetExpressionCategory(semantics_ir_, node_id)) { + switch (GetExpressionCategory(sem_ir_, node_id)) { case ExpressionCategory::NotExpression: case ExpressionCategory::Error: case ExpressionCategory::Value: @@ -720,7 +713,7 @@ class Formatter { FormatArg(node.tuple_id); llvm::ArrayRef inits_and_return_slot = - semantics_ir_.node_blocks().Get(node.inits_and_return_slot_id); + sem_ir_.node_blocks().Get(node.inits_and_return_slot_id); auto inits = inits_and_return_slot.drop_back(1); auto return_slot_id = inits_and_return_slot.back(); @@ -738,11 +731,10 @@ class Formatter { out_ << " "; FormatArg(node.callee_id); - llvm::ArrayRef args = semantics_ir_.node_blocks().Get(node.args_id); + llvm::ArrayRef args = sem_ir_.node_blocks().Get(node.args_id); bool has_return_slot = - GetInitializingRepresentation(semantics_ir_, node.type_id) - .has_return_slot(); + GetInitializingRepresentation(sem_ir_, node.type_id).has_return_slot(); NodeId return_slot_id = NodeId::Invalid; if (has_return_slot) { return_slot_id = args.back(); @@ -776,7 +768,7 @@ class Formatter { auto FormatInstructionRHS(SpliceBlock node) -> void { FormatArgs(node.result_id); out_ << " {"; - if (!semantics_ir_.node_blocks().Get(node.block_id).empty()) { + if (!sem_ir_.node_blocks().Get(node.block_id).empty()) { out_ << "\n"; indent_ += 2; FormatCodeBlock(node.block_id); @@ -793,9 +785,9 @@ class Formatter { auto FormatInstructionRHS(StructType node) -> void { out_ << " {"; llvm::ListSeparator sep; - for (auto field_id : semantics_ir_.node_blocks().Get(node.fields_id)) { + for (auto field_id : sem_ir_.node_blocks().Get(node.fields_id)) { out_ << sep << "."; - auto field = semantics_ir_.nodes().GetAs(field_id); + auto field = sem_ir_.nodes().GetAs(field_id); FormatString(field.name_id); out_ << ": "; FormatType(field.field_type_id); @@ -821,7 +813,7 @@ class Formatter { auto FormatArg(ClassId id) -> void { FormatClassName(id); } auto FormatArg(IntegerId id) -> void { - semantics_ir_.integers().Get(id).print(out_, /*isSigned=*/false); + sem_ir_.integers().Get(id).print(out_, /*isSigned=*/false); } auto FormatArg(MemberIndex index) -> void { out_ << index; } @@ -837,7 +829,7 @@ class Formatter { auto FormatArg(NodeBlockId id) -> void { out_ << '('; llvm::ListSeparator sep; - for (auto node_id : semantics_ir_.node_blocks().Get(id)) { + for (auto node_id : sem_ir_.node_blocks().Get(id)) { out_ << sep; FormatArg(node_id); } @@ -846,14 +838,14 @@ class Formatter { auto FormatArg(RealId id) -> void { // TODO: Format with a `.` when the exponent is near zero. - const auto& real = semantics_ir_.reals().Get(id); + const auto& real = sem_ir_.reals().Get(id); real.mantissa.print(out_, /*isSigned=*/false); out_ << (real.is_decimal ? 'e' : 'p') << real.exponent; } auto FormatArg(StringId id) -> void { out_ << '"'; - out_.write_escaped(semantics_ir_.strings().Get(id), /*UseHexEscapes=*/true); + out_.write_escaped(sem_ir_.strings().Get(id), /*UseHexEscapes=*/true); out_ << '"'; } @@ -862,7 +854,7 @@ class Formatter { auto FormatArg(TypeBlockId id) -> void { out_ << '('; llvm::ListSeparator sep; - for (auto type_id : semantics_ir_.type_blocks().Get(id)) { + for (auto type_id : sem_ir_.type_blocks().Get(id)) { out_ << sep; FormatArg(type_id); } @@ -882,9 +874,7 @@ class Formatter { out_ << node_namer_.GetLabelFor(scope_, id); } - auto FormatString(StringId id) -> void { - out_ << semantics_ir_.strings().Get(id); - } + auto FormatString(StringId id) -> void { out_ << sem_ir_.strings().Get(id); } auto FormatFunctionName(FunctionId id) -> void { out_ << node_namer_.GetNameFor(id); @@ -898,12 +888,12 @@ class Formatter { if (!id.is_valid()) { out_ << "invalid"; } else { - out_ << semantics_ir_.StringifyType(id, /*in_type_context=*/true); + out_ << sem_ir_.StringifyType(id, /*in_type_context=*/true); } } private: - const File& semantics_ir_; + const File& sem_ir_; llvm::raw_ostream& out_; NodeNamer node_namer_; NodeNamer::ScopeIndex scope_ = NodeNamer::ScopeIndex::None; @@ -912,9 +902,9 @@ class Formatter { }; auto FormatFile(const Lex::TokenizedBuffer& tokenized_buffer, - const Parse::Tree& parse_tree, const File& semantics_ir, + const Parse::Tree& parse_tree, const File& sem_ir, llvm::raw_ostream& out) -> void { - Formatter(tokenized_buffer, parse_tree, semantics_ir, out).Format(); + Formatter(tokenized_buffer, parse_tree, sem_ir, out).Format(); } } // namespace Carbon::SemIR diff --git a/toolchain/sem_ir/formatter.h b/toolchain/sem_ir/formatter.h index f07f4912f8ca..29d4d6f87ce8 100644 --- a/toolchain/sem_ir/formatter.h +++ b/toolchain/sem_ir/formatter.h @@ -11,7 +11,7 @@ namespace Carbon::SemIR { auto FormatFile(const Lex::TokenizedBuffer& tokenized_buffer, - const Parse::Tree& parse_tree, const File& semantics_ir, + const Parse::Tree& parse_tree, const File& sem_ir, llvm::raw_ostream& out) -> void; } // namespace Carbon::SemIR