1 //! Codegen of a single function
3 use cranelift_codegen::binemit::{NullStackMapSink, NullTrapSink};
4 use rustc_index::vec::IndexVec;
5 use rustc_middle::ty::adjustment::PointerCast;
6 use rustc_middle::ty::layout::FnAbiExt;
7 use rustc_target::abi::call::FnAbi;
9 use crate::constant::ConstantCx;
10 use crate::prelude::*;
12 pub(crate) fn codegen_fn<'tcx>(
13 cx: &mut crate::CodegenCx<'tcx>,
14 module: &mut dyn Module,
15 instance: Instance<'tcx>,
20 crate::PrintOnPanic(|| format!("{:?} {}", instance, tcx.symbol_name(instance).name));
21 debug_assert!(!instance.substs.needs_infer());
23 let mir = tcx.instance_mir(instance.def);
26 let symbol_name = tcx.symbol_name(instance);
27 let sig = get_function_sig(tcx, module.isa().triple(), instance);
28 let func_id = module.declare_function(symbol_name.name, Linkage::Local, &sig).unwrap();
30 cx.cached_context.clear();
32 // Make the FunctionBuilder
33 let mut func_ctx = FunctionBuilderContext::new();
34 let mut func = std::mem::replace(&mut cx.cached_context.func, Function::new());
35 func.name = ExternalName::user(0, func_id.as_u32());
37 func.collect_debug_info();
39 let mut bcx = FunctionBuilder::new(&mut func, &mut func_ctx);
42 let start_block = bcx.create_block();
43 let block_map: IndexVec<BasicBlock, Block> =
44 (0..mir.basic_blocks().len()).map(|_| bcx.create_block()).collect();
47 let pointer_type = module.target_config().pointer_type();
48 let clif_comments = crate::pretty_clif::CommentWriter::new(tcx, instance);
50 let mut fx = FunctionCx {
55 vtables: FxHashMap::default(),
56 constants_cx: ConstantCx::new(),
61 fn_abi: Some(FnAbi::of_instance(&RevealAllLayoutCx(tcx), instance, &[])),
65 local_map: IndexVec::with_capacity(mir.local_decls.len()),
66 caller_location: None, // set by `codegen_fn_prelude`
69 source_info_set: indexmap::IndexSet::new(),
75 let arg_uninhabited = fx
78 .any(|arg| fx.layout_of(fx.monomorphize(&fx.mir.local_decls[arg].ty)).abi.is_uninhabited());
80 if !crate::constant::check_constants(&mut fx) {
81 fx.bcx.append_block_params_for_function_params(fx.block_map[START_BLOCK]);
82 fx.bcx.switch_to_block(fx.block_map[START_BLOCK]);
83 crate::trap::trap_unreachable(&mut fx, "compilation should have been aborted");
84 } else if arg_uninhabited {
85 fx.bcx.append_block_params_for_function_params(fx.block_map[START_BLOCK]);
86 fx.bcx.switch_to_block(fx.block_map[START_BLOCK]);
87 crate::trap::trap_unreachable(&mut fx, "function has uninhabited argument");
89 tcx.sess.time("codegen clif ir", || {
91 .time("codegen prelude", || crate::abi::codegen_fn_prelude(&mut fx, start_block));
92 codegen_fn_content(&mut fx);
96 // Recover all necessary data from fx, before accessing func will prevent future access to it.
97 let instance = fx.instance;
98 let mut clif_comments = fx.clif_comments;
99 let source_info_set = fx.source_info_set;
100 let local_map = fx.local_map;
102 fx.constants_cx.finalize(fx.tcx, &mut *fx.module);
104 // Store function in context
105 let context = &mut cx.cached_context;
108 crate::pretty_clif::write_clif_file(tcx, "unopt", None, instance, &context, &clif_comments);
111 verify_func(tcx, &clif_comments, &context.func);
113 // If the return block is not reachable, then the SSA builder may have inserted an `iconst.i128`
114 // instruction, which doesn't have an encoding.
115 context.compute_cfg();
116 context.compute_domtree();
117 context.eliminate_unreachable_code(module.isa()).unwrap();
118 context.dce(module.isa()).unwrap();
119 // Some Cranelift optimizations expect the domtree to not yet be computed and as such don't
120 // invalidate it when it would change.
121 context.domtree.clear();
123 // Perform rust specific optimizations
124 tcx.sess.time("optimize clif ir", || {
125 crate::optimize::optimize_function(tcx, instance, context, &mut clif_comments);
129 tcx.sess.time("define function", || {
130 context.want_disasm = crate::pretty_clif::should_write_ir(tcx);
132 .define_function(func_id, context, &mut NullTrapSink {}, &mut NullStackMapSink {})
136 // Write optimized function to file for debugging
137 crate::pretty_clif::write_clif_file(
146 if let Some(disasm) = &context.mach_compile_result.as_ref().unwrap().disasm {
147 crate::pretty_clif::write_ir_file(
149 || format!("{}.vcode", tcx.symbol_name(instance).name),
150 |file| file.write_all(disasm.as_bytes()),
154 // Define debuginfo for function
155 let isa = module.isa();
156 let debug_context = &mut cx.debug_context;
157 let unwind_context = &mut cx.unwind_context;
158 tcx.sess.time("generate debug info", || {
159 if let Some(debug_context) = debug_context {
160 debug_context.define_function(
170 unwind_context.add_function(func_id, &context, isa);
173 // Clear context to make it usable for the next function
177 pub(crate) fn verify_func(
179 writer: &crate::pretty_clif::CommentWriter,
182 tcx.sess.time("verify clif ir", || {
183 let flags = cranelift_codegen::settings::Flags::new(cranelift_codegen::settings::builder());
184 match cranelift_codegen::verify_function(&func, &flags) {
187 tcx.sess.err(&format!("{:?}", err));
188 let pretty_error = cranelift_codegen::print_errors::pretty_verifier_error(
191 Some(Box::new(writer)),
194 tcx.sess.fatal(&format!("cranelift verify error:\n{}", pretty_error));
200 fn codegen_fn_content(fx: &mut FunctionCx<'_, '_, '_>) {
201 for (bb, bb_data) in fx.mir.basic_blocks().iter_enumerated() {
202 let block = fx.get_block(bb);
203 fx.bcx.switch_to_block(block);
205 if bb_data.is_cleanup {
206 // Unwinding after panicking is not supported
209 // FIXME Once unwinding is supported and Cranelift supports marking blocks as cold, do
210 // so for cleanup blocks.
214 for stmt in &bb_data.statements {
215 fx.set_debug_loc(stmt.source_info);
216 codegen_stmt(fx, block, stmt);
219 if fx.clif_comments.enabled() {
220 let mut terminator_head = "\n".to_string();
221 bb_data.terminator().kind.fmt_head(&mut terminator_head).unwrap();
222 let inst = fx.bcx.func.layout.last_inst(block).unwrap();
223 fx.add_comment(inst, terminator_head);
226 fx.set_debug_loc(bb_data.terminator().source_info);
228 match &bb_data.terminator().kind {
229 TerminatorKind::Goto { target } => {
230 if let TerminatorKind::Return = fx.mir[*target].terminator().kind {
231 let mut can_immediately_return = true;
232 for stmt in &fx.mir[*target].statements {
233 if let StatementKind::StorageDead(_) = stmt.kind {
235 // FIXME Can sometimes happen, see rust-lang/rust#70531
236 can_immediately_return = false;
241 if can_immediately_return {
242 crate::abi::codegen_return(fx);
247 let block = fx.get_block(*target);
248 fx.bcx.ins().jump(block, &[]);
250 TerminatorKind::Return => {
251 crate::abi::codegen_return(fx);
253 TerminatorKind::Assert { cond, expected, msg, target, cleanup: _ } => {
254 if !fx.tcx.sess.overflow_checks() {
255 if let mir::AssertKind::OverflowNeg(_) = *msg {
256 let target = fx.get_block(*target);
257 fx.bcx.ins().jump(target, &[]);
261 let cond = codegen_operand(fx, cond).load_scalar(fx);
263 let target = fx.get_block(*target);
264 let failure = fx.bcx.create_block();
265 // FIXME Mark failure block as cold once Cranelift supports it
268 fx.bcx.ins().brz(cond, failure, &[]);
270 fx.bcx.ins().brnz(cond, failure, &[]);
272 fx.bcx.ins().jump(target, &[]);
274 fx.bcx.switch_to_block(failure);
278 AssertKind::BoundsCheck { ref len, ref index } => {
279 let len = codegen_operand(fx, len).load_scalar(fx);
280 let index = codegen_operand(fx, index).load_scalar(fx);
282 .get_caller_location(bb_data.terminator().source_info.span)
287 rustc_hir::LangItem::PanicBoundsCheck,
288 &[index, len, location],
289 bb_data.terminator().source_info.span,
293 let msg_str = msg.description();
294 codegen_panic(fx, msg_str, bb_data.terminator().source_info.span);
299 TerminatorKind::SwitchInt { discr, switch_ty, targets } => {
300 let discr = codegen_operand(fx, discr).load_scalar(fx);
302 let use_bool_opt = switch_ty.kind() == fx.tcx.types.bool.kind()
303 || (targets.iter().count() == 1 && targets.iter().next().unwrap().0 == 0);
305 assert_eq!(targets.iter().count(), 1);
306 let (then_value, then_block) = targets.iter().next().unwrap();
307 let then_block = fx.get_block(then_block);
308 let else_block = fx.get_block(targets.otherwise());
309 let test_zero = match then_value {
312 _ => unreachable!("{:?}", targets),
315 let discr = crate::optimize::peephole::maybe_unwrap_bint(&mut fx.bcx, discr);
316 let (discr, is_inverted) =
317 crate::optimize::peephole::maybe_unwrap_bool_not(&mut fx.bcx, discr);
318 let test_zero = if is_inverted { !test_zero } else { test_zero };
319 let discr = crate::optimize::peephole::maybe_unwrap_bint(&mut fx.bcx, discr);
321 crate::optimize::peephole::make_branchable_value(&mut fx.bcx, discr);
322 if let Some(taken) = crate::optimize::peephole::maybe_known_branch_taken(
323 &fx.bcx, discr, test_zero,
326 fx.bcx.ins().jump(then_block, &[]);
328 fx.bcx.ins().jump(else_block, &[]);
332 fx.bcx.ins().brz(discr, then_block, &[]);
333 fx.bcx.ins().jump(else_block, &[]);
335 fx.bcx.ins().brnz(discr, then_block, &[]);
336 fx.bcx.ins().jump(else_block, &[]);
340 let mut switch = ::cranelift_frontend::Switch::new();
341 for (value, block) in targets.iter() {
342 let block = fx.get_block(block);
343 switch.set_entry(value, block);
345 let otherwise_block = fx.get_block(targets.otherwise());
346 switch.emit(&mut fx.bcx, discr, otherwise_block);
349 TerminatorKind::Call {
357 fx.tcx.sess.time("codegen call", || {
358 crate::abi::codegen_terminator_call(fx, *fn_span, func, args, *destination)
361 TerminatorKind::InlineAsm {
368 crate::inline_asm::codegen_inline_asm(
370 bb_data.terminator().source_info.span,
377 Some(destination) => {
378 let destination_block = fx.get_block(destination);
379 fx.bcx.ins().jump(destination_block, &[]);
382 crate::trap::trap_unreachable(
384 "[corruption] Returned from noreturn inline asm",
389 TerminatorKind::Resume | TerminatorKind::Abort => {
390 trap_unreachable(fx, "[corruption] Unwinding bb reached.");
392 TerminatorKind::Unreachable => {
393 trap_unreachable(fx, "[corruption] Hit unreachable code.");
395 TerminatorKind::Yield { .. }
396 | TerminatorKind::FalseEdge { .. }
397 | TerminatorKind::FalseUnwind { .. }
398 | TerminatorKind::DropAndReplace { .. }
399 | TerminatorKind::GeneratorDrop => {
400 bug!("shouldn't exist at codegen {:?}", bb_data.terminator());
402 TerminatorKind::Drop { place, target, unwind: _ } => {
403 let drop_place = codegen_place(fx, *place);
404 crate::abi::codegen_drop(fx, bb_data.terminator().source_info.span, drop_place);
406 let target_block = fx.get_block(*target);
407 fx.bcx.ins().jump(target_block, &[]);
412 fx.bcx.seal_all_blocks();
416 fn codegen_stmt<'tcx>(
417 fx: &mut FunctionCx<'_, '_, 'tcx>,
418 #[allow(unused_variables)] cur_block: Block,
419 stmt: &Statement<'tcx>,
421 let _print_guard = crate::PrintOnPanic(|| format!("stmt {:?}", stmt));
423 fx.set_debug_loc(stmt.source_info);
427 StatementKind::StorageLive(..) | StatementKind::StorageDead(..) => {} // Those are not very useful
429 if fx.clif_comments.enabled() {
430 let inst = fx.bcx.func.layout.last_inst(cur_block).unwrap();
431 fx.add_comment(inst, format!("{:?}", stmt));
437 StatementKind::SetDiscriminant { place, variant_index } => {
438 let place = codegen_place(fx, **place);
439 crate::discriminant::codegen_set_discriminant(fx, place, *variant_index);
441 StatementKind::Assign(to_place_and_rval) => {
442 let lval = codegen_place(fx, to_place_and_rval.0);
443 let dest_layout = lval.layout();
444 match to_place_and_rval.1 {
445 Rvalue::Use(ref operand) => {
446 let val = codegen_operand(fx, operand);
447 lval.write_cvalue(fx, val);
449 Rvalue::Ref(_, _, place) | Rvalue::AddressOf(_, place) => {
450 let place = codegen_place(fx, place);
451 let ref_ = place.place_ref(fx, lval.layout());
452 lval.write_cvalue(fx, ref_);
454 Rvalue::ThreadLocalRef(def_id) => {
455 let val = crate::constant::codegen_tls_ref(fx, def_id, lval.layout());
456 lval.write_cvalue(fx, val);
458 Rvalue::BinaryOp(bin_op, ref lhs_rhs) => {
459 let lhs = codegen_operand(fx, &lhs_rhs.0);
460 let rhs = codegen_operand(fx, &lhs_rhs.1);
462 let res = crate::num::codegen_binop(fx, bin_op, lhs, rhs);
463 lval.write_cvalue(fx, res);
465 Rvalue::CheckedBinaryOp(bin_op, ref lhs_rhs) => {
466 let lhs = codegen_operand(fx, &lhs_rhs.0);
467 let rhs = codegen_operand(fx, &lhs_rhs.1);
469 let res = if !fx.tcx.sess.overflow_checks() {
471 crate::num::codegen_int_binop(fx, bin_op, lhs, rhs).load_scalar(fx);
472 let is_overflow = fx.bcx.ins().iconst(types::I8, 0);
473 CValue::by_val_pair(val, is_overflow, lval.layout())
475 crate::num::codegen_checked_int_binop(fx, bin_op, lhs, rhs)
478 lval.write_cvalue(fx, res);
480 Rvalue::UnaryOp(un_op, ref operand) => {
481 let operand = codegen_operand(fx, operand);
482 let layout = operand.layout();
483 let val = operand.load_scalar(fx);
484 let res = match un_op {
485 UnOp::Not => match layout.ty.kind() {
487 let res = fx.bcx.ins().icmp_imm(IntCC::Equal, val, 0);
488 CValue::by_val(fx.bcx.ins().bint(types::I8, res), layout)
490 ty::Uint(_) | ty::Int(_) => {
491 CValue::by_val(fx.bcx.ins().bnot(val), layout)
493 _ => unreachable!("un op Not for {:?}", layout.ty),
495 UnOp::Neg => match layout.ty.kind() {
496 ty::Int(IntTy::I128) => {
497 // FIXME remove this case once ineg.i128 works
499 CValue::const_val(fx, layout, ty::ScalarInt::null(layout.size));
500 crate::num::codegen_int_binop(fx, BinOp::Sub, zero, operand)
502 ty::Int(_) => CValue::by_val(fx.bcx.ins().ineg(val), layout),
503 ty::Float(_) => CValue::by_val(fx.bcx.ins().fneg(val), layout),
504 _ => unreachable!("un op Neg for {:?}", layout.ty),
507 lval.write_cvalue(fx, res);
510 CastKind::Pointer(PointerCast::ReifyFnPointer),
514 let from_ty = fx.monomorphize(operand.ty(&fx.mir.local_decls, fx.tcx));
515 let to_layout = fx.layout_of(fx.monomorphize(to_ty));
516 match *from_ty.kind() {
517 ty::FnDef(def_id, substs) => {
518 let func_ref = fx.get_function_ref(
519 Instance::resolve_for_fn_ptr(
521 ParamEnv::reveal_all(),
526 .polymorphize(fx.tcx),
528 let func_addr = fx.bcx.ins().func_addr(fx.pointer_type, func_ref);
529 lval.write_cvalue(fx, CValue::by_val(func_addr, to_layout));
531 _ => bug!("Trying to ReifyFnPointer on non FnDef {:?}", from_ty),
535 CastKind::Pointer(PointerCast::UnsafeFnPointer),
540 CastKind::Pointer(PointerCast::MutToConstPointer),
545 CastKind::Pointer(PointerCast::ArrayToPointer),
549 let to_layout = fx.layout_of(fx.monomorphize(to_ty));
550 let operand = codegen_operand(fx, operand);
551 lval.write_cvalue(fx, operand.cast_pointer_to(to_layout));
553 Rvalue::Cast(CastKind::Misc, ref operand, to_ty) => {
554 let operand = codegen_operand(fx, operand);
555 let from_ty = operand.layout().ty;
556 let to_ty = fx.monomorphize(to_ty);
558 fn is_fat_ptr<'tcx>(fx: &FunctionCx<'_, '_, 'tcx>, ty: Ty<'tcx>) -> bool {
559 ty.builtin_deref(true)
560 .map(|ty::TypeAndMut { ty: pointee_ty, mutbl: _ }| {
561 has_ptr_meta(fx.tcx, pointee_ty)
566 if is_fat_ptr(fx, from_ty) {
567 if is_fat_ptr(fx, to_ty) {
568 // fat-ptr -> fat-ptr
569 lval.write_cvalue(fx, operand.cast_pointer_to(dest_layout));
571 // fat-ptr -> thin-ptr
572 let (ptr, _extra) = operand.load_scalar_pair(fx);
573 lval.write_cvalue(fx, CValue::by_val(ptr, dest_layout))
575 } else if let ty::Adt(adt_def, _substs) = from_ty.kind() {
576 // enum -> discriminant value
577 assert!(adt_def.is_enum());
579 ty::Uint(_) | ty::Int(_) => {}
580 _ => unreachable!("cast adt {} -> {}", from_ty, to_ty),
582 let to_clif_ty = fx.clif_type(to_ty).unwrap();
584 let discriminant = crate::discriminant::codegen_get_discriminant(
587 fx.layout_of(operand.layout().ty.discriminant_ty(fx.tcx)),
591 let res = crate::cast::clif_intcast(
597 lval.write_cvalue(fx, CValue::by_val(res, dest_layout));
599 let to_clif_ty = fx.clif_type(to_ty).unwrap();
600 let from = operand.load_scalar(fx);
602 let res = clif_int_or_float_cast(
609 lval.write_cvalue(fx, CValue::by_val(res, dest_layout));
613 CastKind::Pointer(PointerCast::ClosureFnPointer(_)),
617 let operand = codegen_operand(fx, operand);
618 match *operand.layout().ty.kind() {
619 ty::Closure(def_id, substs) => {
620 let instance = Instance::resolve_closure(
624 ty::ClosureKind::FnOnce,
626 .polymorphize(fx.tcx);
627 let func_ref = fx.get_function_ref(instance);
628 let func_addr = fx.bcx.ins().func_addr(fx.pointer_type, func_ref);
629 lval.write_cvalue(fx, CValue::by_val(func_addr, lval.layout()));
631 _ => bug!("{} cannot be cast to a fn ptr", operand.layout().ty),
634 Rvalue::Cast(CastKind::Pointer(PointerCast::Unsize), ref operand, _to_ty) => {
635 let operand = codegen_operand(fx, operand);
636 operand.unsize_value(fx, lval);
638 Rvalue::Discriminant(place) => {
639 let place = codegen_place(fx, place);
640 let value = place.to_cvalue(fx);
642 crate::discriminant::codegen_get_discriminant(fx, value, dest_layout);
643 lval.write_cvalue(fx, discr);
645 Rvalue::Repeat(ref operand, times) => {
646 let operand = codegen_operand(fx, operand);
649 .eval(fx.tcx, ParamEnv::reveal_all())
651 .try_to_bits(fx.tcx.data_layout.pointer_size)
653 if operand.layout().size.bytes() == 0 {
654 // Do nothing for ZST's
655 } else if fx.clif_type(operand.layout().ty) == Some(types::I8) {
656 let times = fx.bcx.ins().iconst(fx.pointer_type, times as i64);
657 // FIXME use emit_small_memset where possible
658 let addr = lval.to_ptr().get_addr(fx);
659 let val = operand.load_scalar(fx);
660 fx.bcx.call_memset(fx.module.target_config(), addr, val, times);
662 let loop_block = fx.bcx.create_block();
663 let loop_block2 = fx.bcx.create_block();
664 let done_block = fx.bcx.create_block();
665 let index = fx.bcx.append_block_param(loop_block, fx.pointer_type);
666 let zero = fx.bcx.ins().iconst(fx.pointer_type, 0);
667 fx.bcx.ins().jump(loop_block, &[zero]);
669 fx.bcx.switch_to_block(loop_block);
670 let done = fx.bcx.ins().icmp_imm(IntCC::Equal, index, times as i64);
671 fx.bcx.ins().brnz(done, done_block, &[]);
672 fx.bcx.ins().jump(loop_block2, &[]);
674 fx.bcx.switch_to_block(loop_block2);
675 let to = lval.place_index(fx, index);
676 to.write_cvalue(fx, operand);
677 let index = fx.bcx.ins().iadd_imm(index, 1);
678 fx.bcx.ins().jump(loop_block, &[index]);
680 fx.bcx.switch_to_block(done_block);
684 Rvalue::Len(place) => {
685 let place = codegen_place(fx, place);
686 let usize_layout = fx.layout_of(fx.tcx.types.usize);
687 let len = codegen_array_len(fx, place);
688 lval.write_cvalue(fx, CValue::by_val(len, usize_layout));
690 Rvalue::NullaryOp(NullOp::Box, content_ty) => {
691 let usize_type = fx.clif_type(fx.tcx.types.usize).unwrap();
692 let content_ty = fx.monomorphize(content_ty);
693 let layout = fx.layout_of(content_ty);
694 let llsize = fx.bcx.ins().iconst(usize_type, layout.size.bytes() as i64);
695 let llalign = fx.bcx.ins().iconst(usize_type, layout.align.abi.bytes() as i64);
696 let box_layout = fx.layout_of(fx.tcx.mk_box(content_ty));
700 match fx.tcx.lang_items().require(rustc_hir::LangItem::ExchangeMalloc) {
705 .fatal(&format!("allocation of `{}` {}", box_layout.ty, s));
708 let instance = ty::Instance::mono(fx.tcx, def_id).polymorphize(fx.tcx);
709 let func_ref = fx.get_function_ref(instance);
710 let call = fx.bcx.ins().call(func_ref, &[llsize, llalign]);
711 let ptr = fx.bcx.inst_results(call)[0];
712 lval.write_cvalue(fx, CValue::by_val(ptr, box_layout));
714 Rvalue::NullaryOp(NullOp::SizeOf, ty) => {
718 .is_sized(fx.tcx.at(stmt.source_info.span), ParamEnv::reveal_all())
720 let ty_size = fx.layout_of(fx.monomorphize(ty)).size.bytes();
722 CValue::const_val(fx, fx.layout_of(fx.tcx.types.usize), ty_size.into());
723 lval.write_cvalue(fx, val);
725 Rvalue::Aggregate(ref kind, ref operands) => match kind.as_ref() {
726 AggregateKind::Array(_ty) => {
727 for (i, operand) in operands.iter().enumerate() {
728 let operand = codegen_operand(fx, operand);
729 let index = fx.bcx.ins().iconst(fx.pointer_type, i as i64);
730 let to = lval.place_index(fx, index);
731 to.write_cvalue(fx, operand);
734 _ => unreachable!("shouldn't exist at codegen {:?}", to_place_and_rval.1),
738 StatementKind::StorageLive(_)
739 | StatementKind::StorageDead(_)
741 | StatementKind::FakeRead(..)
742 | StatementKind::Retag { .. }
743 | StatementKind::AscribeUserType(..) => {}
745 StatementKind::LlvmInlineAsm(asm) => {
746 match asm.asm.asm.as_str().trim() {
750 _ => fx.tcx.sess.span_fatal(
751 stmt.source_info.span,
752 "Legacy `llvm_asm!` inline assembly is not supported. \
753 Try using the new `asm!` instead.",
757 StatementKind::Coverage { .. } => fx.tcx.sess.fatal("-Zcoverage is unimplemented"),
758 StatementKind::CopyNonOverlapping(inner) => {
759 let dst = codegen_operand(fx, &inner.dst);
762 .pointee_info_at(fx, rustc_target::abi::Size::ZERO)
763 .expect("Expected pointer");
764 let dst = dst.load_scalar(fx);
765 let src = codegen_operand(fx, &inner.src).load_scalar(fx);
766 let count = codegen_operand(fx, &inner.count).load_scalar(fx);
767 let elem_size: u64 = pointee.size.bytes();
769 if elem_size != 1 { fx.bcx.ins().imul_imm(count, elem_size as i64) } else { count };
770 fx.bcx.call_memcpy(fx.module.target_config(), dst, src, bytes);
775 fn codegen_array_len<'tcx>(fx: &mut FunctionCx<'_, '_, 'tcx>, place: CPlace<'tcx>) -> Value {
776 match *place.layout().ty.kind() {
777 ty::Array(_elem_ty, len) => {
778 let len = fx.monomorphize(len).eval_usize(fx.tcx, ParamEnv::reveal_all()) as i64;
779 fx.bcx.ins().iconst(fx.pointer_type, len)
781 ty::Slice(_elem_ty) => {
782 place.to_ptr_maybe_unsized().1.expect("Length metadata for slice place")
784 _ => bug!("Rvalue::Len({:?})", place),
788 pub(crate) fn codegen_place<'tcx>(
789 fx: &mut FunctionCx<'_, '_, 'tcx>,
792 let mut cplace = fx.get_local_place(place.local);
794 for elem in place.projection {
796 PlaceElem::Deref => {
797 cplace = cplace.place_deref(fx);
799 PlaceElem::Field(field, _ty) => {
800 cplace = cplace.place_field(fx, field);
802 PlaceElem::Index(local) => {
803 let index = fx.get_local_place(local).to_cvalue(fx).load_scalar(fx);
804 cplace = cplace.place_index(fx, index);
806 PlaceElem::ConstantIndex { offset, min_length: _, from_end } => {
807 let offset: u64 = offset;
808 let index = if !from_end {
809 fx.bcx.ins().iconst(fx.pointer_type, offset as i64)
811 let len = codegen_array_len(fx, cplace);
812 fx.bcx.ins().iadd_imm(len, -(offset as i64))
814 cplace = cplace.place_index(fx, index);
816 PlaceElem::Subslice { from, to, from_end } => {
817 // These indices are generated by slice patterns.
818 // slice[from:-to] in Python terms.
820 let from: u64 = from;
823 match cplace.layout().ty.kind() {
824 ty::Array(elem_ty, _len) => {
825 assert!(!from_end, "array subslices are never `from_end`");
826 let elem_layout = fx.layout_of(elem_ty);
827 let ptr = cplace.to_ptr();
828 cplace = CPlace::for_ptr(
829 ptr.offset_i64(fx, elem_layout.size.bytes() as i64 * (from as i64)),
830 fx.layout_of(fx.tcx.mk_array(elem_ty, to - from)),
833 ty::Slice(elem_ty) => {
834 assert!(from_end, "slice subslices should be `from_end`");
835 let elem_layout = fx.layout_of(elem_ty);
836 let (ptr, len) = cplace.to_ptr_maybe_unsized();
837 let len = len.unwrap();
838 cplace = CPlace::for_ptr_with_extra(
839 ptr.offset_i64(fx, elem_layout.size.bytes() as i64 * (from as i64)),
840 fx.bcx.ins().iadd_imm(len, -(from as i64 + to as i64)),
847 PlaceElem::Downcast(_adt_def, variant) => {
848 cplace = cplace.downcast_variant(fx, variant);
856 pub(crate) fn codegen_operand<'tcx>(
857 fx: &mut FunctionCx<'_, '_, 'tcx>,
858 operand: &Operand<'tcx>,
861 Operand::Move(place) | Operand::Copy(place) => {
862 let cplace = codegen_place(fx, *place);
865 Operand::Constant(const_) => crate::constant::codegen_constant(fx, const_),
869 pub(crate) fn codegen_panic<'tcx>(fx: &mut FunctionCx<'_, '_, 'tcx>, msg_str: &str, span: Span) {
870 let location = fx.get_caller_location(span).load_scalar(fx);
872 let msg_ptr = fx.anonymous_str(msg_str);
873 let msg_len = fx.bcx.ins().iconst(fx.pointer_type, i64::try_from(msg_str.len()).unwrap());
874 let args = [msg_ptr, msg_len, location];
876 codegen_panic_inner(fx, rustc_hir::LangItem::Panic, &args, span);
879 pub(crate) fn codegen_panic_inner<'tcx>(
880 fx: &mut FunctionCx<'_, '_, 'tcx>,
881 lang_item: rustc_hir::LangItem,
886 fx.tcx.lang_items().require(lang_item).unwrap_or_else(|s| fx.tcx.sess.span_fatal(span, &s));
888 let instance = Instance::mono(fx.tcx, def_id).polymorphize(fx.tcx);
889 let symbol_name = fx.tcx.symbol_name(instance).name;
894 AbiParam::new(fx.pointer_type),
895 AbiParam::new(fx.pointer_type),
896 AbiParam::new(fx.pointer_type),
902 crate::trap::trap_unreachable(fx, "panic lang item returned");