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)
72 let mut debug_context = cx.debug_context.as_mut().map(|debug_context| FunctionDebugContext::new(
80 // Step 3. Make FunctionBuilder
81 let mut func = Function::with_name_signature(ExternalName::user(0, 0), sig);
82 let mut func_ctx = FunctionBuilderContext::new();
83 let mut bcx = FunctionBuilder::new(&mut func, &mut func_ctx);
85 // Step 4. Predefine ebb's
86 let start_ebb = bcx.create_ebb();
87 let mut ebb_map: HashMap<BasicBlock, Ebb> = HashMap::new();
88 for (bb, _bb_data) in mir.basic_blocks().iter_enumerated() {
89 ebb_map.insert(bb, bcx.create_ebb());
92 // Step 5. Make FunctionCx
93 let pointer_type = cx.module.target_config().pointer_type();
94 let clif_comments = crate::pretty_clif::CommentWriter::new(tcx, instance);
96 let mut fx = FunctionCx {
106 local_map: HashMap::new(),
109 constants: &mut cx.ccx,
110 caches: &mut cx.caches,
111 source_info_set: indexmap::IndexSet::new(),
114 // Step 6. Codegen function
115 with_unimpl_span(fx.mir.span, || {
116 crate::abi::codegen_fn_prelude(&mut fx, start_ebb);
117 codegen_fn_content(&mut fx);
119 let source_info_set = fx.source_info_set.clone();
121 // Step 7. Write function to file for debugging
122 #[cfg(debug_assertions)]
123 fx.write_clif_file();
125 // Step 8. Verify function
126 verify_func(tcx, fx.clif_comments, &func);
128 // Step 9. Define function
129 cx.caches.context.func = func;
131 .define_function_peek_compiled(func_id, &mut cx.caches.context, |size, context, isa| {
132 debug_context.as_mut().map(|x| x.define(tcx, size, context, isa, &source_info_set));
135 //let module = &mut cx.module;
136 //let caches = &cx.caches;
137 cx.caches.context.clear();
140 fn verify_func(tcx: TyCtxt, writer: crate::pretty_clif::CommentWriter, func: &Function) {
141 let flags = settings::Flags::new(settings::builder());
142 match ::cranelift::codegen::verify_function(&func, &flags) {
145 tcx.sess.err(&format!("{:?}", err));
146 let pretty_error = ::cranelift::codegen::print_errors::pretty_verifier_error(
149 Some(Box::new(&writer)),
153 .fatal(&format!("cranelift verify error:\n{}", pretty_error));
158 fn codegen_fn_content<'a, 'tcx: 'a>(fx: &mut FunctionCx<'a, 'tcx, impl Backend>) {
159 for (bb, bb_data) in fx.mir.basic_blocks().iter_enumerated() {
160 if bb_data.is_cleanup {
161 // Unwinding after panicking is not supported
165 let ebb = fx.get_ebb(bb);
166 fx.bcx.switch_to_block(ebb);
169 for stmt in &bb_data.statements {
170 fx.set_debug_loc(stmt.source_info);
171 trans_stmt(fx, ebb, stmt);
174 #[cfg(debug_assertions)]
176 let mut terminator_head = "\n".to_string();
180 .fmt_head(&mut terminator_head)
182 let inst = fx.bcx.func.layout.last_inst(ebb).unwrap();
183 fx.add_comment(inst, terminator_head);
186 fx.set_debug_loc(bb_data.terminator().source_info);
188 match &bb_data.terminator().kind {
189 TerminatorKind::Goto { target } => {
190 let ebb = fx.get_ebb(*target);
191 fx.bcx.ins().jump(ebb, &[]);
193 TerminatorKind::Return => {
194 crate::abi::codegen_return(fx);
196 TerminatorKind::Assert {
203 let cond = trans_operand(fx, cond).load_scalar(fx);
204 // TODO HACK brz/brnz for i8/i16 is not yet implemented
205 let cond = fx.bcx.ins().uextend(types::I32, cond);
206 let target = fx.get_ebb(*target);
208 fx.bcx.ins().brnz(cond, target, &[]);
210 fx.bcx.ins().brz(cond, target, &[]);
212 trap_panic(&mut fx.bcx);
215 TerminatorKind::SwitchInt {
221 let discr = trans_operand(fx, discr).load_scalar(fx);
222 let mut switch = ::cranelift::frontend::Switch::new();
223 for (i, value) in values.iter().enumerate() {
224 let ebb = fx.get_ebb(targets[i]);
225 switch.set_entry(*value as u64, ebb);
227 let otherwise_ebb = fx.get_ebb(targets[targets.len() - 1]);
228 switch.emit(&mut fx.bcx, discr, otherwise_ebb);
230 TerminatorKind::Call {
237 crate::abi::codegen_terminator_call(fx, func, args, destination);
239 TerminatorKind::Resume | TerminatorKind::Abort | TerminatorKind::Unreachable => {
240 trap_unreachable(&mut fx.bcx);
242 TerminatorKind::Yield { .. }
243 | TerminatorKind::FalseEdges { .. }
244 | TerminatorKind::FalseUnwind { .. }
245 | TerminatorKind::DropAndReplace { .. } => {
246 bug!("shouldn't exist at trans {:?}", bb_data.terminator());
248 TerminatorKind::Drop {
253 let ty = location.ty(fx.mir, fx.tcx).to_ty(fx.tcx);
254 let ty = fx.monomorphize(&ty);
255 let drop_fn = crate::rustc_mir::monomorphize::resolve_drop_in_place(fx.tcx, ty);
257 if let ty::InstanceDef::DropGlue(_, None) = drop_fn.def {
258 // we don't actually need to drop anything
260 let drop_place = trans_place(fx, location);
261 let arg_place = CPlace::new_stack_slot(
264 &ty::RegionKind::ReErased,
267 mutbl: crate::rustc::hir::Mutability::MutMutable,
271 drop_place.write_place_ref(fx, arg_place);
274 fx.tcx.sess.warn("Drop for trait object");
277 let drop_fn_ty = drop_fn.ty(fx.tcx);
278 let arg_value = arg_place.to_cvalue(fx);
279 crate::abi::codegen_call_inner(
290 /*let mut args = if let Some(llextra) = place.llextra {
291 args2 = [place.llval, llextra];
294 args1 = [place.llval];
297 let (drop_fn, fn_ty) = match ty.sty {
299 let fn_ty = drop_fn.ty(bx.cx.tcx);
300 let sig = common::ty_fn_sig(bx.cx, fn_ty);
301 let sig = bx.tcx().normalize_erasing_late_bound_regions(
302 ty::ParamEnv::reveal_all(),
305 let fn_ty = FnType::new_vtable(bx.cx, sig, &[]);
306 let vtable = args[1];
308 (meth::DESTRUCTOR.get_fn(&bx, vtable, &fn_ty), fn_ty)
311 let value = place.to_cvalue(fx);
312 (callee::get_fn(bx.cx, drop_fn),
313 FnType::of_instance(bx.cx, &drop_fn))
316 do_call(self, bx, fn_ty, drop_fn, args,
317 Some((ReturnDest::Nothing, target)),
321 let target_ebb = fx.get_ebb(*target);
322 fx.bcx.ins().jump(target_ebb, &[]);
324 TerminatorKind::GeneratorDrop => {
325 unimplemented!("terminator GeneratorDrop");
330 fx.bcx.seal_all_blocks();
334 fn trans_stmt<'a, 'tcx: 'a>(
335 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
337 stmt: &Statement<'tcx>,
339 let _print_guard = PrintOnPanic(|| format!("stmt {:?}", stmt));
341 fx.set_debug_loc(stmt.source_info);
343 #[cfg(debug_assertions)]
345 StatementKind::StorageLive(..) | StatementKind::StorageDead(..) => {} // Those are not very useful
347 let inst = fx.bcx.func.layout.last_inst(cur_ebb).unwrap();
348 fx.add_comment(inst, format!("{:?}", stmt));
353 StatementKind::SetDiscriminant {
357 let place = trans_place(fx, place);
358 let layout = place.layout();
359 if layout.for_variant(&*fx, *variant_index).abi == layout::Abi::Uninhabited {
362 match layout.variants {
363 layout::Variants::Single { index } => {
364 assert_eq!(index, *variant_index);
366 layout::Variants::Tagged { .. } => {
367 let ptr = place.place_field(fx, mir::Field::new(0));
372 .discriminant_for_variant(fx.tcx, *variant_index)
374 let discr = CValue::const_val(fx, ptr.layout().ty, to as u64 as i64);
375 ptr.write_cvalue(fx, discr);
377 layout::Variants::NicheFilling {
383 if *variant_index != dataful_variant {
384 let niche = place.place_field(fx, mir::Field::new(0));
385 //let niche_llty = niche.layout.immediate_llvm_type(bx.cx);
387 ((variant_index.as_u32() - niche_variants.start().as_u32()) as u128)
388 .wrapping_add(niche_start);
389 // FIXME(eddyb) Check the actual primitive type here.
390 let niche_llval = if niche_value == 0 {
391 CValue::const_val(fx, niche.layout().ty, 0)
393 CValue::const_val(fx, niche.layout().ty, niche_value as u64 as i64)
395 niche.write_cvalue(fx, niche_llval);
400 StatementKind::Assign(to_place, rval) => {
401 let lval = trans_place(fx, to_place);
402 let dest_layout = lval.layout();
404 Rvalue::Use(operand) => {
405 let val = trans_operand(fx, operand);
406 lval.write_cvalue(fx, val);
408 Rvalue::Ref(_, _, place) => {
409 let place = trans_place(fx, place);
410 place.write_place_ref(fx, lval);
412 Rvalue::BinaryOp(bin_op, lhs, rhs) => {
413 let ty = fx.monomorphize(&lhs.ty(fx.mir, fx.tcx));
414 let lhs = trans_operand(fx, lhs);
415 let rhs = trans_operand(fx, rhs);
417 let res = match ty.sty {
418 ty::Bool => trans_bool_binop(fx, *bin_op, lhs, rhs, lval.layout().ty),
420 trans_int_binop(fx, *bin_op, lhs, rhs, lval.layout().ty, false)
423 trans_int_binop(fx, *bin_op, lhs, rhs, lval.layout().ty, true)
425 ty::Float(_) => trans_float_binop(fx, *bin_op, lhs, rhs, lval.layout().ty),
426 ty::Char => trans_char_binop(fx, *bin_op, lhs, rhs, lval.layout().ty),
427 ty::RawPtr(..) => trans_ptr_binop(fx, *bin_op, lhs, rhs, lval.layout().ty),
428 _ => unimplemented!("binop {:?} for {:?}", bin_op, ty),
430 lval.write_cvalue(fx, res);
432 Rvalue::CheckedBinaryOp(bin_op, lhs, rhs) => {
433 let ty = fx.monomorphize(&lhs.ty(fx.mir, fx.tcx));
434 let lhs = trans_operand(fx, lhs);
435 let rhs = trans_operand(fx, rhs);
437 let res = match ty.sty {
439 trans_checked_int_binop(fx, *bin_op, lhs, rhs, lval.layout().ty, false)
442 trans_checked_int_binop(fx, *bin_op, lhs, rhs, lval.layout().ty, true)
444 _ => unimplemented!("checked binop {:?} for {:?}", bin_op, ty),
446 lval.write_cvalue(fx, res);
448 Rvalue::UnaryOp(un_op, operand) => {
449 let operand = trans_operand(fx, operand);
450 let layout = operand.layout();
451 let val = operand.load_scalar(fx);
452 let res = match un_op {
454 match layout.ty.sty {
456 let val = fx.bcx.ins().uextend(types::I32, val); // WORKAROUND for CraneStation/cranelift#466
457 let res = fx.bcx.ins().icmp_imm(IntCC::Equal, val, 0);
458 fx.bcx.ins().bint(types::I8, res)
460 ty::Uint(_) | ty::Int(_) => fx.bcx.ins().bnot(val),
461 _ => unimplemented!("un op Not for {:?}", layout.ty),
464 UnOp::Neg => match layout.ty.sty {
466 let clif_ty = fx.clif_type(layout.ty).unwrap();
467 let zero = fx.bcx.ins().iconst(clif_ty, 0);
468 fx.bcx.ins().isub(zero, val)
470 ty::Float(_) => fx.bcx.ins().fneg(val),
471 _ => unimplemented!("un op Neg for {:?}", layout.ty),
474 lval.write_cvalue(fx, CValue::ByVal(res, layout));
476 Rvalue::Cast(CastKind::ReifyFnPointer, operand, ty) => {
477 let layout = fx.layout_of(ty);
478 match fx.monomorphize(&operand.ty(&fx.mir.local_decls, fx.tcx)).sty {
479 ty::FnDef(def_id, substs) => {
480 let func_ref = fx.get_function_ref(
481 Instance::resolve(fx.tcx, ParamEnv::reveal_all(), def_id, substs).unwrap(),
483 let func_addr = fx.bcx.ins().func_addr(fx.pointer_type, func_ref);
484 lval.write_cvalue(fx, CValue::ByVal(func_addr, layout));
486 _ => bug!("Trying to ReifyFnPointer on non FnDef {:?}", ty),
489 Rvalue::Cast(CastKind::UnsafeFnPointer, operand, ty) => {
490 let operand = trans_operand(fx, operand);
491 let layout = fx.layout_of(ty);
492 lval.write_cvalue(fx, operand.unchecked_cast_to(layout));
494 Rvalue::Cast(CastKind::Misc, operand, to_ty) => {
495 let operand = trans_operand(fx, operand);
496 let from_ty = operand.layout().ty;
497 match (&from_ty.sty, &to_ty.sty) {
498 (ty::Ref(..), ty::Ref(..))
499 | (ty::Ref(..), ty::RawPtr(..))
500 | (ty::RawPtr(..), ty::Ref(..))
501 | (ty::RawPtr(..), ty::RawPtr(..))
502 | (ty::FnPtr(..), ty::RawPtr(..)) => {
503 lval.write_cvalue(fx, operand.unchecked_cast_to(dest_layout));
505 (ty::RawPtr(..), ty::Uint(_))
506 | (ty::RawPtr(..), ty::Int(_))
507 | (ty::FnPtr(..), ty::Uint(_))
508 if to_ty.sty == fx.tcx.types.usize.sty
509 || to_ty.sty == fx.tcx.types.isize.sty
510 || fx.clif_type(to_ty).unwrap() == pointer_ty(fx.tcx) =>
512 lval.write_cvalue(fx, operand.unchecked_cast_to(dest_layout));
514 (ty::Uint(_), ty::RawPtr(..)) if from_ty.sty == fx.tcx.types.usize.sty => {
515 lval.write_cvalue(fx, operand.unchecked_cast_to(dest_layout));
517 (ty::Char, ty::Uint(_))
518 | (ty::Uint(_), ty::Char)
519 | (ty::Uint(_), ty::Int(_))
520 | (ty::Uint(_), ty::Uint(_)) => {
521 let from = operand.load_scalar(fx);
522 let res = crate::common::clif_intcast(
525 fx.clif_type(to_ty).unwrap(),
528 lval.write_cvalue(fx, CValue::ByVal(res, dest_layout));
530 (ty::Int(_), ty::Int(_)) | (ty::Int(_), ty::Uint(_)) => {
531 let from = operand.load_scalar(fx);
532 let res = crate::common::clif_intcast(
535 fx.clif_type(to_ty).unwrap(),
538 lval.write_cvalue(fx, CValue::ByVal(res, dest_layout));
540 (ty::Float(from_flt), ty::Float(to_flt)) => {
541 let from = operand.load_scalar(fx);
542 let res = match (from_flt, to_flt) {
543 (FloatTy::F32, FloatTy::F64) => {
544 fx.bcx.ins().fpromote(types::F64, from)
546 (FloatTy::F64, FloatTy::F32) => {
547 fx.bcx.ins().fdemote(types::F32, from)
551 lval.write_cvalue(fx, CValue::ByVal(res, dest_layout));
553 (ty::Int(_), ty::Float(_)) => {
554 let from_ty = fx.clif_type(from_ty).unwrap();
555 let from = operand.load_scalar(fx);
556 // FIXME missing encoding for fcvt_from_sint.f32.i8
557 let from = if from_ty == types::I8 || from_ty == types::I16 {
558 fx.bcx.ins().sextend(types::I32, from)
562 let f_type = fx.clif_type(to_ty).unwrap();
563 let res = fx.bcx.ins().fcvt_from_sint(f_type, from);
564 lval.write_cvalue(fx, CValue::ByVal(res, dest_layout));
566 (ty::Uint(_), ty::Float(_)) => {
567 let from_ty = fx.clif_type(from_ty).unwrap();
568 let from = operand.load_scalar(fx);
569 // FIXME missing encoding for fcvt_from_uint.f32.i8
570 let from = if from_ty == types::I8 || from_ty == types::I16 {
571 fx.bcx.ins().uextend(types::I32, from)
575 let f_type = fx.clif_type(to_ty).unwrap();
576 let res = fx.bcx.ins().fcvt_from_uint(f_type, from);
577 lval.write_cvalue(fx, CValue::ByVal(res, dest_layout));
579 (ty::Bool, ty::Uint(_)) | (ty::Bool, ty::Int(_)) => {
580 let to_ty = fx.clif_type(to_ty).unwrap();
581 let from = operand.load_scalar(fx);
582 let res = if to_ty != types::I8 {
583 fx.bcx.ins().uextend(to_ty, from)
587 lval.write_cvalue(fx, CValue::ByVal(res, dest_layout));
589 (ty::Adt(adt_def, _substs), ty::Uint(_)) | (ty::Adt(adt_def, _substs), ty::Int(_)) if adt_def.is_enum() => {
590 let discr = trans_get_discriminant(fx, operand, fx.layout_of(to_ty));
591 lval.write_cvalue(fx, discr);
593 _ => unimpl!("rval misc {:?} {:?}", from_ty, to_ty),
596 Rvalue::Cast(CastKind::ClosureFnPointer, operand, ty) => {
597 unimplemented!("rval closure_fn_ptr {:?} {:?}", operand, ty)
599 Rvalue::Cast(CastKind::Unsize, operand, _ty) => {
600 let operand = trans_operand(fx, operand);
601 operand.unsize_value(fx, lval);
603 Rvalue::Discriminant(place) => {
604 let place = trans_place(fx, place).to_cvalue(fx);
605 let discr = trans_get_discriminant(fx, place, dest_layout);
606 lval.write_cvalue(fx, discr);
608 Rvalue::Repeat(operand, times) => {
609 let operand = trans_operand(fx, operand);
611 let index = fx.bcx.ins().iconst(fx.pointer_type, i as i64);
612 let to = lval.place_index(fx, index);
613 to.write_cvalue(fx, operand);
616 Rvalue::Len(place) => {
617 let place = trans_place(fx, place);
618 let usize_layout = fx.layout_of(fx.tcx.types.usize);
619 let len = codegen_array_len(fx, place);
620 lval.write_cvalue(fx, CValue::ByVal(len, usize_layout));
622 Rvalue::NullaryOp(NullOp::Box, content_ty) => {
623 use rustc::middle::lang_items::ExchangeMallocFnLangItem;
625 let usize_type = fx.clif_type(fx.tcx.types.usize).unwrap();
626 let layout = fx.layout_of(content_ty);
627 let llsize = fx.bcx.ins().iconst(usize_type, layout.size.bytes() as i64);
631 .iconst(usize_type, layout.align.abi.bytes() as i64);
632 let box_layout = fx.layout_of(fx.tcx.mk_box(content_ty));
635 let def_id = match fx.tcx.lang_items().require(ExchangeMallocFnLangItem) {
640 .fatal(&format!("allocation of `{}` {}", box_layout.ty, s));
643 let instance = ty::Instance::mono(fx.tcx, def_id);
644 let func_ref = fx.get_function_ref(instance);
645 let call = fx.bcx.ins().call(func_ref, &[llsize, llalign]);
646 let ptr = fx.bcx.inst_results(call)[0];
647 lval.write_cvalue(fx, CValue::ByVal(ptr, box_layout));
649 Rvalue::NullaryOp(NullOp::SizeOf, ty) => {
653 .is_sized(fx.tcx.at(DUMMY_SP), ParamEnv::reveal_all()));
654 let ty_size = fx.layout_of(ty).size.bytes();
655 let val = CValue::const_val(fx, fx.tcx.types.usize, ty_size as i64);
656 lval.write_cvalue(fx, val);
658 Rvalue::Aggregate(kind, operands) => match **kind {
659 AggregateKind::Array(_ty) => {
660 for (i, operand) in operands.into_iter().enumerate() {
661 let operand = trans_operand(fx, operand);
662 let index = fx.bcx.ins().iconst(fx.pointer_type, i as i64);
663 let to = lval.place_index(fx, index);
664 to.write_cvalue(fx, operand);
667 _ => unimpl!("shouldn't exist at trans {:?}", rval),
671 StatementKind::StorageLive(_)
672 | StatementKind::StorageDead(_)
674 | StatementKind::FakeRead(..)
675 | StatementKind::Retag { .. }
676 | StatementKind::AscribeUserType(..) => {}
678 StatementKind::InlineAsm { .. } => unimpl!("Inline assembly is not supported"),
682 fn codegen_array_len<'a, 'tcx: 'a>(
683 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
686 match place.layout().ty.sty {
687 ty::Array(_elem_ty, len) => {
688 let len = crate::constant::force_eval_const(fx, len).unwrap_usize(fx.tcx) as i64;
689 fx.bcx.ins().iconst(fx.pointer_type, len)
691 ty::Slice(_elem_ty) => {
692 place.to_addr_maybe_unsized(fx).1.expect("Length metadata for slice place")
694 _ => bug!("Rvalue::Len({:?})", place),
698 pub fn trans_get_discriminant<'a, 'tcx: 'a>(
699 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
701 dest_layout: TyLayout<'tcx>,
703 let layout = value.layout();
705 if layout.abi == layout::Abi::Uninhabited {
706 trap_unreachable(&mut fx.bcx);
708 match layout.variants {
709 layout::Variants::Single { index } => {
710 let discr_val = layout
713 .map_or(index.as_u32() as u128, |def| {
714 def.discriminant_for_variant(fx.tcx, index).val
716 return CValue::const_val(fx, dest_layout.ty, discr_val as u64 as i64);
718 layout::Variants::Tagged { .. } | layout::Variants::NicheFilling { .. } => {}
721 let discr = value.value_field(fx, mir::Field::new(0));
722 let discr_ty = discr.layout().ty;
723 let lldiscr = discr.load_scalar(fx);
724 match layout.variants {
725 layout::Variants::Single { .. } => bug!(),
726 layout::Variants::Tagged { ref tag, .. } => {
727 let signed = match tag.value {
728 layout::Int(_, signed) => signed,
731 let val = clif_intcast(fx, lldiscr, fx.clif_type(dest_layout.ty).unwrap(), signed);
732 return CValue::ByVal(val, dest_layout);
734 layout::Variants::NicheFilling {
740 let niche_llty = fx.clif_type(discr_ty).unwrap();
741 let dest_clif_ty = fx.clif_type(dest_layout.ty).unwrap();
742 if niche_variants.start() == niche_variants.end() {
746 .icmp_imm(IntCC::Equal, lldiscr, niche_start as u64 as i64);
750 .iconst(dest_clif_ty, niche_variants.start().as_u32() as i64);
754 .iconst(dest_clif_ty, dataful_variant.as_u32() as i64);
755 let val = fx.bcx.ins().select(b, if_true, if_false);
756 return CValue::ByVal(val, dest_layout);
758 // Rebase from niche values to discriminant values.
759 let delta = niche_start.wrapping_sub(niche_variants.start().as_u32() as u128);
760 let delta = fx.bcx.ins().iconst(niche_llty, delta as u64 as i64);
761 let lldiscr = fx.bcx.ins().isub(lldiscr, delta);
762 let b = fx.bcx.ins().icmp_imm(
763 IntCC::UnsignedLessThanOrEqual,
765 niche_variants.end().as_u32() as i64,
768 clif_intcast(fx, lldiscr, fx.clif_type(dest_layout.ty).unwrap(), false);
772 .iconst(dest_clif_ty, dataful_variant.as_u32() as i64);
773 let val = fx.bcx.ins().select(b, if_true, if_false);
774 return CValue::ByVal(val, dest_layout);
780 macro_rules! binop_match {
781 (@single $fx:expr, $bug_fmt:expr, $var:expr, $signed:expr, $lhs:expr, $rhs:expr, $ret_ty:expr, bug) => {
782 bug!("binop {} on {} lhs: {:?} rhs: {:?}", stringify!($var), $bug_fmt, $lhs, $rhs)
784 (@single $fx:expr, $bug_fmt:expr, $var:expr, $signed:expr, $lhs:expr, $rhs:expr, $ret_ty:expr, icmp($cc:ident)) => {{
785 assert_eq!($fx.tcx.types.bool, $ret_ty);
786 let ret_layout = $fx.layout_of($ret_ty);
788 let b = $fx.bcx.ins().icmp(IntCC::$cc, $lhs, $rhs);
789 CValue::ByVal($fx.bcx.ins().bint(types::I8, b), ret_layout)
791 (@single $fx:expr, $bug_fmt:expr, $var:expr, $signed:expr, $lhs:expr, $rhs:expr, $ret_ty:expr, fcmp($cc:ident)) => {{
792 assert_eq!($fx.tcx.types.bool, $ret_ty);
793 let ret_layout = $fx.layout_of($ret_ty);
794 let b = $fx.bcx.ins().fcmp(FloatCC::$cc, $lhs, $rhs);
795 CValue::ByVal($fx.bcx.ins().bint(types::I8, b), ret_layout)
797 (@single $fx:expr, $bug_fmt:expr, $var:expr, $signed:expr, $lhs:expr, $rhs:expr, $ret_ty:expr, custom(|| $body:expr)) => {{
800 (@single $fx:expr, $bug_fmt:expr, $var:expr, $signed:expr, $lhs:expr, $rhs:expr, $ret_ty:expr, $name:ident) => {{
801 let ret_layout = $fx.layout_of($ret_ty);
802 CValue::ByVal($fx.bcx.ins().$name($lhs, $rhs), ret_layout)
805 $fx:expr, $bin_op:expr, $signed:expr, $lhs:expr, $rhs:expr, $ret_ty:expr, $bug_fmt:expr;
807 $var:ident ($sign:pat) $name:tt $( ( $($next:tt)* ) )? ;
810 let lhs = $lhs.load_scalar($fx);
811 let rhs = $rhs.load_scalar($fx);
812 match ($bin_op, $signed) {
814 (BinOp::$var, $sign) => binop_match!(@single $fx, $bug_fmt, $var, $signed, lhs, rhs, $ret_ty, $name $( ( $($next)* ) )?),
820 fn trans_bool_binop<'a, 'tcx: 'a>(
821 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
827 let res = binop_match! {
828 fx, bin_op, false, lhs, rhs, ty, "bool";
841 Lt (_) icmp(UnsignedLessThan);
842 Le (_) icmp(UnsignedLessThanOrEqual);
843 Ne (_) icmp(NotEqual);
844 Ge (_) icmp(UnsignedGreaterThanOrEqual);
845 Gt (_) icmp(UnsignedGreaterThan);
853 pub fn trans_int_binop<'a, 'tcx: 'a>(
854 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
861 if bin_op != BinOp::Shl && bin_op != BinOp::Shr {
865 "int binop requires lhs and rhs of same type"
869 fx, bin_op, signed, lhs, rhs, out_ty, "int/uint";
885 Lt (false) icmp(UnsignedLessThan);
886 Lt (true) icmp(SignedLessThan);
887 Le (false) icmp(UnsignedLessThanOrEqual);
888 Le (true) icmp(SignedLessThanOrEqual);
889 Ne (_) icmp(NotEqual);
890 Ge (false) icmp(UnsignedGreaterThanOrEqual);
891 Ge (true) icmp(SignedGreaterThanOrEqual);
892 Gt (false) icmp(UnsignedGreaterThan);
893 Gt (true) icmp(SignedGreaterThan);
899 pub fn trans_checked_int_binop<'a, 'tcx: 'a>(
900 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
902 in_lhs: CValue<'tcx>,
903 in_rhs: CValue<'tcx>,
907 if bin_op != BinOp::Shl && bin_op != BinOp::Shr {
911 "checked int binop requires lhs and rhs of same type"
915 let lhs = in_lhs.load_scalar(fx);
916 let rhs = in_rhs.load_scalar(fx);
917 let res = match bin_op {
918 BinOp::Add => fx.bcx.ins().iadd(lhs, rhs),
919 BinOp::Sub => fx.bcx.ins().isub(lhs, rhs),
920 BinOp::Mul => fx.bcx.ins().imul(lhs, rhs),
921 BinOp::Shl => fx.bcx.ins().ishl(lhs, rhs),
924 fx.bcx.ins().ushr(lhs, rhs)
926 fx.bcx.ins().sshr(lhs, rhs)
930 "binop {:?} on checked int/uint lhs: {:?} rhs: {:?}",
937 // TODO: check for overflow
938 let has_overflow = fx.bcx.ins().iconst(types::I8, 0);
940 let out_place = CPlace::new_stack_slot(fx, out_ty);
941 let out_layout = out_place.layout();
942 out_place.write_cvalue(fx, CValue::ByValPair(res, has_overflow, out_layout));
944 out_place.to_cvalue(fx)
947 fn trans_float_binop<'a, 'tcx: 'a>(
948 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
954 let res = binop_match! {
955 fx, bin_op, false, lhs, rhs, ty, "float";
961 assert_eq!(lhs.layout().ty, ty);
962 assert_eq!(rhs.layout().ty, ty);
964 ty::Float(FloatTy::F32) => fx.easy_call("fmodf", &[lhs, rhs], ty),
965 ty::Float(FloatTy::F64) => fx.easy_call("fmod", &[lhs, rhs], ty),
976 Lt (_) fcmp(LessThan);
977 Le (_) fcmp(LessThanOrEqual);
978 Ne (_) fcmp(NotEqual);
979 Ge (_) fcmp(GreaterThanOrEqual);
980 Gt (_) fcmp(GreaterThan);
988 fn trans_char_binop<'a, 'tcx: 'a>(
989 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
995 let res = binop_match! {
996 fx, bin_op, false, lhs, rhs, ty, "char";
1009 Lt (_) icmp(UnsignedLessThan);
1010 Le (_) icmp(UnsignedLessThanOrEqual);
1011 Ne (_) icmp(NotEqual);
1012 Ge (_) icmp(UnsignedGreaterThanOrEqual);
1013 Gt (_) icmp(UnsignedGreaterThan);
1021 fn trans_ptr_binop<'a, 'tcx: 'a>(
1022 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
1028 match lhs.layout().ty.sty {
1029 ty::RawPtr(TypeAndMut { ty, mutbl: _ }) => {
1030 if ty.is_sized(fx.tcx.at(DUMMY_SP), ParamEnv::reveal_all()) {
1032 fx, bin_op, false, lhs, rhs, ret_ty, "ptr";
1045 Lt (_) icmp(UnsignedLessThan);
1046 Le (_) icmp(UnsignedLessThanOrEqual);
1047 Ne (_) icmp(NotEqual);
1048 Ge (_) icmp(UnsignedGreaterThanOrEqual);
1049 Gt (_) icmp(UnsignedGreaterThan);
1054 let lhs = lhs.load_value_pair(fx).0;
1055 let rhs = rhs.load_value_pair(fx).0;
1056 let res = match bin_op {
1057 BinOp::Eq => fx.bcx.ins().icmp(IntCC::Equal, lhs, rhs),
1058 BinOp::Ne => fx.bcx.ins().icmp(IntCC::NotEqual, lhs, rhs),
1059 _ => unimplemented!(
1060 "trans_ptr_binop({:?}, <fat ptr>, <fat ptr>) not implemented",
1065 assert_eq!(fx.tcx.types.bool, ret_ty);
1066 let ret_layout = fx.layout_of(ret_ty);
1067 CValue::ByVal(fx.bcx.ins().bint(types::I8, res), ret_layout)
1070 _ => bug!("trans_ptr_binop on non ptr"),
1074 pub fn trans_place<'a, 'tcx: 'a>(
1075 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
1076 place: &Place<'tcx>,
1079 Place::Local(local) => fx.get_local_place(*local),
1080 Place::Promoted(promoted) => crate::constant::trans_promoted(fx, promoted.0),
1081 Place::Static(static_) => crate::constant::codegen_static_ref(fx, static_),
1082 Place::Projection(projection) => {
1083 let base = trans_place(fx, &projection.base);
1084 match projection.elem {
1085 ProjectionElem::Deref => base.place_deref(fx),
1086 ProjectionElem::Field(field, _ty) => base.place_field(fx, field),
1087 ProjectionElem::Index(local) => {
1088 let index = fx.get_local_place(local).to_cvalue(fx).load_scalar(fx);
1089 base.place_index(fx, index)
1091 ProjectionElem::ConstantIndex {
1096 let index = if !from_end {
1097 fx.bcx.ins().iconst(fx.pointer_type, offset as i64)
1099 let len = codegen_array_len(fx, base);
1100 fx.bcx.ins().iadd_imm(len, -(offset as i64))
1102 base.place_index(fx, index)
1104 ProjectionElem::Subslice { from, to } => unimpl!(
1105 "projection subslice {:?} from {} to {}",
1110 ProjectionElem::Downcast(_adt_def, variant) => base.downcast_variant(fx, variant),
1116 pub fn trans_operand<'a, 'tcx>(
1117 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
1118 operand: &Operand<'tcx>,
1121 Operand::Move(place) | Operand::Copy(place) => {
1122 let cplace = trans_place(fx, place);
1123 cplace.to_cvalue(fx)
1125 Operand::Constant(const_) => crate::constant::trans_constant(fx, const_),