Auto merge of #125141 - SergioGasquez:feat/no_std-xtensa, r=davidtwco

Add no_std Xtensa targets support

Adds no_std Xtensa targets. This enables using Rust on ESP32, ESP32-S2 and ESP32-S3 chips.

Tier 3 policy:

> A tier 3 target must have a designated developer or developers (the "target maintainers") on record to be CCed when issues arise regarding the target. (The mechanism to track and CC such developers may evolve over time.)

`@MabezDev` and I (`@SergioGasquez)` will maintain the targets.

> Targets must use naming consistent with any existing targets; for instance, a target for the same CPU or OS as an existing Rust target should use the same name for that CPU or OS. Targets should normally use the same names and naming conventions as used elsewhere in the broader ecosystem beyond Rust (such as in other toolchains), unless they have a very good reason to diverge. Changing the name of a target can be highly disruptive, especially once the target reaches a higher tier, so getting the name right is important even for a tier 3 target.

The target triple is consistent with other targets.

> Target names should not introduce undue confusion or ambiguity unless absolutely necessary to maintain ecosystem compatibility. For example, if the name of the target makes people extremely likely to form incorrect beliefs about what it targets, the name should be changed or augmented to disambiguate it.
> If possible, use only letters, numbers, dashes and underscores for the name. Periods (.) are known to cause issues in Cargo.

We follow the same naming convention as other targets.

> Tier 3 targets may have unusual requirements to build or use, but must not create legal issues or impose onerous legal terms for the Rust project or for Rust developers or users.

The target does not introduce any legal issues.

> The target must not introduce license incompatibilities.

There are no license incompatibilities

> Anything added to the Rust repository must be under the standard Rust license (MIT OR Apache-2.0).

Everything added is under that licenses

> The target must not cause the Rust tools or libraries built for any other host (even when supporting cross-compilation to the target) to depend on any new dependency less permissive than the Rust licensing policy. This applies whether the dependency is a Rust crate that would require adding new license exceptions (as specified by the tidy tool in the rust-lang/rust repository), or whether the dependency is a native library or binary. In other words, the introduction of the target must not cause a user installing or running a version of Rust or the Rust tools to be subject to any new license requirements.

Requirements are not changed for any other target.

> Compiling, linking, and emitting functional binaries, libraries, or other code for the target (whether hosted on the target itself or cross-compiling from another target) must not depend on proprietary (non-FOSS) libraries. Host tools built for the target itself may depend on the ordinary runtime libraries supplied by the platform and commonly used by other applications built for the target, but those libraries must not be required for code generation for the target; cross-compilation to the target must not require such libraries at all. For instance, rustc built for the target may depend on a common proprietary C runtime library or console output library, but must not depend on a proprietary code generation library or code optimization library. Rust's license permits such combinations, but the Rust project has no interest in maintaining such combinations within the scope of Rust itself, even at tier 3.

The linker used by the targets is the GCC linker from the GCC toolchain cross-compiled for Xtensa. GNU GPL.

> "onerous" here is an intentionally subjective term. At a minimum, "onerous" legal/licensing terms include but are not limited to: non-disclosure requirements, non-compete requirements, contributor license agreements (CLAs) or equivalent, "non-commercial"/"research-only"/etc terms, requirements conditional on the employer or employment of any particular Rust developers, revocable terms, any requirements that create liability for the Rust project or its developers or users, or any requirements that adversely affect the livelihood or prospects of the Rust project or its developers or users.

No such terms exist for this target

> Neither this policy nor any decisions made regarding targets shall create any binding agreement or estoppel by any party. If any member of an approving Rust team serves as one of the maintainers of a target, or has any legal or employment requirement (explicit or implicit) that might affect their decisions regarding a target, they must recuse themselves from any approval decisions regarding the target's tier status, though they may otherwise participate in discussions.

> This requirement does not prevent part or all of this policy from being cited in an explicit contract or work agreement (e.g. to implement or maintain support for a target). This requirement exists to ensure that a developer or team responsible for reviewing and approving a target does not face any legal threats or obligations that would prevent them from freely exercising their judgment in such approval, even if such judgment involves subjective matters or goes beyond the letter of these requirements.

Understood

> Tier 3 targets should attempt to implement as much of the standard libraries as possible and appropriate (core for most targets, alloc for targets that can support dynamic memory allocation, std for targets with an operating system or equivalent layer of system-provided functionality), but may leave some code unimplemented (either unavailable or stubbed out as appropriate), whether because the target makes it impossible to implement or challenging to implement. The authors of pull requests are not obligated to avoid calling any portions of the standard library on the basis of a tier 3 target not implementing those portions.

The target already implements core.

> The target must provide documentation for the Rust community explaining how to build for the target, using cross-compilation if possible. If the target supports running binaries, or running tests (even if they do not pass), the documentation must explain how to run such binaries or tests for the target, using emulation if possible or dedicated hardware if necessary.

Here is how to build for the target https://docs.esp-rs.org/book/installation/riscv-and-xtensa.html and it also covers how to run binaries on the target.

> Tier 3 targets must not impose burden on the authors of pull requests, or other developers in the community, to maintain the target. In particular, do not post comments (automated or manual) on a PR that derail or suggest a block on the PR based on a tier 3 target. Do not send automated messages or notifications (via any medium, including via `@)` to a PR author or others involved with a PR regarding a tier 3 target, unless they have opted into such messages.

> Backlinks such as those generated by the issue/PR tracker when linking to an issue or PR are not considered a violation of this policy, within reason. However, such messages (even on a separate repository) must not generate notifications to anyone involved with a PR who has not requested such notifications.

Understood

> Patches adding or updating tier 3 targets must not break any existing tier 2 or tier 1 target, and must not knowingly break another tier 3 target without approval of either the compiler team or the maintainers of the other tier 3 target.

> In particular, this may come up when working on closely related targets, such as variations of the same architecture with different features. Avoid introducing unconditional uses of features that another variation of the target may not have; use conditional compilation or runtime detection, as appropriate, to let each target run code supported by that target.

No other targets should be affected

> Tier 3 targets must be able to produce assembly using at least one of rustc's supported backends from any host target.

It can produce assembly, but it requires a custom LLVM with Xtensa support (https://github.com/espressif/llvm-project/). The patches are trying to be upstreamed (https://github.com/espressif/llvm-project/issues/4)
This commit is contained in:
bors 2024-06-12 13:43:31 +00:00
commit 0285dab54f
18 changed files with 280 additions and 4 deletions

View File

@ -23,6 +23,7 @@ const OPTIONAL_COMPONENTS: &[&str] = &[
"nvptx",
"hexagon",
"riscv",
"xtensa",
"bpf",
];

View File

@ -155,6 +155,12 @@ extern "C" void LLVMRustTimeTraceProfilerFinish(const char* FileName) {
#define SUBTARGET_SPARC
#endif
#ifdef LLVM_COMPONENT_XTENSA
#define SUBTARGET_XTENSA SUBTARGET(XTENSA)
#else
#define SUBTARGET_XTENSA
#endif
#ifdef LLVM_COMPONENT_HEXAGON
#define SUBTARGET_HEXAGON SUBTARGET(Hexagon)
#else
@ -180,6 +186,7 @@ extern "C" void LLVMRustTimeTraceProfilerFinish(const char* FileName) {
SUBTARGET_MSP430 \
SUBTARGET_SPARC \
SUBTARGET_HEXAGON \
SUBTARGET_XTENSA \
SUBTARGET_RISCV \
SUBTARGET_LOONGARCH \

View File

@ -190,6 +190,13 @@ pub fn initialize_available_targets() {
LLVMInitializeHexagonAsmPrinter,
LLVMInitializeHexagonAsmParser
);
init_target!(
llvm_component = "xtensa",
LLVMInitializeXtensaTargetInfo,
LLVMInitializeXtensaTarget,
LLVMInitializeXtensaTargetMC,
LLVMInitializeXtensaAsmParser
);
init_target!(
llvm_component = "webassembly",
LLVMInitializeWebAssemblyTargetInfo,

View File

@ -29,6 +29,7 @@ mod wasm;
mod x86;
mod x86_64;
mod x86_win64;
mod xtensa;
#[derive(Clone, PartialEq, Eq, Hash, Debug, HashStable_Generic)]
pub enum PassMode {
@ -903,6 +904,7 @@ impl<'a, Ty> FnAbi<'a, Ty> {
}
}
"hexagon" => hexagon::compute_abi_info(self),
"xtensa" => xtensa::compute_abi_info(cx, self),
"riscv32" | "riscv64" => riscv::compute_abi_info(cx, self),
"wasm32" | "wasm64" => {
if cx.target_spec().adjust_abi(cx, abi, self.c_variadic) == spec::abi::Abi::Wasm {

View File

@ -0,0 +1,123 @@
//! The Xtensa ABI implementation
//!
//! This ABI implementation is based on the following sources:
//!
//! Section 8.1.4 & 8.1.5 of the Xtensa ISA reference manual, as well as snippets from
//! Section 2.3 from the Xtensa programmers guide.
use crate::abi::call::{ArgAbi, FnAbi, Reg, Uniform};
use crate::abi::{Abi, HasDataLayout, Size, TyAbiInterface};
use crate::spec::HasTargetSpec;
const NUM_ARG_GPRS: u64 = 6;
const NUM_RET_GPRS: u64 = 4;
const MAX_ARG_IN_REGS_SIZE: u64 = NUM_ARG_GPRS * 32;
const MAX_RET_IN_REGS_SIZE: u64 = NUM_RET_GPRS * 32;
fn classify_ret_ty<'a, Ty, C>(arg: &mut ArgAbi<'_, Ty>)
where
Ty: TyAbiInterface<'a, C> + Copy,
{
if arg.is_ignore() {
return;
}
// The rules for return and argument types are the same,
// so defer to `classify_arg_ty`.
let mut arg_gprs_left = NUM_RET_GPRS;
classify_arg_ty(arg, &mut arg_gprs_left, MAX_RET_IN_REGS_SIZE);
// Ret args cannot be passed via stack, we lower to indirect and let the backend handle the invisble reference
match arg.mode {
super::PassMode::Indirect { attrs: _, meta_attrs: _, ref mut on_stack } => {
*on_stack = false;
}
_ => {}
}
}
fn classify_arg_ty<'a, Ty, C>(arg: &mut ArgAbi<'_, Ty>, arg_gprs_left: &mut u64, max_size: u64)
where
Ty: TyAbiInterface<'a, C> + Copy,
{
assert!(*arg_gprs_left <= NUM_ARG_GPRS, "Arg GPR tracking underflow");
// Ignore empty structs/unions.
if arg.layout.is_zst() {
return;
}
let size = arg.layout.size.bits();
let needed_align = arg.layout.align.abi.bits();
let mut must_use_stack = false;
// Determine the number of GPRs needed to pass the current argument
// according to the ABI. 2*XLen-aligned varargs are passed in "aligned"
// register pairs, so may consume 3 registers.
let mut needed_arg_gprs = (size + 32 - 1) / 32;
if needed_align == 64 {
needed_arg_gprs += *arg_gprs_left % 2;
}
if needed_arg_gprs > *arg_gprs_left
|| needed_align > 128
|| (*arg_gprs_left < (max_size / 32) && needed_align == 128)
{
must_use_stack = true;
needed_arg_gprs = *arg_gprs_left;
}
*arg_gprs_left -= needed_arg_gprs;
if must_use_stack {
arg.make_indirect_byval(None);
} else {
if is_xtensa_aggregate(arg) {
// Aggregates which are <= max_size will be passed in
// registers if possible, so coerce to integers.
// Use a single `xlen` int if possible, 2 * `xlen` if 2 * `xlen` alignment
// is required, and a 2-element `xlen` array if only `xlen` alignment is
// required.
if size <= 32 {
arg.cast_to(Reg::i32());
} else {
let reg = if needed_align == 2 * 32 { Reg::i64() } else { Reg::i32() };
let total = Size::from_bits(((size + 32 - 1) / 32) * 32);
arg.cast_to(Uniform::new(reg, total));
}
} else {
// All integral types are promoted to `xlen`
// width.
//
// We let the LLVM backend handle integral types >= xlen.
if size < 32 {
arg.extend_integer_width_to(32);
}
}
}
}
pub fn compute_abi_info<'a, Ty, C>(_cx: &C, fn_abi: &mut FnAbi<'a, Ty>)
where
Ty: TyAbiInterface<'a, C> + Copy,
C: HasDataLayout + HasTargetSpec,
{
if !fn_abi.ret.is_ignore() {
classify_ret_ty(&mut fn_abi.ret);
}
let mut arg_gprs_left = NUM_ARG_GPRS;
for arg in fn_abi.args.iter_mut() {
if arg.is_ignore() {
continue;
}
classify_arg_ty(arg, &mut arg_gprs_left, MAX_ARG_IN_REGS_SIZE);
}
}
fn is_xtensa_aggregate<'a, Ty>(arg: &ArgAbi<'a, Ty>) -> bool {
match arg.layout.abi {
Abi::Vector { .. } => true,
_ => arg.layout.is_aggregate(),
}
}

View File

@ -35,3 +35,4 @@ pub(crate) mod windows_gnullvm;
pub(crate) mod windows_msvc;
pub(crate) mod windows_uwp_gnu;
pub(crate) mod windows_uwp_msvc;
pub(crate) mod xtensa;

View File

@ -0,0 +1,17 @@
use crate::abi::Endian;
use crate::spec::{Cc, LinkerFlavor, Lld, PanicStrategy, RelocModel, TargetOptions};
pub fn opts() -> TargetOptions {
TargetOptions {
os: "none".into(),
endian: Endian::Little,
c_int_width: "32".into(),
linker_flavor: LinkerFlavor::Gnu(Cc::Yes, Lld::No),
executables: true,
panic_strategy: PanicStrategy::Abort,
relocation_model: RelocModel::Static,
emit_debug_gdb_scripts: false,
atomic_cas: false,
..Default::default()
}
}

View File

@ -1766,6 +1766,10 @@ supported_targets! {
("nvptx64-nvidia-cuda", nvptx64_nvidia_cuda),
("xtensa-esp32-none-elf", xtensa_esp32_none_elf),
("xtensa-esp32s2-none-elf", xtensa_esp32s2_none_elf),
("xtensa-esp32s3-none-elf", xtensa_esp32s3_none_elf),
("i686-wrs-vxworks", i686_wrs_vxworks),
("x86_64-wrs-vxworks", x86_64_wrs_vxworks),
("armv7-wrs-vxworks-eabihf", armv7_wrs_vxworks_eabihf),

View File

@ -0,0 +1,24 @@
use crate::spec::{base::xtensa, Target, TargetOptions};
pub fn target() -> Target {
Target {
llvm_target: "xtensa-none-elf".into(),
pointer_width: 32,
data_layout: "e-m:e-p:32:32-v1:8:8-i64:64-i128:128-n32".into(),
arch: "xtensa".into(),
metadata: crate::spec::TargetMetadata {
description: Some("Xtensa ESP32".into()),
tier: Some(3),
host_tools: Some(false),
std: Some(false),
},
options: TargetOptions {
cpu: "esp32".into(),
linker: Some("xtensa-esp32-elf-gcc".into()),
max_atomic_width: Some(32),
atomic_cas: true,
..xtensa::opts()
},
}
}

View File

@ -0,0 +1,23 @@
use crate::spec::{base::xtensa, Target, TargetOptions};
pub fn target() -> Target {
Target {
llvm_target: "xtensa-none-elf".into(),
pointer_width: 32,
data_layout: "e-m:e-p:32:32-v1:8:8-i64:64-i128:128-n32".into(),
arch: "xtensa".into(),
metadata: crate::spec::TargetMetadata {
description: Some("Xtensa ESP32-S2".into()),
tier: Some(3),
host_tools: Some(false),
std: Some(false),
},
options: TargetOptions {
cpu: "esp32-s2".into(),
linker: Some("xtensa-esp32s2-elf-gcc".into()),
max_atomic_width: Some(32),
..xtensa::opts()
},
}
}

View File

@ -0,0 +1,24 @@
use crate::spec::{base::xtensa, Target, TargetOptions};
pub fn target() -> Target {
Target {
llvm_target: "xtensa-none-elf".into(),
pointer_width: 32,
data_layout: "e-m:e-p:32:32-v1:8:8-i64:64-i128:128-n32".into(),
arch: "xtensa".into(),
metadata: crate::spec::TargetMetadata {
description: Some("Xtensa ESP32-S3".into()),
tier: Some(3),
host_tools: Some(false),
std: Some(false),
},
options: TargetOptions {
cpu: "esp32-s3".into(),
linker: Some("xtensa-esp32s3-elf-gcc".into()),
max_atomic_width: Some(32),
atomic_cas: true,
..xtensa::opts()
},
}
}

View File

@ -1,4 +1,4 @@
Change this file to make users of the `download-ci-llvm` configuration download
a new version of LLVM from CI, even if the LLVM submodule hasnt changed.
Last change is for: https://github.com/rust-lang/rust/pull/120761
Last change is for: https://github.com/rust-lang/rust/pull/125141

View File

@ -330,7 +330,7 @@ impl Step for Llvm {
let llvm_exp_targets = match builder.config.llvm_experimental_targets {
Some(ref s) => s,
None => "AVR;M68k;CSKY",
None => "AVR;M68k;CSKY;Xtensa",
};
let assertions = if builder.config.llvm_assertions { "ON" } else { "OFF" };

View File

@ -383,5 +383,8 @@ target | std | host | notes
`x86_64-wrs-vxworks` | ? | |
[`x86_64h-apple-darwin`](platform-support/x86_64h-apple-darwin.md) | ✓ | ✓ | macOS with late-gen Intel (at least Haswell)
[`x86_64-unknown-linux-none`](platform-support/x86_64-unknown-linux-none.md) | * | | 64-bit Linux with no libc
`xtensa-esp32-none-elf` | | | Xtensa ESP32
`xtensa-esp32s2-none-elf` | | | Xtensa ESP32-S2
`xtensa-esp32s3-none-elf` | | | Xtensa ESP32-S3
[runs on NVIDIA GPUs]: https://github.com/japaric-archived/nvptx#targets

View File

@ -0,0 +1,25 @@
# `xtensa-*`
**Tier: 3**
Targets for Xtensa CPUs.
## Target maintainers
- Scott Mabin [@MabezDev](https://github.com/MabezDev)
- Sergio Gasquez [@SergioGasquez](https://github.com/SergioGasquez)
## Requirements
The target names follow this format: `xtensa-$CPU`, where `$CPU` specifies the target chip. The following targets are currently defined:
| Target name | Target CPU(s) |
| ------------------------- | --------------------------------------------------------------- |
| `xtensa-esp32-none-elf` | [ESP32](https://www.espressif.com/en/products/socs/esp32) |
| `xtensa-esp32s2-none-elf` | [ESP32-S2](https://www.espressif.com/en/products/socs/esp32-s2) |
| `xtensa-esp32s3-none-elf` | [ESP32-S3](https://www.espressif.com/en/products/socs/esp32-s3) |
## Building the target
The targets can be built by installing the [Xtensa enabled Rust channel](https://github.com/esp-rs/rust/). See instructions in the [RISC-V and Xtensa Targets section of the The Rust on ESP Book](https://docs.esp-rs.org/book/installation/riscv-and-xtensa.html).

View File

@ -12,6 +12,10 @@ const EXCEPTIONS: &[&str] = &[
// FIXME: disabled since it fails on CI saying the csky component is missing
"csky_unknown_linux_gnuabiv2",
"csky_unknown_linux_gnuabiv2hf",
// FIXME: disabled since it requires a custom LLVM until the upstream LLVM adds support for the target (https://github.com/espressif/llvm-project/issues/4)
"xtensa_esp32_none_elf",
"xtensa_esp32s2_none_elf",
"xtensa_esp32s3_none_elf",
];
pub fn check(root_path: &Path, bad: &mut bool) {

View File

@ -573,7 +573,18 @@
//@ revisions: x86_64_wrs_vxworks
//@ [x86_64_wrs_vxworks] compile-flags: --target x86_64-wrs-vxworks
//@ [x86_64_wrs_vxworks] needs-llvm-components: x86
// FIXME: disabled since it requires a custom LLVM until the upstream LLVM adds support for the target (https://github.com/espressif/llvm-project/issues/4)
/*
revisions: xtensa_esp32_none_elf
[xtensa_esp32_none_elf] compile-flags: --target xtensa-esp32-none-elf
[xtensa_esp32_none_elf] needs-llvm-components: xtensa
revisions: xtensa_esp32s2_none_elf
[xtensa_esp32s2_none_elf] compile-flags: --target xtensa-esp32s2-none-elf
[xtensa_esp32s2_none_elf] needs-llvm-components: xtensa
revisions: xtensa_esp32s3_none_elf
[xtensa_esp32s3_none_elf] compile-flags: --target xtensa-esp32s3-none-elf
[xtensa_esp32s3_none_elf] needs-llvm-components: xtensa
*/
// Sanity-check that each target can produce assembly code.
#![feature(no_core, lang_items)]

View File

@ -129,7 +129,7 @@ warning: unexpected `cfg` condition value: `_UNEXPECTED_VALUE`
LL | target_arch = "_UNEXPECTED_VALUE",
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
= note: expected values for `target_arch` are: `aarch64`, `arm`, `arm64ec`, `avr`, `bpf`, `csky`, `hexagon`, `loongarch64`, `m68k`, `mips`, `mips32r6`, `mips64`, `mips64r6`, `msp430`, `nvptx64`, `powerpc`, `powerpc64`, `riscv32`, `riscv64`, `s390x`, `sparc`, `sparc64`, `wasm32`, `wasm64`, `x86`, and `x86_64`
= note: expected values for `target_arch` are: `aarch64`, `arm`, `arm64ec`, `avr`, `bpf`, `csky`, `hexagon`, `loongarch64`, `m68k`, `mips`, `mips32r6`, `mips64`, `mips64r6`, `msp430`, `nvptx64`, `powerpc`, `powerpc64`, `riscv32`, `riscv64`, `s390x`, `sparc`, `sparc64`, `wasm32`, `wasm64`, `x86`, `x86_64`, and `xtensa`
= note: see <https://doc.rust-lang.org/nightly/rustc/check-cfg.html> for more information about checking conditional configuration
warning: unexpected `cfg` condition value: `_UNEXPECTED_VALUE`