1 use rustc::ty::adjustment::PointerCast;
2 use rustc_index::vec::IndexVec;
6 pub fn trans_fn<'clif, 'tcx, B: Backend + 'static>(
7 cx: &mut crate::CodegenCx<'clif, '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();
18 let mut debug_context = cx
21 .map(|debug_context| FunctionDebugContext::new(debug_context, instance, func_id, &name));
23 // Make FunctionBuilder
24 let context = &mut cx.cached_context;
26 context.func.name = ExternalName::user(0, func_id.as_u32());
27 context.func.signature = sig;
28 context.func.collect_debug_info();
29 let mut func_ctx = FunctionBuilderContext::new();
30 let mut bcx = FunctionBuilder::new(&mut context.func, &mut func_ctx);
33 let start_block = bcx.create_block();
34 let block_map: IndexVec<BasicBlock, Block> = (0..mir.basic_blocks().len()).map(|_| bcx.create_block()).collect();
37 let pointer_type = cx.module.target_config().pointer_type();
38 let clif_comments = crate::pretty_clif::CommentWriter::new(tcx, instance);
40 let mut fx = FunctionCx {
50 local_map: HashMap::new(),
51 caller_location: None, // set by `codegen_fn_prelude`
52 cold_blocks: EntitySet::new(),
55 constants_cx: &mut cx.constants_cx,
56 vtables: &mut cx.vtables,
57 source_info_set: indexmap::IndexSet::new(),
60 if fx.mir.args_iter().any(|arg| fx.layout_of(fx.monomorphize(&fx.mir.local_decls[arg].ty)).abi.is_uninhabited()) {
61 let entry_block = fx.bcx.create_block();
62 fx.bcx.append_block_params_for_function_params(entry_block);
63 fx.bcx.switch_to_block(entry_block);
64 crate::trap::trap_unreachable(&mut fx, "function has uninhabited argument");
66 tcx.sess.time("codegen clif ir", || {
67 tcx.sess.time("codegen prelude", || crate::abi::codegen_fn_prelude(&mut fx, start_block));
68 codegen_fn_content(&mut fx);
72 // Recover all necessary data from fx, before accessing func will prevent future access to it.
73 let instance = fx.instance;
74 let mut clif_comments = fx.clif_comments;
75 let source_info_set = fx.source_info_set;
76 let local_map = fx.local_map;
77 let cold_blocks = fx.cold_blocks;
79 #[cfg(debug_assertions)]
80 crate::pretty_clif::write_clif_file(cx.tcx, "unopt", instance, &context.func, &clif_comments, None);
83 verify_func(tcx, &clif_comments, &context.func);
85 // Perform rust specific optimizations
86 tcx.sess.time("optimize clif ir", || {
87 crate::optimize::optimize_function(tcx, instance, context, &cold_blocks, &mut clif_comments);
91 let module = &mut cx.module;
92 tcx.sess.time("define function", || module.define_function(func_id, context).unwrap());
94 // Write optimized function to file for debugging
95 #[cfg(debug_assertions)]
97 let value_ranges = context
98 .build_value_labels_ranges(cx.module.isa())
99 .expect("value location ranges");
101 crate::pretty_clif::write_clif_file(
111 // Define debuginfo for function
112 let isa = cx.module.isa();
113 tcx.sess.time("generate debug info", || {
116 .map(|x| x.define(context, isa, &source_info_set, local_map));
119 // Clear context to make it usable for the next function
123 pub fn verify_func(tcx: TyCtxt, writer: &crate::pretty_clif::CommentWriter, func: &Function) {
124 tcx.sess.time("verify clif ir", || {
125 let flags = settings::Flags::new(settings::builder());
126 match ::cranelift_codegen::verify_function(&func, &flags) {
129 tcx.sess.err(&format!("{:?}", err));
130 let pretty_error = ::cranelift_codegen::print_errors::pretty_verifier_error(
133 Some(Box::new(writer)),
137 .fatal(&format!("cranelift verify error:\n{}", pretty_error));
143 fn codegen_fn_content(fx: &mut FunctionCx<'_, '_, impl Backend>) {
144 for (bb, bb_data) in fx.mir.basic_blocks().iter_enumerated() {
145 let block = fx.get_block(bb);
146 fx.bcx.switch_to_block(block);
148 if bb_data.is_cleanup {
149 // Unwinding after panicking is not supported
152 // FIXME once unwinding is supported uncomment next lines
153 // // Unwinding is unlikely to happen, so mark cleanup block's as cold.
154 // fx.cold_blocks.insert(block);
158 for stmt in &bb_data.statements {
159 fx.set_debug_loc(stmt.source_info);
160 trans_stmt(fx, block, stmt);
163 #[cfg(debug_assertions)]
165 let mut terminator_head = "\n".to_string();
169 .fmt_head(&mut terminator_head)
171 let inst = fx.bcx.func.layout.last_inst(block).unwrap();
172 fx.add_comment(inst, terminator_head);
175 fx.set_debug_loc(bb_data.terminator().source_info);
177 match &bb_data.terminator().kind {
178 TerminatorKind::Goto { target } => {
179 let block = fx.get_block(*target);
180 fx.bcx.ins().jump(block, &[]);
182 TerminatorKind::Return => {
183 crate::abi::codegen_return(fx);
185 TerminatorKind::Assert {
192 if !fx.tcx.sess.overflow_checks() {
193 if let mir::AssertKind::OverflowNeg = *msg {
194 let target = fx.get_block(*target);
195 fx.bcx.ins().jump(target, &[]);
199 let cond = trans_operand(fx, cond).load_scalar(fx);
201 let target = fx.get_block(*target);
202 let failure = fx.bcx.create_block();
203 fx.cold_blocks.insert(failure);
206 fx.bcx.ins().brz(cond, failure, &[]);
208 fx.bcx.ins().brnz(cond, failure, &[]);
210 fx.bcx.ins().jump(target, &[]);
212 fx.bcx.switch_to_block(failure);
216 "[panic] Assert {:?} at {:?} failed.",
218 bb_data.terminator().source_info.span
223 TerminatorKind::SwitchInt {
229 let discr = trans_operand(fx, discr).load_scalar(fx);
230 let mut switch = ::cranelift_frontend::Switch::new();
231 for (i, value) in values.iter().enumerate() {
232 let block = fx.get_block(targets[i]);
233 switch.set_entry(*value as u64, block);
235 let otherwise_block = fx.get_block(targets[targets.len() - 1]);
236 switch.emit(&mut fx.bcx, discr, otherwise_block);
238 TerminatorKind::Call {
245 fx.tcx.sess.time("codegen call", || crate::abi::codegen_terminator_call(
247 bb_data.terminator().source_info.span,
253 TerminatorKind::Resume | TerminatorKind::Abort => {
254 trap_unreachable(fx, "[corruption] Unwinding bb reached.");
256 TerminatorKind::Unreachable => {
257 trap_unreachable(fx, "[corruption] Hit unreachable code.");
259 TerminatorKind::Yield { .. }
260 | TerminatorKind::FalseEdges { .. }
261 | TerminatorKind::FalseUnwind { .. }
262 | TerminatorKind::DropAndReplace { .. }
263 | TerminatorKind::GeneratorDrop => {
264 bug!("shouldn't exist at trans {:?}", bb_data.terminator());
266 TerminatorKind::Drop {
271 let drop_place = trans_place(fx, location);
272 crate::abi::codegen_drop(fx, bb_data.terminator().source_info.span, drop_place);
274 let target_block = fx.get_block(*target);
275 fx.bcx.ins().jump(target_block, &[]);
280 fx.bcx.seal_all_blocks();
285 fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
287 stmt: &Statement<'tcx>,
289 let _print_guard = PrintOnPanic(|| format!("stmt {:?}", stmt));
291 fx.set_debug_loc(stmt.source_info);
293 #[cfg(false_debug_assertions)]
295 StatementKind::StorageLive(..) | StatementKind::StorageDead(..) => {} // Those are not very useful
297 let inst = fx.bcx.func.layout.last_inst(cur_block).unwrap();
298 fx.add_comment(inst, format!("{:?}", stmt));
303 StatementKind::SetDiscriminant {
307 let place = trans_place(fx, place);
308 crate::discriminant::codegen_set_discriminant(fx, place, *variant_index);
310 StatementKind::Assign(to_place_and_rval) => {
311 let lval = trans_place(fx, &to_place_and_rval.0);
312 let dest_layout = lval.layout();
313 match &to_place_and_rval.1 {
314 Rvalue::Use(operand) => {
315 let val = trans_operand(fx, operand);
316 lval.write_cvalue(fx, val);
318 Rvalue::Ref(_, _, place) | Rvalue::AddressOf(_, place) => {
319 let place = trans_place(fx, place);
320 place.write_place_ref(fx, lval);
322 Rvalue::BinaryOp(bin_op, lhs, rhs) => {
323 let lhs = trans_operand(fx, lhs);
324 let rhs = trans_operand(fx, rhs);
326 let res = crate::num::codegen_binop(fx, *bin_op, lhs, rhs);
327 lval.write_cvalue(fx, res);
329 Rvalue::CheckedBinaryOp(bin_op, lhs, rhs) => {
330 let lhs = trans_operand(fx, lhs);
331 let rhs = trans_operand(fx, rhs);
333 let res = if !fx.tcx.sess.overflow_checks() {
335 crate::num::trans_int_binop(fx, *bin_op, lhs, rhs).load_scalar(fx);
336 let is_overflow = fx.bcx.ins().iconst(types::I8, 0);
337 CValue::by_val_pair(val, is_overflow, lval.layout())
339 crate::num::trans_checked_int_binop(fx, *bin_op, lhs, rhs)
342 lval.write_cvalue(fx, res);
344 Rvalue::UnaryOp(un_op, operand) => {
345 let operand = trans_operand(fx, operand);
346 let layout = operand.layout();
347 let val = operand.load_scalar(fx);
348 let res = match un_op {
350 match layout.ty.kind {
352 let val = fx.bcx.ins().uextend(types::I32, val); // WORKAROUND for CraneStation/cranelift#466
353 let res = fx.bcx.ins().icmp_imm(IntCC::Equal, val, 0);
354 CValue::by_val(fx.bcx.ins().bint(types::I8, res), layout)
356 ty::Uint(_) | ty::Int(_) => {
357 CValue::by_val(fx.bcx.ins().bnot(val), layout)
359 _ => unreachable!("un op Not for {:?}", layout.ty),
362 UnOp::Neg => match layout.ty.kind {
363 ty::Int(IntTy::I128) => {
364 // FIXME remove this case once ineg.i128 works
365 let zero = CValue::const_val(fx, layout, 0);
366 crate::num::trans_int_binop(fx, BinOp::Sub, zero, operand)
369 CValue::by_val(fx.bcx.ins().ineg(val), layout)
372 CValue::by_val(fx.bcx.ins().fneg(val), layout)
374 _ => unreachable!("un op Neg for {:?}", layout.ty),
377 lval.write_cvalue(fx, res);
379 Rvalue::Cast(CastKind::Pointer(PointerCast::ReifyFnPointer), operand, to_ty) => {
380 let from_ty = fx.monomorphize(&operand.ty(&fx.mir.local_decls, fx.tcx));
381 let to_layout = fx.layout_of(fx.monomorphize(to_ty));
383 ty::FnDef(def_id, substs) => {
384 let func_ref = fx.get_function_ref(
385 Instance::resolve_for_fn_ptr(fx.tcx, ParamEnv::reveal_all(), def_id, substs)
388 let func_addr = fx.bcx.ins().func_addr(fx.pointer_type, func_ref);
389 lval.write_cvalue(fx, CValue::by_val(func_addr, to_layout));
391 _ => bug!("Trying to ReifyFnPointer on non FnDef {:?}", from_ty),
394 Rvalue::Cast(CastKind::Pointer(PointerCast::UnsafeFnPointer), operand, to_ty)
395 | Rvalue::Cast(CastKind::Pointer(PointerCast::MutToConstPointer), operand, to_ty)
396 | Rvalue::Cast(CastKind::Pointer(PointerCast::ArrayToPointer), operand, to_ty) => {
397 let to_layout = fx.layout_of(fx.monomorphize(to_ty));
398 let operand = trans_operand(fx, operand);
399 lval.write_cvalue(fx, operand.unchecked_cast_to(to_layout));
401 Rvalue::Cast(CastKind::Misc, operand, to_ty) => {
402 let operand = trans_operand(fx, operand);
403 let from_ty = operand.layout().ty;
404 let to_ty = fx.monomorphize(to_ty);
407 fx: &FunctionCx<'_, 'tcx, impl Backend>,
410 ty.builtin_deref(true)
415 }| has_ptr_meta(fx.tcx, pointee_ty),
420 if is_fat_ptr(fx, from_ty) {
421 if is_fat_ptr(fx, to_ty) {
422 // fat-ptr -> fat-ptr
423 lval.write_cvalue(fx, operand.unchecked_cast_to(dest_layout));
425 // fat-ptr -> thin-ptr
426 let (ptr, _extra) = operand.load_scalar_pair(fx);
427 lval.write_cvalue(fx, CValue::by_val(ptr, dest_layout))
429 } else if let ty::Adt(adt_def, _substs) = from_ty.kind {
430 // enum -> discriminant value
431 assert!(adt_def.is_enum());
433 ty::Uint(_) | ty::Int(_) => {}
434 _ => unreachable!("cast adt {} -> {}", from_ty, to_ty),
437 let discr = crate::discriminant::codegen_get_discriminant(
442 lval.write_cvalue(fx, discr);
444 let to_clif_ty = fx.clif_type(to_ty).unwrap();
445 let from = operand.load_scalar(fx);
447 let res = clif_int_or_float_cast(
454 lval.write_cvalue(fx, CValue::by_val(res, dest_layout));
457 Rvalue::Cast(CastKind::Pointer(PointerCast::ClosureFnPointer(_)), operand, _to_ty) => {
458 let operand = trans_operand(fx, operand);
459 match operand.layout().ty.kind {
460 ty::Closure(def_id, substs) => {
461 let instance = Instance::resolve_closure(
465 ty::ClosureKind::FnOnce,
467 let func_ref = fx.get_function_ref(instance);
468 let func_addr = fx.bcx.ins().func_addr(fx.pointer_type, func_ref);
469 lval.write_cvalue(fx, CValue::by_val(func_addr, lval.layout()));
471 _ => bug!("{} cannot be cast to a fn ptr", operand.layout().ty),
474 Rvalue::Cast(CastKind::Pointer(PointerCast::Unsize), operand, _to_ty) => {
475 let operand = trans_operand(fx, operand);
476 operand.unsize_value(fx, lval);
478 Rvalue::Discriminant(place) => {
479 let place = trans_place(fx, place);
480 let value = place.to_cvalue(fx);
482 crate::discriminant::codegen_get_discriminant(fx, value, dest_layout);
483 lval.write_cvalue(fx, discr);
485 Rvalue::Repeat(operand, times) => {
486 let operand = trans_operand(fx, operand);
488 let index = fx.bcx.ins().iconst(fx.pointer_type, i as i64);
489 let to = lval.place_index(fx, index);
490 to.write_cvalue(fx, operand);
493 Rvalue::Len(place) => {
494 let place = trans_place(fx, place);
495 let usize_layout = fx.layout_of(fx.tcx.types.usize);
496 let len = codegen_array_len(fx, place);
497 lval.write_cvalue(fx, CValue::by_val(len, usize_layout));
499 Rvalue::NullaryOp(NullOp::Box, content_ty) => {
500 use rustc::middle::lang_items::ExchangeMallocFnLangItem;
502 let usize_type = fx.clif_type(fx.tcx.types.usize).unwrap();
503 let content_ty = fx.monomorphize(content_ty);
504 let layout = fx.layout_of(content_ty);
505 let llsize = fx.bcx.ins().iconst(usize_type, layout.size.bytes() as i64);
509 .iconst(usize_type, layout.align.abi.bytes() as i64);
510 let box_layout = fx.layout_of(fx.tcx.mk_box(content_ty));
513 let def_id = match fx.tcx.lang_items().require(ExchangeMallocFnLangItem) {
518 .fatal(&format!("allocation of `{}` {}", box_layout.ty, s));
521 let instance = ty::Instance::mono(fx.tcx, def_id);
522 let func_ref = fx.get_function_ref(instance);
523 let call = fx.bcx.ins().call(func_ref, &[llsize, llalign]);
524 let ptr = fx.bcx.inst_results(call)[0];
525 lval.write_cvalue(fx, CValue::by_val(ptr, box_layout));
527 Rvalue::NullaryOp(NullOp::SizeOf, ty) => {
531 .is_sized(fx.tcx.at(stmt.source_info.span), ParamEnv::reveal_all()));
532 let ty_size = fx.layout_of(fx.monomorphize(ty)).size.bytes();
533 let val = CValue::const_val(fx, fx.layout_of(fx.tcx.types.usize), ty_size.into());
534 lval.write_cvalue(fx, val);
536 Rvalue::Aggregate(kind, operands) => match **kind {
537 AggregateKind::Array(_ty) => {
538 for (i, operand) in operands.into_iter().enumerate() {
539 let operand = trans_operand(fx, operand);
540 let index = fx.bcx.ins().iconst(fx.pointer_type, i as i64);
541 let to = lval.place_index(fx, index);
542 to.write_cvalue(fx, operand);
545 _ => unreachable!("shouldn't exist at trans {:?}", to_place_and_rval.1),
549 StatementKind::StorageLive(_)
550 | StatementKind::StorageDead(_)
552 | StatementKind::FakeRead(..)
553 | StatementKind::Retag { .. }
554 | StatementKind::AscribeUserType(..) => {}
556 StatementKind::InlineAsm(asm) => {
557 use syntax::ast::Name;
563 let rustc_hir::InlineAsmInner {
564 asm: asm_code, // Name
565 outputs, // Vec<Name>
567 clobbers, // Vec<Name>
570 dialect: _, // syntax::ast::AsmDialect
573 match &*asm_code.as_str() {
575 assert_eq!(inputs, &[Name::intern("r")]);
576 assert!(outputs.is_empty(), "{:?}", outputs);
580 "cpuid" | "cpuid\n" => {
581 assert_eq!(inputs, &[Name::intern("{eax}"), Name::intern("{ecx}")]);
583 assert_eq!(outputs.len(), 4);
584 for (i, c) in (&["={eax}", "={ebx}", "={ecx}", "={edx}"])
588 assert_eq!(&outputs[i].constraint.as_str(), c);
589 assert!(!outputs[i].is_rw);
590 assert!(!outputs[i].is_indirect);
593 assert_eq!(clobbers, &[Name::intern("rbx")]);
596 assert!(!alignstack);
598 crate::trap::trap_unimplemented(
600 "__cpuid_count arch intrinsic is not supported",
604 assert_eq!(inputs, &[Name::intern("{ecx}")]);
606 assert_eq!(outputs.len(), 2);
607 for (i, c) in (&["={eax}", "={edx}"]).iter().enumerate() {
608 assert_eq!(&outputs[i].constraint.as_str(), c);
609 assert!(!outputs[i].is_rw);
610 assert!(!outputs[i].is_indirect);
613 assert_eq!(clobbers, &[]);
616 assert!(!alignstack);
618 crate::trap::trap_unimplemented(fx, "_xgetbv arch intrinsic is not supported");
620 _ if fx.tcx.symbol_name(fx.instance).name.as_str() == "__rust_probestack" => {
621 crate::trap::trap_unimplemented(fx, "__rust_probestack is not supported");
623 _ => unimpl!("Inline assembly is not supported"),
629 fn codegen_array_len<'tcx>(
630 fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
633 match place.layout().ty.kind {
634 ty::Array(_elem_ty, len) => {
635 let len = crate::constant::force_eval_const(fx, len)
636 .eval_usize(fx.tcx, ParamEnv::reveal_all()) as i64;
637 fx.bcx.ins().iconst(fx.pointer_type, len)
639 ty::Slice(_elem_ty) => place
640 .to_ptr_maybe_unsized(fx)
642 .expect("Length metadata for slice place"),
643 _ => bug!("Rvalue::Len({:?})", place),
647 pub fn trans_place<'tcx>(
648 fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
651 let mut cplace = fx.get_local_place(place.local);
653 for elem in &*place.projection {
655 PlaceElem::Deref => {
656 cplace = cplace.place_deref(fx);
658 PlaceElem::Field(field, _ty) => {
659 cplace = cplace.place_field(fx, field);
661 PlaceElem::Index(local) => {
662 let index = fx.get_local_place(local).to_cvalue(fx).load_scalar(fx);
663 cplace = cplace.place_index(fx, index);
665 PlaceElem::ConstantIndex {
670 let index = if !from_end {
671 fx.bcx.ins().iconst(fx.pointer_type, offset as i64)
673 let len = codegen_array_len(fx, cplace);
674 fx.bcx.ins().iadd_imm(len, -(offset as i64))
676 cplace = cplace.place_index(fx, index);
678 PlaceElem::Subslice { from, to, from_end } => {
679 // These indices are generated by slice patterns.
680 // slice[from:-to] in Python terms.
682 match cplace.layout().ty.kind {
683 ty::Array(elem_ty, _len) => {
684 assert!(!from_end, "array subslices are never `from_end`");
685 let elem_layout = fx.layout_of(elem_ty);
686 let ptr = cplace.to_ptr(fx);
687 cplace = CPlace::for_ptr(
688 ptr.offset_i64(fx, elem_layout.size.bytes() as i64 * from as i64),
689 fx.layout_of(fx.tcx.mk_array(elem_ty, to as u64 - from as u64)),
692 ty::Slice(elem_ty) => {
693 assert!(from_end, "slice subslices should be `from_end`");
694 let elem_layout = fx.layout_of(elem_ty);
695 let (ptr, len) = cplace.to_ptr_maybe_unsized(fx);
696 let len = len.unwrap();
697 cplace = CPlace::for_ptr_with_extra(
698 ptr.offset_i64(fx, elem_layout.size.bytes() as i64 * from as i64),
699 fx.bcx.ins().iadd_imm(len, -(from as i64 + to as i64)),
706 PlaceElem::Downcast(_adt_def, variant) => {
707 cplace = cplace.downcast_variant(fx, variant);
715 pub fn trans_operand<'tcx>(
716 fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
717 operand: &Operand<'tcx>,
720 Operand::Move(place) | Operand::Copy(place) => {
721 let cplace = trans_place(fx, place);
724 Operand::Constant(const_) => crate::constant::trans_constant(fx, const_),