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::classify::{element, is_vector, lanes};
20use crate::kind::{FloatKind, IntKind, TypeKind};
21use crate::layout::{float_format, float_width, int_width, integer_info, layout};
22use crate::types::{TypeId, Types};
23
24/// The integer promotions, 6.3.1.1.
25///
26/// Anything narrower than `int` becomes `int`, or `unsigned int` when `int` cannot hold every
27/// value it had. Everything else, floating types and pointers included, is its own answer, so
28/// this can be called on any operand without asking what it is first.
29///
30/// The qualifiers and `_Atomic` come off, because by the time a value is being promoted the
31/// lvalue conversion of 6.3.2.1 has already happened and neither of them is part of the value.
32///
33/// `_BitInt` is deliberately not promoted. That is C23 6.3.1.1p2, and it is what both compilers
34/// do: `+x` on a `_BitInt(8)` is still a `_BitInt(8)`.
35pub fn promote(types: &mut Types, id: TypeId, target: &TargetInfo) -> TypeId {
36 let id = value_type(types, id);
37 match types.kind(id) {
38 TypeKind::Bool => types.int(IntKind::Int),
39 TypeKind::Int(kind) => promoted_int(types, kind, int_width(kind, target), target),
40 TypeKind::Enum(id) => {
41 // An enumeration promotes through whatever it is represented in. Until that has
42 // been decided the declaration is incomplete, which is a diagnostic somewhere with
43 // a span; `int` keeps the rest of the expression checkable in the meantime.
44 let underlying = types.enum_info(id).underlying;
45 match underlying {
46 Some(underlying) => promote(types, underlying, target),
47 None => types.int(IntKind::Int),
48 }
49 }
50 _ => id,
51 }
52}
53
54/// The integer promotions applied to a bit-field of the given width.
55///
56/// A bit-field is narrower than the type it was declared with, and it is the width rather than
57/// the type that decides. `unsigned b:3` promotes to `int`, because every three bit value fits
58/// in one, and `unsigned b:32` promotes to `unsigned int`, because they no longer do.
59///
60/// A bit-field wider than an `int` is an integer of exactly that many bits, which is the type
61/// `_BitInt` already is. The C17 wording says `unsigned int` there, which would turn a forty bit
62/// field into a thirty two bit value, and C23 says the declared type instead. Neither is what
63/// either compiler does: gcc gives such a field a type whose precision is the width, so a forty
64/// bit field shifted left by thirty two is zero rather than a value with bits above the fortieth,
65/// and clang agrees. That is a `_BitInt(40)` here, and saying it that way is what makes the usual
66/// arithmetic conversions below give the right answer for a pair of them without knowing they
67/// came from bit-fields.
68///
69/// A field as wide as the type it was declared with is that type, since there is no precision to
70/// lose and `unsigned long long b:64` reading as a `_BitInt(64)` would be a different type for no
71/// reason.
72pub fn promote_bit_field(types: &mut Types, id: TypeId, width: u32, target: &TargetInfo) -> TypeId {
73 let id = value_type(types, id);
74 let (signed, declared) = match types.kind(id) {
75 TypeKind::Bool => (false, 1),
76 TypeKind::Int(kind) => (kind.is_signed(target.char_is_signed), int_width(kind, target)),
77 TypeKind::BitInt { signed, width } => (signed, width),
78 // An enumeration bit-field promotes through what it is represented in, and anything
79 // else is not something a bit-field may be declared with.
80 _ => return promote(types, id, target),
81 };
82 let int = int_width(IntKind::Int, target);
83 if width < int || (signed && width == int) {
84 return types.int(IntKind::Int);
85 }
86 if !signed && width == int {
87 return types.int(IntKind::UInt);
88 }
89 if width >= declared {
90 return promote(types, id, target);
91 }
92 types.bit_int(signed, width)
93}
94
95/// The usual arithmetic conversions, 6.3.1.8: the one type both operands are converted to.
96///
97/// [`None`] when either operand is not an arithmetic type, which is not a failure of this
98/// function but the shape of a diagnostic its caller is about to write.
99///
100/// The floating rules come first and the integer rules only run when neither side is floating,
101/// which is why `unsigned long long + float` is `float` and loses precision rather than being
102/// the other way round.
103pub fn usual_arithmetic(
104 types: &mut Types,
105 left: TypeId,
106 right: TypeId,
107 target: &TargetInfo,
108) -> Option<TypeId> {
109 let left = value_type(types, left);
110 let right = value_type(types, right);
111 if let Some(common) = floating(types, left, right, target) {
112 return Some(common);
113 }
114 let left = promote(types, left, target);
115 let right = promote(types, right, target);
116 if left == right {
117 // Not only a shortcut: it is also the answer for the types this function does not model
118 // as integers, which is every one of them once the two sides agree.
119 return integer_shape(types, left, target).map(|_| left);
120 }
121 let left = integer_shape(types, left, target)?;
122 let right = integer_shape(types, right, target)?;
123 Some(common_integer(types, left, right, target))
124}
125
126/// Whether one vector may be assigned to another that is not compatible with it.
127///
128/// GNU C is deliberately loose here, and it has to be, because the vector extension gives no way
129/// to spell a conversion: `(V)x` on two vectors reinterprets the bytes and there is no cast that
130/// means anything else, so a rule as strict as the one for records would leave a program with no
131/// way to write what it meant. gcc's rule, in `vector_types_convertible_p`, is that two vectors
132/// of the same total size convert when their lanes are both integers, or are both floating and
133/// the same width. The lane count may differ, so a sixteen lane vector of `short` may be assigned
134/// to an eight lane vector of `int`.
135///
136/// The place a program hits this without asking for it is a comparison. The mask a comparison
137/// answers with has signed lanes whatever the operands had, so `V x = (v > 0);` where `V` has
138/// unsigned lanes is this rule and nothing more exotic, and three of the torture cases are
139/// exactly that line.
140///
141/// gcc notes the first one it converts this way and suggests `-flax-vector-conversions`. Nothing
142/// is said here, because the note is about a flag that turns off a stricter check we do not make.
143#[must_use]
144pub fn vectors_convertible(types: &Types, a: TypeId, b: TypeId, target: &TargetInfo) -> bool {
145 if !is_vector(types, a) || !is_vector(types, b) {
146 return false;
147 }
148 let (Some(x), Some(y)) = (element(types, a), element(types, b)) else {
149 return false;
150 };
151 let sizes = |left, right| match (layout(types, left, target), layout(types, right, target)) {
152 (Ok(left), Ok(right)) => Some((left.size, right.size)),
153 _ => None,
154 };
155 let Some((whole, other)) = sizes(a, b) else {
156 return false;
157 };
158 if whole != other {
159 return false;
160 }
161 match (integer_info(types, x, target), integer_info(types, y, target)) {
162 (Some(_), Some(_)) => true,
163 (None, None) => sizes(x, y).is_some_and(|(left, right)| left == right),
164 _ => false,
165 }
166}
167
168/// The type a comparison of two vectors answers with, and [`None`] where `id` is not a vector.
169///
170/// GNU C says `a < b` over vectors is a vector of signed integers with the lane count the
171/// operands had and a lane as wide as theirs, holding all ones where the comparison held and
172/// zero where it did not. The width has to match rather than merely be an `int`, because the
173/// mask is written to be used: `(a < b) & c` reaches every bit of `c` only when the two line up
174/// lane for lane, and that is what the result of a vector comparison is for.
175///
176/// A vector of signed integers is its own mask type, which is what gcc answers and is worth
177/// keeping, since `v4si` comparing to `v4si` reading back as some other spelling of the same
178/// thing is a diagnostic nobody can act on. Anything else, an unsigned lane or a floating one,
179/// gets the signed integer type of that width.
180///
181/// [`None`] also where the target has no standard integer as wide as the lane, which is the
182/// eighty bit `long double` and nothing else.
183pub fn mask_of(types: &mut Types, id: TypeId, target: &TargetInfo) -> Option<TypeId> {
184 let elem = element(types, id)?;
185 let len = lanes(types, id)?;
186 let bits = match integer_info(types, elem, target) {
187 Some(info) if info.signed => {
188 let lane = types.unqualified(elem);
189 return Some(types.vector(lane, len));
190 }
191 Some(info) => info.width,
192 None => match types.kind(types.canonical(elem)) {
193 TypeKind::Float(kind) => float_width(kind, target),
194 _ => return None,
195 },
196 };
197 let standard = [
198 IntKind::SChar,
199 IntKind::Short,
200 IntKind::Int,
201 IntKind::Long,
202 IntKind::LongLong,
203 IntKind::Int128,
204 ];
205 let kind = standard.into_iter().find(|&kind| int_width(kind, target) == bits)?;
206 let lane = types.int(kind);
207 Some(types.vector(lane, len))
208}
209
210/// The type of a value of type `id`, which is `id` without the parts an lvalue conversion
211/// removes.
212fn value_type(types: &mut Types, id: TypeId) -> TypeId {
213 let id = types.canonical(id);
214 let id = match types.kind(id) {
215 TypeKind::Atomic(inner) => types.canonical(inner),
216 _ => id,
217 };
218 types.unqualified(id)
219}
220
221/// The promotion of a standard integer type of the given width.
222fn promoted_int(types: &mut Types, kind: IntKind, width: u32, target: &TargetInfo) -> TypeId {
223 if kind.rank() >= IntKind::Int.rank() {
224 return types.int(kind);
225 }
226 let int = int_width(IntKind::Int, target);
227 let signed = kind.is_signed(target.char_is_signed);
228 if width < int || (signed && width == int) {
229 return types.int(IntKind::Int);
230 }
231 types.int(IntKind::UInt)
232}
233
234/// The common type when either side is a floating type, and [`None`] when neither is.
235///
236/// The real type is the one with the higher rank, or the floating one when the other side is an
237/// integer, and the result is complex when either operand was. That last part is why
238/// `_Complex float + double` is `_Complex double`: the real types combine first and the
239/// complexity is carried across afterwards.
240fn floating(types: &mut Types, left: TypeId, right: TypeId, target: &TargetInfo) -> Option<TypeId> {
241 let left = float_part(types, left);
242 let right = float_part(types, right);
243 let (kind, complex) = match (left, right) {
244 (None, None) => return None,
245 (Some((kind, complex)), None) | (None, Some((kind, complex))) => (kind, complex),
246 (Some((a, a_complex)), Some((b, b_complex))) => {
247 let kind = if float_rank(a, target) >= float_rank(b, target) { a } else { b };
248 (kind, a_complex || b_complex)
249 }
250 };
251 Some(if complex { types.complex(kind) } else { types.float(kind) })
252}
253
254/// The conversion rank of a real floating type, as something two of which can be compared.
255///
256/// There is no ordering on the kinds themselves to use here, because since C23 the answer
257/// depends on the target: `long double` outranks `_Float64x` on x86-64, where both of them are
258/// the x87 format, and loses to it on Apple, where `long double` is a `double`. So the question
259/// is asked of the format instead. Precision first and then range, which never disagree among
260/// the binary formats, and [`FloatKind::tie_break`] settles two types that are the same format,
261/// which is what makes `double + _Float64` a `_Float64`.
262fn float_rank(kind: FloatKind, target: &TargetInfo) -> (u32, i32, u8) {
263 let format = float_format(kind, target);
264 (format.precision(), format.max_exponent(), kind.tie_break())
265}
266
267/// The real floating type inside `id`, and whether it was complex.
268fn float_part(types: &Types, id: TypeId) -> Option<(FloatKind, bool)> {
269 match types.kind(id) {
270 TypeKind::Float(kind) => Some((kind, false)),
271 TypeKind::Complex(kind) => Some((kind, true)),
272 _ => None,
273 }
274}
275
276/// What an integer type is, once it no longer matters how it was spelled.
277#[derive(Clone, Copy)]
278struct IntShape {
279 signed: bool,
280 width: u32,
281 /// The standard type it is, and [`None`] for a `_BitInt`.
282 standard: Option<IntKind>,
283}
284
285impl IntShape {
286 /// The integer conversion rank, as something two of which can be compared.
287 ///
288 /// Width first, which is what makes a `_BitInt(40)` outrank an `int` and lose to a `long`.
289 /// A standard type outranks a `_BitInt` of the same width, which is C23 6.3.1.1p1 and is
290 /// why `_BitInt(32) + int` is `int`. The standard rank breaks the last tie, which is the
291 /// one that matters on every 64-bit target: `long` and `long long` are both sixty four bits
292 /// and `long long` outranks `long`.
293 fn rank(self) -> (u32, u8, u8) {
294 match self.standard {
295 Some(kind) => (self.width, 1, kind.rank()),
296 None => (self.width, 0, 0),
297 }
298 }
299
300 /// Whether every value of `other` is a value of this type.
301 fn covers(self, other: IntShape) -> bool {
302 if self.signed == other.signed {
303 return self.width >= other.width;
304 }
305 // A signed type loses a bit to the sign, so it takes a strictly wider one to hold every
306 // value of an unsigned type. That is what makes `unsigned int + long` a `long` on
307 // Linux and an `unsigned long` on Windows, where `long` is only thirty two bits.
308 self.signed && self.width > other.width
309 }
310}
311
312/// The shape of an integer type, and [`None`] when `id` is not one.
313fn integer_shape(types: &Types, id: TypeId, target: &TargetInfo) -> Option<IntShape> {
314 match types.kind(id) {
315 TypeKind::Int(kind) => Some(IntShape {
316 signed: kind.is_signed(target.char_is_signed),
317 width: int_width(kind, target),
318 standard: Some(kind),
319 }),
320 TypeKind::BitInt { signed, width } => Some(IntShape { signed, width, standard: None }),
321 _ => None,
322 }
323}
324
325/// The common type of two promoted integer types.
326fn common_integer(
327 types: &mut Types,
328 left: IntShape,
329 right: IntShape,
330 target: &TargetInfo,
331) -> TypeId {
332 let (higher, lower) = if left.rank() >= right.rank() { (left, right) } else { (right, left) };
333 if higher.signed == lower.signed || !higher.signed || higher.covers(lower) {
334 // Same signedness, or the higher ranked one is the unsigned one, or it is the signed
335 // one and wide enough to hold every value the other side had.
336 return build(types, higher, target);
337 }
338 // The signed type wins on rank and loses on range, so neither operand's type will do and
339 // the answer is the unsigned type of the same width. This is the arm that turns
340 // `long + unsigned long` into `unsigned long`, and it is the one a program is surprised by.
341 build(types, IntShape { signed: false, ..higher }, target)
342}
343
344/// The type an [`IntShape`] describes.
345fn build(types: &mut Types, shape: IntShape, target: &TargetInfo) -> TypeId {
346 match shape.standard {
347 Some(kind) if kind.is_signed(target.char_is_signed) == shape.signed => types.int(kind),
348 Some(kind) => types.int(kind.flip_sign()),
349 None => types.bit_int(shape.signed, shape.width),
350 }
351}