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(debug_context, mir, func_id, &name, &sig));
22 // Make FunctionBuilder
23 let mut func = Function::with_name_signature(ExternalName::user(0, 0), sig);
24 func.collect_debug_info();
25 let mut func_ctx = FunctionBuilderContext::new();
26 let mut bcx = FunctionBuilder::new(&mut func, &mut func_ctx);
29 let start_ebb = bcx.create_ebb();
30 let mut ebb_map: HashMap<BasicBlock, Ebb> = HashMap::new();
31 for (bb, _bb_data) in mir.basic_blocks().iter_enumerated() {
32 ebb_map.insert(bb, bcx.create_ebb());
36 let pointer_type = cx.module.target_config().pointer_type();
37 let clif_comments = crate::pretty_clif::CommentWriter::new(tcx, instance);
39 let mut fx = FunctionCx {
49 local_map: HashMap::new(),
52 constants_cx: &mut cx.constants_cx,
53 caches: &mut cx.caches,
54 source_info_set: indexmap::IndexSet::new(),
57 crate::abi::codegen_fn_prelude(&mut fx, start_ebb);
58 codegen_fn_content(&mut fx);
60 // Recover all necessary data from fx, before accessing func will prevent future access to it.
61 let instance = fx.instance;
62 let clif_comments = fx.clif_comments;
63 let source_info_set = fx.source_info_set;
65 #[cfg(debug_assertions)]
66 crate::pretty_clif::write_clif_file(cx.tcx, "unopt", instance, &func, &clif_comments, None);
69 verify_func(tcx, &clif_comments, &func);
72 let context = &mut cx.caches.context;
74 cx.module.define_function(func_id, context).unwrap();
76 let value_ranges = context
77 .build_value_labels_ranges(cx.module.isa())
78 .expect("value location ranges");
80 // Write optimized function to file for debugging
81 #[cfg(debug_assertions)]
82 crate::pretty_clif::write_clif_file(
91 // Define debuginfo for function
92 let isa = cx.module.isa();
95 .map(|x| x.define(tcx, context, isa, &source_info_set));
97 // Clear context to make it usable for the next function
101 fn verify_func(tcx: TyCtxt, writer: &crate::pretty_clif::CommentWriter, func: &Function) {
102 let flags = settings::Flags::new(settings::builder());
103 match ::cranelift::codegen::verify_function(&func, &flags) {
106 tcx.sess.err(&format!("{:?}", err));
107 let pretty_error = ::cranelift::codegen::print_errors::pretty_verifier_error(
110 Some(Box::new(writer)),
114 .fatal(&format!("cranelift verify error:\n{}", pretty_error));
119 fn codegen_fn_content(fx: &mut FunctionCx<'_, '_, impl Backend>) {
120 for (bb, bb_data) in fx.mir.basic_blocks().iter_enumerated() {
121 if bb_data.is_cleanup {
122 // Unwinding after panicking is not supported
126 let ebb = fx.get_ebb(bb);
127 fx.bcx.switch_to_block(ebb);
130 for stmt in &bb_data.statements {
131 fx.set_debug_loc(stmt.source_info);
132 trans_stmt(fx, ebb, stmt);
135 #[cfg(debug_assertions)]
137 let mut terminator_head = "\n".to_string();
141 .fmt_head(&mut terminator_head)
143 let inst = fx.bcx.func.layout.last_inst(ebb).unwrap();
144 fx.add_comment(inst, terminator_head);
147 fx.set_debug_loc(bb_data.terminator().source_info);
149 match &bb_data.terminator().kind {
150 TerminatorKind::Goto { target } => {
151 let ebb = fx.get_ebb(*target);
152 fx.bcx.ins().jump(ebb, &[]);
154 TerminatorKind::Return => {
155 crate::abi::codegen_return(fx);
157 TerminatorKind::Assert {
164 if !fx.tcx.sess.overflow_checks() {
165 if let mir::interpret::PanicInfo::OverflowNeg = *msg {
166 let target = fx.get_ebb(*target);
167 fx.bcx.ins().jump(target, &[]);
171 let cond = trans_operand(fx, cond).load_scalar(fx);
172 let target = fx.get_ebb(*target);
174 fx.bcx.ins().brnz(cond, target, &[]);
176 fx.bcx.ins().brz(cond, target, &[]);
181 "[panic] Assert {:?} at {:?} failed.",
183 bb_data.terminator().source_info.span
188 TerminatorKind::SwitchInt {
194 let discr = trans_operand(fx, discr).load_scalar(fx);
195 let mut switch = ::cranelift::frontend::Switch::new();
196 for (i, value) in values.iter().enumerate() {
197 let ebb = fx.get_ebb(targets[i]);
198 switch.set_entry(*value as u64, ebb);
200 let otherwise_ebb = fx.get_ebb(targets[targets.len() - 1]);
201 switch.emit(&mut fx.bcx, discr, otherwise_ebb);
203 TerminatorKind::Call {
210 crate::abi::codegen_terminator_call(
215 bb_data.terminator().source_info.span,
218 TerminatorKind::Resume | TerminatorKind::Abort => {
219 trap_unreachable(fx, "[corruption] Unwinding bb reached.");
221 TerminatorKind::Unreachable => {
222 trap_unreachable(fx, "[corruption] Hit unreachable code.");
224 TerminatorKind::Yield { .. }
225 | TerminatorKind::FalseEdges { .. }
226 | TerminatorKind::FalseUnwind { .. }
227 | TerminatorKind::DropAndReplace { .. }
228 | TerminatorKind::GeneratorDrop => {
229 bug!("shouldn't exist at trans {:?}", bb_data.terminator());
231 TerminatorKind::Drop {
236 let drop_place = trans_place(fx, location);
237 crate::abi::codegen_drop(fx, drop_place);
239 let target_ebb = fx.get_ebb(*target);
240 fx.bcx.ins().jump(target_ebb, &[]);
245 fx.bcx.seal_all_blocks();
250 fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
252 stmt: &Statement<'tcx>,
254 let _print_guard = PrintOnPanic(|| format!("stmt {:?}", stmt));
256 fx.set_debug_loc(stmt.source_info);
258 #[cfg(debug_assertions)]
260 StatementKind::StorageLive(..) | StatementKind::StorageDead(..) => {} // Those are not very useful
262 let inst = fx.bcx.func.layout.last_inst(cur_ebb).unwrap();
263 fx.add_comment(inst, format!("{:?}", stmt));
268 StatementKind::SetDiscriminant {
272 let place = trans_place(fx, place);
273 crate::discriminant::codegen_set_discriminant(fx, place, *variant_index);
275 StatementKind::Assign(to_place_and_rval) => {
276 let lval = trans_place(fx, &to_place_and_rval.0);
277 let dest_layout = lval.layout();
278 match &to_place_and_rval.1 {
279 Rvalue::Use(operand) => {
280 let val = trans_operand(fx, operand);
281 lval.write_cvalue(fx, val);
283 Rvalue::Ref(_, _, place) => {
284 let place = trans_place(fx, place);
285 place.write_place_ref(fx, lval);
287 Rvalue::BinaryOp(bin_op, lhs, rhs) => {
288 let lhs = trans_operand(fx, lhs);
289 let rhs = trans_operand(fx, rhs);
291 let res = crate::num::codegen_binop(fx, *bin_op, lhs, rhs);
292 lval.write_cvalue(fx, res);
294 Rvalue::CheckedBinaryOp(bin_op, lhs, rhs) => {
295 let lhs = trans_operand(fx, lhs);
296 let rhs = trans_operand(fx, rhs);
298 let res = if !fx.tcx.sess.overflow_checks() {
300 crate::num::trans_int_binop(fx, *bin_op, lhs, rhs).load_scalar(fx);
301 let is_overflow = fx.bcx.ins().iconst(types::I8, 0);
302 CValue::by_val_pair(val, is_overflow, lval.layout())
304 crate::num::trans_checked_int_binop(fx, *bin_op, lhs, rhs)
307 lval.write_cvalue(fx, res);
309 Rvalue::UnaryOp(un_op, operand) => {
310 let operand = trans_operand(fx, operand);
311 let layout = operand.layout();
312 let val = operand.load_scalar(fx);
313 let res = match un_op {
315 match layout.ty.kind {
317 let val = fx.bcx.ins().uextend(types::I32, val); // WORKAROUND for CraneStation/cranelift#466
318 let res = fx.bcx.ins().icmp_imm(IntCC::Equal, val, 0);
319 CValue::by_val(fx.bcx.ins().bint(types::I8, res), layout)
321 ty::Uint(_) | ty::Int(_) => {
322 CValue::by_val(fx.bcx.ins().bnot(val), layout)
324 _ => unimplemented!("un op Not for {:?}", layout.ty),
327 UnOp::Neg => match layout.ty.kind {
329 let zero = CValue::const_val(fx, layout.ty, 0);
330 crate::num::trans_int_binop(fx, BinOp::Sub, zero, operand)
333 CValue::by_val(fx.bcx.ins().fneg(val), layout)
335 _ => unimplemented!("un op Neg for {:?}", layout.ty),
338 lval.write_cvalue(fx, res);
340 Rvalue::Cast(CastKind::Pointer(PointerCast::ReifyFnPointer), operand, ty) => {
341 let layout = fx.layout_of(ty);
343 .monomorphize(&operand.ty(&fx.mir.local_decls, fx.tcx))
346 ty::FnDef(def_id, substs) => {
347 let func_ref = fx.get_function_ref(
348 Instance::resolve(fx.tcx, ParamEnv::reveal_all(), def_id, substs)
351 let func_addr = fx.bcx.ins().func_addr(fx.pointer_type, func_ref);
352 lval.write_cvalue(fx, CValue::by_val(func_addr, layout));
354 _ => bug!("Trying to ReifyFnPointer on non FnDef {:?}", ty),
357 Rvalue::Cast(CastKind::Pointer(PointerCast::UnsafeFnPointer), operand, ty)
358 | Rvalue::Cast(CastKind::Pointer(PointerCast::MutToConstPointer), operand, ty)
359 | Rvalue::Cast(CastKind::Pointer(PointerCast::ArrayToPointer), operand, ty) => {
360 let operand = trans_operand(fx, operand);
361 let layout = fx.layout_of(ty);
362 lval.write_cvalue(fx, operand.unchecked_cast_to(layout));
364 Rvalue::Cast(CastKind::Misc, operand, to_ty) => {
365 let operand = trans_operand(fx, operand);
366 let from_ty = operand.layout().ty;
367 let to_ty = fx.monomorphize(to_ty);
370 fx: &FunctionCx<'_, 'tcx, impl Backend>,
373 ty.builtin_deref(true)
378 }| has_ptr_meta(fx.tcx, pointee_ty),
383 if is_fat_ptr(fx, from_ty) {
384 if is_fat_ptr(fx, to_ty) {
385 // fat-ptr -> fat-ptr
386 lval.write_cvalue(fx, operand.unchecked_cast_to(dest_layout));
388 // fat-ptr -> thin-ptr
389 let (ptr, _extra) = operand.load_scalar_pair(fx);
390 lval.write_cvalue(fx, CValue::by_val(ptr, dest_layout))
392 } else if let ty::Adt(adt_def, _substs) = from_ty.kind {
393 // enum -> discriminant value
394 assert!(adt_def.is_enum());
396 ty::Uint(_) | ty::Int(_) => {}
397 _ => unreachable!("cast adt {} -> {}", from_ty, to_ty),
400 let discr = crate::discriminant::codegen_get_discriminant(
405 lval.write_cvalue(fx, discr);
407 let to_clif_ty = fx.clif_type(to_ty).unwrap();
408 let from = operand.load_scalar(fx);
410 let res = clif_int_or_float_cast(
417 lval.write_cvalue(fx, CValue::by_val(res, dest_layout));
420 Rvalue::Cast(CastKind::Pointer(PointerCast::ClosureFnPointer(_)), operand, _ty) => {
421 let operand = trans_operand(fx, operand);
422 match operand.layout().ty.kind {
423 ty::Closure(def_id, substs) => {
424 let instance = Instance::resolve_closure(
428 ty::ClosureKind::FnOnce,
430 let func_ref = fx.get_function_ref(instance);
431 let func_addr = fx.bcx.ins().func_addr(fx.pointer_type, func_ref);
432 lval.write_cvalue(fx, CValue::by_val(func_addr, lval.layout()));
434 _ => bug!("{} cannot be cast to a fn ptr", operand.layout().ty),
437 Rvalue::Cast(CastKind::Pointer(PointerCast::Unsize), operand, _ty) => {
438 let operand = trans_operand(fx, operand);
439 operand.unsize_value(fx, lval);
441 Rvalue::Discriminant(place) => {
442 let place = trans_place(fx, place);
443 let value = place.to_cvalue(fx);
445 crate::discriminant::codegen_get_discriminant(fx, value, dest_layout);
446 lval.write_cvalue(fx, discr);
448 Rvalue::Repeat(operand, times) => {
449 let operand = trans_operand(fx, operand);
451 let index = fx.bcx.ins().iconst(fx.pointer_type, i as i64);
452 let to = lval.place_index(fx, index);
453 to.write_cvalue(fx, operand);
456 Rvalue::Len(place) => {
457 let place = trans_place(fx, place);
458 let usize_layout = fx.layout_of(fx.tcx.types.usize);
459 let len = codegen_array_len(fx, place);
460 lval.write_cvalue(fx, CValue::by_val(len, usize_layout));
462 Rvalue::NullaryOp(NullOp::Box, content_ty) => {
463 use rustc::middle::lang_items::ExchangeMallocFnLangItem;
465 let usize_type = fx.clif_type(fx.tcx.types.usize).unwrap();
466 let layout = fx.layout_of(content_ty);
467 let llsize = fx.bcx.ins().iconst(usize_type, layout.size.bytes() as i64);
471 .iconst(usize_type, layout.align.abi.bytes() as i64);
472 let box_layout = fx.layout_of(fx.tcx.mk_box(content_ty));
475 let def_id = match fx.tcx.lang_items().require(ExchangeMallocFnLangItem) {
480 .fatal(&format!("allocation of `{}` {}", box_layout.ty, s));
483 let instance = ty::Instance::mono(fx.tcx, def_id);
484 let func_ref = fx.get_function_ref(instance);
485 let call = fx.bcx.ins().call(func_ref, &[llsize, llalign]);
486 let ptr = fx.bcx.inst_results(call)[0];
487 lval.write_cvalue(fx, CValue::by_val(ptr, box_layout));
489 Rvalue::NullaryOp(NullOp::SizeOf, ty) => {
493 .is_sized(fx.tcx.at(DUMMY_SP), ParamEnv::reveal_all()));
494 let ty_size = fx.layout_of(ty).size.bytes();
495 let val = CValue::const_val(fx, fx.tcx.types.usize, ty_size.into());
496 lval.write_cvalue(fx, val);
498 Rvalue::Aggregate(kind, operands) => match **kind {
499 AggregateKind::Array(_ty) => {
500 for (i, operand) in operands.into_iter().enumerate() {
501 let operand = trans_operand(fx, operand);
502 let index = fx.bcx.ins().iconst(fx.pointer_type, i as i64);
503 let to = lval.place_index(fx, index);
504 to.write_cvalue(fx, operand);
507 _ => unreachable!("shouldn't exist at trans {:?}", to_place_and_rval.1),
511 StatementKind::StorageLive(_)
512 | StatementKind::StorageDead(_)
514 | StatementKind::FakeRead(..)
515 | StatementKind::Retag { .. }
516 | StatementKind::AscribeUserType(..) => {}
518 StatementKind::InlineAsm(asm) => {
519 use syntax::ast::Name;
525 let rustc::hir::InlineAsmInner {
526 asm: asm_code, // Name
527 outputs, // Vec<Name>
529 clobbers, // Vec<Name>
532 dialect: _, // syntax::ast::AsmDialect
535 match &*asm_code.as_str() {
537 assert_eq!(inputs, &[Name::intern("r")]);
538 assert!(outputs.is_empty(), "{:?}", outputs);
542 "cpuid" | "cpuid\n" => {
543 assert_eq!(inputs, &[Name::intern("{eax}"), Name::intern("{ecx}")]);
545 assert_eq!(outputs.len(), 4);
546 for (i, c) in (&["={eax}", "={ebx}", "={ecx}", "={edx}"])
550 assert_eq!(&outputs[i].constraint.as_str(), c);
551 assert!(!outputs[i].is_rw);
552 assert!(!outputs[i].is_indirect);
555 assert_eq!(clobbers, &[Name::intern("rbx")]);
558 assert!(!alignstack);
560 crate::trap::trap_unimplemented(
562 "__cpuid_count arch intrinsic is not supported",
566 assert_eq!(inputs, &[Name::intern("{ecx}")]);
568 assert_eq!(outputs.len(), 2);
569 for (i, c) in (&["={eax}", "={edx}"]).iter().enumerate() {
570 assert_eq!(&outputs[i].constraint.as_str(), c);
571 assert!(!outputs[i].is_rw);
572 assert!(!outputs[i].is_indirect);
575 assert_eq!(clobbers, &[]);
578 assert!(!alignstack);
580 crate::trap::trap_unimplemented(fx, "_xgetbv arch intrinsic is not supported");
582 _ if fx.tcx.symbol_name(fx.instance).name.as_str() == "__rust_probestack" => {
583 crate::trap::trap_unimplemented(fx, "__rust_probestack is not supported");
585 _ => unimpl!("Inline assembly is not supported"),
591 fn codegen_array_len<'tcx>(
592 fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
595 match place.layout().ty.kind {
596 ty::Array(_elem_ty, len) => {
597 let len = crate::constant::force_eval_const(fx, len)
598 .eval_usize(fx.tcx, ParamEnv::reveal_all()) as i64;
599 fx.bcx.ins().iconst(fx.pointer_type, len)
601 ty::Slice(_elem_ty) => place
602 .to_addr_maybe_unsized(fx)
604 .expect("Length metadata for slice place"),
605 _ => bug!("Rvalue::Len({:?})", place),
609 pub fn trans_place<'tcx>(
610 fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
613 let mut cplace = match &place.base {
614 PlaceBase::Local(local) => fx.get_local_place(*local),
615 PlaceBase::Static(static_) => match static_.kind {
616 StaticKind::Static => {
617 crate::constant::codegen_static_ref(fx, static_.def_id, static_.ty)
619 StaticKind::Promoted(promoted, substs) => {
620 let instance = Instance::new(static_.def_id, fx.monomorphize(&substs));
621 crate::constant::trans_promoted(fx, instance, promoted, static_.ty)
626 for elem in &*place.projection {
628 PlaceElem::Deref => {
629 cplace = cplace.place_deref(fx);
631 PlaceElem::Field(field, _ty) => {
632 cplace = cplace.place_field(fx, field);
634 PlaceElem::Index(local) => {
635 let index = fx.get_local_place(local).to_cvalue(fx).load_scalar(fx);
636 cplace = cplace.place_index(fx, index);
638 PlaceElem::ConstantIndex {
643 let index = if !from_end {
644 fx.bcx.ins().iconst(fx.pointer_type, offset as i64)
646 let len = codegen_array_len(fx, cplace);
647 fx.bcx.ins().iadd_imm(len, -(offset as i64))
649 cplace = cplace.place_index(fx, index);
651 PlaceElem::Subslice { from, to, from_end } => {
652 // These indices are generated by slice patterns.
653 // slice[from:-to] in Python terms.
655 match cplace.layout().ty.kind {
656 ty::Array(elem_ty, len) => {
657 let elem_layout = fx.layout_of(elem_ty);
658 let ptr = cplace.to_addr(fx);
659 let len = crate::constant::force_eval_const(fx, len)
660 .eval_usize(fx.tcx, ParamEnv::reveal_all());
661 cplace = CPlace::for_addr(
664 .iadd_imm(ptr, elem_layout.size.bytes() as i64 * from as i64),
665 fx.layout_of(fx.tcx.mk_array(elem_ty, len - from as u64 - to as u64)),
668 ty::Slice(elem_ty) => {
669 assert!(from_end, "slice subslices should be `from_end`");
670 let elem_layout = fx.layout_of(elem_ty);
671 let (ptr, len) = cplace.to_addr_maybe_unsized(fx);
672 let len = len.unwrap();
673 cplace = CPlace::for_addr_with_extra(
676 .iadd_imm(ptr, elem_layout.size.bytes() as i64 * from as i64),
677 fx.bcx.ins().iadd_imm(len, -(from as i64 + to as i64)),
684 PlaceElem::Downcast(_adt_def, variant) => {
685 cplace = cplace.downcast_variant(fx, variant);
693 pub fn trans_operand<'tcx>(
694 fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
695 operand: &Operand<'tcx>,
698 Operand::Move(place) | Operand::Copy(place) => {
699 let cplace = trans_place(fx, place);
702 Operand::Constant(const_) => crate::constant::trans_constant(fx, const_),