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;
7 use rustc_middle::ty::print::with_no_trimmed_paths;
9 use indexmap::IndexSet;
11 use crate::constant::ConstantCx;
12 use crate::prelude::*;
13 use crate::pretty_clif::CommentWriter;
15 pub(crate) fn codegen_fn<'tcx>(
16 cx: &mut crate::CodegenCx<'tcx>,
17 module: &mut dyn Module,
18 instance: Instance<'tcx>,
23 crate::PrintOnPanic(|| format!("{:?} {}", instance, tcx.symbol_name(instance).name));
24 debug_assert!(!instance.substs.needs_infer());
26 let mir = tcx.instance_mir(instance.def);
27 let _mir_guard = crate::PrintOnPanic(|| {
28 let mut buf = Vec::new();
29 with_no_trimmed_paths!({
30 rustc_middle::mir::pretty::write_mir_fn(tcx, mir, &mut |_, _| Ok(()), &mut buf)
33 String::from_utf8_lossy(&buf).into_owned()
37 let symbol_name = tcx.symbol_name(instance);
38 let sig = get_function_sig(tcx, module.isa().triple(), instance);
39 let func_id = module.declare_function(symbol_name.name, Linkage::Local, &sig).unwrap();
41 cx.cached_context.clear();
43 // Make the FunctionBuilder
44 let mut func_ctx = FunctionBuilderContext::new();
45 let mut func = std::mem::replace(&mut cx.cached_context.func, Function::new());
46 func.name = ExternalName::user(0, func_id.as_u32());
48 func.collect_debug_info();
50 let mut bcx = FunctionBuilder::new(&mut func, &mut func_ctx);
53 let start_block = bcx.create_block();
54 let block_map: IndexVec<BasicBlock, Block> =
55 (0..mir.basic_blocks().len()).map(|_| bcx.create_block()).collect();
58 let target_config = module.target_config();
59 let pointer_type = target_config.pointer_type();
60 let clif_comments = crate::pretty_clif::CommentWriter::new(tcx, instance);
62 let mut fx = FunctionCx {
68 constants_cx: ConstantCx::new(),
73 fn_abi: Some(RevealAllLayoutCx(tcx).fn_abi_of_instance(instance, ty::List::empty())),
77 local_map: IndexVec::with_capacity(mir.local_decls.len()),
78 caller_location: None, // set by `codegen_fn_prelude`
81 source_info_set: indexmap::IndexSet::new(),
85 let arg_uninhabited = fx
88 .any(|arg| fx.layout_of(fx.monomorphize(fx.mir.local_decls[arg].ty)).abi.is_uninhabited());
90 if !crate::constant::check_constants(&mut fx) {
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, "compilation should have been aborted");
94 } else if arg_uninhabited {
95 fx.bcx.append_block_params_for_function_params(fx.block_map[START_BLOCK]);
96 fx.bcx.switch_to_block(fx.block_map[START_BLOCK]);
97 fx.bcx.ins().trap(TrapCode::UnreachableCodeReached);
99 tcx.sess.time("codegen clif ir", || {
101 .time("codegen prelude", || crate::abi::codegen_fn_prelude(&mut fx, start_block));
102 codegen_fn_content(&mut fx);
106 // Recover all necessary data from fx, before accessing func will prevent future access to it.
107 let instance = fx.instance;
108 let clif_comments = fx.clif_comments;
109 let source_info_set = fx.source_info_set;
110 let local_map = fx.local_map;
112 fx.constants_cx.finalize(fx.tcx, &mut *fx.module);
114 crate::pretty_clif::write_clif_file(
124 verify_func(tcx, &clif_comments, &func);
140 cx: &mut crate::CodegenCx<'tcx>,
141 module: &mut dyn Module,
142 instance: Instance<'tcx>,
146 mut clif_comments: CommentWriter,
147 source_info_set: IndexSet<SourceInfo>,
148 local_map: IndexVec<mir::Local, CPlace<'tcx>>,
152 // Store function in context
153 let context = &mut cx.cached_context;
157 // If the return block is not reachable, then the SSA builder may have inserted an `iconst.i128`
158 // instruction, which doesn't have an encoding.
159 context.compute_cfg();
160 context.compute_domtree();
161 context.eliminate_unreachable_code(module.isa()).unwrap();
162 context.dce(module.isa()).unwrap();
163 // Some Cranelift optimizations expect the domtree to not yet be computed and as such don't
164 // invalidate it when it would change.
165 context.domtree.clear();
167 // Perform rust specific optimizations
168 tcx.sess.time("optimize clif ir", || {
169 crate::optimize::optimize_function(
178 #[cfg(any())] // This is never true
182 let func_clone = context.func.clone();
183 let clif_comments_clone = clif_comments.clone();
184 let mut clif = String::new();
185 for flag in module.isa().flags().iter() {
186 writeln!(clif, "set {}", flag).unwrap();
188 write!(clif, "target {}", module.isa().triple().architecture.to_string()).unwrap();
189 for isa_flag in module.isa().isa_flags().iter() {
190 write!(clif, " {}", isa_flag).unwrap();
192 writeln!(clif, "\n").unwrap();
193 crate::PrintOnPanic(move || {
194 let mut clif = clif.clone();
195 ::cranelift_codegen::write::decorate_function(
196 &mut &clif_comments_clone,
206 tcx.sess.time("define function", || {
207 context.want_disasm = crate::pretty_clif::should_write_ir(tcx);
208 module.define_function(func_id, context).unwrap();
211 // Write optimized function to file for debugging
212 crate::pretty_clif::write_clif_file(
221 if let Some(disasm) = &context.mach_compile_result.as_ref().unwrap().disasm {
222 crate::pretty_clif::write_ir_file(
224 || format!("{}.vcode", tcx.symbol_name(instance).name),
225 |file| file.write_all(disasm.as_bytes()),
229 // Define debuginfo for function
230 let isa = module.isa();
231 let debug_context = &mut cx.debug_context;
232 let unwind_context = &mut cx.unwind_context;
233 tcx.sess.time("generate debug info", || {
234 if let Some(debug_context) = debug_context {
235 debug_context.define_function(
245 unwind_context.add_function(func_id, &context, isa);
249 pub(crate) fn verify_func(
251 writer: &crate::pretty_clif::CommentWriter,
254 tcx.sess.time("verify clif ir", || {
255 let flags = cranelift_codegen::settings::Flags::new(cranelift_codegen::settings::builder());
256 match cranelift_codegen::verify_function(&func, &flags) {
259 tcx.sess.err(&format!("{:?}", err));
260 let pretty_error = cranelift_codegen::print_errors::pretty_verifier_error(
262 Some(Box::new(writer)),
265 tcx.sess.fatal(&format!("cranelift verify error:\n{}", pretty_error));
271 fn codegen_fn_content(fx: &mut FunctionCx<'_, '_, '_>) {
272 for (bb, bb_data) in fx.mir.basic_blocks().iter_enumerated() {
273 let block = fx.get_block(bb);
274 fx.bcx.switch_to_block(block);
276 if bb_data.is_cleanup {
277 // Unwinding after panicking is not supported
280 // FIXME Once unwinding is supported and Cranelift supports marking blocks as cold, do
281 // so for cleanup blocks.
285 for stmt in &bb_data.statements {
286 fx.set_debug_loc(stmt.source_info);
287 codegen_stmt(fx, block, stmt);
290 if fx.clif_comments.enabled() {
291 let mut terminator_head = "\n".to_string();
292 with_no_trimmed_paths!({
293 bb_data.terminator().kind.fmt_head(&mut terminator_head).unwrap();
295 let inst = fx.bcx.func.layout.last_inst(block).unwrap();
296 fx.add_comment(inst, terminator_head);
299 let source_info = bb_data.terminator().source_info;
300 fx.set_debug_loc(source_info);
302 match &bb_data.terminator().kind {
303 TerminatorKind::Goto { target } => {
304 if let TerminatorKind::Return = fx.mir[*target].terminator().kind {
305 let mut can_immediately_return = true;
306 for stmt in &fx.mir[*target].statements {
307 if let StatementKind::StorageDead(_) = stmt.kind {
309 // FIXME Can sometimes happen, see rust-lang/rust#70531
310 can_immediately_return = false;
315 if can_immediately_return {
316 crate::abi::codegen_return(fx);
321 let block = fx.get_block(*target);
322 fx.bcx.ins().jump(block, &[]);
324 TerminatorKind::Return => {
325 crate::abi::codegen_return(fx);
327 TerminatorKind::Assert { cond, expected, msg, target, cleanup: _ } => {
328 if !fx.tcx.sess.overflow_checks() {
329 if let mir::AssertKind::OverflowNeg(_) = *msg {
330 let target = fx.get_block(*target);
331 fx.bcx.ins().jump(target, &[]);
335 let cond = codegen_operand(fx, cond).load_scalar(fx);
337 let target = fx.get_block(*target);
338 let failure = fx.bcx.create_block();
339 fx.bcx.set_cold_block(failure);
342 fx.bcx.ins().brz(cond, failure, &[]);
344 fx.bcx.ins().brnz(cond, failure, &[]);
346 fx.bcx.ins().jump(target, &[]);
348 fx.bcx.switch_to_block(failure);
352 AssertKind::BoundsCheck { ref len, ref index } => {
353 let len = codegen_operand(fx, len).load_scalar(fx);
354 let index = codegen_operand(fx, index).load_scalar(fx);
355 let location = fx.get_caller_location(source_info).load_scalar(fx);
359 rustc_hir::LangItem::PanicBoundsCheck,
360 &[index, len, location],
365 let msg_str = msg.description();
366 codegen_panic(fx, msg_str, source_info);
371 TerminatorKind::SwitchInt { discr, switch_ty, targets } => {
372 let discr = codegen_operand(fx, discr).load_scalar(fx);
374 let use_bool_opt = switch_ty.kind() == fx.tcx.types.bool.kind()
375 || (targets.iter().count() == 1 && targets.iter().next().unwrap().0 == 0);
377 assert_eq!(targets.iter().count(), 1);
378 let (then_value, then_block) = targets.iter().next().unwrap();
379 let then_block = fx.get_block(then_block);
380 let else_block = fx.get_block(targets.otherwise());
381 let test_zero = match then_value {
384 _ => unreachable!("{:?}", targets),
387 let discr = crate::optimize::peephole::maybe_unwrap_bint(&mut fx.bcx, discr);
388 let (discr, is_inverted) =
389 crate::optimize::peephole::maybe_unwrap_bool_not(&mut fx.bcx, discr);
390 let test_zero = if is_inverted { !test_zero } else { test_zero };
391 let discr = crate::optimize::peephole::maybe_unwrap_bint(&mut fx.bcx, discr);
392 if let Some(taken) = crate::optimize::peephole::maybe_known_branch_taken(
393 &fx.bcx, discr, test_zero,
396 fx.bcx.ins().jump(then_block, &[]);
398 fx.bcx.ins().jump(else_block, &[]);
402 fx.bcx.ins().brz(discr, then_block, &[]);
403 fx.bcx.ins().jump(else_block, &[]);
405 fx.bcx.ins().brnz(discr, then_block, &[]);
406 fx.bcx.ins().jump(else_block, &[]);
410 let mut switch = ::cranelift_frontend::Switch::new();
411 for (value, block) in targets.iter() {
412 let block = fx.get_block(block);
413 switch.set_entry(value, block);
415 let otherwise_block = fx.get_block(targets.otherwise());
416 switch.emit(&mut fx.bcx, discr, otherwise_block);
419 TerminatorKind::Call {
428 fx.tcx.sess.time("codegen call", || {
429 crate::abi::codegen_terminator_call(
431 mir::SourceInfo { span: *fn_span, ..source_info },
439 TerminatorKind::InlineAsm {
447 if options.contains(InlineAsmOptions::MAY_UNWIND) {
448 fx.tcx.sess.span_fatal(
450 "cranelift doesn't support unwinding from inline assembly.",
454 crate::inline_asm::codegen_inline_asm(
463 Some(destination) => {
464 let destination_block = fx.get_block(destination);
465 fx.bcx.ins().jump(destination_block, &[]);
468 fx.bcx.ins().trap(TrapCode::UnreachableCodeReached);
472 TerminatorKind::Resume | TerminatorKind::Abort => {
473 // FIXME implement unwinding
474 fx.bcx.ins().trap(TrapCode::UnreachableCodeReached);
476 TerminatorKind::Unreachable => {
477 fx.bcx.ins().trap(TrapCode::UnreachableCodeReached);
479 TerminatorKind::Yield { .. }
480 | TerminatorKind::FalseEdge { .. }
481 | TerminatorKind::FalseUnwind { .. }
482 | TerminatorKind::DropAndReplace { .. }
483 | TerminatorKind::GeneratorDrop => {
484 bug!("shouldn't exist at codegen {:?}", bb_data.terminator());
486 TerminatorKind::Drop { place, target, unwind: _ } => {
487 let drop_place = codegen_place(fx, *place);
488 crate::abi::codegen_drop(fx, source_info, drop_place);
490 let target_block = fx.get_block(*target);
491 fx.bcx.ins().jump(target_block, &[]);
496 fx.bcx.seal_all_blocks();
500 fn codegen_stmt<'tcx>(
501 fx: &mut FunctionCx<'_, '_, 'tcx>,
502 #[allow(unused_variables)] cur_block: Block,
503 stmt: &Statement<'tcx>,
505 let _print_guard = crate::PrintOnPanic(|| format!("stmt {:?}", stmt));
507 fx.set_debug_loc(stmt.source_info);
509 #[cfg(any())] // This is never true
511 StatementKind::StorageLive(..) | StatementKind::StorageDead(..) => {} // Those are not very useful
513 if fx.clif_comments.enabled() {
514 let inst = fx.bcx.func.layout.last_inst(cur_block).unwrap();
515 fx.add_comment(inst, format!("{:?}", stmt));
521 StatementKind::SetDiscriminant { place, variant_index } => {
522 let place = codegen_place(fx, **place);
523 crate::discriminant::codegen_set_discriminant(fx, place, *variant_index);
525 StatementKind::Assign(to_place_and_rval) => {
526 let lval = codegen_place(fx, to_place_and_rval.0);
527 let dest_layout = lval.layout();
528 match to_place_and_rval.1 {
529 Rvalue::Use(ref operand) => {
530 let val = codegen_operand(fx, operand);
531 lval.write_cvalue(fx, val);
533 Rvalue::Ref(_, _, place) | Rvalue::AddressOf(_, place) => {
534 let place = codegen_place(fx, place);
535 let ref_ = place.place_ref(fx, lval.layout());
536 lval.write_cvalue(fx, ref_);
538 Rvalue::ThreadLocalRef(def_id) => {
539 let val = crate::constant::codegen_tls_ref(fx, def_id, lval.layout());
540 lval.write_cvalue(fx, val);
542 Rvalue::BinaryOp(bin_op, ref lhs_rhs) => {
543 let lhs = codegen_operand(fx, &lhs_rhs.0);
544 let rhs = codegen_operand(fx, &lhs_rhs.1);
546 let res = crate::num::codegen_binop(fx, bin_op, lhs, rhs);
547 lval.write_cvalue(fx, res);
549 Rvalue::CheckedBinaryOp(bin_op, ref lhs_rhs) => {
550 let lhs = codegen_operand(fx, &lhs_rhs.0);
551 let rhs = codegen_operand(fx, &lhs_rhs.1);
553 let res = if !fx.tcx.sess.overflow_checks() {
555 crate::num::codegen_int_binop(fx, bin_op, lhs, rhs).load_scalar(fx);
556 let is_overflow = fx.bcx.ins().iconst(types::I8, 0);
557 CValue::by_val_pair(val, is_overflow, lval.layout())
559 crate::num::codegen_checked_int_binop(fx, bin_op, lhs, rhs)
562 lval.write_cvalue(fx, res);
564 Rvalue::UnaryOp(un_op, ref operand) => {
565 let operand = codegen_operand(fx, operand);
566 let layout = operand.layout();
567 let val = operand.load_scalar(fx);
568 let res = match un_op {
569 UnOp::Not => match layout.ty.kind() {
571 let res = fx.bcx.ins().icmp_imm(IntCC::Equal, val, 0);
572 CValue::by_val(fx.bcx.ins().bint(types::I8, res), layout)
574 ty::Uint(_) | ty::Int(_) => {
575 CValue::by_val(fx.bcx.ins().bnot(val), layout)
577 _ => unreachable!("un op Not for {:?}", layout.ty),
579 UnOp::Neg => match layout.ty.kind() {
580 ty::Int(IntTy::I128) => {
581 // FIXME remove this case once ineg.i128 works
583 CValue::const_val(fx, layout, ty::ScalarInt::null(layout.size));
584 crate::num::codegen_int_binop(fx, BinOp::Sub, zero, operand)
586 ty::Int(_) => CValue::by_val(fx.bcx.ins().ineg(val), layout),
587 ty::Float(_) => CValue::by_val(fx.bcx.ins().fneg(val), layout),
588 _ => unreachable!("un op Neg for {:?}", layout.ty),
591 lval.write_cvalue(fx, res);
594 CastKind::Pointer(PointerCast::ReifyFnPointer),
598 let from_ty = fx.monomorphize(operand.ty(&fx.mir.local_decls, fx.tcx));
599 let to_layout = fx.layout_of(fx.monomorphize(to_ty));
600 match *from_ty.kind() {
601 ty::FnDef(def_id, substs) => {
602 let func_ref = fx.get_function_ref(
603 Instance::resolve_for_fn_ptr(
605 ParamEnv::reveal_all(),
610 .polymorphize(fx.tcx),
612 let func_addr = fx.bcx.ins().func_addr(fx.pointer_type, func_ref);
613 lval.write_cvalue(fx, CValue::by_val(func_addr, to_layout));
615 _ => bug!("Trying to ReifyFnPointer on non FnDef {:?}", from_ty),
619 CastKind::Pointer(PointerCast::UnsafeFnPointer),
624 CastKind::Pointer(PointerCast::MutToConstPointer),
629 CastKind::Pointer(PointerCast::ArrayToPointer),
633 let to_layout = fx.layout_of(fx.monomorphize(to_ty));
634 let operand = codegen_operand(fx, operand);
635 lval.write_cvalue(fx, operand.cast_pointer_to(to_layout));
639 | CastKind::PointerExposeAddress
640 | CastKind::PointerFromExposedAddress,
644 let operand = codegen_operand(fx, operand);
645 let from_ty = operand.layout().ty;
646 let to_ty = fx.monomorphize(to_ty);
648 fn is_fat_ptr<'tcx>(fx: &FunctionCx<'_, '_, 'tcx>, ty: Ty<'tcx>) -> bool {
649 ty.builtin_deref(true)
650 .map(|ty::TypeAndMut { ty: pointee_ty, mutbl: _ }| {
651 has_ptr_meta(fx.tcx, pointee_ty)
656 if is_fat_ptr(fx, from_ty) {
657 if is_fat_ptr(fx, to_ty) {
658 // fat-ptr -> fat-ptr
659 lval.write_cvalue(fx, operand.cast_pointer_to(dest_layout));
661 // fat-ptr -> thin-ptr
662 let (ptr, _extra) = operand.load_scalar_pair(fx);
663 lval.write_cvalue(fx, CValue::by_val(ptr, dest_layout))
665 } else if let ty::Adt(adt_def, _substs) = from_ty.kind() {
666 // enum -> discriminant value
667 assert!(adt_def.is_enum());
669 ty::Uint(_) | ty::Int(_) => {}
670 _ => unreachable!("cast adt {} -> {}", from_ty, to_ty),
672 let to_clif_ty = fx.clif_type(to_ty).unwrap();
674 let discriminant = crate::discriminant::codegen_get_discriminant(
677 fx.layout_of(operand.layout().ty.discriminant_ty(fx.tcx)),
681 let res = crate::cast::clif_intcast(
687 lval.write_cvalue(fx, CValue::by_val(res, dest_layout));
689 let to_clif_ty = fx.clif_type(to_ty).unwrap();
690 let from = operand.load_scalar(fx);
692 let res = clif_int_or_float_cast(
699 lval.write_cvalue(fx, CValue::by_val(res, dest_layout));
703 CastKind::Pointer(PointerCast::ClosureFnPointer(_)),
707 let operand = codegen_operand(fx, operand);
708 match *operand.layout().ty.kind() {
709 ty::Closure(def_id, substs) => {
710 let instance = Instance::resolve_closure(
714 ty::ClosureKind::FnOnce,
716 .expect("failed to normalize and resolve closure during codegen")
717 .polymorphize(fx.tcx);
718 let func_ref = fx.get_function_ref(instance);
719 let func_addr = fx.bcx.ins().func_addr(fx.pointer_type, func_ref);
720 lval.write_cvalue(fx, CValue::by_val(func_addr, lval.layout()));
722 _ => bug!("{} cannot be cast to a fn ptr", operand.layout().ty),
725 Rvalue::Cast(CastKind::Pointer(PointerCast::Unsize), ref operand, _to_ty) => {
726 let operand = codegen_operand(fx, operand);
727 operand.unsize_value(fx, lval);
729 Rvalue::Discriminant(place) => {
730 let place = codegen_place(fx, place);
731 let value = place.to_cvalue(fx);
733 crate::discriminant::codegen_get_discriminant(fx, value, dest_layout);
734 lval.write_cvalue(fx, discr);
736 Rvalue::Repeat(ref operand, times) => {
737 let operand = codegen_operand(fx, operand);
740 .eval(fx.tcx, ParamEnv::reveal_all())
742 .try_to_bits(fx.tcx.data_layout.pointer_size)
744 if operand.layout().size.bytes() == 0 {
745 // Do nothing for ZST's
746 } else if fx.clif_type(operand.layout().ty) == Some(types::I8) {
747 let times = fx.bcx.ins().iconst(fx.pointer_type, times as i64);
748 // FIXME use emit_small_memset where possible
749 let addr = lval.to_ptr().get_addr(fx);
750 let val = operand.load_scalar(fx);
751 fx.bcx.call_memset(fx.target_config, addr, val, times);
753 let loop_block = fx.bcx.create_block();
754 let loop_block2 = fx.bcx.create_block();
755 let done_block = fx.bcx.create_block();
756 let index = fx.bcx.append_block_param(loop_block, fx.pointer_type);
757 let zero = fx.bcx.ins().iconst(fx.pointer_type, 0);
758 fx.bcx.ins().jump(loop_block, &[zero]);
760 fx.bcx.switch_to_block(loop_block);
761 let done = fx.bcx.ins().icmp_imm(IntCC::Equal, index, times as i64);
762 fx.bcx.ins().brnz(done, done_block, &[]);
763 fx.bcx.ins().jump(loop_block2, &[]);
765 fx.bcx.switch_to_block(loop_block2);
766 let to = lval.place_index(fx, index);
767 to.write_cvalue(fx, operand);
768 let index = fx.bcx.ins().iadd_imm(index, 1);
769 fx.bcx.ins().jump(loop_block, &[index]);
771 fx.bcx.switch_to_block(done_block);
775 Rvalue::Len(place) => {
776 let place = codegen_place(fx, place);
777 let usize_layout = fx.layout_of(fx.tcx.types.usize);
778 let len = codegen_array_len(fx, place);
779 lval.write_cvalue(fx, CValue::by_val(len, usize_layout));
781 Rvalue::ShallowInitBox(ref operand, content_ty) => {
782 let content_ty = fx.monomorphize(content_ty);
783 let box_layout = fx.layout_of(fx.tcx.mk_box(content_ty));
784 let operand = codegen_operand(fx, operand);
785 let operand = operand.load_scalar(fx);
786 lval.write_cvalue(fx, CValue::by_val(operand, box_layout));
788 Rvalue::NullaryOp(null_op, ty) => {
792 .is_sized(fx.tcx.at(stmt.source_info.span), ParamEnv::reveal_all())
794 let layout = fx.layout_of(fx.monomorphize(ty));
795 let val = match null_op {
796 NullOp::SizeOf => layout.size.bytes(),
797 NullOp::AlignOf => layout.align.abi.bytes(),
799 let val = CValue::const_val(fx, fx.layout_of(fx.tcx.types.usize), val.into());
800 lval.write_cvalue(fx, val);
802 Rvalue::Aggregate(ref kind, ref operands) => match kind.as_ref() {
803 AggregateKind::Array(_ty) => {
804 for (i, operand) in operands.iter().enumerate() {
805 let operand = codegen_operand(fx, operand);
806 let index = fx.bcx.ins().iconst(fx.pointer_type, i as i64);
807 let to = lval.place_index(fx, index);
808 to.write_cvalue(fx, operand);
811 _ => unreachable!("shouldn't exist at codegen {:?}", to_place_and_rval.1),
815 StatementKind::StorageLive(_)
816 | StatementKind::StorageDead(_)
817 | StatementKind::Deinit(_)
819 | StatementKind::FakeRead(..)
820 | StatementKind::Retag { .. }
821 | StatementKind::AscribeUserType(..) => {}
823 StatementKind::Coverage { .. } => fx.tcx.sess.fatal("-Zcoverage is unimplemented"),
824 StatementKind::CopyNonOverlapping(inner) => {
825 let dst = codegen_operand(fx, &inner.dst);
828 .pointee_info_at(fx, rustc_target::abi::Size::ZERO)
829 .expect("Expected pointer");
830 let dst = dst.load_scalar(fx);
831 let src = codegen_operand(fx, &inner.src).load_scalar(fx);
832 let count = codegen_operand(fx, &inner.count).load_scalar(fx);
833 let elem_size: u64 = pointee.size.bytes();
835 if elem_size != 1 { fx.bcx.ins().imul_imm(count, elem_size as i64) } else { count };
836 fx.bcx.call_memcpy(fx.target_config, dst, src, bytes);
841 fn codegen_array_len<'tcx>(fx: &mut FunctionCx<'_, '_, 'tcx>, place: CPlace<'tcx>) -> Value {
842 match *place.layout().ty.kind() {
843 ty::Array(_elem_ty, len) => {
844 let len = fx.monomorphize(len).eval_usize(fx.tcx, ParamEnv::reveal_all()) as i64;
845 fx.bcx.ins().iconst(fx.pointer_type, len)
847 ty::Slice(_elem_ty) => {
848 place.to_ptr_maybe_unsized().1.expect("Length metadata for slice place")
850 _ => bug!("Rvalue::Len({:?})", place),
854 pub(crate) fn codegen_place<'tcx>(
855 fx: &mut FunctionCx<'_, '_, 'tcx>,
858 let mut cplace = fx.get_local_place(place.local);
860 for elem in place.projection {
862 PlaceElem::Deref => {
863 cplace = cplace.place_deref(fx);
865 PlaceElem::Field(field, _ty) => {
866 cplace = cplace.place_field(fx, field);
868 PlaceElem::Index(local) => {
869 let index = fx.get_local_place(local).to_cvalue(fx).load_scalar(fx);
870 cplace = cplace.place_index(fx, index);
872 PlaceElem::ConstantIndex { offset, min_length: _, from_end } => {
873 let offset: u64 = offset;
874 let index = if !from_end {
875 fx.bcx.ins().iconst(fx.pointer_type, offset as i64)
877 let len = codegen_array_len(fx, cplace);
878 fx.bcx.ins().iadd_imm(len, -(offset as i64))
880 cplace = cplace.place_index(fx, index);
882 PlaceElem::Subslice { from, to, from_end } => {
883 // These indices are generated by slice patterns.
884 // slice[from:-to] in Python terms.
886 let from: u64 = from;
889 match cplace.layout().ty.kind() {
890 ty::Array(elem_ty, _len) => {
891 assert!(!from_end, "array subslices are never `from_end`");
892 let elem_layout = fx.layout_of(*elem_ty);
893 let ptr = cplace.to_ptr();
894 cplace = CPlace::for_ptr(
895 ptr.offset_i64(fx, elem_layout.size.bytes() as i64 * (from as i64)),
896 fx.layout_of(fx.tcx.mk_array(*elem_ty, to - from)),
899 ty::Slice(elem_ty) => {
900 assert!(from_end, "slice subslices should be `from_end`");
901 let elem_layout = fx.layout_of(*elem_ty);
902 let (ptr, len) = cplace.to_ptr_maybe_unsized();
903 let len = len.unwrap();
904 cplace = CPlace::for_ptr_with_extra(
905 ptr.offset_i64(fx, elem_layout.size.bytes() as i64 * (from as i64)),
906 fx.bcx.ins().iadd_imm(len, -(from as i64 + to as i64)),
913 PlaceElem::Downcast(_adt_def, variant) => {
914 cplace = cplace.downcast_variant(fx, variant);
922 pub(crate) fn codegen_operand<'tcx>(
923 fx: &mut FunctionCx<'_, '_, 'tcx>,
924 operand: &Operand<'tcx>,
927 Operand::Move(place) | Operand::Copy(place) => {
928 let cplace = codegen_place(fx, *place);
931 Operand::Constant(const_) => crate::constant::codegen_constant(fx, const_),
935 pub(crate) fn codegen_panic<'tcx>(
936 fx: &mut FunctionCx<'_, '_, 'tcx>,
938 source_info: mir::SourceInfo,
940 let location = fx.get_caller_location(source_info).load_scalar(fx);
942 let msg_ptr = fx.anonymous_str(msg_str);
943 let msg_len = fx.bcx.ins().iconst(fx.pointer_type, i64::try_from(msg_str.len()).unwrap());
944 let args = [msg_ptr, msg_len, location];
946 codegen_panic_inner(fx, rustc_hir::LangItem::Panic, &args, source_info.span);
949 pub(crate) fn codegen_panic_inner<'tcx>(
950 fx: &mut FunctionCx<'_, '_, 'tcx>,
951 lang_item: rustc_hir::LangItem,
956 fx.tcx.lang_items().require(lang_item).unwrap_or_else(|s| fx.tcx.sess.span_fatal(span, &s));
958 let instance = Instance::mono(fx.tcx, def_id).polymorphize(fx.tcx);
959 let symbol_name = fx.tcx.symbol_name(instance).name;
964 AbiParam::new(fx.pointer_type),
965 AbiParam::new(fx.pointer_type),
966 AbiParam::new(fx.pointer_type),
972 fx.bcx.ins().trap(TrapCode::UnreachableCodeReached);