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. Declare function
68 let (name, sig) = get_function_name_and_sig(tcx, instance);
69 let func_id = cx.module
70 .declare_function(&name, linkage, &sig)
73 // Step 3. Make FunctionBuilder
74 let mut func = Function::with_name_signature(ExternalName::user(0, 0), sig);
75 let mut func_ctx = FunctionBuilderContext::new();
76 let mut bcx = FunctionBuilder::new(&mut func, &mut func_ctx);
78 // Step 4. Predefine ebb's
79 let start_ebb = bcx.create_ebb();
80 let mut ebb_map: HashMap<BasicBlock, Ebb> = HashMap::new();
81 for (bb, _bb_data) in mir.basic_blocks().iter_enumerated() {
82 ebb_map.insert(bb, bcx.create_ebb());
85 // Step 5. Make FunctionCx
86 let pointer_type = cx.module.target_config().pointer_type();
87 let clif_comments = crate::pretty_clif::CommentWriter::new(tcx, instance);
89 let mut fx = FunctionCx {
99 local_map: HashMap::new(),
102 constants: &mut cx.ccx,
103 caches: &mut cx.caches,
106 // Step 6. Codegen function
107 with_unimpl_span(fx.mir.span, || {
108 crate::abi::codegen_fn_prelude(&mut fx, start_ebb);
109 codegen_fn_content(&mut fx);
112 // Step 7. Write function to file for debugging
113 #[cfg(debug_assertions)]
114 fx.write_clif_file();
116 // Step 8. Verify function
117 verify_func(tcx, fx.clif_comments, &func);
119 // Step 9. Define function
120 cx.caches.context.func = func;
122 .define_function(func_id, &mut cx.caches.context)
124 cx.caches.context.clear();
127 fn verify_func(tcx: TyCtxt, writer: crate::pretty_clif::CommentWriter, func: &Function) {
128 let flags = settings::Flags::new(settings::builder());
129 match ::cranelift::codegen::verify_function(&func, &flags) {
132 tcx.sess.err(&format!("{:?}", err));
133 let pretty_error = ::cranelift::codegen::print_errors::pretty_verifier_error(
136 Some(Box::new(&writer)),
140 .fatal(&format!("cranelift verify error:\n{}", pretty_error));
145 fn codegen_fn_content<'a, 'tcx: 'a>(fx: &mut FunctionCx<'a, 'tcx, impl Backend>) {
146 for (bb, bb_data) in fx.mir.basic_blocks().iter_enumerated() {
147 if bb_data.is_cleanup {
148 // Unwinding after panicking is not supported
152 let ebb = fx.get_ebb(bb);
153 fx.bcx.switch_to_block(ebb);
156 for stmt in &bb_data.statements {
157 trans_stmt(fx, ebb, stmt);
160 #[cfg(debug_assertions)]
162 let mut terminator_head = "\n".to_string();
166 .fmt_head(&mut terminator_head)
168 let inst = fx.bcx.func.layout.last_inst(ebb).unwrap();
169 fx.add_comment(inst, terminator_head);
172 match &bb_data.terminator().kind {
173 TerminatorKind::Goto { target } => {
174 let ebb = fx.get_ebb(*target);
175 fx.bcx.ins().jump(ebb, &[]);
177 TerminatorKind::Return => {
178 crate::abi::codegen_return(fx);
180 TerminatorKind::Assert {
187 let cond = trans_operand(fx, cond).load_value(fx);
188 // TODO HACK brz/brnz for i8/i16 is not yet implemented
189 let cond = fx.bcx.ins().uextend(types::I32, cond);
190 let target = fx.get_ebb(*target);
192 fx.bcx.ins().brnz(cond, target, &[]);
194 fx.bcx.ins().brz(cond, target, &[]);
196 trap_panic(&mut fx.bcx);
199 TerminatorKind::SwitchInt {
205 let discr = trans_operand(fx, discr).load_value(fx);
206 let mut switch = ::cranelift::frontend::Switch::new();
207 for (i, value) in values.iter().enumerate() {
208 let ebb = fx.get_ebb(targets[i]);
209 switch.set_entry(*value as u64, ebb);
211 let otherwise_ebb = fx.get_ebb(targets[targets.len() - 1]);
212 switch.emit(&mut fx.bcx, discr, otherwise_ebb);
214 TerminatorKind::Call {
221 crate::abi::codegen_terminator_call(fx, func, args, destination);
223 TerminatorKind::Resume | TerminatorKind::Abort | TerminatorKind::Unreachable => {
224 trap_unreachable(&mut fx.bcx);
226 TerminatorKind::Yield { .. }
227 | TerminatorKind::FalseEdges { .. }
228 | TerminatorKind::FalseUnwind { .. }
229 | TerminatorKind::DropAndReplace { .. } => {
230 bug!("shouldn't exist at trans {:?}", bb_data.terminator());
232 TerminatorKind::Drop {
237 let ty = location.ty(fx.mir, fx.tcx).to_ty(fx.tcx);
238 let ty = fx.monomorphize(&ty);
239 let drop_fn = crate::rustc_mir::monomorphize::resolve_drop_in_place(fx.tcx, ty);
241 if let ty::InstanceDef::DropGlue(_, None) = drop_fn.def {
242 // we don't actually need to drop anything
244 let drop_place = trans_place(fx, location);
245 let arg_place = CPlace::temp(
248 &ty::RegionKind::ReErased,
251 mutbl: crate::rustc::hir::Mutability::MutMutable,
255 drop_place.write_place_ref(fx, arg_place);
258 fx.tcx.sess.warn("Drop for trait object");
261 let drop_fn_ty = drop_fn.ty(fx.tcx);
262 let arg_value = arg_place.to_cvalue(fx);
263 crate::abi::codegen_call_inner(
274 /*let mut args = if let Some(llextra) = place.llextra {
275 args2 = [place.llval, llextra];
278 args1 = [place.llval];
281 let (drop_fn, fn_ty) = match ty.sty {
283 let fn_ty = drop_fn.ty(bx.cx.tcx);
284 let sig = common::ty_fn_sig(bx.cx, fn_ty);
285 let sig = bx.tcx().normalize_erasing_late_bound_regions(
286 ty::ParamEnv::reveal_all(),
289 let fn_ty = FnType::new_vtable(bx.cx, sig, &[]);
290 let vtable = args[1];
292 (meth::DESTRUCTOR.get_fn(&bx, vtable, &fn_ty), fn_ty)
295 let value = place.to_cvalue(fx);
296 (callee::get_fn(bx.cx, drop_fn),
297 FnType::of_instance(bx.cx, &drop_fn))
300 do_call(self, bx, fn_ty, drop_fn, args,
301 Some((ReturnDest::Nothing, target)),
305 let target_ebb = fx.get_ebb(*target);
306 fx.bcx.ins().jump(target_ebb, &[]);
308 TerminatorKind::GeneratorDrop => {
309 unimplemented!("terminator GeneratorDrop");
314 fx.bcx.seal_all_blocks();
318 fn trans_stmt<'a, 'tcx: 'a>(
319 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
321 stmt: &Statement<'tcx>,
323 let _print_guard = PrintOnPanic(|| format!("stmt {:?}", stmt));
325 #[cfg(debug_assertions)]
327 StatementKind::StorageLive(..) | StatementKind::StorageDead(..) => {} // Those are not very useful
329 let inst = fx.bcx.func.layout.last_inst(cur_ebb).unwrap();
330 fx.add_comment(inst, format!("{:?}", stmt));
335 StatementKind::SetDiscriminant {
339 let place = trans_place(fx, place);
340 let layout = place.layout();
341 if layout.for_variant(&*fx, *variant_index).abi == layout::Abi::Uninhabited {
344 match layout.variants {
345 layout::Variants::Single { index } => {
346 assert_eq!(index, *variant_index);
348 layout::Variants::Tagged { .. } => {
349 let ptr = place.place_field(fx, mir::Field::new(0));
354 .discriminant_for_variant(fx.tcx, *variant_index)
356 let discr = CValue::const_val(fx, ptr.layout().ty, to as u64 as i64);
357 ptr.write_cvalue(fx, discr);
359 layout::Variants::NicheFilling {
365 if *variant_index != dataful_variant {
366 let niche = place.place_field(fx, mir::Field::new(0));
367 //let niche_llty = niche.layout.immediate_llvm_type(bx.cx);
369 ((variant_index.as_u32() - niche_variants.start().as_u32()) as u128)
370 .wrapping_add(niche_start);
371 // FIXME(eddyb) Check the actual primitive type here.
372 let niche_llval = if niche_value == 0 {
373 CValue::const_val(fx, niche.layout().ty, 0)
375 CValue::const_val(fx, niche.layout().ty, niche_value as u64 as i64)
377 niche.write_cvalue(fx, niche_llval);
382 StatementKind::Assign(to_place, rval) => {
383 let lval = trans_place(fx, to_place);
384 let dest_layout = lval.layout();
386 Rvalue::Use(operand) => {
387 let val = trans_operand(fx, operand);
388 lval.write_cvalue(fx, val);
390 Rvalue::Ref(_, _, place) => {
391 let place = trans_place(fx, place);
392 place.write_place_ref(fx, lval);
394 Rvalue::BinaryOp(bin_op, lhs, rhs) => {
395 let ty = fx.monomorphize(&lhs.ty(fx.mir, fx.tcx));
396 let lhs = trans_operand(fx, lhs);
397 let rhs = trans_operand(fx, rhs);
399 let res = match ty.sty {
400 ty::Bool => trans_bool_binop(fx, *bin_op, lhs, rhs, lval.layout().ty),
402 trans_int_binop(fx, *bin_op, lhs, rhs, lval.layout().ty, false)
405 trans_int_binop(fx, *bin_op, lhs, rhs, lval.layout().ty, true)
407 ty::Float(_) => trans_float_binop(fx, *bin_op, lhs, rhs, lval.layout().ty),
408 ty::Char => trans_char_binop(fx, *bin_op, lhs, rhs, lval.layout().ty),
409 ty::RawPtr(..) => trans_ptr_binop(fx, *bin_op, lhs, rhs, lval.layout().ty),
410 _ => unimplemented!("binop {:?} for {:?}", bin_op, ty),
412 lval.write_cvalue(fx, res);
414 Rvalue::CheckedBinaryOp(bin_op, lhs, rhs) => {
415 let ty = fx.monomorphize(&lhs.ty(fx.mir, fx.tcx));
416 let lhs = trans_operand(fx, lhs);
417 let rhs = trans_operand(fx, rhs);
419 let res = match ty.sty {
421 trans_checked_int_binop(fx, *bin_op, lhs, rhs, lval.layout().ty, false)
424 trans_checked_int_binop(fx, *bin_op, lhs, rhs, lval.layout().ty, true)
426 _ => unimplemented!("checked binop {:?} for {:?}", bin_op, ty),
428 lval.write_cvalue(fx, res);
430 Rvalue::UnaryOp(un_op, operand) => {
431 let operand = trans_operand(fx, operand);
432 let layout = operand.layout();
433 let val = operand.load_value(fx);
434 let res = match un_op {
436 match layout.ty.sty {
438 let val = fx.bcx.ins().uextend(types::I32, val); // WORKAROUND for CraneStation/cranelift#466
439 let res = fx.bcx.ins().icmp_imm(IntCC::Equal, val, 0);
440 fx.bcx.ins().bint(types::I8, res)
442 ty::Uint(_) | ty::Int(_) => fx.bcx.ins().bnot(val),
443 _ => unimplemented!("un op Not for {:?}", layout.ty),
446 UnOp::Neg => match layout.ty.sty {
448 let clif_ty = fx.clif_type(layout.ty).unwrap();
449 let zero = fx.bcx.ins().iconst(clif_ty, 0);
450 fx.bcx.ins().isub(zero, val)
452 ty::Float(_) => fx.bcx.ins().fneg(val),
453 _ => unimplemented!("un op Neg for {:?}", layout.ty),
456 lval.write_cvalue(fx, CValue::ByVal(res, layout));
458 Rvalue::Cast(CastKind::ReifyFnPointer, operand, ty) => {
459 let operand = trans_operand(fx, operand);
460 let layout = fx.layout_of(ty);
461 lval.write_cvalue(fx, operand.unchecked_cast_to(layout));
463 Rvalue::Cast(CastKind::UnsafeFnPointer, operand, ty) => {
464 let operand = trans_operand(fx, operand);
465 let layout = fx.layout_of(ty);
466 lval.write_cvalue(fx, operand.unchecked_cast_to(layout));
468 Rvalue::Cast(CastKind::Misc, operand, to_ty) => {
469 let operand = trans_operand(fx, operand);
470 let from_ty = operand.layout().ty;
471 match (&from_ty.sty, &to_ty.sty) {
472 (ty::Ref(..), ty::Ref(..))
473 | (ty::Ref(..), ty::RawPtr(..))
474 | (ty::RawPtr(..), ty::Ref(..))
475 | (ty::RawPtr(..), ty::RawPtr(..))
476 | (ty::FnPtr(..), ty::RawPtr(..)) => {
477 lval.write_cvalue(fx, operand.unchecked_cast_to(dest_layout));
479 (ty::RawPtr(..), ty::Uint(_))
480 | (ty::RawPtr(..), ty::Int(_))
481 | (ty::FnPtr(..), ty::Uint(_))
482 if to_ty.sty == fx.tcx.types.usize.sty
483 || to_ty.sty == fx.tcx.types.isize.sty
484 || fx.clif_type(to_ty).unwrap() == pointer_ty(fx.tcx) =>
486 lval.write_cvalue(fx, operand.unchecked_cast_to(dest_layout));
488 (ty::Uint(_), ty::RawPtr(..)) if from_ty.sty == fx.tcx.types.usize.sty => {
489 lval.write_cvalue(fx, operand.unchecked_cast_to(dest_layout));
491 (ty::Char, ty::Uint(_))
492 | (ty::Uint(_), ty::Char)
493 | (ty::Uint(_), ty::Int(_))
494 | (ty::Uint(_), ty::Uint(_)) => {
495 let from = operand.load_value(fx);
496 let res = crate::common::clif_intcast(
499 fx.clif_type(to_ty).unwrap(),
502 lval.write_cvalue(fx, CValue::ByVal(res, dest_layout));
504 (ty::Int(_), ty::Int(_)) | (ty::Int(_), ty::Uint(_)) => {
505 let from = operand.load_value(fx);
506 let res = crate::common::clif_intcast(
509 fx.clif_type(to_ty).unwrap(),
512 lval.write_cvalue(fx, CValue::ByVal(res, dest_layout));
514 (ty::Float(from_flt), ty::Float(to_flt)) => {
515 let from = operand.load_value(fx);
516 let res = match (from_flt, to_flt) {
517 (FloatTy::F32, FloatTy::F64) => {
518 fx.bcx.ins().fpromote(types::F64, from)
520 (FloatTy::F64, FloatTy::F32) => {
521 fx.bcx.ins().fdemote(types::F32, from)
525 lval.write_cvalue(fx, CValue::ByVal(res, dest_layout));
527 (ty::Int(_), ty::Float(_)) => {
528 let from_ty = fx.clif_type(from_ty).unwrap();
529 let from = operand.load_value(fx);
530 // FIXME missing encoding for fcvt_from_sint.f32.i8
531 let from = if from_ty == types::I8 || from_ty == types::I16 {
532 fx.bcx.ins().sextend(types::I32, from)
536 let f_type = fx.clif_type(to_ty).unwrap();
537 let res = fx.bcx.ins().fcvt_from_sint(f_type, from);
538 lval.write_cvalue(fx, CValue::ByVal(res, dest_layout));
540 (ty::Uint(_), ty::Float(_)) => {
541 let from_ty = fx.clif_type(from_ty).unwrap();
542 let from = operand.load_value(fx);
543 // FIXME missing encoding for fcvt_from_uint.f32.i8
544 let from = if from_ty == types::I8 || from_ty == types::I16 {
545 fx.bcx.ins().uextend(types::I32, from)
549 let f_type = fx.clif_type(to_ty).unwrap();
550 let res = fx.bcx.ins().fcvt_from_uint(f_type, from);
551 lval.write_cvalue(fx, CValue::ByVal(res, dest_layout));
553 (ty::Bool, ty::Uint(_)) | (ty::Bool, ty::Int(_)) => {
554 let to_ty = fx.clif_type(to_ty).unwrap();
555 let from = operand.load_value(fx);
556 let res = if to_ty != types::I8 {
557 fx.bcx.ins().uextend(to_ty, from)
561 lval.write_cvalue(fx, CValue::ByVal(res, dest_layout));
563 (ty::Adt(adt_def, _substs), ty::Uint(_)) | (ty::Adt(adt_def, _substs), ty::Int(_)) if adt_def.is_enum() => {
564 let discr = trans_get_discriminant(fx, operand, fx.layout_of(to_ty));
565 lval.write_cvalue(fx, discr);
567 _ => unimpl!("rval misc {:?} {:?}", from_ty, to_ty),
570 Rvalue::Cast(CastKind::ClosureFnPointer, operand, ty) => {
571 unimplemented!("rval closure_fn_ptr {:?} {:?}", operand, ty)
573 Rvalue::Cast(CastKind::Unsize, operand, _ty) => {
574 let operand = trans_operand(fx, operand);
575 operand.unsize_value(fx, lval);
577 Rvalue::Discriminant(place) => {
578 let place = trans_place(fx, place).to_cvalue(fx);
579 let discr = trans_get_discriminant(fx, place, dest_layout);
580 lval.write_cvalue(fx, discr);
582 Rvalue::Repeat(operand, times) => {
583 let operand = trans_operand(fx, operand);
585 let index = fx.bcx.ins().iconst(fx.pointer_type, i as i64);
586 let to = lval.place_index(fx, index);
587 to.write_cvalue(fx, operand);
590 Rvalue::Len(place) => {
591 let place = trans_place(fx, place);
592 let usize_layout = fx.layout_of(fx.tcx.types.usize);
593 let len = codegen_array_len(fx, place);
594 lval.write_cvalue(fx, CValue::ByVal(len, usize_layout));
596 Rvalue::NullaryOp(NullOp::Box, content_ty) => {
597 use rustc::middle::lang_items::ExchangeMallocFnLangItem;
599 let usize_type = fx.clif_type(fx.tcx.types.usize).unwrap();
600 let layout = fx.layout_of(content_ty);
601 let llsize = fx.bcx.ins().iconst(usize_type, layout.size.bytes() as i64);
605 .iconst(usize_type, layout.align.abi.bytes() as i64);
606 let box_layout = fx.layout_of(fx.tcx.mk_box(content_ty));
609 let def_id = match fx.tcx.lang_items().require(ExchangeMallocFnLangItem) {
614 .fatal(&format!("allocation of `{}` {}", box_layout.ty, s));
617 let instance = ty::Instance::mono(fx.tcx, def_id);
618 let func_ref = fx.get_function_ref(instance);
619 let call = fx.bcx.ins().call(func_ref, &[llsize, llalign]);
620 let ptr = fx.bcx.inst_results(call)[0];
621 lval.write_cvalue(fx, CValue::ByVal(ptr, box_layout));
623 Rvalue::NullaryOp(NullOp::SizeOf, ty) => {
627 .is_sized(fx.tcx.at(DUMMY_SP), ParamEnv::reveal_all()));
628 let ty_size = fx.layout_of(ty).size.bytes();
629 let val = CValue::const_val(fx, fx.tcx.types.usize, ty_size as i64);
630 lval.write_cvalue(fx, val);
632 Rvalue::Aggregate(kind, operands) => match **kind {
633 AggregateKind::Array(_ty) => {
634 for (i, operand) in operands.into_iter().enumerate() {
635 let operand = trans_operand(fx, operand);
636 let index = fx.bcx.ins().iconst(fx.pointer_type, i as i64);
637 let to = lval.place_index(fx, index);
638 to.write_cvalue(fx, operand);
641 _ => unimpl!("shouldn't exist at trans {:?}", rval),
645 StatementKind::StorageLive(_)
646 | StatementKind::StorageDead(_)
648 | StatementKind::FakeRead(..)
649 | StatementKind::Retag { .. }
650 | StatementKind::AscribeUserType(..) => {}
652 StatementKind::InlineAsm { .. } => unimpl!("Inline assembly is not supported"),
656 fn codegen_array_len<'a, 'tcx: 'a>(
657 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
660 match place.layout().ty.sty {
661 ty::Array(_elem_ty, len) => {
662 let len = crate::constant::force_eval_const(fx, len).unwrap_usize(fx.tcx) as i64;
663 fx.bcx.ins().iconst(fx.pointer_type, len)
665 ty::Slice(_elem_ty) => match place {
666 CPlace::Addr(_, size, _) => size.unwrap(),
667 CPlace::Var(_, _) => unreachable!(),
669 _ => bug!("Rvalue::Len({:?})", place),
673 pub fn trans_get_discriminant<'a, 'tcx: 'a>(
674 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
676 dest_layout: TyLayout<'tcx>,
678 let layout = value.layout();
680 if layout.abi == layout::Abi::Uninhabited {
681 trap_unreachable(&mut fx.bcx);
683 match layout.variants {
684 layout::Variants::Single { index } => {
685 let discr_val = layout
688 .map_or(index.as_u32() as u128, |def| {
689 def.discriminant_for_variant(fx.tcx, index).val
691 return CValue::const_val(fx, dest_layout.ty, discr_val as u64 as i64);
693 layout::Variants::Tagged { .. } | layout::Variants::NicheFilling { .. } => {}
696 let discr = value.value_field(fx, mir::Field::new(0));
697 let discr_ty = discr.layout().ty;
698 let lldiscr = discr.load_value(fx);
699 match layout.variants {
700 layout::Variants::Single { .. } => bug!(),
701 layout::Variants::Tagged { ref tag, .. } => {
702 let signed = match tag.value {
703 layout::Int(_, signed) => signed,
706 let val = clif_intcast(fx, lldiscr, fx.clif_type(dest_layout.ty).unwrap(), signed);
707 return CValue::ByVal(val, dest_layout);
709 layout::Variants::NicheFilling {
715 let niche_llty = fx.clif_type(discr_ty).unwrap();
716 let dest_clif_ty = fx.clif_type(dest_layout.ty).unwrap();
717 if niche_variants.start() == niche_variants.end() {
721 .icmp_imm(IntCC::Equal, lldiscr, niche_start as u64 as i64);
725 .iconst(dest_clif_ty, niche_variants.start().as_u32() as i64);
729 .iconst(dest_clif_ty, dataful_variant.as_u32() as i64);
730 let val = fx.bcx.ins().select(b, if_true, if_false);
731 return CValue::ByVal(val, dest_layout);
733 // Rebase from niche values to discriminant values.
734 let delta = niche_start.wrapping_sub(niche_variants.start().as_u32() as u128);
735 let delta = fx.bcx.ins().iconst(niche_llty, delta as u64 as i64);
736 let lldiscr = fx.bcx.ins().isub(lldiscr, delta);
737 let b = fx.bcx.ins().icmp_imm(
738 IntCC::UnsignedLessThanOrEqual,
740 niche_variants.end().as_u32() as i64,
743 clif_intcast(fx, lldiscr, fx.clif_type(dest_layout.ty).unwrap(), false);
747 .iconst(dest_clif_ty, dataful_variant.as_u32() as i64);
748 let val = fx.bcx.ins().select(b, if_true, if_false);
749 return CValue::ByVal(val, dest_layout);
755 macro_rules! binop_match {
756 (@single $fx:expr, $bug_fmt:expr, $var:expr, $signed:expr, $lhs:expr, $rhs:expr, $ret_ty:expr, bug) => {
757 bug!("binop {} on {} lhs: {:?} rhs: {:?}", stringify!($var), $bug_fmt, $lhs, $rhs)
759 (@single $fx:expr, $bug_fmt:expr, $var:expr, $signed:expr, $lhs:expr, $rhs:expr, $ret_ty:expr, icmp($cc:ident)) => {{
760 assert_eq!($fx.tcx.types.bool, $ret_ty);
761 let ret_layout = $fx.layout_of($ret_ty);
763 let b = $fx.bcx.ins().icmp(IntCC::$cc, $lhs, $rhs);
764 CValue::ByVal($fx.bcx.ins().bint(types::I8, b), ret_layout)
766 (@single $fx:expr, $bug_fmt:expr, $var:expr, $signed:expr, $lhs:expr, $rhs:expr, $ret_ty:expr, fcmp($cc:ident)) => {{
767 assert_eq!($fx.tcx.types.bool, $ret_ty);
768 let ret_layout = $fx.layout_of($ret_ty);
769 let b = $fx.bcx.ins().fcmp(FloatCC::$cc, $lhs, $rhs);
770 CValue::ByVal($fx.bcx.ins().bint(types::I8, b), ret_layout)
772 (@single $fx:expr, $bug_fmt:expr, $var:expr, $signed:expr, $lhs:expr, $rhs:expr, $ret_ty:expr, custom(|| $body:expr)) => {{
775 (@single $fx:expr, $bug_fmt:expr, $var:expr, $signed:expr, $lhs:expr, $rhs:expr, $ret_ty:expr, $name:ident) => {{
776 let ret_layout = $fx.layout_of($ret_ty);
777 CValue::ByVal($fx.bcx.ins().$name($lhs, $rhs), ret_layout)
780 $fx:expr, $bin_op:expr, $signed:expr, $lhs:expr, $rhs:expr, $ret_ty:expr, $bug_fmt:expr;
782 $var:ident ($sign:pat) $name:tt $( ( $($next:tt)* ) )? ;
785 let lhs = $lhs.load_value($fx);
786 let rhs = $rhs.load_value($fx);
787 match ($bin_op, $signed) {
789 (BinOp::$var, $sign) => binop_match!(@single $fx, $bug_fmt, $var, $signed, lhs, rhs, $ret_ty, $name $( ( $($next)* ) )?),
795 fn trans_bool_binop<'a, 'tcx: 'a>(
796 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
802 let res = binop_match! {
803 fx, bin_op, false, lhs, rhs, ty, "bool";
816 Lt (_) icmp(UnsignedLessThan);
817 Le (_) icmp(UnsignedLessThanOrEqual);
818 Ne (_) icmp(NotEqual);
819 Ge (_) icmp(UnsignedGreaterThanOrEqual);
820 Gt (_) icmp(UnsignedGreaterThan);
828 pub fn trans_int_binop<'a, 'tcx: 'a>(
829 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
836 if bin_op != BinOp::Shl && bin_op != BinOp::Shr {
840 "int binop requires lhs and rhs of same type"
844 fx, bin_op, signed, lhs, rhs, out_ty, "int/uint";
860 Lt (false) icmp(UnsignedLessThan);
861 Lt (true) icmp(SignedLessThan);
862 Le (false) icmp(UnsignedLessThanOrEqual);
863 Le (true) icmp(SignedLessThanOrEqual);
864 Ne (_) icmp(NotEqual);
865 Ge (false) icmp(UnsignedGreaterThanOrEqual);
866 Ge (true) icmp(SignedGreaterThanOrEqual);
867 Gt (false) icmp(UnsignedGreaterThan);
868 Gt (true) icmp(SignedGreaterThan);
874 pub fn trans_checked_int_binop<'a, 'tcx: 'a>(
875 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
877 in_lhs: CValue<'tcx>,
878 in_rhs: CValue<'tcx>,
882 if bin_op != BinOp::Shl && bin_op != BinOp::Shr {
886 "checked int binop requires lhs and rhs of same type"
890 let lhs = in_lhs.load_value(fx);
891 let rhs = in_rhs.load_value(fx);
892 let res = match bin_op {
893 BinOp::Add => fx.bcx.ins().iadd(lhs, rhs),
894 BinOp::Sub => fx.bcx.ins().isub(lhs, rhs),
895 BinOp::Mul => fx.bcx.ins().imul(lhs, rhs),
896 BinOp::Shl => fx.bcx.ins().ishl(lhs, rhs),
899 fx.bcx.ins().ushr(lhs, rhs)
901 fx.bcx.ins().sshr(lhs, rhs)
905 "binop {:?} on checked int/uint lhs: {:?} rhs: {:?}",
912 // TODO: check for overflow
913 let has_overflow = fx.bcx.ins().iconst(types::I8, 0);
915 let out_place = CPlace::temp(fx, out_ty);
916 let out_layout = out_place.layout();
917 out_place.write_cvalue(fx, CValue::ByValPair(res, has_overflow, out_layout));
919 out_place.to_cvalue(fx)
922 fn trans_float_binop<'a, 'tcx: 'a>(
923 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
929 let res = binop_match! {
930 fx, bin_op, false, lhs, rhs, ty, "float";
936 assert_eq!(lhs.layout().ty, ty);
937 assert_eq!(rhs.layout().ty, ty);
939 ty::Float(FloatTy::F32) => fx.easy_call("fmodf", &[lhs, rhs], ty),
940 ty::Float(FloatTy::F64) => fx.easy_call("fmod", &[lhs, rhs], ty),
951 Lt (_) fcmp(LessThan);
952 Le (_) fcmp(LessThanOrEqual);
953 Ne (_) fcmp(NotEqual);
954 Ge (_) fcmp(GreaterThanOrEqual);
955 Gt (_) fcmp(GreaterThan);
963 fn trans_char_binop<'a, 'tcx: 'a>(
964 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
970 let res = binop_match! {
971 fx, bin_op, false, lhs, rhs, ty, "char";
984 Lt (_) icmp(UnsignedLessThan);
985 Le (_) icmp(UnsignedLessThanOrEqual);
986 Ne (_) icmp(NotEqual);
987 Ge (_) icmp(UnsignedGreaterThanOrEqual);
988 Gt (_) icmp(UnsignedGreaterThan);
996 fn trans_ptr_binop<'a, 'tcx: 'a>(
997 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
1003 match lhs.layout().ty.sty {
1004 ty::RawPtr(TypeAndMut { ty, mutbl: _ }) => {
1005 if ty.is_sized(fx.tcx.at(DUMMY_SP), ParamEnv::reveal_all()) {
1007 fx, bin_op, false, lhs, rhs, ret_ty, "ptr";
1020 Lt (_) icmp(UnsignedLessThan);
1021 Le (_) icmp(UnsignedLessThanOrEqual);
1022 Ne (_) icmp(NotEqual);
1023 Ge (_) icmp(UnsignedGreaterThanOrEqual);
1024 Gt (_) icmp(UnsignedGreaterThan);
1029 let lhs = lhs.load_value_pair(fx).0;
1030 let rhs = rhs.load_value_pair(fx).0;
1031 let res = match bin_op {
1032 BinOp::Eq => fx.bcx.ins().icmp(IntCC::Equal, lhs, rhs),
1033 BinOp::Ne => fx.bcx.ins().icmp(IntCC::NotEqual, lhs, rhs),
1034 _ => unimplemented!(
1035 "trans_ptr_binop({:?}, <fat ptr>, <fat ptr>) not implemented",
1040 assert_eq!(fx.tcx.types.bool, ret_ty);
1041 let ret_layout = fx.layout_of(ret_ty);
1042 CValue::ByVal(fx.bcx.ins().bint(types::I8, res), ret_layout)
1045 _ => bug!("trans_ptr_binop on non ptr"),
1049 pub fn trans_place<'a, 'tcx: 'a>(
1050 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
1051 place: &Place<'tcx>,
1054 Place::Local(local) => fx.get_local_place(*local),
1055 Place::Promoted(promoted) => crate::constant::trans_promoted(fx, promoted.0),
1056 Place::Static(static_) => crate::constant::codegen_static_ref(fx, static_),
1057 Place::Projection(projection) => {
1058 let base = trans_place(fx, &projection.base);
1059 match projection.elem {
1060 ProjectionElem::Deref => base.place_deref(fx),
1061 ProjectionElem::Field(field, _ty) => base.place_field(fx, field),
1062 ProjectionElem::Index(local) => {
1063 let index = fx.get_local_place(local).to_cvalue(fx).load_value(fx);
1064 base.place_index(fx, index)
1066 ProjectionElem::ConstantIndex {
1071 let index = if !from_end {
1072 fx.bcx.ins().iconst(fx.pointer_type, offset as i64)
1074 let len = codegen_array_len(fx, base);
1075 fx.bcx.ins().iadd_imm(len, -(offset as i64))
1077 base.place_index(fx, index)
1079 ProjectionElem::Subslice { from, to } => unimpl!(
1080 "projection subslice {:?} from {} to {}",
1085 ProjectionElem::Downcast(_adt_def, variant) => base.downcast_variant(fx, variant),
1091 pub fn trans_operand<'a, 'tcx>(
1092 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
1093 operand: &Operand<'tcx>,
1096 Operand::Move(place) | Operand::Copy(place) => {
1097 let cplace = trans_place(fx, place);
1098 cplace.to_cvalue(fx)
1100 Operand::Constant(const_) => crate::constant::trans_constant(fx, const_),