1 //! Codegen of a single function
3 use rustc_ast::InlineAsmOptions;
4 use rustc_index::vec::IndexVec;
5 use rustc_middle::ty::adjustment::PointerCast;
6 use rustc_middle::ty::layout::FnAbiOf;
8 use indexmap::IndexSet;
10 use crate::constant::ConstantCx;
11 use crate::prelude::*;
12 use crate::pretty_clif::CommentWriter;
14 pub(crate) fn codegen_fn<'tcx>(
15 cx: &mut crate::CodegenCx<'tcx>,
16 module: &mut dyn Module,
17 instance: Instance<'tcx>,
22 crate::PrintOnPanic(|| format!("{:?} {}", instance, tcx.symbol_name(instance).name));
23 debug_assert!(!instance.substs.needs_infer());
25 let mir = tcx.instance_mir(instance.def);
26 let _mir_guard = crate::PrintOnPanic(|| {
27 let mut buf = Vec::new();
28 rustc_middle::mir::write_mir_pretty(tcx, Some(instance.def_id()), &mut buf).unwrap();
29 String::from_utf8_lossy(&buf).into_owned()
33 let symbol_name = tcx.symbol_name(instance);
34 let sig = get_function_sig(tcx, module.isa().triple(), instance);
35 let func_id = module.declare_function(symbol_name.name, Linkage::Local, &sig).unwrap();
37 cx.cached_context.clear();
39 // Make the FunctionBuilder
40 let mut func_ctx = FunctionBuilderContext::new();
41 let mut func = std::mem::replace(&mut cx.cached_context.func, Function::new());
42 func.name = ExternalName::user(0, func_id.as_u32());
44 func.collect_debug_info();
46 let mut bcx = FunctionBuilder::new(&mut func, &mut func_ctx);
49 let start_block = bcx.create_block();
50 let block_map: IndexVec<BasicBlock, Block> =
51 (0..mir.basic_blocks().len()).map(|_| bcx.create_block()).collect();
54 let target_config = module.target_config();
55 let pointer_type = target_config.pointer_type();
56 let clif_comments = crate::pretty_clif::CommentWriter::new(tcx, instance);
58 let mut fx = FunctionCx {
64 constants_cx: ConstantCx::new(),
69 fn_abi: Some(RevealAllLayoutCx(tcx).fn_abi_of_instance(instance, ty::List::empty())),
73 local_map: IndexVec::with_capacity(mir.local_decls.len()),
74 caller_location: None, // set by `codegen_fn_prelude`
77 source_info_set: indexmap::IndexSet::new(),
81 let arg_uninhabited = fx
84 .any(|arg| fx.layout_of(fx.monomorphize(fx.mir.local_decls[arg].ty)).abi.is_uninhabited());
86 if !crate::constant::check_constants(&mut fx) {
87 fx.bcx.append_block_params_for_function_params(fx.block_map[START_BLOCK]);
88 fx.bcx.switch_to_block(fx.block_map[START_BLOCK]);
89 crate::trap::trap_unreachable(&mut fx, "compilation should have been aborted");
90 } else if arg_uninhabited {
91 fx.bcx.append_block_params_for_function_params(fx.block_map[START_BLOCK]);
92 fx.bcx.switch_to_block(fx.block_map[START_BLOCK]);
93 crate::trap::trap_unreachable(&mut fx, "function has uninhabited argument");
95 tcx.sess.time("codegen clif ir", || {
97 .time("codegen prelude", || crate::abi::codegen_fn_prelude(&mut fx, start_block));
98 codegen_fn_content(&mut fx);
102 // Recover all necessary data from fx, before accessing func will prevent future access to it.
103 let instance = fx.instance;
104 let clif_comments = fx.clif_comments;
105 let source_info_set = fx.source_info_set;
106 let local_map = fx.local_map;
108 fx.constants_cx.finalize(fx.tcx, &mut *fx.module);
110 crate::pretty_clif::write_clif_file(
120 verify_func(tcx, &clif_comments, &func);
136 cx: &mut crate::CodegenCx<'tcx>,
137 module: &mut dyn Module,
138 instance: Instance<'tcx>,
142 mut clif_comments: CommentWriter,
143 source_info_set: IndexSet<SourceInfo>,
144 local_map: IndexVec<mir::Local, CPlace<'tcx>>,
148 // Store function in context
149 let context = &mut cx.cached_context;
153 // If the return block is not reachable, then the SSA builder may have inserted an `iconst.i128`
154 // instruction, which doesn't have an encoding.
155 context.compute_cfg();
156 context.compute_domtree();
157 context.eliminate_unreachable_code(module.isa()).unwrap();
158 context.dce(module.isa()).unwrap();
159 // Some Cranelift optimizations expect the domtree to not yet be computed and as such don't
160 // invalidate it when it would change.
161 context.domtree.clear();
163 // Perform rust specific optimizations
164 tcx.sess.time("optimize clif ir", || {
165 crate::optimize::optimize_function(
175 tcx.sess.time("define function", || {
176 context.want_disasm = crate::pretty_clif::should_write_ir(tcx);
177 module.define_function(func_id, context).unwrap()
180 // Write optimized function to file for debugging
181 crate::pretty_clif::write_clif_file(
190 if let Some(disasm) = &context.mach_compile_result.as_ref().unwrap().disasm {
191 crate::pretty_clif::write_ir_file(
193 || format!("{}.vcode", tcx.symbol_name(instance).name),
194 |file| file.write_all(disasm.as_bytes()),
198 // Define debuginfo for function
199 let isa = module.isa();
200 let debug_context = &mut cx.debug_context;
201 let unwind_context = &mut cx.unwind_context;
202 tcx.sess.time("generate debug info", || {
203 if let Some(debug_context) = debug_context {
204 debug_context.define_function(
214 unwind_context.add_function(func_id, &context, isa);
218 pub(crate) fn verify_func(
220 writer: &crate::pretty_clif::CommentWriter,
223 tcx.sess.time("verify clif ir", || {
224 let flags = cranelift_codegen::settings::Flags::new(cranelift_codegen::settings::builder());
225 match cranelift_codegen::verify_function(&func, &flags) {
228 tcx.sess.err(&format!("{:?}", err));
229 let pretty_error = cranelift_codegen::print_errors::pretty_verifier_error(
231 Some(Box::new(writer)),
234 tcx.sess.fatal(&format!("cranelift verify error:\n{}", pretty_error));
240 fn codegen_fn_content(fx: &mut FunctionCx<'_, '_, '_>) {
241 for (bb, bb_data) in fx.mir.basic_blocks().iter_enumerated() {
242 let block = fx.get_block(bb);
243 fx.bcx.switch_to_block(block);
245 if bb_data.is_cleanup {
246 // Unwinding after panicking is not supported
249 // FIXME Once unwinding is supported and Cranelift supports marking blocks as cold, do
250 // so for cleanup blocks.
254 for stmt in &bb_data.statements {
255 fx.set_debug_loc(stmt.source_info);
256 codegen_stmt(fx, block, stmt);
259 if fx.clif_comments.enabled() {
260 let mut terminator_head = "\n".to_string();
261 bb_data.terminator().kind.fmt_head(&mut terminator_head).unwrap();
262 let inst = fx.bcx.func.layout.last_inst(block).unwrap();
263 fx.add_comment(inst, terminator_head);
266 let source_info = bb_data.terminator().source_info;
267 fx.set_debug_loc(source_info);
269 match &bb_data.terminator().kind {
270 TerminatorKind::Goto { target } => {
271 if let TerminatorKind::Return = fx.mir[*target].terminator().kind {
272 let mut can_immediately_return = true;
273 for stmt in &fx.mir[*target].statements {
274 if let StatementKind::StorageDead(_) = stmt.kind {
276 // FIXME Can sometimes happen, see rust-lang/rust#70531
277 can_immediately_return = false;
282 if can_immediately_return {
283 crate::abi::codegen_return(fx);
288 let block = fx.get_block(*target);
289 fx.bcx.ins().jump(block, &[]);
291 TerminatorKind::Return => {
292 crate::abi::codegen_return(fx);
294 TerminatorKind::Assert { cond, expected, msg, target, cleanup: _ } => {
295 if !fx.tcx.sess.overflow_checks() {
296 if let mir::AssertKind::OverflowNeg(_) = *msg {
297 let target = fx.get_block(*target);
298 fx.bcx.ins().jump(target, &[]);
302 let cond = codegen_operand(fx, cond).load_scalar(fx);
304 let target = fx.get_block(*target);
305 let failure = fx.bcx.create_block();
306 // FIXME Mark failure block as cold once Cranelift supports it
309 fx.bcx.ins().brz(cond, failure, &[]);
311 fx.bcx.ins().brnz(cond, failure, &[]);
313 fx.bcx.ins().jump(target, &[]);
315 fx.bcx.switch_to_block(failure);
319 AssertKind::BoundsCheck { ref len, ref index } => {
320 let len = codegen_operand(fx, len).load_scalar(fx);
321 let index = codegen_operand(fx, index).load_scalar(fx);
322 let location = fx.get_caller_location(source_info.span).load_scalar(fx);
326 rustc_hir::LangItem::PanicBoundsCheck,
327 &[index, len, location],
332 let msg_str = msg.description();
333 codegen_panic(fx, msg_str, source_info.span);
338 TerminatorKind::SwitchInt { discr, switch_ty, targets } => {
339 let discr = codegen_operand(fx, discr).load_scalar(fx);
341 let use_bool_opt = switch_ty.kind() == fx.tcx.types.bool.kind()
342 || (targets.iter().count() == 1 && targets.iter().next().unwrap().0 == 0);
344 assert_eq!(targets.iter().count(), 1);
345 let (then_value, then_block) = targets.iter().next().unwrap();
346 let then_block = fx.get_block(then_block);
347 let else_block = fx.get_block(targets.otherwise());
348 let test_zero = match then_value {
351 _ => unreachable!("{:?}", targets),
354 let discr = crate::optimize::peephole::maybe_unwrap_bint(&mut fx.bcx, discr);
355 let (discr, is_inverted) =
356 crate::optimize::peephole::maybe_unwrap_bool_not(&mut fx.bcx, discr);
357 let test_zero = if is_inverted { !test_zero } else { test_zero };
358 let discr = crate::optimize::peephole::maybe_unwrap_bint(&mut fx.bcx, discr);
359 if let Some(taken) = crate::optimize::peephole::maybe_known_branch_taken(
360 &fx.bcx, discr, test_zero,
363 fx.bcx.ins().jump(then_block, &[]);
365 fx.bcx.ins().jump(else_block, &[]);
369 fx.bcx.ins().brz(discr, then_block, &[]);
370 fx.bcx.ins().jump(else_block, &[]);
372 fx.bcx.ins().brnz(discr, then_block, &[]);
373 fx.bcx.ins().jump(else_block, &[]);
377 let mut switch = ::cranelift_frontend::Switch::new();
378 for (value, block) in targets.iter() {
379 let block = fx.get_block(block);
380 switch.set_entry(value, block);
382 let otherwise_block = fx.get_block(targets.otherwise());
383 switch.emit(&mut fx.bcx, discr, otherwise_block);
386 TerminatorKind::Call {
394 fx.tcx.sess.time("codegen call", || {
395 crate::abi::codegen_terminator_call(fx, *fn_span, func, args, *destination)
398 TerminatorKind::InlineAsm {
406 if options.contains(InlineAsmOptions::MAY_UNWIND) {
407 fx.tcx.sess.span_fatal(
409 "cranelift doesn't support unwinding from inline assembly.",
413 crate::inline_asm::codegen_inline_asm(
422 Some(destination) => {
423 let destination_block = fx.get_block(destination);
424 fx.bcx.ins().jump(destination_block, &[]);
427 crate::trap::trap_unreachable(
429 "[corruption] Returned from noreturn inline asm",
434 TerminatorKind::Resume | TerminatorKind::Abort => {
435 trap_unreachable(fx, "[corruption] Unwinding bb reached.");
437 TerminatorKind::Unreachable => {
438 trap_unreachable(fx, "[corruption] Hit unreachable code.");
440 TerminatorKind::Yield { .. }
441 | TerminatorKind::FalseEdge { .. }
442 | TerminatorKind::FalseUnwind { .. }
443 | TerminatorKind::DropAndReplace { .. }
444 | TerminatorKind::GeneratorDrop => {
445 bug!("shouldn't exist at codegen {:?}", bb_data.terminator());
447 TerminatorKind::Drop { place, target, unwind: _ } => {
448 let drop_place = codegen_place(fx, *place);
449 crate::abi::codegen_drop(fx, source_info.span, drop_place);
451 let target_block = fx.get_block(*target);
452 fx.bcx.ins().jump(target_block, &[]);
457 fx.bcx.seal_all_blocks();
461 fn codegen_stmt<'tcx>(
462 fx: &mut FunctionCx<'_, '_, 'tcx>,
463 #[allow(unused_variables)] cur_block: Block,
464 stmt: &Statement<'tcx>,
466 let _print_guard = crate::PrintOnPanic(|| format!("stmt {:?}", stmt));
468 fx.set_debug_loc(stmt.source_info);
472 StatementKind::StorageLive(..) | StatementKind::StorageDead(..) => {} // Those are not very useful
474 if fx.clif_comments.enabled() {
475 let inst = fx.bcx.func.layout.last_inst(cur_block).unwrap();
476 fx.add_comment(inst, format!("{:?}", stmt));
482 StatementKind::SetDiscriminant { place, variant_index } => {
483 let place = codegen_place(fx, **place);
484 crate::discriminant::codegen_set_discriminant(fx, place, *variant_index);
486 StatementKind::Assign(to_place_and_rval) => {
487 let lval = codegen_place(fx, to_place_and_rval.0);
488 let dest_layout = lval.layout();
489 match to_place_and_rval.1 {
490 Rvalue::Use(ref operand) => {
491 let val = codegen_operand(fx, operand);
492 lval.write_cvalue(fx, val);
494 Rvalue::Ref(_, _, place) | Rvalue::AddressOf(_, place) => {
495 let place = codegen_place(fx, place);
496 let ref_ = place.place_ref(fx, lval.layout());
497 lval.write_cvalue(fx, ref_);
499 Rvalue::ThreadLocalRef(def_id) => {
500 let val = crate::constant::codegen_tls_ref(fx, def_id, lval.layout());
501 lval.write_cvalue(fx, val);
503 Rvalue::BinaryOp(bin_op, ref lhs_rhs) => {
504 let lhs = codegen_operand(fx, &lhs_rhs.0);
505 let rhs = codegen_operand(fx, &lhs_rhs.1);
507 let res = crate::num::codegen_binop(fx, bin_op, lhs, rhs);
508 lval.write_cvalue(fx, res);
510 Rvalue::CheckedBinaryOp(bin_op, ref lhs_rhs) => {
511 let lhs = codegen_operand(fx, &lhs_rhs.0);
512 let rhs = codegen_operand(fx, &lhs_rhs.1);
514 let res = if !fx.tcx.sess.overflow_checks() {
516 crate::num::codegen_int_binop(fx, bin_op, lhs, rhs).load_scalar(fx);
517 let is_overflow = fx.bcx.ins().iconst(types::I8, 0);
518 CValue::by_val_pair(val, is_overflow, lval.layout())
520 crate::num::codegen_checked_int_binop(fx, bin_op, lhs, rhs)
523 lval.write_cvalue(fx, res);
525 Rvalue::UnaryOp(un_op, ref operand) => {
526 let operand = codegen_operand(fx, operand);
527 let layout = operand.layout();
528 let val = operand.load_scalar(fx);
529 let res = match un_op {
530 UnOp::Not => match layout.ty.kind() {
532 let res = fx.bcx.ins().icmp_imm(IntCC::Equal, val, 0);
533 CValue::by_val(fx.bcx.ins().bint(types::I8, res), layout)
535 ty::Uint(_) | ty::Int(_) => {
536 CValue::by_val(fx.bcx.ins().bnot(val), layout)
538 _ => unreachable!("un op Not for {:?}", layout.ty),
540 UnOp::Neg => match layout.ty.kind() {
541 ty::Int(IntTy::I128) => {
542 // FIXME remove this case once ineg.i128 works
544 CValue::const_val(fx, layout, ty::ScalarInt::null(layout.size));
545 crate::num::codegen_int_binop(fx, BinOp::Sub, zero, operand)
547 ty::Int(_) => CValue::by_val(fx.bcx.ins().ineg(val), layout),
548 ty::Float(_) => CValue::by_val(fx.bcx.ins().fneg(val), layout),
549 _ => unreachable!("un op Neg for {:?}", layout.ty),
552 lval.write_cvalue(fx, res);
555 CastKind::Pointer(PointerCast::ReifyFnPointer),
559 let from_ty = fx.monomorphize(operand.ty(&fx.mir.local_decls, fx.tcx));
560 let to_layout = fx.layout_of(fx.monomorphize(to_ty));
561 match *from_ty.kind() {
562 ty::FnDef(def_id, substs) => {
563 let func_ref = fx.get_function_ref(
564 Instance::resolve_for_fn_ptr(
566 ParamEnv::reveal_all(),
571 .polymorphize(fx.tcx),
573 let func_addr = fx.bcx.ins().func_addr(fx.pointer_type, func_ref);
574 lval.write_cvalue(fx, CValue::by_val(func_addr, to_layout));
576 _ => bug!("Trying to ReifyFnPointer on non FnDef {:?}", from_ty),
580 CastKind::Pointer(PointerCast::UnsafeFnPointer),
585 CastKind::Pointer(PointerCast::MutToConstPointer),
590 CastKind::Pointer(PointerCast::ArrayToPointer),
594 let to_layout = fx.layout_of(fx.monomorphize(to_ty));
595 let operand = codegen_operand(fx, operand);
596 lval.write_cvalue(fx, operand.cast_pointer_to(to_layout));
598 Rvalue::Cast(CastKind::Misc, ref operand, to_ty) => {
599 let operand = codegen_operand(fx, operand);
600 let from_ty = operand.layout().ty;
601 let to_ty = fx.monomorphize(to_ty);
603 fn is_fat_ptr<'tcx>(fx: &FunctionCx<'_, '_, 'tcx>, ty: Ty<'tcx>) -> bool {
604 ty.builtin_deref(true)
605 .map(|ty::TypeAndMut { ty: pointee_ty, mutbl: _ }| {
606 has_ptr_meta(fx.tcx, pointee_ty)
611 if is_fat_ptr(fx, from_ty) {
612 if is_fat_ptr(fx, to_ty) {
613 // fat-ptr -> fat-ptr
614 lval.write_cvalue(fx, operand.cast_pointer_to(dest_layout));
616 // fat-ptr -> thin-ptr
617 let (ptr, _extra) = operand.load_scalar_pair(fx);
618 lval.write_cvalue(fx, CValue::by_val(ptr, dest_layout))
620 } else if let ty::Adt(adt_def, _substs) = from_ty.kind() {
621 // enum -> discriminant value
622 assert!(adt_def.is_enum());
624 ty::Uint(_) | ty::Int(_) => {}
625 _ => unreachable!("cast adt {} -> {}", from_ty, to_ty),
627 let to_clif_ty = fx.clif_type(to_ty).unwrap();
629 let discriminant = crate::discriminant::codegen_get_discriminant(
632 fx.layout_of(operand.layout().ty.discriminant_ty(fx.tcx)),
636 let res = crate::cast::clif_intcast(
642 lval.write_cvalue(fx, CValue::by_val(res, dest_layout));
644 let to_clif_ty = fx.clif_type(to_ty).unwrap();
645 let from = operand.load_scalar(fx);
647 let res = clif_int_or_float_cast(
654 lval.write_cvalue(fx, CValue::by_val(res, dest_layout));
658 CastKind::Pointer(PointerCast::ClosureFnPointer(_)),
662 let operand = codegen_operand(fx, operand);
663 match *operand.layout().ty.kind() {
664 ty::Closure(def_id, substs) => {
665 let instance = Instance::resolve_closure(
669 ty::ClosureKind::FnOnce,
671 .polymorphize(fx.tcx);
672 let func_ref = fx.get_function_ref(instance);
673 let func_addr = fx.bcx.ins().func_addr(fx.pointer_type, func_ref);
674 lval.write_cvalue(fx, CValue::by_val(func_addr, lval.layout()));
676 _ => bug!("{} cannot be cast to a fn ptr", operand.layout().ty),
679 Rvalue::Cast(CastKind::Pointer(PointerCast::Unsize), ref operand, _to_ty) => {
680 let operand = codegen_operand(fx, operand);
681 operand.unsize_value(fx, lval);
683 Rvalue::Discriminant(place) => {
684 let place = codegen_place(fx, place);
685 let value = place.to_cvalue(fx);
687 crate::discriminant::codegen_get_discriminant(fx, value, dest_layout);
688 lval.write_cvalue(fx, discr);
690 Rvalue::Repeat(ref operand, times) => {
691 let operand = codegen_operand(fx, operand);
694 .eval(fx.tcx, ParamEnv::reveal_all())
696 .try_to_bits(fx.tcx.data_layout.pointer_size)
698 if operand.layout().size.bytes() == 0 {
699 // Do nothing for ZST's
700 } else if fx.clif_type(operand.layout().ty) == Some(types::I8) {
701 let times = fx.bcx.ins().iconst(fx.pointer_type, times as i64);
702 // FIXME use emit_small_memset where possible
703 let addr = lval.to_ptr().get_addr(fx);
704 let val = operand.load_scalar(fx);
705 fx.bcx.call_memset(fx.target_config, addr, val, times);
707 let loop_block = fx.bcx.create_block();
708 let loop_block2 = fx.bcx.create_block();
709 let done_block = fx.bcx.create_block();
710 let index = fx.bcx.append_block_param(loop_block, fx.pointer_type);
711 let zero = fx.bcx.ins().iconst(fx.pointer_type, 0);
712 fx.bcx.ins().jump(loop_block, &[zero]);
714 fx.bcx.switch_to_block(loop_block);
715 let done = fx.bcx.ins().icmp_imm(IntCC::Equal, index, times as i64);
716 fx.bcx.ins().brnz(done, done_block, &[]);
717 fx.bcx.ins().jump(loop_block2, &[]);
719 fx.bcx.switch_to_block(loop_block2);
720 let to = lval.place_index(fx, index);
721 to.write_cvalue(fx, operand);
722 let index = fx.bcx.ins().iadd_imm(index, 1);
723 fx.bcx.ins().jump(loop_block, &[index]);
725 fx.bcx.switch_to_block(done_block);
729 Rvalue::Len(place) => {
730 let place = codegen_place(fx, place);
731 let usize_layout = fx.layout_of(fx.tcx.types.usize);
732 let len = codegen_array_len(fx, place);
733 lval.write_cvalue(fx, CValue::by_val(len, usize_layout));
735 Rvalue::ShallowInitBox(ref operand, content_ty) => {
736 let content_ty = fx.monomorphize(content_ty);
737 let box_layout = fx.layout_of(fx.tcx.mk_box(content_ty));
738 let operand = codegen_operand(fx, operand);
739 let operand = operand.load_scalar(fx);
740 lval.write_cvalue(fx, CValue::by_val(operand, box_layout));
742 Rvalue::NullaryOp(null_op, ty) => {
746 .is_sized(fx.tcx.at(stmt.source_info.span), ParamEnv::reveal_all())
748 let layout = fx.layout_of(fx.monomorphize(ty));
749 let val = match null_op {
750 NullOp::SizeOf => layout.size.bytes(),
751 NullOp::AlignOf => layout.align.abi.bytes(),
753 let val = CValue::const_val(fx, fx.layout_of(fx.tcx.types.usize), val.into());
754 lval.write_cvalue(fx, val);
756 Rvalue::Aggregate(ref kind, ref operands) => match kind.as_ref() {
757 AggregateKind::Array(_ty) => {
758 for (i, operand) in operands.iter().enumerate() {
759 let operand = codegen_operand(fx, operand);
760 let index = fx.bcx.ins().iconst(fx.pointer_type, i as i64);
761 let to = lval.place_index(fx, index);
762 to.write_cvalue(fx, operand);
765 _ => unreachable!("shouldn't exist at codegen {:?}", to_place_and_rval.1),
769 StatementKind::StorageLive(_)
770 | StatementKind::StorageDead(_)
772 | StatementKind::FakeRead(..)
773 | StatementKind::Retag { .. }
774 | StatementKind::AscribeUserType(..) => {}
776 StatementKind::Coverage { .. } => fx.tcx.sess.fatal("-Zcoverage is unimplemented"),
777 StatementKind::CopyNonOverlapping(inner) => {
778 let dst = codegen_operand(fx, &inner.dst);
781 .pointee_info_at(fx, rustc_target::abi::Size::ZERO)
782 .expect("Expected pointer");
783 let dst = dst.load_scalar(fx);
784 let src = codegen_operand(fx, &inner.src).load_scalar(fx);
785 let count = codegen_operand(fx, &inner.count).load_scalar(fx);
786 let elem_size: u64 = pointee.size.bytes();
788 if elem_size != 1 { fx.bcx.ins().imul_imm(count, elem_size as i64) } else { count };
789 fx.bcx.call_memcpy(fx.target_config, dst, src, bytes);
794 fn codegen_array_len<'tcx>(fx: &mut FunctionCx<'_, '_, 'tcx>, place: CPlace<'tcx>) -> Value {
795 match *place.layout().ty.kind() {
796 ty::Array(_elem_ty, len) => {
797 let len = fx.monomorphize(len).eval_usize(fx.tcx, ParamEnv::reveal_all()) as i64;
798 fx.bcx.ins().iconst(fx.pointer_type, len)
800 ty::Slice(_elem_ty) => {
801 place.to_ptr_maybe_unsized().1.expect("Length metadata for slice place")
803 _ => bug!("Rvalue::Len({:?})", place),
807 pub(crate) fn codegen_place<'tcx>(
808 fx: &mut FunctionCx<'_, '_, 'tcx>,
811 let mut cplace = fx.get_local_place(place.local);
813 for elem in place.projection {
815 PlaceElem::Deref => {
816 cplace = cplace.place_deref(fx);
818 PlaceElem::Field(field, _ty) => {
819 cplace = cplace.place_field(fx, field);
821 PlaceElem::Index(local) => {
822 let index = fx.get_local_place(local).to_cvalue(fx).load_scalar(fx);
823 cplace = cplace.place_index(fx, index);
825 PlaceElem::ConstantIndex { offset, min_length: _, from_end } => {
826 let offset: u64 = offset;
827 let index = if !from_end {
828 fx.bcx.ins().iconst(fx.pointer_type, offset as i64)
830 let len = codegen_array_len(fx, cplace);
831 fx.bcx.ins().iadd_imm(len, -(offset as i64))
833 cplace = cplace.place_index(fx, index);
835 PlaceElem::Subslice { from, to, from_end } => {
836 // These indices are generated by slice patterns.
837 // slice[from:-to] in Python terms.
839 let from: u64 = from;
842 match cplace.layout().ty.kind() {
843 ty::Array(elem_ty, _len) => {
844 assert!(!from_end, "array subslices are never `from_end`");
845 let elem_layout = fx.layout_of(*elem_ty);
846 let ptr = cplace.to_ptr();
847 cplace = CPlace::for_ptr(
848 ptr.offset_i64(fx, elem_layout.size.bytes() as i64 * (from as i64)),
849 fx.layout_of(fx.tcx.mk_array(*elem_ty, to - from)),
852 ty::Slice(elem_ty) => {
853 assert!(from_end, "slice subslices should be `from_end`");
854 let elem_layout = fx.layout_of(*elem_ty);
855 let (ptr, len) = cplace.to_ptr_maybe_unsized();
856 let len = len.unwrap();
857 cplace = CPlace::for_ptr_with_extra(
858 ptr.offset_i64(fx, elem_layout.size.bytes() as i64 * (from as i64)),
859 fx.bcx.ins().iadd_imm(len, -(from as i64 + to as i64)),
866 PlaceElem::Downcast(_adt_def, variant) => {
867 cplace = cplace.downcast_variant(fx, variant);
875 pub(crate) fn codegen_operand<'tcx>(
876 fx: &mut FunctionCx<'_, '_, 'tcx>,
877 operand: &Operand<'tcx>,
880 Operand::Move(place) | Operand::Copy(place) => {
881 let cplace = codegen_place(fx, *place);
884 Operand::Constant(const_) => crate::constant::codegen_constant(fx, const_),
888 pub(crate) fn codegen_panic<'tcx>(fx: &mut FunctionCx<'_, '_, 'tcx>, msg_str: &str, span: Span) {
889 let location = fx.get_caller_location(span).load_scalar(fx);
891 let msg_ptr = fx.anonymous_str(msg_str);
892 let msg_len = fx.bcx.ins().iconst(fx.pointer_type, i64::try_from(msg_str.len()).unwrap());
893 let args = [msg_ptr, msg_len, location];
895 codegen_panic_inner(fx, rustc_hir::LangItem::Panic, &args, span);
898 pub(crate) fn codegen_panic_inner<'tcx>(
899 fx: &mut FunctionCx<'_, '_, 'tcx>,
900 lang_item: rustc_hir::LangItem,
905 fx.tcx.lang_items().require(lang_item).unwrap_or_else(|s| fx.tcx.sess.span_fatal(span, &s));
907 let instance = Instance::mono(fx.tcx, def_id).polymorphize(fx.tcx);
908 let symbol_name = fx.tcx.symbol_name(instance).name;
913 AbiParam::new(fx.pointer_type),
914 AbiParam::new(fx.pointer_type),
915 AbiParam::new(fx.pointer_type),
921 crate::trap::trap_unreachable(fx, "panic lang item returned");