Skip to content

Commit 20ed805

Browse files
authored
Rollup merge of #118688 - celinval:smir-rvalue-ty, r=compiler-errors
Add method to get type of an Rvalue in StableMIR Provide a method to StableMIR users to retrieve the type of an Rvalue operation. There were two possible implementation: 1. Create the logic inside stable_mir to process the type according to the Rvalue semantics, which duplicates the logic of `rustc_middle::mir::Rvalue::ty()`. 2. Implement the Rvalue translation from StableMIR back to internal representation, invoke the `rustc_middle::mir::Rvalue::ty()`, and translate the return value to StableMIR. I chose the first one for now since the duplication was fairly small, and the option 2 would require way more work to translate everything back to rustc internal representation. If we eventually add those translations, we could easily swap to the option 2. ```@compiler-errors``` / ```@ouz-a``` Please let me know if you have any strong opinion here. r? ```@compiler-errors```
2 parents b204303 + 4616b9f commit 20ed805

File tree

5 files changed

+202
-5
lines changed

5 files changed

+202
-5
lines changed

compiler/rustc_smir/src/rustc_smir/context.rs

+16-2
Original file line numberDiff line numberDiff line change
@@ -250,6 +250,13 @@ impl<'tcx> Context for TablesWrapper<'tcx> {
250250
tables.tcx.mk_ty_from_kind(internal_kind).stable(&mut *tables)
251251
}
252252

253+
#[allow(rustc::usage_of_qualified_ty)]
254+
fn new_box_ty(&self, ty: stable_mir::ty::Ty) -> stable_mir::ty::Ty {
255+
let mut tables = self.0.borrow_mut();
256+
let inner = ty.internal(&mut *tables);
257+
ty::Ty::new_box(tables.tcx, inner).stable(&mut *tables)
258+
}
259+
253260
fn def_ty(&self, item: stable_mir::DefId) -> stable_mir::ty::Ty {
254261
let mut tables = self.0.borrow_mut();
255262
tables.tcx.type_of(item.internal(&mut *tables)).instantiate_identity().stable(&mut *tables)
@@ -276,6 +283,13 @@ impl<'tcx> Context for TablesWrapper<'tcx> {
276283
tables.types[ty].kind().stable(&mut *tables)
277284
}
278285

286+
fn rigid_ty_discriminant_ty(&self, ty: &RigidTy) -> stable_mir::ty::Ty {
287+
let mut tables = self.0.borrow_mut();
288+
let internal_kind = ty.internal(&mut *tables);
289+
let internal_ty = tables.tcx.mk_ty_from_kind(internal_kind);
290+
internal_ty.discriminant_ty(tables.tcx).stable(&mut *tables)
291+
}
292+
279293
fn instance_body(&self, def: InstanceDef) -> Option<Body> {
280294
let mut tables = self.0.borrow_mut();
281295
let instance = tables.instances[def];
@@ -308,9 +322,9 @@ impl<'tcx> Context for TablesWrapper<'tcx> {
308322
matches!(instance.def, ty::InstanceDef::DropGlue(_, None))
309323
}
310324

311-
fn mono_instance(&self, item: stable_mir::CrateItem) -> stable_mir::mir::mono::Instance {
325+
fn mono_instance(&self, def_id: stable_mir::DefId) -> stable_mir::mir::mono::Instance {
312326
let mut tables = self.0.borrow_mut();
313-
let def_id = tables[item.0];
327+
let def_id = tables[def_id];
314328
Instance::mono(tables.tcx, def_id).stable(&mut *tables)
315329
}
316330

compiler/stable_mir/src/compiler_interface.rs

+7-1
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,9 @@ pub trait Context {
8787
/// Create a new type from the given kind.
8888
fn new_rigid_ty(&self, kind: RigidTy) -> Ty;
8989

90+
/// Create a new box type, `Box<T>`, for the given inner type `T`.
91+
fn new_box_ty(&self, ty: Ty) -> Ty;
92+
9093
/// Returns the type of given crate item.
9194
fn def_ty(&self, item: DefId) -> Ty;
9295

@@ -102,6 +105,9 @@ pub trait Context {
102105
/// Obtain the representation of a type.
103106
fn ty_kind(&self, ty: Ty) -> TyKind;
104107

108+
// Get the discriminant Ty for this Ty if there's one.
109+
fn rigid_ty_discriminant_ty(&self, ty: &RigidTy) -> Ty;
110+
105111
/// Get the body of an Instance which is already monomorphized.
106112
fn instance_body(&self, instance: InstanceDef) -> Option<Body>;
107113

@@ -119,7 +125,7 @@ pub trait Context {
119125

120126
/// Convert a non-generic crate item into an instance.
121127
/// This function will panic if the item is generic.
122-
fn mono_instance(&self, item: CrateItem) -> Instance;
128+
fn mono_instance(&self, def_id: DefId) -> Instance;
123129

124130
/// Item requires monomorphization.
125131
fn requires_monomorphization(&self, def_id: DefId) -> bool;

compiler/stable_mir/src/mir/body.rs

+100
Original file line numberDiff line numberDiff line change
@@ -274,6 +274,38 @@ pub enum BinOp {
274274
Offset,
275275
}
276276

277+
impl BinOp {
278+
/// Return the type of this operation for the given input Ty.
279+
/// This function does not perform type checking, and it currently doesn't handle SIMD.
280+
pub fn ty(&self, lhs_ty: Ty, rhs_ty: Ty) -> Ty {
281+
assert!(lhs_ty.kind().is_primitive());
282+
assert!(rhs_ty.kind().is_primitive());
283+
match self {
284+
BinOp::Add
285+
| BinOp::AddUnchecked
286+
| BinOp::Sub
287+
| BinOp::SubUnchecked
288+
| BinOp::Mul
289+
| BinOp::MulUnchecked
290+
| BinOp::Div
291+
| BinOp::Rem
292+
| BinOp::BitXor
293+
| BinOp::BitAnd
294+
| BinOp::BitOr => {
295+
assert_eq!(lhs_ty, rhs_ty);
296+
lhs_ty
297+
}
298+
BinOp::Shl | BinOp::ShlUnchecked | BinOp::Shr | BinOp::ShrUnchecked | BinOp::Offset => {
299+
lhs_ty
300+
}
301+
BinOp::Eq | BinOp::Lt | BinOp::Le | BinOp::Ne | BinOp::Ge | BinOp::Gt => {
302+
assert_eq!(lhs_ty, rhs_ty);
303+
Ty::bool_ty()
304+
}
305+
}
306+
}
307+
}
308+
277309
#[derive(Clone, Debug, Eq, PartialEq)]
278310
pub enum UnOp {
279311
Not,
@@ -475,6 +507,63 @@ pub enum Rvalue {
475507
Use(Operand),
476508
}
477509

510+
impl Rvalue {
511+
pub fn ty(&self, locals: &[LocalDecl]) -> Result<Ty, Error> {
512+
match self {
513+
Rvalue::Use(operand) => operand.ty(locals),
514+
Rvalue::Repeat(operand, count) => {
515+
Ok(Ty::new_array_with_const_len(operand.ty(locals)?, count.clone()))
516+
}
517+
Rvalue::ThreadLocalRef(did) => Ok(did.ty()),
518+
Rvalue::Ref(reg, bk, place) => {
519+
let place_ty = place.ty(locals)?;
520+
Ok(Ty::new_ref(reg.clone(), place_ty, bk.to_mutable_lossy()))
521+
}
522+
Rvalue::AddressOf(mutability, place) => {
523+
let place_ty = place.ty(locals)?;
524+
Ok(Ty::new_ptr(place_ty, *mutability))
525+
}
526+
Rvalue::Len(..) => Ok(Ty::usize_ty()),
527+
Rvalue::Cast(.., ty) => Ok(*ty),
528+
Rvalue::BinaryOp(op, lhs, rhs) => {
529+
let lhs_ty = lhs.ty(locals)?;
530+
let rhs_ty = rhs.ty(locals)?;
531+
Ok(op.ty(lhs_ty, rhs_ty))
532+
}
533+
Rvalue::CheckedBinaryOp(op, lhs, rhs) => {
534+
let lhs_ty = lhs.ty(locals)?;
535+
let rhs_ty = rhs.ty(locals)?;
536+
let ty = op.ty(lhs_ty, rhs_ty);
537+
Ok(Ty::new_tuple(&[ty, Ty::bool_ty()]))
538+
}
539+
Rvalue::UnaryOp(UnOp::Not | UnOp::Neg, operand) => operand.ty(locals),
540+
Rvalue::Discriminant(place) => {
541+
let place_ty = place.ty(locals)?;
542+
place_ty
543+
.kind()
544+
.discriminant_ty()
545+
.ok_or_else(|| error!("Expected a `RigidTy` but found: {place_ty:?}"))
546+
}
547+
Rvalue::NullaryOp(NullOp::SizeOf | NullOp::AlignOf | NullOp::OffsetOf(..), _) => {
548+
Ok(Ty::usize_ty())
549+
}
550+
Rvalue::Aggregate(ak, ops) => match *ak {
551+
AggregateKind::Array(ty) => Ty::try_new_array(ty, ops.len() as u64),
552+
AggregateKind::Tuple => Ok(Ty::new_tuple(
553+
&ops.iter().map(|op| op.ty(locals)).collect::<Result<Vec<_>, _>>()?,
554+
)),
555+
AggregateKind::Adt(def, _, ref args, _, _) => Ok(def.ty_with_args(args)),
556+
AggregateKind::Closure(def, ref args) => Ok(Ty::new_closure(def, args.clone())),
557+
AggregateKind::Coroutine(def, ref args, mov) => {
558+
Ok(Ty::new_coroutine(def, args.clone(), mov))
559+
}
560+
},
561+
Rvalue::ShallowInitBox(_, ty) => Ok(Ty::new_box(*ty)),
562+
Rvalue::CopyForDeref(place) => place.ty(locals),
563+
}
564+
}
565+
}
566+
478567
#[derive(Clone, Debug, Eq, PartialEq)]
479568
pub enum AggregateKind {
480569
Array(Ty),
@@ -725,6 +814,17 @@ pub enum BorrowKind {
725814
},
726815
}
727816

817+
impl BorrowKind {
818+
pub fn to_mutable_lossy(self) -> Mutability {
819+
match self {
820+
BorrowKind::Mut { .. } => Mutability::Mut,
821+
BorrowKind::Shared => Mutability::Not,
822+
// FIXME: There's no type corresponding to a shallow borrow, so use `&` as an approximation.
823+
BorrowKind::Fake => Mutability::Not,
824+
}
825+
}
826+
}
827+
728828
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
729829
pub enum MutBorrowKind {
730830
Default,

compiler/stable_mir/src/mir/mono.rs

+18-2
Original file line numberDiff line numberDiff line change
@@ -150,8 +150,9 @@ impl TryFrom<CrateItem> for Instance {
150150

151151
fn try_from(item: CrateItem) -> Result<Self, Self::Error> {
152152
with(|context| {
153-
if !context.requires_monomorphization(item.0) {
154-
Ok(context.mono_instance(item))
153+
let def_id = item.def_id();
154+
if !context.requires_monomorphization(def_id) {
155+
Ok(context.mono_instance(def_id))
155156
} else {
156157
Err(Error::new("Item requires monomorphization".to_string()))
157158
}
@@ -219,6 +220,21 @@ impl TryFrom<CrateItem> for StaticDef {
219220
}
220221
}
221222

223+
impl TryFrom<Instance> for StaticDef {
224+
type Error = crate::Error;
225+
226+
fn try_from(value: Instance) -> Result<Self, Self::Error> {
227+
StaticDef::try_from(CrateItem::try_from(value)?)
228+
}
229+
}
230+
231+
impl From<StaticDef> for Instance {
232+
fn from(value: StaticDef) -> Self {
233+
// A static definition should always be convertible to an instance.
234+
with(|cx| cx.mono_instance(value.def_id()))
235+
}
236+
}
237+
222238
impl StaticDef {
223239
/// Return the type of this static definition.
224240
pub fn ty(&self) -> Ty {

compiler/stable_mir/src/ty.rs

+61
Original file line numberDiff line numberDiff line change
@@ -31,15 +31,50 @@ impl Ty {
3131
Ok(Ty::from_rigid_kind(RigidTy::Array(elem_ty, Const::try_from_target_usize(size)?)))
3232
}
3333

34+
/// Create a new array type from Const length.
35+
pub fn new_array_with_const_len(elem_ty: Ty, len: Const) -> Ty {
36+
Ty::from_rigid_kind(RigidTy::Array(elem_ty, len))
37+
}
38+
3439
/// Create a new pointer type.
3540
pub fn new_ptr(pointee_ty: Ty, mutability: Mutability) -> Ty {
3641
Ty::from_rigid_kind(RigidTy::RawPtr(pointee_ty, mutability))
3742
}
3843

44+
/// Create a new reference type.
45+
pub fn new_ref(reg: Region, pointee_ty: Ty, mutability: Mutability) -> Ty {
46+
Ty::from_rigid_kind(RigidTy::Ref(reg, pointee_ty, mutability))
47+
}
48+
49+
/// Create a new pointer type.
50+
pub fn new_tuple(tys: &[Ty]) -> Ty {
51+
Ty::from_rigid_kind(RigidTy::Tuple(Vec::from(tys)))
52+
}
53+
54+
/// Create a new closure type.
55+
pub fn new_closure(def: ClosureDef, args: GenericArgs) -> Ty {
56+
Ty::from_rigid_kind(RigidTy::Closure(def, args))
57+
}
58+
59+
/// Create a new coroutine type.
60+
pub fn new_coroutine(def: CoroutineDef, args: GenericArgs, mov: Movability) -> Ty {
61+
Ty::from_rigid_kind(RigidTy::Coroutine(def, args, mov))
62+
}
63+
64+
/// Create a new box type that represents `Box<T>`, for the given inner type `T`.
65+
pub fn new_box(inner_ty: Ty) -> Ty {
66+
with(|cx| cx.new_box_ty(inner_ty))
67+
}
68+
3969
/// Create a type representing `usize`.
4070
pub fn usize_ty() -> Ty {
4171
Ty::from_rigid_kind(RigidTy::Uint(UintTy::Usize))
4272
}
73+
74+
/// Create a type representing `bool`.
75+
pub fn bool_ty() -> Ty {
76+
Ty::from_rigid_kind(RigidTy::Bool)
77+
}
4378
}
4479

4580
impl Ty {
@@ -209,6 +244,19 @@ impl TyKind {
209244
matches!(self, TyKind::RigidTy(RigidTy::FnPtr(..)))
210245
}
211246

247+
pub fn is_primitive(&self) -> bool {
248+
matches!(
249+
self,
250+
TyKind::RigidTy(
251+
RigidTy::Bool
252+
| RigidTy::Char
253+
| RigidTy::Int(_)
254+
| RigidTy::Uint(_)
255+
| RigidTy::Float(_)
256+
)
257+
)
258+
}
259+
212260
pub fn trait_principal(&self) -> Option<Binder<ExistentialTraitRef>> {
213261
if let TyKind::RigidTy(RigidTy::Dynamic(predicates, _, _)) = self {
214262
if let Some(Binder { value: ExistentialPredicate::Trait(trait_ref), bound_vars }) =
@@ -251,13 +299,19 @@ impl TyKind {
251299
}
252300

253301
/// Get the function signature for function like types (Fn, FnPtr, Closure, Coroutine)
302+
/// FIXME(closure)
254303
pub fn fn_sig(&self) -> Option<PolyFnSig> {
255304
match self {
256305
TyKind::RigidTy(RigidTy::FnDef(def, args)) => Some(with(|cx| cx.fn_sig(*def, args))),
257306
TyKind::RigidTy(RigidTy::FnPtr(sig)) => Some(sig.clone()),
258307
_ => None,
259308
}
260309
}
310+
311+
/// Get the discriminant type for this type.
312+
pub fn discriminant_ty(&self) -> Option<Ty> {
313+
self.rigid().map(|ty| with(|cx| cx.rigid_ty_discriminant_ty(ty)))
314+
}
261315
}
262316

263317
pub struct TypeAndMut {
@@ -289,6 +343,13 @@ pub enum RigidTy {
289343
CoroutineWitness(CoroutineWitnessDef, GenericArgs),
290344
}
291345

346+
impl RigidTy {
347+
/// Get the discriminant type for this type.
348+
pub fn discriminant_ty(&self) -> Ty {
349+
with(|cx| cx.rigid_ty_discriminant_ty(self))
350+
}
351+
}
352+
292353
impl From<RigidTy> for TyKind {
293354
fn from(value: RigidTy) -> Self {
294355
TyKind::RigidTy(value)

0 commit comments

Comments
 (0)