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);
14 // Check fn sig for u128 and i128 and replace those functions with a trap.
16 // FIXME implement u128 and i128 support
18 // Check sig for u128 and i128
19 let fn_sig = tcx.normalize_erasing_late_bound_regions(ParamEnv::reveal_all(), &instance.fn_sig(tcx));
21 struct UI128Visitor<'tcx>(TyCtxt<'tcx>, bool);
23 impl<'tcx> rustc::ty::fold::TypeVisitor<'tcx> for UI128Visitor<'tcx> {
24 fn visit_ty(&mut self, t: Ty<'tcx>) -> bool {
25 if t.sty == self.0.types.u128.sty || t.sty == self.0.types.i128.sty {
27 return false; // stop visiting
30 t.super_visit_with(self)
34 let mut visitor = UI128Visitor(tcx, false);
35 fn_sig.visit_with(&mut visitor);
37 //If found replace function with a trap.
39 tcx.sess.warn("u128 and i128 are not yet supported. \
40 Functions using these as args will be replaced with a trap.");
42 // Declare function with fake signature
44 params: vec![AbiParam::new(types::INVALID)],
46 call_conv: CallConv::Fast,
48 let name = tcx.symbol_name(instance).as_str();
49 let func_id = cx.module.declare_function(&*name, linkage, &sig).unwrap();
51 // Create trapping function
52 let mut func = Function::with_name_signature(ExternalName::user(0, 0), sig);
53 let mut func_ctx = FunctionBuilderContext::new();
54 let mut bcx = FunctionBuilder::new(&mut func, &mut func_ctx);
55 let start_ebb = bcx.create_ebb();
56 bcx.append_ebb_params_for_function_params(start_ebb);
57 bcx.switch_to_block(start_ebb);
59 let mut fx = FunctionCx {
62 pointer_type: pointer_ty(tcx),
68 ebb_map: HashMap::new(),
69 local_map: HashMap::new(),
71 clif_comments: crate::pretty_clif::CommentWriter::new(tcx, instance),
72 constants: &mut cx.ccx,
73 caches: &mut cx.caches,
74 source_info_set: indexmap::IndexSet::new(),
77 crate::trap::trap_unreachable(&mut fx, "[unimplemented] Called function with u128 or i128 as argument.");
78 fx.bcx.seal_all_blocks();
82 cx.caches.context.func = func;
84 .define_function(func_id, &mut cx.caches.context)
86 cx.caches.context.clear();
92 let (name, sig) = get_function_name_and_sig(tcx, instance, false);
93 let func_id = cx.module.declare_function(&name, linkage, &sig).unwrap();
94 let mut debug_context = cx
97 .map(|debug_context| FunctionDebugContext::new(tcx, debug_context, mir, &name, &sig));
99 // Make FunctionBuilder
100 let mut func = Function::with_name_signature(ExternalName::user(0, 0), sig);
101 let mut func_ctx = FunctionBuilderContext::new();
102 let mut bcx = FunctionBuilder::new(&mut func, &mut func_ctx);
105 let start_ebb = bcx.create_ebb();
106 let mut ebb_map: HashMap<BasicBlock, Ebb> = HashMap::new();
107 for (bb, _bb_data) in mir.basic_blocks().iter_enumerated() {
108 ebb_map.insert(bb, bcx.create_ebb());
112 let pointer_type = cx.module.target_config().pointer_type();
113 let clif_comments = crate::pretty_clif::CommentWriter::new(tcx, instance);
115 let mut fx = FunctionCx {
125 local_map: HashMap::new(),
128 constants: &mut cx.ccx,
129 caches: &mut cx.caches,
130 source_info_set: indexmap::IndexSet::new(),
133 with_unimpl_span(fx.mir.span, || {
134 crate::abi::codegen_fn_prelude(&mut fx, start_ebb);
135 codegen_fn_content(&mut fx);
138 // Recover all necessary data from fx, before accessing func will prevent future access to it.
139 let instance = fx.instance;
140 let clif_comments = fx.clif_comments;
141 let source_info_set = fx.source_info_set;
143 #[cfg(debug_assertions)]
144 crate::pretty_clif::write_clif_file(cx.tcx, "unopt", instance, &func, &clif_comments, None);
147 verify_func(tcx, &clif_comments, &func);
150 let context = &mut cx.caches.context;
153 .define_function(func_id, context)
156 let value_ranges = context.build_value_labels_ranges(cx.module.isa()).expect("value location ranges");
158 // Write optimized function to file for debugging
159 #[cfg(debug_assertions)]
160 crate::pretty_clif::write_clif_file(cx.tcx, "opt", instance, &context.func, &clif_comments, Some(&value_ranges));
162 // Define debuginfo for function
163 let isa = cx.module.isa();
166 .map(|x| x.define(tcx, context, isa, &source_info_set));
168 // Clear context to make it usable for the next function
172 fn verify_func(tcx: TyCtxt, writer: &crate::pretty_clif::CommentWriter, func: &Function) {
173 let flags = settings::Flags::new(settings::builder());
174 match ::cranelift::codegen::verify_function(&func, &flags) {
177 tcx.sess.err(&format!("{:?}", err));
178 let pretty_error = ::cranelift::codegen::print_errors::pretty_verifier_error(
181 Some(Box::new(writer)),
185 .fatal(&format!("cranelift verify error:\n{}", pretty_error));
190 fn codegen_fn_content<'a, 'tcx: 'a>(fx: &mut FunctionCx<'a, 'tcx, impl Backend>) {
191 for (bb, bb_data) in fx.mir.basic_blocks().iter_enumerated() {
192 if bb_data.is_cleanup {
193 // Unwinding after panicking is not supported
197 let ebb = fx.get_ebb(bb);
198 fx.bcx.switch_to_block(ebb);
201 for stmt in &bb_data.statements {
202 fx.set_debug_loc(stmt.source_info);
203 trans_stmt(fx, ebb, stmt);
206 #[cfg(debug_assertions)]
208 let mut terminator_head = "\n".to_string();
212 .fmt_head(&mut terminator_head)
214 let inst = fx.bcx.func.layout.last_inst(ebb).unwrap();
215 fx.add_comment(inst, terminator_head);
218 fx.set_debug_loc(bb_data.terminator().source_info);
220 match &bb_data.terminator().kind {
221 TerminatorKind::Goto { target } => {
222 let ebb = fx.get_ebb(*target);
223 fx.bcx.ins().jump(ebb, &[]);
225 TerminatorKind::Return => {
226 crate::abi::codegen_return(fx);
228 TerminatorKind::Assert {
235 let cond = trans_operand(fx, cond).load_scalar(fx);
236 // TODO HACK brz/brnz for i8/i16 is not yet implemented
237 let cond = fx.bcx.ins().uextend(types::I32, cond);
238 let target = fx.get_ebb(*target);
240 fx.bcx.ins().brnz(cond, target, &[]);
242 fx.bcx.ins().brz(cond, target, &[]);
244 trap_panic(fx, format!("[panic] Assert {:?} failed.", msg));
247 TerminatorKind::SwitchInt {
253 let discr = trans_operand(fx, discr).load_scalar(fx);
254 let mut switch = ::cranelift::frontend::Switch::new();
255 for (i, value) in values.iter().enumerate() {
256 let ebb = fx.get_ebb(targets[i]);
257 switch.set_entry(*value as u64, ebb);
259 let otherwise_ebb = fx.get_ebb(targets[targets.len() - 1]);
260 switch.emit(&mut fx.bcx, discr, otherwise_ebb);
262 TerminatorKind::Call {
269 crate::abi::codegen_terminator_call(fx, func, args, destination);
271 TerminatorKind::Resume | TerminatorKind::Abort => {
272 trap_unreachable(fx, "[corruption] Unwinding bb reached.");
274 TerminatorKind::Unreachable => {
275 trap_unreachable(fx, "[corruption] Hit unreachable code.");
277 TerminatorKind::Yield { .. }
278 | TerminatorKind::FalseEdges { .. }
279 | TerminatorKind::FalseUnwind { .. }
280 | TerminatorKind::DropAndReplace { .. }
281 | TerminatorKind::GeneratorDrop => {
282 bug!("shouldn't exist at trans {:?}", bb_data.terminator());
284 TerminatorKind::Drop {
289 let drop_place = trans_place(fx, location);
290 crate::abi::codegen_drop(fx, drop_place);
292 let target_ebb = fx.get_ebb(*target);
293 fx.bcx.ins().jump(target_ebb, &[]);
298 fx.bcx.seal_all_blocks();
302 fn trans_stmt<'a, 'tcx: 'a>(
303 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
305 stmt: &Statement<'tcx>,
307 let _print_guard = PrintOnPanic(|| format!("stmt {:?}", stmt));
309 fx.set_debug_loc(stmt.source_info);
311 #[cfg(debug_assertions)]
313 StatementKind::StorageLive(..) | StatementKind::StorageDead(..) => {} // Those are not very useful
315 let inst = fx.bcx.func.layout.last_inst(cur_ebb).unwrap();
316 fx.add_comment(inst, format!("{:?}", stmt));
321 StatementKind::SetDiscriminant {
325 let place = trans_place(fx, place);
326 let layout = place.layout();
327 if layout.for_variant(&*fx, *variant_index).abi == layout::Abi::Uninhabited {
330 match layout.variants {
331 layout::Variants::Single { index } => {
332 assert_eq!(index, *variant_index);
334 layout::Variants::Multiple {
337 discr_kind: layout::DiscriminantKind::Tag,
340 let ptr = place.place_field(fx, mir::Field::new(discr_index));
343 .discriminant_for_variant(fx.tcx, *variant_index)
346 let discr = CValue::const_val(fx, ptr.layout().ty, to as u64 as i64);
347 ptr.write_cvalue(fx, discr);
349 layout::Variants::Multiple {
352 discr_kind: layout::DiscriminantKind::Niche {
359 if *variant_index != dataful_variant {
360 let niche = place.place_field(fx, mir::Field::new(discr_index));
361 //let niche_llty = niche.layout.immediate_llvm_type(bx.cx);
363 ((variant_index.as_u32() - niche_variants.start().as_u32()) as u128)
364 .wrapping_add(niche_start);
365 // FIXME(eddyb) Check the actual primitive type here.
366 let niche_llval = if niche_value == 0 {
367 CValue::const_val(fx, niche.layout().ty, 0)
369 CValue::const_val(fx, niche.layout().ty, niche_value as u64 as i64)
371 niche.write_cvalue(fx, niche_llval);
376 StatementKind::Assign(to_place, rval) => {
377 let lval = trans_place(fx, to_place);
378 let dest_layout = lval.layout();
380 Rvalue::Use(operand) => {
381 let val = trans_operand(fx, operand);
382 lval.write_cvalue(fx, val);
384 Rvalue::Ref(_, _, place) => {
385 let place = trans_place(fx, place);
386 place.write_place_ref(fx, lval);
388 Rvalue::BinaryOp(bin_op, lhs, rhs) => {
389 let ty = fx.monomorphize(&lhs.ty(fx.mir, fx.tcx));
390 let lhs = trans_operand(fx, lhs);
391 let rhs = trans_operand(fx, rhs);
393 let res = match ty.sty {
394 ty::Bool => trans_bool_binop(fx, *bin_op, lhs, rhs, lval.layout().ty),
396 trans_int_binop(fx, *bin_op, lhs, rhs, lval.layout().ty, false)
399 trans_int_binop(fx, *bin_op, lhs, rhs, lval.layout().ty, true)
401 ty::Float(_) => trans_float_binop(fx, *bin_op, lhs, rhs, lval.layout().ty),
402 ty::Char => trans_char_binop(fx, *bin_op, lhs, rhs, lval.layout().ty),
403 ty::RawPtr(..) => trans_ptr_binop(fx, *bin_op, lhs, rhs, lval.layout().ty),
404 ty::FnPtr(..) => trans_ptr_binop(fx, *bin_op, lhs, rhs, lval.layout().ty),
405 _ => unimplemented!("binop {:?} for {:?}", bin_op, ty),
407 lval.write_cvalue(fx, res);
409 Rvalue::CheckedBinaryOp(bin_op, lhs, rhs) => {
410 let ty = fx.monomorphize(&lhs.ty(fx.mir, fx.tcx));
411 let lhs = trans_operand(fx, lhs);
412 let rhs = trans_operand(fx, rhs);
414 let res = match ty.sty {
416 trans_checked_int_binop(fx, *bin_op, lhs, rhs, lval.layout().ty, false)
419 trans_checked_int_binop(fx, *bin_op, lhs, rhs, lval.layout().ty, true)
421 _ => unimplemented!("checked binop {:?} for {:?}", bin_op, ty),
423 lval.write_cvalue(fx, res);
425 Rvalue::UnaryOp(un_op, operand) => {
426 let operand = trans_operand(fx, operand);
427 let layout = operand.layout();
428 let val = operand.load_scalar(fx);
429 let res = match un_op {
431 match layout.ty.sty {
433 let val = fx.bcx.ins().uextend(types::I32, val); // WORKAROUND for CraneStation/cranelift#466
434 let res = fx.bcx.ins().icmp_imm(IntCC::Equal, val, 0);
435 fx.bcx.ins().bint(types::I8, res)
437 ty::Uint(_) | ty::Int(_) => fx.bcx.ins().bnot(val),
438 _ => unimplemented!("un op Not for {:?}", layout.ty),
441 UnOp::Neg => match layout.ty.sty {
443 let clif_ty = fx.clif_type(layout.ty).unwrap();
444 let zero = fx.bcx.ins().iconst(clif_ty, 0);
445 fx.bcx.ins().isub(zero, val)
447 ty::Float(_) => fx.bcx.ins().fneg(val),
448 _ => unimplemented!("un op Neg for {:?}", layout.ty),
451 lval.write_cvalue(fx, CValue::by_val(res, layout));
453 Rvalue::Cast(CastKind::Pointer(PointerCast::ReifyFnPointer), operand, ty) => {
454 let layout = fx.layout_of(ty);
456 .monomorphize(&operand.ty(&fx.mir.local_decls, fx.tcx))
459 ty::FnDef(def_id, substs) => {
460 let func_ref = fx.get_function_ref(
461 Instance::resolve(fx.tcx, ParamEnv::reveal_all(), def_id, substs)
464 let func_addr = fx.bcx.ins().func_addr(fx.pointer_type, func_ref);
465 lval.write_cvalue(fx, CValue::by_val(func_addr, layout));
467 _ => bug!("Trying to ReifyFnPointer on non FnDef {:?}", ty),
470 Rvalue::Cast(CastKind::Pointer(PointerCast::UnsafeFnPointer), operand, ty)
471 | Rvalue::Cast(CastKind::Pointer(PointerCast::MutToConstPointer), operand, ty) => {
472 let operand = trans_operand(fx, operand);
473 let layout = fx.layout_of(ty);
474 lval.write_cvalue(fx, operand.unchecked_cast_to(layout));
476 Rvalue::Cast(CastKind::Misc, operand, to_ty) => {
477 let operand = trans_operand(fx, operand);
478 let from_ty = operand.layout().ty;
480 fn is_fat_ptr<'a, 'tcx: 'a>(fx: &FunctionCx<'a, 'tcx, impl Backend>, ty: Ty<'tcx>) -> bool {
483 .map(|ty::TypeAndMut {ty: pointee_ty, mutbl: _ }| fx.layout_of(pointee_ty).is_unsized())
487 if is_fat_ptr(fx, from_ty) {
488 if is_fat_ptr(fx, to_ty) {
489 // fat-ptr -> fat-ptr
490 lval.write_cvalue(fx, operand.unchecked_cast_to(dest_layout));
492 // fat-ptr -> thin-ptr
493 let (ptr, _extra) = operand.load_scalar_pair(fx);
494 lval.write_cvalue(fx, CValue::by_val(ptr, dest_layout))
496 } else if let ty::Adt(adt_def, _substs) = from_ty.sty {
497 // enum -> discriminant value
498 assert!(adt_def.is_enum());
500 ty::Uint(_) | ty::Int(_) => {},
501 _ => unreachable!("cast adt {} -> {}", from_ty, to_ty),
504 // FIXME avoid forcing to stack
506 CPlace::for_addr(operand.force_stack(fx), operand.layout());
507 let discr = trans_get_discriminant(fx, place, fx.layout_of(to_ty));
508 lval.write_cvalue(fx, discr);
510 let from_clif_ty = fx.clif_type(from_ty).unwrap();
511 let to_clif_ty = fx.clif_type(to_ty).unwrap();
512 let from = operand.load_scalar(fx);
514 let signed = match from_ty.sty {
515 ty::Ref(..) | ty::RawPtr(..) | ty::FnPtr(..) | ty::Char | ty::Uint(..) | ty::Bool => false,
517 ty::Float(..) => false, // `signed` is unused for floats
518 _ => panic!("{}", from_ty),
521 let res = if from_clif_ty.is_int() && to_clif_ty.is_int() {
522 // int-like -> int-like
523 crate::common::clif_intcast(
529 } else if from_clif_ty.is_int() && to_clif_ty.is_float() {
532 fx.bcx.ins().fcvt_from_sint(to_clif_ty, from)
534 fx.bcx.ins().fcvt_from_uint(to_clif_ty, from)
536 } else if from_clif_ty.is_float() && to_clif_ty.is_int() {
538 let from = operand.load_scalar(fx);
540 fx.bcx.ins().fcvt_to_sint_sat(to_clif_ty, from)
542 fx.bcx.ins().fcvt_to_uint_sat(to_clif_ty, from)
544 } else if from_clif_ty.is_float() && to_clif_ty.is_float() {
546 match (from_clif_ty, to_clif_ty) {
547 (types::F32, types::F64) => {
548 fx.bcx.ins().fpromote(types::F64, from)
550 (types::F64, types::F32) => {
551 fx.bcx.ins().fdemote(types::F32, from)
556 unimpl!("rval misc {:?} {:?}", from_ty, to_ty)
558 lval.write_cvalue(fx, CValue::by_val(res, dest_layout));
561 Rvalue::Cast(CastKind::Pointer(PointerCast::ClosureFnPointer(_)), operand, _ty) => {
562 let operand = trans_operand(fx, operand);
563 match operand.layout().ty.sty {
564 ty::Closure(def_id, substs) => {
565 let instance = Instance::resolve_closure(
569 ty::ClosureKind::FnOnce,
571 let func_ref = fx.get_function_ref(instance);
572 let func_addr = fx.bcx.ins().func_addr(fx.pointer_type, func_ref);
573 lval.write_cvalue(fx, CValue::by_val(func_addr, lval.layout()));
576 bug!("{} cannot be cast to a fn ptr", operand.layout().ty)
580 Rvalue::Cast(CastKind::Pointer(PointerCast::Unsize), operand, _ty) => {
581 let operand = trans_operand(fx, operand);
582 operand.unsize_value(fx, lval);
584 Rvalue::Discriminant(place) => {
585 let place = trans_place(fx, place);
586 let discr = trans_get_discriminant(fx, place, dest_layout);
587 lval.write_cvalue(fx, discr);
589 Rvalue::Repeat(operand, times) => {
590 let operand = trans_operand(fx, operand);
592 let index = fx.bcx.ins().iconst(fx.pointer_type, i as i64);
593 let to = lval.place_index(fx, index);
594 to.write_cvalue(fx, operand);
597 Rvalue::Len(place) => {
598 let place = trans_place(fx, place);
599 let usize_layout = fx.layout_of(fx.tcx.types.usize);
600 let len = codegen_array_len(fx, place);
601 lval.write_cvalue(fx, CValue::by_val(len, usize_layout));
603 Rvalue::NullaryOp(NullOp::Box, content_ty) => {
604 use rustc::middle::lang_items::ExchangeMallocFnLangItem;
606 let usize_type = fx.clif_type(fx.tcx.types.usize).unwrap();
607 let layout = fx.layout_of(content_ty);
608 let llsize = fx.bcx.ins().iconst(usize_type, layout.size.bytes() as i64);
612 .iconst(usize_type, layout.align.abi.bytes() as i64);
613 let box_layout = fx.layout_of(fx.tcx.mk_box(content_ty));
616 let def_id = match fx.tcx.lang_items().require(ExchangeMallocFnLangItem) {
621 .fatal(&format!("allocation of `{}` {}", box_layout.ty, s));
624 let instance = ty::Instance::mono(fx.tcx, def_id);
625 let func_ref = fx.get_function_ref(instance);
626 let call = fx.bcx.ins().call(func_ref, &[llsize, llalign]);
627 let ptr = fx.bcx.inst_results(call)[0];
628 lval.write_cvalue(fx, CValue::by_val(ptr, box_layout));
630 Rvalue::NullaryOp(NullOp::SizeOf, ty) => {
634 .is_sized(fx.tcx.at(DUMMY_SP), ParamEnv::reveal_all()));
635 let ty_size = fx.layout_of(ty).size.bytes();
636 let val = CValue::const_val(fx, fx.tcx.types.usize, ty_size as i64);
637 lval.write_cvalue(fx, val);
639 Rvalue::Aggregate(kind, operands) => match **kind {
640 AggregateKind::Array(_ty) => {
641 for (i, operand) in operands.into_iter().enumerate() {
642 let operand = trans_operand(fx, operand);
643 let index = fx.bcx.ins().iconst(fx.pointer_type, i as i64);
644 let to = lval.place_index(fx, index);
645 to.write_cvalue(fx, operand);
648 _ => unimpl!("shouldn't exist at trans {:?}", rval),
652 StatementKind::StorageLive(_)
653 | StatementKind::StorageDead(_)
655 | StatementKind::FakeRead(..)
656 | StatementKind::Retag { .. }
657 | StatementKind::AscribeUserType(..) => {}
659 StatementKind::InlineAsm(asm) => {
660 use syntax::ast::Name;
661 let InlineAsm { asm, outputs: _, inputs: _ } = &**asm;
662 let rustc::hir::InlineAsm {
663 asm: asm_code, // Name
664 outputs, // Vec<Name>
666 clobbers, // Vec<Name>
669 dialect, // syntax::ast::AsmDialect
673 match &*asm_code.as_str() {
674 "cpuid" | "cpuid\n" => {
675 assert_eq!(inputs, &[Name::intern("{eax}"), Name::intern("{ecx}")]);
677 assert_eq!(outputs.len(), 4);
678 for (i, c) in (&["={eax}", "={ebx}", "={ecx}", "={edx}"]).iter().enumerate() {
679 assert_eq!(&outputs[i].constraint.as_str(), c);
680 assert!(!outputs[i].is_rw);
681 assert!(!outputs[i].is_indirect);
684 assert_eq!(clobbers, &[Name::intern("rbx")]);
687 assert!(!alignstack);
689 crate::trap::trap_unimplemented(fx, "__cpuid_count arch intrinsic is not supported");
692 assert_eq!(inputs, &[Name::intern("{ecx}")]);
694 assert_eq!(outputs.len(), 2);
695 for (i, c) in (&["={eax}", "={edx}"]).iter().enumerate() {
696 assert_eq!(&outputs[i].constraint.as_str(), c);
697 assert!(!outputs[i].is_rw);
698 assert!(!outputs[i].is_indirect);
701 assert_eq!(clobbers, &[]);
704 assert!(!alignstack);
706 crate::trap::trap_unimplemented(fx, "_xgetbv arch intrinsic is not supported");
708 _ => unimpl!("Inline assembly is not supported"),
714 fn codegen_array_len<'a, 'tcx: 'a>(
715 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
718 match place.layout().ty.sty {
719 ty::Array(_elem_ty, len) => {
720 let len = crate::constant::force_eval_const(fx, len).unwrap_usize(fx.tcx) as i64;
721 fx.bcx.ins().iconst(fx.pointer_type, len)
723 ty::Slice(_elem_ty) => place
724 .to_addr_maybe_unsized(fx)
726 .expect("Length metadata for slice place"),
727 _ => bug!("Rvalue::Len({:?})", place),
731 pub fn trans_get_discriminant<'a, 'tcx: 'a>(
732 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
734 dest_layout: TyLayout<'tcx>,
736 let layout = place.layout();
738 if layout.abi == layout::Abi::Uninhabited {
739 return trap_unreachable_ret_value(fx, dest_layout, "[panic] Tried to get discriminant for uninhabited type.");
742 let (discr_scalar, discr_index, discr_kind) = match &layout.variants {
743 layout::Variants::Single { index } => {
744 let discr_val = layout
747 .map_or(index.as_u32() as u128, |def| {
748 def.discriminant_for_variant(fx.tcx, *index).val
750 return CValue::const_val(fx, dest_layout.ty, discr_val as u64 as i64);
752 layout::Variants::Multiple { discr, discr_index, discr_kind, variants: _ } => {
753 (discr, *discr_index, discr_kind)
757 let discr = place.place_field(fx, mir::Field::new(discr_index)).to_cvalue(fx);
758 let discr_ty = discr.layout().ty;
759 let lldiscr = discr.load_scalar(fx);
761 layout::DiscriminantKind::Tag => {
762 let signed = match discr_scalar.value {
763 layout::Int(_, signed) => signed,
766 let val = clif_intcast(fx, lldiscr, fx.clif_type(dest_layout.ty).unwrap(), signed);
767 return CValue::by_val(val, dest_layout);
769 layout::DiscriminantKind::Niche {
774 let niche_llty = fx.clif_type(discr_ty).unwrap();
775 let dest_clif_ty = fx.clif_type(dest_layout.ty).unwrap();
776 if niche_variants.start() == niche_variants.end() {
780 .icmp_imm(IntCC::Equal, lldiscr, *niche_start as u64 as i64);
784 .iconst(dest_clif_ty, niche_variants.start().as_u32() as i64);
788 .iconst(dest_clif_ty, dataful_variant.as_u32() as i64);
789 let val = fx.bcx.ins().select(b, if_true, if_false);
790 return CValue::by_val(val, dest_layout);
792 // Rebase from niche values to discriminant values.
793 let delta = niche_start.wrapping_sub(niche_variants.start().as_u32() as u128);
794 let delta = fx.bcx.ins().iconst(niche_llty, delta as u64 as i64);
795 let lldiscr = fx.bcx.ins().isub(lldiscr, delta);
796 let b = fx.bcx.ins().icmp_imm(
797 IntCC::UnsignedLessThanOrEqual,
799 niche_variants.end().as_u32() as i64,
802 clif_intcast(fx, lldiscr, fx.clif_type(dest_layout.ty).unwrap(), false);
806 .iconst(dest_clif_ty, dataful_variant.as_u32() as i64);
807 let val = fx.bcx.ins().select(b, if_true, if_false);
808 return CValue::by_val(val, dest_layout);
814 macro_rules! binop_match {
815 (@single $fx:expr, $bug_fmt:expr, $var:expr, $signed:expr, $lhs:expr, $rhs:expr, $ret_ty:expr, bug) => {
816 bug!("binop {} on {} lhs: {:?} rhs: {:?}", stringify!($var), $bug_fmt, $lhs, $rhs)
818 (@single $fx:expr, $bug_fmt:expr, $var:expr, $signed:expr, $lhs:expr, $rhs:expr, $ret_ty:expr, icmp($cc:ident)) => {{
819 assert_eq!($fx.tcx.types.bool, $ret_ty);
820 let ret_layout = $fx.layout_of($ret_ty);
822 let b = $fx.bcx.ins().icmp(IntCC::$cc, $lhs, $rhs);
823 CValue::by_val($fx.bcx.ins().bint(types::I8, b), ret_layout)
825 (@single $fx:expr, $bug_fmt:expr, $var:expr, $signed:expr, $lhs:expr, $rhs:expr, $ret_ty:expr, fcmp($cc:ident)) => {{
826 assert_eq!($fx.tcx.types.bool, $ret_ty);
827 let ret_layout = $fx.layout_of($ret_ty);
828 let b = $fx.bcx.ins().fcmp(FloatCC::$cc, $lhs, $rhs);
829 CValue::by_val($fx.bcx.ins().bint(types::I8, b), ret_layout)
831 (@single $fx:expr, $bug_fmt:expr, $var:expr, $signed:expr, $lhs:expr, $rhs:expr, $ret_ty:expr, custom(|| $body:expr)) => {{
834 (@single $fx:expr, $bug_fmt:expr, $var:expr, $signed:expr, $lhs:expr, $rhs:expr, $ret_ty:expr, $name:ident) => {{
835 let ret_layout = $fx.layout_of($ret_ty);
836 CValue::by_val($fx.bcx.ins().$name($lhs, $rhs), ret_layout)
839 $fx:expr, $bin_op:expr, $signed:expr, $lhs:expr, $rhs:expr, $ret_ty:expr, $bug_fmt:expr;
841 $var:ident ($sign:pat) $name:tt $( ( $($next:tt)* ) )? ;
844 let lhs = $lhs.load_scalar($fx);
845 let rhs = $rhs.load_scalar($fx);
846 match ($bin_op, $signed) {
848 (BinOp::$var, $sign) => binop_match!(@single $fx, $bug_fmt, $var, $signed, lhs, rhs, $ret_ty, $name $( ( $($next)* ) )?),
854 fn trans_bool_binop<'a, 'tcx: 'a>(
855 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
861 let res = binop_match! {
862 fx, bin_op, false, lhs, rhs, ty, "bool";
875 Lt (_) icmp(UnsignedLessThan);
876 Le (_) icmp(UnsignedLessThanOrEqual);
877 Ne (_) icmp(NotEqual);
878 Ge (_) icmp(UnsignedGreaterThanOrEqual);
879 Gt (_) icmp(UnsignedGreaterThan);
887 pub fn trans_int_binop<'a, 'tcx: 'a>(
888 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
895 if bin_op != BinOp::Shl && bin_op != BinOp::Shr {
899 "int binop requires lhs and rhs of same type"
903 fx, bin_op, signed, lhs, rhs, out_ty, "int/uint";
919 Lt (false) icmp(UnsignedLessThan);
920 Lt (true) icmp(SignedLessThan);
921 Le (false) icmp(UnsignedLessThanOrEqual);
922 Le (true) icmp(SignedLessThanOrEqual);
923 Ne (_) icmp(NotEqual);
924 Ge (false) icmp(UnsignedGreaterThanOrEqual);
925 Ge (true) icmp(SignedGreaterThanOrEqual);
926 Gt (false) icmp(UnsignedGreaterThan);
927 Gt (true) icmp(SignedGreaterThan);
933 pub fn trans_checked_int_binop<'a, 'tcx: 'a>(
934 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
936 in_lhs: CValue<'tcx>,
937 in_rhs: CValue<'tcx>,
941 if bin_op != BinOp::Shl && bin_op != BinOp::Shr {
945 "checked int binop requires lhs and rhs of same type"
949 let lhs = in_lhs.load_scalar(fx);
950 let rhs = in_rhs.load_scalar(fx);
951 let res = match bin_op {
952 BinOp::Add => fx.bcx.ins().iadd(lhs, rhs),
953 BinOp::Sub => fx.bcx.ins().isub(lhs, rhs),
954 BinOp::Mul => fx.bcx.ins().imul(lhs, rhs),
955 BinOp::Shl => fx.bcx.ins().ishl(lhs, rhs),
958 fx.bcx.ins().ushr(lhs, rhs)
960 fx.bcx.ins().sshr(lhs, rhs)
964 "binop {:?} on checked int/uint lhs: {:?} rhs: {:?}",
971 // TODO: check for overflow
972 let has_overflow = fx.bcx.ins().iconst(types::I8, 0);
974 let out_place = CPlace::new_stack_slot(fx, out_ty);
975 let out_layout = out_place.layout();
976 out_place.write_cvalue(fx, CValue::by_val_pair(res, has_overflow, out_layout));
978 out_place.to_cvalue(fx)
981 fn trans_float_binop<'a, 'tcx: 'a>(
982 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
988 let res = binop_match! {
989 fx, bin_op, false, lhs, rhs, ty, "float";
995 assert_eq!(lhs.layout().ty, ty);
996 assert_eq!(rhs.layout().ty, ty);
998 ty::Float(FloatTy::F32) => fx.easy_call("fmodf", &[lhs, rhs], ty),
999 ty::Float(FloatTy::F64) => fx.easy_call("fmod", &[lhs, rhs], ty),
1010 Lt (_) fcmp(LessThan);
1011 Le (_) fcmp(LessThanOrEqual);
1012 Ne (_) fcmp(NotEqual);
1013 Ge (_) fcmp(GreaterThanOrEqual);
1014 Gt (_) fcmp(GreaterThan);
1022 fn trans_char_binop<'a, 'tcx: 'a>(
1023 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
1029 let res = binop_match! {
1030 fx, bin_op, false, lhs, rhs, ty, "char";
1043 Lt (_) icmp(UnsignedLessThan);
1044 Le (_) icmp(UnsignedLessThanOrEqual);
1045 Ne (_) icmp(NotEqual);
1046 Ge (_) icmp(UnsignedGreaterThanOrEqual);
1047 Gt (_) icmp(UnsignedGreaterThan);
1055 fn trans_ptr_binop<'a, 'tcx: 'a>(
1056 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
1062 let not_fat = match lhs.layout().ty.sty {
1063 ty::RawPtr(TypeAndMut { ty, mutbl: _ }) => {
1064 ty.is_sized(fx.tcx.at(DUMMY_SP), ParamEnv::reveal_all())
1066 ty::FnPtr(..) => true,
1067 _ => bug!("trans_ptr_binop on non ptr"),
1070 if let BinOp::Offset = bin_op {
1071 let (base, offset) = (lhs, rhs.load_scalar(fx));
1072 let pointee_ty = base.layout().ty.builtin_deref(true).unwrap().ty;
1073 let pointee_size = fx.layout_of(pointee_ty).size.bytes();
1074 let ptr_diff = fx.bcx.ins().imul_imm(offset, pointee_size as i64);
1075 let base_val = base.load_scalar(fx);
1076 let res = fx.bcx.ins().iadd(base_val, ptr_diff);
1077 return CValue::by_val(res, base.layout());
1081 fx, bin_op, false, lhs, rhs, ret_ty, "ptr";
1094 Lt (_) icmp(UnsignedLessThan);
1095 Le (_) icmp(UnsignedLessThanOrEqual);
1096 Ne (_) icmp(NotEqual);
1097 Ge (_) icmp(UnsignedGreaterThanOrEqual);
1098 Gt (_) icmp(UnsignedGreaterThan);
1100 Offset (_) bug; // Handled above
1103 let (lhs_ptr, lhs_extra) = lhs.load_scalar_pair(fx);
1104 let (rhs_ptr, rhs_extra) = rhs.load_scalar_pair(fx);
1106 let res = match bin_op {
1108 let ptr_eq = fx.bcx.ins().icmp(IntCC::Equal, lhs_ptr, rhs_ptr);
1109 let extra_eq = fx.bcx.ins().icmp(IntCC::Equal, lhs_extra, rhs_extra);
1110 fx.bcx.ins().band(ptr_eq, extra_eq)
1113 let ptr_ne = fx.bcx.ins().icmp(IntCC::NotEqual, lhs_ptr, rhs_ptr);
1114 let extra_ne = fx.bcx.ins().icmp(IntCC::NotEqual, lhs_extra, rhs_extra);
1115 fx.bcx.ins().bor(ptr_ne, extra_ne)
1117 BinOp::Lt | BinOp::Le | BinOp::Ge | BinOp::Gt => {
1118 let ptr_eq = fx.bcx.ins().icmp(IntCC::Equal, lhs_ptr, rhs_ptr);
1120 let ptr_cmp = fx.bcx.ins().icmp(match bin_op {
1121 BinOp::Lt => IntCC::UnsignedLessThan,
1122 BinOp::Le => IntCC::UnsignedLessThanOrEqual,
1123 BinOp::Ge => IntCC::UnsignedGreaterThanOrEqual,
1124 BinOp::Gt => IntCC::UnsignedGreaterThan,
1125 _ => unreachable!(),
1126 }, lhs_ptr, rhs_ptr);
1128 let extra_cmp = fx.bcx.ins().icmp(match bin_op {
1129 BinOp::Lt => IntCC::UnsignedLessThan,
1130 BinOp::Le => IntCC::UnsignedLessThanOrEqual,
1131 BinOp::Ge => IntCC::UnsignedGreaterThanOrEqual,
1132 BinOp::Gt => IntCC::UnsignedGreaterThan,
1133 _ => unreachable!(),
1134 }, lhs_extra, rhs_extra);
1136 fx.bcx.ins().select(ptr_eq, extra_cmp, ptr_cmp)
1138 _ => panic!("bin_op {:?} on ptr", bin_op),
1141 assert_eq!(fx.tcx.types.bool, ret_ty);
1142 let ret_layout = fx.layout_of(ret_ty);
1143 CValue::by_val(fx.bcx.ins().bint(types::I8, res), ret_layout)
1147 pub fn trans_place<'a, 'tcx: 'a>(
1148 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
1149 place: &Place<'tcx>,
1152 Place::Base(base) => match base {
1153 PlaceBase::Local(local) => fx.get_local_place(*local),
1154 PlaceBase::Static(static_) => match static_.kind {
1155 StaticKind::Static(def_id) => {
1156 crate::constant::codegen_static_ref(fx, def_id, static_.ty)
1158 StaticKind::Promoted(promoted) => {
1159 crate::constant::trans_promoted(fx, promoted, static_.ty)
1163 Place::Projection(projection) => {
1164 let base = trans_place(fx, &projection.base);
1165 match projection.elem {
1166 ProjectionElem::Deref => base.place_deref(fx),
1167 ProjectionElem::Field(field, _ty) => base.place_field(fx, field),
1168 ProjectionElem::Index(local) => {
1169 let index = fx.get_local_place(local).to_cvalue(fx).load_scalar(fx);
1170 base.place_index(fx, index)
1172 ProjectionElem::ConstantIndex {
1177 let index = if !from_end {
1178 fx.bcx.ins().iconst(fx.pointer_type, offset as i64)
1180 let len = codegen_array_len(fx, base);
1181 fx.bcx.ins().iadd_imm(len, -(offset as i64))
1183 base.place_index(fx, index)
1185 ProjectionElem::Subslice { from, to } => {
1186 // These indices are generated by slice patterns.
1187 // slice[from:-to] in Python terms.
1189 match base.layout().ty.sty {
1190 ty::Array(elem_ty, len) => {
1191 let elem_layout = fx.layout_of(elem_ty);
1192 let ptr = base.to_addr(fx);
1193 let len = crate::constant::force_eval_const(fx, len).unwrap_usize(fx.tcx);
1195 fx.bcx.ins().iadd_imm(ptr, elem_layout.size.bytes() as i64 * from as i64),
1196 fx.layout_of(fx.tcx.mk_array(elem_ty, len - from as u64 - to as u64)),
1199 ty::Slice(elem_ty) => {
1200 let elem_layout = fx.layout_of(elem_ty);
1201 let (ptr, len) = base.to_addr_maybe_unsized(fx);
1202 let len = len.unwrap();
1203 CPlace::for_addr_with_extra(
1204 fx.bcx.ins().iadd_imm(ptr, elem_layout.size.bytes() as i64 * from as i64),
1205 fx.bcx.ins().iadd_imm(len, -(from as i64 + to as i64)),
1209 _ => unreachable!(),
1212 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_),