1 use rustc::ty::adjustment::PointerCast;
5 struct PrintOnPanic<F: Fn() -> String>(F);
6 impl<F: Fn() -> String> Drop for PrintOnPanic<F> {
8 if ::std::thread::panicking() {
9 println!("{}", (self.0)());
14 pub fn trans_mono_item<'a, 'clif, 'tcx: 'a, B: Backend + 'static>(
15 cx: &mut crate::CodegenCx<'a, 'clif, 'tcx, B>,
16 mono_item: MonoItem<'tcx>,
21 MonoItem::Fn(inst) => {
23 PrintOnPanic(|| format!("{:?} {}", inst, tcx.symbol_name(inst).as_str()));
24 debug_assert!(!inst.substs.needs_infer());
25 let _mir_guard = PrintOnPanic(|| {
28 | InstanceDef::DropGlue(_, _)
29 | InstanceDef::Virtual(_, _)
30 if inst.def_id().krate == LOCAL_CRATE =>
32 let mut mir = ::std::io::Cursor::new(Vec::new());
33 crate::rustc_mir::util::write_mir_pretty(
39 String::from_utf8(mir.into_inner()).unwrap()
42 // FIXME fix write_mir_pretty for these instances
43 format!("{:#?}", tcx.instance_mir(inst.def))
48 trans_fn(cx, inst, linkage);
50 MonoItem::Static(def_id) => {
51 crate::constant::codegen_static(&mut cx.ccx, def_id);
53 MonoItem::GlobalAsm(node_id) => tcx
55 .fatal(&format!("Unimplemented global asm mono item {:?}", node_id)),
59 fn trans_fn<'a, 'clif, 'tcx: 'a, B: Backend + 'static>(
60 cx: &mut crate::CodegenCx<'a, 'clif, 'tcx, B>,
61 instance: Instance<'tcx>,
67 let mir = tcx.instance_mir(instance.def);
69 // Step 2. Check fn sig for u128 and i128 and replace those functions with a trap.
71 // FIXME implement u128 and i128 support
73 // Step 2a. Check sig for u128 and i128
74 let fn_sig = tcx.normalize_erasing_late_bound_regions(ParamEnv::reveal_all(), &instance.fn_sig(tcx));
76 struct UI128Visitor<'a, 'tcx: 'a>(TyCtxt<'a, 'tcx, 'tcx>, bool);
78 impl<'a, 'tcx: 'a> rustc::ty::fold::TypeVisitor<'tcx> for UI128Visitor<'a, 'tcx> {
79 fn visit_ty(&mut self, t: Ty<'tcx>) -> bool {
80 if t.sty == self.0.types.u128.sty || t.sty == self.0.types.i128.sty {
82 return false; // stop visiting
85 t.super_visit_with(self)
89 let mut visitor = UI128Visitor(tcx, false);
90 fn_sig.visit_with(&mut visitor);
92 // Step 2b. If found replace function with a trap.
94 tcx.sess.warn("u128 and i128 are not yet supported. \
95 Functions using these as args will be replaced with a trap.");
97 // Step 2b1. Declare function with fake signature
99 params: vec![AbiParam::new(types::INVALID)],
101 call_conv: CallConv::Fast,
103 let name = tcx.symbol_name(instance).as_str();
104 let func_id = cx.module.declare_function(&*name, linkage, &sig).unwrap();
106 // Step 2b2. Create trapping function
107 let mut func = Function::with_name_signature(ExternalName::user(0, 0), sig);
108 let mut func_ctx = FunctionBuilderContext::new();
109 let mut bcx = FunctionBuilder::new(&mut func, &mut func_ctx);
110 let start_ebb = bcx.create_ebb();
111 bcx.append_ebb_params_for_function_params(start_ebb);
112 bcx.switch_to_block(start_ebb);
114 let mut fx = FunctionCx {
117 pointer_type: pointer_ty(tcx),
123 ebb_map: HashMap::new(),
124 local_map: HashMap::new(),
126 clif_comments: crate::pretty_clif::CommentWriter::new(tcx, instance),
127 constants: &mut cx.ccx,
128 caches: &mut cx.caches,
129 source_info_set: indexmap::IndexSet::new(),
132 crate::trap::trap_unreachable(&mut fx, "[unimplemented] Called function with u128 or i128 as argument.");
133 fx.bcx.seal_all_blocks();
136 // Step 2b3. Define function
137 cx.caches.context.func = func;
139 .define_function(func_id, &mut cx.caches.context)
141 cx.caches.context.clear();
146 // Step 3. Declare function
147 let (name, sig) = get_function_name_and_sig(tcx, instance, false);
148 let func_id = cx.module.declare_function(&name, linkage, &sig).unwrap();
149 let mut debug_context = cx
152 .map(|debug_context| FunctionDebugContext::new(tcx, debug_context, mir, &name, &sig));
154 // Step 4. Make FunctionBuilder
155 let mut func = Function::with_name_signature(ExternalName::user(0, 0), sig);
156 let mut func_ctx = FunctionBuilderContext::new();
157 let mut bcx = FunctionBuilder::new(&mut func, &mut func_ctx);
159 // Step 5. Predefine ebb's
160 let start_ebb = bcx.create_ebb();
161 let mut ebb_map: HashMap<BasicBlock, Ebb> = HashMap::new();
162 for (bb, _bb_data) in mir.basic_blocks().iter_enumerated() {
163 ebb_map.insert(bb, bcx.create_ebb());
166 // Step 6. Make FunctionCx
167 let pointer_type = cx.module.target_config().pointer_type();
168 let clif_comments = crate::pretty_clif::CommentWriter::new(tcx, instance);
170 let mut fx = FunctionCx {
180 local_map: HashMap::new(),
183 constants: &mut cx.ccx,
184 caches: &mut cx.caches,
185 source_info_set: indexmap::IndexSet::new(),
188 // Step 7. Codegen function
189 with_unimpl_span(fx.mir.span, || {
190 crate::abi::codegen_fn_prelude(&mut fx, start_ebb);
191 codegen_fn_content(&mut fx);
193 let source_info_set = fx.source_info_set.clone();
195 // Step 8. Write function to file for debugging
196 #[cfg(debug_assertions)]
197 fx.write_clif_file();
199 // Step 9. Verify function
200 verify_func(tcx, fx.clif_comments, &func);
202 // Step 10. Define function
203 cx.caches.context.func = func;
205 .define_function(func_id, &mut cx.caches.context)
208 // Step 11. Define debuginfo for function
209 let context = &cx.caches.context;
210 let isa = cx.module.isa();
213 .map(|x| x.define(tcx, context, isa, &source_info_set));
215 // Step 12. Clear context to make it usable for the next function
216 cx.caches.context.clear();
219 fn verify_func(tcx: TyCtxt, writer: crate::pretty_clif::CommentWriter, func: &Function) {
220 let flags = settings::Flags::new(settings::builder());
221 match ::cranelift::codegen::verify_function(&func, &flags) {
224 tcx.sess.err(&format!("{:?}", err));
225 let pretty_error = ::cranelift::codegen::print_errors::pretty_verifier_error(
228 Some(Box::new(&writer)),
232 .fatal(&format!("cranelift verify error:\n{}", pretty_error));
237 fn codegen_fn_content<'a, 'tcx: 'a>(fx: &mut FunctionCx<'a, 'tcx, impl Backend>) {
238 for (bb, bb_data) in fx.mir.basic_blocks().iter_enumerated() {
239 if bb_data.is_cleanup {
240 // Unwinding after panicking is not supported
244 let ebb = fx.get_ebb(bb);
245 fx.bcx.switch_to_block(ebb);
248 for stmt in &bb_data.statements {
249 fx.set_debug_loc(stmt.source_info);
250 trans_stmt(fx, ebb, stmt);
253 #[cfg(debug_assertions)]
255 let mut terminator_head = "\n".to_string();
259 .fmt_head(&mut terminator_head)
261 let inst = fx.bcx.func.layout.last_inst(ebb).unwrap();
262 fx.add_comment(inst, terminator_head);
265 fx.set_debug_loc(bb_data.terminator().source_info);
267 match &bb_data.terminator().kind {
268 TerminatorKind::Goto { target } => {
269 let ebb = fx.get_ebb(*target);
270 fx.bcx.ins().jump(ebb, &[]);
272 TerminatorKind::Return => {
273 crate::abi::codegen_return(fx);
275 TerminatorKind::Assert {
282 let cond = trans_operand(fx, cond).load_scalar(fx);
283 // TODO HACK brz/brnz for i8/i16 is not yet implemented
284 let cond = fx.bcx.ins().uextend(types::I32, cond);
285 let target = fx.get_ebb(*target);
287 fx.bcx.ins().brnz(cond, target, &[]);
289 fx.bcx.ins().brz(cond, target, &[]);
291 trap_panic(fx, format!("[panic] Assert {:?} failed.", msg));
294 TerminatorKind::SwitchInt {
300 let discr = trans_operand(fx, discr).load_scalar(fx);
301 let mut switch = ::cranelift::frontend::Switch::new();
302 for (i, value) in values.iter().enumerate() {
303 let ebb = fx.get_ebb(targets[i]);
304 switch.set_entry(*value as u64, ebb);
306 let otherwise_ebb = fx.get_ebb(targets[targets.len() - 1]);
307 switch.emit(&mut fx.bcx, discr, otherwise_ebb);
309 TerminatorKind::Call {
316 crate::abi::codegen_terminator_call(fx, func, args, destination);
318 TerminatorKind::Resume | TerminatorKind::Abort => {
319 trap_unreachable(fx, "[corruption] Unwinding bb reached.");
321 TerminatorKind::Unreachable => {
322 trap_unreachable(fx, "[corruption] Hit unreachable code.");
324 TerminatorKind::Yield { .. }
325 | TerminatorKind::FalseEdges { .. }
326 | TerminatorKind::FalseUnwind { .. }
327 | TerminatorKind::DropAndReplace { .. }
328 | TerminatorKind::GeneratorDrop => {
329 bug!("shouldn't exist at trans {:?}", bb_data.terminator());
331 TerminatorKind::Drop {
336 let ty = location.ty(fx.mir, fx.tcx).ty;
337 let ty = fx.monomorphize(&ty);
338 let drop_fn = crate::rustc_mir::monomorphize::resolve_drop_in_place(fx.tcx, ty);
340 if let ty::InstanceDef::DropGlue(_, None) = drop_fn.def {
341 // we don't actually need to drop anything
343 let drop_place = trans_place(fx, location);
344 let drop_fn_ty = drop_fn.ty(fx.tcx);
347 crate::abi::codegen_drop(fx, drop_place, drop_fn_ty);
350 let arg_place = CPlace::new_stack_slot(
353 &ty::RegionKind::ReErased,
356 mutbl: crate::rustc::hir::Mutability::MutMutable,
360 drop_place.write_place_ref(fx, arg_place);
361 let arg_value = arg_place.to_cvalue(fx);
362 crate::abi::codegen_call_inner(
373 let target_ebb = fx.get_ebb(*target);
374 fx.bcx.ins().jump(target_ebb, &[]);
379 fx.bcx.seal_all_blocks();
383 fn trans_stmt<'a, 'tcx: 'a>(
384 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
386 stmt: &Statement<'tcx>,
388 let _print_guard = PrintOnPanic(|| format!("stmt {:?}", stmt));
390 fx.set_debug_loc(stmt.source_info);
392 #[cfg(debug_assertions)]
394 StatementKind::StorageLive(..) | StatementKind::StorageDead(..) => {} // Those are not very useful
396 let inst = fx.bcx.func.layout.last_inst(cur_ebb).unwrap();
397 fx.add_comment(inst, format!("{:?}", stmt));
402 StatementKind::SetDiscriminant {
406 let place = trans_place(fx, place);
407 let layout = place.layout();
408 if layout.for_variant(&*fx, *variant_index).abi == layout::Abi::Uninhabited {
411 match layout.variants {
412 layout::Variants::Single { index } => {
413 assert_eq!(index, *variant_index);
415 layout::Variants::Multiple {
418 discr_kind: layout::DiscriminantKind::Tag,
421 let ptr = place.place_field(fx, mir::Field::new(discr_index));
426 .discriminant_for_variant(fx.tcx, *variant_index)
428 let discr = CValue::const_val(fx, ptr.layout().ty, to as u64 as i64);
429 ptr.write_cvalue(fx, discr);
431 layout::Variants::Multiple {
434 discr_kind: layout::DiscriminantKind::Niche {
441 if *variant_index != dataful_variant {
442 let niche = place.place_field(fx, mir::Field::new(discr_index));
443 //let niche_llty = niche.layout.immediate_llvm_type(bx.cx);
445 ((variant_index.as_u32() - niche_variants.start().as_u32()) as u128)
446 .wrapping_add(niche_start);
447 // FIXME(eddyb) Check the actual primitive type here.
448 let niche_llval = if niche_value == 0 {
449 CValue::const_val(fx, niche.layout().ty, 0)
451 CValue::const_val(fx, niche.layout().ty, niche_value as u64 as i64)
453 niche.write_cvalue(fx, niche_llval);
458 StatementKind::Assign(to_place, rval) => {
459 let lval = trans_place(fx, to_place);
460 let dest_layout = lval.layout();
462 Rvalue::Use(operand) => {
463 let val = trans_operand(fx, operand);
464 lval.write_cvalue(fx, val);
466 Rvalue::Ref(_, _, place) => {
467 let place = trans_place(fx, place);
468 place.write_place_ref(fx, lval);
470 Rvalue::BinaryOp(bin_op, lhs, rhs) => {
471 let ty = fx.monomorphize(&lhs.ty(fx.mir, fx.tcx));
472 let lhs = trans_operand(fx, lhs);
473 let rhs = trans_operand(fx, rhs);
475 let res = match ty.sty {
476 ty::Bool => trans_bool_binop(fx, *bin_op, lhs, rhs, lval.layout().ty),
478 trans_int_binop(fx, *bin_op, lhs, rhs, lval.layout().ty, false)
481 trans_int_binop(fx, *bin_op, lhs, rhs, lval.layout().ty, true)
483 ty::Float(_) => trans_float_binop(fx, *bin_op, lhs, rhs, lval.layout().ty),
484 ty::Char => trans_char_binop(fx, *bin_op, lhs, rhs, lval.layout().ty),
485 ty::RawPtr(..) => trans_ptr_binop(fx, *bin_op, lhs, rhs, lval.layout().ty),
486 ty::FnPtr(..) => trans_ptr_binop(fx, *bin_op, lhs, rhs, lval.layout().ty),
487 _ => unimplemented!("binop {:?} for {:?}", bin_op, ty),
489 lval.write_cvalue(fx, res);
491 Rvalue::CheckedBinaryOp(bin_op, lhs, rhs) => {
492 let ty = fx.monomorphize(&lhs.ty(fx.mir, fx.tcx));
493 let lhs = trans_operand(fx, lhs);
494 let rhs = trans_operand(fx, rhs);
496 let res = match ty.sty {
498 trans_checked_int_binop(fx, *bin_op, lhs, rhs, lval.layout().ty, false)
501 trans_checked_int_binop(fx, *bin_op, lhs, rhs, lval.layout().ty, true)
503 _ => unimplemented!("checked binop {:?} for {:?}", bin_op, ty),
505 lval.write_cvalue(fx, res);
507 Rvalue::UnaryOp(un_op, operand) => {
508 let operand = trans_operand(fx, operand);
509 let layout = operand.layout();
510 let val = operand.load_scalar(fx);
511 let res = match un_op {
513 match layout.ty.sty {
515 let val = fx.bcx.ins().uextend(types::I32, val); // WORKAROUND for CraneStation/cranelift#466
516 let res = fx.bcx.ins().icmp_imm(IntCC::Equal, val, 0);
517 fx.bcx.ins().bint(types::I8, res)
519 ty::Uint(_) | ty::Int(_) => fx.bcx.ins().bnot(val),
520 _ => unimplemented!("un op Not for {:?}", layout.ty),
523 UnOp::Neg => match layout.ty.sty {
525 let clif_ty = fx.clif_type(layout.ty).unwrap();
526 let zero = fx.bcx.ins().iconst(clif_ty, 0);
527 fx.bcx.ins().isub(zero, val)
529 ty::Float(_) => fx.bcx.ins().fneg(val),
530 _ => unimplemented!("un op Neg for {:?}", layout.ty),
533 lval.write_cvalue(fx, CValue::ByVal(res, layout));
535 Rvalue::Cast(CastKind::Pointer(PointerCast::ReifyFnPointer), operand, ty) => {
536 let layout = fx.layout_of(ty);
538 .monomorphize(&operand.ty(&fx.mir.local_decls, fx.tcx))
541 ty::FnDef(def_id, substs) => {
542 let func_ref = fx.get_function_ref(
543 Instance::resolve(fx.tcx, ParamEnv::reveal_all(), def_id, substs)
546 let func_addr = fx.bcx.ins().func_addr(fx.pointer_type, func_ref);
547 lval.write_cvalue(fx, CValue::ByVal(func_addr, layout));
549 _ => bug!("Trying to ReifyFnPointer on non FnDef {:?}", ty),
552 Rvalue::Cast(CastKind::Pointer(PointerCast::UnsafeFnPointer), operand, ty)
553 | Rvalue::Cast(CastKind::Pointer(PointerCast::MutToConstPointer), operand, ty) => {
554 let operand = trans_operand(fx, operand);
555 let layout = fx.layout_of(ty);
556 lval.write_cvalue(fx, operand.unchecked_cast_to(layout));
558 Rvalue::Cast(CastKind::Misc, operand, to_ty) => {
559 let operand = trans_operand(fx, operand);
560 let from_ty = operand.layout().ty;
562 fn is_fat_ptr<'a, 'tcx: 'a>(fx: &FunctionCx<'a, 'tcx, impl Backend>, ty: Ty<'tcx>) -> bool {
565 .map(|ty::TypeAndMut {ty: pointee_ty, mutbl: _ }| fx.layout_of(pointee_ty).is_unsized())
569 if is_fat_ptr(fx, from_ty) {
570 if is_fat_ptr(fx, to_ty) {
571 // fat-ptr -> fat-ptr
572 lval.write_cvalue(fx, operand.unchecked_cast_to(dest_layout));
574 // fat-ptr -> thin-ptr
575 let (ptr, _extra) = operand.load_scalar_pair(fx);
576 lval.write_cvalue(fx, CValue::ByVal(ptr, dest_layout))
578 } else if let ty::Adt(adt_def, _substs) = from_ty.sty {
579 // enum -> discriminant value
580 assert!(adt_def.is_enum());
582 ty::Uint(_) | ty::Int(_) => {},
583 _ => unreachable!("cast adt {} -> {}", from_ty, to_ty),
586 // FIXME avoid forcing to stack
588 CPlace::Addr(operand.force_stack(fx), None, operand.layout());
589 let discr = trans_get_discriminant(fx, place, fx.layout_of(to_ty));
590 lval.write_cvalue(fx, discr);
592 let from_clif_ty = fx.clif_type(from_ty).unwrap();
593 let to_clif_ty = fx.clif_type(to_ty).unwrap();
594 let from = operand.load_scalar(fx);
596 let signed = match from_ty.sty {
597 ty::Ref(..) | ty::RawPtr(..) | ty::FnPtr(..) | ty::Char | ty::Uint(..) | ty::Bool => false,
599 ty::Float(..) => false, // `signed` is unused for floats
600 _ => panic!("{}", from_ty),
603 let res = if from_clif_ty.is_int() && to_clif_ty.is_int() {
604 // int-like -> int-like
605 crate::common::clif_intcast(
611 } else if from_clif_ty.is_int() && to_clif_ty.is_float() {
613 // FIXME missing encoding for fcvt_from_sint.f32.i8
614 let from = if from_clif_ty == types::I8 || from_clif_ty == types::I16 {
615 fx.bcx.ins().uextend(types::I32, from)
620 fx.bcx.ins().fcvt_from_sint(to_clif_ty, from)
622 fx.bcx.ins().fcvt_from_uint(to_clif_ty, from)
624 } else if from_clif_ty.is_float() && to_clif_ty.is_int() {
626 let from = operand.load_scalar(fx);
628 fx.bcx.ins().fcvt_to_sint_sat(to_clif_ty, from)
630 fx.bcx.ins().fcvt_to_uint_sat(to_clif_ty, from)
632 } else if from_clif_ty.is_float() && to_clif_ty.is_float() {
634 match (from_clif_ty, to_clif_ty) {
635 (types::F32, types::F64) => {
636 fx.bcx.ins().fpromote(types::F64, from)
638 (types::F64, types::F32) => {
639 fx.bcx.ins().fdemote(types::F32, from)
644 unimpl!("rval misc {:?} {:?}", from_ty, to_ty)
646 lval.write_cvalue(fx, CValue::ByVal(res, dest_layout));
649 Rvalue::Cast(CastKind::Pointer(PointerCast::ClosureFnPointer(_)), operand, _ty) => {
650 let operand = trans_operand(fx, operand);
651 match operand.layout().ty.sty {
652 ty::Closure(def_id, substs) => {
653 let instance = rustc_mir::monomorphize::resolve_closure(
657 ty::ClosureKind::FnOnce,
659 let func_ref = fx.get_function_ref(instance);
660 let func_addr = fx.bcx.ins().func_addr(fx.pointer_type, func_ref);
661 lval.write_cvalue(fx, CValue::ByVal(func_addr, lval.layout()));
664 bug!("{} cannot be cast to a fn ptr", operand.layout().ty)
668 Rvalue::Cast(CastKind::Pointer(PointerCast::Unsize), operand, _ty) => {
669 let operand = trans_operand(fx, operand);
670 operand.unsize_value(fx, lval);
672 Rvalue::Discriminant(place) => {
673 let place = trans_place(fx, place);
674 let discr = trans_get_discriminant(fx, place, dest_layout);
675 lval.write_cvalue(fx, discr);
677 Rvalue::Repeat(operand, times) => {
678 let operand = trans_operand(fx, operand);
680 let index = fx.bcx.ins().iconst(fx.pointer_type, i as i64);
681 let to = lval.place_index(fx, index);
682 to.write_cvalue(fx, operand);
685 Rvalue::Len(place) => {
686 let place = trans_place(fx, place);
687 let usize_layout = fx.layout_of(fx.tcx.types.usize);
688 let len = codegen_array_len(fx, place);
689 lval.write_cvalue(fx, CValue::ByVal(len, usize_layout));
691 Rvalue::NullaryOp(NullOp::Box, content_ty) => {
692 use rustc::middle::lang_items::ExchangeMallocFnLangItem;
694 let usize_type = fx.clif_type(fx.tcx.types.usize).unwrap();
695 let layout = fx.layout_of(content_ty);
696 let llsize = fx.bcx.ins().iconst(usize_type, layout.size.bytes() as i64);
700 .iconst(usize_type, layout.align.abi.bytes() as i64);
701 let box_layout = fx.layout_of(fx.tcx.mk_box(content_ty));
704 let def_id = match fx.tcx.lang_items().require(ExchangeMallocFnLangItem) {
709 .fatal(&format!("allocation of `{}` {}", box_layout.ty, s));
712 let instance = ty::Instance::mono(fx.tcx, def_id);
713 let func_ref = fx.get_function_ref(instance);
714 let call = fx.bcx.ins().call(func_ref, &[llsize, llalign]);
715 let ptr = fx.bcx.inst_results(call)[0];
716 lval.write_cvalue(fx, CValue::ByVal(ptr, box_layout));
718 Rvalue::NullaryOp(NullOp::SizeOf, ty) => {
722 .is_sized(fx.tcx.at(DUMMY_SP), ParamEnv::reveal_all()));
723 let ty_size = fx.layout_of(ty).size.bytes();
724 let val = CValue::const_val(fx, fx.tcx.types.usize, ty_size as i64);
725 lval.write_cvalue(fx, val);
727 Rvalue::Aggregate(kind, operands) => match **kind {
728 AggregateKind::Array(_ty) => {
729 for (i, operand) in operands.into_iter().enumerate() {
730 let operand = trans_operand(fx, operand);
731 let index = fx.bcx.ins().iconst(fx.pointer_type, i as i64);
732 let to = lval.place_index(fx, index);
733 to.write_cvalue(fx, operand);
736 _ => unimpl!("shouldn't exist at trans {:?}", rval),
740 StatementKind::StorageLive(_)
741 | StatementKind::StorageDead(_)
743 | StatementKind::FakeRead(..)
744 | StatementKind::Retag { .. }
745 | StatementKind::AscribeUserType(..) => {}
747 StatementKind::InlineAsm { .. } => unimpl!("Inline assembly is not supported"),
751 fn codegen_array_len<'a, 'tcx: 'a>(
752 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
755 match place.layout().ty.sty {
756 ty::Array(_elem_ty, len) => {
757 let len = crate::constant::force_eval_const(fx, len).unwrap_usize(fx.tcx) as i64;
758 fx.bcx.ins().iconst(fx.pointer_type, len)
760 ty::Slice(_elem_ty) => place
761 .to_addr_maybe_unsized(fx)
763 .expect("Length metadata for slice place"),
764 _ => bug!("Rvalue::Len({:?})", place),
768 pub fn trans_get_discriminant<'a, 'tcx: 'a>(
769 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
771 dest_layout: TyLayout<'tcx>,
773 let layout = place.layout();
775 if layout.abi == layout::Abi::Uninhabited {
776 return trap_unreachable_ret_value(fx, dest_layout, "[panic] Tried to get discriminant for uninhabited type.");
779 let (discr_scalar, discr_index, discr_kind) = match &layout.variants {
780 layout::Variants::Single { index } => {
781 let discr_val = layout
784 .map_or(index.as_u32() as u128, |def| {
785 def.discriminant_for_variant(fx.tcx, *index).val
787 return CValue::const_val(fx, dest_layout.ty, discr_val as u64 as i64);
789 layout::Variants::Multiple { discr, discr_index, discr_kind, variants: _ } => {
790 (discr, *discr_index, discr_kind)
794 let discr = place.place_field(fx, mir::Field::new(discr_index)).to_cvalue(fx);
795 let discr_ty = discr.layout().ty;
796 let lldiscr = discr.load_scalar(fx);
798 layout::DiscriminantKind::Tag => {
799 let signed = match discr_scalar.value {
800 layout::Int(_, signed) => signed,
803 let val = clif_intcast(fx, lldiscr, fx.clif_type(dest_layout.ty).unwrap(), signed);
804 return CValue::ByVal(val, dest_layout);
806 layout::DiscriminantKind::Niche {
811 let niche_llty = fx.clif_type(discr_ty).unwrap();
812 let dest_clif_ty = fx.clif_type(dest_layout.ty).unwrap();
813 if niche_variants.start() == niche_variants.end() {
817 .icmp_imm(IntCC::Equal, lldiscr, *niche_start as u64 as i64);
821 .iconst(dest_clif_ty, niche_variants.start().as_u32() as i64);
825 .iconst(dest_clif_ty, dataful_variant.as_u32() as i64);
826 let val = fx.bcx.ins().select(b, if_true, if_false);
827 return CValue::ByVal(val, dest_layout);
829 // Rebase from niche values to discriminant values.
830 let delta = niche_start.wrapping_sub(niche_variants.start().as_u32() as u128);
831 let delta = fx.bcx.ins().iconst(niche_llty, delta as u64 as i64);
832 let lldiscr = fx.bcx.ins().isub(lldiscr, delta);
833 let b = fx.bcx.ins().icmp_imm(
834 IntCC::UnsignedLessThanOrEqual,
836 niche_variants.end().as_u32() as i64,
839 clif_intcast(fx, lldiscr, fx.clif_type(dest_layout.ty).unwrap(), false);
843 .iconst(dest_clif_ty, dataful_variant.as_u32() as i64);
844 let val = fx.bcx.ins().select(b, if_true, if_false);
845 return CValue::ByVal(val, dest_layout);
851 macro_rules! binop_match {
852 (@single $fx:expr, $bug_fmt:expr, $var:expr, $signed:expr, $lhs:expr, $rhs:expr, $ret_ty:expr, bug) => {
853 bug!("binop {} on {} lhs: {:?} rhs: {:?}", stringify!($var), $bug_fmt, $lhs, $rhs)
855 (@single $fx:expr, $bug_fmt:expr, $var:expr, $signed:expr, $lhs:expr, $rhs:expr, $ret_ty:expr, icmp($cc:ident)) => {{
856 assert_eq!($fx.tcx.types.bool, $ret_ty);
857 let ret_layout = $fx.layout_of($ret_ty);
859 let b = $fx.bcx.ins().icmp(IntCC::$cc, $lhs, $rhs);
860 CValue::ByVal($fx.bcx.ins().bint(types::I8, b), ret_layout)
862 (@single $fx:expr, $bug_fmt:expr, $var:expr, $signed:expr, $lhs:expr, $rhs:expr, $ret_ty:expr, fcmp($cc:ident)) => {{
863 assert_eq!($fx.tcx.types.bool, $ret_ty);
864 let ret_layout = $fx.layout_of($ret_ty);
865 let b = $fx.bcx.ins().fcmp(FloatCC::$cc, $lhs, $rhs);
866 CValue::ByVal($fx.bcx.ins().bint(types::I8, b), ret_layout)
868 (@single $fx:expr, $bug_fmt:expr, $var:expr, $signed:expr, $lhs:expr, $rhs:expr, $ret_ty:expr, custom(|| $body:expr)) => {{
871 (@single $fx:expr, $bug_fmt:expr, $var:expr, $signed:expr, $lhs:expr, $rhs:expr, $ret_ty:expr, $name:ident) => {{
872 let ret_layout = $fx.layout_of($ret_ty);
873 CValue::ByVal($fx.bcx.ins().$name($lhs, $rhs), ret_layout)
876 $fx:expr, $bin_op:expr, $signed:expr, $lhs:expr, $rhs:expr, $ret_ty:expr, $bug_fmt:expr;
878 $var:ident ($sign:pat) $name:tt $( ( $($next:tt)* ) )? ;
881 let lhs = $lhs.load_scalar($fx);
882 let rhs = $rhs.load_scalar($fx);
883 match ($bin_op, $signed) {
885 (BinOp::$var, $sign) => binop_match!(@single $fx, $bug_fmt, $var, $signed, lhs, rhs, $ret_ty, $name $( ( $($next)* ) )?),
891 fn trans_bool_binop<'a, 'tcx: 'a>(
892 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
898 let res = binop_match! {
899 fx, bin_op, false, lhs, rhs, ty, "bool";
912 Lt (_) icmp(UnsignedLessThan);
913 Le (_) icmp(UnsignedLessThanOrEqual);
914 Ne (_) icmp(NotEqual);
915 Ge (_) icmp(UnsignedGreaterThanOrEqual);
916 Gt (_) icmp(UnsignedGreaterThan);
924 pub fn trans_int_binop<'a, 'tcx: 'a>(
925 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
932 if bin_op != BinOp::Shl && bin_op != BinOp::Shr {
936 "int binop requires lhs and rhs of same type"
940 fx, bin_op, signed, lhs, rhs, out_ty, "int/uint";
956 Lt (false) icmp(UnsignedLessThan);
957 Lt (true) icmp(SignedLessThan);
958 Le (false) icmp(UnsignedLessThanOrEqual);
959 Le (true) icmp(SignedLessThanOrEqual);
960 Ne (_) icmp(NotEqual);
961 Ge (false) icmp(UnsignedGreaterThanOrEqual);
962 Ge (true) icmp(SignedGreaterThanOrEqual);
963 Gt (false) icmp(UnsignedGreaterThan);
964 Gt (true) icmp(SignedGreaterThan);
970 pub fn trans_checked_int_binop<'a, 'tcx: 'a>(
971 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
973 in_lhs: CValue<'tcx>,
974 in_rhs: CValue<'tcx>,
978 if bin_op != BinOp::Shl && bin_op != BinOp::Shr {
982 "checked int binop requires lhs and rhs of same type"
986 let lhs = in_lhs.load_scalar(fx);
987 let rhs = in_rhs.load_scalar(fx);
988 let res = match bin_op {
989 BinOp::Add => fx.bcx.ins().iadd(lhs, rhs),
990 BinOp::Sub => fx.bcx.ins().isub(lhs, rhs),
991 BinOp::Mul => fx.bcx.ins().imul(lhs, rhs),
992 BinOp::Shl => fx.bcx.ins().ishl(lhs, rhs),
995 fx.bcx.ins().ushr(lhs, rhs)
997 fx.bcx.ins().sshr(lhs, rhs)
1001 "binop {:?} on checked int/uint lhs: {:?} rhs: {:?}",
1008 // TODO: check for overflow
1009 let has_overflow = fx.bcx.ins().iconst(types::I8, 0);
1011 let out_place = CPlace::new_stack_slot(fx, out_ty);
1012 let out_layout = out_place.layout();
1013 out_place.write_cvalue(fx, CValue::ByValPair(res, has_overflow, out_layout));
1015 out_place.to_cvalue(fx)
1018 fn trans_float_binop<'a, 'tcx: 'a>(
1019 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
1025 let res = binop_match! {
1026 fx, bin_op, false, lhs, rhs, ty, "float";
1032 assert_eq!(lhs.layout().ty, ty);
1033 assert_eq!(rhs.layout().ty, ty);
1035 ty::Float(FloatTy::F32) => fx.easy_call("fmodf", &[lhs, rhs], ty),
1036 ty::Float(FloatTy::F64) => fx.easy_call("fmod", &[lhs, rhs], ty),
1047 Lt (_) fcmp(LessThan);
1048 Le (_) fcmp(LessThanOrEqual);
1049 Ne (_) fcmp(NotEqual);
1050 Ge (_) fcmp(GreaterThanOrEqual);
1051 Gt (_) fcmp(GreaterThan);
1059 fn trans_char_binop<'a, 'tcx: 'a>(
1060 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
1066 let res = binop_match! {
1067 fx, bin_op, false, lhs, rhs, ty, "char";
1080 Lt (_) icmp(UnsignedLessThan);
1081 Le (_) icmp(UnsignedLessThanOrEqual);
1082 Ne (_) icmp(NotEqual);
1083 Ge (_) icmp(UnsignedGreaterThanOrEqual);
1084 Gt (_) icmp(UnsignedGreaterThan);
1092 fn trans_ptr_binop<'a, 'tcx: 'a>(
1093 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
1099 let not_fat = match lhs.layout().ty.sty {
1100 ty::RawPtr(TypeAndMut { ty, mutbl: _ }) => {
1101 ty.is_sized(fx.tcx.at(DUMMY_SP), ParamEnv::reveal_all())
1103 ty::FnPtr(..) => true,
1104 _ => bug!("trans_ptr_binop on non ptr"),
1107 if let BinOp::Offset = bin_op {
1108 let (base, offset) = (lhs, rhs.load_scalar(fx));
1109 let pointee_ty = base.layout().ty.builtin_deref(true).unwrap().ty;
1110 let pointee_size = fx.layout_of(pointee_ty).size.bytes();
1111 let ptr_diff = fx.bcx.ins().imul_imm(offset, pointee_size as i64);
1112 let base_val = base.load_scalar(fx);
1113 let res = fx.bcx.ins().iadd(base_val, ptr_diff);
1114 return CValue::ByVal(res, base.layout());
1118 fx, bin_op, false, lhs, rhs, ret_ty, "ptr";
1131 Lt (_) icmp(UnsignedLessThan);
1132 Le (_) icmp(UnsignedLessThanOrEqual);
1133 Ne (_) icmp(NotEqual);
1134 Ge (_) icmp(UnsignedGreaterThanOrEqual);
1135 Gt (_) icmp(UnsignedGreaterThan);
1137 Offset (_) bug; // Handled above
1140 let (lhs_ptr, lhs_extra) = lhs.load_scalar_pair(fx);
1141 let (rhs_ptr, rhs_extra) = rhs.load_scalar_pair(fx);
1142 let res = match bin_op {
1144 let ptr_eq = fx.bcx.ins().icmp(IntCC::Equal, lhs_ptr, rhs_ptr);
1145 let extra_eq = fx.bcx.ins().icmp(IntCC::Equal, lhs_extra, rhs_extra);
1146 fx.bcx.ins().band(ptr_eq, extra_eq)
1149 let ptr_ne = fx.bcx.ins().icmp(IntCC::NotEqual, lhs_ptr, rhs_ptr);
1150 let extra_ne = fx.bcx.ins().icmp(IntCC::NotEqual, lhs_extra, rhs_extra);
1151 fx.bcx.ins().bor(ptr_ne, extra_ne)
1153 _ => unimplemented!(
1154 "trans_ptr_binop({:?}, <fat ptr>, <fat ptr>) not implemented",
1159 assert_eq!(fx.tcx.types.bool, ret_ty);
1160 let ret_layout = fx.layout_of(ret_ty);
1161 CValue::ByVal(fx.bcx.ins().bint(types::I8, res), ret_layout)
1165 pub fn trans_place<'a, 'tcx: 'a>(
1166 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
1167 place: &Place<'tcx>,
1170 Place::Base(base) => match base {
1171 PlaceBase::Local(local) => fx.get_local_place(*local),
1172 PlaceBase::Static(static_) => match static_.kind {
1173 StaticKind::Static(def_id) => {
1174 crate::constant::codegen_static_ref(fx, def_id, static_.ty)
1176 StaticKind::Promoted(promoted) => {
1177 crate::constant::trans_promoted(fx, promoted, static_.ty)
1181 Place::Projection(projection) => {
1182 let base = trans_place(fx, &projection.base);
1183 match projection.elem {
1184 ProjectionElem::Deref => base.place_deref(fx),
1185 ProjectionElem::Field(field, _ty) => base.place_field(fx, field),
1186 ProjectionElem::Index(local) => {
1187 let index = fx.get_local_place(local).to_cvalue(fx).load_scalar(fx);
1188 base.place_index(fx, index)
1190 ProjectionElem::ConstantIndex {
1195 let index = if !from_end {
1196 fx.bcx.ins().iconst(fx.pointer_type, offset as i64)
1198 let len = codegen_array_len(fx, base);
1199 fx.bcx.ins().iadd_imm(len, -(offset as i64))
1201 base.place_index(fx, index)
1203 ProjectionElem::Subslice { from, to } => {
1204 // These indices are generated by slice patterns.
1205 // slice[from:-to] in Python terms.
1207 match base.layout().ty.sty {
1208 ty::Array(elem_ty, len) => {
1209 let elem_layout = fx.layout_of(elem_ty);
1210 let ptr = base.to_addr(fx);
1211 let len = crate::constant::force_eval_const(fx, len).unwrap_usize(fx.tcx);
1213 fx.bcx.ins().iadd_imm(ptr, elem_layout.size.bytes() as i64 * from as i64),
1215 fx.layout_of(fx.tcx.mk_array(elem_ty, len - from as u64 - to as u64)),
1218 ty::Slice(elem_ty) => {
1219 let elem_layout = fx.layout_of(elem_ty);
1220 let (ptr, len) = base.to_addr_maybe_unsized(fx);
1221 let len = len.unwrap();
1223 fx.bcx.ins().iadd_imm(ptr, elem_layout.size.bytes() as i64 * from as i64),
1224 Some(fx.bcx.ins().iadd_imm(len, -(from as i64 + to as i64))),
1228 _ => unreachable!(),
1231 ProjectionElem::Downcast(_adt_def, variant) => base.downcast_variant(fx, variant),
1237 pub fn trans_operand<'a, 'tcx>(
1238 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
1239 operand: &Operand<'tcx>,
1242 Operand::Move(place) | Operand::Copy(place) => {
1243 let cplace = trans_place(fx, place);
1244 cplace.to_cvalue(fx)
1246 Operand::Constant(const_) => crate::constant::trans_constant(fx, const_),