-
Notifications
You must be signed in to change notification settings - Fork 13.1k
/
Copy pathconstant.rs
1345 lines (1235 loc) · 58.6 KB
/
constant.rs
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
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use llvm::{self, ValueRef};
use rustc::middle::const_val::{ConstEvalErr, ConstVal, ErrKind};
use rustc_const_math::ConstInt::*;
use rustc_const_math::{ConstInt, ConstMathErr, MAX_F32_PLUS_HALF_ULP};
use rustc::hir::def_id::DefId;
use rustc::infer::TransNormalize;
use rustc::traits;
use rustc::mir;
use rustc::mir::tcx::PlaceTy;
use rustc::ty::{self, Ty, TyCtxt, TypeFoldable};
use rustc::ty::layout::{self, LayoutOf, Size};
use rustc::ty::cast::{CastTy, IntTy};
use rustc::ty::subst::{Kind, Substs};
use rustc_apfloat::{ieee, Float, Status};
use rustc_data_structures::indexed_vec::{Idx, IndexVec};
use base;
use abi::{self, Abi};
use callee;
use builder::Builder;
use common::{self, CodegenCx, const_get_elt, val_ty};
use common::{C_array, C_bool, C_bytes, C_int, C_uint, C_uint_big, C_u32, C_u64};
use common::{C_null, C_struct, C_str_slice, C_undef, C_usize, C_vector, C_fat_ptr};
use common::const_to_opt_u128;
use consts;
use type_of::LayoutLlvmExt;
use type_::Type;
use value::Value;
use syntax_pos::Span;
use syntax::ast;
use std::fmt;
use std::ptr;
use super::operand::{OperandRef, OperandValue};
use super::FunctionCx;
/// A sized constant rvalue.
/// The LLVM type might not be the same for a single Rust type,
/// e.g. each enum variant would have its own LLVM struct type.
#[derive(Copy, Clone)]
pub struct Const<'tcx> {
pub llval: ValueRef,
pub ty: Ty<'tcx>
}
impl<'a, 'tcx> Const<'tcx> {
pub fn new(llval: ValueRef, ty: Ty<'tcx>) -> Const<'tcx> {
Const {
llval,
ty,
}
}
pub fn from_constint(cx: &CodegenCx<'a, 'tcx>, ci: &ConstInt) -> Const<'tcx> {
let tcx = cx.tcx;
let (llval, ty) = match *ci {
I8(v) => (C_int(Type::i8(cx), v as i64), tcx.types.i8),
I16(v) => (C_int(Type::i16(cx), v as i64), tcx.types.i16),
I32(v) => (C_int(Type::i32(cx), v as i64), tcx.types.i32),
I64(v) => (C_int(Type::i64(cx), v as i64), tcx.types.i64),
I128(v) => (C_uint_big(Type::i128(cx), v as u128), tcx.types.i128),
Isize(v) => (C_int(Type::isize(cx), v.as_i64()), tcx.types.isize),
U8(v) => (C_uint(Type::i8(cx), v as u64), tcx.types.u8),
U16(v) => (C_uint(Type::i16(cx), v as u64), tcx.types.u16),
U32(v) => (C_uint(Type::i32(cx), v as u64), tcx.types.u32),
U64(v) => (C_uint(Type::i64(cx), v), tcx.types.u64),
U128(v) => (C_uint_big(Type::i128(cx), v), tcx.types.u128),
Usize(v) => (C_uint(Type::isize(cx), v.as_u64()), tcx.types.usize),
};
Const { llval: llval, ty: ty }
}
/// Translate ConstVal into a LLVM constant value.
pub fn from_constval(cx: &CodegenCx<'a, 'tcx>,
cv: &ConstVal,
ty: Ty<'tcx>)
-> Const<'tcx> {
let llty = cx.layout_of(ty).llvm_type(cx);
let val = match *cv {
ConstVal::Float(v) => {
let bits = match v.ty {
ast::FloatTy::F32 => C_u32(cx, v.bits as u32),
ast::FloatTy::F64 => C_u64(cx, v.bits as u64)
};
consts::bitcast(bits, llty)
}
ConstVal::Bool(v) => C_bool(cx, v),
ConstVal::Integral(ref i) => return Const::from_constint(cx, i),
ConstVal::Str(ref v) => C_str_slice(cx, v.clone()),
ConstVal::ByteStr(v) => {
consts::addr_of(cx, C_bytes(cx, v.data), cx.align_of(ty), "byte_str")
}
ConstVal::Char(c) => C_uint(Type::char(cx), c as u64),
ConstVal::Function(..) => C_undef(llty),
ConstVal::Variant(_) |
ConstVal::Aggregate(..) |
ConstVal::Unevaluated(..) => {
bug!("MIR must not use `{:?}` (aggregates are expanded to MIR rvalues)", cv)
}
};
assert!(!ty.has_erasable_regions());
Const::new(val, ty)
}
fn get_field(&self, cx: &CodegenCx<'a, 'tcx>, i: usize) -> ValueRef {
let layout = cx.layout_of(self.ty);
let field = layout.field(cx, i);
if field.is_zst() {
return C_undef(field.immediate_llvm_type(cx));
}
let offset = layout.fields.offset(i);
match layout.abi {
layout::Abi::Scalar(_) |
layout::Abi::ScalarPair(..) |
layout::Abi::Vector { .. }
if offset.bytes() == 0 && field.size == layout.size => self.llval,
layout::Abi::ScalarPair(ref a, ref b) => {
if offset.bytes() == 0 {
assert_eq!(field.size, a.value.size(cx));
const_get_elt(self.llval, 0)
} else {
assert_eq!(offset, a.value.size(cx)
.abi_align(b.value.align(cx)));
assert_eq!(field.size, b.value.size(cx));
const_get_elt(self.llval, 1)
}
}
_ => {
match layout.fields {
layout::FieldPlacement::Union(_) => self.llval,
_ => const_get_elt(self.llval, layout.llvm_field_index(i)),
}
}
}
}
fn get_pair(&self, cx: &CodegenCx<'a, 'tcx>) -> (ValueRef, ValueRef) {
(self.get_field(cx, 0), self.get_field(cx, 1))
}
fn get_fat_ptr(&self, cx: &CodegenCx<'a, 'tcx>) -> (ValueRef, ValueRef) {
assert_eq!(abi::FAT_PTR_ADDR, 0);
assert_eq!(abi::FAT_PTR_EXTRA, 1);
self.get_pair(cx)
}
fn as_place(&self) -> ConstPlace<'tcx> {
ConstPlace {
base: Base::Value(self.llval),
llextra: ptr::null_mut(),
ty: self.ty
}
}
pub fn to_operand(&self, cx: &CodegenCx<'a, 'tcx>) -> OperandRef<'tcx> {
let layout = cx.layout_of(self.ty);
let llty = layout.immediate_llvm_type(cx);
let llvalty = val_ty(self.llval);
let val = if llty == llvalty && layout.is_llvm_scalar_pair() {
OperandValue::Pair(
const_get_elt(self.llval, 0),
const_get_elt(self.llval, 1))
} else if llty == llvalty && layout.is_llvm_immediate() {
// If the types match, we can use the value directly.
OperandValue::Immediate(self.llval)
} else {
// Otherwise, or if the value is not immediate, we create
// a constant LLVM global and cast its address if necessary.
let align = cx.align_of(self.ty);
let ptr = consts::addr_of(cx, self.llval, align, "const");
OperandValue::Ref(consts::ptrcast(ptr, layout.llvm_type(cx).ptr_to()),
layout.align)
};
OperandRef {
val,
layout
}
}
}
impl<'tcx> fmt::Debug for Const<'tcx> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Const({:?}: {:?})", Value(self.llval), self.ty)
}
}
#[derive(Copy, Clone)]
enum Base {
/// A constant value without an unique address.
Value(ValueRef),
/// String literal base pointer (cast from array).
Str(ValueRef),
/// The address of a static.
Static(ValueRef)
}
/// A place as seen from a constant.
#[derive(Copy, Clone)]
struct ConstPlace<'tcx> {
base: Base,
llextra: ValueRef,
ty: Ty<'tcx>
}
impl<'tcx> ConstPlace<'tcx> {
fn to_const(&self, span: Span) -> Const<'tcx> {
match self.base {
Base::Value(val) => Const::new(val, self.ty),
Base::Str(ptr) => {
span_bug!(span, "loading from `str` ({:?}) in constant",
Value(ptr))
}
Base::Static(val) => {
span_bug!(span, "loading from `static` ({:?}) in constant",
Value(val))
}
}
}
pub fn len<'a>(&self, cx: &CodegenCx<'a, 'tcx>) -> ValueRef {
match self.ty.sty {
ty::TyArray(_, n) => {
C_usize(cx, n.val.to_const_int().unwrap().to_u64().unwrap())
}
ty::TySlice(_) | ty::TyStr => {
assert!(self.llextra != ptr::null_mut());
self.llextra
}
_ => bug!("unexpected type `{}` in ConstPlace::len", self.ty)
}
}
}
/// Machinery for translating a constant's MIR to LLVM values.
/// FIXME(eddyb) use miri and lower its allocations to LLVM.
struct MirConstContext<'a, 'tcx: 'a> {
cx: &'a CodegenCx<'a, 'tcx>,
mir: &'a mir::Mir<'tcx>,
/// Type parameters for const fn and associated constants.
substs: &'tcx Substs<'tcx>,
/// Values of locals in a constant or const fn.
locals: IndexVec<mir::Local, Option<Result<Const<'tcx>, ConstEvalErr<'tcx>>>>
}
fn add_err<'tcx, U, V>(failure: &mut Result<U, ConstEvalErr<'tcx>>,
value: &Result<V, ConstEvalErr<'tcx>>)
{
if let &Err(ref err) = value {
if failure.is_ok() {
*failure = Err(err.clone());
}
}
}
impl<'a, 'tcx> MirConstContext<'a, 'tcx> {
fn new(cx: &'a CodegenCx<'a, 'tcx>,
mir: &'a mir::Mir<'tcx>,
substs: &'tcx Substs<'tcx>,
args: IndexVec<mir::Local, Result<Const<'tcx>, ConstEvalErr<'tcx>>>)
-> MirConstContext<'a, 'tcx> {
let mut context = MirConstContext {
cx,
mir,
substs,
locals: (0..mir.local_decls.len()).map(|_| None).collect(),
};
for (i, arg) in args.into_iter().enumerate() {
// Locals after local 0 are the function arguments
let index = mir::Local::new(i + 1);
context.locals[index] = Some(arg);
}
context
}
fn trans_def(cx: &'a CodegenCx<'a, 'tcx>,
def_id: DefId,
substs: &'tcx Substs<'tcx>,
args: IndexVec<mir::Local, Result<Const<'tcx>, ConstEvalErr<'tcx>>>)
-> Result<Const<'tcx>, ConstEvalErr<'tcx>> {
let instance = ty::Instance::resolve(cx.tcx,
ty::ParamEnv::empty(traits::Reveal::All),
def_id,
substs).unwrap();
let mir = cx.tcx.instance_mir(instance.def);
MirConstContext::new(cx, &mir, instance.substs, args).trans()
}
fn monomorphize<T>(&self, value: &T) -> T
where T: TransNormalize<'tcx>
{
self.cx.tcx.trans_apply_param_substs(self.substs, value)
}
fn trans(&mut self) -> Result<Const<'tcx>, ConstEvalErr<'tcx>> {
let tcx = self.cx.tcx;
let mut bb = mir::START_BLOCK;
// Make sure to evaluate all statemenets to
// report as many errors as we possibly can.
let mut failure = Ok(());
loop {
let data = &self.mir[bb];
for statement in &data.statements {
let span = statement.source_info.span;
match statement.kind {
mir::StatementKind::Assign(ref dest, ref rvalue) => {
let ty = dest.ty(self.mir, tcx);
let ty = self.monomorphize(&ty).to_ty(tcx);
let value = self.const_rvalue(rvalue, ty, span);
add_err(&mut failure, &value);
self.store(dest, value, span);
}
mir::StatementKind::StorageLive(_) |
mir::StatementKind::StorageDead(_) |
mir::StatementKind::Validate(..) |
mir::StatementKind::EndRegion(_) |
mir::StatementKind::Nop => {}
mir::StatementKind::InlineAsm { .. } |
mir::StatementKind::SetDiscriminant{ .. } => {
span_bug!(span, "{:?} should not appear in constants?", statement.kind);
}
}
}
let terminator = data.terminator();
let span = terminator.source_info.span;
bb = match terminator.kind {
mir::TerminatorKind::Drop { target, .. } | // No dropping.
mir::TerminatorKind::Goto { target } => target,
mir::TerminatorKind::Return => {
failure?;
return self.locals[mir::RETURN_PLACE].clone().unwrap_or_else(|| {
span_bug!(span, "no returned value in constant");
});
}
mir::TerminatorKind::Assert { ref cond, expected, ref msg, target, .. } => {
let cond = self.const_operand(cond, span)?;
let cond_bool = common::const_to_uint(cond.llval) != 0;
if cond_bool != expected {
let err = match *msg {
mir::AssertMessage::BoundsCheck { ref len, ref index } => {
let len = self.const_operand(len, span)?;
let index = self.const_operand(index, span)?;
ErrKind::IndexOutOfBounds {
len: common::const_to_uint(len.llval),
index: common::const_to_uint(index.llval)
}
}
mir::AssertMessage::Math(ref err) => {
ErrKind::Math(err.clone())
}
mir::AssertMessage::GeneratorResumedAfterReturn |
mir::AssertMessage::GeneratorResumedAfterPanic =>
span_bug!(span, "{:?} should not appear in constants?", msg),
};
let err = ConstEvalErr { span: span, kind: err };
err.report(tcx, span, "expression");
failure = Err(err);
}
target
}
mir::TerminatorKind::Call { ref func, ref args, ref destination, .. } => {
let fn_ty = func.ty(self.mir, tcx);
let fn_ty = self.monomorphize(&fn_ty);
let (def_id, substs) = match fn_ty.sty {
ty::TyFnDef(def_id, substs) => (def_id, substs),
_ => span_bug!(span, "calling {:?} (of type {}) in constant",
func, fn_ty)
};
let mut arg_vals = IndexVec::with_capacity(args.len());
for arg in args {
let arg_val = self.const_operand(arg, span);
add_err(&mut failure, &arg_val);
arg_vals.push(arg_val);
}
if let Some((ref dest, target)) = *destination {
let result = if fn_ty.fn_sig(tcx).abi() == Abi::RustIntrinsic {
match &tcx.item_name(def_id)[..] {
"size_of" => {
let llval = C_usize(self.cx,
self.cx.size_of(substs.type_at(0)).bytes());
Ok(Const::new(llval, tcx.types.usize))
}
"min_align_of" => {
let llval = C_usize(self.cx,
self.cx.align_of(substs.type_at(0)).abi());
Ok(Const::new(llval, tcx.types.usize))
}
"type_id" => {
let llval = C_u64(self.cx,
self.cx.tcx.type_id_hash(substs.type_at(0)));
Ok(Const::new(llval, tcx.types.u64))
}
_ => span_bug!(span, "{:?} in constant", terminator.kind)
}
} else if let Some((op, is_checked)) = self.is_binop_lang_item(def_id) {
(||{
assert_eq!(arg_vals.len(), 2);
let rhs = arg_vals.pop().unwrap()?;
let lhs = arg_vals.pop().unwrap()?;
if !is_checked {
let binop_ty = op.ty(tcx, lhs.ty, rhs.ty);
let (lhs, rhs) = (lhs.llval, rhs.llval);
Ok(Const::new(const_scalar_binop(op, lhs, rhs, binop_ty),
binop_ty))
} else {
let ty = lhs.ty;
let val_ty = op.ty(tcx, lhs.ty, rhs.ty);
let binop_ty = tcx.intern_tup(&[val_ty, tcx.types.bool], false);
let (lhs, rhs) = (lhs.llval, rhs.llval);
assert!(!ty.is_fp());
match const_scalar_checked_binop(tcx, op, lhs, rhs, ty) {
Some((llval, of)) => {
Ok(trans_const_adt(
self.cx,
binop_ty,
&mir::AggregateKind::Tuple,
&[
Const::new(llval, val_ty),
Const::new(C_bool(self.cx, of), tcx.types.bool)
]))
}
None => {
span_bug!(span,
"{:?} got non-integer operands: {:?} and {:?}",
op, Value(lhs), Value(rhs));
}
}
}
})()
} else {
MirConstContext::trans_def(self.cx, def_id, substs, arg_vals)
};
add_err(&mut failure, &result);
self.store(dest, result, span);
target
} else {
span_bug!(span, "diverging {:?} in constant", terminator.kind);
}
}
_ => span_bug!(span, "{:?} in constant", terminator.kind)
};
}
}
fn is_binop_lang_item(&mut self, def_id: DefId) -> Option<(mir::BinOp, bool)> {
let tcx = self.cx.tcx;
let items = tcx.lang_items();
let def_id = Some(def_id);
if items.i128_add_fn() == def_id { Some((mir::BinOp::Add, false)) }
else if items.u128_add_fn() == def_id { Some((mir::BinOp::Add, false)) }
else if items.i128_sub_fn() == def_id { Some((mir::BinOp::Sub, false)) }
else if items.u128_sub_fn() == def_id { Some((mir::BinOp::Sub, false)) }
else if items.i128_mul_fn() == def_id { Some((mir::BinOp::Mul, false)) }
else if items.u128_mul_fn() == def_id { Some((mir::BinOp::Mul, false)) }
else if items.i128_div_fn() == def_id { Some((mir::BinOp::Div, false)) }
else if items.u128_div_fn() == def_id { Some((mir::BinOp::Div, false)) }
else if items.i128_rem_fn() == def_id { Some((mir::BinOp::Rem, false)) }
else if items.u128_rem_fn() == def_id { Some((mir::BinOp::Rem, false)) }
else if items.i128_shl_fn() == def_id { Some((mir::BinOp::Shl, false)) }
else if items.u128_shl_fn() == def_id { Some((mir::BinOp::Shl, false)) }
else if items.i128_shr_fn() == def_id { Some((mir::BinOp::Shr, false)) }
else if items.u128_shr_fn() == def_id { Some((mir::BinOp::Shr, false)) }
else if items.i128_addo_fn() == def_id { Some((mir::BinOp::Add, true)) }
else if items.u128_addo_fn() == def_id { Some((mir::BinOp::Add, true)) }
else if items.i128_subo_fn() == def_id { Some((mir::BinOp::Sub, true)) }
else if items.u128_subo_fn() == def_id { Some((mir::BinOp::Sub, true)) }
else if items.i128_mulo_fn() == def_id { Some((mir::BinOp::Mul, true)) }
else if items.u128_mulo_fn() == def_id { Some((mir::BinOp::Mul, true)) }
else if items.i128_shlo_fn() == def_id { Some((mir::BinOp::Shl, true)) }
else if items.u128_shlo_fn() == def_id { Some((mir::BinOp::Shl, true)) }
else if items.i128_shro_fn() == def_id { Some((mir::BinOp::Shr, true)) }
else if items.u128_shro_fn() == def_id { Some((mir::BinOp::Shr, true)) }
else { None }
}
fn store(&mut self,
dest: &mir::Place<'tcx>,
value: Result<Const<'tcx>, ConstEvalErr<'tcx>>,
span: Span) {
if let mir::Place::Local(index) = *dest {
self.locals[index] = Some(value);
} else {
span_bug!(span, "assignment to {:?} in constant", dest);
}
}
fn const_place(&self, place: &mir::Place<'tcx>, span: Span)
-> Result<ConstPlace<'tcx>, ConstEvalErr<'tcx>> {
let tcx = self.cx.tcx;
if let mir::Place::Local(index) = *place {
return self.locals[index].clone().unwrap_or_else(|| {
span_bug!(span, "{:?} not initialized", place)
}).map(|v| v.as_place());
}
let place = match *place {
mir::Place::Local(_) => bug!(), // handled above
mir::Place::Static(box mir::Static { def_id, ty }) => {
ConstPlace {
base: Base::Static(consts::get_static(self.cx, def_id)),
llextra: ptr::null_mut(),
ty: self.monomorphize(&ty),
}
}
mir::Place::Projection(ref projection) => {
let tr_base = self.const_place(&projection.base, span)?;
let projected_ty = PlaceTy::Ty { ty: tr_base.ty }
.projection_ty(tcx, &projection.elem);
let base = tr_base.to_const(span);
let projected_ty = self.monomorphize(&projected_ty).to_ty(tcx);
let has_metadata = self.cx.type_has_metadata(projected_ty);
let (projected, llextra) = match projection.elem {
mir::ProjectionElem::Deref => {
let (base, extra) = if !has_metadata {
(base.llval, ptr::null_mut())
} else {
base.get_fat_ptr(self.cx)
};
if self.cx.statics.borrow().contains_key(&base) {
(Base::Static(base), extra)
} else if let ty::TyStr = projected_ty.sty {
(Base::Str(base), extra)
} else {
let v = base;
let v = self.cx.const_unsized.borrow().get(&v).map_or(v, |&v| v);
let mut val = unsafe { llvm::LLVMGetInitializer(v) };
if val.is_null() {
span_bug!(span, "dereference of non-constant pointer `{:?}`",
Value(base));
}
let layout = self.cx.layout_of(projected_ty);
if let layout::Abi::Scalar(ref scalar) = layout.abi {
let i1_type = Type::i1(self.cx);
if scalar.is_bool() && val_ty(val) != i1_type {
unsafe {
val = llvm::LLVMConstTrunc(val, i1_type.to_ref());
}
}
}
(Base::Value(val), extra)
}
}
mir::ProjectionElem::Field(ref field, _) => {
let llprojected = base.get_field(self.cx, field.index());
let llextra = if !has_metadata {
ptr::null_mut()
} else {
tr_base.llextra
};
(Base::Value(llprojected), llextra)
}
mir::ProjectionElem::Index(index) => {
let index = &mir::Operand::Copy(mir::Place::Local(index));
let llindex = self.const_operand(index, span)?.llval;
let iv = if let Some(iv) = common::const_to_opt_u128(llindex, false) {
iv
} else {
span_bug!(span, "index is not an integer-constant expression")
};
// Produce an undef instead of a LLVM assertion on OOB.
let len = common::const_to_uint(tr_base.len(self.cx));
let llelem = if iv < len as u128 {
const_get_elt(base.llval, iv as u64)
} else {
C_undef(self.cx.layout_of(projected_ty).llvm_type(self.cx))
};
(Base::Value(llelem), ptr::null_mut())
}
_ => span_bug!(span, "{:?} in constant", projection.elem)
};
ConstPlace {
base: projected,
llextra,
ty: projected_ty
}
}
};
Ok(place)
}
fn const_operand(&self, operand: &mir::Operand<'tcx>, span: Span)
-> Result<Const<'tcx>, ConstEvalErr<'tcx>> {
debug!("const_operand({:?} @ {:?})", operand, span);
let result = match *operand {
mir::Operand::Copy(ref place) |
mir::Operand::Move(ref place) => {
Ok(self.const_place(place, span)?.to_const(span))
}
mir::Operand::Constant(ref constant) => {
let ty = self.monomorphize(&constant.ty);
match constant.literal.clone() {
mir::Literal::Promoted { index } => {
let mir = &self.mir.promoted[index];
MirConstContext::new(self.cx, mir, self.substs, IndexVec::new()).trans()
}
mir::Literal::Value { value } => {
if let ConstVal::Unevaluated(def_id, substs) = value.val {
let substs = self.monomorphize(&substs);
MirConstContext::trans_def(self.cx, def_id, substs, IndexVec::new())
} else {
Ok(Const::from_constval(self.cx, &value.val, ty))
}
}
}
}
};
debug!("const_operand({:?} @ {:?}) = {:?}", operand, span,
result.as_ref().ok());
result
}
fn const_array(&self, array_ty: Ty<'tcx>, fields: &[ValueRef])
-> Const<'tcx>
{
let elem_ty = array_ty.builtin_index().unwrap_or_else(|| {
bug!("bad array type {:?}", array_ty)
});
let llunitty = self.cx.layout_of(elem_ty).llvm_type(self.cx);
// If the array contains enums, an LLVM array won't work.
let val = if fields.iter().all(|&f| val_ty(f) == llunitty) {
C_array(llunitty, fields)
} else {
C_struct(self.cx, fields, false)
};
Const::new(val, array_ty)
}
fn const_rvalue(&self, rvalue: &mir::Rvalue<'tcx>,
dest_ty: Ty<'tcx>, span: Span)
-> Result<Const<'tcx>, ConstEvalErr<'tcx>> {
let tcx = self.cx.tcx;
debug!("const_rvalue({:?}: {:?} @ {:?})", rvalue, dest_ty, span);
let val = match *rvalue {
mir::Rvalue::Use(ref operand) => self.const_operand(operand, span)?,
mir::Rvalue::Repeat(ref elem, count) => {
let elem = self.const_operand(elem, span)?;
let size = count.as_u64();
assert_eq!(size as usize as u64, size);
let fields = vec![elem.llval; size as usize];
self.const_array(dest_ty, &fields)
}
mir::Rvalue::Aggregate(box mir::AggregateKind::Array(_), ref operands) => {
// Make sure to evaluate all operands to
// report as many errors as we possibly can.
let mut fields = Vec::with_capacity(operands.len());
let mut failure = Ok(());
for operand in operands {
match self.const_operand(operand, span) {
Ok(val) => fields.push(val.llval),
Err(err) => if failure.is_ok() { failure = Err(err); }
}
}
failure?;
self.const_array(dest_ty, &fields)
}
mir::Rvalue::Aggregate(ref kind, ref operands) => {
// Make sure to evaluate all operands to
// report as many errors as we possibly can.
let mut fields = Vec::with_capacity(operands.len());
let mut failure = Ok(());
for operand in operands {
match self.const_operand(operand, span) {
Ok(val) => fields.push(val),
Err(err) => if failure.is_ok() { failure = Err(err); }
}
}
failure?;
trans_const_adt(self.cx, dest_ty, kind, &fields)
}
mir::Rvalue::Cast(ref kind, ref source, cast_ty) => {
let operand = self.const_operand(source, span)?;
let cast_ty = self.monomorphize(&cast_ty);
let val = match *kind {
mir::CastKind::ReifyFnPointer => {
match operand.ty.sty {
ty::TyFnDef(def_id, substs) => {
callee::resolve_and_get_fn(self.cx, def_id, substs)
}
_ => {
span_bug!(span, "{} cannot be reified to a fn ptr",
operand.ty)
}
}
}
mir::CastKind::ClosureFnPointer => {
match operand.ty.sty {
ty::TyClosure(def_id, substs) => {
// Get the def_id for FnOnce::call_once
let fn_once = tcx.lang_items().fn_once_trait().unwrap();
let call_once = tcx
.global_tcx().associated_items(fn_once)
.find(|it| it.kind == ty::AssociatedKind::Method)
.unwrap().def_id;
// Now create its substs [Closure, Tuple]
let input = substs.closure_sig(def_id, tcx).input(0);
let input = tcx.erase_late_bound_regions_and_normalize(&input);
let substs = tcx.mk_substs([operand.ty, input]
.iter().cloned().map(Kind::from));
callee::resolve_and_get_fn(self.cx, call_once, substs)
}
_ => {
bug!("{} cannot be cast to a fn ptr", operand.ty)
}
}
}
mir::CastKind::UnsafeFnPointer => {
// this is a no-op at the LLVM level
operand.llval
}
mir::CastKind::Unsize => {
let pointee_ty = operand.ty.builtin_deref(true)
.expect("consts: unsizing got non-pointer type").ty;
let (base, old_info) = if !self.cx.type_is_sized(pointee_ty) {
// Normally, the source is a thin pointer and we are
// adding extra info to make a fat pointer. The exception
// is when we are upcasting an existing object fat pointer
// to use a different vtable. In that case, we want to
// load out the original data pointer so we can repackage
// it.
let (base, extra) = operand.get_fat_ptr(self.cx);
(base, Some(extra))
} else {
(operand.llval, None)
};
let unsized_ty = cast_ty.builtin_deref(true)
.expect("consts: unsizing got non-pointer target type").ty;
let ptr_ty = self.cx.layout_of(unsized_ty).llvm_type(self.cx).ptr_to();
let base = consts::ptrcast(base, ptr_ty);
let info = base::unsized_info(self.cx, pointee_ty,
unsized_ty, old_info);
if old_info.is_none() {
let prev_const = self.cx.const_unsized.borrow_mut()
.insert(base, operand.llval);
assert!(prev_const.is_none() || prev_const == Some(operand.llval));
}
C_fat_ptr(self.cx, base, info)
}
mir::CastKind::Misc if self.cx.layout_of(operand.ty).is_llvm_immediate() => {
let r_t_in = CastTy::from_ty(operand.ty).expect("bad input type for cast");
let r_t_out = CastTy::from_ty(cast_ty).expect("bad output type for cast");
let cast_layout = self.cx.layout_of(cast_ty);
assert!(cast_layout.is_llvm_immediate());
let ll_t_out = cast_layout.immediate_llvm_type(self.cx);
let llval = operand.llval;
let mut signed = false;
let l = self.cx.layout_of(operand.ty);
if let layout::Abi::Scalar(ref scalar) = l.abi {
if let layout::Int(_, true) = scalar.value {
signed = true;
}
}
unsafe {
match (r_t_in, r_t_out) {
(CastTy::Int(_), CastTy::Int(_)) => {
let s = signed as llvm::Bool;
llvm::LLVMConstIntCast(llval, ll_t_out.to_ref(), s)
}
(CastTy::Int(_), CastTy::Float) => {
cast_const_int_to_float(self.cx, llval, signed, ll_t_out)
}
(CastTy::Float, CastTy::Float) => {
llvm::LLVMConstFPCast(llval, ll_t_out.to_ref())
}
(CastTy::Float, CastTy::Int(IntTy::I)) => {
cast_const_float_to_int(self.cx, &operand,
true, ll_t_out, span)
}
(CastTy::Float, CastTy::Int(_)) => {
cast_const_float_to_int(self.cx, &operand,
false, ll_t_out, span)
}
(CastTy::Ptr(_), CastTy::Ptr(_)) |
(CastTy::FnPtr, CastTy::Ptr(_)) |
(CastTy::RPtr(_), CastTy::Ptr(_)) => {
consts::ptrcast(llval, ll_t_out)
}
(CastTy::Int(_), CastTy::Ptr(_)) => {
let s = signed as llvm::Bool;
let usize_llval = llvm::LLVMConstIntCast(llval,
self.cx.isize_ty.to_ref(), s);
llvm::LLVMConstIntToPtr(usize_llval, ll_t_out.to_ref())
}
(CastTy::Ptr(_), CastTy::Int(_)) |
(CastTy::FnPtr, CastTy::Int(_)) => {
llvm::LLVMConstPtrToInt(llval, ll_t_out.to_ref())
}
_ => bug!("unsupported cast: {:?} to {:?}", operand.ty, cast_ty)
}
}
}
mir::CastKind::Misc => { // Casts from a fat-ptr.
let l = self.cx.layout_of(operand.ty);
let cast = self.cx.layout_of(cast_ty);
if l.is_llvm_scalar_pair() {
let (data_ptr, meta) = operand.get_fat_ptr(self.cx);
if cast.is_llvm_scalar_pair() {
let data_cast = consts::ptrcast(data_ptr,
cast.scalar_pair_element_llvm_type(self.cx, 0));
C_fat_ptr(self.cx, data_cast, meta)
} else { // cast to thin-ptr
// Cast of fat-ptr to thin-ptr is an extraction of data-ptr and
// pointer-cast of that pointer to desired pointer type.
let llcast_ty = cast.immediate_llvm_type(self.cx);
consts::ptrcast(data_ptr, llcast_ty)
}
} else {
bug!("Unexpected non-fat-pointer operand")
}
}
};
Const::new(val, cast_ty)
}
mir::Rvalue::Ref(_, bk, ref place) => {
let tr_place = self.const_place(place, span)?;
let ty = tr_place.ty;
let ref_ty = tcx.mk_ref(tcx.types.re_erased,
ty::TypeAndMut { ty: ty, mutbl: bk.to_mutbl_lossy() });
let base = match tr_place.base {
Base::Value(llval) => {
// FIXME: may be wrong for &*(&simd_vec as &fmt::Debug)
let align = if self.cx.type_is_sized(ty) {
self.cx.align_of(ty)
} else {
self.cx.tcx.data_layout.pointer_align
};
if bk == mir::BorrowKind::Mut {
consts::addr_of_mut(self.cx, llval, align, "ref_mut")
} else {
consts::addr_of(self.cx, llval, align, "ref")
}
}
Base::Str(llval) |
Base::Static(llval) => llval
};
let ptr = if self.cx.type_is_sized(ty) {
base
} else {
C_fat_ptr(self.cx, base, tr_place.llextra)
};
Const::new(ptr, ref_ty)
}
mir::Rvalue::Len(ref place) => {
let tr_place = self.const_place(place, span)?;
Const::new(tr_place.len(self.cx), tcx.types.usize)
}
mir::Rvalue::BinaryOp(op, ref lhs, ref rhs) => {
let lhs = self.const_operand(lhs, span)?;
let rhs = self.const_operand(rhs, span)?;
let ty = lhs.ty;
let binop_ty = op.ty(tcx, lhs.ty, rhs.ty);
let (lhs, rhs) = (lhs.llval, rhs.llval);
Const::new(const_scalar_binop(op, lhs, rhs, ty), binop_ty)
}
mir::Rvalue::CheckedBinaryOp(op, ref lhs, ref rhs) => {
let lhs = self.const_operand(lhs, span)?;
let rhs = self.const_operand(rhs, span)?;
let ty = lhs.ty;
let val_ty = op.ty(tcx, lhs.ty, rhs.ty);
let binop_ty = tcx.intern_tup(&[val_ty, tcx.types.bool], false);
let (lhs, rhs) = (lhs.llval, rhs.llval);
assert!(!ty.is_fp());
match const_scalar_checked_binop(tcx, op, lhs, rhs, ty) {
Some((llval, of)) => {
trans_const_adt(self.cx, binop_ty, &mir::AggregateKind::Tuple, &[
Const::new(llval, val_ty),
Const::new(C_bool(self.cx, of), tcx.types.bool)
])
}
None => {
span_bug!(span, "{:?} got non-integer operands: {:?} and {:?}",
rvalue, Value(lhs), Value(rhs));
}
}
}
mir::Rvalue::UnaryOp(op, ref operand) => {
let operand = self.const_operand(operand, span)?;
let lloperand = operand.llval;
let llval = match op {
mir::UnOp::Not => {
unsafe {
llvm::LLVMConstNot(lloperand)
}
}
mir::UnOp::Neg => {
let is_float = operand.ty.is_fp();
unsafe {
if is_float {
llvm::LLVMConstFNeg(lloperand)
} else {
llvm::LLVMConstNeg(lloperand)
}
}
}
};
Const::new(llval, operand.ty)
}
mir::Rvalue::NullaryOp(mir::NullOp::SizeOf, ty) => {
assert!(self.cx.type_is_sized(ty));
let llval = C_usize(self.cx, self.cx.size_of(ty).bytes());
Const::new(llval, tcx.types.usize)
}
_ => span_bug!(span, "{:?} in constant", rvalue)
};
debug!("const_rvalue({:?}: {:?} @ {:?}) = {:?}", rvalue, dest_ty, span, val);
Ok(val)
}
}
fn to_const_int(value: ValueRef, t: Ty, tcx: TyCtxt) -> Option<ConstInt> {
match t.sty {
ty::TyInt(int_type) => const_to_opt_u128(value, true)
.and_then(|input| ConstInt::new_signed(input as i128, int_type,
tcx.sess.target.isize_ty)),
ty::TyUint(uint_type) => const_to_opt_u128(value, false)
.and_then(|input| ConstInt::new_unsigned(input, uint_type,
tcx.sess.target.usize_ty)),
_ => None
}
}
pub fn const_scalar_binop(op: mir::BinOp,
lhs: ValueRef,
rhs: ValueRef,
input_ty: Ty) -> ValueRef {
assert!(!input_ty.is_simd());
let is_float = input_ty.is_fp();
let signed = input_ty.is_signed();
unsafe {
match op {
mir::BinOp::Add if is_float => llvm::LLVMConstFAdd(lhs, rhs),
mir::BinOp::Add => llvm::LLVMConstAdd(lhs, rhs),
mir::BinOp::Sub if is_float => llvm::LLVMConstFSub(lhs, rhs),
mir::BinOp::Sub => llvm::LLVMConstSub(lhs, rhs),
mir::BinOp::Mul if is_float => llvm::LLVMConstFMul(lhs, rhs),
mir::BinOp::Mul => llvm::LLVMConstMul(lhs, rhs),
mir::BinOp::Div if is_float => llvm::LLVMConstFDiv(lhs, rhs),
mir::BinOp::Div if signed => llvm::LLVMConstSDiv(lhs, rhs),