1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
use back::abi;
use driver::session;
use lib::llvm::ValueRef;
use lib::llvm::llvm;
use metadata::csearch;
use middle::def;
use middle::subst;
use middle::subst::{Subst, VecPerParamSpace};
use middle::trans::base;
use middle::trans::base::*;
use middle::trans::build::*;
use middle::trans::callee;
use middle::trans::cleanup;
use middle::trans::cleanup::CleanupMethods;
use middle::trans::common;
use middle::trans::common::*;
use middle::trans::datum::*;
use middle::trans::datum::Datum;
use middle::trans::expr;
use middle::trans::glue;
use middle::trans::inline;
use middle::trans::meth;
use middle::trans::monomorphize;
use middle::trans::type_of;
use middle::trans::foreign;
use middle::ty;
use middle::typeck;
use middle::typeck::coherence::make_substs_for_receiver_types;
use middle::typeck::MethodCall;
use util::ppaux::Repr;
use middle::trans::type_::Type;
use syntax::ast;
use synabi = syntax::abi;
use syntax::ast_map;
use std::gc::Gc;
pub struct MethodData {
pub llfn: ValueRef,
pub llself: ValueRef,
}
pub enum CalleeData {
Closure(Datum<Lvalue>),Fn(ValueRef),
TraitMethod(MethodData)
}
pub struct Callee<'a> {
pub bcx: &'a Block<'a>,
pub data: CalleeData
}
fn trans<'a>(bcx: &'a Block<'a>, expr: &ast::Expr) -> Callee<'a> {
let _icx = push_ctxt("trans_callee");
debug!("callee::trans(expr={})", expr.repr(bcx.tcx()));match expr.node {
ast::ExprPath(_) => {
return trans_def(bcx, bcx.def(expr.id), expr);
}
_ => {}
}return datum_callee(bcx, expr);
fn datum_callee<'a>(bcx: &'a Block<'a>, expr: &ast::Expr) -> Callee<'a> {
let DatumBlock {bcx: mut bcx, datum} = expr::trans(bcx, expr);
match ty::get(datum.ty).sty {
ty::ty_bare_fn(..) => {
let llval = datum.to_llscalarish(bcx);
return Callee {bcx: bcx, data: Fn(llval)};
}
ty::ty_closure(..) => {
let datum = unpack_datum!(
bcx, datum.to_lvalue_datum(bcx, "callee", expr.id));
return Callee {bcx: bcx, data: Closure(datum)};
}
_ => {
bcx.tcx().sess.span_bug(
expr.span,
format!("type of callee is neither bare-fn nor closure: \
{}",
bcx.ty_to_str(datum.ty)).as_slice());
}
}
}
fn fn_callee<'a>(bcx: &'a Block<'a>, llfn: ValueRef) -> Callee<'a> {
return Callee {bcx: bcx, data: Fn(llfn)};
}
fn trans_def<'a>(bcx: &'a Block<'a>, def: def::Def, ref_expr: &ast::Expr)
-> Callee<'a> {
match def {
def::DefFn(did, _) |
def::DefStaticMethod(did, def::FromImpl(_), _) => {
fn_callee(bcx, trans_fn_ref(bcx, did, ExprId(ref_expr.id)))
}
def::DefStaticMethod(impl_did,
def::FromTrait(trait_did),
_) => {
fn_callee(bcx, meth::trans_static_method_callee(bcx, impl_did,
trait_did,
ref_expr.id))
}
def::DefVariant(tid, vid, _) => {assert!(ty::enum_variant_with_id(bcx.tcx(),
tid,
vid).args.len() > 0u);
fn_callee(bcx, trans_fn_ref(bcx, vid, ExprId(ref_expr.id)))
}
def::DefStruct(def_id) => {
fn_callee(bcx, trans_fn_ref(bcx, def_id, ExprId(ref_expr.id)))
}
def::DefStatic(..) |
def::DefArg(..) |
def::DefLocal(..) |
def::DefBinding(..) |
def::DefUpvar(..) => {
datum_callee(bcx, ref_expr)
}
def::DefMod(..) | def::DefForeignMod(..) | def::DefTrait(..) |
def::DefTy(..) | def::DefPrimTy(..) |
def::DefUse(..) | def::DefTyParamBinder(..) |
def::DefRegion(..) | def::DefLabel(..) | def::DefTyParam(..) |
def::DefSelfTy(..) | def::DefMethod(..) => {
bcx.tcx().sess.span_bug(
ref_expr.span,
format!("cannot translate def {:?} \
to a callable thing!", def).as_slice());
}
}
}
}
pub fn trans_fn_ref(bcx: &Block, def_id: ast::DefId, node: ExprOrMethodCall) -> ValueRef {
let _icx = push_ctxt("trans_fn_ref");
let substs = node_id_substs(bcx, node);
let vtable_key = match node {
ExprId(id) => MethodCall::expr(id),
MethodCall(method_call) => method_call
};
let vtables = node_vtables(bcx, vtable_key);
debug!("trans_fn_ref(def_id={}, node={:?}, substs={}, vtables={})",
def_id.repr(bcx.tcx()),
node,
substs.repr(bcx.tcx()),
vtables.repr(bcx.tcx()));
trans_fn_ref_with_vtables(bcx, def_id, node, substs, vtables)
}
fn trans_fn_ref_with_vtables_to_callee<'a>(bcx: &'a Block<'a>,
def_id: ast::DefId,
ref_id: ast::NodeId,
substs: subst::Substs,
vtables: typeck::vtable_res)
-> Callee<'a> {
Callee {bcx: bcx,
data: Fn(trans_fn_ref_with_vtables(bcx, def_id, ExprId(ref_id),
substs, vtables))}
}
fn resolve_default_method_vtables(bcx: &Block,
impl_id: ast::DefId,
substs: &subst::Substs,
impl_vtables: typeck::vtable_res)
-> typeck::vtable_res
{let impl_res = ty::lookup_impl_vtables(bcx.tcx(), impl_id);let param_substs = param_substs {
substs: (*substs).clone(),
vtables: impl_vtables.clone()
};
let mut param_vtables = resolve_vtables_under_param_substs(
bcx.tcx(), ¶m_substs, &impl_res);param_vtables
.get_mut_vec(subst::FnSpace)
.push_all(
impl_vtables.get_vec(subst::FnSpace).as_slice());
param_vtables
}
pub fn trans_fn_ref_with_vtables(
bcx: &Block,def_id: ast::DefId,node: ExprOrMethodCall,substs: subst::Substs,vtables: typeck::vtable_res)-> ValueRef
{
let _icx = push_ctxt("trans_fn_ref_with_vtables");
let ccx = bcx.ccx();
let tcx = bcx.tcx();
debug!("trans_fn_ref_with_vtables(bcx={}, def_id={}, node={:?}, \
substs={}, vtables={})",
bcx.to_str(),
def_id.repr(tcx),
node,
substs.repr(tcx),
vtables.repr(tcx));
assert!(substs.types.all(|t| !ty::type_needs_infer(*t)));let fn_tpt = ty::lookup_item_type(tcx, def_id);match ty::trait_of_method(tcx, def_id) {
None => {}
Some(trait_id) => {
ty::populate_implementations_for_trait_if_necessary(tcx, trait_id)
}
}let (is_default, def_id, substs, vtables) =
match ty::provided_source(tcx, def_id) {
None => (false, def_id, substs, vtables),
Some(source_id) => {let impl_id = ty::method(tcx, def_id).container_id();
let method = ty::method(tcx, source_id);
let trait_ref = ty::impl_trait_ref(tcx, impl_id)
.expect("could not find trait_ref for impl with \
default methods");let first_subst = make_substs_for_receiver_types(
tcx, &*trait_ref, &*method);let new_substs = first_subst.subst(tcx, &substs);
debug!("trans_fn_with_vtables - default method: \
substs = {}, trait_subst = {}, \
first_subst = {}, new_subst = {}, \
vtables = {}",
substs.repr(tcx), trait_ref.substs.repr(tcx),
first_subst.repr(tcx), new_substs.repr(tcx),
vtables.repr(tcx));
let param_vtables =
resolve_default_method_vtables(bcx, impl_id, &substs, vtables);
debug!("trans_fn_with_vtables - default method: \
param_vtables = {}",
param_vtables.repr(tcx));
(true, source_id, new_substs, param_vtables)
}
};let def_id = {
if def_id.krate != ast::LOCAL_CRATE {
inline::maybe_instantiate_inline(ccx, def_id)
} else {
def_id
}
};let must_monomorphise = if !substs.types.is_empty() || is_default {
true
} else if def_id.krate == ast::LOCAL_CRATE {
let map_node = session::expect(
ccx.sess(),
tcx.map.find(def_id.node),
|| "local item should be in ast map".to_string());
match map_node {
ast_map::NodeForeignItem(_) => {
tcx.map.get_foreign_abi(def_id.node) == synabi::RustIntrinsic
}
_ => false
}
} else {
false
};if must_monomorphise {assert_eq!(def_id.krate, ast::LOCAL_CRATE);
let opt_ref_id = match node {
ExprId(id) => if id != 0 { Some(id) } else { None },
MethodCall(_) => None,
};
let (val, must_cast) =
monomorphize::monomorphic_fn(ccx, def_id, &substs,
vtables, opt_ref_id);
let mut val = val;
if must_cast && node != ExprId(0) {let ref_ty = match node {
ExprId(id) => node_id_type(bcx, id),
MethodCall(method_call) => {
let t = bcx.tcx().method_map.borrow().get(&method_call).ty;
monomorphize_type(bcx, t)
}
};
val = PointerCast(
bcx, val, type_of::type_of_fn_from_ty(ccx, ref_ty).ptr_to());
}
return val;
}let mut val = {
if def_id.krate == ast::LOCAL_CRATE {get_item_val(ccx, def_id.node)
} else {trans_external_path(ccx, def_id, fn_tpt.ty)
}
};let llty = type_of::type_of_fn_from_ty(ccx, fn_tpt.ty);
let llptrty = llty.ptr_to();
if val_ty(val) != llptrty {
val = BitCast(bcx, val, llptrty);
}
val
}pub fn trans_call<'a>(
in_cx: &'a Block<'a>,
call_ex: &ast::Expr,
f: &ast::Expr,
args: CallArgs,
dest: expr::Dest)
-> &'a Block<'a> {
let _icx = push_ctxt("trans_call");
trans_call_inner(in_cx,
Some(common::expr_info(call_ex)),
expr_ty(in_cx, f),
|cx, _| trans(cx, f),
args,
Some(dest)).bcx
}
pub fn trans_method_call<'a>(
bcx: &'a Block<'a>,
call_ex: &ast::Expr,
rcvr: &ast::Expr,
args: CallArgs,
dest: expr::Dest)
-> &'a Block<'a> {
let _icx = push_ctxt("trans_method_call");
debug!("trans_method_call(call_ex={})", call_ex.repr(bcx.tcx()));
let method_call = MethodCall::expr(call_ex.id);
let method_ty = bcx.tcx().method_map.borrow().get(&method_call).ty;
trans_call_inner(
bcx,
Some(common::expr_info(call_ex)),
monomorphize_type(bcx, method_ty),
|cx, arg_cleanup_scope| {
meth::trans_method_callee(cx, method_call, Some(rcvr), arg_cleanup_scope)
},
args,
Some(dest)).bcx
}
pub fn trans_lang_call<'a>(
bcx: &'a Block<'a>,
did: ast::DefId,
args: &[ValueRef],
dest: Option<expr::Dest>)
-> Result<'a> {
let fty = if did.krate == ast::LOCAL_CRATE {
ty::node_id_to_type(bcx.tcx(), did.node)
} else {
csearch::get_type(bcx.tcx(), did).ty
};
callee::trans_call_inner(bcx,
None,
fty,
|bcx, _| {
trans_fn_ref_with_vtables_to_callee(bcx,
did,
0,
subst::Substs::empty(),
VecPerParamSpace::empty())
},
ArgVals(args),
dest)
}
pub fn trans_call_inner<'a>(
bcx: &'a Block<'a>,
call_info: Option<NodeInfo>,
callee_ty: ty::t,
get_callee: |bcx: &'a Block<'a>,
arg_cleanup_scope: cleanup::ScopeId|
-> Callee<'a>,
args: CallArgs,
dest: Option<expr::Dest>)
-> Result<'a> {
let fcx = bcx.fcx;
let ccx = fcx.ccx;
let arg_cleanup_scope = fcx.push_custom_cleanup_scope();
let callee = get_callee(bcx, cleanup::CustomScope(arg_cleanup_scope));
let mut bcx = callee.bcx;
let (llfn, llenv, llself) = match callee.data {
Fn(llfn) => {
(llfn, None, None)
}
TraitMethod(d) => {
(d.llfn, None, Some(d.llself))
}
Closure(d) => {let pair = d.to_llref();
let llfn = GEPi(bcx, pair, [0u, abi::fn_field_code]);
let llfn = Load(bcx, llfn);
let llenv = GEPi(bcx, pair, [0u, abi::fn_field_box]);
let llenv = Load(bcx, llenv);
(llfn, Some(llenv), None)
}
};
let (abi, ret_ty) = match ty::get(callee_ty).sty {
ty::ty_bare_fn(ref f) => (f.abi, f.sig.output),
ty::ty_closure(ref f) => (synabi::Rust, f.sig.output),
_ => fail!("expected bare rust fn or closure in trans_call_inner")
};
let is_rust_fn = abi == synabi::Rust || abi == synabi::RustIntrinsic;let opt_llretslot = match dest {
None => {
assert!(!type_of::return_uses_outptr(ccx, ret_ty));
None
}
Some(expr::SaveIn(dst)) => Some(dst),
Some(expr::Ignore) => {
if !type_is_zero_size(ccx, ret_ty) {
Some(alloc_ty(bcx, ret_ty, "__llret"))
} else {
let llty = type_of::type_of(ccx, ret_ty);
Some(C_undef(llty.ptr_to()))
}
}
};
let mut llresult = unsafe {
llvm::LLVMGetUndef(Type::nil(ccx).ptr_to().to_ref())
};if is_rust_fn {
let mut llargs = Vec::new();if type_of::return_uses_outptr(ccx, ret_ty) {
llargs.push(opt_llretslot.unwrap());
}match (llenv, llself) {
(Some(llenv), None) => {
llargs.push(llenv)
},
(None, Some(llself)) => llargs.push(llself),
_ => {}
}bcx = trans_args(bcx, args, callee_ty, &mut llargs,
cleanup::CustomScope(arg_cleanup_scope),
llself.is_some());
fcx.pop_custom_cleanup_scope(arg_cleanup_scope);let (llret, b) = base::invoke(bcx,
llfn,
llargs,
callee_ty,
call_info);
bcx = b;
llresult = llret;match opt_llretslot {
Some(llretslot) => {
if !type_of::return_uses_outptr(bcx.ccx(), ret_ty) &&
!type_is_zero_size(bcx.ccx(), ret_ty)
{
Store(bcx, llret, llretslot);
}
}
None => {}
}
} else {assert!(dest.is_some());
let mut llargs = Vec::new();
let arg_tys = match args {
ArgExprs(a) => a.iter().map(|x| expr_ty(bcx, &**x)).collect(),
_ => fail!("expected arg exprs.")
};
bcx = trans_args(bcx, args, callee_ty, &mut llargs,
cleanup::CustomScope(arg_cleanup_scope), false);
fcx.pop_custom_cleanup_scope(arg_cleanup_scope);
bcx = foreign::trans_native_call(bcx, callee_ty,
llfn, opt_llretslot.unwrap(),
llargs.as_slice(), arg_tys);
}match dest {
None => {
assert!(!type_of::return_uses_outptr(bcx.ccx(), ret_ty));
}
Some(expr::Ignore) => {bcx = glue::drop_ty(bcx, opt_llretslot.unwrap(), ret_ty);
}
Some(expr::SaveIn(_)) => { }
}
if ty::type_is_bot(ret_ty) {
Unreachable(bcx);
}
Result::new(bcx, llresult)
}
pub enum CallArgs<'a> {ArgExprs(&'a [Gc<ast::Expr>]),ArgVals(&'a [ValueRef]),ArgOverloadedOp(Datum<Expr>, Option<(Datum<Expr>, ast::NodeId)>),
}
fn trans_args<'a>(cx: &'a Block<'a>,
args: CallArgs,
fn_ty: ty::t,
llargs: &mut Vec<ValueRef> ,
arg_cleanup_scope: cleanup::ScopeId,
ignore_self: bool)
-> &'a Block<'a> {
let _icx = push_ctxt("trans_args");
let arg_tys = ty::ty_fn_args(fn_ty);
let variadic = ty::fn_is_variadic(fn_ty);
let mut bcx = cx;match args {
ArgExprs(arg_exprs) => {
let num_formal_args = arg_tys.len();
for (i, arg_expr) in arg_exprs.iter().enumerate() {
if i == 0 && ignore_self {
continue;
}
let arg_ty = if i >= num_formal_args {
assert!(variadic);
expr_ty_adjusted(cx, &**arg_expr)
} else {
*arg_tys.get(i)
};
let arg_datum = unpack_datum!(bcx, expr::trans(bcx, &**arg_expr));
llargs.push(unpack_result!(bcx, {
trans_arg_datum(bcx, arg_ty, arg_datum,
arg_cleanup_scope,
DontAutorefArg)
}));
}
}
ArgOverloadedOp(lhs, rhs) => {
assert!(!variadic);
llargs.push(unpack_result!(bcx, {
trans_arg_datum(bcx, *arg_tys.get(0), lhs,
arg_cleanup_scope,
DontAutorefArg)
}));
match rhs {
Some((rhs, rhs_id)) => {
assert_eq!(arg_tys.len(), 2);
llargs.push(unpack_result!(bcx, {
trans_arg_datum(bcx, *arg_tys.get(1), rhs,
arg_cleanup_scope,
DoAutorefArg(rhs_id))
}));
}
None => assert_eq!(arg_tys.len(), 1)
}
}
ArgVals(vs) => {
llargs.push_all(vs);
}
}
bcx
}
pub enum AutorefArg {
DontAutorefArg,
DoAutorefArg(ast::NodeId)
}
pub fn trans_arg_datum<'a>(
bcx: &'a Block<'a>,
formal_arg_ty: ty::t,
arg_datum: Datum<Expr>,
arg_cleanup_scope: cleanup::ScopeId,
autoref_arg: AutorefArg)
-> Result<'a> {
let _icx = push_ctxt("trans_arg_datum");
let mut bcx = bcx;
let ccx = bcx.ccx();
debug!("trans_arg_datum({})",
formal_arg_ty.repr(bcx.tcx()));
let arg_datum_ty = arg_datum.ty;
debug!(" arg datum: {}", arg_datum.to_str(bcx.ccx()));
let mut val;
if ty::type_is_bot(arg_datum_ty) {let llformal_arg_ty = type_of::type_of_explicit_arg(ccx, formal_arg_ty);
unsafe {
val = llvm::LLVMGetUndef(llformal_arg_ty.to_ref());
}
} else {match autoref_arg {
DoAutorefArg(arg_id) => {let arg_datum = unpack_datum!(
bcx, arg_datum.to_lvalue_datum(bcx, "arg", arg_id));
val = arg_datum.val;
}
DontAutorefArg => {let arg_datum = unpack_datum!(
bcx, arg_datum.to_rvalue_datum(bcx, "arg"));let arg_datum = unpack_datum!(
bcx, arg_datum.to_appropriate_datum(bcx));val = arg_datum.add_clean(bcx.fcx, arg_cleanup_scope);
}
}
if formal_arg_ty != arg_datum_ty {let llformal_arg_ty = type_of::type_of_explicit_arg(ccx, formal_arg_ty);
debug!("casting actual type ({}) to match formal ({})",
bcx.val_to_str(val), bcx.llty_str(llformal_arg_ty));
val = PointerCast(bcx, val, llformal_arg_ty);
}
}
debug!("--- trans_arg_datum passing {}", bcx.val_to_str(val));
Result::new(bcx, val)
}