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, 'tcx: 'a>(
13 tcx: TyCtxt<'a, 'tcx, 'tcx>,
14 module: &mut Module<impl Backend>,
15 caches: &mut Caches<'tcx>,
16 ccx: &mut crate::constant::ConstantCx,
17 mono_item: MonoItem<'tcx>,
20 MonoItem::Fn(inst) => {
21 let _inst_guard = PrintOnPanic(|| format!("{:?}", inst));
22 let _mir_guard = PrintOnPanic(|| {
25 | InstanceDef::DropGlue(_, _)
26 | InstanceDef::Virtual(_, _)
27 if inst.def_id().krate == LOCAL_CRATE =>
29 let mut mir = ::std::io::Cursor::new(Vec::new());
30 crate::rustc_mir::util::write_mir_pretty(
36 String::from_utf8(mir.into_inner()).unwrap()
39 // FIXME fix write_mir_pretty for these instances
40 format!("{:#?}", tcx.instance_mir(inst.def))
45 trans_fn(tcx, module, ccx, caches, inst);
47 MonoItem::Static(def_id) => {
48 crate::constant::codegen_static(ccx, def_id);
50 MonoItem::GlobalAsm(node_id) => tcx
52 .fatal(&format!("Unimplemented global asm mono item {:?}", node_id)),
56 fn trans_fn<'a, 'tcx: 'a>(
57 tcx: TyCtxt<'a, 'tcx, 'tcx>,
58 module: &mut Module<impl Backend>,
59 constants: &mut crate::constant::ConstantCx,
60 caches: &mut Caches<'tcx>,
61 instance: Instance<'tcx>,
64 let mir = tcx.instance_mir(instance.def);
66 // Step 2. Declare function
67 let (name, sig) = get_function_name_and_sig(tcx, instance);
69 .declare_function(&name, Linkage::Export, &sig)
72 // Step 3. Make FunctionBuilder
73 let mut func = Function::with_name_signature(ExternalName::user(0, 0), sig);
74 let mut func_ctx = FunctionBuilderContext::new();
75 let mut bcx: FunctionBuilder = FunctionBuilder::new(&mut func, &mut func_ctx);
77 // Step 4. Predefine ebb's
78 let start_ebb = bcx.create_ebb();
79 let mut ebb_map: HashMap<BasicBlock, Ebb> = HashMap::new();
80 for (bb, _bb_data) in mir.basic_blocks().iter_enumerated() {
81 ebb_map.insert(bb, bcx.create_ebb());
84 // Step 5. Make FunctionCx
85 let pointer_type = module.target_config().pointer_type();
86 let mut fx = FunctionCx {
94 assert!(!instance.substs.needs_infer());
98 local_map: HashMap::new(),
99 comments: HashMap::new(),
106 // Step 6. Codegen function
107 crate::abi::codegen_fn_prelude(&mut fx, start_ebb);
108 codegen_fn_content(&mut fx);
110 // Step 7. Write function to file for debugging
111 let mut writer = crate::pretty_clif::CommentWriter(fx.comments);
113 let mut cton = String::new();
114 if cfg!(debug_assertions) {
115 ::cranelift::codegen::write::decorate_function(&mut writer, &mut cton, &func, None)
117 let clif_file_name = format!(
119 concat!(env!("CARGO_MANIFEST_DIR"), "/target/out/clif"),
120 tcx.crate_name(LOCAL_CRATE),
121 tcx.symbol_name(instance).as_str(),
123 if let Err(e) = ::std::fs::write(clif_file_name, cton.as_bytes()) {
124 tcx.sess.warn(&format!("err writing clif file: {:?}", e));
128 // Step 8. Verify function
129 verify_func(tcx, writer, &func);
131 // Step 9. Define function
132 // TODO: cranelift doesn't yet support some of the things needed
133 if should_codegen(tcx.sess) {
134 caches.context.func = func;
136 .define_function(func_id, &mut caches.context)
138 caches.context.clear();
142 fn verify_func(tcx: TyCtxt, writer: crate::pretty_clif::CommentWriter, func: &Function) {
143 let flags = settings::Flags::new(settings::builder());
144 match ::cranelift::codegen::verify_function(&func, &flags) {
147 tcx.sess.err(&format!("{:?}", err));
148 let pretty_error = ::cranelift::codegen::print_errors::pretty_verifier_error(
151 Some(Box::new(writer)),
155 .fatal(&format!("cretonne verify error:\n{}", pretty_error));
160 fn codegen_fn_content<'a, 'tcx: 'a>(fx: &mut FunctionCx<'a, 'tcx, impl Backend>) {
161 for (bb, bb_data) in fx.mir.basic_blocks().iter_enumerated() {
162 if bb_data.is_cleanup {
163 // Unwinding after panicking is not supported
167 let ebb = fx.get_ebb(bb);
168 fx.bcx.switch_to_block(ebb);
171 for stmt in &bb_data.statements {
172 trans_stmt(fx, ebb, stmt);
175 let mut terminator_head = "\n".to_string();
179 .fmt_head(&mut terminator_head)
181 let inst = fx.bcx.func.layout.last_inst(ebb).unwrap();
182 fx.add_comment(inst, terminator_head);
184 match &bb_data.terminator().kind {
185 TerminatorKind::Goto { target } => {
186 let ebb = fx.get_ebb(*target);
187 fx.bcx.ins().jump(ebb, &[]);
189 TerminatorKind::Return => {
190 crate::abi::codegen_return(fx);
192 TerminatorKind::Assert {
199 let cond = trans_operand(fx, cond).load_value(fx);
200 // TODO HACK brz/brnz for i8/i16 is not yet implemented
201 let cond = fx.bcx.ins().uextend(types::I32, cond);
202 let target = fx.get_ebb(*target);
204 fx.bcx.ins().brnz(cond, target, &[]);
206 fx.bcx.ins().brz(cond, target, &[]);
208 fx.bcx.ins().trap(TrapCode::User(!0));
211 TerminatorKind::SwitchInt {
217 let discr = trans_operand(fx, discr).load_value(fx);
218 let mut switch = ::cranelift::frontend::Switch::new();
219 for (i, value) in values.iter().enumerate() {
220 let ebb = fx.get_ebb(targets[i]);
221 switch.set_entry(*value as u64, ebb);
223 let otherwise_ebb = fx.get_ebb(targets[targets.len() - 1]);
224 switch.emit(&mut fx.bcx, discr, otherwise_ebb);
226 TerminatorKind::Call {
233 crate::abi::codegen_terminator_call(fx, func, args, destination);
235 TerminatorKind::Resume | TerminatorKind::Abort | TerminatorKind::Unreachable => {
236 fx.bcx.ins().trap(TrapCode::User(!0));
238 TerminatorKind::Yield { .. }
239 | TerminatorKind::FalseEdges { .. }
240 | TerminatorKind::FalseUnwind { .. }
241 | TerminatorKind::DropAndReplace { .. } => {
242 bug!("shouldn't exist at trans {:?}", bb_data.terminator());
244 TerminatorKind::Drop {
249 let ty = location.ty(fx.mir, fx.tcx).to_ty(fx.tcx);
250 let ty = fx.monomorphize(&ty);
251 let drop_fn = crate::rustc_mir::monomorphize::resolve_drop_in_place(fx.tcx, ty);
253 if let ty::InstanceDef::DropGlue(_, None) = drop_fn.def {
254 // we don't actually need to drop anything
256 let drop_place = trans_place(fx, location);
257 let arg_place = CPlace::temp(
260 &ty::RegionKind::ReErased,
263 mutbl: crate::rustc::hir::Mutability::MutMutable,
267 drop_place.write_place_ref(fx, arg_place);
270 unimplemented!("Drop for trait object");
273 let drop_fn_ty = drop_fn.ty(fx.tcx);
274 let arg_value = arg_place.to_cvalue(fx);
275 crate::abi::codegen_call_inner(
286 /*let mut args = if let Some(llextra) = place.llextra {
287 args2 = [place.llval, llextra];
290 args1 = [place.llval];
293 let (drop_fn, fn_ty) = match ty.sty {
295 let fn_ty = drop_fn.ty(bx.cx.tcx);
296 let sig = common::ty_fn_sig(bx.cx, fn_ty);
297 let sig = bx.tcx().normalize_erasing_late_bound_regions(
298 ty::ParamEnv::reveal_all(),
301 let fn_ty = FnType::new_vtable(bx.cx, sig, &[]);
302 let vtable = args[1];
304 (meth::DESTRUCTOR.get_fn(&bx, vtable, &fn_ty), fn_ty)
307 let value = place.to_cvalue(fx);
308 (callee::get_fn(bx.cx, drop_fn),
309 FnType::of_instance(bx.cx, &drop_fn))
312 do_call(self, bx, fn_ty, drop_fn, args,
313 Some((ReturnDest::Nothing, target)),
317 let target_ebb = fx.get_ebb(*target);
318 fx.bcx.ins().jump(target_ebb, &[]);
320 TerminatorKind::GeneratorDrop => {
321 unimplemented!("terminator GeneratorDrop");
326 fx.bcx.seal_all_blocks();
330 fn trans_stmt<'a, 'tcx: 'a>(
331 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
333 stmt: &Statement<'tcx>,
335 let _print_guard = PrintOnPanic(|| format!("stmt {:?}", stmt));
338 StatementKind::StorageLive(..) | StatementKind::StorageDead(..) => {} // Those are not very useful
340 let inst = fx.bcx.func.layout.last_inst(cur_ebb).unwrap();
341 fx.add_comment(inst, format!("{:?}", stmt));
346 StatementKind::SetDiscriminant {
350 let place = trans_place(fx, place);
351 let layout = place.layout();
352 if layout.for_variant(&*fx, *variant_index).abi == layout::Abi::Uninhabited {
355 match layout.variants {
356 layout::Variants::Single { index } => {
357 assert_eq!(index, *variant_index);
359 layout::Variants::Tagged { .. } => {
360 let ptr = place.place_field(fx, mir::Field::new(0));
365 .discriminant_for_variant(fx.tcx, *variant_index)
367 let discr = CValue::const_val(fx, ptr.layout().ty, to as u64 as i64);
368 ptr.write_cvalue(fx, discr);
370 layout::Variants::NicheFilling {
376 if *variant_index != dataful_variant {
377 let niche = place.place_field(fx, mir::Field::new(0));
378 //let niche_llty = niche.layout.immediate_llvm_type(bx.cx);
379 let niche_value = ((variant_index - *niche_variants.start()) as u128)
380 .wrapping_add(niche_start);
381 // FIXME(eddyb) Check the actual primitive type here.
382 let niche_llval = if niche_value == 0 {
383 CValue::const_val(fx, niche.layout().ty, 0)
385 CValue::const_val(fx, niche.layout().ty, niche_value as u64 as i64)
387 niche.write_cvalue(fx, niche_llval);
392 StatementKind::Assign(to_place, rval) => {
393 let lval = trans_place(fx, to_place);
394 let dest_layout = lval.layout();
396 Rvalue::Use(operand) => {
397 let val = trans_operand(fx, operand);
398 lval.write_cvalue(fx, val);
400 Rvalue::Ref(_, _, place) => {
401 let place = trans_place(fx, place);
402 place.write_place_ref(fx, lval);
404 Rvalue::BinaryOp(bin_op, lhs, rhs) => {
405 let ty = fx.monomorphize(&lhs.ty(fx.mir, fx.tcx));
406 let lhs = trans_operand(fx, lhs);
407 let rhs = trans_operand(fx, rhs);
409 let res = match ty.sty {
410 ty::Bool => trans_bool_binop(fx, *bin_op, lhs, rhs, lval.layout().ty),
412 trans_int_binop(fx, *bin_op, lhs, rhs, lval.layout().ty, false)
415 trans_int_binop(fx, *bin_op, lhs, rhs, lval.layout().ty, true)
417 ty::Float(_) => trans_float_binop(fx, *bin_op, lhs, rhs, lval.layout().ty),
418 ty::Char => trans_char_binop(fx, *bin_op, lhs, rhs, lval.layout().ty),
419 ty::RawPtr(..) => trans_ptr_binop(fx, *bin_op, lhs, rhs, lval.layout().ty),
420 _ => unimplemented!("binop {:?} for {:?}", bin_op, ty),
422 lval.write_cvalue(fx, res);
424 Rvalue::CheckedBinaryOp(bin_op, lhs, rhs) => {
425 let ty = fx.monomorphize(&lhs.ty(fx.mir, fx.tcx));
426 let lhs = trans_operand(fx, lhs);
427 let rhs = trans_operand(fx, rhs);
429 let res = match ty.sty {
431 trans_checked_int_binop(fx, *bin_op, lhs, rhs, lval.layout().ty, false)
434 trans_checked_int_binop(fx, *bin_op, lhs, rhs, lval.layout().ty, true)
436 _ => unimplemented!("checked binop {:?} for {:?}", bin_op, ty),
438 lval.write_cvalue(fx, res);
440 Rvalue::UnaryOp(un_op, operand) => {
441 let operand = trans_operand(fx, operand);
442 let layout = operand.layout();
443 let val = operand.load_value(fx);
444 let res = match un_op {
446 match layout.ty.sty {
448 let val = fx.bcx.ins().uextend(types::I32, val); // WORKAROUND for CraneStation/cranelift#466
449 let res = fx.bcx.ins().icmp_imm(IntCC::Equal, val, 0);
450 fx.bcx.ins().bint(types::I8, res)
452 ty::Uint(_) | ty::Int(_) => fx.bcx.ins().bnot(val),
453 _ => unimplemented!("un op Not for {:?}", layout.ty),
456 UnOp::Neg => match layout.ty.sty {
458 let clif_ty = fx.cton_type(layout.ty).unwrap();
459 let zero = fx.bcx.ins().iconst(clif_ty, 0);
460 fx.bcx.ins().isub(zero, val)
462 ty::Float(_) => fx.bcx.ins().fneg(val),
463 _ => unimplemented!("un op Neg for {:?}", layout.ty),
466 lval.write_cvalue(fx, CValue::ByVal(res, layout));
468 Rvalue::Cast(CastKind::ReifyFnPointer, operand, ty) => {
469 let operand = trans_operand(fx, operand);
470 let layout = fx.layout_of(ty);
471 lval.write_cvalue(fx, operand.unchecked_cast_to(layout));
473 Rvalue::Cast(CastKind::UnsafeFnPointer, operand, ty) => {
474 let operand = trans_operand(fx, operand);
475 let layout = fx.layout_of(ty);
476 lval.write_cvalue(fx, operand.unchecked_cast_to(layout));
478 Rvalue::Cast(CastKind::Misc, operand, to_ty) => {
479 let operand = trans_operand(fx, operand);
480 let from_ty = operand.layout().ty;
481 match (&from_ty.sty, &to_ty.sty) {
482 (ty::Ref(..), ty::Ref(..))
483 | (ty::Ref(..), ty::RawPtr(..))
484 | (ty::RawPtr(..), ty::Ref(..))
485 | (ty::RawPtr(..), ty::RawPtr(..)) => {
486 lval.write_cvalue(fx, operand.unchecked_cast_to(dest_layout));
488 (ty::RawPtr(..), ty::Uint(_)) | (ty::FnPtr(..), ty::Uint(_))
489 if to_ty.sty == fx.tcx.types.usize.sty =>
491 lval.write_cvalue(fx, operand.unchecked_cast_to(dest_layout));
493 (ty::Uint(_), ty::RawPtr(..)) if from_ty.sty == fx.tcx.types.usize.sty => {
494 lval.write_cvalue(fx, operand.unchecked_cast_to(dest_layout));
496 (ty::Char, ty::Uint(_))
497 | (ty::Uint(_), ty::Char)
498 | (ty::Uint(_), ty::Int(_))
499 | (ty::Uint(_), ty::Uint(_)) => {
500 let from = operand.load_value(fx);
501 let res = crate::common::cton_intcast(
504 fx.cton_type(to_ty).unwrap(),
507 lval.write_cvalue(fx, CValue::ByVal(res, dest_layout));
509 (ty::Int(_), ty::Int(_)) | (ty::Int(_), ty::Uint(_)) => {
510 let from = operand.load_value(fx);
511 let res = crate::common::cton_intcast(
514 fx.cton_type(to_ty).unwrap(),
517 lval.write_cvalue(fx, CValue::ByVal(res, dest_layout));
519 (ty::Float(from_flt), ty::Float(to_flt)) => {
520 let from = operand.load_value(fx);
521 let res = match (from_flt, to_flt) {
522 (FloatTy::F32, FloatTy::F64) => {
523 fx.bcx.ins().fpromote(types::F64, from)
525 (FloatTy::F64, FloatTy::F32) => {
526 fx.bcx.ins().fdemote(types::F32, from)
530 lval.write_cvalue(fx, CValue::ByVal(res, dest_layout));
532 (ty::Int(_), ty::Float(_)) => {
533 let from_ty = fx.cton_type(from_ty).unwrap();
534 let from = operand.load_value(fx);
535 // FIXME missing encoding for fcvt_from_sint.f32.i8
536 let from = if from_ty == types::I8 || from_ty == types::I16 {
537 fx.bcx.ins().sextend(types::I32, from)
541 let f_type = fx.cton_type(to_ty).unwrap();
542 let res = fx.bcx.ins().fcvt_from_sint(f_type, from);
543 lval.write_cvalue(fx, CValue::ByVal(res, dest_layout));
545 (ty::Uint(_), ty::Float(_)) => {
546 let from_ty = fx.cton_type(from_ty).unwrap();
547 let from = operand.load_value(fx);
548 // FIXME missing encoding for fcvt_from_uint.f32.i8
549 let from = if from_ty == types::I8 || from_ty == types::I16 {
550 fx.bcx.ins().uextend(types::I32, from)
554 let f_type = fx.cton_type(to_ty).unwrap();
555 let res = fx.bcx.ins().fcvt_from_uint(f_type, from);
556 lval.write_cvalue(fx, CValue::ByVal(res, dest_layout));
558 (ty::Bool, ty::Uint(_)) | (ty::Bool, ty::Int(_)) => {
559 let to_ty = fx.cton_type(to_ty).unwrap();
560 let from = operand.load_value(fx);
561 let res = if to_ty != types::I8 {
562 fx.bcx.ins().uextend(to_ty, from)
566 lval.write_cvalue(fx, CValue::ByVal(res, dest_layout));
568 _ => unimpl!("rval misc {:?} {:?}", from_ty, to_ty),
571 Rvalue::Cast(CastKind::ClosureFnPointer, operand, ty) => {
572 unimplemented!("rval closure_fn_ptr {:?} {:?}", operand, ty)
574 Rvalue::Cast(CastKind::Unsize, operand, _ty) => {
575 let operand = trans_operand(fx, operand);
576 operand.unsize_value(fx, lval);
578 Rvalue::Discriminant(place) => {
579 let place = trans_place(fx, place).to_cvalue(fx);
580 let discr = trans_get_discriminant(fx, place, dest_layout);
581 lval.write_cvalue(fx, discr);
583 Rvalue::Repeat(operand, times) => {
584 let operand = trans_operand(fx, operand);
586 let index = fx.bcx.ins().iconst(fx.pointer_type, i as i64);
587 let to = lval.place_index(fx, index);
588 to.write_cvalue(fx, operand);
591 Rvalue::Len(place) => {
592 let place = trans_place(fx, place);
593 let usize_layout = fx.layout_of(fx.tcx.types.usize);
594 let len = match place.layout().ty.sty {
595 ty::Array(_elem_ty, len) => {
596 let len = crate::constant::force_eval_const(fx, len)
597 .unwrap_usize(fx.tcx) as i64;
598 fx.bcx.ins().iconst(fx.pointer_type, len)
600 ty::Slice(_elem_ty) => match place {
601 CPlace::Addr(_, size, _) => size.unwrap(),
602 CPlace::Var(_, _) => unreachable!(),
604 _ => bug!("Rvalue::Len({:?})", place),
606 lval.write_cvalue(fx, CValue::ByVal(len, usize_layout));
608 Rvalue::NullaryOp(NullOp::Box, content_ty) => {
609 use rustc::middle::lang_items::ExchangeMallocFnLangItem;
611 let usize_type = fx.cton_type(fx.tcx.types.usize).unwrap();
612 let (size, align) = fx.layout_of(content_ty).size_and_align();
613 let llsize = fx.bcx.ins().iconst(usize_type, size.bytes() as i64);
614 let llalign = fx.bcx.ins().iconst(usize_type, align.abi() as i64);
615 let box_layout = fx.layout_of(fx.tcx.mk_box(content_ty));
618 let def_id = match fx.tcx.lang_items().require(ExchangeMallocFnLangItem) {
623 .fatal(&format!("allocation of `{}` {}", box_layout.ty, s));
626 let instance = ty::Instance::mono(fx.tcx, def_id);
627 let func_ref = fx.get_function_ref(instance);
628 let call = fx.bcx.ins().call(func_ref, &[llsize, llalign]);
629 let ptr = fx.bcx.inst_results(call)[0];
630 lval.write_cvalue(fx, CValue::ByVal(ptr, box_layout));
632 Rvalue::NullaryOp(NullOp::SizeOf, ty) => {
636 .is_sized(fx.tcx.at(DUMMY_SP), ParamEnv::reveal_all())
638 let ty_size = fx.layout_of(ty).size.bytes();
639 let val = CValue::const_val(fx, fx.tcx.types.usize, ty_size as i64);
640 lval.write_cvalue(fx, val);
642 Rvalue::Aggregate(kind, operands) => match **kind {
643 AggregateKind::Array(_ty) => {
644 for (i, operand) in operands.into_iter().enumerate() {
645 let operand = trans_operand(fx, operand);
646 let index = fx.bcx.ins().iconst(fx.pointer_type, i as i64);
647 let to = lval.place_index(fx, index);
648 to.write_cvalue(fx, operand);
651 _ => unimpl!("shouldn't exist at trans {:?}", rval),
655 StatementKind::StorageLive(_)
656 | StatementKind::StorageDead(_)
658 | StatementKind::FakeRead(..)
659 | StatementKind::EndRegion(_)
660 | StatementKind::Retag { .. }
661 | StatementKind::AscribeUserType(..) => {}
663 StatementKind::InlineAsm { .. } => unimpl!("Inline assembly is not supported"),
667 pub fn trans_get_discriminant<'a, 'tcx: 'a>(
668 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
670 dest_layout: TyLayout<'tcx>,
672 let layout = value.layout();
674 if layout.abi == layout::Abi::Uninhabited {
675 fx.bcx.ins().trap(TrapCode::User(!0));
677 match layout.variants {
678 layout::Variants::Single { index } => {
679 let discr_val = layout.ty.ty_adt_def().map_or(index as u128, |def| {
680 def.discriminant_for_variant(fx.tcx, index).val
682 return CValue::const_val(fx, dest_layout.ty, discr_val as u64 as i64);
684 layout::Variants::Tagged { .. } | layout::Variants::NicheFilling { .. } => {}
687 let discr = value.value_field(fx, mir::Field::new(0));
688 let discr_ty = discr.layout().ty;
689 let lldiscr = discr.load_value(fx);
690 match layout.variants {
691 layout::Variants::Single { .. } => bug!(),
692 layout::Variants::Tagged { ref tag, .. } => {
693 let signed = match tag.value {
694 layout::Int(_, signed) => signed,
697 let val = cton_intcast(fx, lldiscr, fx.cton_type(dest_layout.ty).unwrap(), signed);
698 return CValue::ByVal(val, dest_layout);
700 layout::Variants::NicheFilling {
706 let niche_llty = fx.cton_type(discr_ty).unwrap();
707 let dest_cton_ty = fx.cton_type(dest_layout.ty).unwrap();
708 if niche_variants.start() == niche_variants.end() {
712 .icmp_imm(IntCC::Equal, lldiscr, niche_start as u64 as i64);
716 .iconst(dest_cton_ty, *niche_variants.start() as u64 as i64);
720 .iconst(dest_cton_ty, dataful_variant as u64 as i64);
721 let val = fx.bcx.ins().select(b, if_true, if_false);
722 return CValue::ByVal(val, dest_layout);
724 // Rebase from niche values to discriminant values.
725 let delta = niche_start.wrapping_sub(*niche_variants.start() as u128);
726 let delta = fx.bcx.ins().iconst(niche_llty, delta as u64 as i64);
727 let lldiscr = fx.bcx.ins().isub(lldiscr, delta);
728 let b = fx.bcx.ins().icmp_imm(
729 IntCC::UnsignedLessThanOrEqual,
731 *niche_variants.end() as u64 as i64,
734 cton_intcast(fx, lldiscr, fx.cton_type(dest_layout.ty).unwrap(), false);
738 .iconst(dest_cton_ty, dataful_variant as u64 as i64);
739 let val = fx.bcx.ins().select(b, if_true, if_false);
740 return CValue::ByVal(val, dest_layout);
746 macro_rules! binop_match {
747 (@single $fx:expr, $bug_fmt:expr, $var:expr, $signed:expr, $lhs:expr, $rhs:expr, $ret_ty:expr, bug) => {
748 bug!("binop {} on {} lhs: {:?} rhs: {:?}", stringify!($var), $bug_fmt, $lhs, $rhs)
750 (@single $fx:expr, $bug_fmt:expr, $var:expr, $signed:expr, $lhs:expr, $rhs:expr, $ret_ty:expr, icmp($cc:ident)) => {{
751 assert_eq!($fx.tcx.types.bool, $ret_ty);
752 let ret_layout = $fx.layout_of($ret_ty);
754 // TODO HACK no encoding for icmp.i8
755 use crate::common::cton_intcast;
757 cton_intcast($fx, $lhs, types::I64, $signed),
758 cton_intcast($fx, $rhs, types::I64, $signed),
760 let b = $fx.bcx.ins().icmp(IntCC::$cc, lhs, rhs);
762 CValue::ByVal($fx.bcx.ins().bint(types::I8, b), ret_layout)
764 (@single $fx:expr, $bug_fmt:expr, $var:expr, $signed:expr, $lhs:expr, $rhs:expr, $ret_ty:expr, fcmp($cc:ident)) => {{
765 assert_eq!($fx.tcx.types.bool, $ret_ty);
766 let ret_layout = $fx.layout_of($ret_ty);
767 let b = $fx.bcx.ins().fcmp(FloatCC::$cc, $lhs, $rhs);
768 CValue::ByVal($fx.bcx.ins().bint(types::I8, b), ret_layout)
770 (@single $fx:expr, $bug_fmt:expr, $var:expr, $signed:expr, $lhs:expr, $rhs:expr, $ret_ty:expr, custom(|| $body:expr)) => {{
773 (@single $fx:expr, $bug_fmt:expr, $var:expr, $signed:expr, $lhs:expr, $rhs:expr, $ret_ty:expr, $name:ident) => {{
774 let ret_layout = $fx.layout_of($ret_ty);
775 CValue::ByVal($fx.bcx.ins().$name($lhs, $rhs), ret_layout)
778 $fx:expr, $bin_op:expr, $signed:expr, $lhs:expr, $rhs:expr, $ret_ty:expr, $bug_fmt:expr;
780 $var:ident ($sign:pat) $name:tt $( ( $($next:tt)* ) )? ;
783 let lhs = $lhs.load_value($fx);
784 let rhs = $rhs.load_value($fx);
785 match ($bin_op, $signed) {
787 (BinOp::$var, $sign) => binop_match!(@single $fx, $bug_fmt, $var, $signed, lhs, rhs, $ret_ty, $name $( ( $($next)* ) )?),
793 fn trans_bool_binop<'a, 'tcx: 'a>(
794 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
800 let res = binop_match! {
801 fx, bin_op, false, lhs, rhs, ty, "bool";
814 Lt (_) icmp(UnsignedLessThan);
815 Le (_) icmp(UnsignedLessThanOrEqual);
816 Ne (_) icmp(NotEqual);
817 Ge (_) icmp(UnsignedGreaterThanOrEqual);
818 Gt (_) icmp(UnsignedGreaterThan);
826 pub fn trans_int_binop<'a, 'tcx: 'a>(
827 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
834 if bin_op != BinOp::Shl && bin_op != BinOp::Shr {
838 "int binop requires lhs and rhs of same type"
842 fx, bin_op, signed, lhs, rhs, out_ty, "int/uint";
858 Lt (false) icmp(UnsignedLessThan);
859 Lt (true) icmp(SignedLessThan);
860 Le (false) icmp(UnsignedLessThanOrEqual);
861 Le (true) icmp(SignedLessThanOrEqual);
862 Ne (_) icmp(NotEqual);
863 Ge (false) icmp(UnsignedGreaterThanOrEqual);
864 Ge (true) icmp(SignedGreaterThanOrEqual);
865 Gt (false) icmp(UnsignedGreaterThan);
866 Gt (true) icmp(SignedGreaterThan);
872 pub fn trans_checked_int_binop<'a, 'tcx: 'a>(
873 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
875 in_lhs: CValue<'tcx>,
876 in_rhs: CValue<'tcx>,
880 if bin_op != BinOp::Shl && bin_op != BinOp::Shr {
884 "checked int binop requires lhs and rhs of same type"
888 let lhs = in_lhs.load_value(fx);
889 let rhs = in_rhs.load_value(fx);
890 let res = match bin_op {
891 BinOp::Add => fx.bcx.ins().iadd(lhs, rhs),
892 BinOp::Sub => fx.bcx.ins().isub(lhs, rhs),
893 BinOp::Mul => fx.bcx.ins().imul(lhs, rhs),
894 BinOp::Shl => fx.bcx.ins().ishl(lhs, rhs),
897 fx.bcx.ins().ushr(lhs, rhs)
899 fx.bcx.ins().sshr(lhs, rhs)
903 "binop {:?} on checked int/uint lhs: {:?} rhs: {:?}",
910 // TODO: check for overflow
911 let has_overflow = fx.bcx.ins().iconst(types::I8, 0);
913 let out_place = CPlace::temp(fx, out_ty);
914 let out_layout = out_place.layout();
915 out_place.write_cvalue(fx, CValue::ByValPair(res, has_overflow, out_layout));
917 out_place.to_cvalue(fx)
920 fn trans_float_binop<'a, 'tcx: 'a>(
921 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
927 let res = binop_match! {
928 fx, bin_op, false, lhs, rhs, ty, "float";
934 assert_eq!(lhs.layout().ty, ty);
935 assert_eq!(rhs.layout().ty, ty);
937 ty::Float(FloatTy::F32) => fx.easy_call("fmodf", &[lhs, rhs], ty),
938 ty::Float(FloatTy::F64) => fx.easy_call("fmod", &[lhs, rhs], ty),
949 Lt (_) fcmp(LessThan);
950 Le (_) fcmp(LessThanOrEqual);
951 Ne (_) fcmp(NotEqual);
952 Ge (_) fcmp(GreaterThanOrEqual);
953 Gt (_) fcmp(GreaterThan);
961 fn trans_char_binop<'a, 'tcx: 'a>(
962 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
968 let res = binop_match! {
969 fx, bin_op, false, lhs, rhs, ty, "char";
982 Lt (_) icmp(UnsignedLessThan);
983 Le (_) icmp(UnsignedLessThanOrEqual);
984 Ne (_) icmp(NotEqual);
985 Ge (_) icmp(UnsignedGreaterThanOrEqual);
986 Gt (_) icmp(UnsignedGreaterThan);
994 fn trans_ptr_binop<'a, 'tcx: 'a>(
995 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
1001 match lhs.layout().ty.sty {
1002 ty::RawPtr(TypeAndMut { ty, mutbl: _ }) => {
1003 if ty.is_sized(fx.tcx.at(DUMMY_SP), ParamEnv::reveal_all()) {
1005 fx, bin_op, false, lhs, rhs, ret_ty, "ptr";
1018 Lt (_) icmp(UnsignedLessThan);
1019 Le (_) icmp(UnsignedLessThanOrEqual);
1020 Ne (_) icmp(NotEqual);
1021 Ge (_) icmp(UnsignedGreaterThanOrEqual);
1022 Gt (_) icmp(UnsignedGreaterThan);
1027 let lhs = lhs.load_value_pair(fx).0;
1028 let rhs = rhs.load_value_pair(fx).0;
1029 let res = match bin_op {
1030 BinOp::Eq => fx.bcx.ins().icmp(IntCC::Equal, lhs, rhs),
1031 BinOp::Ne => fx.bcx.ins().icmp(IntCC::NotEqual, lhs, rhs),
1032 _ => unimplemented!(
1033 "trans_ptr_binop({:?}, <fat ptr>, <fat ptr>) not implemented",
1038 assert_eq!(fx.tcx.types.bool, ret_ty);
1039 let ret_layout = fx.layout_of(ret_ty);
1040 CValue::ByVal(fx.bcx.ins().bint(types::I8, res), ret_layout)
1043 _ => bug!("trans_ptr_binop on non ptr"),
1047 pub fn trans_place<'a, 'tcx: 'a>(
1048 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
1049 place: &Place<'tcx>,
1052 Place::Local(local) => fx.get_local_place(*local),
1053 Place::Promoted(promoted) => crate::constant::trans_promoted(fx, promoted.0),
1054 Place::Static(static_) => crate::constant::codegen_static_ref(fx, static_),
1055 Place::Projection(projection) => {
1056 let base = trans_place(fx, &projection.base);
1057 match projection.elem {
1058 ProjectionElem::Deref => base.place_deref(fx),
1059 ProjectionElem::Field(field, _ty) => base.place_field(fx, field),
1060 ProjectionElem::Index(local) => {
1061 let index = fx.get_local_place(local).to_cvalue(fx).load_value(fx);
1062 base.place_index(fx, index)
1064 ProjectionElem::ConstantIndex {
1068 } => unimplemented!(
1069 "projection const index {:?} offset {:?} not from end",
1073 ProjectionElem::ConstantIndex {
1077 } => unimplemented!(
1078 "projection const index {:?} offset {:?} from end",
1082 ProjectionElem::Subslice { from, to } => unimplemented!(
1083 "projection subslice {:?} from {} to {}",
1088 ProjectionElem::Downcast(_adt_def, variant) => base.downcast_variant(fx, variant),
1094 pub fn trans_operand<'a, 'tcx>(
1095 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
1096 operand: &Operand<'tcx>,
1099 Operand::Move(place) | Operand::Copy(place) => {
1100 let cplace = trans_place(fx, place);
1101 cplace.to_cvalue(fx)
1103 Operand::Constant(const_) => crate::constant::trans_constant(fx, const_),