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);
24 let _mir_guard = crate::PrintOnPanic(|| {
25 let mut buf = Vec::new();
26 rustc_mir::util::write_mir_pretty(tcx, Some(instance.def_id()), &mut buf).unwrap();
27 String::from_utf8_lossy(&buf).into_owned()
31 let symbol_name = tcx.symbol_name(instance);
32 let sig = get_function_sig(tcx, module.isa().triple(), instance);
33 let func_id = module.declare_function(symbol_name.name, Linkage::Local, &sig).unwrap();
35 cx.cached_context.clear();
37 // Make the FunctionBuilder
38 let mut func_ctx = FunctionBuilderContext::new();
39 let mut func = std::mem::replace(&mut cx.cached_context.func, Function::new());
40 func.name = ExternalName::user(0, func_id.as_u32());
42 func.collect_debug_info();
44 let mut bcx = FunctionBuilder::new(&mut func, &mut func_ctx);
47 let start_block = bcx.create_block();
48 let block_map: IndexVec<BasicBlock, Block> =
49 (0..mir.basic_blocks().len()).map(|_| bcx.create_block()).collect();
52 let pointer_type = module.target_config().pointer_type();
53 let clif_comments = crate::pretty_clif::CommentWriter::new(tcx, instance);
55 let mut fx = FunctionCx {
60 constants_cx: ConstantCx::new(),
65 fn_abi: Some(FnAbi::of_instance(&RevealAllLayoutCx(tcx), instance, &[])),
69 local_map: IndexVec::with_capacity(mir.local_decls.len()),
70 caller_location: None, // set by `codegen_fn_prelude`
73 source_info_set: indexmap::IndexSet::new(),
79 let arg_uninhabited = fx
82 .any(|arg| fx.layout_of(fx.monomorphize(&fx.mir.local_decls[arg].ty)).abi.is_uninhabited());
84 if !crate::constant::check_constants(&mut fx) {
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, "compilation should have been aborted");
88 } else if arg_uninhabited {
89 fx.bcx.append_block_params_for_function_params(fx.block_map[START_BLOCK]);
90 fx.bcx.switch_to_block(fx.block_map[START_BLOCK]);
91 crate::trap::trap_unreachable(&mut fx, "function has uninhabited argument");
93 tcx.sess.time("codegen clif ir", || {
95 .time("codegen prelude", || crate::abi::codegen_fn_prelude(&mut fx, start_block));
96 codegen_fn_content(&mut fx);
100 // Recover all necessary data from fx, before accessing func will prevent future access to it.
101 let instance = fx.instance;
102 let mut clif_comments = fx.clif_comments;
103 let source_info_set = fx.source_info_set;
104 let local_map = fx.local_map;
106 fx.constants_cx.finalize(fx.tcx, &mut *fx.module);
108 // Store function in context
109 let context = &mut cx.cached_context;
112 crate::pretty_clif::write_clif_file(
122 verify_func(tcx, &clif_comments, &context.func);
124 // If the return block is not reachable, then the SSA builder may have inserted an `iconst.i128`
125 // instruction, which doesn't have an encoding.
126 context.compute_cfg();
127 context.compute_domtree();
128 context.eliminate_unreachable_code(module.isa()).unwrap();
129 context.dce(module.isa()).unwrap();
130 // Some Cranelift optimizations expect the domtree to not yet be computed and as such don't
131 // invalidate it when it would change.
132 context.domtree.clear();
134 // Perform rust specific optimizations
135 tcx.sess.time("optimize clif ir", || {
136 crate::optimize::optimize_function(
146 tcx.sess.time("define function", || {
147 context.want_disasm = crate::pretty_clif::should_write_ir(tcx);
149 .define_function(func_id, context, &mut NullTrapSink {}, &mut NullStackMapSink {})
153 // Write optimized function to file for debugging
154 crate::pretty_clif::write_clif_file(
163 if let Some(disasm) = &context.mach_compile_result.as_ref().unwrap().disasm {
164 crate::pretty_clif::write_ir_file(
166 || format!("{}.vcode", tcx.symbol_name(instance).name),
167 |file| file.write_all(disasm.as_bytes()),
171 // Define debuginfo for function
172 let isa = module.isa();
173 let debug_context = &mut cx.debug_context;
174 let unwind_context = &mut cx.unwind_context;
175 tcx.sess.time("generate debug info", || {
176 if let Some(debug_context) = debug_context {
177 debug_context.define_function(
187 unwind_context.add_function(func_id, &context, isa);
190 // Clear context to make it usable for the next function
194 pub(crate) fn verify_func(
196 writer: &crate::pretty_clif::CommentWriter,
199 tcx.sess.time("verify clif ir", || {
200 let flags = cranelift_codegen::settings::Flags::new(cranelift_codegen::settings::builder());
201 match cranelift_codegen::verify_function(&func, &flags) {
204 tcx.sess.err(&format!("{:?}", err));
205 let pretty_error = cranelift_codegen::print_errors::pretty_verifier_error(
208 Some(Box::new(writer)),
211 tcx.sess.fatal(&format!("cranelift verify error:\n{}", pretty_error));
217 fn codegen_fn_content(fx: &mut FunctionCx<'_, '_, '_>) {
218 for (bb, bb_data) in fx.mir.basic_blocks().iter_enumerated() {
219 let block = fx.get_block(bb);
220 fx.bcx.switch_to_block(block);
222 if bb_data.is_cleanup {
223 // Unwinding after panicking is not supported
226 // FIXME Once unwinding is supported and Cranelift supports marking blocks as cold, do
227 // so for cleanup blocks.
231 for stmt in &bb_data.statements {
232 fx.set_debug_loc(stmt.source_info);
233 codegen_stmt(fx, block, stmt);
236 if fx.clif_comments.enabled() {
237 let mut terminator_head = "\n".to_string();
238 bb_data.terminator().kind.fmt_head(&mut terminator_head).unwrap();
239 let inst = fx.bcx.func.layout.last_inst(block).unwrap();
240 fx.add_comment(inst, terminator_head);
243 fx.set_debug_loc(bb_data.terminator().source_info);
245 match &bb_data.terminator().kind {
246 TerminatorKind::Goto { target } => {
247 if let TerminatorKind::Return = fx.mir[*target].terminator().kind {
248 let mut can_immediately_return = true;
249 for stmt in &fx.mir[*target].statements {
250 if let StatementKind::StorageDead(_) = stmt.kind {
252 // FIXME Can sometimes happen, see rust-lang/rust#70531
253 can_immediately_return = false;
258 if can_immediately_return {
259 crate::abi::codegen_return(fx);
264 let block = fx.get_block(*target);
265 fx.bcx.ins().jump(block, &[]);
267 TerminatorKind::Return => {
268 crate::abi::codegen_return(fx);
270 TerminatorKind::Assert { cond, expected, msg, target, cleanup: _ } => {
271 if !fx.tcx.sess.overflow_checks() {
272 if let mir::AssertKind::OverflowNeg(_) = *msg {
273 let target = fx.get_block(*target);
274 fx.bcx.ins().jump(target, &[]);
278 let cond = codegen_operand(fx, cond).load_scalar(fx);
280 let target = fx.get_block(*target);
281 let failure = fx.bcx.create_block();
282 // FIXME Mark failure block as cold once Cranelift supports it
285 fx.bcx.ins().brz(cond, failure, &[]);
287 fx.bcx.ins().brnz(cond, failure, &[]);
289 fx.bcx.ins().jump(target, &[]);
291 fx.bcx.switch_to_block(failure);
295 AssertKind::BoundsCheck { ref len, ref index } => {
296 let len = codegen_operand(fx, len).load_scalar(fx);
297 let index = codegen_operand(fx, index).load_scalar(fx);
299 .get_caller_location(bb_data.terminator().source_info.span)
304 rustc_hir::LangItem::PanicBoundsCheck,
305 &[index, len, location],
306 bb_data.terminator().source_info.span,
310 let msg_str = msg.description();
311 codegen_panic(fx, msg_str, bb_data.terminator().source_info.span);
316 TerminatorKind::SwitchInt { discr, switch_ty, targets } => {
317 let discr = codegen_operand(fx, discr).load_scalar(fx);
319 let use_bool_opt = switch_ty.kind() == fx.tcx.types.bool.kind()
320 || (targets.iter().count() == 1 && targets.iter().next().unwrap().0 == 0);
322 assert_eq!(targets.iter().count(), 1);
323 let (then_value, then_block) = targets.iter().next().unwrap();
324 let then_block = fx.get_block(then_block);
325 let else_block = fx.get_block(targets.otherwise());
326 let test_zero = match then_value {
329 _ => unreachable!("{:?}", targets),
332 let discr = crate::optimize::peephole::maybe_unwrap_bint(&mut fx.bcx, discr);
333 let (discr, is_inverted) =
334 crate::optimize::peephole::maybe_unwrap_bool_not(&mut fx.bcx, discr);
335 let test_zero = if is_inverted { !test_zero } else { test_zero };
336 let discr = crate::optimize::peephole::maybe_unwrap_bint(&mut fx.bcx, discr);
337 if let Some(taken) = crate::optimize::peephole::maybe_known_branch_taken(
338 &fx.bcx, discr, test_zero,
341 fx.bcx.ins().jump(then_block, &[]);
343 fx.bcx.ins().jump(else_block, &[]);
347 fx.bcx.ins().brz(discr, then_block, &[]);
348 fx.bcx.ins().jump(else_block, &[]);
350 fx.bcx.ins().brnz(discr, then_block, &[]);
351 fx.bcx.ins().jump(else_block, &[]);
355 let mut switch = ::cranelift_frontend::Switch::new();
356 for (value, block) in targets.iter() {
357 let block = fx.get_block(block);
358 switch.set_entry(value, block);
360 let otherwise_block = fx.get_block(targets.otherwise());
361 switch.emit(&mut fx.bcx, discr, otherwise_block);
364 TerminatorKind::Call {
372 fx.tcx.sess.time("codegen call", || {
373 crate::abi::codegen_terminator_call(fx, *fn_span, func, args, *destination)
376 TerminatorKind::InlineAsm {
383 crate::inline_asm::codegen_inline_asm(
385 bb_data.terminator().source_info.span,
392 Some(destination) => {
393 let destination_block = fx.get_block(destination);
394 fx.bcx.ins().jump(destination_block, &[]);
397 crate::trap::trap_unreachable(
399 "[corruption] Returned from noreturn inline asm",
404 TerminatorKind::Resume | TerminatorKind::Abort => {
405 trap_unreachable(fx, "[corruption] Unwinding bb reached.");
407 TerminatorKind::Unreachable => {
408 trap_unreachable(fx, "[corruption] Hit unreachable code.");
410 TerminatorKind::Yield { .. }
411 | TerminatorKind::FalseEdge { .. }
412 | TerminatorKind::FalseUnwind { .. }
413 | TerminatorKind::DropAndReplace { .. }
414 | TerminatorKind::GeneratorDrop => {
415 bug!("shouldn't exist at codegen {:?}", bb_data.terminator());
417 TerminatorKind::Drop { place, target, unwind: _ } => {
418 let drop_place = codegen_place(fx, *place);
419 crate::abi::codegen_drop(fx, bb_data.terminator().source_info.span, drop_place);
421 let target_block = fx.get_block(*target);
422 fx.bcx.ins().jump(target_block, &[]);
427 fx.bcx.seal_all_blocks();
431 fn codegen_stmt<'tcx>(
432 fx: &mut FunctionCx<'_, '_, 'tcx>,
433 #[allow(unused_variables)] cur_block: Block,
434 stmt: &Statement<'tcx>,
436 let _print_guard = crate::PrintOnPanic(|| format!("stmt {:?}", stmt));
438 fx.set_debug_loc(stmt.source_info);
442 StatementKind::StorageLive(..) | StatementKind::StorageDead(..) => {} // Those are not very useful
444 if fx.clif_comments.enabled() {
445 let inst = fx.bcx.func.layout.last_inst(cur_block).unwrap();
446 fx.add_comment(inst, format!("{:?}", stmt));
452 StatementKind::SetDiscriminant { place, variant_index } => {
453 let place = codegen_place(fx, **place);
454 crate::discriminant::codegen_set_discriminant(fx, place, *variant_index);
456 StatementKind::Assign(to_place_and_rval) => {
457 let lval = codegen_place(fx, to_place_and_rval.0);
458 let dest_layout = lval.layout();
459 match to_place_and_rval.1 {
460 Rvalue::Use(ref operand) => {
461 let val = codegen_operand(fx, operand);
462 lval.write_cvalue(fx, val);
464 Rvalue::Ref(_, _, place) | Rvalue::AddressOf(_, place) => {
465 let place = codegen_place(fx, place);
466 let ref_ = place.place_ref(fx, lval.layout());
467 lval.write_cvalue(fx, ref_);
469 Rvalue::ThreadLocalRef(def_id) => {
470 let val = crate::constant::codegen_tls_ref(fx, def_id, lval.layout());
471 lval.write_cvalue(fx, val);
473 Rvalue::BinaryOp(bin_op, ref lhs_rhs) => {
474 let lhs = codegen_operand(fx, &lhs_rhs.0);
475 let rhs = codegen_operand(fx, &lhs_rhs.1);
477 let res = crate::num::codegen_binop(fx, bin_op, lhs, rhs);
478 lval.write_cvalue(fx, res);
480 Rvalue::CheckedBinaryOp(bin_op, ref lhs_rhs) => {
481 let lhs = codegen_operand(fx, &lhs_rhs.0);
482 let rhs = codegen_operand(fx, &lhs_rhs.1);
484 let res = if !fx.tcx.sess.overflow_checks() {
486 crate::num::codegen_int_binop(fx, bin_op, lhs, rhs).load_scalar(fx);
487 let is_overflow = fx.bcx.ins().iconst(types::I8, 0);
488 CValue::by_val_pair(val, is_overflow, lval.layout())
490 crate::num::codegen_checked_int_binop(fx, bin_op, lhs, rhs)
493 lval.write_cvalue(fx, res);
495 Rvalue::UnaryOp(un_op, ref operand) => {
496 let operand = codegen_operand(fx, operand);
497 let layout = operand.layout();
498 let val = operand.load_scalar(fx);
499 let res = match un_op {
500 UnOp::Not => match layout.ty.kind() {
502 let res = fx.bcx.ins().icmp_imm(IntCC::Equal, val, 0);
503 CValue::by_val(fx.bcx.ins().bint(types::I8, res), layout)
505 ty::Uint(_) | ty::Int(_) => {
506 CValue::by_val(fx.bcx.ins().bnot(val), layout)
508 _ => unreachable!("un op Not for {:?}", layout.ty),
510 UnOp::Neg => match layout.ty.kind() {
511 ty::Int(IntTy::I128) => {
512 // FIXME remove this case once ineg.i128 works
514 CValue::const_val(fx, layout, ty::ScalarInt::null(layout.size));
515 crate::num::codegen_int_binop(fx, BinOp::Sub, zero, operand)
517 ty::Int(_) => CValue::by_val(fx.bcx.ins().ineg(val), layout),
518 ty::Float(_) => CValue::by_val(fx.bcx.ins().fneg(val), layout),
519 _ => unreachable!("un op Neg for {:?}", layout.ty),
522 lval.write_cvalue(fx, res);
525 CastKind::Pointer(PointerCast::ReifyFnPointer),
529 let from_ty = fx.monomorphize(operand.ty(&fx.mir.local_decls, fx.tcx));
530 let to_layout = fx.layout_of(fx.monomorphize(to_ty));
531 match *from_ty.kind() {
532 ty::FnDef(def_id, substs) => {
533 let func_ref = fx.get_function_ref(
534 Instance::resolve_for_fn_ptr(
536 ParamEnv::reveal_all(),
541 .polymorphize(fx.tcx),
543 let func_addr = fx.bcx.ins().func_addr(fx.pointer_type, func_ref);
544 lval.write_cvalue(fx, CValue::by_val(func_addr, to_layout));
546 _ => bug!("Trying to ReifyFnPointer on non FnDef {:?}", from_ty),
550 CastKind::Pointer(PointerCast::UnsafeFnPointer),
555 CastKind::Pointer(PointerCast::MutToConstPointer),
560 CastKind::Pointer(PointerCast::ArrayToPointer),
564 let to_layout = fx.layout_of(fx.monomorphize(to_ty));
565 let operand = codegen_operand(fx, operand);
566 lval.write_cvalue(fx, operand.cast_pointer_to(to_layout));
568 Rvalue::Cast(CastKind::Misc, ref operand, to_ty) => {
569 let operand = codegen_operand(fx, operand);
570 let from_ty = operand.layout().ty;
571 let to_ty = fx.monomorphize(to_ty);
573 fn is_fat_ptr<'tcx>(fx: &FunctionCx<'_, '_, 'tcx>, ty: Ty<'tcx>) -> bool {
574 ty.builtin_deref(true)
575 .map(|ty::TypeAndMut { ty: pointee_ty, mutbl: _ }| {
576 has_ptr_meta(fx.tcx, pointee_ty)
581 if is_fat_ptr(fx, from_ty) {
582 if is_fat_ptr(fx, to_ty) {
583 // fat-ptr -> fat-ptr
584 lval.write_cvalue(fx, operand.cast_pointer_to(dest_layout));
586 // fat-ptr -> thin-ptr
587 let (ptr, _extra) = operand.load_scalar_pair(fx);
588 lval.write_cvalue(fx, CValue::by_val(ptr, dest_layout))
590 } else if let ty::Adt(adt_def, _substs) = from_ty.kind() {
591 // enum -> discriminant value
592 assert!(adt_def.is_enum());
594 ty::Uint(_) | ty::Int(_) => {}
595 _ => unreachable!("cast adt {} -> {}", from_ty, to_ty),
597 let to_clif_ty = fx.clif_type(to_ty).unwrap();
599 let discriminant = crate::discriminant::codegen_get_discriminant(
602 fx.layout_of(operand.layout().ty.discriminant_ty(fx.tcx)),
606 let res = crate::cast::clif_intcast(
612 lval.write_cvalue(fx, CValue::by_val(res, dest_layout));
614 let to_clif_ty = fx.clif_type(to_ty).unwrap();
615 let from = operand.load_scalar(fx);
617 let res = clif_int_or_float_cast(
624 lval.write_cvalue(fx, CValue::by_val(res, dest_layout));
628 CastKind::Pointer(PointerCast::ClosureFnPointer(_)),
632 let operand = codegen_operand(fx, operand);
633 match *operand.layout().ty.kind() {
634 ty::Closure(def_id, substs) => {
635 let instance = Instance::resolve_closure(
639 ty::ClosureKind::FnOnce,
641 .polymorphize(fx.tcx);
642 let func_ref = fx.get_function_ref(instance);
643 let func_addr = fx.bcx.ins().func_addr(fx.pointer_type, func_ref);
644 lval.write_cvalue(fx, CValue::by_val(func_addr, lval.layout()));
646 _ => bug!("{} cannot be cast to a fn ptr", operand.layout().ty),
649 Rvalue::Cast(CastKind::Pointer(PointerCast::Unsize), ref operand, _to_ty) => {
650 let operand = codegen_operand(fx, operand);
651 operand.unsize_value(fx, lval);
653 Rvalue::Discriminant(place) => {
654 let place = codegen_place(fx, place);
655 let value = place.to_cvalue(fx);
657 crate::discriminant::codegen_get_discriminant(fx, value, dest_layout);
658 lval.write_cvalue(fx, discr);
660 Rvalue::Repeat(ref operand, times) => {
661 let operand = codegen_operand(fx, operand);
664 .eval(fx.tcx, ParamEnv::reveal_all())
666 .try_to_bits(fx.tcx.data_layout.pointer_size)
668 if operand.layout().size.bytes() == 0 {
669 // Do nothing for ZST's
670 } else if fx.clif_type(operand.layout().ty) == Some(types::I8) {
671 let times = fx.bcx.ins().iconst(fx.pointer_type, times as i64);
672 // FIXME use emit_small_memset where possible
673 let addr = lval.to_ptr().get_addr(fx);
674 let val = operand.load_scalar(fx);
675 fx.bcx.call_memset(fx.module.target_config(), addr, val, times);
677 let loop_block = fx.bcx.create_block();
678 let loop_block2 = fx.bcx.create_block();
679 let done_block = fx.bcx.create_block();
680 let index = fx.bcx.append_block_param(loop_block, fx.pointer_type);
681 let zero = fx.bcx.ins().iconst(fx.pointer_type, 0);
682 fx.bcx.ins().jump(loop_block, &[zero]);
684 fx.bcx.switch_to_block(loop_block);
685 let done = fx.bcx.ins().icmp_imm(IntCC::Equal, index, times as i64);
686 fx.bcx.ins().brnz(done, done_block, &[]);
687 fx.bcx.ins().jump(loop_block2, &[]);
689 fx.bcx.switch_to_block(loop_block2);
690 let to = lval.place_index(fx, index);
691 to.write_cvalue(fx, operand);
692 let index = fx.bcx.ins().iadd_imm(index, 1);
693 fx.bcx.ins().jump(loop_block, &[index]);
695 fx.bcx.switch_to_block(done_block);
699 Rvalue::Len(place) => {
700 let place = codegen_place(fx, place);
701 let usize_layout = fx.layout_of(fx.tcx.types.usize);
702 let len = codegen_array_len(fx, place);
703 lval.write_cvalue(fx, CValue::by_val(len, usize_layout));
705 Rvalue::NullaryOp(NullOp::Box, content_ty) => {
706 let usize_type = fx.clif_type(fx.tcx.types.usize).unwrap();
707 let content_ty = fx.monomorphize(content_ty);
708 let layout = fx.layout_of(content_ty);
709 let llsize = fx.bcx.ins().iconst(usize_type, layout.size.bytes() as i64);
710 let llalign = fx.bcx.ins().iconst(usize_type, layout.align.abi.bytes() as i64);
711 let box_layout = fx.layout_of(fx.tcx.mk_box(content_ty));
715 match fx.tcx.lang_items().require(rustc_hir::LangItem::ExchangeMalloc) {
720 .fatal(&format!("allocation of `{}` {}", box_layout.ty, s));
723 let instance = ty::Instance::mono(fx.tcx, def_id).polymorphize(fx.tcx);
724 let func_ref = fx.get_function_ref(instance);
725 let call = fx.bcx.ins().call(func_ref, &[llsize, llalign]);
726 let ptr = fx.bcx.inst_results(call)[0];
727 lval.write_cvalue(fx, CValue::by_val(ptr, box_layout));
729 Rvalue::NullaryOp(NullOp::SizeOf, ty) => {
733 .is_sized(fx.tcx.at(stmt.source_info.span), ParamEnv::reveal_all())
735 let ty_size = fx.layout_of(fx.monomorphize(ty)).size.bytes();
737 CValue::const_val(fx, fx.layout_of(fx.tcx.types.usize), ty_size.into());
738 lval.write_cvalue(fx, val);
740 Rvalue::Aggregate(ref kind, ref operands) => match kind.as_ref() {
741 AggregateKind::Array(_ty) => {
742 for (i, operand) in operands.iter().enumerate() {
743 let operand = codegen_operand(fx, operand);
744 let index = fx.bcx.ins().iconst(fx.pointer_type, i as i64);
745 let to = lval.place_index(fx, index);
746 to.write_cvalue(fx, operand);
749 _ => unreachable!("shouldn't exist at codegen {:?}", to_place_and_rval.1),
753 StatementKind::StorageLive(_)
754 | StatementKind::StorageDead(_)
756 | StatementKind::FakeRead(..)
757 | StatementKind::Retag { .. }
758 | StatementKind::AscribeUserType(..) => {}
760 StatementKind::LlvmInlineAsm(asm) => {
761 match asm.asm.asm.as_str().trim() {
765 _ => fx.tcx.sess.span_fatal(
766 stmt.source_info.span,
767 "Legacy `llvm_asm!` inline assembly is not supported. \
768 Try using the new `asm!` instead.",
772 StatementKind::Coverage { .. } => fx.tcx.sess.fatal("-Zcoverage is unimplemented"),
773 StatementKind::CopyNonOverlapping(inner) => {
774 let dst = codegen_operand(fx, &inner.dst);
777 .pointee_info_at(fx, rustc_target::abi::Size::ZERO)
778 .expect("Expected pointer");
779 let dst = dst.load_scalar(fx);
780 let src = codegen_operand(fx, &inner.src).load_scalar(fx);
781 let count = codegen_operand(fx, &inner.count).load_scalar(fx);
782 let elem_size: u64 = pointee.size.bytes();
784 if elem_size != 1 { fx.bcx.ins().imul_imm(count, elem_size as i64) } else { count };
785 fx.bcx.call_memcpy(fx.module.target_config(), dst, src, bytes);
790 fn codegen_array_len<'tcx>(fx: &mut FunctionCx<'_, '_, 'tcx>, place: CPlace<'tcx>) -> Value {
791 match *place.layout().ty.kind() {
792 ty::Array(_elem_ty, len) => {
793 let len = fx.monomorphize(len).eval_usize(fx.tcx, ParamEnv::reveal_all()) as i64;
794 fx.bcx.ins().iconst(fx.pointer_type, len)
796 ty::Slice(_elem_ty) => {
797 place.to_ptr_maybe_unsized().1.expect("Length metadata for slice place")
799 _ => bug!("Rvalue::Len({:?})", place),
803 pub(crate) fn codegen_place<'tcx>(
804 fx: &mut FunctionCx<'_, '_, 'tcx>,
807 let mut cplace = fx.get_local_place(place.local);
809 for elem in place.projection {
811 PlaceElem::Deref => {
812 cplace = cplace.place_deref(fx);
814 PlaceElem::Field(field, _ty) => {
815 cplace = cplace.place_field(fx, field);
817 PlaceElem::Index(local) => {
818 let index = fx.get_local_place(local).to_cvalue(fx).load_scalar(fx);
819 cplace = cplace.place_index(fx, index);
821 PlaceElem::ConstantIndex { offset, min_length: _, from_end } => {
822 let offset: u64 = offset;
823 let index = if !from_end {
824 fx.bcx.ins().iconst(fx.pointer_type, offset as i64)
826 let len = codegen_array_len(fx, cplace);
827 fx.bcx.ins().iadd_imm(len, -(offset as i64))
829 cplace = cplace.place_index(fx, index);
831 PlaceElem::Subslice { from, to, from_end } => {
832 // These indices are generated by slice patterns.
833 // slice[from:-to] in Python terms.
835 let from: u64 = from;
838 match cplace.layout().ty.kind() {
839 ty::Array(elem_ty, _len) => {
840 assert!(!from_end, "array subslices are never `from_end`");
841 let elem_layout = fx.layout_of(elem_ty);
842 let ptr = cplace.to_ptr();
843 cplace = CPlace::for_ptr(
844 ptr.offset_i64(fx, elem_layout.size.bytes() as i64 * (from as i64)),
845 fx.layout_of(fx.tcx.mk_array(elem_ty, to - from)),
848 ty::Slice(elem_ty) => {
849 assert!(from_end, "slice subslices should be `from_end`");
850 let elem_layout = fx.layout_of(elem_ty);
851 let (ptr, len) = cplace.to_ptr_maybe_unsized();
852 let len = len.unwrap();
853 cplace = CPlace::for_ptr_with_extra(
854 ptr.offset_i64(fx, elem_layout.size.bytes() as i64 * (from as i64)),
855 fx.bcx.ins().iadd_imm(len, -(from as i64 + to as i64)),
862 PlaceElem::Downcast(_adt_def, variant) => {
863 cplace = cplace.downcast_variant(fx, variant);
871 pub(crate) fn codegen_operand<'tcx>(
872 fx: &mut FunctionCx<'_, '_, 'tcx>,
873 operand: &Operand<'tcx>,
876 Operand::Move(place) | Operand::Copy(place) => {
877 let cplace = codegen_place(fx, *place);
880 Operand::Constant(const_) => crate::constant::codegen_constant(fx, const_),
884 pub(crate) fn codegen_panic<'tcx>(fx: &mut FunctionCx<'_, '_, 'tcx>, msg_str: &str, span: Span) {
885 let location = fx.get_caller_location(span).load_scalar(fx);
887 let msg_ptr = fx.anonymous_str(msg_str);
888 let msg_len = fx.bcx.ins().iconst(fx.pointer_type, i64::try_from(msg_str.len()).unwrap());
889 let args = [msg_ptr, msg_len, location];
891 codegen_panic_inner(fx, rustc_hir::LangItem::Panic, &args, span);
894 pub(crate) fn codegen_panic_inner<'tcx>(
895 fx: &mut FunctionCx<'_, '_, 'tcx>,
896 lang_item: rustc_hir::LangItem,
901 fx.tcx.lang_items().require(lang_item).unwrap_or_else(|s| fx.tcx.sess.span_fatal(span, &s));
903 let instance = Instance::mono(fx.tcx, def_id).polymorphize(fx.tcx);
904 let symbol_name = fx.tcx.symbol_name(instance).name;
909 AbiParam::new(fx.pointer_type),
910 AbiParam::new(fx.pointer_type),
911 AbiParam::new(fx.pointer_type),
917 crate::trap::trap_unreachable(fx, "panic lang item returned");