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>,
286 #[allow(unused_variables)]
288 stmt: &Statement<'tcx>,
290 let _print_guard = PrintOnPanic(|| format!("stmt {:?}", stmt));
292 fx.set_debug_loc(stmt.source_info);
294 #[cfg(false_debug_assertions)]
296 StatementKind::StorageLive(..) | StatementKind::StorageDead(..) => {} // Those are not very useful
298 let inst = fx.bcx.func.layout.last_inst(cur_block).unwrap();
299 fx.add_comment(inst, format!("{:?}", stmt));
304 StatementKind::SetDiscriminant {
308 let place = trans_place(fx, place);
309 crate::discriminant::codegen_set_discriminant(fx, place, *variant_index);
311 StatementKind::Assign(to_place_and_rval) => {
312 let lval = trans_place(fx, &to_place_and_rval.0);
313 let dest_layout = lval.layout();
314 match &to_place_and_rval.1 {
315 Rvalue::Use(operand) => {
316 let val = trans_operand(fx, operand);
317 lval.write_cvalue(fx, val);
319 Rvalue::Ref(_, _, place) | Rvalue::AddressOf(_, place) => {
320 let place = trans_place(fx, place);
321 place.write_place_ref(fx, lval);
323 Rvalue::BinaryOp(bin_op, lhs, rhs) => {
324 let lhs = trans_operand(fx, lhs);
325 let rhs = trans_operand(fx, rhs);
327 let res = crate::num::codegen_binop(fx, *bin_op, lhs, rhs);
328 lval.write_cvalue(fx, res);
330 Rvalue::CheckedBinaryOp(bin_op, lhs, rhs) => {
331 let lhs = trans_operand(fx, lhs);
332 let rhs = trans_operand(fx, rhs);
334 let res = if !fx.tcx.sess.overflow_checks() {
336 crate::num::trans_int_binop(fx, *bin_op, lhs, rhs).load_scalar(fx);
337 let is_overflow = fx.bcx.ins().iconst(types::I8, 0);
338 CValue::by_val_pair(val, is_overflow, lval.layout())
340 crate::num::trans_checked_int_binop(fx, *bin_op, lhs, rhs)
343 lval.write_cvalue(fx, res);
345 Rvalue::UnaryOp(un_op, operand) => {
346 let operand = trans_operand(fx, operand);
347 let layout = operand.layout();
348 let val = operand.load_scalar(fx);
349 let res = match un_op {
351 match layout.ty.kind {
353 let val = fx.bcx.ins().uextend(types::I32, val); // WORKAROUND for CraneStation/cranelift#466
354 let res = fx.bcx.ins().icmp_imm(IntCC::Equal, val, 0);
355 CValue::by_val(fx.bcx.ins().bint(types::I8, res), layout)
357 ty::Uint(_) | ty::Int(_) => {
358 CValue::by_val(fx.bcx.ins().bnot(val), layout)
360 _ => unreachable!("un op Not for {:?}", layout.ty),
363 UnOp::Neg => match layout.ty.kind {
364 ty::Int(IntTy::I128) => {
365 // FIXME remove this case once ineg.i128 works
366 let zero = CValue::const_val(fx, layout, 0);
367 crate::num::trans_int_binop(fx, BinOp::Sub, zero, operand)
370 CValue::by_val(fx.bcx.ins().ineg(val), layout)
373 CValue::by_val(fx.bcx.ins().fneg(val), layout)
375 _ => unreachable!("un op Neg for {:?}", layout.ty),
378 lval.write_cvalue(fx, res);
380 Rvalue::Cast(CastKind::Pointer(PointerCast::ReifyFnPointer), operand, to_ty) => {
381 let from_ty = fx.monomorphize(&operand.ty(&fx.mir.local_decls, fx.tcx));
382 let to_layout = fx.layout_of(fx.monomorphize(to_ty));
384 ty::FnDef(def_id, substs) => {
385 let func_ref = fx.get_function_ref(
386 Instance::resolve_for_fn_ptr(fx.tcx, ParamEnv::reveal_all(), def_id, substs)
389 let func_addr = fx.bcx.ins().func_addr(fx.pointer_type, func_ref);
390 lval.write_cvalue(fx, CValue::by_val(func_addr, to_layout));
392 _ => bug!("Trying to ReifyFnPointer on non FnDef {:?}", from_ty),
395 Rvalue::Cast(CastKind::Pointer(PointerCast::UnsafeFnPointer), operand, to_ty)
396 | Rvalue::Cast(CastKind::Pointer(PointerCast::MutToConstPointer), operand, to_ty)
397 | Rvalue::Cast(CastKind::Pointer(PointerCast::ArrayToPointer), operand, to_ty) => {
398 let to_layout = fx.layout_of(fx.monomorphize(to_ty));
399 let operand = trans_operand(fx, operand);
400 lval.write_cvalue(fx, operand.unchecked_cast_to(to_layout));
402 Rvalue::Cast(CastKind::Misc, operand, to_ty) => {
403 let operand = trans_operand(fx, operand);
404 let from_ty = operand.layout().ty;
405 let to_ty = fx.monomorphize(to_ty);
408 fx: &FunctionCx<'_, 'tcx, impl Backend>,
411 ty.builtin_deref(true)
416 }| has_ptr_meta(fx.tcx, pointee_ty),
421 if is_fat_ptr(fx, from_ty) {
422 if is_fat_ptr(fx, to_ty) {
423 // fat-ptr -> fat-ptr
424 lval.write_cvalue(fx, operand.unchecked_cast_to(dest_layout));
426 // fat-ptr -> thin-ptr
427 let (ptr, _extra) = operand.load_scalar_pair(fx);
428 lval.write_cvalue(fx, CValue::by_val(ptr, dest_layout))
430 } else if let ty::Adt(adt_def, _substs) = from_ty.kind {
431 // enum -> discriminant value
432 assert!(adt_def.is_enum());
434 ty::Uint(_) | ty::Int(_) => {}
435 _ => unreachable!("cast adt {} -> {}", from_ty, to_ty),
438 let discr = crate::discriminant::codegen_get_discriminant(
443 lval.write_cvalue(fx, discr);
445 let to_clif_ty = fx.clif_type(to_ty).unwrap();
446 let from = operand.load_scalar(fx);
448 let res = clif_int_or_float_cast(
455 lval.write_cvalue(fx, CValue::by_val(res, dest_layout));
458 Rvalue::Cast(CastKind::Pointer(PointerCast::ClosureFnPointer(_)), operand, _to_ty) => {
459 let operand = trans_operand(fx, operand);
460 match operand.layout().ty.kind {
461 ty::Closure(def_id, substs) => {
462 let instance = Instance::resolve_closure(
466 ty::ClosureKind::FnOnce,
468 let func_ref = fx.get_function_ref(instance);
469 let func_addr = fx.bcx.ins().func_addr(fx.pointer_type, func_ref);
470 lval.write_cvalue(fx, CValue::by_val(func_addr, lval.layout()));
472 _ => bug!("{} cannot be cast to a fn ptr", operand.layout().ty),
475 Rvalue::Cast(CastKind::Pointer(PointerCast::Unsize), operand, _to_ty) => {
476 let operand = trans_operand(fx, operand);
477 operand.unsize_value(fx, lval);
479 Rvalue::Discriminant(place) => {
480 let place = trans_place(fx, place);
481 let value = place.to_cvalue(fx);
483 crate::discriminant::codegen_get_discriminant(fx, value, dest_layout);
484 lval.write_cvalue(fx, discr);
486 Rvalue::Repeat(operand, times) => {
487 let operand = trans_operand(fx, operand);
489 let index = fx.bcx.ins().iconst(fx.pointer_type, i as i64);
490 let to = lval.place_index(fx, index);
491 to.write_cvalue(fx, operand);
494 Rvalue::Len(place) => {
495 let place = trans_place(fx, place);
496 let usize_layout = fx.layout_of(fx.tcx.types.usize);
497 let len = codegen_array_len(fx, place);
498 lval.write_cvalue(fx, CValue::by_val(len, usize_layout));
500 Rvalue::NullaryOp(NullOp::Box, content_ty) => {
501 use rustc::middle::lang_items::ExchangeMallocFnLangItem;
503 let usize_type = fx.clif_type(fx.tcx.types.usize).unwrap();
504 let content_ty = fx.monomorphize(content_ty);
505 let layout = fx.layout_of(content_ty);
506 let llsize = fx.bcx.ins().iconst(usize_type, layout.size.bytes() as i64);
510 .iconst(usize_type, layout.align.abi.bytes() as i64);
511 let box_layout = fx.layout_of(fx.tcx.mk_box(content_ty));
514 let def_id = match fx.tcx.lang_items().require(ExchangeMallocFnLangItem) {
519 .fatal(&format!("allocation of `{}` {}", box_layout.ty, s));
522 let instance = ty::Instance::mono(fx.tcx, def_id);
523 let func_ref = fx.get_function_ref(instance);
524 let call = fx.bcx.ins().call(func_ref, &[llsize, llalign]);
525 let ptr = fx.bcx.inst_results(call)[0];
526 lval.write_cvalue(fx, CValue::by_val(ptr, box_layout));
528 Rvalue::NullaryOp(NullOp::SizeOf, ty) => {
532 .is_sized(fx.tcx.at(stmt.source_info.span), ParamEnv::reveal_all()));
533 let ty_size = fx.layout_of(fx.monomorphize(ty)).size.bytes();
534 let val = CValue::const_val(fx, fx.layout_of(fx.tcx.types.usize), ty_size.into());
535 lval.write_cvalue(fx, val);
537 Rvalue::Aggregate(kind, operands) => match **kind {
538 AggregateKind::Array(_ty) => {
539 for (i, operand) in operands.into_iter().enumerate() {
540 let operand = trans_operand(fx, operand);
541 let index = fx.bcx.ins().iconst(fx.pointer_type, i as i64);
542 let to = lval.place_index(fx, index);
543 to.write_cvalue(fx, operand);
546 _ => unreachable!("shouldn't exist at trans {:?}", to_place_and_rval.1),
550 StatementKind::StorageLive(_)
551 | StatementKind::StorageDead(_)
553 | StatementKind::FakeRead(..)
554 | StatementKind::Retag { .. }
555 | StatementKind::AscribeUserType(..) => {}
557 StatementKind::InlineAsm(asm) => {
558 use syntax::ast::Name;
564 let rustc_hir::InlineAsmInner {
565 asm: asm_code, // Name
566 outputs, // Vec<Name>
568 clobbers, // Vec<Name>
571 dialect: _, // syntax::ast::AsmDialect
574 match &*asm_code.as_str() {
576 assert_eq!(inputs, &[Name::intern("r")]);
577 assert!(outputs.is_empty(), "{:?}", outputs);
581 "cpuid" | "cpuid\n" => {
582 assert_eq!(inputs, &[Name::intern("{eax}"), Name::intern("{ecx}")]);
584 assert_eq!(outputs.len(), 4);
585 for (i, c) in (&["={eax}", "={ebx}", "={ecx}", "={edx}"])
589 assert_eq!(&outputs[i].constraint.as_str(), c);
590 assert!(!outputs[i].is_rw);
591 assert!(!outputs[i].is_indirect);
594 assert_eq!(clobbers, &[Name::intern("rbx")]);
597 assert!(!alignstack);
599 crate::trap::trap_unimplemented(
601 "__cpuid_count arch intrinsic is not supported",
605 assert_eq!(inputs, &[Name::intern("{ecx}")]);
607 assert_eq!(outputs.len(), 2);
608 for (i, c) in (&["={eax}", "={edx}"]).iter().enumerate() {
609 assert_eq!(&outputs[i].constraint.as_str(), c);
610 assert!(!outputs[i].is_rw);
611 assert!(!outputs[i].is_indirect);
614 assert_eq!(clobbers, &[]);
617 assert!(!alignstack);
619 crate::trap::trap_unimplemented(fx, "_xgetbv arch intrinsic is not supported");
621 _ if fx.tcx.symbol_name(fx.instance).name.as_str() == "__rust_probestack" => {
622 crate::trap::trap_unimplemented(fx, "__rust_probestack is not supported");
624 _ => unimpl!("Inline assembly is not supported"),
630 fn codegen_array_len<'tcx>(
631 fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
634 match place.layout().ty.kind {
635 ty::Array(_elem_ty, len) => {
636 let len = fx.monomorphize(&len)
637 .eval(fx.tcx, ParamEnv::reveal_all())
638 .eval_usize(fx.tcx, ParamEnv::reveal_all()) as i64;
639 fx.bcx.ins().iconst(fx.pointer_type, len)
641 ty::Slice(_elem_ty) => place
642 .to_ptr_maybe_unsized(fx)
644 .expect("Length metadata for slice place"),
645 _ => bug!("Rvalue::Len({:?})", place),
649 pub fn trans_place<'tcx>(
650 fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
653 let mut cplace = fx.get_local_place(place.local);
655 for elem in &*place.projection {
657 PlaceElem::Deref => {
658 cplace = cplace.place_deref(fx);
660 PlaceElem::Field(field, _ty) => {
661 cplace = cplace.place_field(fx, field);
663 PlaceElem::Index(local) => {
664 let index = fx.get_local_place(local).to_cvalue(fx).load_scalar(fx);
665 cplace = cplace.place_index(fx, index);
667 PlaceElem::ConstantIndex {
672 let index = if !from_end {
673 fx.bcx.ins().iconst(fx.pointer_type, offset as i64)
675 let len = codegen_array_len(fx, cplace);
676 fx.bcx.ins().iadd_imm(len, -(offset as i64))
678 cplace = cplace.place_index(fx, index);
680 PlaceElem::Subslice { from, to, from_end } => {
681 // These indices are generated by slice patterns.
682 // slice[from:-to] in Python terms.
684 match cplace.layout().ty.kind {
685 ty::Array(elem_ty, _len) => {
686 assert!(!from_end, "array subslices are never `from_end`");
687 let elem_layout = fx.layout_of(elem_ty);
688 let ptr = cplace.to_ptr(fx);
689 cplace = CPlace::for_ptr(
690 ptr.offset_i64(fx, elem_layout.size.bytes() as i64 * from as i64),
691 fx.layout_of(fx.tcx.mk_array(elem_ty, to as u64 - from as u64)),
694 ty::Slice(elem_ty) => {
695 assert!(from_end, "slice subslices should be `from_end`");
696 let elem_layout = fx.layout_of(elem_ty);
697 let (ptr, len) = cplace.to_ptr_maybe_unsized(fx);
698 let len = len.unwrap();
699 cplace = CPlace::for_ptr_with_extra(
700 ptr.offset_i64(fx, elem_layout.size.bytes() as i64 * from as i64),
701 fx.bcx.ins().iadd_imm(len, -(from as i64 + to as i64)),
708 PlaceElem::Downcast(_adt_def, variant) => {
709 cplace = cplace.downcast_variant(fx, variant);
717 pub fn trans_operand<'tcx>(
718 fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
719 operand: &Operand<'tcx>,
722 Operand::Move(place) | Operand::Copy(place) => {
723 let cplace = trans_place(fx, place);
726 Operand::Constant(const_) => crate::constant::trans_constant(fx, const_),