1 use rustc::ty::adjustment::PointerCast;
5 pub fn trans_fn<'a, 'clif, 'tcx: 'a, B: Backend + 'static>(
6 cx: &mut crate::CodegenCx<'clif, 'tcx, B>,
7 instance: Instance<'tcx>,
12 let mir = tcx.instance_mir(instance.def);
15 let (name, sig) = get_function_name_and_sig(tcx, instance, false);
16 let func_id = cx.module.declare_function(&name, linkage, &sig).unwrap();
17 let mut debug_context = cx
20 .map(|debug_context| FunctionDebugContext::new(tcx, debug_context, mir, &name, &sig));
22 // Make FunctionBuilder
23 let mut func = Function::with_name_signature(ExternalName::user(0, 0), sig);
24 let mut func_ctx = FunctionBuilderContext::new();
25 let mut bcx = FunctionBuilder::new(&mut func, &mut func_ctx);
28 let start_ebb = bcx.create_ebb();
29 let mut ebb_map: HashMap<BasicBlock, Ebb> = HashMap::new();
30 for (bb, _bb_data) in mir.basic_blocks().iter_enumerated() {
31 ebb_map.insert(bb, bcx.create_ebb());
35 let pointer_type = cx.module.target_config().pointer_type();
36 let clif_comments = crate::pretty_clif::CommentWriter::new(tcx, instance);
38 let mut fx = FunctionCx {
48 local_map: HashMap::new(),
51 constants: &mut cx.ccx,
52 caches: &mut cx.caches,
53 source_info_set: indexmap::IndexSet::new(),
56 with_unimpl_span(fx.mir.span, || {
57 crate::abi::codegen_fn_prelude(&mut fx, start_ebb);
58 codegen_fn_content(&mut fx);
61 // Recover all necessary data from fx, before accessing func will prevent future access to it.
62 let instance = fx.instance;
63 let clif_comments = fx.clif_comments;
64 let source_info_set = fx.source_info_set;
66 #[cfg(debug_assertions)]
67 crate::pretty_clif::write_clif_file(cx.tcx, "unopt", instance, &func, &clif_comments, None);
70 verify_func(tcx, &clif_comments, &func);
73 let context = &mut cx.caches.context;
76 .define_function(func_id, context)
79 let value_ranges = context.build_value_labels_ranges(cx.module.isa()).expect("value location ranges");
81 // Write optimized function to file for debugging
82 #[cfg(debug_assertions)]
83 crate::pretty_clif::write_clif_file(cx.tcx, "opt", instance, &context.func, &clif_comments, Some(&value_ranges));
85 // Define debuginfo for function
86 let isa = cx.module.isa();
89 .map(|x| x.define(tcx, context, isa, &source_info_set));
91 // Clear context to make it usable for the next function
95 fn verify_func(tcx: TyCtxt, writer: &crate::pretty_clif::CommentWriter, func: &Function) {
96 let flags = settings::Flags::new(settings::builder());
97 match ::cranelift::codegen::verify_function(&func, &flags) {
100 tcx.sess.err(&format!("{:?}", err));
101 let pretty_error = ::cranelift::codegen::print_errors::pretty_verifier_error(
104 Some(Box::new(writer)),
108 .fatal(&format!("cranelift verify error:\n{}", pretty_error));
113 fn codegen_fn_content<'a, 'tcx: 'a>(fx: &mut FunctionCx<'a, 'tcx, impl Backend>) {
114 for (bb, bb_data) in fx.mir.basic_blocks().iter_enumerated() {
115 if bb_data.is_cleanup {
116 // Unwinding after panicking is not supported
120 let ebb = fx.get_ebb(bb);
121 fx.bcx.switch_to_block(ebb);
124 for stmt in &bb_data.statements {
125 fx.set_debug_loc(stmt.source_info);
126 trans_stmt(fx, ebb, stmt);
129 #[cfg(debug_assertions)]
131 let mut terminator_head = "\n".to_string();
135 .fmt_head(&mut terminator_head)
137 let inst = fx.bcx.func.layout.last_inst(ebb).unwrap();
138 fx.add_comment(inst, terminator_head);
141 fx.set_debug_loc(bb_data.terminator().source_info);
143 match &bb_data.terminator().kind {
144 TerminatorKind::Goto { target } => {
145 let ebb = fx.get_ebb(*target);
146 fx.bcx.ins().jump(ebb, &[]);
148 TerminatorKind::Return => {
149 crate::abi::codegen_return(fx);
151 TerminatorKind::Assert {
158 let cond = trans_operand(fx, cond).load_scalar(fx);
159 // TODO HACK brz/brnz for i8/i16 is not yet implemented
160 let cond = fx.bcx.ins().uextend(types::I32, cond);
161 let target = fx.get_ebb(*target);
163 fx.bcx.ins().brnz(cond, target, &[]);
165 fx.bcx.ins().brz(cond, target, &[]);
167 trap_panic(fx, format!("[panic] Assert {:?} failed at {:?}.", msg, bb_data.terminator().source_info.span));
170 TerminatorKind::SwitchInt {
176 let discr = trans_operand(fx, discr).load_scalar(fx);
177 let mut switch = ::cranelift::frontend::Switch::new();
178 for (i, value) in values.iter().enumerate() {
179 let ebb = fx.get_ebb(targets[i]);
180 switch.set_entry(*value as u64, ebb);
182 let otherwise_ebb = fx.get_ebb(targets[targets.len() - 1]);
183 switch.emit(&mut fx.bcx, discr, otherwise_ebb);
185 TerminatorKind::Call {
192 crate::abi::codegen_terminator_call(fx, func, args, destination);
194 TerminatorKind::Resume | TerminatorKind::Abort => {
195 trap_unreachable(fx, "[corruption] Unwinding bb reached.");
197 TerminatorKind::Unreachable => {
198 trap_unreachable(fx, "[corruption] Hit unreachable code.");
200 TerminatorKind::Yield { .. }
201 | TerminatorKind::FalseEdges { .. }
202 | TerminatorKind::FalseUnwind { .. }
203 | TerminatorKind::DropAndReplace { .. }
204 | TerminatorKind::GeneratorDrop => {
205 bug!("shouldn't exist at trans {:?}", bb_data.terminator());
207 TerminatorKind::Drop {
212 let drop_place = trans_place(fx, location);
213 crate::abi::codegen_drop(fx, drop_place);
215 let target_ebb = fx.get_ebb(*target);
216 fx.bcx.ins().jump(target_ebb, &[]);
221 fx.bcx.seal_all_blocks();
225 fn trans_stmt<'a, 'tcx: 'a>(
226 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
228 stmt: &Statement<'tcx>,
230 let _print_guard = PrintOnPanic(|| format!("stmt {:?}", stmt));
232 fx.set_debug_loc(stmt.source_info);
234 #[cfg(debug_assertions)]
236 StatementKind::StorageLive(..) | StatementKind::StorageDead(..) => {} // Those are not very useful
238 let inst = fx.bcx.func.layout.last_inst(cur_ebb).unwrap();
239 fx.add_comment(inst, format!("{:?}", stmt));
244 StatementKind::SetDiscriminant {
248 let place = trans_place(fx, place);
249 let layout = place.layout();
250 if layout.for_variant(&*fx, *variant_index).abi == layout::Abi::Uninhabited {
253 match layout.variants {
254 layout::Variants::Single { index } => {
255 assert_eq!(index, *variant_index);
257 layout::Variants::Multiple {
260 discr_kind: layout::DiscriminantKind::Tag,
263 let ptr = place.place_field(fx, mir::Field::new(discr_index));
266 .discriminant_for_variant(fx.tcx, *variant_index)
269 let discr = CValue::const_val(fx, ptr.layout().ty, to as u64 as i64);
270 ptr.write_cvalue(fx, discr);
272 layout::Variants::Multiple {
275 discr_kind: layout::DiscriminantKind::Niche {
282 if *variant_index != dataful_variant {
283 let niche = place.place_field(fx, mir::Field::new(discr_index));
284 //let niche_llty = niche.layout.immediate_llvm_type(bx.cx);
286 ((variant_index.as_u32() - niche_variants.start().as_u32()) as u128)
287 .wrapping_add(niche_start);
288 // FIXME(eddyb) Check the actual primitive type here.
289 let niche_llval = if niche_value == 0 {
290 CValue::const_val(fx, niche.layout().ty, 0)
292 CValue::const_val(fx, niche.layout().ty, niche_value as u64 as i64)
294 niche.write_cvalue(fx, niche_llval);
299 StatementKind::Assign(to_place, rval) => {
300 let lval = trans_place(fx, to_place);
301 let dest_layout = lval.layout();
303 Rvalue::Use(operand) => {
304 let val = trans_operand(fx, operand);
305 lval.write_cvalue(fx, val);
307 Rvalue::Ref(_, _, place) => {
308 let place = trans_place(fx, place);
309 place.write_place_ref(fx, lval);
311 Rvalue::BinaryOp(bin_op, lhs, rhs) => {
312 let ty = fx.monomorphize(&lhs.ty(fx.mir, fx.tcx));
313 let lhs = trans_operand(fx, lhs);
314 let rhs = trans_operand(fx, rhs);
316 let res = match ty.sty {
317 ty::Bool => trans_bool_binop(fx, *bin_op, lhs, rhs),
319 trans_int_binop(fx, *bin_op, lhs, rhs, lval.layout().ty, false)
322 trans_int_binop(fx, *bin_op, lhs, rhs, lval.layout().ty, true)
324 ty::Float(_) => trans_float_binop(fx, *bin_op, lhs, rhs, lval.layout().ty),
325 ty::Char => trans_char_binop(fx, *bin_op, lhs, rhs, lval.layout().ty),
326 ty::RawPtr(..) => trans_ptr_binop(fx, *bin_op, lhs, rhs, lval.layout().ty),
327 ty::FnPtr(..) => trans_ptr_binop(fx, *bin_op, lhs, rhs, lval.layout().ty),
328 _ => unimplemented!("binop {:?} for {:?}", bin_op, ty),
330 lval.write_cvalue(fx, res);
332 Rvalue::CheckedBinaryOp(bin_op, lhs, rhs) => {
333 let ty = fx.monomorphize(&lhs.ty(fx.mir, fx.tcx));
334 let lhs = trans_operand(fx, lhs);
335 let rhs = trans_operand(fx, rhs);
337 let res = match ty.sty {
339 trans_checked_int_binop(fx, *bin_op, lhs, rhs, lval.layout().ty, false)
342 trans_checked_int_binop(fx, *bin_op, lhs, rhs, lval.layout().ty, true)
344 _ => unimplemented!("checked binop {:?} for {:?}", bin_op, ty),
346 lval.write_cvalue(fx, res);
348 Rvalue::UnaryOp(un_op, operand) => {
349 let operand = trans_operand(fx, operand);
350 let layout = operand.layout();
351 let val = operand.load_scalar(fx);
352 let res = match un_op {
354 match layout.ty.sty {
356 let val = fx.bcx.ins().uextend(types::I32, val); // WORKAROUND for CraneStation/cranelift#466
357 let res = fx.bcx.ins().icmp_imm(IntCC::Equal, val, 0);
358 fx.bcx.ins().bint(types::I8, res)
360 ty::Uint(_) | ty::Int(_) => {
361 fx.bcx.ins().bnot(val)
363 _ => unimplemented!("un op Not for {:?}", layout.ty),
366 UnOp::Neg => match layout.ty.sty {
368 let clif_ty = fx.clif_type(layout.ty).unwrap();
369 if clif_ty == types::I128 {
370 crate::trap::trap_unreachable_ret_value(fx, layout, "i128 neg is not yet supported").load_scalar(fx)
372 let zero = fx.bcx.ins().iconst(clif_ty, 0);
373 fx.bcx.ins().isub(zero, val)
376 ty::Float(_) => fx.bcx.ins().fneg(val),
377 _ => unimplemented!("un op Neg for {:?}", layout.ty),
380 lval.write_cvalue(fx, CValue::by_val(res, layout));
382 Rvalue::Cast(CastKind::Pointer(PointerCast::ReifyFnPointer), operand, ty) => {
383 let layout = fx.layout_of(ty);
385 .monomorphize(&operand.ty(&fx.mir.local_decls, fx.tcx))
388 ty::FnDef(def_id, substs) => {
389 let func_ref = fx.get_function_ref(
390 Instance::resolve(fx.tcx, ParamEnv::reveal_all(), def_id, substs)
393 let func_addr = fx.bcx.ins().func_addr(fx.pointer_type, func_ref);
394 lval.write_cvalue(fx, CValue::by_val(func_addr, layout));
396 _ => bug!("Trying to ReifyFnPointer on non FnDef {:?}", ty),
399 Rvalue::Cast(CastKind::Pointer(PointerCast::UnsafeFnPointer), operand, ty)
400 | Rvalue::Cast(CastKind::Pointer(PointerCast::MutToConstPointer), operand, ty) => {
401 let operand = trans_operand(fx, operand);
402 let layout = fx.layout_of(ty);
403 lval.write_cvalue(fx, operand.unchecked_cast_to(layout));
405 Rvalue::Cast(CastKind::Misc, operand, to_ty) => {
406 let operand = trans_operand(fx, operand);
407 let from_ty = operand.layout().ty;
409 fn is_fat_ptr<'a, 'tcx: 'a>(fx: &FunctionCx<'a, 'tcx, impl Backend>, ty: Ty<'tcx>) -> bool {
412 .map(|ty::TypeAndMut {ty: pointee_ty, mutbl: _ }| fx.layout_of(pointee_ty).is_unsized())
416 if is_fat_ptr(fx, from_ty) {
417 if is_fat_ptr(fx, to_ty) {
418 // fat-ptr -> fat-ptr
419 lval.write_cvalue(fx, operand.unchecked_cast_to(dest_layout));
421 // fat-ptr -> thin-ptr
422 let (ptr, _extra) = operand.load_scalar_pair(fx);
423 lval.write_cvalue(fx, CValue::by_val(ptr, dest_layout))
425 } else if let ty::Adt(adt_def, _substs) = from_ty.sty {
426 // enum -> discriminant value
427 assert!(adt_def.is_enum());
429 ty::Uint(_) | ty::Int(_) => {},
430 _ => unreachable!("cast adt {} -> {}", from_ty, to_ty),
433 // FIXME avoid forcing to stack
435 CPlace::for_addr(operand.force_stack(fx), operand.layout());
436 let discr = trans_get_discriminant(fx, place, fx.layout_of(to_ty));
437 lval.write_cvalue(fx, discr);
439 let from_clif_ty = fx.clif_type(from_ty).unwrap();
440 let to_clif_ty = fx.clif_type(to_ty).unwrap();
441 let from = operand.load_scalar(fx);
443 let signed = match from_ty.sty {
444 ty::Ref(..) | ty::RawPtr(..) | ty::FnPtr(..) | ty::Char | ty::Uint(..) | ty::Bool => false,
446 ty::Float(..) => false, // `signed` is unused for floats
447 _ => panic!("{}", from_ty),
450 let res = if from_clif_ty.is_int() && to_clif_ty.is_int() {
451 // int-like -> int-like
452 crate::common::clif_intcast(
458 } else if from_clif_ty.is_int() && to_clif_ty.is_float() {
461 fx.bcx.ins().fcvt_from_sint(to_clif_ty, from)
463 fx.bcx.ins().fcvt_from_uint(to_clif_ty, from)
465 } else if from_clif_ty.is_float() && to_clif_ty.is_int() {
467 let from = operand.load_scalar(fx);
469 fx.bcx.ins().fcvt_to_sint_sat(to_clif_ty, from)
471 fx.bcx.ins().fcvt_to_uint_sat(to_clif_ty, from)
473 } else if from_clif_ty.is_float() && to_clif_ty.is_float() {
475 match (from_clif_ty, to_clif_ty) {
476 (types::F32, types::F64) => {
477 fx.bcx.ins().fpromote(types::F64, from)
479 (types::F64, types::F32) => {
480 fx.bcx.ins().fdemote(types::F32, from)
485 unimpl!("rval misc {:?} {:?}", from_ty, to_ty)
487 lval.write_cvalue(fx, CValue::by_val(res, dest_layout));
490 Rvalue::Cast(CastKind::Pointer(PointerCast::ClosureFnPointer(_)), operand, _ty) => {
491 let operand = trans_operand(fx, operand);
492 match operand.layout().ty.sty {
493 ty::Closure(def_id, substs) => {
494 let instance = Instance::resolve_closure(
498 ty::ClosureKind::FnOnce,
500 let func_ref = fx.get_function_ref(instance);
501 let func_addr = fx.bcx.ins().func_addr(fx.pointer_type, func_ref);
502 lval.write_cvalue(fx, CValue::by_val(func_addr, lval.layout()));
505 bug!("{} cannot be cast to a fn ptr", operand.layout().ty)
509 Rvalue::Cast(CastKind::Pointer(PointerCast::Unsize), operand, _ty) => {
510 let operand = trans_operand(fx, operand);
511 operand.unsize_value(fx, lval);
513 Rvalue::Discriminant(place) => {
514 let place = trans_place(fx, place);
515 let discr = trans_get_discriminant(fx, place, dest_layout);
516 lval.write_cvalue(fx, discr);
518 Rvalue::Repeat(operand, times) => {
519 let operand = trans_operand(fx, operand);
521 let index = fx.bcx.ins().iconst(fx.pointer_type, i as i64);
522 let to = lval.place_index(fx, index);
523 to.write_cvalue(fx, operand);
526 Rvalue::Len(place) => {
527 let place = trans_place(fx, place);
528 let usize_layout = fx.layout_of(fx.tcx.types.usize);
529 let len = codegen_array_len(fx, place);
530 lval.write_cvalue(fx, CValue::by_val(len, usize_layout));
532 Rvalue::NullaryOp(NullOp::Box, content_ty) => {
533 use rustc::middle::lang_items::ExchangeMallocFnLangItem;
535 let usize_type = fx.clif_type(fx.tcx.types.usize).unwrap();
536 let layout = fx.layout_of(content_ty);
537 let llsize = fx.bcx.ins().iconst(usize_type, layout.size.bytes() as i64);
541 .iconst(usize_type, layout.align.abi.bytes() as i64);
542 let box_layout = fx.layout_of(fx.tcx.mk_box(content_ty));
545 let def_id = match fx.tcx.lang_items().require(ExchangeMallocFnLangItem) {
550 .fatal(&format!("allocation of `{}` {}", box_layout.ty, s));
553 let instance = ty::Instance::mono(fx.tcx, def_id);
554 let func_ref = fx.get_function_ref(instance);
555 let call = fx.bcx.ins().call(func_ref, &[llsize, llalign]);
556 let ptr = fx.bcx.inst_results(call)[0];
557 lval.write_cvalue(fx, CValue::by_val(ptr, box_layout));
559 Rvalue::NullaryOp(NullOp::SizeOf, ty) => {
563 .is_sized(fx.tcx.at(DUMMY_SP), ParamEnv::reveal_all()));
564 let ty_size = fx.layout_of(ty).size.bytes();
565 let val = CValue::const_val(fx, fx.tcx.types.usize, ty_size as i64);
566 lval.write_cvalue(fx, val);
568 Rvalue::Aggregate(kind, operands) => match **kind {
569 AggregateKind::Array(_ty) => {
570 for (i, operand) in operands.into_iter().enumerate() {
571 let operand = trans_operand(fx, operand);
572 let index = fx.bcx.ins().iconst(fx.pointer_type, i as i64);
573 let to = lval.place_index(fx, index);
574 to.write_cvalue(fx, operand);
577 _ => unimpl!("shouldn't exist at trans {:?}", rval),
581 StatementKind::StorageLive(_)
582 | StatementKind::StorageDead(_)
584 | StatementKind::FakeRead(..)
585 | StatementKind::Retag { .. }
586 | StatementKind::AscribeUserType(..) => {}
588 StatementKind::InlineAsm(asm) => {
589 use syntax::ast::Name;
590 let InlineAsm { asm, outputs: _, inputs: _ } = &**asm;
591 let rustc::hir::InlineAsm {
592 asm: asm_code, // Name
593 outputs, // Vec<Name>
595 clobbers, // Vec<Name>
598 dialect: _, // syntax::ast::AsmDialect
602 match &*asm_code.as_str() {
603 "cpuid" | "cpuid\n" => {
604 assert_eq!(inputs, &[Name::intern("{eax}"), Name::intern("{ecx}")]);
606 assert_eq!(outputs.len(), 4);
607 for (i, c) in (&["={eax}", "={ebx}", "={ecx}", "={edx}"]).iter().enumerate() {
608 assert_eq!(&outputs[i].constraint.as_str(), c);
609 assert!(!outputs[i].is_rw);
610 assert!(!outputs[i].is_indirect);
613 assert_eq!(clobbers, &[Name::intern("rbx")]);
616 assert!(!alignstack);
618 crate::trap::trap_unimplemented(fx, "__cpuid_count arch intrinsic is not supported");
621 assert_eq!(inputs, &[Name::intern("{ecx}")]);
623 assert_eq!(outputs.len(), 2);
624 for (i, c) in (&["={eax}", "={edx}"]).iter().enumerate() {
625 assert_eq!(&outputs[i].constraint.as_str(), c);
626 assert!(!outputs[i].is_rw);
627 assert!(!outputs[i].is_indirect);
630 assert_eq!(clobbers, &[]);
633 assert!(!alignstack);
635 crate::trap::trap_unimplemented(fx, "_xgetbv arch intrinsic is not supported");
637 _ if fx.tcx.symbol_name(fx.instance).as_str() == "__rust_probestack" => {
638 crate::trap::trap_unimplemented(fx, "__rust_probestack is not supported");
640 _ => unimpl!("Inline assembly is not supported"),
646 fn codegen_array_len<'a, 'tcx: 'a>(
647 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
650 match place.layout().ty.sty {
651 ty::Array(_elem_ty, len) => {
652 let len = crate::constant::force_eval_const(fx, len).unwrap_usize(fx.tcx) as i64;
653 fx.bcx.ins().iconst(fx.pointer_type, len)
655 ty::Slice(_elem_ty) => place
656 .to_addr_maybe_unsized(fx)
658 .expect("Length metadata for slice place"),
659 _ => bug!("Rvalue::Len({:?})", place),
663 pub fn trans_get_discriminant<'a, 'tcx: 'a>(
664 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
666 dest_layout: TyLayout<'tcx>,
668 let layout = place.layout();
670 if layout.abi == layout::Abi::Uninhabited {
671 return trap_unreachable_ret_value(fx, dest_layout, "[panic] Tried to get discriminant for uninhabited type.");
674 let (discr_scalar, discr_index, discr_kind) = match &layout.variants {
675 layout::Variants::Single { index } => {
676 let discr_val = layout
679 .map_or(index.as_u32() 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::Multiple { discr, discr_index, discr_kind, variants: _ } => {
685 (discr, *discr_index, discr_kind)
689 let discr = place.place_field(fx, mir::Field::new(discr_index)).to_cvalue(fx);
690 let discr_ty = discr.layout().ty;
691 let lldiscr = discr.load_scalar(fx);
693 layout::DiscriminantKind::Tag => {
694 let signed = match discr_scalar.value {
695 layout::Int(_, signed) => signed,
698 let val = clif_intcast(fx, lldiscr, fx.clif_type(dest_layout.ty).unwrap(), signed);
699 return CValue::by_val(val, dest_layout);
701 layout::DiscriminantKind::Niche {
706 let niche_llty = fx.clif_type(discr_ty).unwrap();
707 let dest_clif_ty = fx.clif_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_clif_ty, niche_variants.start().as_u32() as i64);
720 .iconst(dest_clif_ty, dataful_variant.as_u32() as i64);
721 let val = fx.bcx.ins().select(b, if_true, if_false);
722 return CValue::by_val(val, dest_layout);
724 // Rebase from niche values to discriminant values.
725 let delta = niche_start.wrapping_sub(niche_variants.start().as_u32() 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_u32() as i64,
734 clif_intcast(fx, lldiscr, fx.clif_type(dest_layout.ty).unwrap(), false);
738 .iconst(dest_clif_ty, dataful_variant.as_u32() as i64);
739 let val = fx.bcx.ins().select(b, if_true, if_false);
740 return CValue::by_val(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 let b = $fx.bcx.ins().icmp(IntCC::$cc, $lhs, $rhs);
755 CValue::by_val($fx.bcx.ins().bint(types::I8, b), ret_layout)
757 (@single $fx:expr, $bug_fmt:expr, $var:expr, $signed:expr, $lhs:expr, $rhs:expr, $ret_ty:expr, fcmp($cc:ident)) => {{
758 assert_eq!($fx.tcx.types.bool, $ret_ty);
759 let ret_layout = $fx.layout_of($ret_ty);
760 let b = $fx.bcx.ins().fcmp(FloatCC::$cc, $lhs, $rhs);
761 CValue::by_val($fx.bcx.ins().bint(types::I8, b), ret_layout)
763 (@single $fx:expr, $bug_fmt:expr, $var:expr, $signed:expr, $lhs:expr, $rhs:expr, $ret_ty:expr, custom(|| $body:expr)) => {{
766 (@single $fx:expr, $bug_fmt:expr, $var:expr, $signed:expr, $lhs:expr, $rhs:expr, $ret_ty:expr, $name:ident) => {{
767 let ret_layout = $fx.layout_of($ret_ty);
768 CValue::by_val($fx.bcx.ins().$name($lhs, $rhs), ret_layout)
771 $fx:expr, $bin_op:expr, $signed:expr, $lhs:expr, $rhs:expr, $ret_ty:expr, $bug_fmt:expr;
773 $var:ident ($sign:pat) $name:tt $( ( $($next:tt)* ) )? ;
776 let lhs = $lhs.load_scalar($fx);
777 let rhs = $rhs.load_scalar($fx);
778 match ($bin_op, $signed) {
780 (BinOp::$var, $sign) => binop_match!(@single $fx, $bug_fmt, $var, $signed, lhs, rhs, $ret_ty, $name $( ( $($next)* ) )?),
786 fn trans_bool_binop<'a, 'tcx: 'a>(
787 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
792 let res = binop_match! {
793 fx, bin_op, false, lhs, rhs, fx.tcx.types.bool, "bool";
806 Lt (_) icmp(UnsignedLessThan);
807 Le (_) icmp(UnsignedLessThanOrEqual);
808 Ne (_) icmp(NotEqual);
809 Ge (_) icmp(UnsignedGreaterThanOrEqual);
810 Gt (_) icmp(UnsignedGreaterThan);
818 pub fn trans_int_binop<'a, 'tcx: 'a>(
819 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
826 if bin_op != BinOp::Shl && bin_op != BinOp::Shr {
830 "int binop requires lhs and rhs of same type"
834 if let Some(res) = crate::codegen_i128::maybe_codegen(fx, bin_op, false, signed, lhs, rhs, out_ty) {
839 fx, bin_op, signed, lhs, rhs, out_ty, "int/uint";
855 Lt (false) icmp(UnsignedLessThan);
856 Lt (true) icmp(SignedLessThan);
857 Le (false) icmp(UnsignedLessThanOrEqual);
858 Le (true) icmp(SignedLessThanOrEqual);
859 Ne (_) icmp(NotEqual);
860 Ge (false) icmp(UnsignedGreaterThanOrEqual);
861 Ge (true) icmp(SignedGreaterThanOrEqual);
862 Gt (false) icmp(UnsignedGreaterThan);
863 Gt (true) icmp(SignedGreaterThan);
869 pub fn trans_checked_int_binop<'a, 'tcx: 'a>(
870 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
872 in_lhs: CValue<'tcx>,
873 in_rhs: CValue<'tcx>,
877 if !fx.tcx.sess.overflow_checks() {
878 return trans_int_binop(fx, bin_op, in_lhs, in_rhs, out_ty, signed);
881 if bin_op != BinOp::Shl && bin_op != BinOp::Shr {
885 "checked int binop requires lhs and rhs of same type"
889 let lhs = in_lhs.load_scalar(fx);
890 let rhs = in_rhs.load_scalar(fx);
892 if let Some(res) = crate::codegen_i128::maybe_codegen(fx, bin_op, true, signed, in_lhs, in_rhs, out_ty) {
896 let (res, has_overflow) = match bin_op {
898 /*let (val, c_out) = fx.bcx.ins().iadd_cout(lhs, rhs);
900 // FIXME(CraneStation/cranelift#849) legalize iadd_cout for i8 and i16
901 let val = fx.bcx.ins().iadd(lhs, rhs);
902 let has_overflow = if !signed {
903 fx.bcx.ins().icmp(IntCC::UnsignedLessThan, val, lhs)
905 let rhs_is_negative = fx.bcx.ins().icmp_imm(IntCC::SignedLessThan, rhs, 0);
906 let slt = fx.bcx.ins().icmp(IntCC::SignedLessThan, val, lhs);
907 fx.bcx.ins().bxor(rhs_is_negative, slt)
912 /*let (val, b_out) = fx.bcx.ins().isub_bout(lhs, rhs);
914 // FIXME(CraneStation/cranelift#849) legalize isub_bout for i8 and i16
915 let val = fx.bcx.ins().isub(lhs, rhs);
916 let has_overflow = if !signed {
917 fx.bcx.ins().icmp(IntCC::UnsignedGreaterThan, val, lhs)
919 let rhs_is_negative = fx.bcx.ins().icmp_imm(IntCC::SignedLessThan, rhs, 0);
920 let sgt = fx.bcx.ins().icmp(IntCC::SignedGreaterThan, val, lhs);
921 fx.bcx.ins().bxor(rhs_is_negative, sgt)
926 let val = fx.bcx.ins().imul(lhs, rhs);
927 /*let val_hi = if !signed {
928 fx.bcx.ins().umulhi(lhs, rhs)
930 fx.bcx.ins().smulhi(lhs, rhs)
932 let has_overflow = fx.bcx.ins().icmp_imm(IntCC::NotEqual, val_hi, 0);*/
933 // TODO: check for overflow
934 let has_overflow = fx.bcx.ins().bconst(types::B1, false);
938 let val = fx.bcx.ins().ishl(lhs, rhs);
939 // TODO: check for overflow
940 let has_overflow = fx.bcx.ins().bconst(types::B1, false);
944 let val = if !signed {
945 fx.bcx.ins().ushr(lhs, rhs)
947 fx.bcx.ins().sshr(lhs, rhs)
949 // TODO: check for overflow
950 let has_overflow = fx.bcx.ins().bconst(types::B1, false);
954 "binop {:?} on checked int/uint lhs: {:?} rhs: {:?}",
961 let has_overflow = fx.bcx.ins().bint(types::I8, has_overflow);
962 let out_place = CPlace::new_stack_slot(fx, out_ty);
963 let out_layout = out_place.layout();
964 out_place.write_cvalue(fx, CValue::by_val_pair(res, has_overflow, out_layout));
966 out_place.to_cvalue(fx)
969 fn trans_float_binop<'a, 'tcx: 'a>(
970 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
976 let res = binop_match! {
977 fx, bin_op, false, lhs, rhs, ty, "float";
983 assert_eq!(lhs.layout().ty, ty);
984 assert_eq!(rhs.layout().ty, ty);
986 ty::Float(FloatTy::F32) => fx.easy_call("fmodf", &[lhs, rhs], ty),
987 ty::Float(FloatTy::F64) => fx.easy_call("fmod", &[lhs, rhs], ty),
998 Lt (_) fcmp(LessThan);
999 Le (_) fcmp(LessThanOrEqual);
1000 Ne (_) fcmp(NotEqual);
1001 Ge (_) fcmp(GreaterThanOrEqual);
1002 Gt (_) fcmp(GreaterThan);
1010 fn trans_char_binop<'a, 'tcx: 'a>(
1011 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
1017 let res = binop_match! {
1018 fx, bin_op, false, lhs, rhs, ty, "char";
1031 Lt (_) icmp(UnsignedLessThan);
1032 Le (_) icmp(UnsignedLessThanOrEqual);
1033 Ne (_) icmp(NotEqual);
1034 Ge (_) icmp(UnsignedGreaterThanOrEqual);
1035 Gt (_) icmp(UnsignedGreaterThan);
1043 fn trans_ptr_binop<'a, 'tcx: 'a>(
1044 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
1050 let not_fat = match lhs.layout().ty.sty {
1051 ty::RawPtr(TypeAndMut { ty, mutbl: _ }) => {
1052 ty.is_sized(fx.tcx.at(DUMMY_SP), ParamEnv::reveal_all())
1054 ty::FnPtr(..) => true,
1055 _ => bug!("trans_ptr_binop on non ptr"),
1058 if let BinOp::Offset = bin_op {
1059 let (base, offset) = (lhs, rhs.load_scalar(fx));
1060 let pointee_ty = base.layout().ty.builtin_deref(true).unwrap().ty;
1061 let pointee_size = fx.layout_of(pointee_ty).size.bytes();
1062 let ptr_diff = fx.bcx.ins().imul_imm(offset, pointee_size as i64);
1063 let base_val = base.load_scalar(fx);
1064 let res = fx.bcx.ins().iadd(base_val, ptr_diff);
1065 return CValue::by_val(res, base.layout());
1069 fx, bin_op, false, lhs, rhs, ret_ty, "ptr";
1082 Lt (_) icmp(UnsignedLessThan);
1083 Le (_) icmp(UnsignedLessThanOrEqual);
1084 Ne (_) icmp(NotEqual);
1085 Ge (_) icmp(UnsignedGreaterThanOrEqual);
1086 Gt (_) icmp(UnsignedGreaterThan);
1088 Offset (_) bug; // Handled above
1091 let (lhs_ptr, lhs_extra) = lhs.load_scalar_pair(fx);
1092 let (rhs_ptr, rhs_extra) = rhs.load_scalar_pair(fx);
1094 let res = match bin_op {
1096 let ptr_eq = fx.bcx.ins().icmp(IntCC::Equal, lhs_ptr, rhs_ptr);
1097 let extra_eq = fx.bcx.ins().icmp(IntCC::Equal, lhs_extra, rhs_extra);
1098 fx.bcx.ins().band(ptr_eq, extra_eq)
1101 let ptr_ne = fx.bcx.ins().icmp(IntCC::NotEqual, lhs_ptr, rhs_ptr);
1102 let extra_ne = fx.bcx.ins().icmp(IntCC::NotEqual, lhs_extra, rhs_extra);
1103 fx.bcx.ins().bor(ptr_ne, extra_ne)
1105 BinOp::Lt | BinOp::Le | BinOp::Ge | BinOp::Gt => {
1106 let ptr_eq = fx.bcx.ins().icmp(IntCC::Equal, lhs_ptr, rhs_ptr);
1108 let ptr_cmp = fx.bcx.ins().icmp(match bin_op {
1109 BinOp::Lt => IntCC::UnsignedLessThan,
1110 BinOp::Le => IntCC::UnsignedLessThanOrEqual,
1111 BinOp::Ge => IntCC::UnsignedGreaterThanOrEqual,
1112 BinOp::Gt => IntCC::UnsignedGreaterThan,
1113 _ => unreachable!(),
1114 }, lhs_ptr, rhs_ptr);
1116 let extra_cmp = fx.bcx.ins().icmp(match bin_op {
1117 BinOp::Lt => IntCC::UnsignedLessThan,
1118 BinOp::Le => IntCC::UnsignedLessThanOrEqual,
1119 BinOp::Ge => IntCC::UnsignedGreaterThanOrEqual,
1120 BinOp::Gt => IntCC::UnsignedGreaterThan,
1121 _ => unreachable!(),
1122 }, lhs_extra, rhs_extra);
1124 fx.bcx.ins().select(ptr_eq, extra_cmp, ptr_cmp)
1126 _ => panic!("bin_op {:?} on ptr", bin_op),
1129 assert_eq!(fx.tcx.types.bool, ret_ty);
1130 let ret_layout = fx.layout_of(ret_ty);
1131 CValue::by_val(fx.bcx.ins().bint(types::I8, res), ret_layout)
1135 pub fn trans_place<'a, 'tcx: 'a>(
1136 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
1137 place: &Place<'tcx>,
1139 let base = match &place.base {
1140 PlaceBase::Local(local) => fx.get_local_place(*local),
1141 PlaceBase::Static(static_) => match static_.kind {
1142 StaticKind::Static(def_id) => {
1143 crate::constant::codegen_static_ref(fx, def_id, static_.ty)
1145 StaticKind::Promoted(promoted) => {
1146 crate::constant::trans_promoted(fx, promoted, static_.ty)
1151 trans_place_projection(fx, base, &place.projection)
1154 pub fn trans_place_projection<'a, 'tcx: 'a>(
1155 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
1157 projection: &Option<Box<Projection<'tcx>>>,
1159 let projection = if let Some(projection) = projection {
1165 let base = trans_place_projection(fx, base, &projection.base);
1167 match projection.elem {
1168 ProjectionElem::Deref => base.place_deref(fx),
1169 ProjectionElem::Field(field, _ty) => base.place_field(fx, field),
1170 ProjectionElem::Index(local) => {
1171 let index = fx.get_local_place(local).to_cvalue(fx).load_scalar(fx);
1172 base.place_index(fx, index)
1174 ProjectionElem::ConstantIndex {
1179 let index = if !from_end {
1180 fx.bcx.ins().iconst(fx.pointer_type, offset as i64)
1182 let len = codegen_array_len(fx, base);
1183 fx.bcx.ins().iadd_imm(len, -(offset as i64))
1185 base.place_index(fx, index)
1187 ProjectionElem::Subslice { from, to } => {
1188 // These indices are generated by slice patterns.
1189 // slice[from:-to] in Python terms.
1191 match base.layout().ty.sty {
1192 ty::Array(elem_ty, len) => {
1193 let elem_layout = fx.layout_of(elem_ty);
1194 let ptr = base.to_addr(fx);
1195 let len = crate::constant::force_eval_const(fx, len).unwrap_usize(fx.tcx);
1197 fx.bcx.ins().iadd_imm(ptr, elem_layout.size.bytes() as i64 * from as i64),
1198 fx.layout_of(fx.tcx.mk_array(elem_ty, len - from as u64 - to as u64)),
1201 ty::Slice(elem_ty) => {
1202 let elem_layout = fx.layout_of(elem_ty);
1203 let (ptr, len) = base.to_addr_maybe_unsized(fx);
1204 let len = len.unwrap();
1205 CPlace::for_addr_with_extra(
1206 fx.bcx.ins().iadd_imm(ptr, elem_layout.size.bytes() as i64 * from as i64),
1207 fx.bcx.ins().iadd_imm(len, -(from as i64 + to as i64)),
1211 _ => unreachable!(),
1214 ProjectionElem::Downcast(_adt_def, variant) => base.downcast_variant(fx, variant),
1218 pub fn trans_operand<'a, 'tcx>(
1219 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
1220 operand: &Operand<'tcx>,
1223 Operand::Move(place) | Operand::Copy(place) => {
1224 let cplace = trans_place(fx, place);
1225 cplace.to_cvalue(fx)
1227 Operand::Constant(const_) => crate::constant::trans_constant(fx, const_),