Commit Graph
3130 Commits
Author SHA1 Message Date
Dana Jansens f2479321fc Correct name of ComparableFromDifference in Generics details (#4547)
The name ComparableFromDifferenceFn comes from the next example. In this
example ComparableFromDifference is the name of the class that will be
implictly cast to a Facet matching Comparable.
2024-11-18 17:18:59 +00:00
Dana Jansens cb94609889 Suppress readability-redundant-member-init (#4538)
This initializes the DriverResult::per_file_success field explicitly
with `= {}` in order to encode that DriverResult can be constucted via
aggregate initialization while omitting the per_file_success field. This
prevents -Wmissing-designated-field-initializers from firing in newer
clang versions when constructing DriverResult like:
```
return {.success = false};
```

Newer clang-tidy warns that the `= {}` is redundant however it is not,
as its marking which fields need to be explicitly initialized. So we
suppress it.
2024-11-18 16:38:46 +00:00
Richard Smith 145f878ce8 Allow extend adapt of non-class types. (#4544)
Stop rejecting `extend adapt` of non-class types such as struct and
tuple. These don't actually work just yet because name lookup into
struct and tuple types is a special case that doesn't handle adapters,
but this gets us a bit closer.

This also slightly improves error recovery for name lookup into an
invalid scope.
2024-11-18 16:01:44 +00:00
Richard Smith bc395eb889 Represent integer literals as IntLiteral not as i32. (#4532)
When an `IntLiteral` appears as an operand of an `if` expression,
convert it to `i32` for now, so that we don't reject things like `if
cond then 1 else 2` due to having a non-constant value of type
`IntLiteral`.

For tuple indexing expressions such as `(a, b).0`, convert the index to
type `IntLiteral`, not to type `i32`. This isn't strictly necessary to
do in this PR, but avoids the need to provide an `IntLiteral` -> `i32`
implicit conversion for `no_prelude` tests using this syntax.
v0.0.0-0.nightly.2024.11.18 v0.0.0-0.nightly.2024.11.17 v0.0.0-0.nightly.2024.11.16
2024-11-15 23:24:15 +00:00
Richard Smith 980ce6b25a Convert array bounds to IntLiteral. (#4526)
Instead of leaving array bounds as whatever integer type they arrive as,
convert them to the `IntLiteral` type as part of forming an `ArrayType`.
This ensures that array types canonicalize properly even when the bounds
are specified with different types.

Create an empty generic definition for a generic builtin function to
avoid this causing "use of undefined generic function" errors.
2024-11-15 22:09:31 +00:00
Dana Jansens a65cde6ae2 Use llvm::any_of instead of std::ranges::any_of (#4542)
We do not intend to use std::ranges in the Carbon implementation due to
concerns of compile time cost, largely due to implicit instantiation of
types involved in calling and typechecking the functions and their
requires clauses.

In #4539, we converted std::any_of to std::ranges::any_of, but this
replaces that with llvm::any_of from llvm/ADT/STLExtras.h.

This conversion was suggested by the modernize-use-ranges clang-tidy
check. We can keep the check on, and use it to guide conversion to llvm
helpers that do similar things (as was done in this CL now). If it's
being too confusing, then it can be disabled as well.
2024-11-15 21:59:32 +00:00
Jon Ross-Perkins 86a057b820 Add blank lines betweeen EntityWithParamsBase members. (#4536)
This is at a point where it's getting difficult to read, and #4479 is
adding a large block comment. In order to more clearly delineate
members, add blank lines between.
2024-11-15 21:53:36 +00:00
Richard Smith ff530305d1 Add prelude support for implicit conversion between integer literals and sized integer types. (#4525)
In preparation for changing integer literals to be of `IntLiteral` type.
Conversions from the integer literal type are only permitted when the
value fits within the destination type.

For now, if conversion cannot be checked because the source value is a
symbolic constant, produce a symbolic constant representing the
conversion rather than rejecting it.
2024-11-15 21:46:14 +00:00
Jon Ross-Perkins c2ff865700 Reconstruct rational for disabled clang-tidy checks. (#4541)
Commenting on danakj's clang-tidy PRs, it would've been helpful to just
have a quick reference for older checks. So while I've been getting
comments for new things, go back and comment the ones that predate
adding per-check comments.

I did this mainly by running clang-tidy and seeing whether we could
re-enable them, thus also fixing the clang-tidy wrapper script.

Adding backticks to try to make it easier to scan.
2024-11-15 21:17:27 +00:00
4ee65ef58a Reduce the size of formatted SemIR. (#4534)
- Do not include entities imported from files that we are not dumping.
- Do not include constants and import_refs that are not referenced by
something that we are including in the formatted output.

---------

Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
Co-authored-by: Carbon Infra Bot <carbon-external-infra@google.com>
2024-11-15 21:00:26 +00:00
Dana Jansens 3c18a6c477 Suppress readability-enum-initial-value in clang-tidy (#4540)
This warns unhelpfully on enums like:

```
enum Kind: int8_t {
  Value,
  ValueOrRef,
  ...
  FullInitializer,
  Last = FullInitializer
};
```

It claims that all enum values should have explicit values if any of the
values do, but that's not what we would want to write here.
2024-11-15 20:02:03 +00:00
Dana Jansens 9112053cee Use std::ranges::any_of instead of std::any_of (#4539)
This is suggested by clang-tidy's modernize checks, and is a safer
coding practice.
2024-11-15 19:51:21 +00:00
Jon Ross-Perkins 1d8c7ffe89 Add support for scoped timings. (#4533)
I think there are a few related ways to do this. I considered
llvm::make_scope_exit, but the return type is difficult to work with. I
particularly was thinking I could encapsulate the duration logic this
way.
2024-11-15 16:57:33 +00:00
Jon Ross-Perkins fe5d3cecbd Try running 'bazel cquery //...' before target-determinator (#4531)
Trying to improve robustness against failures such as
[here](https://github.com/carbon-language/carbon-lang/actions/runs/11845529962/job/33011203628):

```
WARNING: Download from https://ftp.gnu.org/gnu/m4/m4-1.4.18.tar.xz failed: class java.net.ConnectException Connection refused
```

Which is coming from the target-determinator invocation:

```
subprocess.CalledProcessError: Command '['/home/runner/.cache/carbon-lang-scripts/target-determinator', '--bazel=/usr/local/bin/bazelisk', 'a720921dfb99c21f08832663c91a1f9e48a1bcc4']' returned non-zero exit status 1.
```

My thought is that the `bazel cquery` should trigger equivalent
downloads (equally though, I'd thought the `bazel mod deps` would do
that, so I don't want to give the impression of confidence).

It's harder to inject this into the target-determinator command line,
since we'd need something that retries by default.
2024-11-15 01:01:24 +00:00
josh11bandJosh L 93169c30b1 Update LLVM (#4530)
Includes updates to reflect these LLVM changes:
* https://github.com/llvm/llvm-project/pull/112517
* https://github.com/llvm/llvm-project/pull/113331

---------

Co-authored-by: Josh L <josh11b@users.noreply.github.com>
2024-11-15 00:09:10 +00:00
Jon Ross-Perkins b2ea19f269 Add a small lowering test with an imported argument. (#4529)
We don't have much import coverage at present, but this seems worth a
tiny bit of validation. I believe the LLVM IR is currently correct.
v0.0.0-0.nightly.2024.11.15
2024-11-14 21:16:46 +00:00
Jon Ross-Perkins a720921dfb Test an absolute symlink (#4528) 2024-11-14 18:48:26 +00:00
Jon Ross-Perkins c59faea0e8 Fix up busybox detection for relative symlinks (#4522)
Handling for relative symlinks is new (comment talks about relative
symlinks). Relocated to add tests though, to do extra checking of logic.
2024-11-14 17:13:01 +00:00
Richard Smith cbd88e5c72 Add builtin for performing checked conversion between integer types. (#4523)
As a prerequisite for switching the type of int literals to be the
`IntLiteral` type, add support for performing conversions of in-bounds
integer constant values to other integer types in which they fit.

This incidentally is our first compile-time-only builtin function, so
add very minimal support for compile-time-only functions while we're
here.
v0.0.0-0.nightly.2024.11.14
2024-11-14 00:27:40 +00:00
josh11bandJosh L abd12c18c7 Support extended scopes that are parameterized types (#4524)
* The `extended_scopes` in a `NameScope` were represented by a
`NameScopeId`. Replace that with an `InstId` of an instruction returning
the type that is extending this name scope.
* `Context::LookupQualifiedName` now can take multiple scopes to look
in.
* `GetAsLookupScope` was moved out of `member_access.cpp` and is now
`Context::AppendLookupScopesForConstant`

This PR also fixes some existing issues that were revealed as part of
writing and testing this PR:
* Additional validation and handling of invalid ids.
* `extend impl` in a class is not properly imported yet, but at least
now it doesn't crash.

The change to use an `InstId` also allowed some diagnostics and
formatting to be improved.

---------

Co-authored-by: Josh L <josh11b@users.noreply.github.com>
2024-11-13 23:48:02 +00:00
Jon Ross-Perkins 5e293ad97f Fix bazel-bin invocations of run_tool (#4521)
SCRIPT_LOCATION contains `bazel-out`, so this drops the portions shared
between the script and tool locations before removing the suffix.
2024-11-13 18:16:49 +00:00
Chandler Carruth f17939e252 Follow-up to #4487 to fix file names (#4520)
This switches from `int_store*` to `int*` as this file contains both the
ID and the store for integers.

This was supposed to be added to #4487 before merging, apologies for
missing that.
2024-11-13 18:10:52 +00:00
Jon Ross-Perkins fa95892a37 Add diagnostic coverage, remove possibly-unreachable unary op diagnostic (#4519)
I'm working to make sure remaining diagnostics have coverage, at least
the ones I'd previously added a TODO for. Note in particular that I
couldn't figure out a repro for UnaryOperatorRequiresWhitespace; if you
have one, I can add a test, but otherwise maybe it's actually
unreachable due to being diagnosed through infix logic (or, maybe
this'll let fuzzing tell me an example).
2024-11-13 18:04:25 +00:00
3ba4997855 Canonicalize away bit width and embed small integers into IntIds (#4487)
The first change here is to canonicalize away bit width when tracking
integers in our shared value store. This lets us have a more definitive
model of "what is the mathematical value". It also frees us to use more
efficient bit widths when available, such as bits inside the ID itself.

For canonicalizing, we try to minimize the width adjustments and
maximize the use of the SSO in APInt, and so we never shrink belowe
64-bits and grow in multiples of the word bit width in the
implementation. We also canonicalize to the signed 2s compliment
representation so we can represent negative numbers in an intuitive way.

The canonicalizing requires getting the bit width out of the type and
adjusting to it within the toolchain when doing any kind of math, and
this PR updates various places to do that, as well as adding some
convenience APIs to assist.

Then we take advantage of the canonical form and embed small integers
into the ID itself rather than allocating storage for them and
referencing them with an index. This is especially helpful for the
pervasive small integers such as the sizes of types, arrays, etc. Those
no longer require indirection at all. Various short-cut APIs to take
advantage of this have also been added.

This PR improves lexing by about 5% when there are lots of `i32` types.

---------

Co-authored-by: Dana Jansens <danakj@orodu.net>
Co-authored-by: Carbon Infra Bot <carbon-external-infra@google.com>
Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2024-11-13 09:36:20 +00:00
josh11bandJosh L 39ed62dad7 Add facet_types() accessor to Check::Context (#4518)
Co-authored-by: Josh L <josh11b@users.noreply.github.com>
2024-11-13 01:20:07 +00:00
Sam EstepandJon Ross-Perkins e0e305536e Collect timing data per unit for each phase (#4512)
This PR adds a `--dump-timings` flag to the `compile` subcommand
(similar to the existing `--dump-mem-usage` flag), which collects timing
data per compilation unit for each compilation phase. For example, on my
2020 M1 MacBook:

```
$ bazel build -c opt //toolchain
$ bazel-bin/toolchain/install/run_carbon compile --phase=lower --dump-timings examples/sieve.carbon | tail
...
---
filename:        'examples/sieve.carbon'
nanoseconds:
  lex:             30792
  parse:           25458
  check:           226625
  lower:           1136958
  Total:           1419833
...
```

Most of the changes are pretty straightforward. There were a couple I
wasn't sure about though; let me know if I should change:

- new `Timings` class in its own file, pretty similar to the existing
`MemUsage` class
- added a `timings_` field to the `CompilationUnit` class
- added a `timings` field to the `Check::Unit` struct
- renamed `CheckParseTree` function to `CheckParseTreeInner` for ease of
timing with early `return`

---------

Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2024-11-12 20:47:08 +00:00
josh11bandJosh L 3824c5fd30 Look in libraries associated with the interface (#4510)
This was broken by #4499 .

---------

Co-authored-by: Josh L <josh11b@users.noreply.github.com>
2024-11-12 20:35:32 +00:00
josh11bandJosh L ada9564077 Add missing #include (#4513)
Co-authored-by: Josh L <josh11b@users.noreply.github.com>
2024-11-12 16:53:41 +00:00
David Blaikie 79c5c47911 Preserve the is_dynamic property of classes when importing them (#4501)
The test update shows a class derived from an imported base class with a
vptr, and without this change the derived class got its own vptr, with
this change the derived class can see the base is dynamic, so the
derived doesn't need to add a vptr and can rely on the base class's vptr
instead.
2024-11-12 16:11:19 +00:00
Richard Smith 0a6321f492 Include the arguments for a generic class or interface in diagnostics. (#4511)
This can lead to us trying and failing to print certain kinds of
constant value, but we can fix that in future changes.

Note that `StringifyType` should probably be substantially refactored.
For this change I'm trying to leave the overall structure relatively
intact, but hopefully this additional formatting support will help guide
future refactorings.
2024-11-12 01:47:33 +00:00
Richard Smith de9b7d282a Fix use-after-free printing the name of an interface that might have been invalidated by lazy import. (#4509)
While here, also change the diagnostic emission to pass the interface
type rather than the interface name. This prepares us to include the
arguments in the diagnostic.
2024-11-12 00:50:10 +00:00
josh11bandJosh L 4f474fafb5 Remove some single-interface restrictions from some uses of facet types (#4508)
Co-authored-by: Josh L <josh11b@users.noreply.github.com>
2024-11-12 00:43:45 +00:00
Richard Smith 2c1d02d991 Don't eagerly materialize an initializing expression used as the object in a compound member access. (#4496)
Instead, wait until we know whether it is used as a value or reference
expression. This allows us to avoid materializing a temporary if it is
used as a value and the initializing representation holds a copy of a
value representation.
2024-11-11 21:32:33 +00:00
a69c2630f9 Replace InterfaceType with FacetType (#4499)
This does a few things:
* Replaces the single `TypeId` in the `FacetTypeInfo` struct with a
vector of `InterfaceId`, `SpecificId` pairs (sorted in id order)
representing the set of interface requirements of the facet type. This
will later be used to support facet types with multiple interface
requirements (as in `I & J` or `I where .Self impls J`).
* Replace `InterfaceType` instructions (used as the type of an
`InterfaceDecl` instruction) with `FacetType` instructions (introduced
in #4460) with a (newly introduced) `FacetTypeFromInterface()` function.
* Replace code that consumed `InterfaceType` values with code that
consumed `FaceType` values. I've generally left the assumption in the
code that it is dealing with a single interface, using the (newly
introduced) `FacetTypeInfo::TryAsSingleInterface`, and producing an
error otherwise. There isn't yet support for the `&` operator or `where
.Self impls`, so this is generally a good assumption for now, except you
can get a facet type with no associated interfaces from a `type
where`... expression. In some cases, the facet type value is pulled from
the evaluation of an `InterfaceDecl` instruction, where the single
interface assumption will hold permanently.
* Some related cleans up: nicer stringification and formatting of facet
types, suppression of some errors when there already was an error.

There is still a lot left to do, including:
* Type `type` should be a facet type with a reserved id, replacing the
built-in instruction.
* Code using `TryAsSingleInterface` should generally be upgraded to
handle more than (or less than) one interface. Name lookup should be
particularly exciting.
* Operator `&` should be defined on facet types, unioning their
interface and other requirements.
* Requirements from a `where` clause don't do anything yet.
* Impls and impl lookup need to resolve facet types, and do things like
determine if all the associated constants are given values.

---------

Co-authored-by: Josh L <josh11b@users.noreply.github.com>
Co-authored-by: Geoff Romer <gromer@google.com>
2024-11-11 18:01:50 +00:00
Jon Ross-Perkins 6dce164c49 Change the bazel-out structure to avoid busybox symlinks. (#4505)
As described in symlink_helpers.bzl, copied here for visibility:

Symlinking busybox things needs special logic.

This is because Bazel doesn't cache the actual symlink, resulting in
essentially resolved symlinks being produced in place of the expected
tool. As a consequence, we can't rely on the symlink name when dealing
with busybox entries.

An example repro of this using a local build cache is:

    bazel build //toolchain
    bazel clean
    bazel build //toolchain

We could in theory get reasonable behavior with
`ctx.actions.declare_symlink`, but that's disallowed in our `.bazelrc`
for cross-environment compatibility.

The particular approach here uses the Python script as a launching pad
so that the busybox still receives an appropriate location in argv[0],
allowing it to find other files in the lib directory. Arguments are
inserted to get equivalent behavior as if symlink resolution had
occurred.

The underlying bug is noted at:
https://github.com/bazelbuild/bazel/issues/23620
2024-11-08 22:08:50 +00:00
Geoff Romer db43bb1b42 Replace FIXME with TODO in toolchain code (#4506) 2024-11-08 21:10:30 +00:00
Geoff RomerandRichard Smith 5759ad8b42 Remove forward references from binding patterns (#4494)
This is primarily to free up space in the BindingPattern insts, but as a
side effect it moves the link between BindingPattern and its BindName
out of the SemIR, and into a transient data structure in Context.

---------

Co-authored-by: Richard Smith <richard@metafoo.co.uk>
2024-11-08 20:18:22 +00:00
Jon Ross-Perkins 10e256a241 Name empty tuples distinctly in SemIR. (#4503)
Building on #4502, give empty tuple values a distinct name, and also
explicitly name tuple types (previously values but not types were
named).
2024-11-08 17:14:52 +00:00
josh11bandJosh L bbeb66b5fe Test class with multiple extend (#4504)
Adds coverage for an existing diagnostic. Code appears to work without
modification.

---------

Co-authored-by: Josh L <josh11b@users.noreply.github.com>
2024-11-08 16:29:53 +00:00
Jon Ross-Perkins cab7818df8 Make empty ids for all block types (#4502)
Adding empty IDs to all block types. This is primarily for
TypeBlockId::Empty, which allows me to disambiguate empty tuple types,
which I think might yield a SemIR readability improvement (PR
forthcoming). I'm splitting PRs so that the limited test impact here is
clear.
v0.0.0-0.nightly.2024.11.08
2024-11-07 22:46:22 +00:00
josh11bandJosh L caba03d27e Support deduction of the types of struct fields (#4500)
Follow-on to #4492 .

---------

Co-authored-by: Josh L <josh11b@users.noreply.github.com>
2024-11-07 21:25:49 +00:00
Jon Ross-Perkins 138ecf108f Remove verbose formatting of instructions on crash messages. (#4495)
Undoes a chunk of #4125 because nobody's really in favor of keeping the
formatting, and it's occasionally caused a crash in Formatter to
dominate output (and even when working, it can be verbose; the source
location in (5) is often more helpful).

Basically goes back to:

```
4.	Check::Context
          NodeStack:
            0. LetIntroducer: no value
            1. BindingPattern: inst+15
            2. LetInitializer: no value
            3. StructLiteralStart: no value
          inst_block_stack_:
            0.	block<invalid>	{inst+0, inst+1, inst+6, inst+7, inst+8, inst+9, inst+10, inst+11, inst+12}
            1.	global_init	{}
          pattern_block_stack_:
            0.	block<invalid>	{}
          param_and_arg_refs_stack:
            0.	block<invalid>	{}
          args_type_info_stack_:
            0.	block<invalid>	{}
5.	alias_of_alias.carbon:15:12: checking StructLiteral
          let d: c = {};
                     ^~
```

Fixes #4145
2024-11-07 16:22:36 +00:00
Jon Ross-Perkins be56ff87c6 Convert StructTypeField to a specific type. (#4492)
This converts `StructTypeField` from an instruction to a dedicated type,
with its own store. This had originated from discussing how
`.GetAs<SemIR::StructTypeField>` was more prevalent than for other
instructions, but is probably more interesting for the storage savings
(16 bytes StructTypeField + 4 byte LocId + 4 byte InstId -> 8 byte
StructTypeField).

Due to the different structure, these now have their own stack during
construction, reducing (but not eliminating) `args_type_info_stack_`
use-cases.

The test changes of different InstIds is expected because structs and
classes generate fewer instructions now. Other than that, results should
remain the same.

I'm generally trying to avoid unrelated cleanup here due to the PR size,
though I did scrutinize the `VerifyOnFinish` calls, adding one and
commenting others (putting them in member order because that's how I was
checking what was verified and what wasn't).
v0.0.0-0.nightly.2024.11.07
2024-11-06 21:38:27 +00:00
Jon Ross-Perkins 7977a9cddc Fix the command used for nightly release versions. (#4498) 2024-11-06 21:04:30 +00:00
David Blaikie d79a374ad4 Skip vptr when performing object initialization (#4490)
The cehck for vptr could be done differently (is this class dynamic and
its base class non-dynamic), and if we change the layout (to put the
vptr after any base) then this code will break (could add an assertion
that the vptr isn't present apart from at the start of the field list if
that'd seem worthwhile).

There's still later issues with lowering (if this patch causes crashes
in lowering, do they result in fuzz failures/need to be avoided before
this change is submitted?)
2024-11-06 18:27:40 +00:00
Richard Smith fcabeb6725 Don't create instructions for implicit constants. (#4497)
When an instruction is created as part of an implicit call to an
interface member, we generated a bunch of constants for naming the
interface, finding the corresponding specific, accessing its member
function, and so on. This led to significant bloat in SemIR.

Instead, we now track whether an instruction is created implicitly in
its location, and where relevant, we use the constant value of the
instruction directly instead of storing a new `Inst`.

This doesn't reduce the amount of work we need to do, but does make the
representation in SemIR smaller and more readable.
2024-11-06 15:44:56 +00:00
Jon Ross-Perkins 9aae9de43c Clean up some CopyOnWriteBlock details (#4493) 2024-11-06 02:23:51 +00:00
Richard Smith a68acb1975 Fix crash lowering an imported impl method. (#4489)
While we don't need a lookup table for an imported impl from a different
library, we do still need to import the name scope so we can compute the
parent scope for mangling purposes.
2024-11-05 20:38:26 +00:00
Richard Smith 2bcd4659f3 Don't copy maps and sets when computing their memory usage. (#4491)
Also use the `Impl` base class to type-erase the small size of
`SmallVector`. (I'd like to do the same for `Map` and `Set` by using
`MapView` and `SetView`, but that runs into ambiguities due to
`BumpPtrAllocator`'s unconstrained converting constructor.)
2024-11-05 20:37:22 +00:00
Dana Jansens 361efa90a8 Always call MemUsage::Collect to collect metrics from a field (#4480)
Previously Collect() was used for types that implemented
CollectMemUsage() but otherwise Add() was used. This required the caller
to think about the type of the field and know/decide which method to
use.

Now, the caller always uses Collect() unless they are adding specific
byte values, in which case Add is used. Typically then, Add will only be
used to implement the CollectMemUsage() function.

To do this we require all Collect() methods to be templates so that they
all be a single overload set. The Collect on BumpPtrAllocator is
converted to a template that checks
`std::same_as<llvm::BumpPtrAllocator, T>`.
2024-11-05 19:31:14 +00:00