Skip to content

Commit f4befa6

Browse files
committed
Auto merge of #30890 - nagisa:mir-tuple-adts, r=nikomatsakis
This PR changes translation of tuple-like ADTs from being calls to being proper aggregates. This change is done in hope to make code generation better. Namely, now we can avoid: 1. Call overhead; 2. Generating landingpads in presence of cleanups (we know for sure constructing ADTs can’t panic); 3. And probably much more, gaining better MIR introspectablilty. Along with that a few serious deficiencies with translation of ADTs and switches have been fixed as well (commits 2 and 3). r? @nikomatsakis cc @tsion
2 parents dd51c3a + 7d6da8e commit f4befa6

File tree

5 files changed

+152
-22
lines changed

5 files changed

+152
-22
lines changed

src/librustc_mir/hair/cx/expr.rs

Lines changed: 40 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,6 @@ impl<'tcx> Mirror<'tcx> for &'tcx hir::Expr {
5353
// Find the actual method implementation being called and
5454
// build the appropriate UFCS call expression with the
5555
// callee-object as self parameter.
56-
5756
let method = method_callee(cx, self, ty::MethodCall::expr(self.id));
5857
let mut argrefs = vec![fun.to_ref()];
5958
argrefs.extend(args.iter().map(|a| a.to_ref()));
@@ -64,12 +63,40 @@ impl<'tcx> Mirror<'tcx> for &'tcx hir::Expr {
6463
args: argrefs,
6564
}
6665
} else {
67-
ExprKind::Call {
68-
ty: &cx.tcx.node_id_to_type(fun.id),
69-
fun: fun.to_ref(),
70-
args: args.to_ref(),
66+
let adt_data = if let hir::ExprPath(..) = fun.node {
67+
// Tuple-like ADTs are represented as ExprCall. We convert them here.
68+
expr_ty.ty_adt_def().and_then(|adt_def|{
69+
match cx.tcx.def_map.borrow()[&fun.id].full_def() {
70+
def::DefVariant(_, variant_id, false) => {
71+
Some((adt_def, adt_def.variant_index_with_id(variant_id)))
72+
},
73+
def::DefStruct(_) => {
74+
Some((adt_def, 0))
75+
},
76+
_ => None
77+
}
78+
})
79+
} else { None };
80+
if let Some((adt_def, index)) = adt_data {
81+
let substs = cx.tcx.mk_substs(cx.tcx.node_id_item_substs(fun.id).substs);
82+
let field_refs = args.iter().enumerate().map(|(idx, e)| FieldExprRef {
83+
name: Field::new(idx),
84+
expr: e.to_ref()
85+
}).collect();
86+
ExprKind::Adt {
87+
adt_def: adt_def,
88+
substs: substs,
89+
variant_index: index,
90+
fields: field_refs,
91+
base: None
92+
}
93+
} else {
94+
ExprKind::Call {
95+
ty: cx.tcx.node_id_to_type(fun.id),
96+
fun: fun.to_ref(),
97+
args: args.to_ref(),
98+
}
7199
}
72-
73100
}
74101
}
75102

@@ -549,10 +576,11 @@ fn convert_path_expr<'a, 'tcx: 'a>(cx: &mut Cx<'a, 'tcx>, expr: &'tcx hir::Expr)
549576
def::DefFn(def_id, _) => (def_id, ItemKind::Function),
550577
def::DefMethod(def_id) => (def_id, ItemKind::Method),
551578
def::DefStruct(def_id) => match cx.tcx.node_id_to_type(expr.id).sty {
552-
// A tuple-struct constructor.
579+
// A tuple-struct constructor. Should only be reached if not called in the same
580+
// expression.
553581
ty::TyBareFn(..) => (def_id, ItemKind::Function),
554-
// This is a special case: a unit struct which is used as a value. We return a
555-
// completely different ExprKind here to account for this special case.
582+
// A unit struct which is used as a value. We return a completely different ExprKind
583+
// here to account for this special case.
556584
ty::TyStruct(adt_def, substs) => return ExprKind::Adt {
557585
adt_def: adt_def,
558586
variant_index: 0,
@@ -563,7 +591,8 @@ fn convert_path_expr<'a, 'tcx: 'a>(cx: &mut Cx<'a, 'tcx>, expr: &'tcx hir::Expr)
563591
ref sty => panic!("unexpected sty: {:?}", sty)
564592
},
565593
def::DefVariant(enum_id, variant_id, false) => match cx.tcx.node_id_to_type(expr.id).sty {
566-
// A variant constructor.
594+
// A variant constructor. Should only be reached if not called in the same
595+
// expression.
567596
ty::TyBareFn(..) => (variant_id, ItemKind::Function),
568597
// A unit variant, similar special case to the struct case above.
569598
ty::TyEnum(adt_def, substs) => {
@@ -900,6 +929,7 @@ fn loop_label<'a, 'tcx: 'a>(cx: &mut Cx<'a, 'tcx>, expr: &'tcx hir::Expr) -> Cod
900929
}
901930
}
902931

932+
/// Converts a list of named fields (i.e. for struct-like struct/enum ADTs) into FieldExprRef.
903933
fn field_refs<'tcx>(variant: VariantDef<'tcx>,
904934
fields: &'tcx [hir::Field])
905935
-> Vec<FieldExprRef<'tcx>>

src/librustc_trans/trans/mir/block.rs

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -48,11 +48,10 @@ impl<'bcx, 'tcx> MirContext<'bcx, 'tcx> {
4848
}
4949

5050
mir::Terminator::Switch { ref discr, ref adt_def, ref targets } => {
51-
let adt_ty = bcx.tcx().lookup_item_type(adt_def.did).ty;
52-
let represented_ty = adt::represent_type(bcx.ccx(), adt_ty);
53-
5451
let discr_lvalue = self.trans_lvalue(bcx, discr);
55-
let discr = adt::trans_get_discr(bcx, &represented_ty, discr_lvalue.llval, None);
52+
let ty = discr_lvalue.ty.to_ty(bcx.tcx());
53+
let repr = adt::represent_type(bcx.ccx(), ty);
54+
let discr = adt::trans_get_discr(bcx, &repr, discr_lvalue.llval, None);
5655

5756
// The else branch of the Switch can't be hit, so branch to an unreachable
5857
// instruction so LLVM knows that
@@ -61,7 +60,7 @@ impl<'bcx, 'tcx> MirContext<'bcx, 'tcx> {
6160
let switch = build::Switch(bcx, discr, unreachable_blk.llbb, targets.len());
6261
assert_eq!(adt_def.variants.len(), targets.len());
6362
for (adt_variant, target) in adt_def.variants.iter().zip(targets) {
64-
let llval = adt::trans_case(bcx, &*represented_ty, adt_variant.disr_val);
63+
let llval = adt::trans_case(bcx, &*repr, adt_variant.disr_val);
6564
let llbb = self.llblock(*target);
6665

6766
build::AddCase(switch, llval, llbb)

src/librustc_trans/trans/mir/rvalue.rs

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -98,13 +98,19 @@ impl<'bcx, 'tcx> MirContext<'bcx, 'tcx> {
9898

9999
mir::Rvalue::Aggregate(ref kind, ref operands) => {
100100
match *kind {
101-
// Unit struct or variant; both are translated very differently compared to any
102-
// other aggregate
103-
mir::AggregateKind::Adt(adt_def, index, _)
104-
if adt_def.variants[index].kind() == ty::VariantKind::Unit => {
101+
mir::AggregateKind::Adt(adt_def, index, _) => {
105102
let repr = adt::represent_type(bcx.ccx(), dest.ty.to_ty(bcx.tcx()));
106103
let disr = adt_def.variants[index].disr_val;
107104
adt::trans_set_discr(bcx, &*repr, dest.llval, disr);
105+
for (i, operand) in operands.iter().enumerate() {
106+
let op = self.trans_operand(bcx, operand);
107+
// Do not generate stores and GEPis for zero-sized fields.
108+
if !common::type_is_zero_size(bcx.ccx(), op.ty) {
109+
let val = adt::MaybeSizedValue::sized(dest.llval);
110+
let lldest_i = adt::trans_field_ptr(bcx, &*repr, val, disr, i);
111+
self.store_operand(bcx, lldest_i, op);
112+
}
113+
}
108114
},
109115
_ => {
110116
for (i, operand) in operands.iter().enumerate() {
Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2+
// file at the top-level directory of this distribution and at
3+
// http://rust-lang.org/COPYRIGHT.
4+
//
5+
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6+
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7+
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8+
// option. This file may not be copied, modified, or distributed
9+
// except according to those terms.
10+
11+
#![feature(rustc_attrs)]
12+
13+
#[repr(C, u32)]
14+
enum CEnum {
15+
Hello = 30,
16+
World = 60
17+
}
18+
19+
#[rustc_mir]
20+
fn test1(c: CEnum) -> i32 {
21+
let c2 = CEnum::Hello;
22+
match (c, c2) {
23+
(CEnum::Hello, CEnum::Hello) => 42,
24+
(CEnum::World, CEnum::Hello) => 0,
25+
_ => 1
26+
}
27+
}
28+
29+
#[repr(packed)]
30+
#[derive(PartialEq, Debug)]
31+
struct Pakd {
32+
a: u64,
33+
b: u32,
34+
c: u16,
35+
d: u8,
36+
e: ()
37+
}
38+
39+
impl Drop for Pakd {
40+
fn drop(&mut self) {}
41+
}
42+
43+
#[rustc_mir]
44+
fn test2() -> Pakd {
45+
Pakd { a: 42, b: 42, c: 42, d: 42, e: () }
46+
}
47+
48+
#[derive(PartialEq, Debug)]
49+
struct TupleLike(u64, u32);
50+
51+
#[rustc_mir]
52+
fn test3() -> TupleLike {
53+
TupleLike(42, 42)
54+
}
55+
56+
#[rustc_mir]
57+
fn test4(x: fn(u64, u32) -> TupleLike) -> (TupleLike, TupleLike) {
58+
let y = TupleLike;
59+
(x(42, 84), y(42, 84))
60+
}
61+
62+
#[rustc_mir]
63+
fn test5(x: fn(u32) -> Option<u32>) -> (Option<u32>, Option<u32>) {
64+
let y = Some;
65+
(x(42), y(42))
66+
}
67+
68+
fn main() {
69+
assert_eq!(test1(CEnum::Hello), 42);
70+
assert_eq!(test1(CEnum::World), 0);
71+
assert_eq!(test2(), Pakd { a: 42, b: 42, c: 42, d: 42, e: () });
72+
assert_eq!(test3(), TupleLike(42, 42));
73+
let t4 = test4(TupleLike);
74+
assert_eq!(t4.0, t4.1);
75+
let t5 = test5(Some);
76+
assert_eq!(t5.0, t5.1);
77+
}

src/test/run-pass/mir_build_match_comparisons.rs

Lines changed: 21 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111
#![feature(rustc_attrs)]
1212

1313
#[rustc_mir]
14-
pub fn test1(x: i8) -> i32 {
14+
fn test1(x: i8) -> i32 {
1515
match x {
1616
1...10 => 0,
1717
_ => 1,
@@ -22,21 +22,36 @@ const U: Option<i8> = Some(10);
2222
const S: &'static str = "hello";
2323

2424
#[rustc_mir]
25-
pub fn test2(x: i8) -> i32 {
25+
fn test2(x: i8) -> i32 {
2626
match Some(x) {
2727
U => 0,
2828
_ => 1,
2929
}
3030
}
3131

3232
#[rustc_mir]
33-
pub fn test3(x: &'static str) -> i32 {
33+
fn test3(x: &'static str) -> i32 {
3434
match x {
3535
S => 0,
3636
_ => 1,
3737
}
3838
}
3939

40+
enum Opt<T> {
41+
Some { v: T },
42+
None
43+
}
44+
45+
#[rustc_mir]
46+
fn test4(x: u64) -> i32 {
47+
let opt = Opt::Some{ v: x };
48+
match opt {
49+
Opt::Some { v: 10 } => 0,
50+
_ => 1,
51+
}
52+
}
53+
54+
4055
fn main() {
4156
assert_eq!(test1(0), 1);
4257
assert_eq!(test1(1), 0);
@@ -52,4 +67,7 @@ fn main() {
5267
assert_eq!(test3("hello"), 0);
5368
assert_eq!(test3(""), 1);
5469
assert_eq!(test3("world"), 1);
70+
assert_eq!(test4(10), 0);
71+
assert_eq!(test4(0), 1);
72+
assert_eq!(test4(20), 1);
5573
}

0 commit comments

Comments
 (0)