Files
carbon-lang/explorer/interpreter/action.cpp
T
4845f40dff Switch CARBON_CHECK to a format string API (#4285)
This switches `DCHECK` and `FATAL` as well.

The goal is to reduce the code size impact of these assertions so that
we can keep more of them enabled. Currently, the largest cost I see from
`CHECK` is not the actual check or the cold code itself, but actually
the failure to inline trivial functions due to the presence of the cold
code. This means that our goal isn't to reduce apparent code size in the
final binary but the LLVM IR cost assessed for these routines in the
inliner, which closely correlates with code size but is a bit different.

As discussed in #4283, experimentation shows that a single function call
with a minimal number of arguments is the lowest cost model for these.
This is easily achieved with a format-string API that internally uses
`llvm::formatv`. This PR is essentially the `CHECK` version of #4283.

However, the check macros are substantially harder to make work with
both format strings and streaming because they also take a condition.
Also, unexpectedly, I was very successful at devising a regular
expression based automated rewrite from the streaming to the format
string form with only low 10s of manual fixes. This includes compacting
strings broken up across lines, etc. Given how well that went, I've
prepared this PR which just directly switches to the format string API
and migrate everything to use it.

One nice side-effect is that the format string approach ends up greatly
simplifying the implementation here as well.

This is ... *shockingly* effective. Parsing speeds up by more than 3%
with just this change. And checking speeds up by **8%** with this change
alone:
```
BM_CompileAPIFileDenseDecls<Phase::Parse>/256      86.3µs ± 1%  82.9µs ± 1%  -3.94%  (p=0.000 n=17+19)
BM_CompileAPIFileDenseDecls<Phase::Parse>/1024      431µs ± 1%   415µs ± 1%  -3.76%  (p=0.000 n=18+19)
BM_CompileAPIFileDenseDecls<Phase::Parse>/4096     1.77ms ± 1%  1.71ms ± 1%  -3.18%  (p=0.000 n=18+19)
BM_CompileAPIFileDenseDecls<Phase::Parse>/16384    7.44ms ± 1%  7.17ms ± 2%  -3.56%  (p=0.000 n=18+20)
BM_CompileAPIFileDenseDecls<Phase::Parse>/65536    30.7ms ± 1%  29.7ms ± 1%  -3.15%  (p=0.000 n=18+20)
BM_CompileAPIFileDenseDecls<Phase::Parse>/262144    131ms ± 1%   127ms ± 1%  -2.81%  (p=0.000 n=18+18)
BM_CompileAPIFileDenseDecls<Phase::Check>/256       878µs ± 2%   800µs ± 1%  -8.91%  (p=0.000 n=19+20)
BM_CompileAPIFileDenseDecls<Phase::Check>/1024     1.88ms ± 2%  1.72ms ± 1%  -8.56%  (p=0.000 n=19+20)
BM_CompileAPIFileDenseDecls<Phase::Check>/4096     5.78ms ± 2%  5.28ms ± 1%  -8.70%  (p=0.000 n=20+18)
BM_CompileAPIFileDenseDecls<Phase::Check>/16384    21.9ms ± 1%  20.1ms ± 1%  -8.02%  (p=0.000 n=18+20)
BM_CompileAPIFileDenseDecls<Phase::Check>/65536    90.4ms ± 2%  83.1ms ± 1%  -8.04%  (p=0.000 n=19+20)
BM_CompileAPIFileDenseDecls<Phase::Check>/262144    381ms ± 2%   352ms ± 1%  -7.79%  (p=0.000 n=19+19)
```

---------

Co-authored-by: Richard Smith <richard@metafoo.co.uk>
Co-authored-by: josh11b <15258583+josh11b@users.noreply.github.com>
2024-09-12 16:42:08 +00:00

213 lines
7.2 KiB
C++

// Part of the Carbon Language project, under the Apache License v2.0 with LLVM
// Exceptions. See /LICENSE for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
#include "explorer/interpreter/action.h"
#include <iterator>
#include <map>
#include <optional>
#include <utility>
#include <vector>
#include "common/check.h"
#include "common/error.h"
#include "explorer/ast/declaration.h"
#include "explorer/ast/expression.h"
#include "explorer/ast/value.h"
#include "explorer/base/arena.h"
#include "explorer/base/print_as_id.h"
#include "explorer/base/source_location.h"
#include "explorer/interpreter/stack.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/Support/Casting.h"
namespace Carbon {
using llvm::cast;
RuntimeScope::RuntimeScope(RuntimeScope&& other) noexcept
: locals_(std::move(other.locals_)),
bound_values_(std::move(other.bound_values_)),
// To transfer ownership of other.allocations_, we have to empty it out.
allocations_(std::exchange(other.allocations_, {})),
heap_(other.heap_) {}
auto RuntimeScope::operator=(RuntimeScope&& rhs) noexcept -> RuntimeScope& {
locals_ = std::move(rhs.locals_);
bound_values_ = std::move(rhs.bound_values_);
// To transfer ownership of rhs.allocations_, we have to empty it out.
allocations_ = std::exchange(rhs.allocations_, {});
heap_ = rhs.heap_;
return *this;
}
void RuntimeScope::Print(llvm::raw_ostream& out) const {
out << "scope: [";
llvm::ListSeparator sep;
for (const auto& [value_node, value] : locals_) {
out << sep << "`" << value_node.base() << "`: `" << *value << "`";
}
out << "]";
}
void RuntimeScope::Bind(ValueNodeView value_node, Address address) {
CARBON_CHECK(!value_node.constant_value().has_value());
bool success =
locals_.insert({value_node, heap_->arena().New<LocationValue>(address)})
.second;
CARBON_CHECK(success, "Duplicate definition of {0}", value_node.base());
}
void RuntimeScope::BindAndPin(ValueNodeView value_node, Address address) {
Bind(value_node, address);
bool success = bound_values_.insert(&value_node.base()).second;
CARBON_CHECK(success, "Duplicate pinned node for {0}", value_node.base());
heap_->BindValueToReference(value_node, address);
}
void RuntimeScope::BindLifetimeToScope(Address address) {
CARBON_CHECK(address.element_path_.IsEmpty(),
"Cannot extend lifetime of a specific sub-element");
allocations_.push_back(address.allocation_);
}
void RuntimeScope::BindValue(ValueNodeView value_node,
Nonnull<const Value*> value) {
CARBON_CHECK(!value_node.constant_value().has_value());
CARBON_CHECK(value->kind() != Value::Kind::LocationValue);
bool success = locals_.insert({value_node, value}).second;
CARBON_CHECK(success, "Duplicate definition of {0}", value_node.base());
}
auto RuntimeScope::Initialize(ValueNodeView value_node,
Nonnull<const Value*> value)
-> Nonnull<const LocationValue*> {
CARBON_CHECK(!value_node.constant_value().has_value());
CARBON_CHECK(value->kind() != Value::Kind::LocationValue);
allocations_.push_back(heap_->AllocateValue(value));
const auto* location =
heap_->arena().New<LocationValue>(Address(allocations_.back()));
bool success = locals_.insert({value_node, location}).second;
CARBON_CHECK(success, "Duplicate definition of {0}", value_node.base());
return location;
}
void RuntimeScope::Merge(RuntimeScope other) {
CARBON_CHECK(heap_ == other.heap_);
for (auto& element : other.locals_) {
bool success = locals_.insert(element).second;
CARBON_CHECK(success, "Duplicate definition of {0}", element.first);
}
for (const auto* element : other.bound_values_) {
bool success = bound_values_.insert(element).second;
CARBON_CHECK(success, "Duplicate bound value.");
}
allocations_.insert(allocations_.end(), other.allocations_.begin(),
other.allocations_.end());
other.allocations_.clear();
}
auto RuntimeScope::Get(ValueNodeView value_node,
SourceLocation source_loc) const
-> ErrorOr<std::optional<Nonnull<const Value*>>> {
auto it = locals_.find(value_node);
if (it == locals_.end()) {
return {std::nullopt};
}
if (bound_values_.contains(&value_node.base())) {
// Check if the bound value is still alive.
CARBON_CHECK(it->second->kind() == Value::Kind::LocationValue);
if (!heap_->is_bound_value_alive(
value_node, cast<LocationValue>(it->second)->address())) {
return ProgramError(source_loc)
<< "Reference has changed since this value was bound.";
}
}
return {it->second};
}
auto RuntimeScope::Capture(
const std::vector<Nonnull<const RuntimeScope*>>& scopes) -> RuntimeScope {
CARBON_CHECK(!scopes.empty());
RuntimeScope result(scopes.front()->heap_);
for (Nonnull<const RuntimeScope*> scope : scopes) {
CARBON_CHECK(scope->heap_ == result.heap_);
for (const auto& entry : scope->locals_) {
// Intentionally disregards duplicates later in the vector.
result.locals_.insert(entry);
}
}
return result;
}
void Action::Print(llvm::raw_ostream& out) const {
out << kind_string() << " pos: " << pos_ << " ";
switch (kind()) {
case Action::Kind::LocationAction:
out << "`" << cast<LocationAction>(*this).expression() << "`";
break;
case Action::Kind::ValueExpressionAction:
out << "`" << cast<ValueExpressionAction>(*this).expression() << "`";
break;
case Action::Kind::ExpressionAction:
out << "`" << cast<ExpressionAction>(*this).expression() << "`";
break;
case Action::Kind::WitnessAction:
out << "`" << *cast<WitnessAction>(*this).witness() << "`";
break;
case Action::Kind::StatementAction:
out << "`" << PrintAsID(cast<StatementAction>(*this).statement()) << "`";
break;
case Action::Kind::DeclarationAction:
out << "`" << PrintAsID(cast<DeclarationAction>(*this).declaration())
<< "`";
break;
case Action::Kind::TypeInstantiationAction:
out << "`" << *cast<TypeInstantiationAction>(*this).type() << "`";
break;
default:
break;
}
if (!results_.empty()) {
out << " results: [";
llvm::ListSeparator sep;
for (const auto& result : results_) {
out << sep << "`" << *result << "`";
}
out << "] ";
}
if (scope_.has_value()) {
out << " " << *scope_;
}
}
auto Action::kind_string() const -> std::string_view {
switch (kind()) {
case Action::Kind::LocationAction:
return "LocationAction";
case Action::Kind::ValueExpressionAction:
return "ValueExpressionAction";
case Action::Kind::ExpressionAction:
return "ExpressionAction";
case Action::Kind::WitnessAction:
return "WitnessAction";
case Action::Kind::StatementAction:
return "StatementAction";
case Action::Kind::DeclarationAction:
return "DeclarationAction";
case Action::Kind::TypeInstantiationAction:
return "TypeInstantiationAction";
case Action::Kind::ScopeAction:
return "ScopeAction";
case Action::Kind::RecursiveAction:
return "RecursiveAction";
case Action::Kind::CleanUpAction:
return "CleanUpAction";
case Action::Kind::DestroyAction:
return "DestroyAction";
}
}
} // namespace Carbon