1 use rustc_middle::ty::adjustment::PointerCast;
2 use rustc_index::vec::IndexVec;
6 pub(crate) fn trans_fn<'tcx, B: Backend + 'static>(
7 cx: &mut crate::CodegenCx<'tcx, B>,
8 instance: Instance<'tcx>,
13 let mir = tcx.instance_mir(instance.def);
16 let (name, sig) = get_function_name_and_sig(tcx, cx.module.isa().triple(), instance, false);
17 let func_id = cx.module.declare_function(&name, linkage, &sig).unwrap();
19 // Make FunctionBuilder
20 let context = &mut cx.cached_context;
22 context.func.name = ExternalName::user(0, func_id.as_u32());
23 context.func.signature = sig;
24 context.func.collect_debug_info();
25 let mut func_ctx = FunctionBuilderContext::new();
26 let mut bcx = FunctionBuilder::new(&mut context.func, &mut func_ctx);
29 let start_block = bcx.create_block();
30 let block_map: IndexVec<BasicBlock, Block> = (0..mir.basic_blocks().len()).map(|_| bcx.create_block()).collect();
33 let pointer_type = cx.module.target_config().pointer_type();
34 let clif_comments = crate::pretty_clif::CommentWriter::new(tcx, instance);
36 let mut fx = FunctionCx {
38 module: &mut cx.module,
39 global_asm: &mut cx.global_asm,
47 local_map: FxHashMap::with_capacity_and_hasher(mir.local_decls.len(), Default::default()),
48 caller_location: None, // set by `codegen_fn_prelude`
49 cold_blocks: EntitySet::new(),
52 constants_cx: &mut cx.constants_cx,
53 vtables: &mut cx.vtables,
54 source_info_set: indexmap::IndexSet::new(),
60 let arg_uninhabited = fx.mir.args_iter().any(|arg| fx.layout_of(fx.monomorphize(&fx.mir.local_decls[arg].ty)).abi.is_uninhabited());
63 fx.bcx.append_block_params_for_function_params(fx.block_map[START_BLOCK]);
64 fx.bcx.switch_to_block(fx.block_map[START_BLOCK]);
65 crate::trap::trap_unreachable(&mut fx, "function has uninhabited argument");
67 tcx.sess.time("codegen clif ir", || {
68 tcx.sess.time("codegen prelude", || crate::abi::codegen_fn_prelude(&mut fx, start_block));
69 codegen_fn_content(&mut fx);
73 // Recover all necessary data from fx, before accessing func will prevent future access to it.
74 let instance = fx.instance;
75 let mut clif_comments = fx.clif_comments;
76 let source_info_set = fx.source_info_set;
77 let local_map = fx.local_map;
78 let cold_blocks = fx.cold_blocks;
80 crate::pretty_clif::write_clif_file(
90 verify_func(tcx, &clif_comments, &context.func);
92 // Perform rust specific optimizations
93 tcx.sess.time("optimize clif ir", || {
94 crate::optimize::optimize_function(tcx, instance, context, &cold_blocks, &mut clif_comments);
97 // If the return block is not reachable, then the SSA builder may have inserted a `iconst.i128`
98 // instruction, which doesn't have an encoding.
99 context.compute_cfg();
100 context.compute_domtree();
101 context.eliminate_unreachable_code(cx.module.isa()).unwrap();
104 let module = &mut cx.module;
107 || module.define_function(
110 &mut cranelift_codegen::binemit::NullTrapSink {},
114 // Write optimized function to file for debugging
115 crate::pretty_clif::write_clif_file(
118 Some(cx.module.isa()),
124 // Define debuginfo for function
125 let isa = cx.module.isa();
126 let debug_context = &mut cx.debug_context;
127 let unwind_context = &mut cx.unwind_context;
128 tcx.sess.time("generate debug info", || {
129 if let Some(debug_context) = debug_context {
130 debug_context.define_function(instance, func_id, &name, isa, context, &source_info_set, local_map);
132 unwind_context.add_function(func_id, &context, isa);
135 // Clear context to make it usable for the next function
139 pub(crate) fn verify_func(tcx: TyCtxt<'_>, writer: &crate::pretty_clif::CommentWriter, func: &Function) {
140 tcx.sess.time("verify clif ir", || {
141 let flags = cranelift_codegen::settings::Flags::new(cranelift_codegen::settings::builder());
142 match cranelift_codegen::verify_function(&func, &flags) {
145 tcx.sess.err(&format!("{:?}", err));
146 let pretty_error = cranelift_codegen::print_errors::pretty_verifier_error(
149 Some(Box::new(writer)),
153 .fatal(&format!("cranelift verify error:\n{}", pretty_error));
159 fn codegen_fn_content(fx: &mut FunctionCx<'_, '_, impl Backend>) {
160 for (bb, bb_data) in fx.mir.basic_blocks().iter_enumerated() {
161 let block = fx.get_block(bb);
162 fx.bcx.switch_to_block(block);
164 if bb_data.is_cleanup {
165 // Unwinding after panicking is not supported
168 // FIXME once unwinding is supported uncomment next lines
169 // // Unwinding is unlikely to happen, so mark cleanup block's as cold.
170 // fx.cold_blocks.insert(block);
174 for stmt in &bb_data.statements {
175 fx.set_debug_loc(stmt.source_info);
176 trans_stmt(fx, block, stmt);
179 #[cfg(debug_assertions)]
181 let mut terminator_head = "\n".to_string();
185 .fmt_head(&mut terminator_head)
187 let inst = fx.bcx.func.layout.last_inst(block).unwrap();
188 fx.add_comment(inst, terminator_head);
191 fx.set_debug_loc(bb_data.terminator().source_info);
193 match &bb_data.terminator().kind {
194 TerminatorKind::Goto { target } => {
195 if let TerminatorKind::Return = fx.mir[*target].terminator().kind {
196 let mut can_immediately_return = true;
197 for stmt in &fx.mir[*target].statements {
198 if let StatementKind::StorageDead(_) = stmt.kind {
200 // FIXME Can sometimes happen, see rust-lang/rust#70531
201 can_immediately_return = false;
206 if can_immediately_return {
207 crate::abi::codegen_return(fx);
212 let block = fx.get_block(*target);
213 fx.bcx.ins().jump(block, &[]);
215 TerminatorKind::Return => {
216 crate::abi::codegen_return(fx);
218 TerminatorKind::Assert {
225 if !fx.tcx.sess.overflow_checks() {
226 if let mir::AssertKind::OverflowNeg(_) = *msg {
227 let target = fx.get_block(*target);
228 fx.bcx.ins().jump(target, &[]);
232 let cond = trans_operand(fx, cond).load_scalar(fx);
234 let target = fx.get_block(*target);
235 let failure = fx.bcx.create_block();
236 fx.cold_blocks.insert(failure);
239 fx.bcx.ins().brz(cond, failure, &[]);
241 fx.bcx.ins().brnz(cond, failure, &[]);
243 fx.bcx.ins().jump(target, &[]);
245 fx.bcx.switch_to_block(failure);
247 let location = fx.get_caller_location(bb_data.terminator().source_info.span).load_scalar(fx);
250 let lang_item = match msg {
251 AssertKind::BoundsCheck { ref len, ref index } => {
252 let len = trans_operand(fx, len).load_scalar(fx);
253 let index = trans_operand(fx, index).load_scalar(fx);
254 args = [index, len, location];
255 rustc_hir::lang_items::PanicBoundsCheckFnLangItem
258 let msg_str = msg.description();
259 let msg_ptr = fx.anonymous_str("assert", msg_str);
260 let msg_len = fx.bcx.ins().iconst(fx.pointer_type, i64::try_from(msg_str.len()).unwrap());
261 args = [msg_ptr, msg_len, location];
262 rustc_hir::lang_items::PanicFnLangItem
266 let def_id = fx.tcx.lang_items().require(lang_item).unwrap_or_else(|s| {
267 fx.tcx.sess.span_fatal(bb_data.terminator().source_info.span, &s)
270 let instance = Instance::mono(fx.tcx, def_id).polymorphize(fx.tcx);
271 let symbol_name = fx.tcx.symbol_name(instance).name;
273 fx.lib_call(&*symbol_name, vec![fx.pointer_type, fx.pointer_type, fx.pointer_type], vec![], &args);
275 crate::trap::trap_unreachable(fx, "panic lang item returned");
278 TerminatorKind::SwitchInt {
284 let discr = trans_operand(fx, discr).load_scalar(fx);
285 let mut switch = ::cranelift_frontend::Switch::new();
286 for (i, value) in values.iter().enumerate() {
287 let block = fx.get_block(targets[i]);
288 switch.set_entry(*value, block);
290 let otherwise_block = fx.get_block(targets[targets.len() - 1]);
291 switch.emit(&mut fx.bcx, discr, otherwise_block);
293 TerminatorKind::Call {
301 fx.tcx.sess.time("codegen call", || crate::abi::codegen_terminator_call(
310 TerminatorKind::InlineAsm {
317 crate::inline_asm::codegen_inline_asm(
319 bb_data.terminator().source_info.span,
326 Some(destination) => {
327 let destination_block = fx.get_block(destination);
328 fx.bcx.ins().jump(destination_block, &[]);
331 crate::trap::trap_unreachable(fx, "[corruption] Returned from noreturn inline asm");
335 TerminatorKind::Resume | TerminatorKind::Abort => {
336 trap_unreachable(fx, "[corruption] Unwinding bb reached.");
338 TerminatorKind::Unreachable => {
339 trap_unreachable(fx, "[corruption] Hit unreachable code.");
341 TerminatorKind::Yield { .. }
342 | TerminatorKind::FalseEdge { .. }
343 | TerminatorKind::FalseUnwind { .. }
344 | TerminatorKind::DropAndReplace { .. }
345 | TerminatorKind::GeneratorDrop => {
346 bug!("shouldn't exist at trans {:?}", bb_data.terminator());
348 TerminatorKind::Drop {
353 let drop_place = trans_place(fx, *place);
354 crate::abi::codegen_drop(fx, bb_data.terminator().source_info.span, drop_place);
356 let target_block = fx.get_block(*target);
357 fx.bcx.ins().jump(target_block, &[]);
362 fx.bcx.seal_all_blocks();
367 fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
368 #[allow(unused_variables)]
370 stmt: &Statement<'tcx>,
372 let _print_guard = crate::PrintOnPanic(|| format!("stmt {:?}", stmt));
374 fx.set_debug_loc(stmt.source_info);
376 #[cfg(false_debug_assertions)]
378 StatementKind::StorageLive(..) | StatementKind::StorageDead(..) => {} // Those are not very useful
380 let inst = fx.bcx.func.layout.last_inst(cur_block).unwrap();
381 fx.add_comment(inst, format!("{:?}", stmt));
386 StatementKind::SetDiscriminant {
390 let place = trans_place(fx, **place);
391 crate::discriminant::codegen_set_discriminant(fx, place, *variant_index);
393 StatementKind::Assign(to_place_and_rval) => {
394 let lval = trans_place(fx, to_place_and_rval.0);
395 let dest_layout = lval.layout();
396 match &to_place_and_rval.1 {
397 Rvalue::Use(operand) => {
398 let val = trans_operand(fx, operand);
399 lval.write_cvalue(fx, val);
401 Rvalue::Ref(_, _, place) | Rvalue::AddressOf(_, place) => {
402 let place = trans_place(fx, *place);
403 place.write_place_ref(fx, lval);
405 Rvalue::ThreadLocalRef(def_id) => {
406 let val = crate::constant::codegen_tls_ref(fx, *def_id, lval.layout());
407 lval.write_cvalue(fx, val);
409 Rvalue::BinaryOp(bin_op, lhs, rhs) => {
410 let lhs = trans_operand(fx, lhs);
411 let rhs = trans_operand(fx, rhs);
413 let res = crate::num::codegen_binop(fx, *bin_op, lhs, rhs);
414 lval.write_cvalue(fx, res);
416 Rvalue::CheckedBinaryOp(bin_op, lhs, rhs) => {
417 let lhs = trans_operand(fx, lhs);
418 let rhs = trans_operand(fx, rhs);
420 let res = if !fx.tcx.sess.overflow_checks() {
422 crate::num::trans_int_binop(fx, *bin_op, lhs, rhs).load_scalar(fx);
423 let is_overflow = fx.bcx.ins().iconst(types::I8, 0);
424 CValue::by_val_pair(val, is_overflow, lval.layout())
426 crate::num::trans_checked_int_binop(fx, *bin_op, lhs, rhs)
429 lval.write_cvalue(fx, res);
431 Rvalue::UnaryOp(un_op, operand) => {
432 let operand = trans_operand(fx, operand);
433 let layout = operand.layout();
434 let val = operand.load_scalar(fx);
435 let res = match un_op {
437 match layout.ty.kind {
439 let res = fx.bcx.ins().icmp_imm(IntCC::Equal, val, 0);
440 CValue::by_val(fx.bcx.ins().bint(types::I8, res), layout)
442 ty::Uint(_) | ty::Int(_) => {
443 CValue::by_val(fx.bcx.ins().bnot(val), layout)
445 _ => unreachable!("un op Not for {:?}", layout.ty),
448 UnOp::Neg => match layout.ty.kind {
449 ty::Int(IntTy::I128) => {
450 // FIXME remove this case once ineg.i128 works
451 let zero = CValue::const_val(fx, layout, 0);
452 crate::num::trans_int_binop(fx, BinOp::Sub, zero, operand)
455 CValue::by_val(fx.bcx.ins().ineg(val), layout)
458 CValue::by_val(fx.bcx.ins().fneg(val), layout)
460 _ => unreachable!("un op Neg for {:?}", layout.ty),
463 lval.write_cvalue(fx, res);
465 Rvalue::Cast(CastKind::Pointer(PointerCast::ReifyFnPointer), operand, to_ty) => {
466 let from_ty = fx.monomorphize(&operand.ty(&fx.mir.local_decls, fx.tcx));
467 let to_layout = fx.layout_of(fx.monomorphize(to_ty));
469 ty::FnDef(def_id, substs) => {
470 let func_ref = fx.get_function_ref(
471 Instance::resolve_for_fn_ptr(fx.tcx, ParamEnv::reveal_all(), def_id, substs)
473 .polymorphize(fx.tcx),
475 let func_addr = fx.bcx.ins().func_addr(fx.pointer_type, func_ref);
476 lval.write_cvalue(fx, CValue::by_val(func_addr, to_layout));
478 _ => bug!("Trying to ReifyFnPointer on non FnDef {:?}", from_ty),
481 Rvalue::Cast(CastKind::Pointer(PointerCast::UnsafeFnPointer), operand, to_ty)
482 | Rvalue::Cast(CastKind::Pointer(PointerCast::MutToConstPointer), operand, to_ty)
483 | Rvalue::Cast(CastKind::Pointer(PointerCast::ArrayToPointer), operand, to_ty) => {
484 let to_layout = fx.layout_of(fx.monomorphize(to_ty));
485 let operand = trans_operand(fx, operand);
486 lval.write_cvalue(fx, operand.cast_pointer_to(to_layout));
488 Rvalue::Cast(CastKind::Misc, operand, to_ty) => {
489 let operand = trans_operand(fx, operand);
490 let from_ty = operand.layout().ty;
491 let to_ty = fx.monomorphize(to_ty);
494 fx: &FunctionCx<'_, 'tcx, impl Backend>,
497 ty.builtin_deref(true)
502 }| has_ptr_meta(fx.tcx, pointee_ty),
507 if is_fat_ptr(fx, from_ty) {
508 if is_fat_ptr(fx, to_ty) {
509 // fat-ptr -> fat-ptr
510 lval.write_cvalue(fx, operand.cast_pointer_to(dest_layout));
512 // fat-ptr -> thin-ptr
513 let (ptr, _extra) = operand.load_scalar_pair(fx);
514 lval.write_cvalue(fx, CValue::by_val(ptr, dest_layout))
516 } else if let ty::Adt(adt_def, _substs) = from_ty.kind {
517 // enum -> discriminant value
518 assert!(adt_def.is_enum());
520 ty::Uint(_) | ty::Int(_) => {}
521 _ => unreachable!("cast adt {} -> {}", from_ty, to_ty),
524 use rustc_target::abi::{TagEncoding, Int, Variants};
526 match &operand.layout().variants {
527 Variants::Single { index } => {
528 let discr = operand.layout().ty.discriminant_for_variant(fx.tcx, *index).unwrap();
529 let discr = if discr.ty.is_signed() {
530 rustc_middle::mir::interpret::sign_extend(discr.val, fx.layout_of(discr.ty).size)
535 let discr = CValue::const_val(fx, fx.layout_of(to_ty), discr);
536 lval.write_cvalue(fx, discr);
541 tag_encoding: TagEncoding::Direct,
544 let cast_to = fx.clif_type(dest_layout.ty).unwrap();
546 // Read the tag/niche-encoded discriminant from memory.
547 let encoded_discr = operand.value_field(fx, mir::Field::new(*tag_field));
548 let encoded_discr = encoded_discr.load_scalar(fx);
550 // Decode the discriminant (specifically if it's niche-encoded).
551 let signed = match tag.value {
552 Int(_, signed) => signed,
555 let val = clif_intcast(fx, encoded_discr, cast_to, signed);
556 let val = CValue::by_val(val, dest_layout);
557 lval.write_cvalue(fx, val);
559 Variants::Multiple { ..} => unreachable!(),
562 let to_clif_ty = fx.clif_type(to_ty).unwrap();
563 let from = operand.load_scalar(fx);
565 let res = clif_int_or_float_cast(
572 lval.write_cvalue(fx, CValue::by_val(res, dest_layout));
575 Rvalue::Cast(CastKind::Pointer(PointerCast::ClosureFnPointer(_)), operand, _to_ty) => {
576 let operand = trans_operand(fx, operand);
577 match operand.layout().ty.kind {
578 ty::Closure(def_id, substs) => {
579 let instance = Instance::resolve_closure(
583 ty::ClosureKind::FnOnce,
584 ).polymorphize(fx.tcx);
585 let func_ref = fx.get_function_ref(instance);
586 let func_addr = fx.bcx.ins().func_addr(fx.pointer_type, func_ref);
587 lval.write_cvalue(fx, CValue::by_val(func_addr, lval.layout()));
589 _ => bug!("{} cannot be cast to a fn ptr", operand.layout().ty),
592 Rvalue::Cast(CastKind::Pointer(PointerCast::Unsize), operand, _to_ty) => {
593 let operand = trans_operand(fx, operand);
594 operand.unsize_value(fx, lval);
596 Rvalue::Discriminant(place) => {
597 let place = trans_place(fx, *place);
598 let value = place.to_cvalue(fx);
600 crate::discriminant::codegen_get_discriminant(fx, value, dest_layout);
601 lval.write_cvalue(fx, discr);
603 Rvalue::Repeat(operand, times) => {
604 let operand = trans_operand(fx, operand);
607 .eval(fx.tcx, ParamEnv::reveal_all())
609 .try_to_bits(fx.tcx.data_layout.pointer_size)
612 let index = fx.bcx.ins().iconst(fx.pointer_type, i as i64);
613 let to = lval.place_index(fx, index);
614 to.write_cvalue(fx, operand);
617 Rvalue::Len(place) => {
618 let place = trans_place(fx, *place);
619 let usize_layout = fx.layout_of(fx.tcx.types.usize);
620 let len = codegen_array_len(fx, place);
621 lval.write_cvalue(fx, CValue::by_val(len, usize_layout));
623 Rvalue::NullaryOp(NullOp::Box, content_ty) => {
624 use rustc_hir::lang_items::ExchangeMallocFnLangItem;
626 let usize_type = fx.clif_type(fx.tcx.types.usize).unwrap();
627 let content_ty = fx.monomorphize(content_ty);
628 let layout = fx.layout_of(content_ty);
629 let llsize = fx.bcx.ins().iconst(usize_type, layout.size.bytes() as i64);
633 .iconst(usize_type, layout.align.abi.bytes() as i64);
634 let box_layout = fx.layout_of(fx.tcx.mk_box(content_ty));
637 let def_id = match fx.tcx.lang_items().require(ExchangeMallocFnLangItem) {
642 .fatal(&format!("allocation of `{}` {}", box_layout.ty, s));
645 let instance = ty::Instance::mono(fx.tcx, def_id).polymorphize(fx.tcx);
646 let func_ref = fx.get_function_ref(instance);
647 let call = fx.bcx.ins().call(func_ref, &[llsize, llalign]);
648 let ptr = fx.bcx.inst_results(call)[0];
649 lval.write_cvalue(fx, CValue::by_val(ptr, box_layout));
651 Rvalue::NullaryOp(NullOp::SizeOf, ty) => {
655 .is_sized(fx.tcx.at(stmt.source_info.span), ParamEnv::reveal_all()));
656 let ty_size = fx.layout_of(fx.monomorphize(ty)).size.bytes();
657 let val = CValue::const_val(fx, fx.layout_of(fx.tcx.types.usize), ty_size.into());
658 lval.write_cvalue(fx, val);
660 Rvalue::Aggregate(kind, operands) => match **kind {
661 AggregateKind::Array(_ty) => {
662 for (i, operand) in operands.into_iter().enumerate() {
663 let operand = trans_operand(fx, operand);
664 let index = fx.bcx.ins().iconst(fx.pointer_type, i as i64);
665 let to = lval.place_index(fx, index);
666 to.write_cvalue(fx, operand);
669 _ => unreachable!("shouldn't exist at trans {:?}", to_place_and_rval.1),
673 StatementKind::StorageLive(_)
674 | StatementKind::StorageDead(_)
676 | StatementKind::FakeRead(..)
677 | StatementKind::Retag { .. }
678 | StatementKind::AscribeUserType(..) => {}
680 StatementKind::LlvmInlineAsm(asm) => {
681 use rustc_span::symbol::Symbol;
687 let rustc_hir::LlvmInlineAsmInner {
688 asm: asm_code, // Name
689 outputs: output_names, // Vec<LlvmInlineAsmOutput>
690 inputs: input_names, // Vec<Name>
691 clobbers, // Vec<Name>
697 match asm_code.as_str().trim() {
701 "mov %rbx, %rsi\n cpuid\n xchg %rbx, %rsi" => {
702 assert_eq!(input_names, &[Symbol::intern("{eax}"), Symbol::intern("{ecx}")]);
703 assert_eq!(output_names.len(), 4);
704 for (i, c) in (&["={eax}", "={esi}", "={ecx}", "={edx}"]).iter().enumerate() {
705 assert_eq!(&output_names[i].constraint.as_str(), c);
706 assert!(!output_names[i].is_rw);
707 assert!(!output_names[i].is_indirect);
710 assert_eq!(clobbers, &[]);
713 assert!(!alignstack);
715 assert_eq!(inputs.len(), 2);
716 let leaf = trans_operand(fx, &inputs[0].1).load_scalar(fx); // %eax
717 let subleaf = trans_operand(fx, &inputs[1].1).load_scalar(fx); // %ecx
719 let (eax, ebx, ecx, edx) = crate::intrinsics::codegen_cpuid_call(fx, leaf, subleaf);
721 assert_eq!(outputs.len(), 4);
722 trans_place(fx, outputs[0]).write_cvalue(fx, CValue::by_val(eax, fx.layout_of(fx.tcx.types.u32)));
723 trans_place(fx, outputs[1]).write_cvalue(fx, CValue::by_val(ebx, fx.layout_of(fx.tcx.types.u32)));
724 trans_place(fx, outputs[2]).write_cvalue(fx, CValue::by_val(ecx, fx.layout_of(fx.tcx.types.u32)));
725 trans_place(fx, outputs[3]).write_cvalue(fx, CValue::by_val(edx, fx.layout_of(fx.tcx.types.u32)));
728 assert_eq!(input_names, &[Symbol::intern("{ecx}")]);
730 assert_eq!(output_names.len(), 2);
731 for (i, c) in (&["={eax}", "={edx}"]).iter().enumerate() {
732 assert_eq!(&output_names[i].constraint.as_str(), c);
733 assert!(!output_names[i].is_rw);
734 assert!(!output_names[i].is_indirect);
737 assert_eq!(clobbers, &[]);
740 assert!(!alignstack);
742 crate::trap::trap_unimplemented(fx, "_xgetbv arch intrinsic is not supported");
744 // ___chkstk, ___chkstk_ms and __alloca are only used on Windows
745 _ if fx.tcx.symbol_name(fx.instance).name.starts_with("___chkstk") => {
746 crate::trap::trap_unimplemented(fx, "Stack probes are not supported");
748 _ if fx.tcx.symbol_name(fx.instance).name == "__alloca" => {
749 crate::trap::trap_unimplemented(fx, "Alloca is not supported");
751 // Used in sys::windows::abort_internal
753 crate::trap::trap_unimplemented(fx, "Windows abort");
755 _ => fx.tcx.sess.span_fatal(stmt.source_info.span, "Inline assembly is not supported"),
761 fn codegen_array_len<'tcx>(
762 fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
765 match place.layout().ty.kind {
766 ty::Array(_elem_ty, len) => {
767 let len = fx.monomorphize(&len)
768 .eval(fx.tcx, ParamEnv::reveal_all())
769 .eval_usize(fx.tcx, ParamEnv::reveal_all()) as i64;
770 fx.bcx.ins().iconst(fx.pointer_type, len)
772 ty::Slice(_elem_ty) => place
773 .to_ptr_maybe_unsized()
775 .expect("Length metadata for slice place"),
776 _ => bug!("Rvalue::Len({:?})", place),
780 pub(crate) fn trans_place<'tcx>(
781 fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
784 let mut cplace = fx.get_local_place(place.local);
786 for elem in place.projection {
788 PlaceElem::Deref => {
789 cplace = cplace.place_deref(fx);
791 PlaceElem::Field(field, _ty) => {
792 cplace = cplace.place_field(fx, field);
794 PlaceElem::Index(local) => {
795 let index = fx.get_local_place(local).to_cvalue(fx).load_scalar(fx);
796 cplace = cplace.place_index(fx, index);
798 PlaceElem::ConstantIndex {
803 let index = if !from_end {
804 fx.bcx.ins().iconst(fx.pointer_type, i64::from(offset))
806 let len = codegen_array_len(fx, cplace);
807 fx.bcx.ins().iadd_imm(len, -i64::from(offset))
809 cplace = cplace.place_index(fx, index);
811 PlaceElem::Subslice { from, to, from_end } => {
812 // These indices are generated by slice patterns.
813 // slice[from:-to] in Python terms.
815 match cplace.layout().ty.kind {
816 ty::Array(elem_ty, _len) => {
817 assert!(!from_end, "array subslices are never `from_end`");
818 let elem_layout = fx.layout_of(elem_ty);
819 let ptr = cplace.to_ptr();
820 cplace = CPlace::for_ptr(
821 ptr.offset_i64(fx, elem_layout.size.bytes() as i64 * i64::from(from)),
822 fx.layout_of(fx.tcx.mk_array(elem_ty, u64::from(to) - u64::from(from))),
825 ty::Slice(elem_ty) => {
826 assert!(from_end, "slice subslices should be `from_end`");
827 let elem_layout = fx.layout_of(elem_ty);
828 let (ptr, len) = cplace.to_ptr_maybe_unsized();
829 let len = len.unwrap();
830 cplace = CPlace::for_ptr_with_extra(
831 ptr.offset_i64(fx, elem_layout.size.bytes() as i64 * i64::from(from)),
832 fx.bcx.ins().iadd_imm(len, -(i64::from(from) + i64::from(to))),
839 PlaceElem::Downcast(_adt_def, variant) => {
840 cplace = cplace.downcast_variant(fx, variant);
848 pub(crate) fn trans_operand<'tcx>(
849 fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
850 operand: &Operand<'tcx>,
853 Operand::Move(place) | Operand::Copy(place) => {
854 let cplace = trans_place(fx, *place);
857 Operand::Constant(const_) => crate::constant::trans_constant(fx, const_),