Commit Graph
34 Commits
Author SHA1 Message Date
aa69a484eb Add support for running LLVM optimizer. (#6225)
Adds a flag `--optimize=<mode>` that specifies what to optimize for:

* `--optimize=none` turns off the optimizer as much as possible, but
still respects always_inline.
* `--optimize=debug` aims to be the equivalent of `-Og` / `-O1`, and
provides optimizations that don't affect the ability to debug the
program. This is the default.
* `--optimize=size` optimizes for the size of the produced program, and
aims to be the equivalent of `-Oz`.
* `--optimize=speed` optimizes for the execution time of the produced
program, and aims to be the equivalent of `-O3`.

Following the approach taken by Clang, the optimization level feeds into
both the configuration of the LLVM pass pipeline and the attributes
added to function definitions generated by the frontend.

Optimization is performed in a new phase, `optimize`, which runs between
`lower` and `codegen`.

---------

Co-authored-by: Dana Jansens <danakj@orodu.net>
Co-authored-by: Chandler Carruth <chandlerc@gmail.com>
2025-11-05 00:15:14 +00:00
Aiden Grossman 5714f4deb2 Use Overload of lookupTarget Accepting Triple (#6205)
The overload accepting a string/llvm::StringRef is deprecated and will
be removed when LLVM 22 branches.
2025-10-13 18:52:49 +00:00
Jon Ross-Perkins d599023c19 Change CodeGen to use a diagnostic consumer (#5847)
We've been trying to have errors/warnings all go through the diagnostics
consumers instead of straight to stderr.
2025-07-24 21:44:44 +00:00
Jon Ross-PerkinsandChandler Carruth 59619fa8eb Make driver fuzzing more robust for clang flags (#5845)
I'm not sure the target in use here will reliably crash over time, but
it does right now, and that seems reasonable...?

Example crash:

```
file_test: external/+llvm_project+llvm-project/clang/lib/Driver/ToolChains/Darwin.h:505: bool clang::driver::toolchains::Darwin::isTargetWatchOSBased() const: Assertion `TargetInitialized && "Target not initialized!"' failed.
```

Stack fragment:

```
...
#10 0x0000562ba07dec33 isTargetWatchOSBased /proc/self/cwd/external/+llvm_project+llvm-project/clang/lib/Driver/ToolChains/Darwin.h:505:5
#11 0x0000562ba07dec33 clang::driver::toolchains::DarwinClang::addClangWarningOptions(llvm::SmallVector<char const*, 16u>&) const /proc/self/cwd/external/+llvm_project+llvm-project/clang/lib/Driver/ToolChains/Darwin.cpp:1188:7
#12 0x0000562ba072afc7 clang::driver::tools::Clang::ConstructJob(clang::driver::Compilation&, clang::driver::JobAction const&, clang::driver::InputInfo const&, llvm::SmallVector<clang::driver::InputInfo, 4u> const&, llvm::opt::ArgList const&, char const*) const /proc/self/cwd/external/+llvm_project+llvm-project/clang/lib/Driver/ToolChains/Clang.cpp:0:6
#13 0x0000562ba06306d8 clang::driver::Driver::BuildJobsForActionNoCache(clang::driver::Compilation&, clang::driver::Action const*, clang::driver::ToolChain const*, llvm::StringRef, bool, bool, char const*, std::__1::map<std::__1::pair<clang::driver::Action const*, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char>>>, llvm::SmallVector<clang::driver::InputInfo, 4u>, std::__1::less<std::__1::pair<clang::driver::Action const*, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char>>>>, std::__1::allocator<std::__1::pair<std::__1::pair<clang::driver::Action const*, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char>>> const, llvm::SmallVector<clang::driver::InputInfo, 4u>>>>&, clang::driver::Action::OffloadKind) const /proc/self/cwd/external/+llvm_project+llvm-project/clang/lib/Driver/Driver.cpp:6083:10
...
#28 0x0000562b9e479d1f Carbon::BuildClangInvocation(Carbon::Diagnostics::Consumer&, llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem>, llvm::ArrayRef<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char>>>) /proc/self/cwd/toolchain/base/clang_invocation.cpp:103:21
...
```

---------

Co-authored-by: Chandler Carruth <chandlerc@gmail.com>
2025-07-24 20:00:41 +00:00
Jon Ross-Perkins 70c94cb5b4 Clean up --no-prelude-import uses (#5722)
For some of these, it's just replacing with min_prelude/none.carbon.
Some had min_preludes specified, and I'm generally switching those to
none.carbon as well. The one exception is the destroy.carbon test, which
I noticed because of #5678
2025-06-25 21:03:15 +00:00
Jon Ross-Perkins 806bee1063 Shift from ARGS to EXTRA-ARGS where possible (#5602)
Adds minimal defaults for codegen so that those tests don't need to
specify the full command line.

Moves driver/testdata/compile to check/testdata/basics/raw_sem_ir, which
seems like it better reflects the focus. Removes the textual IR test
because we have plenty of those now.

Moves a multiline token diagnostic test to parse because (a) diagnostics
doesn't have other tests and (b) this is really testing the way that
parse structures the location.

Drops `--include-diagnostic-kind` from some driver tests that aren't
testing a diagnostic, so the flag felt a bit like noise (even before
this change, there are a few tests that don't specify it because they're
not intended to test an emitted diagnostic, just high-level diagnostic
behaviors).

Adds some comments to reflect my understanding of why a test exists,
when I was pausing to think about it.

Modifies the stdin test to do more dumps; which happens to expose we
currently misbehave.
2025-06-03 22:09:57 +00:00
Chandler Carruth 55705aaef8 Update LLVM, picking up new -disable-free flag logic (#5333)
This requires fixing some uses of deprecated APIs.
2025-04-18 03:49:27 +00:00
Thomas Köppe bf32da8dad Add missing standard library header inclusions (#5316)
Discovered by clang-tidy.
2025-04-17 15:37:57 +00:00
Jon Ross-Perkins 8c3fa80691 Add cc rule wrappers for cc_env (#5277)
Rules executed by bazel don't necessarily have the right environment to
find the symbolizer, which was the intent of `cc_env` setting
`LLVM_SYMBOLIZER_PATH`. So far, this has kind of been a case-by-case
fix, but every so often I'm trying to debug a crash in a test that
doesn't provide it. Rather continuing down this route, instead add
drop-in wrappers for cc rules so that it's hard to forget.

Note `bazel/cc_rules` is intended to mirror `bazel/carbon_rules` and
`bazel/cc_toolchains`, rather than `@rules_cc`.

AFAICT there isn't a great way to add this as a default for the `bazel
run` environment. It's not typically going to be set on its own,
forwarding `$PATH` would be too broad, and the [action
`env_sets`](https://bazel.build/docs/cc-toolchain-config-reference#using-action-config)
I think are not quite what we need (I think those don't include output
execution, only compilation).
2025-04-11 19:58:54 +00:00
Jon Ross-PerkinsandRichard Smith 422df75a92 Switch tree-sitter from explorer to toolchain testdata (#5292)
Noticed as part of #5290; `srcs` is needed to make `$(locations)` work.

---------

Co-authored-by: Richard Smith <richard@metafoo.co.uk>
2025-04-10 23:45:19 +00:00
Boaz Brickner ccd2cb346a Change CodeGen::Make() to take module and errors as pointers and not references (#5229)
Per [the style
guide](https://github.com/carbon-language/carbon-lang/blob/trunk/docs/project/cpp_style_guide.md#syntax-and-formatting):
* If it is captured and must outlive the call expression itself, use a
pointer and document that it must not be null (unless it is also
optional).
* When storing an object's address as a non-owned member, prefer storing
a pointer.
2025-04-01 14:55:04 +00:00
josh11bandJosh L 820ace95e8 Update LLVM (#5082)
Co-authored-by: Josh L <josh11b@users.noreply.github.com>
2025-03-07 19:34:31 +00:00
Jon Ross-PerkinsandChandler Carruth 7befe2ce9f Switch custom error stream output to diagnostic (#4846)
This switches most error printing to use diagnostics instead of direct
stream writes, even when not a specific file diagnostic. I'm allowing
empty filenames for this use-case.

This allows a little more specific testing to validate coverage of
output using the diagnostic coverage test. I'm adding a few tests to
cover things that weren't previously tested.

Separately, this also forces a little more standardization in format...
considering how changes like #4568 show effort being spent to _mirror_
diagnostic style, my thought is now to just use diagnostic code where
possible.

Note this also allows incrementally better testing of the language
server; I'm changing the crash fix from #4847 in favor of diagnostic
testing.

---------

Co-authored-by: Chandler Carruth <chandlerc@gmail.com>
2025-01-30 01:58:07 +00:00
David BlaikieandJon Ross-Perkins e6c1f0630a Add a newline after diagnostic output when testing (#4818)
This removes some churn when adding new diagnostic cases to test files
(where previous to this change the newly added newline would cause the
previous diagnostic CHECKs to be updated including changes to the line
number because the CHECK for the blank line meant an extra line between
CHECK and source line).

A few alternatives discussed here:
https://discord.com/channels/655572317891461132/655578254970716160/1329573358475673723

---------

Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2025-01-16 23:23:57 +00:00
josh11bandJosh L 4febf7c459 Add capitilization and punctuation to TODO comments (#4486)
Co-authored-by: Josh L <josh11b@users.noreply.github.com>
2024-11-05 16:31:00 +00:00
Jon Ross-PerkinsandRichard Smith e7aebbe581 Update basic diagnostic capitalization/punctuation (#4328)
This is a primarily automated change:

- Search & replace for capitalization
-
`(CARBON_DIAGNOSTIC\((?:\n\s+)?\w+,(?:\n\s+)?\s\w+,(?:\n\s+)?\s")([A-Z])`
    - `$1\L$2`
- Search & replace for period
-
`(CARBON_DIAGNOSTIC\((?:\n\s+)?\w+,(?:\n\s+)?\s\w+,(?:\n\s+)?\s"(?:[^)]|\n)+)\.("[,)])`
    - `$1$2`
- Limited search & replace for `ERROR: ` -> `error: ` in streamed things
- Leaving a TODO for command_line because there's more cleanup that can
be done there
- Modify diagnostic_consumer.cpp
    - ERROR -> error
    - WARNING -> warning

---------

Co-authored-by: Richard Smith <richard@metafoo.co.uk>
2024-09-19 21:32:53 +00:00
Geoff Romer 7f6d684b29 Add usage tips to NOAUTOUPDATE tests (#4324)
These tips are especially valuable in these cases, because you can't use
`autoupdate_testdata.py` to identify the output difference, so dumping
the output is pretty much the only option.
2024-09-19 21:00:21 +00:00
a548eff0bb Rudimentary name mangling support (#4267)
This seems to be enough to avoid naming collisions for functions in any
of the current test cases (verified by asserting that the name of the
`llvm::Function` matches the name passed to create it - not triggering
LLVM's numbering that happens when names collide)

It currently implements mangling for namespace scopes, class scopes, and
impls.
Nothing generic is mangled yet - haven't looked at how that works,
though evidently it's not covered by existing testing, I guess.

Follow-up change will document the current mangling algorithm in
`toolchain/docs/lower.md`

---------

Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
Co-authored-by: Carbon Infra Bot <carbon-external-infra@google.com>
2024-09-06 23:10:21 +00:00
Jon Ross-Perkins 8bb80d8271 Add a basic Core.Print function for ints. (#4078)
We'd been discussing that explorer remains necessary for print, and I
was wondering if this kind of approach would be okay (we _probably_ want
this to work, based on #2110, albeit with more overloads -- but I don't
think there's a good way to support overloads at the moment).

```
╚╡../bazel-bin/examples/sieve
2
3
5
7
11
13
17
19
23
29
31
37
41
43
...
```
2024-06-25 21:32:07 +00:00
Jon Ross-Perkins 83413479d7 Move some of the test information to TIP lines (#4007)
This has is a nice-to-have for me. Frequently I want to run a specific
test, and end up digging through output to be able to copy-paste the run
line. This uses TIP lines to inject the command into the file when using
AUTOUPDATE.

Note, one of the reasons I want this is because "bazel test
//toolchain/testing:file_test --test_output=all" has been regularly
exceeding bazel's output limit for me (workaround is either opening the
output file or specifying an obscure output limit flag), making it a
little harder for me to get the commands. However, frequently I'm adding
a file and want to iterate on it, so that's really the use case I have
in mind here.
2024-06-04 17:57:23 +00:00
Jon Ross-Perkins 895e90e791 Start including the prelude for testing. (#3861)
- Adds an empty prelude.carbon file
- Imports that file in any non-Core package file
  - Adds --disable-prelude-import to avoid that
- Adds --exclude-dump-file-prefix to be able to hide files from dumping
- Used to hide core files (we can't do this by package name due to lex
dumps, for example)
- Restructures some tests to not rely on `i32`, particularly `alias`
tests (which rely on a name ref) and tests with no prelude.

I'm adding the framework for switching i32 to calling Int32 in the
prelude, but I'm running into a separate error actually switching over.
So that *mostly* works, but isn't quite ready for prime time. However,
maybe the current state of this PR is still useful to review since it
does a lot of the infrastructure work and adds the %Core everywhere?
2024-04-07 17:11:42 +00:00
Jon Ross-Perkins 1974e44fd9 Rename factory functions from 'Create' to 'Make' (#3706)
Similar to #3705, we actually have a mix of `Make` and `Create` in
factory functions too, so this PR is normalizing on `Make`. It's
intended to be consistent with the naming choice for Carbon factory
functions.

Note, MakeSyntheticBlock is the only one I feel a little weird about
because llvm's own APIs use Create, and this is essentially wrapping
LLVM calls. But the flipside is it also feels like a vague line to draw,
when we also differ from LLVM coding style in other ways.
2024-02-14 18:26:56 +00:00
Richard SmithandJon Ross-Perkins bf8697113a Move llvm::Initialize* calls to main. (#3449)
Per their documentation, the `llvm::Initialize*` functions are only
supposed to be called by the main program, not by a library like
toolchain/codegen. Fixes a hang due to a data race in multithreaded
autoupdate.

Add a utility class `Carbon::InitLLVM` to do the common LLVM
initialization shared by all Carbon tools, optionally including
initializing the LLVM targets. Because the LLVM targets add a lot of
binary size, only initialize them for binaries that opt in by depending
on a new target `//common:all_llvm_targets`.

Also fix `//explorer:file_test` and `//explorer:file_test.trace` to
share a binary rather than linking an identical binary twice.

---------

Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
2023-12-07 01:45:47 +00:00
Jon Ross-Perkins d6f689ba07 Another LLVM fix for CodeGenFileType (#3242)
Due to:

https://github.com/llvm/llvm-project/commit/0a1aa6cda2758b0926a95f87d39ffefb1cb90200
2023-09-16 01:18:54 +00:00
Jon Ross-Perkins 8aa3d960f5 Merge toolchain file_test children in order to improve linking. (#3206)
Specifically this should improve linking by producing one large binary
instead of one-per-directory. The inclusion of the driver hits the size
issue. Separating out things which have more llvm deps has been
discussed, but I'm not doing that here because I think the semantics
layer will need to depend on clang for interop, and we'd lose a lot of
the benefits that way. Also, having just one place to look seems
simpler.

Includes supporting changes to file_test infrastructure, the most
significant of which is probably passing tests via file instead of a
really large args thing, using a custom rule to do that. That's because
dealing with the layered filegroups that allow the toolchain setup is
more complicated, and this approach scales well.

Combined test time is ~9s, so not sharding right now.

I wasn't sure if people would prefer having the autoupdate script under
testing, so I left it alone for now.
2023-09-11 17:54:41 +00:00
Jon Ross-Perkins b9df8ca765 Manual cleanup of toolchain clang-tidy/clangd warnings. (#3157)
A lot of this is more boring "remove unused header", plus some other
minor cleanups. I think the most significant changes were:

- yaml_test_helpers.cpp is doing a switch on an unsigned int, comparing
to enum values.
-
[bugprone-switch-missing-default-case](https://clang.llvm.org/extra/clang-tidy/checks/bugprone/switch-missing-default-case.html)
is unhappy with EnumBase, but correctly identified
yaml_test_helpers.cpp, so I'm opting to address it rather than disabling
it even though it needs NOLINT in several locations as a result, in
addition to what I think are some low-value `default` cases. I'd be fine
going the other way with this too and disabling it globally (I could see
it being noisier in the explorer).
- MarkInitializerFor swaps the argument names between the .h and .cpp. I
think the .cpp had the order as intended.
- There's a new-ish
[performance-enum-size](https://clang.llvm.org/extra/clang-tidy/checks/performance/enum-size.html)
which I'm basically treating as "add int8_t to enums".

My main motivation here is to just clean up as many of these as I can so
that I stop seeing them in vscode.
2023-08-25 22:45:57 +00:00
Jon Ross-Perkins 605763d62d Add lint fixes to the buildifier setup. (#3109)
The main motivation for this is to get python loads in using the
`native-py` lint fix. However, enabling that made me wonder, maybe we
should fix in general?

`native-cc` is delayed, but not wholly cancelled (and `native-py`
picking up might indicate `native-cc` won't be too far behind). There's
also some automated fixes for `.append` and dict sorting -- this felt
okay to me, maybe not something to eagerly add but probably not worth
stopping buildifier from fixing (I've noticed the warnings in the past
and had been ignoring them).

Running everything does mean that load orders are sorted automatically
now, which I think is a positive. Most generally, I think these fixes
aren't _harmful_, and having them done automatically seems beneficial:
my biggest concern about `native-py` and `native-cc` was actually that
regressions wouldn't be caught, but this addresses that issue
automatically.
2023-08-22 21:01:42 +00:00
a2b4cabeaa Switch the toolchain to the new CLI library. (#2979)
This also tries to restructure the command line interface to the
toolchain a bit to make it start operating more like a compiler that
could be integrated into a build system rather than primarily as
a testing tool.

1) This switches form a `dump` subcommand to a `compile` subcommand
   which has "dump" actions that can be enabled within it.

2) A distinct set of compile _phases_ that match the toolchain
   structure:
   - `lex` to run the lexer
   - `parse` to run the parser
   - `check` to fully check that the code is valid
   - `lower` to lower to LLVM's IR
   - `codegen` to generate executable code

3) The codegen phase has two output formats: textual assembly and
   a binary object. These outputs can be configured, with a default for
   an object when writing to a file and more firm default for textual
   assembly when writing to stdout.

4) Select and expose the use of the LLVM host detection to compute
   a default code generation target in the driver so that the command
   line interface can reflect this. For example, the `help` output will
   include the default target.

5) The `//toolchain/codegen` library APIs have been restructured a bit
   to make the code flow a bit more naturally when implementing the new
   command line structure. No real changes to the logic though.

There are also some minor tweaks to the command line interface based on
trying to use the shortest names for things that still seem likely to be
learnable for users:

- Switched `target-triple` to just `target`: the "triple" component to
  this name is historical and can be confusing. For example, almost all
  "triple" strings have more than three components today.

- Switched to just `--output` as now the fact that it is a file can be
  configured in the documentation -- it will render as `--output=FILE`.

This also adds support for two custom output filename modes. First, when
no output is specified, we now compute one in the conventional way for
compilers by removing the file extension of the input file and replacing
it with `.o` for an object file output or `.s` for an assembly file
output. This matches the behavior of Clang and GCC for example.

Second, output to stdout is enabled with the special output file name of
`-` since it is no longer the default. This also follows the convention
of most compilers and many other command line tools to use `-` as a file
name to signify using standard in/out pipes.

There are still some rough edges here that I suspect could be improved,
but this seems like a good start of switching over to a complete
argument parser.

---------

Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
Co-authored-by: Lucile Rose Nihlen <luci.the.rose@gmail.com>
Co-authored-by: Richard Smith <richard@metafoo.co.uk>
2023-08-18 01:06:09 +00:00
Richard Smith 212188a922 Prefer to put STDOUT CHECK at the end of the file. (#3073)
Allow interleaving of STDOUT and STDERR check lines. Put STDOUT lines
after the line they're attached to, and STDERR lines before. If no
STDOUT check line is attached to any line, then put them all at the end
of the file instead.

This is intended to better handle the case where stdout contains
unreplaced mentions of line numbers, and also reflects that stdout is
typically a consequence of the test rather than commentary on it, so
placing it after the test seems likely to read better.
2023-08-08 19:51:52 +00:00
Jon Ross-Perkins b5167b2d69 Implement autoupdate for file_test. (#3043)
I've migrated the toolchain autoupdate scripts here, I just need a
little more time to do the explorer side (which I need to check
performance, that may require multithreading as we do in the current
script). However, this felt substantial enough to share and it means I
can handle autoupdate in more of the toolchain, including preparatory
work for autoupdate on multi-file tests.

Once explorer is done I'll remove the old script.
2023-08-02 21:32:21 +00:00
Jon Ross-PerkinsandChandler Carruth eb05f618ce Refactor FileTest construction so that the test class is directly available. (#3035)
This is a simplification of the construction, although somewhat limiting
(it means that the caller can't register the same file multiple times,
though I stopped doing that anyways since it was causing confusion).
What this more importantly _allows_ is logic on the FileTestBase child
itself that's not test-specific -- in particular, autoupdate
functionality which wouldn't use RUN_ALL_TESTS.

---------

Co-authored-by: Chandler Carruth <chandlerc@gmail.com>
2023-08-01 16:00:29 +00:00
Jon Ross-Perkins f088a71cec Add file_test support for specifying arguments and only checking a subset of output. (#3018)
This is sufficient to convert remaining toolchain tests to file_test. %s
and %t are currently used. While #2978 might use %T with lit, I think
that's resolving a lit-specific issue that's not necessary when
TEST_TMPDIR is readily available for any necessary operations (i.e.,
setting the working directory). With ARGS, I think it's feasible to
switch to file_test without %T.

Also adds documentation to file_test_base.h, which was starting to feel
like a significant gap.

This is not yet handled by autoupdate, but I'm eyeing that next.
2023-07-25 22:47:56 +00:00
037196f69f Creates object file from the module. (#2955)
This pr creates the object file for the carbon code that returns either
0 or 1. The command to convert the object code to binary is `clang
<object_file_name> -o <binary_name>`

---------

Co-authored-by: Farzana Ahmed Siddique <fasiddique@google.com>
Co-authored-by: Richard Smith <richard@metafoo.co.uk>
2023-07-07 22:16:41 +00:00
Farzana Ahmed SiddiqueandFarzana Ahmed Siddique aad4ed2083 Codegen: Given a carbon file prints the assembly to the stdout (#2944)
Co-authored-by: Farzana Ahmed Siddique <fasiddique@google.com>
2023-06-23 15:23:39 -07:00