1 use rustc::ty::adjustment::PointerCast;
5 pub fn trans_fn<'clif, 'tcx, B: Backend + 'static>(
6 cx: &mut crate::CodegenCx<'clif, 'tcx, B>,
7 instance: Instance<'tcx>,
12 let mir = tcx.instance_mir(instance.def);
15 let (name, sig) = get_function_name_and_sig(tcx, instance, false);
16 let func_id = cx.module.declare_function(&name, linkage, &sig).unwrap();
17 let mut debug_context = cx
20 .map(|debug_context| FunctionDebugContext::new(tcx, debug_context, mir, &name, &sig));
22 // FIXME reuse Function and FunctionBuilder between multiple trans_fn calls
23 let mut bcx = FunctionBuilder::new(Function::with_name_signature(ExternalName::user(0, 0), sig));
26 let start_ebb = bcx.create_ebb();
27 let mut ebb_map: HashMap<BasicBlock, Ebb> = HashMap::new();
28 for (bb, _bb_data) in mir.basic_blocks().iter_enumerated() {
29 ebb_map.insert(bb, bcx.create_ebb());
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 {
46 local_map: HashMap::new(),
49 constants_cx: &mut cx.constants_cx,
50 caches: &mut cx.caches,
51 source_info_set: indexmap::IndexSet::new(),
54 with_unimpl_span(fx.mir.span, || {
55 crate::abi::codegen_fn_prelude(&mut fx, start_ebb);
56 codegen_fn_content(&mut fx);
59 fx.bcx.seal_all_blocks();
60 let func = fx.bcx.finalize();
62 // Recover all necessary data from fx, before accessing func will prevent future access to it.
63 let instance = fx.instance;
64 let clif_comments = fx.clif_comments;
65 let source_info_set = fx.source_info_set;
67 #[cfg(debug_assertions)]
68 crate::pretty_clif::write_clif_file(cx.tcx, "unopt", instance, &func, &clif_comments, None);
71 verify_func(tcx, &clif_comments, &func);
74 let context = &mut cx.caches.context;
76 cx.module.define_function(func_id, context).unwrap();
78 let value_ranges = context
79 .build_value_labels_ranges(cx.module.isa())
80 .expect("value location ranges");
82 // Write optimized function to file for debugging
83 #[cfg(debug_assertions)]
84 crate::pretty_clif::write_clif_file(
93 // Define debuginfo for function
94 let isa = cx.module.isa();
97 .map(|x| x.define(tcx, context, isa, &source_info_set));
99 // Clear context to make it usable for the next function
103 fn verify_func(tcx: TyCtxt, writer: &crate::pretty_clif::CommentWriter, func: &Function) {
104 let flags = settings::Flags::new(settings::builder());
105 match ::cranelift::codegen::verify_function(&func, &flags) {
108 tcx.sess.err(&format!("{:?}", err));
109 let pretty_error = ::cranelift::codegen::print_errors::pretty_verifier_error(
112 Some(Box::new(writer)),
116 .fatal(&format!("cranelift verify error:\n{}", pretty_error));
121 fn codegen_fn_content(fx: &mut FunctionCx<'_, '_, impl Backend>) {
122 for (bb, bb_data) in fx.mir.basic_blocks().iter_enumerated() {
123 if bb_data.is_cleanup {
124 // Unwinding after panicking is not supported
128 let ebb = fx.get_ebb(bb);
129 fx.bcx.switch_to_block(ebb);
132 for stmt in &bb_data.statements {
133 fx.set_debug_loc(stmt.source_info);
134 trans_stmt(fx, ebb, stmt);
137 #[cfg(debug_assertions)]
139 let mut terminator_head = "\n".to_string();
143 .fmt_head(&mut terminator_head)
145 let inst = fx.bcx.func.layout.last_inst(ebb).unwrap();
146 fx.add_comment(inst, terminator_head);
149 fx.set_debug_loc(bb_data.terminator().source_info);
151 match &bb_data.terminator().kind {
152 TerminatorKind::Goto { target } => {
153 let ebb = fx.get_ebb(*target);
154 fx.bcx.ins().jump(ebb, &[]);
156 TerminatorKind::Return => {
157 crate::abi::codegen_return(fx);
159 TerminatorKind::Assert {
166 if !fx.tcx.sess.overflow_checks() {
167 if let mir::interpret::PanicInfo::OverflowNeg = *msg {
168 let target = fx.get_ebb(*target);
169 fx.bcx.ins().jump(target, &[]);
173 let cond = trans_operand(fx, cond).load_scalar(fx);
174 // TODO HACK brz/brnz for i8/i16 is not yet implemented
175 let cond = fx.bcx.ins().uextend(types::I32, cond);
176 let target = fx.get_ebb(*target);
178 fx.bcx.ins().brnz(cond, target, &[]);
180 fx.bcx.ins().brz(cond, target, &[]);
185 "[panic] Assert {:?} at {:?} failed.",
187 bb_data.terminator().source_info.span
192 TerminatorKind::SwitchInt {
198 let discr = trans_operand(fx, discr).load_scalar(fx);
199 let mut switch = ::cranelift::frontend::Switch::new();
200 for (i, value) in values.iter().enumerate() {
201 let ebb = fx.get_ebb(targets[i]);
202 switch.set_entry(*value as u64, ebb);
204 let otherwise_ebb = fx.get_ebb(targets[targets.len() - 1]);
205 switch.emit(&mut fx.bcx, discr, otherwise_ebb);
207 TerminatorKind::Call {
214 crate::abi::codegen_terminator_call(fx, func, args, destination);
216 TerminatorKind::Resume | TerminatorKind::Abort => {
217 trap_unreachable(fx, "[corruption] Unwinding bb reached.");
219 TerminatorKind::Unreachable => {
220 trap_unreachable(fx, "[corruption] Hit unreachable code.");
222 TerminatorKind::Yield { .. }
223 | TerminatorKind::FalseEdges { .. }
224 | TerminatorKind::FalseUnwind { .. }
225 | TerminatorKind::DropAndReplace { .. }
226 | TerminatorKind::GeneratorDrop => {
227 bug!("shouldn't exist at trans {:?}", bb_data.terminator());
229 TerminatorKind::Drop {
234 let drop_place = trans_place(fx, location);
235 crate::abi::codegen_drop(fx, drop_place);
237 let target_ebb = fx.get_ebb(*target);
238 fx.bcx.ins().jump(target_ebb, &[]);
245 fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
247 stmt: &Statement<'tcx>,
249 let _print_guard = PrintOnPanic(|| format!("stmt {:?}", stmt));
251 fx.set_debug_loc(stmt.source_info);
253 #[cfg(debug_assertions)]
255 StatementKind::StorageLive(..) | StatementKind::StorageDead(..) => {} // Those are not very useful
257 let inst = fx.bcx.func.layout.last_inst(cur_ebb).unwrap();
258 fx.add_comment(inst, format!("{:?}", stmt));
263 StatementKind::SetDiscriminant {
267 let place = trans_place(fx, place);
268 crate::discriminant::codegen_set_discriminant(fx, place, *variant_index);
270 StatementKind::Assign(to_place_and_rval) => {
271 let lval = trans_place(fx, &to_place_and_rval.0);
272 let dest_layout = lval.layout();
273 match &to_place_and_rval.1 {
274 Rvalue::Use(operand) => {
275 let val = trans_operand(fx, operand);
276 lval.write_cvalue(fx, val);
278 Rvalue::Ref(_, _, place) => {
279 let place = trans_place(fx, place);
280 place.write_place_ref(fx, lval);
282 Rvalue::BinaryOp(bin_op, lhs, rhs) => {
283 let lhs = trans_operand(fx, lhs);
284 let rhs = trans_operand(fx, rhs);
286 let res = crate::num::codegen_binop(fx, *bin_op, lhs, rhs);
287 lval.write_cvalue(fx, res);
289 Rvalue::CheckedBinaryOp(bin_op, lhs, rhs) => {
290 let lhs = trans_operand(fx, lhs);
291 let rhs = trans_operand(fx, rhs);
293 let res = if !fx.tcx.sess.overflow_checks() {
295 crate::num::trans_int_binop(fx, *bin_op, lhs, rhs).load_scalar(fx);
296 let is_overflow = fx.bcx.ins().iconst(types::I8, 0);
297 CValue::by_val_pair(val, is_overflow, lval.layout())
299 crate::num::trans_checked_int_binop(fx, *bin_op, lhs, rhs)
302 lval.write_cvalue(fx, res);
304 Rvalue::UnaryOp(un_op, operand) => {
305 let operand = trans_operand(fx, operand);
306 let layout = operand.layout();
307 let val = operand.load_scalar(fx);
308 let res = match un_op {
310 match layout.ty.kind {
312 let val = fx.bcx.ins().uextend(types::I32, val); // WORKAROUND for CraneStation/cranelift#466
313 let res = fx.bcx.ins().icmp_imm(IntCC::Equal, val, 0);
314 fx.bcx.ins().bint(types::I8, res)
316 ty::Uint(_) | ty::Int(_) => fx.bcx.ins().bnot(val),
317 _ => unimplemented!("un op Not for {:?}", layout.ty),
320 UnOp::Neg => match layout.ty.kind {
322 let clif_ty = fx.clif_type(layout.ty).unwrap();
323 if clif_ty == types::I128 {
324 // FIXME implement it
325 crate::trap::trap_unreachable_ret_value(
328 "i128 neg is not yet supported",
332 let zero = fx.bcx.ins().iconst(clif_ty, 0);
333 fx.bcx.ins().isub(zero, val)
336 ty::Float(_) => fx.bcx.ins().fneg(val),
337 _ => unimplemented!("un op Neg for {:?}", layout.ty),
340 lval.write_cvalue(fx, CValue::by_val(res, layout));
342 Rvalue::Cast(CastKind::Pointer(PointerCast::ReifyFnPointer), operand, ty) => {
343 let layout = fx.layout_of(ty);
345 .monomorphize(&operand.ty(&fx.mir.local_decls, fx.tcx))
348 ty::FnDef(def_id, substs) => {
349 let func_ref = fx.get_function_ref(
350 Instance::resolve(fx.tcx, ParamEnv::reveal_all(), def_id, substs)
353 let func_addr = fx.bcx.ins().func_addr(fx.pointer_type, func_ref);
354 lval.write_cvalue(fx, CValue::by_val(func_addr, layout));
356 _ => bug!("Trying to ReifyFnPointer on non FnDef {:?}", ty),
359 Rvalue::Cast(CastKind::Pointer(PointerCast::UnsafeFnPointer), operand, ty)
360 | Rvalue::Cast(CastKind::Pointer(PointerCast::MutToConstPointer), operand, ty) => {
361 let operand = trans_operand(fx, operand);
362 let layout = fx.layout_of(ty);
363 lval.write_cvalue(fx, operand.unchecked_cast_to(layout));
365 Rvalue::Cast(CastKind::Misc, operand, to_ty) => {
366 let operand = trans_operand(fx, operand);
367 let from_ty = operand.layout().ty;
368 let to_ty = fx.monomorphize(to_ty);
371 fx: &FunctionCx<'_, 'tcx, impl Backend>,
374 ty.builtin_deref(true)
379 }| has_ptr_meta(fx.tcx, pointee_ty),
384 if is_fat_ptr(fx, from_ty) {
385 if is_fat_ptr(fx, to_ty) {
386 // fat-ptr -> fat-ptr
387 lval.write_cvalue(fx, operand.unchecked_cast_to(dest_layout));
389 // fat-ptr -> thin-ptr
390 let (ptr, _extra) = operand.load_scalar_pair(fx);
391 lval.write_cvalue(fx, CValue::by_val(ptr, dest_layout))
393 } else if let ty::Adt(adt_def, _substs) = from_ty.kind {
394 // enum -> discriminant value
395 assert!(adt_def.is_enum());
397 ty::Uint(_) | ty::Int(_) => {}
398 _ => unreachable!("cast adt {} -> {}", from_ty, to_ty),
401 let discr = crate::discriminant::codegen_get_discriminant(
406 lval.write_cvalue(fx, discr);
408 let to_clif_ty = fx.clif_type(to_ty).unwrap();
409 let from = operand.load_scalar(fx);
411 let res = clif_int_or_float_cast(
418 lval.write_cvalue(fx, CValue::by_val(res, dest_layout));
421 Rvalue::Cast(CastKind::Pointer(PointerCast::ClosureFnPointer(_)), operand, _ty) => {
422 let operand = trans_operand(fx, operand);
423 match operand.layout().ty.kind {
424 ty::Closure(def_id, substs) => {
425 let instance = Instance::resolve_closure(
429 ty::ClosureKind::FnOnce,
431 let func_ref = fx.get_function_ref(instance);
432 let func_addr = fx.bcx.ins().func_addr(fx.pointer_type, func_ref);
433 lval.write_cvalue(fx, CValue::by_val(func_addr, lval.layout()));
435 _ => bug!("{} cannot be cast to a fn ptr", operand.layout().ty),
438 Rvalue::Cast(CastKind::Pointer(PointerCast::Unsize), operand, _ty) => {
439 let operand = trans_operand(fx, operand);
440 operand.unsize_value(fx, lval);
442 Rvalue::Discriminant(place) => {
443 let place = trans_place(fx, place);
444 let value = place.to_cvalue(fx);
446 crate::discriminant::codegen_get_discriminant(fx, value, dest_layout);
447 lval.write_cvalue(fx, discr);
449 Rvalue::Repeat(operand, times) => {
450 let operand = trans_operand(fx, operand);
452 let index = fx.bcx.ins().iconst(fx.pointer_type, i as i64);
453 let to = lval.place_index(fx, index);
454 to.write_cvalue(fx, operand);
457 Rvalue::Len(place) => {
458 let place = trans_place(fx, place);
459 let usize_layout = fx.layout_of(fx.tcx.types.usize);
460 let len = codegen_array_len(fx, place);
461 lval.write_cvalue(fx, CValue::by_val(len, usize_layout));
463 Rvalue::NullaryOp(NullOp::Box, content_ty) => {
464 use rustc::middle::lang_items::ExchangeMallocFnLangItem;
466 let usize_type = fx.clif_type(fx.tcx.types.usize).unwrap();
467 let layout = fx.layout_of(content_ty);
468 let llsize = fx.bcx.ins().iconst(usize_type, layout.size.bytes() as i64);
472 .iconst(usize_type, layout.align.abi.bytes() as i64);
473 let box_layout = fx.layout_of(fx.tcx.mk_box(content_ty));
476 let def_id = match fx.tcx.lang_items().require(ExchangeMallocFnLangItem) {
481 .fatal(&format!("allocation of `{}` {}", box_layout.ty, s));
484 let instance = ty::Instance::mono(fx.tcx, def_id);
485 let func_ref = fx.get_function_ref(instance);
486 let call = fx.bcx.ins().call(func_ref, &[llsize, llalign]);
487 let ptr = fx.bcx.inst_results(call)[0];
488 lval.write_cvalue(fx, CValue::by_val(ptr, box_layout));
490 Rvalue::NullaryOp(NullOp::SizeOf, ty) => {
494 .is_sized(fx.tcx.at(DUMMY_SP), ParamEnv::reveal_all()));
495 let ty_size = fx.layout_of(ty).size.bytes();
496 let val = CValue::const_val(fx, fx.tcx.types.usize, ty_size.into());
497 lval.write_cvalue(fx, val);
499 Rvalue::Aggregate(kind, operands) => match **kind {
500 AggregateKind::Array(_ty) => {
501 for (i, operand) in operands.into_iter().enumerate() {
502 let operand = trans_operand(fx, operand);
503 let index = fx.bcx.ins().iconst(fx.pointer_type, i as i64);
504 let to = lval.place_index(fx, index);
505 to.write_cvalue(fx, operand);
508 _ => unimpl!("shouldn't exist at trans {:?}", to_place_and_rval.1),
512 StatementKind::StorageLive(_)
513 | StatementKind::StorageDead(_)
515 | StatementKind::FakeRead(..)
516 | StatementKind::Retag { .. }
517 | StatementKind::AscribeUserType(..) => {}
519 StatementKind::InlineAsm(asm) => {
520 use syntax::ast::Name;
526 let rustc::hir::InlineAsm {
527 asm: asm_code, // Name
528 outputs, // Vec<Name>
530 clobbers, // Vec<Name>
533 dialect: _, // syntax::ast::AsmDialect
536 match &*asm_code.as_str() {
537 "cpuid" | "cpuid\n" => {
538 assert_eq!(inputs, &[Name::intern("{eax}"), Name::intern("{ecx}")]);
540 assert_eq!(outputs.len(), 4);
541 for (i, c) in (&["={eax}", "={ebx}", "={ecx}", "={edx}"])
545 assert_eq!(&outputs[i].constraint.as_str(), c);
546 assert!(!outputs[i].is_rw);
547 assert!(!outputs[i].is_indirect);
550 assert_eq!(clobbers, &[Name::intern("rbx")]);
553 assert!(!alignstack);
555 crate::trap::trap_unimplemented(
557 "__cpuid_count arch intrinsic is not supported",
561 assert_eq!(inputs, &[Name::intern("{ecx}")]);
563 assert_eq!(outputs.len(), 2);
564 for (i, c) in (&["={eax}", "={edx}"]).iter().enumerate() {
565 assert_eq!(&outputs[i].constraint.as_str(), c);
566 assert!(!outputs[i].is_rw);
567 assert!(!outputs[i].is_indirect);
570 assert_eq!(clobbers, &[]);
573 assert!(!alignstack);
575 crate::trap::trap_unimplemented(fx, "_xgetbv arch intrinsic is not supported");
577 _ if fx.tcx.symbol_name(fx.instance).name.as_str() == "__rust_probestack" => {
578 crate::trap::trap_unimplemented(fx, "__rust_probestack is not supported");
580 _ => unimpl!("Inline assembly is not supported"),
586 fn codegen_array_len<'tcx>(
587 fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
590 match place.layout().ty.kind {
591 ty::Array(_elem_ty, len) => {
592 let len = crate::constant::force_eval_const(fx, len)
593 .eval_usize(fx.tcx, ParamEnv::reveal_all()) as i64;
594 fx.bcx.ins().iconst(fx.pointer_type, len)
596 ty::Slice(_elem_ty) => place
597 .to_addr_maybe_unsized(fx)
599 .expect("Length metadata for slice place"),
600 _ => bug!("Rvalue::Len({:?})", place),
604 pub fn trans_place<'tcx>(
605 fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
608 let mut cplace = match &place.base {
609 PlaceBase::Local(local) => fx.get_local_place(*local),
610 PlaceBase::Static(static_) => match static_.kind {
611 StaticKind::Static => {
612 crate::constant::codegen_static_ref(fx, static_.def_id, static_.ty)
614 StaticKind::Promoted(promoted, substs) => {
615 let instance = Instance::new(static_.def_id, fx.monomorphize(&substs));
616 crate::constant::trans_promoted(fx, instance, promoted, static_.ty)
621 for elem in &*place.projection {
623 PlaceElem::Deref => {
624 cplace = cplace.place_deref(fx);
626 PlaceElem::Field(field, _ty) => {
627 cplace = cplace.place_field(fx, field);
629 PlaceElem::Index(local) => {
630 let index = fx.get_local_place(local).to_cvalue(fx).load_scalar(fx);
631 cplace = cplace.place_index(fx, index);
633 PlaceElem::ConstantIndex {
638 let index = if !from_end {
639 fx.bcx.ins().iconst(fx.pointer_type, offset as i64)
641 let len = codegen_array_len(fx, cplace);
642 fx.bcx.ins().iadd_imm(len, -(offset as i64))
644 cplace = cplace.place_index(fx, index);
646 PlaceElem::Subslice { from, to } => {
647 // These indices are generated by slice patterns.
648 // slice[from:-to] in Python terms.
650 match cplace.layout().ty.kind {
651 ty::Array(elem_ty, len) => {
652 let elem_layout = fx.layout_of(elem_ty);
653 let ptr = cplace.to_addr(fx);
654 let len = crate::constant::force_eval_const(fx, len)
655 .eval_usize(fx.tcx, ParamEnv::reveal_all());
656 cplace = CPlace::for_addr(
659 .iadd_imm(ptr, elem_layout.size.bytes() as i64 * from as i64),
660 fx.layout_of(fx.tcx.mk_array(elem_ty, len - from as u64 - to as u64)),
663 ty::Slice(elem_ty) => {
664 let elem_layout = fx.layout_of(elem_ty);
665 let (ptr, len) = cplace.to_addr_maybe_unsized(fx);
666 let len = len.unwrap();
667 cplace = CPlace::for_addr_with_extra(
670 .iadd_imm(ptr, elem_layout.size.bytes() as i64 * from as i64),
671 fx.bcx.ins().iadd_imm(len, -(from as i64 + to as i64)),
678 PlaceElem::Downcast(_adt_def, variant) => {
679 cplace = cplace.downcast_variant(fx, variant);
687 pub fn trans_operand<'tcx>(
688 fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
689 operand: &Operand<'tcx>,
692 Operand::Move(place) | Operand::Copy(place) => {
693 let cplace = trans_place(fx, place);
696 Operand::Constant(const_) => crate::constant::trans_constant(fx, const_),