Skip to main content

rucc_types/
convert.rs

1//! The integer promotions and the usual arithmetic conversions.
2//!
3//! Design: `spec/07-types-and-semantics.md` section 7.2.
4//!
5//! These are 6.3.1.1 and 6.3.1.8, the two rules that decide what type an arithmetic expression
6//! has, and they are where a compiler quietly goes wrong in ways that only show up as an
7//! overflow or a sign extension in generated code. So the answers here were read out of gcc
8//! 13.3 and clang 18 rather than out of the standard, with `_Generic` naming the type of every
9//! interesting pair, and the standard was used to explain what was measured.
10//!
11//! C23 changed three things and they are all here. `bool` is a real type and promotes to `int`.
12//! An enumeration may have a fixed underlying type, and then it promotes through that rather
13//! than through a type the implementation picked. And `_BitInt` does not promote at all, so
14//! `_BitInt(8) + _BitInt(8)` is `_BitInt(8)` where `char + char` is `int`, which is the point
15//! of the type: it is the one integer type in C that does what it says.
16
17use rucc_target::TargetInfo;
18
19use crate::kind::{FloatKind, IntKind, TypeKind};
20use crate::layout::{float_format, int_width};
21use crate::types::{TypeId, Types};
22
23/// The integer promotions, 6.3.1.1.
24///
25/// Anything narrower than `int` becomes `int`, or `unsigned int` when `int` cannot hold every
26/// value it had. Everything else, floating types and pointers included, is its own answer, so
27/// this can be called on any operand without asking what it is first.
28///
29/// The qualifiers and `_Atomic` come off, because by the time a value is being promoted the
30/// lvalue conversion of 6.3.2.1 has already happened and neither of them is part of the value.
31///
32/// `_BitInt` is deliberately not promoted. That is C23 6.3.1.1p2, and it is what both compilers
33/// do: `+x` on a `_BitInt(8)` is still a `_BitInt(8)`.
34pub fn promote(types: &mut Types, id: TypeId, target: &TargetInfo) -> TypeId {
35    let id = value_type(types, id);
36    match types.kind(id) {
37        TypeKind::Bool => types.int(IntKind::Int),
38        TypeKind::Int(kind) => promoted_int(types, kind, int_width(kind, target), target),
39        TypeKind::Enum(id) => {
40            // An enumeration promotes through whatever it is represented in. Until that has
41            // been decided the declaration is incomplete, which is a diagnostic somewhere with
42            // a span; `int` keeps the rest of the expression checkable in the meantime.
43            let underlying = types.enum_info(id).underlying;
44            match underlying {
45                Some(underlying) => promote(types, underlying, target),
46                None => types.int(IntKind::Int),
47            }
48        }
49        _ => id,
50    }
51}
52
53/// The integer promotions applied to a bit-field of the given width.
54///
55/// A bit-field is narrower than the type it was declared with, and it is the width rather than
56/// the type that decides. `unsigned b:3` promotes to `int`, because every three bit value fits
57/// in one, and `unsigned b:32` promotes to `unsigned int`, because they no longer do.
58///
59/// A bit-field wider than an `int` is an integer of exactly that many bits, which is the type
60/// `_BitInt` already is. The C17 wording says `unsigned int` there, which would turn a forty bit
61/// field into a thirty two bit value, and C23 says the declared type instead. Neither is what
62/// either compiler does: gcc gives such a field a type whose precision is the width, so a forty
63/// bit field shifted left by thirty two is zero rather than a value with bits above the fortieth,
64/// and clang agrees. That is a `_BitInt(40)` here, and saying it that way is what makes the usual
65/// arithmetic conversions below give the right answer for a pair of them without knowing they
66/// came from bit-fields.
67///
68/// A field as wide as the type it was declared with is that type, since there is no precision to
69/// lose and `unsigned long long b:64` reading as a `_BitInt(64)` would be a different type for no
70/// reason.
71pub fn promote_bit_field(types: &mut Types, id: TypeId, width: u32, target: &TargetInfo) -> TypeId {
72    let id = value_type(types, id);
73    let (signed, declared) = match types.kind(id) {
74        TypeKind::Bool => (false, 1),
75        TypeKind::Int(kind) => (kind.is_signed(target.char_is_signed), int_width(kind, target)),
76        TypeKind::BitInt { signed, width } => (signed, width),
77        // An enumeration bit-field promotes through what it is represented in, and anything
78        // else is not something a bit-field may be declared with.
79        _ => return promote(types, id, target),
80    };
81    let int = int_width(IntKind::Int, target);
82    if width < int || (signed && width == int) {
83        return types.int(IntKind::Int);
84    }
85    if !signed && width == int {
86        return types.int(IntKind::UInt);
87    }
88    if width >= declared {
89        return promote(types, id, target);
90    }
91    types.bit_int(signed, width)
92}
93
94/// The usual arithmetic conversions, 6.3.1.8: the one type both operands are converted to.
95///
96/// [`None`] when either operand is not an arithmetic type, which is not a failure of this
97/// function but the shape of a diagnostic its caller is about to write.
98///
99/// The floating rules come first and the integer rules only run when neither side is floating,
100/// which is why `unsigned long long + float` is `float` and loses precision rather than being
101/// the other way round.
102pub fn usual_arithmetic(
103    types: &mut Types,
104    left: TypeId,
105    right: TypeId,
106    target: &TargetInfo,
107) -> Option<TypeId> {
108    let left = value_type(types, left);
109    let right = value_type(types, right);
110    if let Some(common) = floating(types, left, right, target) {
111        return Some(common);
112    }
113    let left = promote(types, left, target);
114    let right = promote(types, right, target);
115    if left == right {
116        // Not only a shortcut: it is also the answer for the types this function does not model
117        // as integers, which is every one of them once the two sides agree.
118        return integer_shape(types, left, target).map(|_| left);
119    }
120    let left = integer_shape(types, left, target)?;
121    let right = integer_shape(types, right, target)?;
122    Some(common_integer(types, left, right, target))
123}
124
125/// The type of a value of type `id`, which is `id` without the parts an lvalue conversion
126/// removes.
127fn value_type(types: &mut Types, id: TypeId) -> TypeId {
128    let id = types.canonical(id);
129    let id = match types.kind(id) {
130        TypeKind::Atomic(inner) => types.canonical(inner),
131        _ => id,
132    };
133    types.unqualified(id)
134}
135
136/// The promotion of a standard integer type of the given width.
137fn promoted_int(types: &mut Types, kind: IntKind, width: u32, target: &TargetInfo) -> TypeId {
138    if kind.rank() >= IntKind::Int.rank() {
139        return types.int(kind);
140    }
141    let int = int_width(IntKind::Int, target);
142    let signed = kind.is_signed(target.char_is_signed);
143    if width < int || (signed && width == int) {
144        return types.int(IntKind::Int);
145    }
146    types.int(IntKind::UInt)
147}
148
149/// The common type when either side is a floating type, and [`None`] when neither is.
150///
151/// The real type is the one with the higher rank, or the floating one when the other side is an
152/// integer, and the result is complex when either operand was. That last part is why
153/// `_Complex float + double` is `_Complex double`: the real types combine first and the
154/// complexity is carried across afterwards.
155fn floating(types: &mut Types, left: TypeId, right: TypeId, target: &TargetInfo) -> Option<TypeId> {
156    let left = float_part(types, left);
157    let right = float_part(types, right);
158    let (kind, complex) = match (left, right) {
159        (None, None) => return None,
160        (Some((kind, complex)), None) | (None, Some((kind, complex))) => (kind, complex),
161        (Some((a, a_complex)), Some((b, b_complex))) => {
162            let kind = if float_rank(a, target) >= float_rank(b, target) { a } else { b };
163            (kind, a_complex || b_complex)
164        }
165    };
166    Some(if complex { types.complex(kind) } else { types.float(kind) })
167}
168
169/// The conversion rank of a real floating type, as something two of which can be compared.
170///
171/// There is no ordering on the kinds themselves to use here, because since C23 the answer
172/// depends on the target: `long double` outranks `_Float64x` on x86-64, where both of them are
173/// the x87 format, and loses to it on Apple, where `long double` is a `double`. So the question
174/// is asked of the format instead. Precision first and then range, which never disagree among
175/// the binary formats, and [`FloatKind::tie_break`] settles two types that are the same format,
176/// which is what makes `double + _Float64` a `_Float64`.
177fn float_rank(kind: FloatKind, target: &TargetInfo) -> (u32, i32, u8) {
178    let format = float_format(kind, target);
179    (format.precision(), format.max_exponent(), kind.tie_break())
180}
181
182/// The real floating type inside `id`, and whether it was complex.
183fn float_part(types: &Types, id: TypeId) -> Option<(FloatKind, bool)> {
184    match types.kind(id) {
185        TypeKind::Float(kind) => Some((kind, false)),
186        TypeKind::Complex(kind) => Some((kind, true)),
187        _ => None,
188    }
189}
190
191/// What an integer type is, once it no longer matters how it was spelled.
192#[derive(Clone, Copy)]
193struct IntShape {
194    signed: bool,
195    width: u32,
196    /// The standard type it is, and [`None`] for a `_BitInt`.
197    standard: Option<IntKind>,
198}
199
200impl IntShape {
201    /// The integer conversion rank, as something two of which can be compared.
202    ///
203    /// Width first, which is what makes a `_BitInt(40)` outrank an `int` and lose to a `long`.
204    /// A standard type outranks a `_BitInt` of the same width, which is C23 6.3.1.1p1 and is
205    /// why `_BitInt(32) + int` is `int`. The standard rank breaks the last tie, which is the
206    /// one that matters on every 64-bit target: `long` and `long long` are both sixty four bits
207    /// and `long long` outranks `long`.
208    fn rank(self) -> (u32, u8, u8) {
209        match self.standard {
210            Some(kind) => (self.width, 1, kind.rank()),
211            None => (self.width, 0, 0),
212        }
213    }
214
215    /// Whether every value of `other` is a value of this type.
216    fn covers(self, other: IntShape) -> bool {
217        if self.signed == other.signed {
218            return self.width >= other.width;
219        }
220        // A signed type loses a bit to the sign, so it takes a strictly wider one to hold every
221        // value of an unsigned type. That is what makes `unsigned int + long` a `long` on
222        // Linux and an `unsigned long` on Windows, where `long` is only thirty two bits.
223        self.signed && self.width > other.width
224    }
225}
226
227/// The shape of an integer type, and [`None`] when `id` is not one.
228fn integer_shape(types: &Types, id: TypeId, target: &TargetInfo) -> Option<IntShape> {
229    match types.kind(id) {
230        TypeKind::Int(kind) => Some(IntShape {
231            signed: kind.is_signed(target.char_is_signed),
232            width: int_width(kind, target),
233            standard: Some(kind),
234        }),
235        TypeKind::BitInt { signed, width } => Some(IntShape { signed, width, standard: None }),
236        _ => None,
237    }
238}
239
240/// The common type of two promoted integer types.
241fn common_integer(
242    types: &mut Types,
243    left: IntShape,
244    right: IntShape,
245    target: &TargetInfo,
246) -> TypeId {
247    let (higher, lower) = if left.rank() >= right.rank() { (left, right) } else { (right, left) };
248    if higher.signed == lower.signed || !higher.signed || higher.covers(lower) {
249        // Same signedness, or the higher ranked one is the unsigned one, or it is the signed
250        // one and wide enough to hold every value the other side had.
251        return build(types, higher, target);
252    }
253    // The signed type wins on rank and loses on range, so neither operand's type will do and
254    // the answer is the unsigned type of the same width. This is the arm that turns
255    // `long + unsigned long` into `unsigned long`, and it is the one a program is surprised by.
256    build(types, IntShape { signed: false, ..higher }, target)
257}
258
259/// The type an [`IntShape`] describes.
260fn build(types: &mut Types, shape: IntShape, target: &TargetInfo) -> TypeId {
261    match shape.standard {
262        Some(kind) if kind.is_signed(target.char_is_signed) == shape.signed => types.int(kind),
263        Some(kind) => types.int(kind.flip_sign()),
264        None => types.bit_int(shape.signed, shape.width),
265    }
266}