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 mut func = Function::with_name_signature(ExternalName::user(0, 0), sig);
25 func.collect_debug_info();
26 let mut func_ctx = FunctionBuilderContext::new();
27 let mut bcx = FunctionBuilder::new(&mut func, &mut func_ctx);
30 let start_ebb = bcx.create_ebb();
31 let ebb_map: IndexVec<BasicBlock, Ebb> = (0..mir.basic_blocks().len()).map(|_| bcx.create_ebb()).collect();
34 let pointer_type = cx.module.target_config().pointer_type();
35 let clif_comments = crate::pretty_clif::CommentWriter::new(tcx, instance);
37 let mut fx = FunctionCx {
47 local_map: HashMap::new(),
50 constants_cx: &mut cx.constants_cx,
51 caches: &mut cx.caches,
52 source_info_set: indexmap::IndexSet::new(),
55 if fx.mir.args_iter().any(|arg| fx.layout_of(fx.monomorphize(&fx.mir.local_decls[arg].ty)).abi.is_uninhabited()) {
56 let entry_block = fx.bcx.create_ebb();
57 fx.bcx.append_ebb_params_for_function_params(entry_block);
58 fx.bcx.switch_to_block(entry_block);
59 crate::trap::trap_unreachable(&mut fx, "function has uninhabited argument");
61 crate::abi::codegen_fn_prelude(&mut fx, start_ebb);
62 codegen_fn_content(&mut fx);
65 // Recover all necessary data from fx, before accessing func will prevent future access to it.
66 let instance = fx.instance;
67 let mut clif_comments = fx.clif_comments;
68 let source_info_set = fx.source_info_set;
69 let local_map = fx.local_map;
71 #[cfg(debug_assertions)]
72 crate::pretty_clif::write_clif_file(cx.tcx, "unopt", instance, &func, &clif_comments, None);
75 verify_func(tcx, &clif_comments, &func);
77 let context = &mut cx.caches.context;
80 // Perform rust specific optimizations
81 crate::optimize::optimize_function(cx.tcx, instance, context, &mut clif_comments);
84 cx.module.define_function(func_id, context).unwrap();
86 // Write optimized function to file for debugging
87 #[cfg(debug_assertions)]
89 let value_ranges = context
90 .build_value_labels_ranges(cx.module.isa())
91 .expect("value location ranges");
93 crate::pretty_clif::write_clif_file(
103 // Define debuginfo for function
104 let isa = cx.module.isa();
107 .map(|x| x.define(context, isa, &source_info_set, local_map));
109 // Clear context to make it usable for the next function
113 pub fn verify_func(tcx: TyCtxt, writer: &crate::pretty_clif::CommentWriter, func: &Function) {
114 let flags = settings::Flags::new(settings::builder());
115 match ::cranelift_codegen::verify_function(&func, &flags) {
118 tcx.sess.err(&format!("{:?}", err));
119 let pretty_error = ::cranelift_codegen::print_errors::pretty_verifier_error(
122 Some(Box::new(writer)),
126 .fatal(&format!("cranelift verify error:\n{}", pretty_error));
131 fn codegen_fn_content(fx: &mut FunctionCx<'_, '_, impl Backend>) {
132 for (bb, bb_data) in fx.mir.basic_blocks().iter_enumerated() {
133 if bb_data.is_cleanup {
134 // Unwinding after panicking is not supported
138 let ebb = fx.get_ebb(bb);
139 fx.bcx.switch_to_block(ebb);
142 for stmt in &bb_data.statements {
143 fx.set_debug_loc(stmt.source_info);
144 trans_stmt(fx, ebb, stmt);
147 #[cfg(debug_assertions)]
149 let mut terminator_head = "\n".to_string();
153 .fmt_head(&mut terminator_head)
155 let inst = fx.bcx.func.layout.last_inst(ebb).unwrap();
156 fx.add_comment(inst, terminator_head);
159 fx.set_debug_loc(bb_data.terminator().source_info);
161 match &bb_data.terminator().kind {
162 TerminatorKind::Goto { target } => {
163 let ebb = fx.get_ebb(*target);
164 fx.bcx.ins().jump(ebb, &[]);
166 TerminatorKind::Return => {
167 crate::abi::codegen_return(fx);
169 TerminatorKind::Assert {
176 if !fx.tcx.sess.overflow_checks() {
177 if let mir::interpret::PanicInfo::OverflowNeg = *msg {
178 let target = fx.get_ebb(*target);
179 fx.bcx.ins().jump(target, &[]);
183 let cond = trans_operand(fx, cond).load_scalar(fx);
184 let target = fx.get_ebb(*target);
186 fx.bcx.ins().brnz(cond, target, &[]);
188 fx.bcx.ins().brz(cond, target, &[]);
193 "[panic] Assert {:?} at {:?} failed.",
195 bb_data.terminator().source_info.span
200 TerminatorKind::SwitchInt {
206 let discr = trans_operand(fx, discr).load_scalar(fx);
207 let mut switch = ::cranelift_frontend::Switch::new();
208 for (i, value) in values.iter().enumerate() {
209 let ebb = fx.get_ebb(targets[i]);
210 switch.set_entry(*value as u64, ebb);
212 let otherwise_ebb = fx.get_ebb(targets[targets.len() - 1]);
213 switch.emit(&mut fx.bcx, discr, otherwise_ebb);
215 TerminatorKind::Call {
222 crate::abi::codegen_terminator_call(
227 bb_data.terminator().source_info.span,
230 TerminatorKind::Resume | TerminatorKind::Abort => {
231 trap_unreachable(fx, "[corruption] Unwinding bb reached.");
233 TerminatorKind::Unreachable => {
234 trap_unreachable(fx, "[corruption] Hit unreachable code.");
236 TerminatorKind::Yield { .. }
237 | TerminatorKind::FalseEdges { .. }
238 | TerminatorKind::FalseUnwind { .. }
239 | TerminatorKind::DropAndReplace { .. }
240 | TerminatorKind::GeneratorDrop => {
241 bug!("shouldn't exist at trans {:?}", bb_data.terminator());
243 TerminatorKind::Drop {
248 let drop_place = trans_place(fx, location);
249 crate::abi::codegen_drop(fx, drop_place);
251 let target_ebb = fx.get_ebb(*target);
252 fx.bcx.ins().jump(target_ebb, &[]);
257 fx.bcx.seal_all_blocks();
262 fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
264 stmt: &Statement<'tcx>,
266 let _print_guard = PrintOnPanic(|| format!("stmt {:?}", stmt));
268 fx.set_debug_loc(stmt.source_info);
270 #[cfg(debug_assertions)]
272 StatementKind::StorageLive(..) | StatementKind::StorageDead(..) => {} // Those are not very useful
274 let inst = fx.bcx.func.layout.last_inst(cur_ebb).unwrap();
275 fx.add_comment(inst, format!("{:?}", stmt));
280 StatementKind::SetDiscriminant {
284 let place = trans_place(fx, place);
285 crate::discriminant::codegen_set_discriminant(fx, place, *variant_index);
287 StatementKind::Assign(to_place_and_rval) => {
288 let lval = trans_place(fx, &to_place_and_rval.0);
289 let dest_layout = lval.layout();
290 match &to_place_and_rval.1 {
291 Rvalue::Use(operand) => {
292 let val = trans_operand(fx, operand);
293 lval.write_cvalue(fx, val);
295 Rvalue::Ref(_, _, place) | Rvalue::AddressOf(_, place) => {
296 let place = trans_place(fx, place);
297 place.write_place_ref(fx, lval);
299 Rvalue::BinaryOp(bin_op, lhs, rhs) => {
300 let lhs = trans_operand(fx, lhs);
301 let rhs = trans_operand(fx, rhs);
303 let res = crate::num::codegen_binop(fx, *bin_op, lhs, rhs);
304 lval.write_cvalue(fx, res);
306 Rvalue::CheckedBinaryOp(bin_op, lhs, rhs) => {
307 let lhs = trans_operand(fx, lhs);
308 let rhs = trans_operand(fx, rhs);
310 let res = if !fx.tcx.sess.overflow_checks() {
312 crate::num::trans_int_binop(fx, *bin_op, lhs, rhs).load_scalar(fx);
313 let is_overflow = fx.bcx.ins().iconst(types::I8, 0);
314 CValue::by_val_pair(val, is_overflow, lval.layout())
316 crate::num::trans_checked_int_binop(fx, *bin_op, lhs, rhs)
319 lval.write_cvalue(fx, res);
321 Rvalue::UnaryOp(un_op, operand) => {
322 let operand = trans_operand(fx, operand);
323 let layout = operand.layout();
324 let val = operand.load_scalar(fx);
325 let res = match un_op {
327 match layout.ty.kind {
329 let val = fx.bcx.ins().uextend(types::I32, val); // WORKAROUND for CraneStation/cranelift#466
330 let res = fx.bcx.ins().icmp_imm(IntCC::Equal, val, 0);
331 CValue::by_val(fx.bcx.ins().bint(types::I8, res), layout)
333 ty::Uint(_) | ty::Int(_) => {
334 CValue::by_val(fx.bcx.ins().bnot(val), layout)
336 _ => unimplemented!("un op Not for {:?}", layout.ty),
339 UnOp::Neg => match layout.ty.kind {
341 let zero = CValue::const_val(fx, layout.ty, 0);
342 crate::num::trans_int_binop(fx, BinOp::Sub, zero, operand)
345 CValue::by_val(fx.bcx.ins().fneg(val), layout)
347 _ => unimplemented!("un op Neg for {:?}", layout.ty),
350 lval.write_cvalue(fx, res);
352 Rvalue::Cast(CastKind::Pointer(PointerCast::ReifyFnPointer), operand, to_ty) => {
353 let from_ty = fx.monomorphize(&operand.ty(&fx.mir.local_decls, fx.tcx));
354 let to_layout = fx.layout_of(fx.monomorphize(to_ty));
356 ty::FnDef(def_id, substs) => {
357 let func_ref = fx.get_function_ref(
358 Instance::resolve(fx.tcx, ParamEnv::reveal_all(), def_id, substs)
361 let func_addr = fx.bcx.ins().func_addr(fx.pointer_type, func_ref);
362 lval.write_cvalue(fx, CValue::by_val(func_addr, to_layout));
364 _ => bug!("Trying to ReifyFnPointer on non FnDef {:?}", from_ty),
367 Rvalue::Cast(CastKind::Pointer(PointerCast::UnsafeFnPointer), operand, to_ty)
368 | Rvalue::Cast(CastKind::Pointer(PointerCast::MutToConstPointer), operand, to_ty)
369 | Rvalue::Cast(CastKind::Pointer(PointerCast::ArrayToPointer), operand, to_ty) => {
370 let to_layout = fx.layout_of(fx.monomorphize(to_ty));
371 let operand = trans_operand(fx, operand);
372 lval.write_cvalue(fx, operand.unchecked_cast_to(to_layout));
374 Rvalue::Cast(CastKind::Misc, operand, to_ty) => {
375 let operand = trans_operand(fx, operand);
376 let from_ty = operand.layout().ty;
377 let to_ty = fx.monomorphize(to_ty);
380 fx: &FunctionCx<'_, 'tcx, impl Backend>,
383 ty.builtin_deref(true)
388 }| has_ptr_meta(fx.tcx, pointee_ty),
393 if is_fat_ptr(fx, from_ty) {
394 if is_fat_ptr(fx, to_ty) {
395 // fat-ptr -> fat-ptr
396 lval.write_cvalue(fx, operand.unchecked_cast_to(dest_layout));
398 // fat-ptr -> thin-ptr
399 let (ptr, _extra) = operand.load_scalar_pair(fx);
400 lval.write_cvalue(fx, CValue::by_val(ptr, dest_layout))
402 } else if let ty::Adt(adt_def, _substs) = from_ty.kind {
403 // enum -> discriminant value
404 assert!(adt_def.is_enum());
406 ty::Uint(_) | ty::Int(_) => {}
407 _ => unreachable!("cast adt {} -> {}", from_ty, to_ty),
410 let discr = crate::discriminant::codegen_get_discriminant(
415 lval.write_cvalue(fx, discr);
417 let to_clif_ty = fx.clif_type(to_ty).unwrap();
418 let from = operand.load_scalar(fx);
420 let res = clif_int_or_float_cast(
427 lval.write_cvalue(fx, CValue::by_val(res, dest_layout));
430 Rvalue::Cast(CastKind::Pointer(PointerCast::ClosureFnPointer(_)), operand, _to_ty) => {
431 let operand = trans_operand(fx, operand);
432 match operand.layout().ty.kind {
433 ty::Closure(def_id, substs) => {
434 let instance = Instance::resolve_closure(
438 ty::ClosureKind::FnOnce,
440 let func_ref = fx.get_function_ref(instance);
441 let func_addr = fx.bcx.ins().func_addr(fx.pointer_type, func_ref);
442 lval.write_cvalue(fx, CValue::by_val(func_addr, lval.layout()));
444 _ => bug!("{} cannot be cast to a fn ptr", operand.layout().ty),
447 Rvalue::Cast(CastKind::Pointer(PointerCast::Unsize), operand, _to_ty) => {
448 let operand = trans_operand(fx, operand);
449 operand.unsize_value(fx, lval);
451 Rvalue::Discriminant(place) => {
452 let place = trans_place(fx, place);
453 let value = place.to_cvalue(fx);
455 crate::discriminant::codegen_get_discriminant(fx, value, dest_layout);
456 lval.write_cvalue(fx, discr);
458 Rvalue::Repeat(operand, times) => {
459 let operand = trans_operand(fx, operand);
461 let index = fx.bcx.ins().iconst(fx.pointer_type, i as i64);
462 let to = lval.place_index(fx, index);
463 to.write_cvalue(fx, operand);
466 Rvalue::Len(place) => {
467 let place = trans_place(fx, place);
468 let usize_layout = fx.layout_of(fx.tcx.types.usize);
469 let len = codegen_array_len(fx, place);
470 lval.write_cvalue(fx, CValue::by_val(len, usize_layout));
472 Rvalue::NullaryOp(NullOp::Box, content_ty) => {
473 use rustc::middle::lang_items::ExchangeMallocFnLangItem;
475 let usize_type = fx.clif_type(fx.tcx.types.usize).unwrap();
476 let content_ty = fx.monomorphize(content_ty);
477 let layout = fx.layout_of(content_ty);
478 let llsize = fx.bcx.ins().iconst(usize_type, layout.size.bytes() as i64);
482 .iconst(usize_type, layout.align.abi.bytes() as i64);
483 let box_layout = fx.layout_of(fx.tcx.mk_box(content_ty));
486 let def_id = match fx.tcx.lang_items().require(ExchangeMallocFnLangItem) {
491 .fatal(&format!("allocation of `{}` {}", box_layout.ty, s));
494 let instance = ty::Instance::mono(fx.tcx, def_id);
495 let func_ref = fx.get_function_ref(instance);
496 let call = fx.bcx.ins().call(func_ref, &[llsize, llalign]);
497 let ptr = fx.bcx.inst_results(call)[0];
498 lval.write_cvalue(fx, CValue::by_val(ptr, box_layout));
500 Rvalue::NullaryOp(NullOp::SizeOf, ty) => {
504 .is_sized(fx.tcx.at(DUMMY_SP), ParamEnv::reveal_all()));
505 let ty_size = fx.layout_of(fx.monomorphize(ty)).size.bytes();
506 let val = CValue::const_val(fx, fx.tcx.types.usize, ty_size.into());
507 lval.write_cvalue(fx, val);
509 Rvalue::Aggregate(kind, operands) => match **kind {
510 AggregateKind::Array(_ty) => {
511 for (i, operand) in operands.into_iter().enumerate() {
512 let operand = trans_operand(fx, operand);
513 let index = fx.bcx.ins().iconst(fx.pointer_type, i as i64);
514 let to = lval.place_index(fx, index);
515 to.write_cvalue(fx, operand);
518 _ => unreachable!("shouldn't exist at trans {:?}", to_place_and_rval.1),
522 StatementKind::StorageLive(_)
523 | StatementKind::StorageDead(_)
525 | StatementKind::FakeRead(..)
526 | StatementKind::Retag { .. }
527 | StatementKind::AscribeUserType(..) => {}
529 StatementKind::InlineAsm(asm) => {
530 use syntax::ast::Name;
536 let rustc::hir::InlineAsmInner {
537 asm: asm_code, // Name
538 outputs, // Vec<Name>
540 clobbers, // Vec<Name>
543 dialect: _, // syntax::ast::AsmDialect
546 match &*asm_code.as_str() {
548 assert_eq!(inputs, &[Name::intern("r")]);
549 assert!(outputs.is_empty(), "{:?}", outputs);
553 "cpuid" | "cpuid\n" => {
554 assert_eq!(inputs, &[Name::intern("{eax}"), Name::intern("{ecx}")]);
556 assert_eq!(outputs.len(), 4);
557 for (i, c) in (&["={eax}", "={ebx}", "={ecx}", "={edx}"])
561 assert_eq!(&outputs[i].constraint.as_str(), c);
562 assert!(!outputs[i].is_rw);
563 assert!(!outputs[i].is_indirect);
566 assert_eq!(clobbers, &[Name::intern("rbx")]);
569 assert!(!alignstack);
571 crate::trap::trap_unimplemented(
573 "__cpuid_count arch intrinsic is not supported",
577 assert_eq!(inputs, &[Name::intern("{ecx}")]);
579 assert_eq!(outputs.len(), 2);
580 for (i, c) in (&["={eax}", "={edx}"]).iter().enumerate() {
581 assert_eq!(&outputs[i].constraint.as_str(), c);
582 assert!(!outputs[i].is_rw);
583 assert!(!outputs[i].is_indirect);
586 assert_eq!(clobbers, &[]);
589 assert!(!alignstack);
591 crate::trap::trap_unimplemented(fx, "_xgetbv arch intrinsic is not supported");
593 _ if fx.tcx.symbol_name(fx.instance).name.as_str() == "__rust_probestack" => {
594 crate::trap::trap_unimplemented(fx, "__rust_probestack is not supported");
596 _ => unimpl!("Inline assembly is not supported"),
602 fn codegen_array_len<'tcx>(
603 fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
606 match place.layout().ty.kind {
607 ty::Array(_elem_ty, len) => {
608 let len = crate::constant::force_eval_const(fx, len)
609 .eval_usize(fx.tcx, ParamEnv::reveal_all()) as i64;
610 fx.bcx.ins().iconst(fx.pointer_type, len)
612 ty::Slice(_elem_ty) => place
613 .to_ptr_maybe_unsized(fx)
615 .expect("Length metadata for slice place"),
616 _ => bug!("Rvalue::Len({:?})", place),
620 pub fn trans_place<'tcx>(
621 fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
624 let mut cplace = match &place.base {
625 PlaceBase::Local(local) => fx.get_local_place(*local),
626 PlaceBase::Static(static_) => match static_.kind {
627 StaticKind::Static => {
628 // Statics can't be generic, so `static_.ty` doesn't need to be monomorphized.
629 crate::constant::codegen_static_ref(fx, static_.def_id, static_.ty)
631 StaticKind::Promoted(promoted, substs) => {
632 let instance = Instance::new(static_.def_id, fx.monomorphize(&substs));
633 let ty = fx.monomorphize(&static_.ty);
634 crate::constant::trans_promoted(fx, instance, promoted, ty)
639 for elem in &*place.projection {
641 PlaceElem::Deref => {
642 cplace = cplace.place_deref(fx);
644 PlaceElem::Field(field, _ty) => {
645 cplace = cplace.place_field(fx, field);
647 PlaceElem::Index(local) => {
648 let index = fx.get_local_place(local).to_cvalue(fx).load_scalar(fx);
649 cplace = cplace.place_index(fx, index);
651 PlaceElem::ConstantIndex {
656 let index = if !from_end {
657 fx.bcx.ins().iconst(fx.pointer_type, offset as i64)
659 let len = codegen_array_len(fx, cplace);
660 fx.bcx.ins().iadd_imm(len, -(offset as i64))
662 cplace = cplace.place_index(fx, index);
664 PlaceElem::Subslice { from, to, from_end } => {
665 // These indices are generated by slice patterns.
666 // slice[from:-to] in Python terms.
668 match cplace.layout().ty.kind {
669 ty::Array(elem_ty, len) => {
670 let elem_layout = fx.layout_of(elem_ty);
671 let ptr = cplace.to_ptr(fx);
672 let len = crate::constant::force_eval_const(fx, len)
673 .eval_usize(fx.tcx, ParamEnv::reveal_all());
674 cplace = CPlace::for_ptr(
675 ptr.offset_i64(fx, elem_layout.size.bytes() as i64 * from as i64),
676 fx.layout_of(fx.tcx.mk_array(elem_ty, len - from as u64 - to as u64)),
679 ty::Slice(elem_ty) => {
680 assert!(from_end, "slice subslices should be `from_end`");
681 let elem_layout = fx.layout_of(elem_ty);
682 let (ptr, len) = cplace.to_ptr_maybe_unsized(fx);
683 let len = len.unwrap();
684 cplace = CPlace::for_ptr_with_extra(
685 ptr.offset_i64(fx, elem_layout.size.bytes() as i64 * from as i64),
686 fx.bcx.ins().iadd_imm(len, -(from as i64 + to as i64)),
693 PlaceElem::Downcast(_adt_def, variant) => {
694 cplace = cplace.downcast_variant(fx, variant);
702 pub fn trans_operand<'tcx>(
703 fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
704 operand: &Operand<'tcx>,
707 Operand::Move(place) | Operand::Copy(place) => {
708 let cplace = trans_place(fx, place);
711 Operand::Constant(const_) => crate::constant::trans_constant(fx, const_),