3 struct PrintOnPanic<F: Fn() -> String>(F);
4 impl<F: Fn() -> String> Drop for PrintOnPanic<F> {
6 if ::std::thread::panicking() {
7 println!("{}", (self.0)());
12 pub fn trans_mono_item<'a, 'clif, 'tcx: 'a, B: Backend + 'static>(
13 cx: &mut crate::CodegenCx<'a, 'clif, 'tcx, B>,
14 mono_item: MonoItem<'tcx>,
19 MonoItem::Fn(inst) => {
21 PrintOnPanic(|| format!("{:?} {}", inst, tcx.symbol_name(inst).as_str()));
22 debug_assert!(!inst.substs.needs_infer());
23 let _mir_guard = PrintOnPanic(|| {
26 | InstanceDef::DropGlue(_, _)
27 | InstanceDef::Virtual(_, _)
28 if inst.def_id().krate == LOCAL_CRATE =>
30 let mut mir = ::std::io::Cursor::new(Vec::new());
31 crate::rustc_mir::util::write_mir_pretty(
37 String::from_utf8(mir.into_inner()).unwrap()
40 // FIXME fix write_mir_pretty for these instances
41 format!("{:#?}", tcx.instance_mir(inst.def))
46 trans_fn(cx, inst, linkage);
48 MonoItem::Static(def_id) => {
49 crate::constant::codegen_static(&mut cx.ccx, def_id);
51 MonoItem::GlobalAsm(node_id) => tcx
53 .fatal(&format!("Unimplemented global asm mono item {:?}", node_id)),
57 fn trans_fn<'a, 'clif, 'tcx: 'a, B: Backend + 'static>(
58 cx: &mut crate::CodegenCx<'a, 'clif, 'tcx, B>,
59 instance: Instance<'tcx>,
65 let mir = tcx.instance_mir(instance.def);
67 // Step 2. Check fn sig for u128 and i128 and replace those functions with a trap.
69 // FIXME implement u128 and i128 support
71 // Step 2a. Check sig for u128 and i128
72 let fn_sig = tcx.normalize_erasing_late_bound_regions(ParamEnv::reveal_all(), &instance.fn_sig(tcx));
74 struct UI128Visitor<'a, 'tcx: 'a>(TyCtxt<'a, 'tcx, 'tcx>, bool);
76 impl<'a, 'tcx: 'a> rustc::ty::fold::TypeVisitor<'tcx> for UI128Visitor<'a, 'tcx> {
77 fn visit_ty(&mut self, t: Ty<'tcx>) -> bool {
78 if t.sty == self.0.types.u128.sty || t.sty == self.0.types.i128.sty {
80 return false; // stop visiting
83 t.super_visit_with(self)
87 let mut visitor = UI128Visitor(tcx, false);
88 fn_sig.visit_with(&mut visitor);
90 // Step 2b. If found replace function with a trap.
92 tcx.sess.warn("u128 and i128 are not yet supported. \
93 Functions using these as args will be replaced with a trap.");
95 // Step 2b1. Declare function with fake signature
97 params: vec![AbiParam::new(types::INVALID)],
99 call_conv: CallConv::Fast,
101 let name = tcx.symbol_name(instance).as_str();
102 let func_id = cx.module.declare_function(&*name, linkage, &sig).unwrap();
104 // Step 2b2. Create trapping function
105 let mut func = Function::with_name_signature(ExternalName::user(0, 0), sig);
106 let mut func_ctx = FunctionBuilderContext::new();
107 let mut bcx = FunctionBuilder::new(&mut func, &mut func_ctx);
108 let start_ebb = bcx.create_ebb();
109 bcx.append_ebb_params_for_function_params(start_ebb);
110 bcx.switch_to_block(start_ebb);
112 let mut fx = FunctionCx {
115 pointer_type: pointer_ty(tcx),
121 ebb_map: HashMap::new(),
122 local_map: HashMap::new(),
124 clif_comments: crate::pretty_clif::CommentWriter::new(tcx, instance),
125 constants: &mut cx.ccx,
126 caches: &mut cx.caches,
127 source_info_set: indexmap::IndexSet::new(),
130 crate::trap::trap_unreachable(&mut fx, "[unimplemented] Called function with u128 or i128 as argument.");
131 fx.bcx.seal_all_blocks();
134 // Step 2b3. Define function
135 cx.caches.context.func = func;
137 .define_function(func_id, &mut cx.caches.context)
139 cx.caches.context.clear();
144 // Step 3. Declare function
145 let (name, sig) = get_function_name_and_sig(tcx, instance, false);
146 let func_id = cx.module.declare_function(&name, linkage, &sig).unwrap();
147 let mut debug_context = cx
150 .map(|debug_context| FunctionDebugContext::new(tcx, debug_context, mir, &name, &sig));
152 // Step 4. Make FunctionBuilder
153 let mut func = Function::with_name_signature(ExternalName::user(0, 0), sig);
154 let mut func_ctx = FunctionBuilderContext::new();
155 let mut bcx = FunctionBuilder::new(&mut func, &mut func_ctx);
157 // Step 5. Predefine ebb's
158 let start_ebb = bcx.create_ebb();
159 let mut ebb_map: HashMap<BasicBlock, Ebb> = HashMap::new();
160 for (bb, _bb_data) in mir.basic_blocks().iter_enumerated() {
161 ebb_map.insert(bb, bcx.create_ebb());
164 // Step 6. Make FunctionCx
165 let pointer_type = cx.module.target_config().pointer_type();
166 let clif_comments = crate::pretty_clif::CommentWriter::new(tcx, instance);
168 let mut fx = FunctionCx {
178 local_map: HashMap::new(),
181 constants: &mut cx.ccx,
182 caches: &mut cx.caches,
183 source_info_set: indexmap::IndexSet::new(),
186 // Step 7. Codegen function
187 with_unimpl_span(fx.mir.span, || {
188 crate::abi::codegen_fn_prelude(&mut fx, start_ebb);
189 codegen_fn_content(&mut fx);
191 let source_info_set = fx.source_info_set.clone();
193 // Step 8. Write function to file for debugging
194 #[cfg(debug_assertions)]
195 fx.write_clif_file();
197 // Step 9. Verify function
198 verify_func(tcx, fx.clif_comments, &func);
200 // Step 10. Define function
201 cx.caches.context.func = func;
203 .define_function(func_id, &mut cx.caches.context)
206 // Step 11. Define debuginfo for function
207 let context = &cx.caches.context;
208 let isa = cx.module.isa();
211 .map(|x| x.define(tcx, context, isa, &source_info_set));
213 // Step 12. Clear context to make it usable for the next function
214 cx.caches.context.clear();
217 fn verify_func(tcx: TyCtxt, writer: crate::pretty_clif::CommentWriter, func: &Function) {
218 let flags = settings::Flags::new(settings::builder());
219 match ::cranelift::codegen::verify_function(&func, &flags) {
222 tcx.sess.err(&format!("{:?}", err));
223 let pretty_error = ::cranelift::codegen::print_errors::pretty_verifier_error(
226 Some(Box::new(&writer)),
230 .fatal(&format!("cranelift verify error:\n{}", pretty_error));
235 fn codegen_fn_content<'a, 'tcx: 'a>(fx: &mut FunctionCx<'a, 'tcx, impl Backend>) {
236 for (bb, bb_data) in fx.mir.basic_blocks().iter_enumerated() {
237 if bb_data.is_cleanup {
238 // Unwinding after panicking is not supported
242 let ebb = fx.get_ebb(bb);
243 fx.bcx.switch_to_block(ebb);
246 for stmt in &bb_data.statements {
247 fx.set_debug_loc(stmt.source_info);
248 trans_stmt(fx, ebb, stmt);
251 #[cfg(debug_assertions)]
253 let mut terminator_head = "\n".to_string();
257 .fmt_head(&mut terminator_head)
259 let inst = fx.bcx.func.layout.last_inst(ebb).unwrap();
260 fx.add_comment(inst, terminator_head);
263 fx.set_debug_loc(bb_data.terminator().source_info);
265 match &bb_data.terminator().kind {
266 TerminatorKind::Goto { target } => {
267 let ebb = fx.get_ebb(*target);
268 fx.bcx.ins().jump(ebb, &[]);
270 TerminatorKind::Return => {
271 crate::abi::codegen_return(fx);
273 TerminatorKind::Assert {
280 let cond = trans_operand(fx, cond).load_scalar(fx);
281 // TODO HACK brz/brnz for i8/i16 is not yet implemented
282 let cond = fx.bcx.ins().uextend(types::I32, cond);
283 let target = fx.get_ebb(*target);
285 fx.bcx.ins().brnz(cond, target, &[]);
287 fx.bcx.ins().brz(cond, target, &[]);
289 trap_panic(fx, format!("[panic] Assert {:?} failed.", msg));
292 TerminatorKind::SwitchInt {
298 let discr = trans_operand(fx, discr).load_scalar(fx);
299 let mut switch = ::cranelift::frontend::Switch::new();
300 for (i, value) in values.iter().enumerate() {
301 let ebb = fx.get_ebb(targets[i]);
302 switch.set_entry(*value as u64, ebb);
304 let otherwise_ebb = fx.get_ebb(targets[targets.len() - 1]);
305 switch.emit(&mut fx.bcx, discr, otherwise_ebb);
307 TerminatorKind::Call {
314 crate::abi::codegen_terminator_call(fx, func, args, destination);
316 TerminatorKind::Resume | TerminatorKind::Abort => {
317 trap_unreachable(fx, "[corruption] Unwinding bb reached.");
319 TerminatorKind::Unreachable => {
320 trap_unreachable(fx, "[corruption] Hit unreachable code.");
322 TerminatorKind::Yield { .. }
323 | TerminatorKind::FalseEdges { .. }
324 | TerminatorKind::FalseUnwind { .. }
325 | TerminatorKind::DropAndReplace { .. }
326 | TerminatorKind::GeneratorDrop => {
327 bug!("shouldn't exist at trans {:?}", bb_data.terminator());
329 TerminatorKind::Drop {
334 let ty = location.ty(fx.mir, fx.tcx).ty;
335 let ty = fx.monomorphize(&ty);
336 let drop_fn = crate::rustc_mir::monomorphize::resolve_drop_in_place(fx.tcx, ty);
338 if let ty::InstanceDef::DropGlue(_, None) = drop_fn.def {
339 // we don't actually need to drop anything
341 let drop_place = trans_place(fx, location);
342 let drop_fn_ty = drop_fn.ty(fx.tcx);
345 crate::abi::codegen_drop(fx, drop_place, drop_fn_ty);
348 let arg_place = CPlace::new_stack_slot(
351 &ty::RegionKind::ReErased,
354 mutbl: crate::rustc::hir::Mutability::MutMutable,
358 drop_place.write_place_ref(fx, arg_place);
359 let arg_value = arg_place.to_cvalue(fx);
360 crate::abi::codegen_call_inner(
371 let target_ebb = fx.get_ebb(*target);
372 fx.bcx.ins().jump(target_ebb, &[]);
377 fx.bcx.seal_all_blocks();
381 fn trans_stmt<'a, 'tcx: 'a>(
382 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
384 stmt: &Statement<'tcx>,
386 let _print_guard = PrintOnPanic(|| format!("stmt {:?}", stmt));
388 fx.set_debug_loc(stmt.source_info);
390 #[cfg(debug_assertions)]
392 StatementKind::StorageLive(..) | StatementKind::StorageDead(..) => {} // Those are not very useful
394 let inst = fx.bcx.func.layout.last_inst(cur_ebb).unwrap();
395 fx.add_comment(inst, format!("{:?}", stmt));
400 StatementKind::SetDiscriminant {
404 let place = trans_place(fx, place);
405 let layout = place.layout();
406 if layout.for_variant(&*fx, *variant_index).abi == layout::Abi::Uninhabited {
409 match layout.variants {
410 layout::Variants::Single { index } => {
411 assert_eq!(index, *variant_index);
413 layout::Variants::Multiple { discr_kind: layout::DiscriminantKind::Tag, .. } => {
414 let ptr = place.place_field(fx, mir::Field::new(0));
419 .discriminant_for_variant(fx.tcx, *variant_index)
421 let discr = CValue::const_val(fx, ptr.layout().ty, to as u64 as i64);
422 ptr.write_cvalue(fx, discr);
424 layout::Variants::Multiple {
425 discr_kind: layout::DiscriminantKind::Niche {
432 if *variant_index != dataful_variant {
433 let niche = place.place_field(fx, mir::Field::new(0));
434 //let niche_llty = niche.layout.immediate_llvm_type(bx.cx);
436 ((variant_index.as_u32() - niche_variants.start().as_u32()) as u128)
437 .wrapping_add(niche_start);
438 // FIXME(eddyb) Check the actual primitive type here.
439 let niche_llval = if niche_value == 0 {
440 CValue::const_val(fx, niche.layout().ty, 0)
442 CValue::const_val(fx, niche.layout().ty, niche_value as u64 as i64)
444 niche.write_cvalue(fx, niche_llval);
449 StatementKind::Assign(to_place, rval) => {
450 let lval = trans_place(fx, to_place);
451 let dest_layout = lval.layout();
453 Rvalue::Use(operand) => {
454 let val = trans_operand(fx, operand);
455 lval.write_cvalue(fx, val);
457 Rvalue::Ref(_, _, place) => {
458 let place = trans_place(fx, place);
459 place.write_place_ref(fx, lval);
461 Rvalue::BinaryOp(bin_op, lhs, rhs) => {
462 let ty = fx.monomorphize(&lhs.ty(fx.mir, fx.tcx));
463 let lhs = trans_operand(fx, lhs);
464 let rhs = trans_operand(fx, rhs);
466 let res = match ty.sty {
467 ty::Bool => trans_bool_binop(fx, *bin_op, lhs, rhs, lval.layout().ty),
469 trans_int_binop(fx, *bin_op, lhs, rhs, lval.layout().ty, false)
472 trans_int_binop(fx, *bin_op, lhs, rhs, lval.layout().ty, true)
474 ty::Float(_) => trans_float_binop(fx, *bin_op, lhs, rhs, lval.layout().ty),
475 ty::Char => trans_char_binop(fx, *bin_op, lhs, rhs, lval.layout().ty),
476 ty::RawPtr(..) => trans_ptr_binop(fx, *bin_op, lhs, rhs, lval.layout().ty),
477 ty::FnPtr(..) => trans_ptr_binop(fx, *bin_op, lhs, rhs, lval.layout().ty),
478 _ => unimplemented!("binop {:?} for {:?}", bin_op, ty),
480 lval.write_cvalue(fx, res);
482 Rvalue::CheckedBinaryOp(bin_op, lhs, rhs) => {
483 let ty = fx.monomorphize(&lhs.ty(fx.mir, fx.tcx));
484 let lhs = trans_operand(fx, lhs);
485 let rhs = trans_operand(fx, rhs);
487 let res = match ty.sty {
489 trans_checked_int_binop(fx, *bin_op, lhs, rhs, lval.layout().ty, false)
492 trans_checked_int_binop(fx, *bin_op, lhs, rhs, lval.layout().ty, true)
494 _ => unimplemented!("checked binop {:?} for {:?}", bin_op, ty),
496 lval.write_cvalue(fx, res);
498 Rvalue::UnaryOp(un_op, operand) => {
499 let operand = trans_operand(fx, operand);
500 let layout = operand.layout();
501 let val = operand.load_scalar(fx);
502 let res = match un_op {
504 match layout.ty.sty {
506 let val = fx.bcx.ins().uextend(types::I32, val); // WORKAROUND for CraneStation/cranelift#466
507 let res = fx.bcx.ins().icmp_imm(IntCC::Equal, val, 0);
508 fx.bcx.ins().bint(types::I8, res)
510 ty::Uint(_) | ty::Int(_) => fx.bcx.ins().bnot(val),
511 _ => unimplemented!("un op Not for {:?}", layout.ty),
514 UnOp::Neg => match layout.ty.sty {
516 let clif_ty = fx.clif_type(layout.ty).unwrap();
517 let zero = fx.bcx.ins().iconst(clif_ty, 0);
518 fx.bcx.ins().isub(zero, val)
520 ty::Float(_) => fx.bcx.ins().fneg(val),
521 _ => unimplemented!("un op Neg for {:?}", layout.ty),
524 lval.write_cvalue(fx, CValue::ByVal(res, layout));
526 Rvalue::Cast(CastKind::ReifyFnPointer, operand, ty) => {
527 let layout = fx.layout_of(ty);
529 .monomorphize(&operand.ty(&fx.mir.local_decls, fx.tcx))
532 ty::FnDef(def_id, substs) => {
533 let func_ref = fx.get_function_ref(
534 Instance::resolve(fx.tcx, ParamEnv::reveal_all(), def_id, substs)
537 let func_addr = fx.bcx.ins().func_addr(fx.pointer_type, func_ref);
538 lval.write_cvalue(fx, CValue::ByVal(func_addr, layout));
540 _ => bug!("Trying to ReifyFnPointer on non FnDef {:?}", ty),
543 Rvalue::Cast(CastKind::UnsafeFnPointer, operand, ty)
544 | Rvalue::Cast(CastKind::MutToConstPointer, operand, ty) => {
545 let operand = trans_operand(fx, operand);
546 let layout = fx.layout_of(ty);
547 lval.write_cvalue(fx, operand.unchecked_cast_to(layout));
549 Rvalue::Cast(CastKind::Misc, operand, to_ty) => {
550 let operand = trans_operand(fx, operand);
551 let from_ty = operand.layout().ty;
553 fn is_fat_ptr<'a, 'tcx: 'a>(fx: &FunctionCx<'a, 'tcx, impl Backend>, ty: Ty<'tcx>) -> bool {
556 .map(|ty::TypeAndMut {ty: pointee_ty, mutbl: _ }| fx.layout_of(pointee_ty).is_unsized())
560 if is_fat_ptr(fx, from_ty) {
561 if is_fat_ptr(fx, to_ty) {
562 // fat-ptr -> fat-ptr
563 lval.write_cvalue(fx, operand.unchecked_cast_to(dest_layout));
565 // fat-ptr -> thin-ptr
566 let (ptr, _extra) = operand.load_scalar_pair(fx);
567 lval.write_cvalue(fx, CValue::ByVal(ptr, dest_layout))
569 } else if let ty::Adt(adt_def, _substs) = from_ty.sty {
570 // enum -> discriminant value
571 assert!(adt_def.is_enum());
573 ty::Uint(_) | ty::Int(_) => {},
574 _ => unreachable!("cast adt {} -> {}", from_ty, to_ty),
577 // FIXME avoid forcing to stack
579 CPlace::Addr(operand.force_stack(fx), None, operand.layout());
580 let discr = trans_get_discriminant(fx, place, fx.layout_of(to_ty));
581 lval.write_cvalue(fx, discr);
583 let from_clif_ty = fx.clif_type(from_ty).unwrap();
584 let to_clif_ty = fx.clif_type(to_ty).unwrap();
585 let from = operand.load_scalar(fx);
587 let signed = match from_ty.sty {
588 ty::Ref(..) | ty::RawPtr(..) | ty::FnPtr(..) | ty::Char | ty::Uint(..) | ty::Bool => false,
590 ty::Float(..) => false, // `signed` is unused for floats
591 _ => panic!("{}", from_ty),
594 let res = if from_clif_ty.is_int() && to_clif_ty.is_int() {
595 // int-like -> int-like
596 crate::common::clif_intcast(
602 } else if from_clif_ty.is_int() && to_clif_ty.is_float() {
604 // FIXME missing encoding for fcvt_from_sint.f32.i8
605 let from = if from_clif_ty == types::I8 || from_clif_ty == types::I16 {
606 fx.bcx.ins().uextend(types::I32, from)
611 fx.bcx.ins().fcvt_from_sint(to_clif_ty, from)
613 fx.bcx.ins().fcvt_from_uint(to_clif_ty, from)
615 } else if from_clif_ty.is_float() && to_clif_ty.is_int() {
617 let from = operand.load_scalar(fx);
619 fx.bcx.ins().fcvt_to_sint_sat(to_clif_ty, from)
621 fx.bcx.ins().fcvt_to_uint_sat(to_clif_ty, from)
623 } else if from_clif_ty.is_float() && to_clif_ty.is_float() {
625 match (from_clif_ty, to_clif_ty) {
626 (types::F32, types::F64) => {
627 fx.bcx.ins().fpromote(types::F64, from)
629 (types::F64, types::F32) => {
630 fx.bcx.ins().fdemote(types::F32, from)
635 unimpl!("rval misc {:?} {:?}", from_ty, to_ty)
637 lval.write_cvalue(fx, CValue::ByVal(res, dest_layout));
640 Rvalue::Cast(CastKind::ClosureFnPointer(_), operand, _ty) => {
641 let operand = trans_operand(fx, operand);
642 match operand.layout().ty.sty {
643 ty::Closure(def_id, substs) => {
644 let instance = rustc_mir::monomorphize::resolve_closure(
648 ty::ClosureKind::FnOnce,
650 let func_ref = fx.get_function_ref(instance);
651 let func_addr = fx.bcx.ins().func_addr(fx.pointer_type, func_ref);
652 lval.write_cvalue(fx, CValue::ByVal(func_addr, lval.layout()));
655 bug!("{} cannot be cast to a fn ptr", operand.layout().ty)
659 Rvalue::Cast(CastKind::Unsize, operand, _ty) => {
660 let operand = trans_operand(fx, operand);
661 operand.unsize_value(fx, lval);
663 Rvalue::Discriminant(place) => {
664 let place = trans_place(fx, place);
665 let discr = trans_get_discriminant(fx, place, dest_layout);
666 lval.write_cvalue(fx, discr);
668 Rvalue::Repeat(operand, times) => {
669 let operand = trans_operand(fx, operand);
671 let index = fx.bcx.ins().iconst(fx.pointer_type, i as i64);
672 let to = lval.place_index(fx, index);
673 to.write_cvalue(fx, operand);
676 Rvalue::Len(place) => {
677 let place = trans_place(fx, place);
678 let usize_layout = fx.layout_of(fx.tcx.types.usize);
679 let len = codegen_array_len(fx, place);
680 lval.write_cvalue(fx, CValue::ByVal(len, usize_layout));
682 Rvalue::NullaryOp(NullOp::Box, content_ty) => {
683 use rustc::middle::lang_items::ExchangeMallocFnLangItem;
685 let usize_type = fx.clif_type(fx.tcx.types.usize).unwrap();
686 let layout = fx.layout_of(content_ty);
687 let llsize = fx.bcx.ins().iconst(usize_type, layout.size.bytes() as i64);
691 .iconst(usize_type, layout.align.abi.bytes() as i64);
692 let box_layout = fx.layout_of(fx.tcx.mk_box(content_ty));
695 let def_id = match fx.tcx.lang_items().require(ExchangeMallocFnLangItem) {
700 .fatal(&format!("allocation of `{}` {}", box_layout.ty, s));
703 let instance = ty::Instance::mono(fx.tcx, def_id);
704 let func_ref = fx.get_function_ref(instance);
705 let call = fx.bcx.ins().call(func_ref, &[llsize, llalign]);
706 let ptr = fx.bcx.inst_results(call)[0];
707 lval.write_cvalue(fx, CValue::ByVal(ptr, box_layout));
709 Rvalue::NullaryOp(NullOp::SizeOf, ty) => {
713 .is_sized(fx.tcx.at(DUMMY_SP), ParamEnv::reveal_all()));
714 let ty_size = fx.layout_of(ty).size.bytes();
715 let val = CValue::const_val(fx, fx.tcx.types.usize, ty_size as i64);
716 lval.write_cvalue(fx, val);
718 Rvalue::Aggregate(kind, operands) => match **kind {
719 AggregateKind::Array(_ty) => {
720 for (i, operand) in operands.into_iter().enumerate() {
721 let operand = trans_operand(fx, operand);
722 let index = fx.bcx.ins().iconst(fx.pointer_type, i as i64);
723 let to = lval.place_index(fx, index);
724 to.write_cvalue(fx, operand);
727 _ => unimpl!("shouldn't exist at trans {:?}", rval),
731 StatementKind::StorageLive(_)
732 | StatementKind::StorageDead(_)
734 | StatementKind::FakeRead(..)
735 | StatementKind::Retag { .. }
736 | StatementKind::AscribeUserType(..) => {}
738 StatementKind::InlineAsm { .. } => unimpl!("Inline assembly is not supported"),
742 fn codegen_array_len<'a, 'tcx: 'a>(
743 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
746 match place.layout().ty.sty {
747 ty::Array(_elem_ty, len) => {
748 let len = crate::constant::force_eval_const(fx, len).unwrap_usize(fx.tcx) as i64;
749 fx.bcx.ins().iconst(fx.pointer_type, len)
751 ty::Slice(_elem_ty) => place
752 .to_addr_maybe_unsized(fx)
754 .expect("Length metadata for slice place"),
755 _ => bug!("Rvalue::Len({:?})", place),
759 pub fn trans_get_discriminant<'a, 'tcx: 'a>(
760 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
762 dest_layout: TyLayout<'tcx>,
764 let layout = place.layout();
766 if layout.abi == layout::Abi::Uninhabited {
767 return trap_unreachable_ret_value(fx, dest_layout, "[panic] Tried to get discriminant for uninhabited type.");
770 let (discr_scalar, discr_kind) = match &layout.variants {
771 layout::Variants::Single { index } => {
772 let discr_val = layout
775 .map_or(index.as_u32() as u128, |def| {
776 def.discriminant_for_variant(fx.tcx, *index).val
778 return CValue::const_val(fx, dest_layout.ty, discr_val as u64 as i64);
780 layout::Variants::Multiple { discr, discr_kind, variants: _ } => (discr, discr_kind),
783 let discr = place.place_field(fx, mir::Field::new(0)).to_cvalue(fx);
784 let discr_ty = discr.layout().ty;
785 let lldiscr = discr.load_scalar(fx);
787 layout::DiscriminantKind::Tag => {
788 let signed = match discr_scalar.value {
789 layout::Int(_, signed) => signed,
792 let val = clif_intcast(fx, lldiscr, fx.clif_type(dest_layout.ty).unwrap(), signed);
793 return CValue::ByVal(val, dest_layout);
795 layout::DiscriminantKind::Niche {
800 let niche_llty = fx.clif_type(discr_ty).unwrap();
801 let dest_clif_ty = fx.clif_type(dest_layout.ty).unwrap();
802 if niche_variants.start() == niche_variants.end() {
806 .icmp_imm(IntCC::Equal, lldiscr, *niche_start as u64 as i64);
810 .iconst(dest_clif_ty, niche_variants.start().as_u32() as i64);
814 .iconst(dest_clif_ty, dataful_variant.as_u32() as i64);
815 let val = fx.bcx.ins().select(b, if_true, if_false);
816 return CValue::ByVal(val, dest_layout);
818 // Rebase from niche values to discriminant values.
819 let delta = niche_start.wrapping_sub(niche_variants.start().as_u32() as u128);
820 let delta = fx.bcx.ins().iconst(niche_llty, delta as u64 as i64);
821 let lldiscr = fx.bcx.ins().isub(lldiscr, delta);
822 let b = fx.bcx.ins().icmp_imm(
823 IntCC::UnsignedLessThanOrEqual,
825 niche_variants.end().as_u32() as i64,
828 clif_intcast(fx, lldiscr, fx.clif_type(dest_layout.ty).unwrap(), false);
832 .iconst(dest_clif_ty, dataful_variant.as_u32() as i64);
833 let val = fx.bcx.ins().select(b, if_true, if_false);
834 return CValue::ByVal(val, dest_layout);
840 macro_rules! binop_match {
841 (@single $fx:expr, $bug_fmt:expr, $var:expr, $signed:expr, $lhs:expr, $rhs:expr, $ret_ty:expr, bug) => {
842 bug!("binop {} on {} lhs: {:?} rhs: {:?}", stringify!($var), $bug_fmt, $lhs, $rhs)
844 (@single $fx:expr, $bug_fmt:expr, $var:expr, $signed:expr, $lhs:expr, $rhs:expr, $ret_ty:expr, icmp($cc:ident)) => {{
845 assert_eq!($fx.tcx.types.bool, $ret_ty);
846 let ret_layout = $fx.layout_of($ret_ty);
848 let b = $fx.bcx.ins().icmp(IntCC::$cc, $lhs, $rhs);
849 CValue::ByVal($fx.bcx.ins().bint(types::I8, b), ret_layout)
851 (@single $fx:expr, $bug_fmt:expr, $var:expr, $signed:expr, $lhs:expr, $rhs:expr, $ret_ty:expr, fcmp($cc:ident)) => {{
852 assert_eq!($fx.tcx.types.bool, $ret_ty);
853 let ret_layout = $fx.layout_of($ret_ty);
854 let b = $fx.bcx.ins().fcmp(FloatCC::$cc, $lhs, $rhs);
855 CValue::ByVal($fx.bcx.ins().bint(types::I8, b), ret_layout)
857 (@single $fx:expr, $bug_fmt:expr, $var:expr, $signed:expr, $lhs:expr, $rhs:expr, $ret_ty:expr, custom(|| $body:expr)) => {{
860 (@single $fx:expr, $bug_fmt:expr, $var:expr, $signed:expr, $lhs:expr, $rhs:expr, $ret_ty:expr, $name:ident) => {{
861 let ret_layout = $fx.layout_of($ret_ty);
862 CValue::ByVal($fx.bcx.ins().$name($lhs, $rhs), ret_layout)
865 $fx:expr, $bin_op:expr, $signed:expr, $lhs:expr, $rhs:expr, $ret_ty:expr, $bug_fmt:expr;
867 $var:ident ($sign:pat) $name:tt $( ( $($next:tt)* ) )? ;
870 let lhs = $lhs.load_scalar($fx);
871 let rhs = $rhs.load_scalar($fx);
872 match ($bin_op, $signed) {
874 (BinOp::$var, $sign) => binop_match!(@single $fx, $bug_fmt, $var, $signed, lhs, rhs, $ret_ty, $name $( ( $($next)* ) )?),
880 fn trans_bool_binop<'a, 'tcx: 'a>(
881 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
887 let res = binop_match! {
888 fx, bin_op, false, lhs, rhs, ty, "bool";
901 Lt (_) icmp(UnsignedLessThan);
902 Le (_) icmp(UnsignedLessThanOrEqual);
903 Ne (_) icmp(NotEqual);
904 Ge (_) icmp(UnsignedGreaterThanOrEqual);
905 Gt (_) icmp(UnsignedGreaterThan);
913 pub fn trans_int_binop<'a, 'tcx: 'a>(
914 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
921 if bin_op != BinOp::Shl && bin_op != BinOp::Shr {
925 "int binop requires lhs and rhs of same type"
929 fx, bin_op, signed, lhs, rhs, out_ty, "int/uint";
945 Lt (false) icmp(UnsignedLessThan);
946 Lt (true) icmp(SignedLessThan);
947 Le (false) icmp(UnsignedLessThanOrEqual);
948 Le (true) icmp(SignedLessThanOrEqual);
949 Ne (_) icmp(NotEqual);
950 Ge (false) icmp(UnsignedGreaterThanOrEqual);
951 Ge (true) icmp(SignedGreaterThanOrEqual);
952 Gt (false) icmp(UnsignedGreaterThan);
953 Gt (true) icmp(SignedGreaterThan);
959 pub fn trans_checked_int_binop<'a, 'tcx: 'a>(
960 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
962 in_lhs: CValue<'tcx>,
963 in_rhs: CValue<'tcx>,
967 if bin_op != BinOp::Shl && bin_op != BinOp::Shr {
971 "checked int binop requires lhs and rhs of same type"
975 let lhs = in_lhs.load_scalar(fx);
976 let rhs = in_rhs.load_scalar(fx);
977 let res = match bin_op {
978 BinOp::Add => fx.bcx.ins().iadd(lhs, rhs),
979 BinOp::Sub => fx.bcx.ins().isub(lhs, rhs),
980 BinOp::Mul => fx.bcx.ins().imul(lhs, rhs),
981 BinOp::Shl => fx.bcx.ins().ishl(lhs, rhs),
984 fx.bcx.ins().ushr(lhs, rhs)
986 fx.bcx.ins().sshr(lhs, rhs)
990 "binop {:?} on checked int/uint lhs: {:?} rhs: {:?}",
997 // TODO: check for overflow
998 let has_overflow = fx.bcx.ins().iconst(types::I8, 0);
1000 let out_place = CPlace::new_stack_slot(fx, out_ty);
1001 let out_layout = out_place.layout();
1002 out_place.write_cvalue(fx, CValue::ByValPair(res, has_overflow, out_layout));
1004 out_place.to_cvalue(fx)
1007 fn trans_float_binop<'a, 'tcx: 'a>(
1008 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
1014 let res = binop_match! {
1015 fx, bin_op, false, lhs, rhs, ty, "float";
1021 assert_eq!(lhs.layout().ty, ty);
1022 assert_eq!(rhs.layout().ty, ty);
1024 ty::Float(FloatTy::F32) => fx.easy_call("fmodf", &[lhs, rhs], ty),
1025 ty::Float(FloatTy::F64) => fx.easy_call("fmod", &[lhs, rhs], ty),
1036 Lt (_) fcmp(LessThan);
1037 Le (_) fcmp(LessThanOrEqual);
1038 Ne (_) fcmp(NotEqual);
1039 Ge (_) fcmp(GreaterThanOrEqual);
1040 Gt (_) fcmp(GreaterThan);
1048 fn trans_char_binop<'a, 'tcx: 'a>(
1049 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
1055 let res = binop_match! {
1056 fx, bin_op, false, lhs, rhs, ty, "char";
1069 Lt (_) icmp(UnsignedLessThan);
1070 Le (_) icmp(UnsignedLessThanOrEqual);
1071 Ne (_) icmp(NotEqual);
1072 Ge (_) icmp(UnsignedGreaterThanOrEqual);
1073 Gt (_) icmp(UnsignedGreaterThan);
1081 fn trans_ptr_binop<'a, 'tcx: 'a>(
1082 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
1088 let not_fat = match lhs.layout().ty.sty {
1089 ty::RawPtr(TypeAndMut { ty, mutbl: _ }) => {
1090 ty.is_sized(fx.tcx.at(DUMMY_SP), ParamEnv::reveal_all())
1092 ty::FnPtr(..) => true,
1093 _ => bug!("trans_ptr_binop on non ptr"),
1096 if let BinOp::Offset = bin_op {
1097 let (base, offset) = (lhs, rhs.load_scalar(fx));
1098 let pointee_ty = base.layout().ty.builtin_deref(true).unwrap().ty;
1099 let pointee_size = fx.layout_of(pointee_ty).size.bytes();
1100 let ptr_diff = fx.bcx.ins().imul_imm(offset, pointee_size as i64);
1101 let base_val = base.load_scalar(fx);
1102 let res = fx.bcx.ins().iadd(base_val, ptr_diff);
1103 return CValue::ByVal(res, base.layout());
1107 fx, bin_op, false, lhs, rhs, ret_ty, "ptr";
1120 Lt (_) icmp(UnsignedLessThan);
1121 Le (_) icmp(UnsignedLessThanOrEqual);
1122 Ne (_) icmp(NotEqual);
1123 Ge (_) icmp(UnsignedGreaterThanOrEqual);
1124 Gt (_) icmp(UnsignedGreaterThan);
1126 Offset (_) bug; // Handled above
1129 let (lhs_ptr, lhs_extra) = lhs.load_scalar_pair(fx);
1130 let (rhs_ptr, rhs_extra) = rhs.load_scalar_pair(fx);
1131 let res = match bin_op {
1133 let ptr_eq = fx.bcx.ins().icmp(IntCC::Equal, lhs_ptr, rhs_ptr);
1134 let extra_eq = fx.bcx.ins().icmp(IntCC::Equal, lhs_extra, rhs_extra);
1135 fx.bcx.ins().band(ptr_eq, extra_eq)
1138 let ptr_ne = fx.bcx.ins().icmp(IntCC::NotEqual, lhs_ptr, rhs_ptr);
1139 let extra_ne = fx.bcx.ins().icmp(IntCC::NotEqual, lhs_extra, rhs_extra);
1140 fx.bcx.ins().bor(ptr_ne, extra_ne)
1142 _ => unimplemented!(
1143 "trans_ptr_binop({:?}, <fat ptr>, <fat ptr>) not implemented",
1148 assert_eq!(fx.tcx.types.bool, ret_ty);
1149 let ret_layout = fx.layout_of(ret_ty);
1150 CValue::ByVal(fx.bcx.ins().bint(types::I8, res), ret_layout)
1154 pub fn trans_place<'a, 'tcx: 'a>(
1155 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
1156 place: &Place<'tcx>,
1159 Place::Base(base) => match base {
1160 PlaceBase::Local(local) => fx.get_local_place(*local),
1161 PlaceBase::Static(static_) => match static_.kind {
1162 StaticKind::Static(def_id) => {
1163 crate::constant::codegen_static_ref(fx, def_id, static_.ty)
1165 StaticKind::Promoted(promoted) => {
1166 crate::constant::trans_promoted(fx, promoted, static_.ty)
1170 Place::Projection(projection) => {
1171 let base = trans_place(fx, &projection.base);
1172 match projection.elem {
1173 ProjectionElem::Deref => base.place_deref(fx),
1174 ProjectionElem::Field(field, _ty) => base.place_field(fx, field),
1175 ProjectionElem::Index(local) => {
1176 let index = fx.get_local_place(local).to_cvalue(fx).load_scalar(fx);
1177 base.place_index(fx, index)
1179 ProjectionElem::ConstantIndex {
1184 let index = if !from_end {
1185 fx.bcx.ins().iconst(fx.pointer_type, offset as i64)
1187 let len = codegen_array_len(fx, base);
1188 fx.bcx.ins().iadd_imm(len, -(offset as i64))
1190 base.place_index(fx, index)
1192 ProjectionElem::Subslice { from, to } => {
1193 // These indices are generated by slice patterns.
1194 // slice[from:-to] in Python terms.
1196 match base.layout().ty.sty {
1197 ty::Array(elem_ty, len) => {
1198 let elem_layout = fx.layout_of(elem_ty);
1199 let ptr = base.to_addr(fx);
1200 let len = crate::constant::force_eval_const(fx, len).unwrap_usize(fx.tcx);
1202 fx.bcx.ins().iadd_imm(ptr, elem_layout.size.bytes() as i64 * from as i64),
1204 fx.layout_of(fx.tcx.mk_array(elem_ty, len - from as u64 - to as u64)),
1207 ty::Slice(elem_ty) => {
1208 let elem_layout = fx.layout_of(elem_ty);
1209 let (ptr, len) = base.to_addr_maybe_unsized(fx);
1210 let len = len.unwrap();
1212 fx.bcx.ins().iadd_imm(ptr, elem_layout.size.bytes() as i64 * from as i64),
1213 Some(fx.bcx.ins().iadd_imm(len, -(from as i64 + to as i64))),
1217 _ => unreachable!(),
1220 ProjectionElem::Downcast(_adt_def, variant) => base.downcast_variant(fx, variant),
1226 pub fn trans_operand<'a, 'tcx>(
1227 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
1228 operand: &Operand<'tcx>,
1231 Operand::Move(place) | Operand::Copy(place) => {
1232 let cplace = trans_place(fx, place);
1233 cplace.to_cvalue(fx)
1235 Operand::Constant(const_) => crate::constant::trans_constant(fx, const_),