rucc_target/lib.rs
1//! Target descriptions: triples, and the facts about a target that the rest of the
2//! compiler reads rather than hard-codes.
3//!
4//! Design: `spec/12-abi-and-runtime.md`. Layer rank 2, see `spec/18-package-layout.md`.
5//!
6//! The rule from `spec/18-package-layout.md` section 18.2 is that there is no
7//! target-specific code outside this crate, `rucc-tuple`, `rucc-abi`, `rucc-sysroot` and the
8//! per-target rule sets. Those four are one group rather than four exceptions: the tuple names
9//! a machine, `rucc-abi` says what its types look like and how its calls are made,
10//! `rucc-sysroot` says where its headers and libraries are, and this crate is what the rest of
11//! the compiler reads all of it through. Everything a pass
12//! needs to know about a target is a field it can read here. That rule is what makes the
13//! claim in `spec/10-backend.md` testable, namely that a new target is a rule set and a few
14//! data files, and `M10` brings up a fourth target specifically to put a number on it.
15//!
16//! [`TargetInfo::call`] is the other half of that rule and the one with teeth. How a structure
17//! travels between a caller and a callee is the target's answer rather than C's, so the walk to
18//! the IR flattens a C type into a [`Shape`] and asks here what form it takes. Every psABI rule
19//! is behind [`Call`] and nothing outside this crate matches on an architecture to find one.
20//! The rules themselves are `rucc-abi`'s, as data rather than as code, and this crate hands the
21//! question over to them. It answers [`None`] on a target whose ABI is not written down yet,
22//! which today is AArch64 on Windows and nothing else.
23//!
24//! # Status
25//!
26//! Triple parsing and the basic data model are real, which is what `rucc --print-config`
27//! reports, and so is the argument classification of every psABI in
28//! `spec/12-abi-and-runtime.md` sections 12.2 to 12.5, which `rucc-abi` describes as data and
29//! this crate selects between. x86-64's register file is written down,
30//! in [`x86_64`], along with what each of the two conventions over it does with each register,
31//! what each of its machine instructions does with its operands, and which instructions a frame
32//! is made of, which is [`FrameInsts`]. AArch64's and RISC-V's arrive with their backends.
33//! Machine models land in `M6`.
34//!
35//! This crate is tier 3 in `spec/18-package-layout.md` section 18.5: its Rust API is
36//! explicitly unstable and will change without a major version bump.
37
38#![doc(html_root_url = "https://docs.rs/rucc-target/0.10.65")]
39
40use std::fmt;
41use std::str::FromStr;
42
43use rucc_abi::DataLayout;
44use rucc_base::float::Format;
45use rucc_tuple::{self as tuple, TargetTuple};
46
47mod abi;
48mod bits;
49mod branch;
50mod flags;
51mod frame;
52mod machine;
53mod operand;
54mod regs;
55mod short;
56mod timing;
57pub mod x86_64;
58
59pub use crate::abi::{Arg, Call, Kind, Pass, Piece, Scalar, Shape, Slot};
60pub use crate::bits::BitInsts;
61pub use crate::branch::{BranchInsts, Fusion};
62pub use crate::flags::{Compare, FlagInsts, Reader, Reads, Zeroing};
63pub use crate::frame::{ClassMoves, FrameInsts, Probe};
64pub use crate::machine::MachineInsts;
65pub use crate::operand::{Constraint, OperandDesc, Role};
66pub use crate::regs::{
67 CallRegs, Chkstk, ClassInfo, Guard, PhysReg, Places, RegClass, RegFile, Segment, Trace, Where,
68};
69pub use crate::short::{Copied, Narrowed, ShortInsts, Stepped, Tested, Zeroed};
70pub use crate::timing::{Timing, TimingInsts, Unit};
71
72/// A target architecture.
73#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
74// Deliberately not `#[non_exhaustive]`. Adding a variant here has to break every
75// match that needs to change, in this workspace and in anyone else's code. That is
76// the property `spec/10-backend.md` section 10.8 is claiming when it says adding a
77// target is a data change: the compiler tells you every place the data is read.
78pub enum Arch {
79 /// x86-64, the first target and the one `M3` brings up.
80 X86_64,
81 /// AArch64, the second target, `M6`.
82 Aarch64,
83 /// 64-bit RISC-V. `spec/10-backend.md` calls this the middle-end canary, because it has
84 /// no condition codes and no complex addressing modes, so anything the middle end got
85 /// away with on x86-64 shows up here.
86 Riscv64,
87}
88
89impl Arch {
90 /// Pointer width in bits.
91 pub const fn pointer_width(self) -> u32 {
92 match self {
93 Arch::X86_64 | Arch::Aarch64 | Arch::Riscv64 => 64,
94 }
95 }
96
97 /// Whether the target is little-endian.
98 pub const fn is_little_endian(self) -> bool {
99 match self {
100 Arch::X86_64 | Arch::Aarch64 | Arch::Riscv64 => true,
101 }
102 }
103
104 /// The name as it appears in a triple.
105 pub const fn as_str(self) -> &'static str {
106 match self {
107 Arch::X86_64 => "x86_64",
108 Arch::Aarch64 => "aarch64",
109 Arch::Riscv64 => "riscv64",
110 }
111 }
112}
113
114/// The operating system a target runs on.
115#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
116// Deliberately not `#[non_exhaustive]`. Adding a variant here has to break every
117// match that needs to change, in this workspace and in anyone else's code. That is
118// the property `spec/10-backend.md` section 10.8 is claiming when it says adding a
119// target is a data change: the compiler tells you every place the data is read.
120pub enum Os {
121 /// Linux, hosted or freestanding.
122 Linux,
123 /// Apple platforms. `spec/12-abi-and-runtime.md` section 12.3 lists the four places
124 /// Apple diverges from AAPCS64, and every one of them is a real bug if missed.
125 Darwin,
126 /// Windows.
127 Windows,
128 /// No operating system, which is what `-ffreestanding` kernel work looks like.
129 None,
130}
131
132impl Os {
133 /// The name as it appears in a triple.
134 pub const fn as_str(self) -> &'static str {
135 match self {
136 Os::Linux => "linux",
137 Os::Darwin => "darwin",
138 Os::Windows => "windows",
139 Os::None => "none",
140 }
141 }
142
143 /// The object file format this operating system uses.
144 pub const fn object_format(self) -> ObjectFormat {
145 match self {
146 Os::Linux | Os::None => ObjectFormat::Elf,
147 Os::Darwin => ObjectFormat::MachO,
148 Os::Windows => ObjectFormat::Coff,
149 }
150 }
151}
152
153/// The C runtime and ABI variant.
154#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
155// Deliberately not `#[non_exhaustive]`. Adding a variant here has to break every
156// match that needs to change, in this workspace and in anyone else's code. That is
157// the property `spec/10-backend.md` section 10.8 is claiming when it says adding a
158// target is a data change: the compiler tells you every place the data is read.
159pub enum Env {
160 /// The default for the operating system.
161 None,
162 /// glibc.
163 Gnu,
164 /// musl.
165 Musl,
166 /// The MSVC ABI.
167 Msvc,
168}
169
170impl Env {
171 /// The name as it appears in a triple, if it appears at all.
172 pub const fn as_str(self) -> &'static str {
173 match self {
174 Env::None => "none",
175 Env::Gnu => "gnu",
176 Env::Musl => "musl",
177 Env::Msvc => "msvc",
178 }
179 }
180}
181
182/// The object file format to emit.
183#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
184// Deliberately not `#[non_exhaustive]`. Adding a variant here has to break every
185// match that needs to change, in this workspace and in anyone else's code. That is
186// the property `spec/10-backend.md` section 10.8 is claiming when it says adding a
187// target is a data change: the compiler tells you every place the data is read.
188pub enum ObjectFormat {
189 /// ELF.
190 Elf,
191 /// Mach-O.
192 MachO,
193 /// COFF.
194 Coff,
195 /// WebAssembly, which is a format for a module rather than for a machine's object file and
196 /// is in this list because the target table has two rows that emit one.
197 Wasm,
198}
199
200impl ObjectFormat {
201 /// The name used in diagnostics and in `--print-config`.
202 pub const fn as_str(self) -> &'static str {
203 match self {
204 ObjectFormat::Elf => "elf",
205 ObjectFormat::MachO => "macho",
206 ObjectFormat::Coff => "coff",
207 ObjectFormat::Wasm => "wasm",
208 }
209 }
210
211 /// The same format as [`rucc_tuple::ObjectFormat`] names it.
212 ///
213 /// The two enumerations exist because the tuple describes forty two targets and this crate
214 /// describes what the compiler emits for one, and they will stay separate for as long as that
215 /// is true. This is the one place they are put side by side.
216 #[must_use]
217 pub const fn from_tuple(format: tuple::ObjectFormat) -> Self {
218 match format {
219 tuple::ObjectFormat::Elf => ObjectFormat::Elf,
220 tuple::ObjectFormat::MachO => ObjectFormat::MachO,
221 tuple::ObjectFormat::Coff => ObjectFormat::Coff,
222 tuple::ObjectFormat::Wasm => ObjectFormat::Wasm,
223 }
224 }
225}
226
227/// A target triple.
228///
229/// We accept the LLVM-style `arch-vendor-os-env` form because that is what build systems
230/// pass, and we normalise it to the three fields we actually branch on. The vendor field is
231/// parsed and discarded: no decision in the compiler depends on it, and keeping it would
232/// invite one.
233#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
234pub struct Triple {
235 /// The architecture.
236 pub arch: Arch,
237 /// The operating system.
238 pub os: Os,
239 /// The runtime and ABI variant.
240 pub env: Env,
241}
242
243impl Triple {
244 /// A triple from its three parts.
245 pub const fn new(arch: Arch, os: Os, env: Env) -> Self {
246 Self { arch, os, env }
247 }
248
249 /// The same machine as a [`TargetTuple`], which is what the layout and ABI descriptions are
250 /// written over.
251 ///
252 /// The tuple carries ten fields and this carries three, so this fills the other seven in from
253 /// their defaults, and every one of those defaults is the answer for the targets this type can
254 /// spell. There is no `x32` here and no big-endian AArch64, so the data model and the byte
255 /// order follow the architecture, and the sub-architecture, the versions and the float ABI have
256 /// nothing to say about any of the combinations.
257 ///
258 /// The environment is narrowed rather than copied across. This type will hold
259 /// `Triple { os: Darwin, env: Gnu }`, because its parser takes the fields by content and
260 /// `aarch64-apple-darwin-gnu` is a string somebody can type, and that is not a machine: a
261 /// Darwin target has one libc and it is not glibc. A tuple refuses to describe one, so the
262 /// pairs that are not machines are mapped to the environment the operating system actually
263 /// has.
264 ///
265 /// # Panics
266 ///
267 /// Never, for a triple this type can hold, which `every_triple_describes_a_machine` checks by
268 /// building all forty eight of them.
269 #[must_use]
270 pub fn tuple(self) -> TargetTuple {
271 let arch = match self.arch {
272 Arch::X86_64 => tuple::Arch::X86_64,
273 Arch::Aarch64 => tuple::Arch::Aarch64,
274 Arch::Riscv64 => tuple::Arch::Riscv64,
275 };
276 let os = match self.os {
277 Os::Linux => tuple::Os::Linux,
278 // macOS rather than iOS, because the three field triple cannot tell them apart and
279 // this compiler is hosted on the one and not on the other.
280 Os::Darwin => tuple::Os::MacOs,
281 Os::Windows => tuple::Os::Windows,
282 Os::None => tuple::Os::None,
283 };
284 let env = match (self.os, self.env) {
285 (Os::Linux, Env::Musl) => tuple::Env::Musl,
286 (Os::Linux, _) => tuple::Env::Gnu,
287 // mingw-w64 is a real Windows environment and the one place `gnu` survives the
288 // narrowing, because it has a different `long double` from MSVC on the same OS.
289 (Os::Windows, Env::Gnu) => tuple::Env::Gnu,
290 (Os::Windows, _) => tuple::Env::Msvc,
291 // Darwin and freestanding have no libc to name.
292 (Os::Darwin | Os::None, _) => tuple::Env::None,
293 };
294 TargetTuple::builder(arch, os)
295 .env(env)
296 .build()
297 .expect("every triple this type can hold describes a machine")
298 }
299
300 /// The triple that describes the same machine as `target`, if this type can spell it.
301 ///
302 /// The inverse of [`Triple::tuple`], and computed by running that function over every triple
303 /// there is rather than by writing the narrowing out a second time. A second table would be a
304 /// second thing to keep in step, and the failure it invites is not a compile error: it is one
305 /// row of the matrix quietly answering as a neighbour.
306 ///
307 /// It returns `None` for most of the target table, and that is the honest answer rather than a
308 /// gap to be papered over. `rucc-abi` describes the scalar layout of all forty two rows, and
309 /// this type holds three fields with three architectures in the first, so seventeen of those
310 /// rows have a [`TargetInfo`] and the other twenty five do not. Anything that needs to lay a
311 /// record out for `s390x-linux-gnu` needs that gap closed rather than an approximation of it.
312 ///
313 /// The environment of the answer is the narrowed one, so the triple this gives back is the
314 /// canonical spelling of that machine: `Env::None` on Darwin and on a freestanding target,
315 /// never the `Env::Gnu` that a parser will accept from a string somebody typed.
316 #[must_use]
317 pub fn from_tuple(target: TargetTuple) -> Option<Triple> {
318 // Four triples narrow onto `x86_64-linux-gnu`, because a Darwin triple claiming glibc is
319 // a string somebody can type and not a machine. So a match is not enough on its own: the
320 // answer is the candidate whose environment came through the narrowing unchanged, and
321 // anything else is only a fallback for the day a narrowing loses a spelling entirely.
322 let mut fallback = None;
323 for arch in [Arch::X86_64, Arch::Aarch64, Arch::Riscv64] {
324 for os in [Os::Linux, Os::Darwin, Os::Windows, Os::None] {
325 for env in [Env::None, Env::Gnu, Env::Musl, Env::Msvc] {
326 let candidate = Triple::new(arch, os, env);
327 if candidate.tuple() != target {
328 continue;
329 }
330 // By name rather than by a match on the pair, so that an environment added to
331 // either enumeration does not need a line here. The one name the two spell
332 // differently is the absent one, which the tuple writes as nothing.
333 let survived = match env {
334 Env::None => target.env() == tuple::Env::None,
335 _ => env.as_str() == target.env().as_str(),
336 };
337 if survived {
338 return Some(candidate);
339 }
340 fallback.get_or_insert(candidate);
341 }
342 }
343 }
344 fallback
345 }
346
347 /// The triple of the machine this compiler is running on.
348 ///
349 /// Used as the default target, which is what makes `rucc hello.c` work with no flags.
350 /// Unknown host combinations are not an error here: they are reported by the driver,
351 /// where there is somewhere to report them to.
352 pub fn host() -> Option<Self> {
353 let arch = match std::env::consts::ARCH {
354 "x86_64" => Arch::X86_64,
355 "aarch64" => Arch::Aarch64,
356 "riscv64" => Arch::Riscv64,
357 _ => return None,
358 };
359 // Which libc this is matters, and `std::env::consts` does not say. A compiler built on
360 // Alpine and defaulting to `x86_64-unknown-linux-gnu` describes a machine it is not
361 // running on: musl and glibc disagree about `int_fast16_t` among other things, and a
362 // header that is written out of the predefined type names picks the disagreement up.
363 // The libc rucc itself was linked against is the best evidence available about the one
364 // the code it compiles will be linked against, and it is right on every machine where
365 // rucc was built for the machine it runs on.
366 let linux = if cfg!(target_env = "musl") { Env::Musl } else { Env::Gnu };
367 let (os, env) = match std::env::consts::OS {
368 "linux" => (Os::Linux, linux),
369 "macos" => (Os::Darwin, Env::None),
370 "windows" => (Os::Windows, Env::Msvc),
371 _ => return None,
372 };
373 Some(Self::new(arch, os, env))
374 }
375}
376
377impl fmt::Display for Triple {
378 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
379 // Always four fields, always the same spelling, because this string ends up in
380 // `--print-config` output that people diff.
381 write!(f, "{}-unknown-{}-{}", self.arch.as_str(), self.os.as_str(), self.env.as_str())
382 }
383}
384
385/// Why a triple failed to parse.
386#[derive(Debug, Clone, PartialEq, Eq)]
387pub struct ParseTripleError {
388 /// The triple as given.
389 pub input: String,
390 /// What specifically was not recognised.
391 pub reason: &'static str,
392}
393
394impl fmt::Display for ParseTripleError {
395 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
396 write!(f, "unsupported target triple `{}`: {}", self.input, self.reason)
397 }
398}
399
400impl std::error::Error for ParseTripleError {}
401
402impl FromStr for Triple {
403 type Err = ParseTripleError;
404
405 fn from_str(s: &str) -> Result<Self, Self::Err> {
406 let err = |reason| ParseTripleError { input: s.to_owned(), reason };
407 let mut parts = s.split('-');
408
409 let arch = match parts.next() {
410 Some("x86_64" | "amd64") => Arch::X86_64,
411 Some("aarch64" | "arm64") => Arch::Aarch64,
412 Some("riscv64") => Arch::Riscv64,
413 _ => return Err(err("unknown architecture")),
414 };
415
416 // The vendor field is optional in practice. `x86_64-linux-gnu` and
417 // `x86_64-unknown-linux-gnu` both occur in the wild and mean the same thing, so the
418 // remaining fields are matched by content rather than by position.
419 let rest: Vec<&str> = parts.collect();
420 let mut os = None;
421 let mut env = None;
422 for part in &rest {
423 match *part {
424 "linux" => os = Some(Os::Linux),
425 "darwin" | "macos" | "macosx" | "ios" => os = Some(Os::Darwin),
426 "windows" | "win32" => os = Some(Os::Windows),
427 // `none` is the one token that means different things in the two positions.
428 // In `x86_64-unknown-none-elf` it is the operating system; in
429 // `aarch64-apple-darwin-none` it is the environment. Which one it is depends
430 // on whether an operating system has already been seen, and that rule is what
431 // makes `Display` round-trip through `FromStr`.
432 "none" if os.is_none() => os = Some(Os::None),
433 "none" => env = Some(Env::None),
434 "elf" => os = os.or(Some(Os::None)),
435 "gnu" | "gnueabi" | "gnueabihf" => env = Some(Env::Gnu),
436 "musl" | "musleabi" | "musleabihf" => env = Some(Env::Musl),
437 "msvc" => env = Some(Env::Msvc),
438 _ => {}
439 }
440 }
441
442 let os = os.ok_or_else(|| err("unknown operating system"))?;
443 let env = env.unwrap_or(match os {
444 Os::Linux => Env::Gnu,
445 Os::Windows => Env::Msvc,
446 Os::Darwin | Os::None => Env::None,
447 });
448 Ok(Self::new(arch, os, env))
449 }
450}
451
452/// The facts about a target that the compiler reads instead of hard-coding.
453///
454/// This is the whole of what a pass is allowed to know about where its output will run.
455/// It grows, and every field added here is one fewer `#[cfg]` somewhere it should not be.
456#[derive(Debug, Clone, PartialEq, Eq)]
457#[non_exhaustive]
458pub struct TargetInfo {
459 /// The machine this describes, as the ten field tuple rather than as a three field triple.
460 ///
461 /// It is the tuple because a record layout is a question every row of the target table has an
462 /// answer to, and a triple can spell fifteen of the forty two. Nothing else in this type had
463 /// to change to widen it: every field below is already derived from `rucc-abi`'s description
464 /// of this tuple, and the ones that were not were the bugs.
465 pub tuple: TargetTuple,
466 /// The sizes, the alignments and the signedness this target's headers were written against.
467 ///
468 /// The widths below are views of this and the alignments are not, which is the reason it is
469 /// kept whole. A `long long` is eight bytes on every row of the table and is aligned to four
470 /// on System V i386 and to eight everywhere else, and no width can say that.
471 pub scalars: DataLayout,
472 /// Width of a pointer in bits.
473 pub pointer_width: u32,
474 /// Whether bytes are ordered little end first.
475 pub little_endian: bool,
476 /// Whether a bare `char` is signed.
477 ///
478 /// Signed on x86-64 and unsigned on AArch64 Linux, which is the classic source of code
479 /// that works on one and not the other, so it is data rather than an assumption.
480 pub char_is_signed: bool,
481 /// Width of `long` in bits. This is the field that separates the LP64 world from
482 /// Windows LLP64.
483 pub long_width: u32,
484 /// Width of `long double` in bits: 80 bits of x87 stored in 128 on every x86-64 target but
485 /// MSVC, 128 of true quad precision on AArch64 Linux and RISC-V, and 64 on Apple's AArch64 and
486 /// under MSVC.
487 ///
488 /// Apple's x86-64 is not one of the 64-bit ones, which is the trap. The change to a `double`
489 /// came with AArch64 and the Intel answer stayed as it was, so `x86_64-apple-darwin` and
490 /// `x86_64-unknown-linux-gnu` agree here and `aarch64-apple-darwin` is the odd one.
491 pub long_double_width: u32,
492 /// The format `long double` actually is, which the width does not say.
493 ///
494 /// It is 128 bits wide on SysV x86-64 and on AArch64 Linux and the two are not the same
495 /// type: one is the x87 eighty bit format padded out to sixteen bytes and the other is
496 /// true quad precision with a hundred and thirteen bits of significand. Anything that
497 /// converts a constant or folds one has to know which, and the width alone cannot say.
498 pub long_double_format: Format,
499 /// The format `_Float64x` is, which is the widest format the target has short of a software
500 /// one.
501 ///
502 /// It follows the architecture and not the operating system, which is what makes it worth a
503 /// field of its own next to `long double`. Apple and Windows define `long double` as a
504 /// `double` and neither of them takes `_Float64x` down with it: the type has to be wider
505 /// than a `_Float64`, so it is the x87 eighty bit format on x86-64 and quad precision on
506 /// AArch64 and RISC-V wherever it is written.
507 ///
508 /// [`None`] on a machine whose widest format is a `double`, which is 32-bit ARM and wasm32.
509 /// The type does not exist there and neither reference defines the macros that describe it,
510 /// so the honest answer is that there is no format rather than a `double` in its place.
511 pub float64x_format: Option<Format>,
512 /// Whether the target has `_Float16`.
513 ///
514 /// The named types are not all universal the way `_Float32` and `_Float64` are. gcc 13 has
515 /// this one on x86-64, AArch64 and RISC-V and does not have it on i686, armv7, ppc64le or
516 /// s390x, which was measured by compiling a declaration of it with each of those cross
517 /// compilers. The `__FLT16_*__` macros and the `f16` suffix are defined on exactly the rows
518 /// where the type is, so all three ask this one field.
519 ///
520 /// i686 is the row worth explaining. gcc aims at the baseline of the target rather than at
521 /// whatever chip is under it, and half precision on x86 needs SSE2, which is in the baseline
522 /// of x86-64 and not in the baseline of i686. So the two x86 rows disagree, and a `-msse2`
523 /// on the command line would move the 32-bit one, which is a thing this compiler has no
524 /// place to say yet.
525 pub has_float16: bool,
526 /// Whether the target has `_Float128`.
527 ///
528 /// Every row but 32-bit ARM among the seven measured against gcc 13. x86-64 and i686 have it
529 /// in software, and AArch64, RISC-V, s390x and ppc64le have it because quad precision is
530 /// already the format of something on those machines. armv7 has no format wider than a
531 /// `double` at all, so the type is not there and gcc says so.
532 ///
533 /// This is the ISO spelling. gcc's `__float128` is a narrower thing and is not this field:
534 /// that name exists on x86 and PowerPC only, and on AArch64, RISC-V and s390x gcc offers
535 /// `_Float128` in its place when a program writes it. `__SIZEOF_FLOAT128__` follows the
536 /// vendor name rather than the type, which is why it is missing on rows where the type is
537 /// there.
538 pub has_float128: bool,
539 /// Width of `wchar_t` in bits, which decides what a wide literal is encoded in.
540 ///
541 /// It is 16 on Windows, so a wide string there is UTF-16 and a character outside the basic
542 /// plane takes two elements, and 32 everywhere else, where a wide string is UTF-32 and no
543 /// character takes more than one.
544 pub wchar_width: u32,
545 /// Whether `wchar_t` is signed.
546 ///
547 /// x86-64 Linux makes it a signed `int` and AArch64 Linux makes it an `unsigned int`,
548 /// following the psABI's rule for plain `char`, so `L'\xffffffff'` is minus one on one of
549 /// them and four billion on the other.
550 pub wchar_is_signed: bool,
551 /// The granule a `_BitInt` wider than 64 bits is laid out in, in bits.
552 ///
553 /// Above 64 bits the psABIs stop treating a `_BitInt` like a standard integer type and
554 /// start treating it like an array of these, so its size is rounded up to a multiple of
555 /// this and its alignment is this. It is 64 on x86-64 and RISC-V and 128 on AArch64, which
556 /// is why `_BitInt(65)` is sixteen bytes aligned to eight on one and sixteen bytes aligned
557 /// to sixteen on the other. Measured with clang 18 on x86-64 Linux and clang on AArch64
558 /// Darwin rather than read off the documents.
559 pub bit_int_granule: u32,
560 /// The widest access, in bits, this machine performs atomically without taking a lock.
561 ///
562 /// It is what `__atomic_always_lock_free` and `__atomic_is_lock_free` answer from, and it is
563 /// a claim about what this compiler emits rather than about what the processor is capable of.
564 /// Sixty four on every target here. x86-64 does sixteen bytes atomically with `cmpxchg16b`,
565 /// which is not in the baseline the psABI names and which nothing in this compiler writes, and
566 /// AArch64 does the same with its pair instructions, which nothing writes either. A target
567 /// that answered yes for sixteen bytes and then called a library that has to take a lock for
568 /// them would have two answers to one question, and the wrong one is the one in the header.
569 pub lock_free_width: u32,
570 /// The object format to emit.
571 pub object_format: ObjectFormat,
572 /// How bit-fields are allocated into storage, which is the one record layout question where
573 /// two targets in this table run different algorithms rather than the same one over different
574 /// numbers.
575 pub bit_field_style: BitFieldStyle,
576 /// Whether an unnamed bit-field raises the record's alignment the way a named one does.
577 ///
578 /// Almost everywhere it does not, which is why `struct { char c; int :20; }` is four bytes
579 /// aligned to one on x86-64 and four aligned to four with the field named. AAPCS64 says
580 /// otherwise and says it for the zero width member too, so `struct { unsigned :0; }` is
581 /// aligned to four on AArch64 Linux and to one on Apple's AArch64, on Windows on AArch64, on
582 /// x86-64 and on RISC-V. Measured with the pinned reference across every row that has one,
583 /// because it is neither an architecture rule nor an operating system rule: it is the ABI, and
584 /// Apple and Microsoft each dropped it.
585 ///
586 /// Windows says yes as well, and there it is not AAPCS64 but Microsoft's own rule, which is
587 /// why the two facts are separate fields rather than one. In a `union` the Microsoft rule goes
588 /// further and no bit-field contributes alignment at all, named or not, so this field is only
589 /// half the answer there and [`BitFieldStyle`] carries the other half.
590 pub unnamed_bit_field_aligns: bool,
591 /// How large a record with no storage in it is, in bytes, before its alignment is applied.
592 ///
593 /// Zero everywhere but MSVC, where it is four. A `struct` with no members is not C at all, it
594 /// is a GNU extension, and C++ gives it a size of one, so there is no standard to read the
595 /// answer out of and the number has to come from whatever else compiles for the target. On
596 /// mingw that is GCC and the answer is zero. On MSVC it is clang, because MSVC itself rejects
597 /// the declaration outright, and clang's Microsoft record layout gives it four bytes and gives
598 /// an array of three of them twelve. So this is a fact about the environment and not about the
599 /// operating system, which is the one place in this type where those two come apart in that
600 /// direction.
601 ///
602 /// It covers a record with no members and a record whose only members occupy nothing, which is
603 /// the zero width bit-field, the zero length array and the flexible array member. All four
604 /// were measured and all four agree.
605 pub empty_record_size: u64,
606 /// What `__builtin_va_list` is, which is the type every `va_list` in every header is a
607 /// typedef of.
608 ///
609 /// [`None`] on a target whose answer is a type this crate does not build yet. 32-bit ARM's is
610 /// a structure of one pointer and s390x's is a structure of four members, and neither is any
611 /// of the four below. A target with no backend cannot compile a call to `va_arg` in any case,
612 /// so saying so beats naming a neighbour's type and having a header believe it.
613 pub va_list: Option<VaList>,
614 /// The registers the machine has, which is [`RegFile::EMPTY`] for an architecture nothing
615 /// has described yet.
616 pub regs: &'static RegFile,
617 /// Which registers the calling convention gives which job, or `None` while the
618 /// architecture has no register file to name them out of.
619 pub call_regs: Option<&'static CallRegs>,
620 /// How long this machine's instructions take, or `None` for an architecture with no backend.
621 ///
622 /// [`None`] rather than a model of a machine nobody measured, for the reason the two fields
623 /// above are: a scheduler told made up numbers about a processor has no way to find out they
624 /// were made up. `--print-config` prints [`TimingInsts::model`] off this, which is the first
625 /// thing anybody comparing two runs of a benchmark wants to know.
626 pub timing: Option<&'static TimingInsts>,
627}
628
629/// The type a target's `__builtin_va_list` is.
630///
631/// A variable argument list is the one place a psABI dictates a C type rather than how a type
632/// travels, and the four answers below are not four spellings of one thing: `sizeof(va_list)` is
633/// eight bytes on Apple's AArch64 and thirty two on Linux's, and on SysV x86-64 a `va_list` is an
634/// array, so a `va_list` passed to a function is passed as a pointer and one assigned to another
635/// is a constraint violation rather than a copy. Code in the wild depends on all of that.
636#[derive(Debug, Clone, Copy, PartialEq, Eq)]
637// Deliberately not `#[non_exhaustive]`, for the reason [`Arch`] is not: a fifth answer here is
638// a fifth type to build, and every place that builds one should stop compiling until it does.
639pub enum VaList {
640 /// `char *`, which is what a target whose arguments are all passed in one place needs: the
641 /// address of the next argument and nothing else. Apple's AArch64 and both Windows targets.
642 CharPointer,
643 /// `void *`, which is the RISC-V psABI's spelling of the same thing.
644 VoidPointer,
645 /// `struct __va_list_tag { unsigned gp_offset, fp_offset; void *overflow_arg_area,
646 /// *reg_save_area; } [1]`, the SysV x86-64 one. Arguments arrive in two register files and
647 /// on the stack, so the list is a cursor into each, and the array of one is what makes
648 /// passing it to `vfprintf` pass its address.
649 SysV,
650 /// `struct __va_list { void *__stack, *__gr_top, *__vr_top; int __gr_offs, __vr_offs; }`,
651 /// the AAPCS64 one. The same idea as SysV's, counting down from the top of each save area
652 /// rather than up from the bottom, and not an array.
653 Aapcs,
654}
655
656impl VaList {
657 /// The name used in `--print-config`.
658 #[must_use]
659 pub const fn as_str(self) -> &'static str {
660 match self {
661 VaList::CharPointer => "char-pointer",
662 VaList::VoidPointer => "void-pointer",
663 VaList::SysV => "sysv",
664 VaList::Aapcs => "aapcs",
665 }
666 }
667}
668
669/// How a target allocates bit-fields into storage.
670///
671/// Everything else about laying a record out is one algorithm reading different sizes and
672/// alignments per target. This is not: the two answers below place the same members at different
673/// offsets and give the same struct different sizes, and no amount of changing what an `int` is
674/// turns one into the other. `struct { unsigned m:3; char c; }` is four bytes with the `char` at
675/// offset one under the first and eight bytes with it at offset four under the second.
676#[derive(Debug, Clone, Copy, PartialEq, Eq)]
677// Deliberately not `#[non_exhaustive]`, for the reason [`Arch`] is not: a third answer here is a
678// third algorithm to write, and every place that chooses between them should stop compiling until
679// it does.
680pub enum BitFieldStyle {
681 /// The Itanium C++ ABI's rule, which every psABI in this table except Windows follows. A
682 /// bit-field goes at the next free bit unless that would make it span more storage than its
683 /// own type occupies, in which case it starts at the next boundary of its alignment. Storage
684 /// is shared between members of different types freely, so `struct { char a:3; unsigned b:3; }`
685 /// is four bytes with both fields in the first one.
686 Itanium,
687 /// Microsoft's rule, which both Windows environments follow and not only MSVC. A run of
688 /// bit-fields is allocated into a unit the size and alignment of the declared type, and the
689 /// unit is closed both when the next member's declared type has a different size and when the
690 /// field does not fit in what is left. An ordinary member closes a unit too, and the closed
691 /// unit occupies its whole declared size whether or not the bits were used. So the same struct
692 /// is eight bytes: a one byte unit for the `char` and a four byte one for the `unsigned`,
693 /// aligned to four.
694 Microsoft,
695}
696
697impl BitFieldStyle {
698 /// The name used in `--print-config`.
699 #[must_use]
700 pub const fn as_str(self) -> &'static str {
701 match self {
702 BitFieldStyle::Itanium => "itanium",
703 BitFieldStyle::Microsoft => "microsoft",
704 }
705 }
706}
707
708/// A width in bits, from a size in bytes.
709///
710/// The fields here are widths because that is what a predefined macro and a diagnostic say, and a
711/// layout is sizes because that is what `sizeof` says. The conversion belongs at the one boundary
712/// between them rather than at every reader of one of these fields.
713fn bits(bytes: u64) -> u32 {
714 u32::try_from(bytes * 8).expect("no standard type is four billion bits wide")
715}
716
717impl TargetInfo {
718 /// The description of `triple`.
719 ///
720 /// The three field triple spells fifteen of the forty two rows of the target table, which is
721 /// every row with a backend and every row a driver will be handed today, so this is what the
722 /// compiler proper calls. [`TargetInfo::for_tuple`] is the one that answers for the whole
723 /// table.
724 #[must_use]
725 pub fn new(triple: Triple) -> Self {
726 Self::for_tuple(triple.tuple())
727 }
728
729 /// The description of `target`.
730 ///
731 /// Every row of the target table has one of these, whether or not there is a backend that can
732 /// emit code for it, because laying a record out and reading a header are questions that do
733 /// not need a backend. The fields that genuinely need one say so: [`TargetInfo::regs`] is
734 /// empty and [`TargetInfo::call_regs`] is [`None`] for an architecture whose register file is
735 /// not written down.
736 #[must_use]
737 pub fn for_tuple(target: TargetTuple) -> Self {
738 // Every size, alignment and signedness below is `rucc-abi`'s answer over the ten field
739 // tuple rather than a match written out here. They were written out here, and the copy was
740 // wrong about `x86_64-apple-darwin`, whose `long double` is the eighty bit x87 format in
741 // sixteen bytes and not a `double`: Apple made that change on AArch64 and left the Intel
742 // answer alone, and a rule keyed on the operating system takes both.
743 let layout = DataLayout::for_target(target);
744 // AArch64, RISC-V and everything else with a row and no backend have register files and
745 // this crate has not written them down yet. They arrive with the backends that need them,
746 // in M6 and M7.
747 let regs = match target.arch() {
748 tuple::Arch::X86_64 => &x86_64::REGS,
749 _ => &RegFile::EMPTY,
750 };
751 let call_regs = match (target.arch(), target.os(), target.env()) {
752 // The environment, and this is the one question it decides about a convention. What the
753 // two Windows runtimes disagree about is the name of the routine a large frame reaches
754 // its pages by calling, which is in the runtime rather than in the compiler, so a build
755 // against mingw-w64 and a build against Microsoft's runtime want different names for the
756 // same routine.
757 (tuple::Arch::X86_64, tuple::Os::Windows, tuple::Env::Gnu) => Some(&x86_64::MINGW64),
758 (tuple::Arch::X86_64, tuple::Os::Windows, _) => Some(&x86_64::WIN64),
759 // Apple's x86-64 follows SysV, and its divergences from it are on AArch64.
760 (tuple::Arch::X86_64, _, _) => Some(&x86_64::SYSV),
761 _ => None,
762 };
763 // The same rule as the register file. A model is a measurement of a processor, and there
764 // is nothing to measure until there is a backend emitting instructions for it.
765 let timing = match target.arch() {
766 tuple::Arch::X86_64 => Some(&x86_64::TIMING),
767 _ => None,
768 };
769 Self {
770 tuple: target,
771 scalars: layout,
772 pointer_width: bits(layout.pointer_size),
773 little_endian: target.is_little_endian(),
774 char_is_signed: layout.char_is_signed,
775 long_width: bits(layout.long_size),
776 long_double_width: bits(layout.long_double.size),
777 long_double_format: layout.long_double.format,
778 float64x_format: float64x_format(target),
779 has_float16: has_float16(target),
780 has_float128: has_float128(target),
781 wchar_width: bits(layout.wchar_size),
782 wchar_is_signed: layout.wchar_is_signed,
783 bit_int_granule: bit_int_granule(target),
784 // Eight bytes everywhere, for the reason the field gives: it is the widest access this
785 // compiler writes an instruction for, and every one of these machines has a wider one
786 // that nothing here reaches. It is a claim about the code this compiler emits, so the
787 // day a backend emits a sixteen byte atomic is the day this stops being one number.
788 lock_free_width: 64,
789 object_format: ObjectFormat::from_tuple(target.object_format()),
790 bit_field_style: bit_field_style(target),
791 unnamed_bit_field_aligns: unnamed_bit_field_aligns(target),
792 // The environment and not the operating system, so `x86_64-windows-gnu` keeps GCC's
793 // zero while `x86_64-windows-msvc` takes clang's four.
794 empty_record_size: match target.env() {
795 tuple::Env::Msvc => 4,
796 _ => 0,
797 },
798 va_list: va_list(target),
799 regs,
800 call_regs,
801 timing,
802 }
803 }
804
805 /// The largest an object may be on this target, in bytes.
806 ///
807 /// `PTRDIFF_MAX`, which is what C 6.5.6 needs it to be: subtracting two pointers into one
808 /// object has to have an answer, and the answer has a `ptrdiff_t` to fit in. So an object
809 /// of exactly this many bytes is allowed and one byte more is not, which is the line GCC
810 /// draws too. It is the only size limit in the compiler and every layout question that has
811 /// one asks here rather than at whatever its own arithmetic happens to overflow at.
812 #[must_use]
813 pub const fn max_object_size(&self) -> u64 {
814 (1u64 << (self.pointer_width - 1)) - 1
815 }
816}
817
818/// The format `_Float64x` is, where the target has one.
819fn float64x_format(target: TargetTuple) -> Option<Format> {
820 match target.arch() {
821 // The x87 unit is on the machine whatever the operating system says a `long double` is,
822 // so `x86_64-apple-darwin` and `x86_64-windows-msvc` both have an eighty bit `_Float64x`
823 // and an eight byte `long double`.
824 tuple::Arch::X86_64 | tuple::Arch::X86 => Some(Format::X87Extended),
825 tuple::Arch::Aarch64
826 | tuple::Arch::Riscv64
827 | tuple::Arch::Riscv32
828 | tuple::Arch::LoongArch64
829 | tuple::Arch::S390x
830 | tuple::Arch::PowerPc64 => Some(Format::Quad),
831 // Nothing on these machines is wider than a `double`, so there is no type here to
832 // describe and neither reference defines the macros that would describe it.
833 tuple::Arch::Arm | tuple::Arch::Arm64Ec | tuple::Arch::Wasm32 => None,
834 }
835}
836
837/// Whether the target has `_Float16`.
838fn has_float16(target: TargetTuple) -> bool {
839 match target.arch() {
840 // Half precision is in the baseline of these: SSE2 on x86-64, the FP16 storage format
841 // every ARMv8 has, and RISC-V, where gcc gives the type whether or not the hardware has
842 // the instructions to go with it.
843 tuple::Arch::X86_64
844 | tuple::Arch::Aarch64
845 | tuple::Arch::Arm64Ec
846 | tuple::Arch::Riscv64
847 | tuple::Arch::Riscv32 => true,
848 // i686 for the reason the field gives, which is the baseline and not the chip, and the
849 // rest are machines gcc 13 has not written the type for.
850 tuple::Arch::X86
851 | tuple::Arch::Arm
852 | tuple::Arch::LoongArch64
853 | tuple::Arch::PowerPc64
854 | tuple::Arch::S390x
855 | tuple::Arch::Wasm32 => false,
856 }
857}
858
859/// Whether the target has `_Float128`.
860fn has_float128(target: TargetTuple) -> bool {
861 match target.arch() {
862 // Either the machine already has quad precision, which is the AArch64, RISC-V, s390x and
863 // PowerPC answer, or the compiler provides it in software, which is what x86 does.
864 tuple::Arch::X86_64
865 | tuple::Arch::X86
866 | tuple::Arch::Aarch64
867 | tuple::Arch::Arm64Ec
868 | tuple::Arch::Riscv64
869 | tuple::Arch::Riscv32
870 | tuple::Arch::LoongArch64
871 | tuple::Arch::PowerPc64
872 | tuple::Arch::S390x => true,
873 // The same two rows that have no `_Float64x`, and for the same reason: nothing on the
874 // machine is wider than a `double` and neither reference offers a type that is.
875 tuple::Arch::Arm | tuple::Arch::Wasm32 => false,
876 }
877}
878
879/// The granule a `_BitInt` wider than 64 bits is laid out in, in bits.
880fn bit_int_granule(target: TargetTuple) -> u32 {
881 match target.arch() {
882 // AAPCS64 says a `_BitInt` above sixty four bits is an array of `__int128`, which is the
883 // one psABI that departs from the register width here.
884 tuple::Arch::Aarch64 | tuple::Arch::Arm64Ec => 128,
885 // Everywhere else it is the width of a general purpose register, which is what the psABIs
886 // that have written the rule down all say and what both references do on the rows that
887 // have not.
888 tuple::Arch::X86 | tuple::Arch::Arm | tuple::Arch::Riscv32 => 32,
889 tuple::Arch::X86_64
890 | tuple::Arch::Riscv64
891 | tuple::Arch::LoongArch64
892 | tuple::Arch::PowerPc64
893 | tuple::Arch::S390x
894 | tuple::Arch::Wasm32 => 64,
895 }
896}
897
898/// How this target allocates bit-fields into storage.
899///
900/// Keyed on the operating system rather than the environment, because mingw's answer here is
901/// Microsoft's and not GCC's. That is the whole reason it is not a guess: a rule keyed on
902/// `Env::Msvc` gets `x86_64-windows-gnu` wrong by four bytes on a struct of an `unsigned :3` and a
903/// `char`, and gets it wrong quietly.
904fn bit_field_style(target: TargetTuple) -> BitFieldStyle {
905 match target.os() {
906 tuple::Os::Windows => BitFieldStyle::Microsoft,
907 _ => BitFieldStyle::Itanium,
908 }
909}
910
911/// Whether an unnamed bit-field raises the record's alignment the way a named one does.
912///
913/// AAPCS says it does, on both widths of ARM, and Apple and Microsoft each dropped that rule.
914/// Microsoft then put its own rule in the same place for a `struct`, so Windows says yes again by
915/// a different route, and says something else entirely for a `union`, which [`BitFieldStyle`]
916/// carries rather than this.
917fn unnamed_bit_field_aligns(target: TargetTuple) -> bool {
918 match (target.arch(), target.os()) {
919 (_, tuple::Os::Windows) => true,
920 // A freestanding ARM target is AAPCS proper, so it says yes: there is no operating system
921 // there to have dropped it.
922 (tuple::Arch::Aarch64 | tuple::Arch::Arm | tuple::Arch::Arm64Ec, os) => !os.is_darwin(),
923 _ => false,
924 }
925}
926
927/// What `__builtin_va_list` is on this target, where this crate can build the type.
928fn va_list(target: TargetTuple) -> Option<VaList> {
929 match (target.arch(), target.os()) {
930 // Windows passes every argument in one place and spills the register ones next to the
931 // stack ones, so the list is an address, and Apple does the same on AArch64.
932 (_, tuple::Os::Windows) => Some(VaList::CharPointer),
933 (tuple::Arch::Aarch64, os) if os.is_darwin() => Some(VaList::CharPointer),
934 (tuple::Arch::Aarch64, _) => Some(VaList::Aapcs),
935 // The x32 ABI's list is the same structure with four byte pointers in it, which is what
936 // building it out of this target's pointer type gives, so it is the same answer.
937 (tuple::Arch::X86_64, _) => Some(VaList::SysV),
938 (tuple::Arch::X86, _) => Some(VaList::CharPointer),
939 (tuple::Arch::Riscv64 | tuple::Arch::Riscv32 | tuple::Arch::LoongArch64, _)
940 | (tuple::Arch::Wasm32, _) => Some(VaList::VoidPointer),
941 // 32-bit ARM's is a structure of one pointer, s390x's is a structure of four members, and
942 // PowerPC's is a structure of five. None of them is any of the four types above and this
943 // crate does not build them, so it says so rather than naming a neighbour's.
944 (
945 tuple::Arch::Arm | tuple::Arch::S390x | tuple::Arch::PowerPc64 | tuple::Arch::Arm64Ec,
946 _,
947 ) => None,
948 }
949}
950
951#[cfg(test)]
952mod tests {
953 use super::*;
954
955 #[test]
956 fn parses_a_four_field_triple() {
957 let t: Triple = "x86_64-unknown-linux-gnu".parse().unwrap();
958 assert_eq!(t, Triple::new(Arch::X86_64, Os::Linux, Env::Gnu));
959 }
960
961 #[test]
962 fn parses_a_triple_with_no_vendor() {
963 let t: Triple = "aarch64-linux-musl".parse().unwrap();
964 assert_eq!(t, Triple::new(Arch::Aarch64, Os::Linux, Env::Musl));
965 }
966
967 #[test]
968 fn accepts_the_common_aliases() {
969 let a: Triple = "arm64-apple-darwin".parse().unwrap();
970 let b: Triple = "aarch64-apple-darwin".parse().unwrap();
971 assert_eq!(a, b);
972 assert_eq!(a.env, Env::None);
973 }
974
975 #[test]
976 fn fills_in_the_default_environment() {
977 let t: Triple = "x86_64-unknown-linux".parse().unwrap();
978 assert_eq!(t.env, Env::Gnu);
979 let w: Triple = "x86_64-pc-windows".parse().unwrap();
980 assert_eq!(w.env, Env::Msvc);
981 }
982
983 #[test]
984 fn rejects_what_it_does_not_support() {
985 let e = "sparc64-unknown-linux-gnu".parse::<Triple>().unwrap_err();
986 assert_eq!(e.reason, "unknown architecture");
987 let e = "x86_64-unknown-plan9".parse::<Triple>().unwrap_err();
988 assert_eq!(e.reason, "unknown operating system");
989 }
990
991 #[test]
992 fn displays_in_a_normalised_form() {
993 let t: Triple = "amd64-linux-gnu".parse().unwrap();
994 assert_eq!(t.to_string(), "x86_64-unknown-linux-gnu");
995 }
996
997 #[test]
998 fn display_round_trips_through_parse() {
999 for s in [
1000 "x86_64-unknown-linux-gnu",
1001 "aarch64-unknown-darwin-none",
1002 "riscv64-unknown-linux-musl",
1003 ] {
1004 let t: Triple = s.parse().unwrap();
1005 assert_eq!(t.to_string().parse::<Triple>().unwrap(), t);
1006 }
1007 }
1008
1009 #[test]
1010 fn char_signedness_follows_the_psabi() {
1011 let x86 = TargetInfo::new("x86_64-unknown-linux-gnu".parse().unwrap());
1012 let arm = TargetInfo::new("aarch64-unknown-linux-gnu".parse().unwrap());
1013 let mac = TargetInfo::new("aarch64-apple-darwin".parse().unwrap());
1014 assert!(x86.char_is_signed);
1015 assert!(!arm.char_is_signed);
1016 assert!(mac.char_is_signed, "Apple overrides AAPCS64 back to a signed char");
1017 }
1018
1019 #[test]
1020 fn windows_is_llp64() {
1021 let win = TargetInfo::new("x86_64-pc-windows-msvc".parse().unwrap());
1022 assert_eq!(win.pointer_width, 64);
1023 assert_eq!(win.long_width, 32);
1024 }
1025
1026 #[test]
1027 fn the_largest_object_is_ptrdiff_max() {
1028 // Half the address space less one, which is what a pointer subtraction across the whole
1029 // of one object has to fit in. gcc 16 on x86-64 prints this same number when it refuses
1030 // an array, and takes an object of exactly this many bytes.
1031 for triple in ["x86_64-unknown-linux-gnu", "aarch64-apple-darwin", "x86_64-pc-windows-msvc"]
1032 {
1033 let target = TargetInfo::new(triple.parse().unwrap());
1034 assert_eq!(target.max_object_size(), 9_223_372_036_854_775_807, "{triple}");
1035 }
1036 }
1037
1038 #[test]
1039 fn apple_long_double_is_double() {
1040 let mac = TargetInfo::new("aarch64-apple-darwin".parse().unwrap());
1041 assert_eq!(mac.long_double_width, 64);
1042 assert_eq!(mac.long_double_format, Format::Double);
1043 let linux = TargetInfo::new("x86_64-unknown-linux-gnu".parse().unwrap());
1044 assert_eq!(linux.long_double_width, 128);
1045 }
1046
1047 #[test]
1048 fn apples_x86_64_is_not_one_of_the_targets_that_narrowed_long_double() {
1049 // The bug the layout facts moving to `rucc-abi` fixed. This crate used to decide the
1050 // width from the operating system, which took both Apple targets, and Apple made the
1051 // change on AArch64 only. `facts/x86_64-macos.facts` in tamnd/rucc-cross records
1052 // `long_double_format=x87_extended` with `sizeof_long_double=16`, from a reference
1053 // compiler, and this used to answer a sixty four bit `double`.
1054 //
1055 // It is the quiet kind of wrong. `sizeof(long double)` came out at eight where the
1056 // headers say sixteen, so `printf("%Lf")` read the wrong bytes and every structure with
1057 // a `long double` in it laid out differently from the system's own.
1058 let mac = TargetInfo::new("x86_64-apple-darwin".parse().unwrap());
1059 assert_eq!(mac.long_double_width, 128);
1060 assert_eq!(mac.long_double_format, Format::X87Extended);
1061
1062 let linux = TargetInfo::new("x86_64-unknown-linux-gnu".parse().unwrap());
1063 assert_eq!(
1064 (mac.long_double_width, mac.long_double_format),
1065 (linux.long_double_width, linux.long_double_format)
1066 );
1067 }
1068
1069 #[test]
1070 fn every_triple_describes_a_machine() {
1071 // `Triple::tuple` panics on a pair that is not a machine and this is what says there is
1072 // no such pair. All forty eight combinations, including the ones the parser will produce
1073 // from a string somebody can type and no machine has, such as a Darwin target claiming
1074 // glibc.
1075 let mut built = 0;
1076 for arch in [Arch::X86_64, Arch::Aarch64, Arch::Riscv64] {
1077 for os in [Os::Linux, Os::Darwin, Os::Windows, Os::None] {
1078 for env in [Env::None, Env::Gnu, Env::Musl, Env::Msvc] {
1079 let triple = Triple::new(arch, os, env);
1080 let tuple = triple.tuple();
1081 assert_eq!(tuple.pointer_width(), 64, "{triple}");
1082 // The one field the narrowing has to preserve, because mingw and MSVC are the
1083 // same operating system with two different `long double`s.
1084 if os == Os::Windows {
1085 let expected = match env {
1086 Env::Gnu => rucc_tuple::Env::Gnu,
1087 _ => rucc_tuple::Env::Msvc,
1088 };
1089 assert_eq!(tuple.env(), expected, "{triple}");
1090 }
1091 built += 1;
1092 }
1093 }
1094 }
1095 assert_eq!(built, 48);
1096 }
1097
1098 #[test]
1099 fn from_tuple_undoes_the_narrowing() {
1100 // Every triple's tuple comes back as a triple describing the same machine. It is not
1101 // always the triple it started as, because the narrowing is many to one: a Darwin target
1102 // claiming glibc and the same one claiming nothing are one machine, and the answer is the
1103 // spelling that names no libc.
1104 for arch in [Arch::X86_64, Arch::Aarch64, Arch::Riscv64] {
1105 for os in [Os::Linux, Os::Darwin, Os::Windows, Os::None] {
1106 for env in [Env::None, Env::Gnu, Env::Musl, Env::Msvc] {
1107 let triple = Triple::new(arch, os, env);
1108 let back = Triple::from_tuple(triple.tuple())
1109 .unwrap_or_else(|| panic!("{triple} has a tuple and no way back"));
1110 assert_eq!(back.tuple(), triple.tuple(), "{triple}");
1111 assert_eq!(back.arch, arch, "{triple}");
1112 assert_eq!(back.os, os, "{triple}");
1113 }
1114 }
1115 }
1116 }
1117
1118 #[test]
1119 fn from_tuple_gives_the_canonical_environment() {
1120 let musl = Triple::from_tuple("aarch64-linux-musl".parse().unwrap()).unwrap();
1121 assert_eq!(musl, Triple::new(Arch::Aarch64, Os::Linux, Env::Musl));
1122 let gnu = Triple::from_tuple("x86_64-linux-gnu".parse().unwrap()).unwrap();
1123 assert_eq!(gnu, Triple::new(Arch::X86_64, Os::Linux, Env::Gnu));
1124 // Darwin and freestanding name no libc, so the answer does too, even though the parser
1125 // will hand this type a Darwin triple with `gnu` on the end.
1126 let macos = Triple::from_tuple("aarch64-macos".parse().unwrap()).unwrap();
1127 assert_eq!(macos, Triple::new(Arch::Aarch64, Os::Darwin, Env::None));
1128 let bare = Triple::from_tuple("riscv64-none".parse().unwrap()).unwrap();
1129 assert_eq!(bare, Triple::new(Arch::Riscv64, Os::None, Env::None));
1130 // The two Windows environments stay apart, which is the whole reason the narrowing keeps
1131 // the environment there and nowhere else.
1132 let mingw = Triple::from_tuple("x86_64-windows-gnu".parse().unwrap()).unwrap();
1133 assert_eq!(mingw.env, Env::Gnu);
1134 let msvc = Triple::from_tuple("x86_64-windows-msvc".parse().unwrap()).unwrap();
1135 assert_eq!(msvc.env, Env::Msvc);
1136 }
1137
1138 #[test]
1139 fn from_tuple_says_no_rather_than_saying_something_near() {
1140 // Twenty five of the forty two rows have no triple, and the answer is `None` rather than
1141 // a neighbour. `rucc-abi` knows the scalar layout of every one of these and this type
1142 // cannot hold any of them, which is the gap the record layout engine inherits.
1143 for tuple in [
1144 "i686-linux-gnu",
1145 "armv7-linux-gnueabihf",
1146 "s390x-linux-gnu",
1147 "powerpc64le-linux-gnu",
1148 "loongarch64-linux-gnu",
1149 "x86_64-linux-gnux32",
1150 "aarch64-linux-android",
1151 "aarch64-ios",
1152 "wasm32-wasip1",
1153 "x86_64-freebsd",
1154 ] {
1155 let target = tuple.parse().unwrap();
1156 assert_eq!(Triple::from_tuple(target), None, "{tuple}");
1157 }
1158 }
1159
1160 #[test]
1161 fn mingw_and_msvc_are_one_operating_system_with_two_long_doubles() {
1162 // The narrowing in `Triple::tuple` keeps the environment on Windows for this reason and
1163 // throws it away everywhere else. GCC's Windows targets keep the eighty bit `long double`
1164 // and Microsoft's make it a `double`, on the same processor and the same OS.
1165 let mingw = TargetInfo::new("x86_64-pc-windows-gnu".parse().unwrap());
1166 assert_eq!(mingw.long_double_width, 128);
1167 assert_eq!(mingw.long_double_format, Format::X87Extended);
1168
1169 let msvc = TargetInfo::new("x86_64-pc-windows-msvc".parse().unwrap());
1170 assert_eq!(msvc.long_double_width, 64);
1171 assert_eq!(msvc.long_double_format, Format::Double);
1172
1173 // And they agree about everything the operating system does decide.
1174 assert_eq!(mingw.long_width, msvc.long_width);
1175 assert_eq!(mingw.wchar_width, msvc.wchar_width);
1176 assert_eq!(mingw.object_format, msvc.object_format);
1177 }
1178
1179 #[test]
1180 fn wchar_t_divides_the_targets_in_two_directions_at_once() {
1181 // Windows narrows it to sixteen bits, which makes a wide string UTF-16 there and
1182 // UTF-32 everywhere else, and AArch64 Linux makes it unsigned without narrowing it.
1183 let windows = TargetInfo::new("x86_64-pc-windows-msvc".parse().unwrap());
1184 assert_eq!((windows.wchar_width, windows.wchar_is_signed), (16, false));
1185 let arm = TargetInfo::new("aarch64-unknown-linux-gnu".parse().unwrap());
1186 assert_eq!((arm.wchar_width, arm.wchar_is_signed), (32, false));
1187 let linux = TargetInfo::new("x86_64-unknown-linux-gnu".parse().unwrap());
1188 assert_eq!((linux.wchar_width, linux.wchar_is_signed), (32, true));
1189 // Apple keeps it signed on the same processor where Linux does not, in the same way it
1190 // keeps plain `char` signed there.
1191 let mac = TargetInfo::new("aarch64-apple-darwin".parse().unwrap());
1192 assert_eq!((mac.wchar_width, mac.wchar_is_signed), (32, true));
1193 }
1194
1195 #[test]
1196 fn va_list_is_the_psabis_type_and_not_one_type_with_four_spellings() {
1197 let linux = TargetInfo::new("x86_64-unknown-linux-gnu".parse().unwrap());
1198 assert_eq!(linux.va_list, Some(VaList::SysV));
1199 // x86-64 Darwin follows SysV here, and AArch64 Darwin does not follow AAPCS64.
1200 let mac = TargetInfo::new("x86_64-apple-darwin".parse().unwrap());
1201 assert_eq!(mac.va_list, Some(VaList::SysV));
1202 let arm_mac = TargetInfo::new("aarch64-apple-darwin".parse().unwrap());
1203 assert_eq!(arm_mac.va_list, Some(VaList::CharPointer));
1204 let arm = TargetInfo::new("aarch64-unknown-linux-gnu".parse().unwrap());
1205 assert_eq!(arm.va_list, Some(VaList::Aapcs));
1206 // Windows passes everything one way on both processors, so both get the simple one.
1207 let win = TargetInfo::new("x86_64-pc-windows-msvc".parse().unwrap());
1208 assert_eq!(win.va_list, Some(VaList::CharPointer));
1209 let arm_win = TargetInfo::new("aarch64-pc-windows-msvc".parse().unwrap());
1210 assert_eq!(arm_win.va_list, Some(VaList::CharPointer));
1211 let riscv = TargetInfo::new("riscv64-unknown-linux-gnu".parse().unwrap());
1212 assert_eq!(riscv.va_list, Some(VaList::VoidPointer));
1213 }
1214
1215 #[test]
1216 fn two_targets_agree_on_the_width_of_long_double_and_not_on_the_type() {
1217 // Sixteen bytes on both, and a different number in them: the x87 format has sixty four
1218 // bits of significand and quad precision has a hundred and thirteen, so a constant
1219 // converted for one is the wrong bits for the other.
1220 let x86 = TargetInfo::new("x86_64-unknown-linux-gnu".parse().unwrap());
1221 let arm = TargetInfo::new("aarch64-unknown-linux-gnu".parse().unwrap());
1222 assert_eq!(x86.long_double_width, arm.long_double_width);
1223 assert_eq!(x86.long_double_format, Format::X87Extended);
1224 assert_eq!(arm.long_double_format, Format::Quad);
1225 assert_eq!(x86.long_double_format.precision(), 64);
1226 assert_eq!(arm.long_double_format.precision(), 113);
1227 // Windows keeps the name and drops the type, the way Apple does.
1228 let windows = TargetInfo::new("x86_64-pc-windows-msvc".parse().unwrap());
1229 assert_eq!(windows.long_double_format, Format::Double);
1230 }
1231
1232 #[test]
1233 fn float64x_follows_the_processor_where_long_double_follows_the_operating_system() {
1234 // `_Float64x` is the widest format the hardware has, and no ABI takes it away the way
1235 // Apple and Windows take `long double` away. So the two fields say the same thing on
1236 // Linux and disagree everywhere else, which is the whole reason there are two of them.
1237 let x86 = TargetInfo::new("x86_64-unknown-linux-gnu".parse().unwrap());
1238 assert_eq!(x86.float64x_format, Some(Format::X87Extended));
1239 let arm = TargetInfo::new("aarch64-unknown-linux-gnu".parse().unwrap());
1240 assert_eq!(arm.float64x_format, Some(Format::Quad));
1241 let riscv = TargetInfo::new("riscv64-unknown-linux-gnu".parse().unwrap());
1242 assert_eq!(riscv.float64x_format, Some(Format::Quad));
1243
1244 let mac = TargetInfo::new("aarch64-apple-darwin".parse().unwrap());
1245 assert_eq!(mac.long_double_format, Format::Double);
1246 assert_eq!(mac.float64x_format, Some(Format::Quad));
1247 let windows = TargetInfo::new("x86_64-pc-windows-msvc".parse().unwrap());
1248 assert_eq!(windows.long_double_format, Format::Double);
1249 assert_eq!(windows.float64x_format, Some(Format::X87Extended));
1250 }
1251
1252 #[test]
1253 fn the_named_floating_types_are_not_on_every_machine() {
1254 // gcc 13, measured with the cross compilers rather than reasoned about. `_Float16` is on
1255 // three of these seven and `_Float128` is on six, and the two lists are not the same
1256 // list, which is why there are two fields.
1257 // The three field triple spells three architectures, and four of these rows are not
1258 // among them, so this asks the tuple the way the layout tests do.
1259 let of = |tuple: &str| TargetInfo::for_tuple(tuple.parse().expect("a row in the table"));
1260 let rows = [
1261 ("x86_64-linux-gnu", true, true),
1262 ("i686-linux-gnu", false, true),
1263 ("aarch64-linux-gnu", true, true),
1264 ("armv7-linux-gnueabihf", false, false),
1265 ("powerpc64le-linux-gnu", false, true),
1266 ("riscv64-linux-gnu", true, true),
1267 ("s390x-linux-gnu", false, true),
1268 ];
1269 for (tuple, float16, float128) in rows {
1270 let target = of(tuple);
1271 assert_eq!(target.has_float16, float16, "{tuple} `_Float16`");
1272 assert_eq!(target.has_float128, float128, "{tuple} `_Float128`");
1273 }
1274 // The operating system has nothing to do with it, the way it has nothing to do with
1275 // `_Float64x`, so Apple and Windows keep both types.
1276 assert!(of("aarch64-apple-darwin").has_float16);
1277 assert!(of("x86_64-pc-windows-msvc").has_float128);
1278 }
1279
1280 #[test]
1281 fn the_object_format_follows_the_operating_system() {
1282 assert_eq!(Os::Linux.object_format(), ObjectFormat::Elf);
1283 assert_eq!(Os::Darwin.object_format(), ObjectFormat::MachO);
1284 assert_eq!(Os::Windows.object_format(), ObjectFormat::Coff);
1285 }
1286
1287 #[test]
1288 fn a_target_carries_its_registers_and_says_so_when_it_has_none() {
1289 let of = |triple: &str| TargetInfo::new(triple.parse().unwrap());
1290 let linux = of("x86_64-unknown-linux-gnu");
1291 assert_eq!(linux.regs.reg_named("rdi"), Some((x86_64::GPR, x86_64::RDI)));
1292 assert_eq!(linux.call_regs.map(|regs| regs.int_args[0]), Some(x86_64::RDI));
1293 // Apple's x86-64 is SysV and Windows is the one that is not.
1294 let apple = of("x86_64-apple-darwin");
1295 assert_eq!(apple.call_regs.map(|regs| regs.int_args[0]), Some(x86_64::RDI));
1296 let windows = of("x86_64-pc-windows-msvc");
1297 assert_eq!(windows.regs.len(x86_64::GPR), 16);
1298 assert_eq!(windows.call_regs.map(|regs| regs.int_args[0]), Some(x86_64::RCX));
1299 // Not described yet, and saying nothing is the answer rather than saying x86-64's.
1300 let arm = of("aarch64-unknown-linux-gnu");
1301 assert!(arm.regs.is_empty());
1302 assert!(arm.call_regs.is_none());
1303 }
1304
1305 /// The timing model, which follows the register file: an architecture with no backend has
1306 /// nothing to measure and says so rather than borrowing a neighbour's numbers.
1307 #[test]
1308 fn a_target_carries_the_model_its_schedules_were_chosen_with() {
1309 let of = |triple: &str| TargetInfo::new(triple.parse().unwrap());
1310 let linux = of("x86_64-unknown-linux-gnu");
1311 let timing = linux.timing.expect("x86-64 has a backend and so has a model");
1312 assert!(timing.model.contains("Skylake"), "{}", timing.model);
1313 assert!(!timing.accurate, "and it says it is not a cycle accurate one");
1314 assert_eq!(timing.of("x64.imul_rr_64").map(|cost| cost.unit), Some(Unit::Mul));
1315
1316 // The same model whatever the operating system, since a model is about the processor.
1317 assert_eq!(of("x86_64-apple-darwin").timing, linux.timing);
1318 assert_eq!(of("x86_64-pc-windows-msvc").timing, linux.timing);
1319
1320 assert!(of("aarch64-unknown-linux-gnu").timing.is_none(), "nobody has measured it here");
1321 }
1322
1323 #[test]
1324 fn the_host_triple_is_one_we_support() {
1325 // Every host in spec/15-testing.md section 15.7 must be recognised, and CI runs on
1326 // all three, so a failure here means a host we claim support for stopped resolving.
1327 let host = Triple::host().expect("the host must be a supported target");
1328 assert_eq!(host.to_string().parse::<Triple>().unwrap(), host);
1329 }
1330}