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 cranelift_codegen::ir::UserFuncName;
11 use crate::constant::ConstantCx;
12 use crate::debuginfo::FunctionDebugContext;
13 use crate::prelude::*;
14 use crate::pretty_clif::CommentWriter;
16 pub(crate) struct CodegenedFunction {
20 clif_comments: CommentWriter,
21 func_debug_cx: Option<FunctionDebugContext>,
24 #[cfg_attr(not(feature = "jit"), allow(dead_code))]
25 pub(crate) fn codegen_and_compile_fn<'tcx>(
27 cx: &mut crate::CodegenCx,
28 cached_context: &mut Context,
29 module: &mut dyn Module,
30 instance: Instance<'tcx>,
33 crate::PrintOnPanic(|| format!("{:?} {}", instance, tcx.symbol_name(instance).name));
35 let cached_func = std::mem::replace(&mut cached_context.func, Function::new());
36 let codegened_func = codegen_fn(tcx, cx, cached_func, module, instance);
38 compile_fn(cx, cached_context, module, codegened_func);
41 pub(crate) fn codegen_fn<'tcx>(
43 cx: &mut crate::CodegenCx,
44 cached_func: Function,
45 module: &mut dyn Module,
46 instance: Instance<'tcx>,
47 ) -> CodegenedFunction {
48 debug_assert!(!instance.substs.needs_infer());
50 let mir = tcx.instance_mir(instance.def);
51 let _mir_guard = crate::PrintOnPanic(|| {
52 let mut buf = Vec::new();
53 with_no_trimmed_paths!({
54 rustc_middle::mir::pretty::write_mir_fn(tcx, mir, &mut |_, _| Ok(()), &mut buf)
57 String::from_utf8_lossy(&buf).into_owned()
61 let symbol_name = tcx.symbol_name(instance).name.to_string();
62 let sig = get_function_sig(tcx, module.isa().triple(), instance);
63 let func_id = module.declare_function(&symbol_name, Linkage::Local, &sig).unwrap();
65 // Make the FunctionBuilder
66 let mut func_ctx = FunctionBuilderContext::new();
67 let mut func = cached_func;
69 func.name = UserFuncName::user(0, func_id.as_u32());
71 func.collect_debug_info();
73 let mut bcx = FunctionBuilder::new(&mut func, &mut func_ctx);
76 let start_block = bcx.create_block();
77 let block_map: IndexVec<BasicBlock, Block> =
78 (0..mir.basic_blocks.len()).map(|_| bcx.create_block()).collect();
81 let target_config = module.target_config();
82 let pointer_type = target_config.pointer_type();
83 let clif_comments = crate::pretty_clif::CommentWriter::new(tcx, instance);
85 let func_debug_cx = if let Some(debug_context) = &mut cx.debug_context {
86 Some(debug_context.define_function(tcx, &symbol_name, mir.span))
91 let mut fx = FunctionCx {
97 constants_cx: ConstantCx::new(),
103 fn_abi: Some(RevealAllLayoutCx(tcx).fn_abi_of_instance(instance, ty::List::empty())),
107 local_map: IndexVec::with_capacity(mir.local_decls.len()),
108 caller_location: None, // set by `codegen_fn_prelude`
111 last_source_file: None,
115 tcx.sess.time("codegen clif ir", || codegen_fn_body(&mut fx, start_block));
117 // Recover all necessary data from fx, before accessing func will prevent future access to it.
118 let symbol_name = fx.symbol_name;
119 let clif_comments = fx.clif_comments;
120 let func_debug_cx = fx.func_debug_cx;
122 fx.constants_cx.finalize(fx.tcx, &mut *fx.module);
124 if cx.should_write_ir {
125 crate::pretty_clif::write_clif_file(
126 tcx.output_filenames(()),
136 verify_func(tcx, &clif_comments, &func);
138 CodegenedFunction { symbol_name, func_id, func, clif_comments, func_debug_cx }
141 pub(crate) fn compile_fn(
142 cx: &mut crate::CodegenCx,
143 cached_context: &mut Context,
144 module: &mut dyn Module,
145 codegened_func: CodegenedFunction,
147 let clif_comments = codegened_func.clif_comments;
149 // Store function in context
150 let context = cached_context;
152 context.func = codegened_func.func;
154 // If the return block is not reachable, then the SSA builder may have inserted an `iconst.i128`
155 // instruction, which doesn't have an encoding.
156 context.compute_cfg();
157 context.compute_domtree();
158 context.eliminate_unreachable_code(module.isa()).unwrap();
159 context.dce(module.isa()).unwrap();
160 // Some Cranelift optimizations expect the domtree to not yet be computed and as such don't
161 // invalidate it when it would change.
162 context.domtree.clear();
164 #[cfg(any())] // This is never true
168 let func_clone = context.func.clone();
169 let clif_comments_clone = clif_comments.clone();
170 let mut clif = String::new();
171 for flag in module.isa().flags().iter() {
172 writeln!(clif, "set {}", flag).unwrap();
174 write!(clif, "target {}", module.isa().triple().architecture.to_string()).unwrap();
175 for isa_flag in module.isa().isa_flags().iter() {
176 write!(clif, " {}", isa_flag).unwrap();
178 writeln!(clif, "\n").unwrap();
179 crate::PrintOnPanic(move || {
180 let mut clif = clif.clone();
181 ::cranelift_codegen::write::decorate_function(
182 &mut &clif_comments_clone,
192 cx.profiler.verbose_generic_activity("define function").run(|| {
193 context.want_disasm = cx.should_write_ir;
194 module.define_function(codegened_func.func_id, context).unwrap();
197 if cx.should_write_ir {
198 // Write optimized function to file for debugging
199 crate::pretty_clif::write_clif_file(
200 &cx.output_filenames,
201 &codegened_func.symbol_name,
208 if let Some(disasm) = &context.compiled_code().unwrap().disasm {
209 crate::pretty_clif::write_ir_file(
210 &cx.output_filenames,
211 &format!("{}.vcode", codegened_func.symbol_name),
212 |file| file.write_all(disasm.as_bytes()),
217 // Define debuginfo for function
218 let isa = module.isa();
219 let debug_context = &mut cx.debug_context;
220 let unwind_context = &mut cx.unwind_context;
221 cx.profiler.verbose_generic_activity("generate debug info").run(|| {
222 if let Some(debug_context) = debug_context {
223 codegened_func.func_debug_cx.unwrap().finalize(
225 codegened_func.func_id,
229 unwind_context.add_function(codegened_func.func_id, &context, isa);
233 pub(crate) fn verify_func(
235 writer: &crate::pretty_clif::CommentWriter,
238 tcx.sess.time("verify clif ir", || {
239 let flags = cranelift_codegen::settings::Flags::new(cranelift_codegen::settings::builder());
240 match cranelift_codegen::verify_function(&func, &flags) {
243 tcx.sess.err(&format!("{:?}", err));
244 let pretty_error = cranelift_codegen::print_errors::pretty_verifier_error(
246 Some(Box::new(writer)),
249 tcx.sess.fatal(&format!("cranelift verify error:\n{}", pretty_error));
255 fn codegen_fn_body(fx: &mut FunctionCx<'_, '_, '_>, start_block: Block) {
256 if !crate::constant::check_constants(fx) {
257 fx.bcx.append_block_params_for_function_params(fx.block_map[START_BLOCK]);
258 fx.bcx.switch_to_block(fx.block_map[START_BLOCK]);
259 // compilation should have been aborted
260 fx.bcx.ins().trap(TrapCode::UnreachableCodeReached);
264 let arg_uninhabited = fx
267 .any(|arg| fx.layout_of(fx.monomorphize(fx.mir.local_decls[arg].ty)).abi.is_uninhabited());
269 fx.bcx.append_block_params_for_function_params(fx.block_map[START_BLOCK]);
270 fx.bcx.switch_to_block(fx.block_map[START_BLOCK]);
271 fx.bcx.ins().trap(TrapCode::UnreachableCodeReached);
274 fx.tcx.sess.time("codegen prelude", || crate::abi::codegen_fn_prelude(fx, start_block));
276 for (bb, bb_data) in fx.mir.basic_blocks.iter_enumerated() {
277 let block = fx.get_block(bb);
278 fx.bcx.switch_to_block(block);
280 if bb_data.is_cleanup {
281 // Unwinding after panicking is not supported
284 // FIXME Once unwinding is supported and Cranelift supports marking blocks as cold, do
285 // so for cleanup blocks.
289 for stmt in &bb_data.statements {
290 fx.set_debug_loc(stmt.source_info);
291 codegen_stmt(fx, block, stmt);
294 if fx.clif_comments.enabled() {
295 let mut terminator_head = "\n".to_string();
296 with_no_trimmed_paths!({
297 bb_data.terminator().kind.fmt_head(&mut terminator_head).unwrap();
299 let inst = fx.bcx.func.layout.last_inst(block).unwrap();
300 fx.add_comment(inst, terminator_head);
303 let source_info = bb_data.terminator().source_info;
304 fx.set_debug_loc(source_info);
306 match &bb_data.terminator().kind {
307 TerminatorKind::Goto { target } => {
308 if let TerminatorKind::Return = fx.mir[*target].terminator().kind {
309 let mut can_immediately_return = true;
310 for stmt in &fx.mir[*target].statements {
311 if let StatementKind::StorageDead(_) = stmt.kind {
313 // FIXME Can sometimes happen, see rust-lang/rust#70531
314 can_immediately_return = false;
319 if can_immediately_return {
320 crate::abi::codegen_return(fx);
325 let block = fx.get_block(*target);
326 fx.bcx.ins().jump(block, &[]);
328 TerminatorKind::Return => {
329 crate::abi::codegen_return(fx);
331 TerminatorKind::Assert { cond, expected, msg, target, cleanup: _ } => {
332 if !fx.tcx.sess.overflow_checks() {
333 if let mir::AssertKind::OverflowNeg(_) = *msg {
334 let target = fx.get_block(*target);
335 fx.bcx.ins().jump(target, &[]);
339 let cond = codegen_operand(fx, cond).load_scalar(fx);
341 let target = fx.get_block(*target);
342 let failure = fx.bcx.create_block();
343 fx.bcx.set_cold_block(failure);
346 fx.bcx.ins().brz(cond, failure, &[]);
348 fx.bcx.ins().brnz(cond, failure, &[]);
350 fx.bcx.ins().jump(target, &[]);
352 fx.bcx.switch_to_block(failure);
356 AssertKind::BoundsCheck { ref len, ref index } => {
357 let len = codegen_operand(fx, len).load_scalar(fx);
358 let index = codegen_operand(fx, index).load_scalar(fx);
359 let location = fx.get_caller_location(source_info).load_scalar(fx);
363 rustc_hir::LangItem::PanicBoundsCheck,
364 &[index, len, location],
369 let msg_str = msg.description();
370 codegen_panic(fx, msg_str, source_info);
375 TerminatorKind::SwitchInt { discr, targets } => {
376 let discr = codegen_operand(fx, discr);
377 let switch_ty = discr.layout().ty;
378 let discr = discr.load_scalar(fx);
380 let use_bool_opt = switch_ty.kind() == fx.tcx.types.bool.kind()
381 || (targets.iter().count() == 1 && targets.iter().next().unwrap().0 == 0);
383 assert_eq!(targets.iter().count(), 1);
384 let (then_value, then_block) = targets.iter().next().unwrap();
385 let then_block = fx.get_block(then_block);
386 let else_block = fx.get_block(targets.otherwise());
387 let test_zero = match then_value {
390 _ => unreachable!("{:?}", targets),
393 let discr = crate::optimize::peephole::maybe_unwrap_bint(&mut fx.bcx, discr);
394 let (discr, is_inverted) =
395 crate::optimize::peephole::maybe_unwrap_bool_not(&mut fx.bcx, discr);
396 let test_zero = if is_inverted { !test_zero } else { test_zero };
397 let discr = crate::optimize::peephole::maybe_unwrap_bint(&mut fx.bcx, discr);
398 if let Some(taken) = crate::optimize::peephole::maybe_known_branch_taken(
399 &fx.bcx, discr, test_zero,
402 fx.bcx.ins().jump(then_block, &[]);
404 fx.bcx.ins().jump(else_block, &[]);
408 fx.bcx.ins().brz(discr, then_block, &[]);
409 fx.bcx.ins().jump(else_block, &[]);
411 fx.bcx.ins().brnz(discr, then_block, &[]);
412 fx.bcx.ins().jump(else_block, &[]);
416 let mut switch = ::cranelift_frontend::Switch::new();
417 for (value, block) in targets.iter() {
418 let block = fx.get_block(block);
419 switch.set_entry(value, block);
421 let otherwise_block = fx.get_block(targets.otherwise());
422 switch.emit(&mut fx.bcx, discr, otherwise_block);
425 TerminatorKind::Call {
434 fx.tcx.sess.time("codegen call", || {
435 crate::abi::codegen_terminator_call(
437 mir::SourceInfo { span: *fn_span, ..source_info },
445 TerminatorKind::InlineAsm {
453 if options.contains(InlineAsmOptions::MAY_UNWIND) {
454 fx.tcx.sess.span_fatal(
456 "cranelift doesn't support unwinding from inline assembly.",
460 crate::inline_asm::codegen_inline_asm(
469 TerminatorKind::Resume | TerminatorKind::Abort => {
470 // FIXME implement unwinding
471 fx.bcx.ins().trap(TrapCode::UnreachableCodeReached);
473 TerminatorKind::Unreachable => {
474 fx.bcx.ins().trap(TrapCode::UnreachableCodeReached);
476 TerminatorKind::Yield { .. }
477 | TerminatorKind::FalseEdge { .. }
478 | TerminatorKind::FalseUnwind { .. }
479 | TerminatorKind::DropAndReplace { .. }
480 | TerminatorKind::GeneratorDrop => {
481 bug!("shouldn't exist at codegen {:?}", bb_data.terminator());
483 TerminatorKind::Drop { place, target, unwind: _ } => {
484 let drop_place = codegen_place(fx, *place);
485 crate::abi::codegen_drop(fx, source_info, drop_place);
487 let target_block = fx.get_block(*target);
488 fx.bcx.ins().jump(target_block, &[]);
493 fx.bcx.seal_all_blocks();
497 fn codegen_stmt<'tcx>(
498 fx: &mut FunctionCx<'_, '_, 'tcx>,
499 #[allow(unused_variables)] cur_block: Block,
500 stmt: &Statement<'tcx>,
502 let _print_guard = crate::PrintOnPanic(|| format!("stmt {:?}", stmt));
504 fx.set_debug_loc(stmt.source_info);
506 #[cfg(any())] // This is never true
508 StatementKind::StorageLive(..) | StatementKind::StorageDead(..) => {} // Those are not very useful
510 if fx.clif_comments.enabled() {
511 let inst = fx.bcx.func.layout.last_inst(cur_block).unwrap();
512 fx.add_comment(inst, format!("{:?}", stmt));
518 StatementKind::SetDiscriminant { place, variant_index } => {
519 let place = codegen_place(fx, **place);
520 crate::discriminant::codegen_set_discriminant(fx, place, *variant_index);
522 StatementKind::Assign(to_place_and_rval) => {
523 let lval = codegen_place(fx, to_place_and_rval.0);
524 let dest_layout = lval.layout();
525 match to_place_and_rval.1 {
526 Rvalue::Use(ref operand) => {
527 let val = codegen_operand(fx, operand);
528 lval.write_cvalue(fx, val);
530 Rvalue::CopyForDeref(place) => {
531 let cplace = codegen_place(fx, place);
532 let val = cplace.to_cvalue(fx);
533 lval.write_cvalue(fx, val)
535 Rvalue::Ref(_, _, place) | Rvalue::AddressOf(_, place) => {
536 let place = codegen_place(fx, place);
537 let ref_ = place.place_ref(fx, lval.layout());
538 lval.write_cvalue(fx, ref_);
540 Rvalue::ThreadLocalRef(def_id) => {
541 let val = crate::constant::codegen_tls_ref(fx, def_id, lval.layout());
542 lval.write_cvalue(fx, val);
544 Rvalue::BinaryOp(bin_op, ref lhs_rhs) => {
545 let lhs = codegen_operand(fx, &lhs_rhs.0);
546 let rhs = codegen_operand(fx, &lhs_rhs.1);
548 let res = crate::num::codegen_binop(fx, bin_op, lhs, rhs);
549 lval.write_cvalue(fx, res);
551 Rvalue::CheckedBinaryOp(bin_op, ref lhs_rhs) => {
552 let lhs = codegen_operand(fx, &lhs_rhs.0);
553 let rhs = codegen_operand(fx, &lhs_rhs.1);
555 let res = if !fx.tcx.sess.overflow_checks() {
557 crate::num::codegen_int_binop(fx, bin_op, lhs, rhs).load_scalar(fx);
558 let is_overflow = fx.bcx.ins().iconst(types::I8, 0);
559 CValue::by_val_pair(val, is_overflow, lval.layout())
561 crate::num::codegen_checked_int_binop(fx, bin_op, lhs, rhs)
564 lval.write_cvalue(fx, res);
566 Rvalue::UnaryOp(un_op, ref operand) => {
567 let operand = codegen_operand(fx, operand);
568 let layout = operand.layout();
569 let val = operand.load_scalar(fx);
570 let res = match un_op {
571 UnOp::Not => match layout.ty.kind() {
573 let res = fx.bcx.ins().icmp_imm(IntCC::Equal, val, 0);
574 CValue::by_val(fx.bcx.ins().bint(types::I8, res), layout)
576 ty::Uint(_) | ty::Int(_) => {
577 CValue::by_val(fx.bcx.ins().bnot(val), layout)
579 _ => unreachable!("un op Not for {:?}", layout.ty),
581 UnOp::Neg => match layout.ty.kind() {
582 ty::Int(IntTy::I128) => {
583 // FIXME remove this case once ineg.i128 works
585 CValue::const_val(fx, layout, ty::ScalarInt::null(layout.size));
586 crate::num::codegen_int_binop(fx, BinOp::Sub, zero, operand)
588 ty::Int(_) => CValue::by_val(fx.bcx.ins().ineg(val), layout),
589 ty::Float(_) => CValue::by_val(fx.bcx.ins().fneg(val), layout),
590 _ => unreachable!("un op Neg for {:?}", layout.ty),
593 lval.write_cvalue(fx, res);
596 CastKind::Pointer(PointerCast::ReifyFnPointer),
600 let from_ty = fx.monomorphize(operand.ty(&fx.mir.local_decls, fx.tcx));
601 let to_layout = fx.layout_of(fx.monomorphize(to_ty));
602 match *from_ty.kind() {
603 ty::FnDef(def_id, substs) => {
604 let func_ref = fx.get_function_ref(
605 Instance::resolve_for_fn_ptr(
607 ParamEnv::reveal_all(),
612 .polymorphize(fx.tcx),
614 let func_addr = fx.bcx.ins().func_addr(fx.pointer_type, func_ref);
615 lval.write_cvalue(fx, CValue::by_val(func_addr, to_layout));
617 _ => bug!("Trying to ReifyFnPointer on non FnDef {:?}", from_ty),
621 CastKind::Pointer(PointerCast::UnsafeFnPointer),
626 CastKind::Pointer(PointerCast::MutToConstPointer),
631 CastKind::Pointer(PointerCast::ArrayToPointer),
635 let to_layout = fx.layout_of(fx.monomorphize(to_ty));
636 let operand = codegen_operand(fx, operand);
637 lval.write_cvalue(fx, operand.cast_pointer_to(to_layout));
641 | CastKind::FloatToFloat
642 | CastKind::FloatToInt
643 | CastKind::IntToFloat
644 | CastKind::FnPtrToPtr
646 | CastKind::PointerExposeAddress
647 | CastKind::PointerFromExposedAddress,
651 let operand = codegen_operand(fx, operand);
652 let from_ty = operand.layout().ty;
653 let to_ty = fx.monomorphize(to_ty);
655 fn is_fat_ptr<'tcx>(fx: &FunctionCx<'_, '_, 'tcx>, ty: Ty<'tcx>) -> bool {
656 ty.builtin_deref(true)
657 .map(|ty::TypeAndMut { ty: pointee_ty, mutbl: _ }| {
658 has_ptr_meta(fx.tcx, pointee_ty)
663 if is_fat_ptr(fx, from_ty) {
664 if is_fat_ptr(fx, to_ty) {
665 // fat-ptr -> fat-ptr
666 lval.write_cvalue(fx, operand.cast_pointer_to(dest_layout));
668 // fat-ptr -> thin-ptr
669 let (ptr, _extra) = operand.load_scalar_pair(fx);
670 lval.write_cvalue(fx, CValue::by_val(ptr, dest_layout))
673 let to_clif_ty = fx.clif_type(to_ty).unwrap();
674 let from = operand.load_scalar(fx);
676 let res = clif_int_or_float_cast(
683 lval.write_cvalue(fx, CValue::by_val(res, dest_layout));
687 CastKind::Pointer(PointerCast::ClosureFnPointer(_)),
691 let operand = codegen_operand(fx, operand);
692 match *operand.layout().ty.kind() {
693 ty::Closure(def_id, substs) => {
694 let instance = Instance::resolve_closure(
698 ty::ClosureKind::FnOnce,
700 .expect("failed to normalize and resolve closure during codegen")
701 .polymorphize(fx.tcx);
702 let func_ref = fx.get_function_ref(instance);
703 let func_addr = fx.bcx.ins().func_addr(fx.pointer_type, func_ref);
704 lval.write_cvalue(fx, CValue::by_val(func_addr, lval.layout()));
706 _ => bug!("{} cannot be cast to a fn ptr", operand.layout().ty),
709 Rvalue::Cast(CastKind::Pointer(PointerCast::Unsize), ref operand, _to_ty) => {
710 let operand = codegen_operand(fx, operand);
711 operand.unsize_value(fx, lval);
713 Rvalue::Cast(CastKind::DynStar, ref operand, _) => {
714 let operand = codegen_operand(fx, operand);
715 operand.coerce_dyn_star(fx, lval);
717 Rvalue::Discriminant(place) => {
718 let place = codegen_place(fx, place);
719 let value = place.to_cvalue(fx);
720 crate::discriminant::codegen_get_discriminant(fx, lval, value, dest_layout);
722 Rvalue::Repeat(ref operand, times) => {
723 let operand = codegen_operand(fx, operand);
726 .eval(fx.tcx, ParamEnv::reveal_all())
728 .try_to_bits(fx.tcx.data_layout.pointer_size)
730 if operand.layout().size.bytes() == 0 {
731 // Do nothing for ZST's
732 } else if fx.clif_type(operand.layout().ty) == Some(types::I8) {
733 let times = fx.bcx.ins().iconst(fx.pointer_type, times as i64);
734 // FIXME use emit_small_memset where possible
735 let addr = lval.to_ptr().get_addr(fx);
736 let val = operand.load_scalar(fx);
737 fx.bcx.call_memset(fx.target_config, addr, val, times);
739 let loop_block = fx.bcx.create_block();
740 let loop_block2 = fx.bcx.create_block();
741 let done_block = fx.bcx.create_block();
742 let index = fx.bcx.append_block_param(loop_block, fx.pointer_type);
743 let zero = fx.bcx.ins().iconst(fx.pointer_type, 0);
744 fx.bcx.ins().jump(loop_block, &[zero]);
746 fx.bcx.switch_to_block(loop_block);
747 let done = fx.bcx.ins().icmp_imm(IntCC::Equal, index, times as i64);
748 fx.bcx.ins().brnz(done, done_block, &[]);
749 fx.bcx.ins().jump(loop_block2, &[]);
751 fx.bcx.switch_to_block(loop_block2);
752 let to = lval.place_index(fx, index);
753 to.write_cvalue(fx, operand);
754 let index = fx.bcx.ins().iadd_imm(index, 1);
755 fx.bcx.ins().jump(loop_block, &[index]);
757 fx.bcx.switch_to_block(done_block);
761 Rvalue::Len(place) => {
762 let place = codegen_place(fx, place);
763 let usize_layout = fx.layout_of(fx.tcx.types.usize);
764 let len = codegen_array_len(fx, place);
765 lval.write_cvalue(fx, CValue::by_val(len, usize_layout));
767 Rvalue::ShallowInitBox(ref operand, content_ty) => {
768 let content_ty = fx.monomorphize(content_ty);
769 let box_layout = fx.layout_of(fx.tcx.mk_box(content_ty));
770 let operand = codegen_operand(fx, operand);
771 let operand = operand.load_scalar(fx);
772 lval.write_cvalue(fx, CValue::by_val(operand, box_layout));
774 Rvalue::NullaryOp(null_op, ty) => {
775 assert!(lval.layout().ty.is_sized(fx.tcx, ParamEnv::reveal_all()));
776 let layout = fx.layout_of(fx.monomorphize(ty));
777 let val = match null_op {
778 NullOp::SizeOf => layout.size.bytes(),
779 NullOp::AlignOf => layout.align.abi.bytes(),
781 let val = CValue::const_val(fx, fx.layout_of(fx.tcx.types.usize), val.into());
782 lval.write_cvalue(fx, val);
784 Rvalue::Aggregate(ref kind, ref operands) => match kind.as_ref() {
785 AggregateKind::Array(_ty) => {
786 for (i, operand) in operands.iter().enumerate() {
787 let operand = codegen_operand(fx, operand);
788 let index = fx.bcx.ins().iconst(fx.pointer_type, i as i64);
789 let to = lval.place_index(fx, index);
790 to.write_cvalue(fx, operand);
793 _ => unreachable!("shouldn't exist at codegen {:?}", to_place_and_rval.1),
797 StatementKind::StorageLive(_)
798 | StatementKind::StorageDead(_)
799 | StatementKind::Deinit(_)
801 | StatementKind::FakeRead(..)
802 | StatementKind::Retag { .. }
803 | StatementKind::AscribeUserType(..) => {}
805 StatementKind::Coverage { .. } => fx.tcx.sess.fatal("-Zcoverage is unimplemented"),
806 StatementKind::Intrinsic(ref intrinsic) => match &**intrinsic {
807 // We ignore `assume` intrinsics, they are only useful for optimizations
808 NonDivergingIntrinsic::Assume(_) => {}
809 NonDivergingIntrinsic::CopyNonOverlapping(mir::CopyNonOverlapping {
814 let dst = codegen_operand(fx, dst);
817 .pointee_info_at(fx, rustc_target::abi::Size::ZERO)
818 .expect("Expected pointer");
819 let dst = dst.load_scalar(fx);
820 let src = codegen_operand(fx, src).load_scalar(fx);
821 let count = codegen_operand(fx, count).load_scalar(fx);
822 let elem_size: u64 = pointee.size.bytes();
823 let bytes = if elem_size != 1 {
824 fx.bcx.ins().imul_imm(count, elem_size as i64)
828 fx.bcx.call_memcpy(fx.target_config, dst, src, bytes);
834 fn codegen_array_len<'tcx>(fx: &mut FunctionCx<'_, '_, 'tcx>, place: CPlace<'tcx>) -> Value {
835 match *place.layout().ty.kind() {
836 ty::Array(_elem_ty, len) => {
837 let len = fx.monomorphize(len).eval_usize(fx.tcx, ParamEnv::reveal_all()) as i64;
838 fx.bcx.ins().iconst(fx.pointer_type, len)
840 ty::Slice(_elem_ty) => {
841 place.to_ptr_maybe_unsized().1.expect("Length metadata for slice place")
843 _ => bug!("Rvalue::Len({:?})", place),
847 pub(crate) fn codegen_place<'tcx>(
848 fx: &mut FunctionCx<'_, '_, 'tcx>,
851 let mut cplace = fx.get_local_place(place.local);
853 for elem in place.projection {
855 PlaceElem::Deref => {
856 cplace = cplace.place_deref(fx);
858 PlaceElem::OpaqueCast(ty) => cplace = cplace.place_opaque_cast(fx, ty),
859 PlaceElem::Field(field, _ty) => {
860 cplace = cplace.place_field(fx, field);
862 PlaceElem::Index(local) => {
863 let index = fx.get_local_place(local).to_cvalue(fx).load_scalar(fx);
864 cplace = cplace.place_index(fx, index);
866 PlaceElem::ConstantIndex { offset, min_length: _, from_end } => {
867 let offset: u64 = offset;
868 let index = if !from_end {
869 fx.bcx.ins().iconst(fx.pointer_type, offset as i64)
871 let len = codegen_array_len(fx, cplace);
872 fx.bcx.ins().iadd_imm(len, -(offset as i64))
874 cplace = cplace.place_index(fx, index);
876 PlaceElem::Subslice { from, to, from_end } => {
877 // These indices are generated by slice patterns.
878 // slice[from:-to] in Python terms.
880 let from: u64 = from;
883 match cplace.layout().ty.kind() {
884 ty::Array(elem_ty, _len) => {
885 assert!(!from_end, "array subslices are never `from_end`");
886 let elem_layout = fx.layout_of(*elem_ty);
887 let ptr = cplace.to_ptr();
888 cplace = CPlace::for_ptr(
889 ptr.offset_i64(fx, elem_layout.size.bytes() as i64 * (from as i64)),
890 fx.layout_of(fx.tcx.mk_array(*elem_ty, to - from)),
893 ty::Slice(elem_ty) => {
894 assert!(from_end, "slice subslices should be `from_end`");
895 let elem_layout = fx.layout_of(*elem_ty);
896 let (ptr, len) = cplace.to_ptr_maybe_unsized();
897 let len = len.unwrap();
898 cplace = CPlace::for_ptr_with_extra(
899 ptr.offset_i64(fx, elem_layout.size.bytes() as i64 * (from as i64)),
900 fx.bcx.ins().iadd_imm(len, -(from as i64 + to as i64)),
907 PlaceElem::Downcast(_adt_def, variant) => {
908 cplace = cplace.downcast_variant(fx, variant);
916 pub(crate) fn codegen_operand<'tcx>(
917 fx: &mut FunctionCx<'_, '_, 'tcx>,
918 operand: &Operand<'tcx>,
921 Operand::Move(place) | Operand::Copy(place) => {
922 let cplace = codegen_place(fx, *place);
925 Operand::Constant(const_) => crate::constant::codegen_constant_operand(fx, const_),
929 pub(crate) fn codegen_panic<'tcx>(
930 fx: &mut FunctionCx<'_, '_, 'tcx>,
932 source_info: mir::SourceInfo,
934 let location = fx.get_caller_location(source_info).load_scalar(fx);
936 let msg_ptr = fx.anonymous_str(msg_str);
937 let msg_len = fx.bcx.ins().iconst(fx.pointer_type, i64::try_from(msg_str.len()).unwrap());
938 let args = [msg_ptr, msg_len, location];
940 codegen_panic_inner(fx, rustc_hir::LangItem::Panic, &args, source_info.span);
943 pub(crate) fn codegen_panic_inner<'tcx>(
944 fx: &mut FunctionCx<'_, '_, 'tcx>,
945 lang_item: rustc_hir::LangItem,
953 .unwrap_or_else(|e| fx.tcx.sess.span_fatal(span, e.to_string()));
955 let instance = Instance::mono(fx.tcx, def_id).polymorphize(fx.tcx);
956 let symbol_name = fx.tcx.symbol_name(instance).name;
961 AbiParam::new(fx.pointer_type),
962 AbiParam::new(fx.pointer_type),
963 AbiParam::new(fx.pointer_type),
969 fx.bcx.ins().trap(TrapCode::UnreachableCodeReached);