1 //! Codegen of a single function
3 use cranelift_codegen::binemit::{NullStackMapSink, NullTrapSink};
4 use rustc_index::vec::IndexVec;
5 use rustc_middle::ty::adjustment::PointerCast;
6 use rustc_middle::ty::layout::FnAbiExt;
7 use rustc_target::abi::call::FnAbi;
11 pub(crate) fn codegen_fn<'tcx>(cx: &mut crate::CodegenCx<'_, 'tcx>, instance: Instance<'tcx>) {
15 crate::PrintOnPanic(|| format!("{:?} {}", instance, tcx.symbol_name(instance).name));
16 debug_assert!(!instance.substs.needs_infer());
18 let mir = tcx.instance_mir(instance.def);
21 let name = tcx.symbol_name(instance).name.to_string();
22 let sig = get_function_sig(tcx, cx.module.isa().triple(), instance);
23 let func_id = cx.module.declare_function(&name, Linkage::Local, &sig).unwrap();
25 cx.cached_context.clear();
27 // Make the FunctionBuilder
28 let mut func_ctx = FunctionBuilderContext::new();
29 let mut func = std::mem::replace(&mut cx.cached_context.func, Function::new());
30 func.name = ExternalName::user(0, func_id.as_u32());
32 func.collect_debug_info();
34 let mut bcx = FunctionBuilder::new(&mut func, &mut func_ctx);
37 let start_block = bcx.create_block();
38 let block_map: IndexVec<BasicBlock, Block> =
39 (0..mir.basic_blocks().len()).map(|_| bcx.create_block()).collect();
42 let pointer_type = cx.module.target_config().pointer_type();
43 let clif_comments = crate::pretty_clif::CommentWriter::new(tcx, instance);
45 let mut fx = FunctionCx {
52 fn_abi: Some(FnAbi::of_instance(&RevealAllLayoutCx(tcx), instance, &[])),
56 local_map: IndexVec::with_capacity(mir.local_decls.len()),
57 caller_location: None, // set by `codegen_fn_prelude`
58 cold_blocks: EntitySet::new(),
61 source_info_set: indexmap::IndexSet::new(),
67 let arg_uninhabited = fx
70 .any(|arg| fx.layout_of(fx.monomorphize(&fx.mir.local_decls[arg].ty)).abi.is_uninhabited());
72 if !crate::constant::check_constants(&mut fx) {
73 fx.bcx.append_block_params_for_function_params(fx.block_map[START_BLOCK]);
74 fx.bcx.switch_to_block(fx.block_map[START_BLOCK]);
75 crate::trap::trap_unreachable(&mut fx, "compilation should have been aborted");
76 } else if arg_uninhabited {
77 fx.bcx.append_block_params_for_function_params(fx.block_map[START_BLOCK]);
78 fx.bcx.switch_to_block(fx.block_map[START_BLOCK]);
79 crate::trap::trap_unreachable(&mut fx, "function has uninhabited argument");
81 tcx.sess.time("codegen clif ir", || {
83 .time("codegen prelude", || crate::abi::codegen_fn_prelude(&mut fx, start_block));
84 codegen_fn_content(&mut fx);
88 // Recover all necessary data from fx, before accessing func will prevent future access to it.
89 let instance = fx.instance;
90 let mut clif_comments = fx.clif_comments;
91 let source_info_set = fx.source_info_set;
92 let local_map = fx.local_map;
93 let cold_blocks = fx.cold_blocks;
95 // Store function in context
96 let context = &mut cx.cached_context;
99 crate::pretty_clif::write_clif_file(tcx, "unopt", None, instance, &context, &clif_comments);
102 verify_func(tcx, &clif_comments, &context.func);
104 // Perform rust specific optimizations
105 tcx.sess.time("optimize clif ir", || {
106 crate::optimize::optimize_function(
115 // If the return block is not reachable, then the SSA builder may have inserted an `iconst.i128`
116 // instruction, which doesn't have an encoding.
117 context.compute_cfg();
118 context.compute_domtree();
119 context.eliminate_unreachable_code(cx.module.isa()).unwrap();
120 context.dce(cx.module.isa()).unwrap();
121 // Some Cranelift optimizations expect the domtree to not yet be computed and as such don't
122 // invalidate it when it would change.
123 context.domtree.clear();
125 context.want_disasm = crate::pretty_clif::should_write_ir(tcx);
128 let module = &mut cx.module;
129 tcx.sess.time("define function", || {
131 .define_function(func_id, context, &mut NullTrapSink {}, &mut NullStackMapSink {})
135 // Write optimized function to file for debugging
136 crate::pretty_clif::write_clif_file(
139 Some(cx.module.isa()),
145 if let Some(disasm) = &context.mach_compile_result.as_ref().unwrap().disasm {
146 crate::pretty_clif::write_ir_file(
148 &format!("{}.vcode", tcx.symbol_name(instance).name),
149 |file| file.write_all(disasm.as_bytes()),
153 // Define debuginfo for function
154 let isa = cx.module.isa();
155 let debug_context = &mut cx.debug_context;
156 let unwind_context = &mut cx.unwind_context;
157 tcx.sess.time("generate debug info", || {
158 if let Some(debug_context) = debug_context {
159 debug_context.define_function(
169 unwind_context.add_function(func_id, &context, isa);
172 // Clear context to make it usable for the next function
176 pub(crate) fn verify_func(
178 writer: &crate::pretty_clif::CommentWriter,
181 tcx.sess.time("verify clif ir", || {
182 let flags = cranelift_codegen::settings::Flags::new(cranelift_codegen::settings::builder());
183 match cranelift_codegen::verify_function(&func, &flags) {
186 tcx.sess.err(&format!("{:?}", err));
187 let pretty_error = cranelift_codegen::print_errors::pretty_verifier_error(
190 Some(Box::new(writer)),
193 tcx.sess.fatal(&format!("cranelift verify error:\n{}", pretty_error));
199 fn codegen_fn_content(fx: &mut FunctionCx<'_, '_, '_>) {
200 for (bb, bb_data) in fx.mir.basic_blocks().iter_enumerated() {
201 let block = fx.get_block(bb);
202 fx.bcx.switch_to_block(block);
204 if bb_data.is_cleanup {
205 // Unwinding after panicking is not supported
208 // FIXME once unwinding is supported uncomment next lines
209 // // Unwinding is unlikely to happen, so mark cleanup block's as cold.
210 // fx.cold_blocks.insert(block);
214 for stmt in &bb_data.statements {
215 fx.set_debug_loc(stmt.source_info);
216 codegen_stmt(fx, block, stmt);
219 if fx.clif_comments.enabled() {
220 let mut terminator_head = "\n".to_string();
221 bb_data.terminator().kind.fmt_head(&mut terminator_head).unwrap();
222 let inst = fx.bcx.func.layout.last_inst(block).unwrap();
223 fx.add_comment(inst, terminator_head);
226 fx.set_debug_loc(bb_data.terminator().source_info);
228 match &bb_data.terminator().kind {
229 TerminatorKind::Goto { target } => {
230 if let TerminatorKind::Return = fx.mir[*target].terminator().kind {
231 let mut can_immediately_return = true;
232 for stmt in &fx.mir[*target].statements {
233 if let StatementKind::StorageDead(_) = stmt.kind {
235 // FIXME Can sometimes happen, see rust-lang/rust#70531
236 can_immediately_return = false;
241 if can_immediately_return {
242 crate::abi::codegen_return(fx);
247 let block = fx.get_block(*target);
248 fx.bcx.ins().jump(block, &[]);
250 TerminatorKind::Return => {
251 crate::abi::codegen_return(fx);
253 TerminatorKind::Assert { cond, expected, msg, target, cleanup: _ } => {
254 if !fx.tcx.sess.overflow_checks() {
255 if let mir::AssertKind::OverflowNeg(_) = *msg {
256 let target = fx.get_block(*target);
257 fx.bcx.ins().jump(target, &[]);
261 let cond = codegen_operand(fx, cond).load_scalar(fx);
263 let target = fx.get_block(*target);
264 let failure = fx.bcx.create_block();
265 fx.cold_blocks.insert(failure);
268 fx.bcx.ins().brz(cond, failure, &[]);
270 fx.bcx.ins().brnz(cond, failure, &[]);
272 fx.bcx.ins().jump(target, &[]);
274 fx.bcx.switch_to_block(failure);
278 AssertKind::BoundsCheck { ref len, ref index } => {
279 let len = codegen_operand(fx, len).load_scalar(fx);
280 let index = codegen_operand(fx, index).load_scalar(fx);
282 .get_caller_location(bb_data.terminator().source_info.span)
287 rustc_hir::LangItem::PanicBoundsCheck,
288 &[index, len, location],
289 bb_data.terminator().source_info.span,
293 let msg_str = msg.description();
294 codegen_panic(fx, msg_str, bb_data.terminator().source_info.span);
299 TerminatorKind::SwitchInt { discr, switch_ty, targets } => {
300 let discr = codegen_operand(fx, discr).load_scalar(fx);
302 let use_bool_opt = switch_ty.kind() == fx.tcx.types.bool.kind()
303 || (targets.iter().count() == 1 && targets.iter().next().unwrap().0 == 0);
305 assert_eq!(targets.iter().count(), 1);
306 let (then_value, then_block) = targets.iter().next().unwrap();
307 let then_block = fx.get_block(then_block);
308 let else_block = fx.get_block(targets.otherwise());
309 let test_zero = match then_value {
312 _ => unreachable!("{:?}", targets),
315 let discr = crate::optimize::peephole::maybe_unwrap_bint(&mut fx.bcx, discr);
316 let (discr, is_inverted) =
317 crate::optimize::peephole::maybe_unwrap_bool_not(&mut fx.bcx, discr);
318 let test_zero = if is_inverted { !test_zero } else { test_zero };
319 let discr = crate::optimize::peephole::maybe_unwrap_bint(&mut fx.bcx, discr);
321 crate::optimize::peephole::make_branchable_value(&mut fx.bcx, discr);
322 if let Some(taken) = crate::optimize::peephole::maybe_known_branch_taken(
323 &fx.bcx, discr, test_zero,
326 fx.bcx.ins().jump(then_block, &[]);
328 fx.bcx.ins().jump(else_block, &[]);
332 fx.bcx.ins().brz(discr, then_block, &[]);
333 fx.bcx.ins().jump(else_block, &[]);
335 fx.bcx.ins().brnz(discr, then_block, &[]);
336 fx.bcx.ins().jump(else_block, &[]);
340 let mut switch = ::cranelift_frontend::Switch::new();
341 for (value, block) in targets.iter() {
342 let block = fx.get_block(block);
343 switch.set_entry(value, block);
345 let otherwise_block = fx.get_block(targets.otherwise());
346 switch.emit(&mut fx.bcx, discr, otherwise_block);
349 TerminatorKind::Call {
357 fx.tcx.sess.time("codegen call", || {
358 crate::abi::codegen_terminator_call(
368 TerminatorKind::InlineAsm {
375 crate::inline_asm::codegen_inline_asm(
377 bb_data.terminator().source_info.span,
384 Some(destination) => {
385 let destination_block = fx.get_block(destination);
386 fx.bcx.ins().jump(destination_block, &[]);
389 crate::trap::trap_unreachable(
391 "[corruption] Returned from noreturn inline asm",
396 TerminatorKind::Resume | TerminatorKind::Abort => {
397 trap_unreachable(fx, "[corruption] Unwinding bb reached.");
399 TerminatorKind::Unreachable => {
400 trap_unreachable(fx, "[corruption] Hit unreachable code.");
402 TerminatorKind::Yield { .. }
403 | TerminatorKind::FalseEdge { .. }
404 | TerminatorKind::FalseUnwind { .. }
405 | TerminatorKind::DropAndReplace { .. }
406 | TerminatorKind::GeneratorDrop => {
407 bug!("shouldn't exist at codegen {:?}", bb_data.terminator());
409 TerminatorKind::Drop { place, target, unwind: _ } => {
410 let drop_place = codegen_place(fx, *place);
411 crate::abi::codegen_drop(fx, bb_data.terminator().source_info.span, drop_place);
413 let target_block = fx.get_block(*target);
414 fx.bcx.ins().jump(target_block, &[]);
419 fx.bcx.seal_all_blocks();
423 fn codegen_stmt<'tcx>(
424 fx: &mut FunctionCx<'_, '_, 'tcx>,
425 #[allow(unused_variables)] cur_block: Block,
426 stmt: &Statement<'tcx>,
428 let _print_guard = crate::PrintOnPanic(|| format!("stmt {:?}", stmt));
430 fx.set_debug_loc(stmt.source_info);
434 StatementKind::StorageLive(..) | StatementKind::StorageDead(..) => {} // Those are not very useful
436 if fx.clif_comments.enabled() {
437 let inst = fx.bcx.func.layout.last_inst(cur_block).unwrap();
438 fx.add_comment(inst, format!("{:?}", stmt));
444 StatementKind::SetDiscriminant { place, variant_index } => {
445 let place = codegen_place(fx, **place);
446 crate::discriminant::codegen_set_discriminant(fx, place, *variant_index);
448 StatementKind::Assign(to_place_and_rval) => {
449 let lval = codegen_place(fx, to_place_and_rval.0);
450 let dest_layout = lval.layout();
451 match to_place_and_rval.1 {
452 Rvalue::Use(ref operand) => {
453 let val = codegen_operand(fx, operand);
454 lval.write_cvalue(fx, val);
456 Rvalue::Ref(_, _, place) | Rvalue::AddressOf(_, place) => {
457 let place = codegen_place(fx, place);
458 let ref_ = place.place_ref(fx, lval.layout());
459 lval.write_cvalue(fx, ref_);
461 Rvalue::ThreadLocalRef(def_id) => {
462 let val = crate::constant::codegen_tls_ref(fx, def_id, lval.layout());
463 lval.write_cvalue(fx, val);
465 Rvalue::BinaryOp(bin_op, ref lhs_rhs) => {
466 let lhs = codegen_operand(fx, &lhs_rhs.0);
467 let rhs = codegen_operand(fx, &lhs_rhs.1);
469 let res = crate::num::codegen_binop(fx, bin_op, lhs, rhs);
470 lval.write_cvalue(fx, res);
472 Rvalue::CheckedBinaryOp(bin_op, ref lhs_rhs) => {
473 let lhs = codegen_operand(fx, &lhs_rhs.0);
474 let rhs = codegen_operand(fx, &lhs_rhs.1);
476 let res = if !fx.tcx.sess.overflow_checks() {
478 crate::num::codegen_int_binop(fx, bin_op, lhs, rhs).load_scalar(fx);
479 let is_overflow = fx.bcx.ins().iconst(types::I8, 0);
480 CValue::by_val_pair(val, is_overflow, lval.layout())
482 crate::num::codegen_checked_int_binop(fx, bin_op, lhs, rhs)
485 lval.write_cvalue(fx, res);
487 Rvalue::UnaryOp(un_op, ref operand) => {
488 let operand = codegen_operand(fx, operand);
489 let layout = operand.layout();
490 let val = operand.load_scalar(fx);
491 let res = match un_op {
492 UnOp::Not => match layout.ty.kind() {
494 let res = fx.bcx.ins().icmp_imm(IntCC::Equal, val, 0);
495 CValue::by_val(fx.bcx.ins().bint(types::I8, res), layout)
497 ty::Uint(_) | ty::Int(_) => {
498 CValue::by_val(fx.bcx.ins().bnot(val), layout)
500 _ => unreachable!("un op Not for {:?}", layout.ty),
502 UnOp::Neg => match layout.ty.kind() {
503 ty::Int(IntTy::I128) => {
504 // FIXME remove this case once ineg.i128 works
506 CValue::const_val(fx, layout, ty::ScalarInt::null(layout.size));
507 crate::num::codegen_int_binop(fx, BinOp::Sub, zero, operand)
509 ty::Int(_) => CValue::by_val(fx.bcx.ins().ineg(val), layout),
510 ty::Float(_) => CValue::by_val(fx.bcx.ins().fneg(val), layout),
511 _ => unreachable!("un op Neg for {:?}", layout.ty),
514 lval.write_cvalue(fx, res);
517 CastKind::Pointer(PointerCast::ReifyFnPointer),
521 let from_ty = fx.monomorphize(operand.ty(&fx.mir.local_decls, fx.tcx));
522 let to_layout = fx.layout_of(fx.monomorphize(to_ty));
523 match *from_ty.kind() {
524 ty::FnDef(def_id, substs) => {
525 let func_ref = fx.get_function_ref(
526 Instance::resolve_for_fn_ptr(
528 ParamEnv::reveal_all(),
533 .polymorphize(fx.tcx),
535 let func_addr = fx.bcx.ins().func_addr(fx.pointer_type, func_ref);
536 lval.write_cvalue(fx, CValue::by_val(func_addr, to_layout));
538 _ => bug!("Trying to ReifyFnPointer on non FnDef {:?}", from_ty),
542 CastKind::Pointer(PointerCast::UnsafeFnPointer),
547 CastKind::Pointer(PointerCast::MutToConstPointer),
552 CastKind::Pointer(PointerCast::ArrayToPointer),
556 let to_layout = fx.layout_of(fx.monomorphize(to_ty));
557 let operand = codegen_operand(fx, operand);
558 lval.write_cvalue(fx, operand.cast_pointer_to(to_layout));
560 Rvalue::Cast(CastKind::Misc, ref operand, to_ty) => {
561 let operand = codegen_operand(fx, operand);
562 let from_ty = operand.layout().ty;
563 let to_ty = fx.monomorphize(to_ty);
565 fn is_fat_ptr<'tcx>(fx: &FunctionCx<'_, '_, 'tcx>, ty: Ty<'tcx>) -> bool {
566 ty.builtin_deref(true)
567 .map(|ty::TypeAndMut { ty: pointee_ty, mutbl: _ }| {
568 has_ptr_meta(fx.tcx, pointee_ty)
573 if is_fat_ptr(fx, from_ty) {
574 if is_fat_ptr(fx, to_ty) {
575 // fat-ptr -> fat-ptr
576 lval.write_cvalue(fx, operand.cast_pointer_to(dest_layout));
578 // fat-ptr -> thin-ptr
579 let (ptr, _extra) = operand.load_scalar_pair(fx);
580 lval.write_cvalue(fx, CValue::by_val(ptr, dest_layout))
582 } else if let ty::Adt(adt_def, _substs) = from_ty.kind() {
583 // enum -> discriminant value
584 assert!(adt_def.is_enum());
586 ty::Uint(_) | ty::Int(_) => {}
587 _ => unreachable!("cast adt {} -> {}", from_ty, to_ty),
589 let to_clif_ty = fx.clif_type(to_ty).unwrap();
591 let discriminant = crate::discriminant::codegen_get_discriminant(
594 fx.layout_of(operand.layout().ty.discriminant_ty(fx.tcx)),
598 let res = crate::cast::clif_intcast(
604 lval.write_cvalue(fx, CValue::by_val(res, dest_layout));
606 let to_clif_ty = fx.clif_type(to_ty).unwrap();
607 let from = operand.load_scalar(fx);
609 let res = clif_int_or_float_cast(
616 lval.write_cvalue(fx, CValue::by_val(res, dest_layout));
620 CastKind::Pointer(PointerCast::ClosureFnPointer(_)),
624 let operand = codegen_operand(fx, operand);
625 match *operand.layout().ty.kind() {
626 ty::Closure(def_id, substs) => {
627 let instance = Instance::resolve_closure(
631 ty::ClosureKind::FnOnce,
633 .polymorphize(fx.tcx);
634 let func_ref = fx.get_function_ref(instance);
635 let func_addr = fx.bcx.ins().func_addr(fx.pointer_type, func_ref);
636 lval.write_cvalue(fx, CValue::by_val(func_addr, lval.layout()));
638 _ => bug!("{} cannot be cast to a fn ptr", operand.layout().ty),
641 Rvalue::Cast(CastKind::Pointer(PointerCast::Unsize), ref operand, _to_ty) => {
642 let operand = codegen_operand(fx, operand);
643 operand.unsize_value(fx, lval);
645 Rvalue::Discriminant(place) => {
646 let place = codegen_place(fx, place);
647 let value = place.to_cvalue(fx);
649 crate::discriminant::codegen_get_discriminant(fx, value, dest_layout);
650 lval.write_cvalue(fx, discr);
652 Rvalue::Repeat(ref operand, times) => {
653 let operand = codegen_operand(fx, operand);
656 .eval(fx.tcx, ParamEnv::reveal_all())
658 .try_to_bits(fx.tcx.data_layout.pointer_size)
660 if operand.layout().size.bytes() == 0 {
661 // Do nothing for ZST's
662 } else if fx.clif_type(operand.layout().ty) == Some(types::I8) {
663 let times = fx.bcx.ins().iconst(fx.pointer_type, times as i64);
664 // FIXME use emit_small_memset where possible
665 let addr = lval.to_ptr().get_addr(fx);
666 let val = operand.load_scalar(fx);
667 fx.bcx.call_memset(fx.cx.module.target_config(), addr, val, times);
669 let loop_block = fx.bcx.create_block();
670 let loop_block2 = fx.bcx.create_block();
671 let done_block = fx.bcx.create_block();
672 let index = fx.bcx.append_block_param(loop_block, fx.pointer_type);
673 let zero = fx.bcx.ins().iconst(fx.pointer_type, 0);
674 fx.bcx.ins().jump(loop_block, &[zero]);
676 fx.bcx.switch_to_block(loop_block);
677 let done = fx.bcx.ins().icmp_imm(IntCC::Equal, index, times as i64);
678 fx.bcx.ins().brnz(done, done_block, &[]);
679 fx.bcx.ins().jump(loop_block2, &[]);
681 fx.bcx.switch_to_block(loop_block2);
682 let to = lval.place_index(fx, index);
683 to.write_cvalue(fx, operand);
684 let index = fx.bcx.ins().iadd_imm(index, 1);
685 fx.bcx.ins().jump(loop_block, &[index]);
687 fx.bcx.switch_to_block(done_block);
691 Rvalue::Len(place) => {
692 let place = codegen_place(fx, place);
693 let usize_layout = fx.layout_of(fx.tcx.types.usize);
694 let len = codegen_array_len(fx, place);
695 lval.write_cvalue(fx, CValue::by_val(len, usize_layout));
697 Rvalue::NullaryOp(NullOp::Box, content_ty) => {
698 let usize_type = fx.clif_type(fx.tcx.types.usize).unwrap();
699 let content_ty = fx.monomorphize(content_ty);
700 let layout = fx.layout_of(content_ty);
701 let llsize = fx.bcx.ins().iconst(usize_type, layout.size.bytes() as i64);
702 let llalign = fx.bcx.ins().iconst(usize_type, layout.align.abi.bytes() as i64);
703 let box_layout = fx.layout_of(fx.tcx.mk_box(content_ty));
707 match fx.tcx.lang_items().require(rustc_hir::LangItem::ExchangeMalloc) {
712 .fatal(&format!("allocation of `{}` {}", box_layout.ty, s));
715 let instance = ty::Instance::mono(fx.tcx, def_id).polymorphize(fx.tcx);
716 let func_ref = fx.get_function_ref(instance);
717 let call = fx.bcx.ins().call(func_ref, &[llsize, llalign]);
718 let ptr = fx.bcx.inst_results(call)[0];
719 lval.write_cvalue(fx, CValue::by_val(ptr, box_layout));
721 Rvalue::NullaryOp(NullOp::SizeOf, ty) => {
725 .is_sized(fx.tcx.at(stmt.source_info.span), ParamEnv::reveal_all())
727 let ty_size = fx.layout_of(fx.monomorphize(ty)).size.bytes();
729 CValue::const_val(fx, fx.layout_of(fx.tcx.types.usize), ty_size.into());
730 lval.write_cvalue(fx, val);
732 Rvalue::Aggregate(ref kind, ref operands) => match kind.as_ref() {
733 AggregateKind::Array(_ty) => {
734 for (i, operand) in operands.iter().enumerate() {
735 let operand = codegen_operand(fx, operand);
736 let index = fx.bcx.ins().iconst(fx.pointer_type, i as i64);
737 let to = lval.place_index(fx, index);
738 to.write_cvalue(fx, operand);
741 _ => unreachable!("shouldn't exist at codegen {:?}", to_place_and_rval.1),
745 StatementKind::StorageLive(_)
746 | StatementKind::StorageDead(_)
748 | StatementKind::FakeRead(..)
749 | StatementKind::Retag { .. }
750 | StatementKind::AscribeUserType(..) => {}
752 StatementKind::LlvmInlineAsm(asm) => {
753 use rustc_span::symbol::Symbol;
754 let LlvmInlineAsm { asm, outputs, inputs } = &**asm;
755 let rustc_hir::LlvmInlineAsmInner {
756 asm: asm_code, // Name
757 outputs: output_names, // Vec<LlvmInlineAsmOutput>
758 inputs: input_names, // Vec<Name>
759 clobbers, // Vec<Name>
765 match asm_code.as_str().trim() {
769 "mov %rbx, %rsi\n cpuid\n xchg %rbx, %rsi" => {
770 assert_eq!(input_names, &[Symbol::intern("{eax}"), Symbol::intern("{ecx}")]);
771 assert_eq!(output_names.len(), 4);
772 for (i, c) in (&["={eax}", "={esi}", "={ecx}", "={edx}"]).iter().enumerate() {
773 assert_eq!(&output_names[i].constraint.as_str(), c);
774 assert!(!output_names[i].is_rw);
775 assert!(!output_names[i].is_indirect);
778 assert_eq!(clobbers, &[]);
781 assert!(!alignstack);
783 assert_eq!(inputs.len(), 2);
784 let leaf = codegen_operand(fx, &inputs[0].1).load_scalar(fx); // %eax
785 let subleaf = codegen_operand(fx, &inputs[1].1).load_scalar(fx); // %ecx
787 let (eax, ebx, ecx, edx) =
788 crate::intrinsics::codegen_cpuid_call(fx, leaf, subleaf);
790 assert_eq!(outputs.len(), 4);
791 codegen_place(fx, outputs[0])
792 .write_cvalue(fx, CValue::by_val(eax, fx.layout_of(fx.tcx.types.u32)));
793 codegen_place(fx, outputs[1])
794 .write_cvalue(fx, CValue::by_val(ebx, fx.layout_of(fx.tcx.types.u32)));
795 codegen_place(fx, outputs[2])
796 .write_cvalue(fx, CValue::by_val(ecx, fx.layout_of(fx.tcx.types.u32)));
797 codegen_place(fx, outputs[3])
798 .write_cvalue(fx, CValue::by_val(edx, fx.layout_of(fx.tcx.types.u32)));
801 assert_eq!(input_names, &[Symbol::intern("{ecx}")]);
803 assert_eq!(output_names.len(), 2);
804 for (i, c) in (&["={eax}", "={edx}"]).iter().enumerate() {
805 assert_eq!(&output_names[i].constraint.as_str(), c);
806 assert!(!output_names[i].is_rw);
807 assert!(!output_names[i].is_indirect);
810 assert_eq!(clobbers, &[]);
813 assert!(!alignstack);
815 crate::trap::trap_unimplemented(fx, "_xgetbv arch intrinsic is not supported");
817 // ___chkstk, ___chkstk_ms and __alloca are only used on Windows
818 _ if fx.tcx.symbol_name(fx.instance).name.starts_with("___chkstk") => {
819 crate::trap::trap_unimplemented(fx, "Stack probes are not supported");
821 _ if fx.tcx.symbol_name(fx.instance).name == "__alloca" => {
822 crate::trap::trap_unimplemented(fx, "Alloca is not supported");
824 // Used in sys::windows::abort_internal
826 crate::trap::trap_unimplemented(fx, "Windows abort");
831 .span_fatal(stmt.source_info.span, "Inline assembly is not supported"),
834 StatementKind::Coverage { .. } => fx.tcx.sess.fatal("-Zcoverage is unimplemented"),
835 StatementKind::CopyNonOverlapping(inner) => {
836 let dst = codegen_operand(fx, &inner.dst);
839 .pointee_info_at(fx, rustc_target::abi::Size::ZERO)
840 .expect("Expected pointer");
841 let dst = dst.load_scalar(fx);
842 let src = codegen_operand(fx, &inner.src).load_scalar(fx);
843 let count = codegen_operand(fx, &inner.count).load_scalar(fx);
844 let elem_size: u64 = pointee.size.bytes();
846 if elem_size != 1 { fx.bcx.ins().imul_imm(count, elem_size as i64) } else { count };
847 fx.bcx.call_memcpy(fx.cx.module.target_config(), dst, src, bytes);
852 fn codegen_array_len<'tcx>(fx: &mut FunctionCx<'_, '_, 'tcx>, place: CPlace<'tcx>) -> Value {
853 match *place.layout().ty.kind() {
854 ty::Array(_elem_ty, len) => {
855 let len = fx.monomorphize(len).eval_usize(fx.tcx, ParamEnv::reveal_all()) as i64;
856 fx.bcx.ins().iconst(fx.pointer_type, len)
858 ty::Slice(_elem_ty) => {
859 place.to_ptr_maybe_unsized().1.expect("Length metadata for slice place")
861 _ => bug!("Rvalue::Len({:?})", place),
865 pub(crate) fn codegen_place<'tcx>(
866 fx: &mut FunctionCx<'_, '_, 'tcx>,
869 let mut cplace = fx.get_local_place(place.local);
871 for elem in place.projection {
873 PlaceElem::Deref => {
874 cplace = cplace.place_deref(fx);
876 PlaceElem::Field(field, _ty) => {
877 cplace = cplace.place_field(fx, field);
879 PlaceElem::Index(local) => {
880 let index = fx.get_local_place(local).to_cvalue(fx).load_scalar(fx);
881 cplace = cplace.place_index(fx, index);
883 PlaceElem::ConstantIndex { offset, min_length: _, from_end } => {
884 let offset: u64 = offset;
885 let index = if !from_end {
886 fx.bcx.ins().iconst(fx.pointer_type, offset as i64)
888 let len = codegen_array_len(fx, cplace);
889 fx.bcx.ins().iadd_imm(len, -(offset as i64))
891 cplace = cplace.place_index(fx, index);
893 PlaceElem::Subslice { from, to, from_end } => {
894 // These indices are generated by slice patterns.
895 // slice[from:-to] in Python terms.
897 let from: u64 = from;
900 match cplace.layout().ty.kind() {
901 ty::Array(elem_ty, _len) => {
902 assert!(!from_end, "array subslices are never `from_end`");
903 let elem_layout = fx.layout_of(elem_ty);
904 let ptr = cplace.to_ptr();
905 cplace = CPlace::for_ptr(
906 ptr.offset_i64(fx, elem_layout.size.bytes() as i64 * (from as i64)),
907 fx.layout_of(fx.tcx.mk_array(elem_ty, to - from)),
910 ty::Slice(elem_ty) => {
911 assert!(from_end, "slice subslices should be `from_end`");
912 let elem_layout = fx.layout_of(elem_ty);
913 let (ptr, len) = cplace.to_ptr_maybe_unsized();
914 let len = len.unwrap();
915 cplace = CPlace::for_ptr_with_extra(
916 ptr.offset_i64(fx, elem_layout.size.bytes() as i64 * (from as i64)),
917 fx.bcx.ins().iadd_imm(len, -(from as i64 + to as i64)),
924 PlaceElem::Downcast(_adt_def, variant) => {
925 cplace = cplace.downcast_variant(fx, variant);
933 pub(crate) fn codegen_operand<'tcx>(
934 fx: &mut FunctionCx<'_, '_, 'tcx>,
935 operand: &Operand<'tcx>,
938 Operand::Move(place) | Operand::Copy(place) => {
939 let cplace = codegen_place(fx, *place);
942 Operand::Constant(const_) => crate::constant::codegen_constant(fx, const_),
946 pub(crate) fn codegen_panic<'tcx>(fx: &mut FunctionCx<'_, '_, 'tcx>, msg_str: &str, span: Span) {
947 let location = fx.get_caller_location(span).load_scalar(fx);
949 let msg_ptr = fx.anonymous_str("assert", msg_str);
950 let msg_len = fx.bcx.ins().iconst(fx.pointer_type, i64::try_from(msg_str.len()).unwrap());
951 let args = [msg_ptr, msg_len, location];
953 codegen_panic_inner(fx, rustc_hir::LangItem::Panic, &args, span);
956 pub(crate) fn codegen_panic_inner<'tcx>(
957 fx: &mut FunctionCx<'_, '_, 'tcx>,
958 lang_item: rustc_hir::LangItem,
963 fx.tcx.lang_items().require(lang_item).unwrap_or_else(|s| fx.tcx.sess.span_fatal(span, &s));
965 let instance = Instance::mono(fx.tcx, def_id).polymorphize(fx.tcx);
966 let symbol_name = fx.tcx.symbol_name(instance).name;
971 AbiParam::new(fx.pointer_type),
972 AbiParam::new(fx.pointer_type),
973 AbiParam::new(fx.pointer_type),
979 crate::trap::trap_unreachable(fx, "panic lang item returned");