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 // Make FunctionBuilder
23 let mut func = Function::with_name_signature(ExternalName::user(0, 0), sig);
24 let mut func_ctx = FunctionBuilderContext::new();
25 let mut bcx = FunctionBuilder::new(&mut func, &mut func_ctx);
28 let start_ebb = bcx.create_ebb();
29 let mut ebb_map: HashMap<BasicBlock, Ebb> = HashMap::new();
30 for (bb, _bb_data) in mir.basic_blocks().iter_enumerated() {
31 ebb_map.insert(bb, bcx.create_ebb());
35 let pointer_type = cx.module.target_config().pointer_type();
36 let clif_comments = crate::pretty_clif::CommentWriter::new(tcx, instance);
38 let mut fx = FunctionCx {
48 local_map: HashMap::new(),
51 constants_cx: &mut cx.constants_cx,
52 caches: &mut cx.caches,
53 source_info_set: indexmap::IndexSet::new(),
56 with_unimpl_span(fx.mir.span, || {
57 crate::abi::codegen_fn_prelude(&mut fx, start_ebb);
58 codegen_fn_content(&mut fx);
61 // Recover all necessary data from fx, before accessing func will prevent future access to it.
62 let instance = fx.instance;
63 let clif_comments = fx.clif_comments;
64 let source_info_set = fx.source_info_set;
66 #[cfg(debug_assertions)]
67 crate::pretty_clif::write_clif_file(cx.tcx, "unopt", instance, &func, &clif_comments, None);
70 verify_func(tcx, &clif_comments, &func);
73 let context = &mut cx.caches.context;
75 cx.module.define_function(func_id, context).unwrap();
77 let value_ranges = context
78 .build_value_labels_ranges(cx.module.isa())
79 .expect("value location ranges");
81 // Write optimized function to file for debugging
82 #[cfg(debug_assertions)]
83 crate::pretty_clif::write_clif_file(
92 // Define debuginfo for function
93 let isa = cx.module.isa();
96 .map(|x| x.define(tcx, context, isa, &source_info_set));
98 // Clear context to make it usable for the next function
102 fn verify_func(tcx: TyCtxt, writer: &crate::pretty_clif::CommentWriter, func: &Function) {
103 let flags = settings::Flags::new(settings::builder());
104 match ::cranelift::codegen::verify_function(&func, &flags) {
107 tcx.sess.err(&format!("{:?}", err));
108 let pretty_error = ::cranelift::codegen::print_errors::pretty_verifier_error(
111 Some(Box::new(writer)),
115 .fatal(&format!("cranelift verify error:\n{}", pretty_error));
120 fn codegen_fn_content(fx: &mut FunctionCx<'_, '_, impl Backend>) {
121 for (bb, bb_data) in fx.mir.basic_blocks().iter_enumerated() {
122 if bb_data.is_cleanup {
123 // Unwinding after panicking is not supported
127 let ebb = fx.get_ebb(bb);
128 fx.bcx.switch_to_block(ebb);
131 for stmt in &bb_data.statements {
132 fx.set_debug_loc(stmt.source_info);
133 trans_stmt(fx, ebb, stmt);
136 #[cfg(debug_assertions)]
138 let mut terminator_head = "\n".to_string();
142 .fmt_head(&mut terminator_head)
144 let inst = fx.bcx.func.layout.last_inst(ebb).unwrap();
145 fx.add_comment(inst, terminator_head);
148 fx.set_debug_loc(bb_data.terminator().source_info);
150 match &bb_data.terminator().kind {
151 TerminatorKind::Goto { target } => {
152 let ebb = fx.get_ebb(*target);
153 fx.bcx.ins().jump(ebb, &[]);
155 TerminatorKind::Return => {
156 crate::abi::codegen_return(fx);
158 TerminatorKind::Assert {
165 if !fx.tcx.sess.overflow_checks() {
166 if let mir::interpret::PanicInfo::OverflowNeg = *msg {
167 let target = fx.get_ebb(*target);
168 fx.bcx.ins().jump(target, &[]);
172 let cond = trans_operand(fx, cond).load_scalar(fx);
173 // TODO HACK brz/brnz for i8/i16 is not yet implemented
174 let cond = fx.bcx.ins().uextend(types::I32, cond);
175 let target = fx.get_ebb(*target);
177 fx.bcx.ins().brnz(cond, target, &[]);
179 fx.bcx.ins().brz(cond, target, &[]);
184 "[panic] Assert {:?} at {:?} failed.",
186 bb_data.terminator().source_info.span
191 TerminatorKind::SwitchInt {
197 let discr = trans_operand(fx, discr).load_scalar(fx);
198 let mut switch = ::cranelift::frontend::Switch::new();
199 for (i, value) in values.iter().enumerate() {
200 let ebb = fx.get_ebb(targets[i]);
201 switch.set_entry(*value as u64, ebb);
203 let otherwise_ebb = fx.get_ebb(targets[targets.len() - 1]);
204 switch.emit(&mut fx.bcx, discr, otherwise_ebb);
206 TerminatorKind::Call {
213 crate::abi::codegen_terminator_call(fx, func, args, destination);
215 TerminatorKind::Resume | TerminatorKind::Abort => {
216 trap_unreachable(fx, "[corruption] Unwinding bb reached.");
218 TerminatorKind::Unreachable => {
219 trap_unreachable(fx, "[corruption] Hit unreachable code.");
221 TerminatorKind::Yield { .. }
222 | TerminatorKind::FalseEdges { .. }
223 | TerminatorKind::FalseUnwind { .. }
224 | TerminatorKind::DropAndReplace { .. }
225 | TerminatorKind::GeneratorDrop => {
226 bug!("shouldn't exist at trans {:?}", bb_data.terminator());
228 TerminatorKind::Drop {
233 let drop_place = trans_place(fx, location);
234 crate::abi::codegen_drop(fx, drop_place);
236 let target_ebb = fx.get_ebb(*target);
237 fx.bcx.ins().jump(target_ebb, &[]);
242 fx.bcx.seal_all_blocks();
247 fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
249 stmt: &Statement<'tcx>,
251 let _print_guard = PrintOnPanic(|| format!("stmt {:?}", stmt));
253 fx.set_debug_loc(stmt.source_info);
255 #[cfg(debug_assertions)]
257 StatementKind::StorageLive(..) | StatementKind::StorageDead(..) => {} // Those are not very useful
259 let inst = fx.bcx.func.layout.last_inst(cur_ebb).unwrap();
260 fx.add_comment(inst, format!("{:?}", stmt));
265 StatementKind::SetDiscriminant {
269 let place = trans_place(fx, place);
270 crate::discriminant::codegen_set_discriminant(fx, place, *variant_index);
272 StatementKind::Assign(to_place_and_rval) => {
273 let lval = trans_place(fx, &to_place_and_rval.0);
274 let dest_layout = lval.layout();
275 match &to_place_and_rval.1 {
276 Rvalue::Use(operand) => {
277 let val = trans_operand(fx, operand);
278 lval.write_cvalue(fx, val);
280 Rvalue::Ref(_, _, place) => {
281 let place = trans_place(fx, place);
282 place.write_place_ref(fx, lval);
284 Rvalue::BinaryOp(bin_op, lhs, rhs) => {
285 let lhs = trans_operand(fx, lhs);
286 let rhs = trans_operand(fx, rhs);
288 let res = crate::num::codegen_binop(fx, *bin_op, lhs, rhs);
289 lval.write_cvalue(fx, res);
291 Rvalue::CheckedBinaryOp(bin_op, lhs, rhs) => {
292 let lhs = trans_operand(fx, lhs);
293 let rhs = trans_operand(fx, rhs);
295 let res = if !fx.tcx.sess.overflow_checks() {
297 crate::num::trans_int_binop(fx, *bin_op, lhs, rhs).load_scalar(fx);
298 let is_overflow = fx.bcx.ins().iconst(types::I8, 0);
299 CValue::by_val_pair(val, is_overflow, lval.layout())
301 crate::num::trans_checked_int_binop(fx, *bin_op, lhs, rhs)
304 lval.write_cvalue(fx, res);
306 Rvalue::UnaryOp(un_op, operand) => {
307 let operand = trans_operand(fx, operand);
308 let layout = operand.layout();
309 let val = operand.load_scalar(fx);
310 let res = match un_op {
312 match layout.ty.kind {
314 let val = fx.bcx.ins().uextend(types::I32, val); // WORKAROUND for CraneStation/cranelift#466
315 let res = fx.bcx.ins().icmp_imm(IntCC::Equal, val, 0);
316 CValue::by_val(fx.bcx.ins().bint(types::I8, res), layout)
318 ty::Uint(_) | ty::Int(_) => {
319 CValue::by_val(fx.bcx.ins().bnot(val), layout)
321 _ => unimplemented!("un op Not for {:?}", layout.ty),
324 UnOp::Neg => match layout.ty.kind {
326 let zero = CValue::const_val(fx, layout.ty, 0);
327 crate::num::trans_int_binop(fx, BinOp::Sub, zero, operand)
330 CValue::by_val(fx.bcx.ins().fneg(val), layout)
332 _ => unimplemented!("un op Neg for {:?}", layout.ty),
335 lval.write_cvalue(fx, res);
337 Rvalue::Cast(CastKind::Pointer(PointerCast::ReifyFnPointer), operand, ty) => {
338 let layout = fx.layout_of(ty);
340 .monomorphize(&operand.ty(&fx.mir.local_decls, fx.tcx))
343 ty::FnDef(def_id, substs) => {
344 let func_ref = fx.get_function_ref(
345 Instance::resolve(fx.tcx, ParamEnv::reveal_all(), def_id, substs)
348 let func_addr = fx.bcx.ins().func_addr(fx.pointer_type, func_ref);
349 lval.write_cvalue(fx, CValue::by_val(func_addr, layout));
351 _ => bug!("Trying to ReifyFnPointer on non FnDef {:?}", ty),
354 Rvalue::Cast(CastKind::Pointer(PointerCast::UnsafeFnPointer), operand, ty)
355 | Rvalue::Cast(CastKind::Pointer(PointerCast::MutToConstPointer), operand, ty) => {
356 let operand = trans_operand(fx, operand);
357 let layout = fx.layout_of(ty);
358 lval.write_cvalue(fx, operand.unchecked_cast_to(layout));
360 Rvalue::Cast(CastKind::Misc, operand, to_ty) => {
361 let operand = trans_operand(fx, operand);
362 let from_ty = operand.layout().ty;
363 let to_ty = fx.monomorphize(to_ty);
366 fx: &FunctionCx<'_, 'tcx, impl Backend>,
369 ty.builtin_deref(true)
374 }| has_ptr_meta(fx.tcx, pointee_ty),
379 if is_fat_ptr(fx, from_ty) {
380 if is_fat_ptr(fx, to_ty) {
381 // fat-ptr -> fat-ptr
382 lval.write_cvalue(fx, operand.unchecked_cast_to(dest_layout));
384 // fat-ptr -> thin-ptr
385 let (ptr, _extra) = operand.load_scalar_pair(fx);
386 lval.write_cvalue(fx, CValue::by_val(ptr, dest_layout))
388 } else if let ty::Adt(adt_def, _substs) = from_ty.kind {
389 // enum -> discriminant value
390 assert!(adt_def.is_enum());
392 ty::Uint(_) | ty::Int(_) => {}
393 _ => unreachable!("cast adt {} -> {}", from_ty, to_ty),
396 let discr = crate::discriminant::codegen_get_discriminant(
401 lval.write_cvalue(fx, discr);
403 let to_clif_ty = fx.clif_type(to_ty).unwrap();
404 let from = operand.load_scalar(fx);
406 let res = clif_int_or_float_cast(
413 lval.write_cvalue(fx, CValue::by_val(res, dest_layout));
416 Rvalue::Cast(CastKind::Pointer(PointerCast::ClosureFnPointer(_)), operand, _ty) => {
417 let operand = trans_operand(fx, operand);
418 match operand.layout().ty.kind {
419 ty::Closure(def_id, substs) => {
420 let instance = Instance::resolve_closure(
424 ty::ClosureKind::FnOnce,
426 let func_ref = fx.get_function_ref(instance);
427 let func_addr = fx.bcx.ins().func_addr(fx.pointer_type, func_ref);
428 lval.write_cvalue(fx, CValue::by_val(func_addr, lval.layout()));
430 _ => bug!("{} cannot be cast to a fn ptr", operand.layout().ty),
433 Rvalue::Cast(CastKind::Pointer(PointerCast::Unsize), operand, _ty) => {
434 let operand = trans_operand(fx, operand);
435 operand.unsize_value(fx, lval);
437 Rvalue::Discriminant(place) => {
438 let place = trans_place(fx, place);
439 let value = place.to_cvalue(fx);
441 crate::discriminant::codegen_get_discriminant(fx, value, dest_layout);
442 lval.write_cvalue(fx, discr);
444 Rvalue::Repeat(operand, times) => {
445 let operand = trans_operand(fx, operand);
447 let index = fx.bcx.ins().iconst(fx.pointer_type, i as i64);
448 let to = lval.place_index(fx, index);
449 to.write_cvalue(fx, operand);
452 Rvalue::Len(place) => {
453 let place = trans_place(fx, place);
454 let usize_layout = fx.layout_of(fx.tcx.types.usize);
455 let len = codegen_array_len(fx, place);
456 lval.write_cvalue(fx, CValue::by_val(len, usize_layout));
458 Rvalue::NullaryOp(NullOp::Box, content_ty) => {
459 use rustc::middle::lang_items::ExchangeMallocFnLangItem;
461 let usize_type = fx.clif_type(fx.tcx.types.usize).unwrap();
462 let layout = fx.layout_of(content_ty);
463 let llsize = fx.bcx.ins().iconst(usize_type, layout.size.bytes() as i64);
467 .iconst(usize_type, layout.align.abi.bytes() as i64);
468 let box_layout = fx.layout_of(fx.tcx.mk_box(content_ty));
471 let def_id = match fx.tcx.lang_items().require(ExchangeMallocFnLangItem) {
476 .fatal(&format!("allocation of `{}` {}", box_layout.ty, s));
479 let instance = ty::Instance::mono(fx.tcx, def_id);
480 let func_ref = fx.get_function_ref(instance);
481 let call = fx.bcx.ins().call(func_ref, &[llsize, llalign]);
482 let ptr = fx.bcx.inst_results(call)[0];
483 lval.write_cvalue(fx, CValue::by_val(ptr, box_layout));
485 Rvalue::NullaryOp(NullOp::SizeOf, ty) => {
489 .is_sized(fx.tcx.at(DUMMY_SP), ParamEnv::reveal_all()));
490 let ty_size = fx.layout_of(ty).size.bytes();
491 let val = CValue::const_val(fx, fx.tcx.types.usize, ty_size.into());
492 lval.write_cvalue(fx, val);
494 Rvalue::Aggregate(kind, operands) => match **kind {
495 AggregateKind::Array(_ty) => {
496 for (i, operand) in operands.into_iter().enumerate() {
497 let operand = trans_operand(fx, operand);
498 let index = fx.bcx.ins().iconst(fx.pointer_type, i as i64);
499 let to = lval.place_index(fx, index);
500 to.write_cvalue(fx, operand);
503 _ => unimpl!("shouldn't exist at trans {:?}", to_place_and_rval.1),
507 StatementKind::StorageLive(_)
508 | StatementKind::StorageDead(_)
510 | StatementKind::FakeRead(..)
511 | StatementKind::Retag { .. }
512 | StatementKind::AscribeUserType(..) => {}
514 StatementKind::InlineAsm(asm) => {
515 use syntax::ast::Name;
521 let rustc::hir::InlineAsm {
522 asm: asm_code, // Name
523 outputs, // Vec<Name>
525 clobbers, // Vec<Name>
528 dialect: _, // syntax::ast::AsmDialect
531 match &*asm_code.as_str() {
533 assert_eq!(inputs, &[Name::intern("r")]);
534 assert!(outputs.is_empty(), "{:?}", outputs);
538 "cpuid" | "cpuid\n" => {
539 assert_eq!(inputs, &[Name::intern("{eax}"), Name::intern("{ecx}")]);
541 assert_eq!(outputs.len(), 4);
542 for (i, c) in (&["={eax}", "={ebx}", "={ecx}", "={edx}"])
546 assert_eq!(&outputs[i].constraint.as_str(), c);
547 assert!(!outputs[i].is_rw);
548 assert!(!outputs[i].is_indirect);
551 assert_eq!(clobbers, &[Name::intern("rbx")]);
554 assert!(!alignstack);
556 crate::trap::trap_unimplemented(
558 "__cpuid_count arch intrinsic is not supported",
562 assert_eq!(inputs, &[Name::intern("{ecx}")]);
564 assert_eq!(outputs.len(), 2);
565 for (i, c) in (&["={eax}", "={edx}"]).iter().enumerate() {
566 assert_eq!(&outputs[i].constraint.as_str(), c);
567 assert!(!outputs[i].is_rw);
568 assert!(!outputs[i].is_indirect);
571 assert_eq!(clobbers, &[]);
574 assert!(!alignstack);
576 crate::trap::trap_unimplemented(fx, "_xgetbv arch intrinsic is not supported");
578 _ if fx.tcx.symbol_name(fx.instance).name.as_str() == "__rust_probestack" => {
579 crate::trap::trap_unimplemented(fx, "__rust_probestack is not supported");
581 _ => unimpl!("Inline assembly is not supported"),
587 fn codegen_array_len<'tcx>(
588 fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
591 match place.layout().ty.kind {
592 ty::Array(_elem_ty, len) => {
593 let len = crate::constant::force_eval_const(fx, len)
594 .eval_usize(fx.tcx, ParamEnv::reveal_all()) as i64;
595 fx.bcx.ins().iconst(fx.pointer_type, len)
597 ty::Slice(_elem_ty) => place
598 .to_addr_maybe_unsized(fx)
600 .expect("Length metadata for slice place"),
601 _ => bug!("Rvalue::Len({:?})", place),
605 pub fn trans_place<'tcx>(
606 fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
609 let mut cplace = match &place.base {
610 PlaceBase::Local(local) => fx.get_local_place(*local),
611 PlaceBase::Static(static_) => match static_.kind {
612 StaticKind::Static => {
613 crate::constant::codegen_static_ref(fx, static_.def_id, static_.ty)
615 StaticKind::Promoted(promoted, substs) => {
616 let instance = Instance::new(static_.def_id, fx.monomorphize(&substs));
617 crate::constant::trans_promoted(fx, instance, promoted, static_.ty)
622 for elem in &*place.projection {
624 PlaceElem::Deref => {
625 cplace = cplace.place_deref(fx);
627 PlaceElem::Field(field, _ty) => {
628 cplace = cplace.place_field(fx, field);
630 PlaceElem::Index(local) => {
631 let index = fx.get_local_place(local).to_cvalue(fx).load_scalar(fx);
632 cplace = cplace.place_index(fx, index);
634 PlaceElem::ConstantIndex {
639 let index = if !from_end {
640 fx.bcx.ins().iconst(fx.pointer_type, offset as i64)
642 let len = codegen_array_len(fx, cplace);
643 fx.bcx.ins().iadd_imm(len, -(offset as i64))
645 cplace = cplace.place_index(fx, index);
647 PlaceElem::Subslice { from, to } => {
648 // These indices are generated by slice patterns.
649 // slice[from:-to] in Python terms.
651 match cplace.layout().ty.kind {
652 ty::Array(elem_ty, len) => {
653 let elem_layout = fx.layout_of(elem_ty);
654 let ptr = cplace.to_addr(fx);
655 let len = crate::constant::force_eval_const(fx, len)
656 .eval_usize(fx.tcx, ParamEnv::reveal_all());
657 cplace = CPlace::for_addr(
660 .iadd_imm(ptr, elem_layout.size.bytes() as i64 * from as i64),
661 fx.layout_of(fx.tcx.mk_array(elem_ty, len - from as u64 - to as u64)),
664 ty::Slice(elem_ty) => {
665 let elem_layout = fx.layout_of(elem_ty);
666 let (ptr, len) = cplace.to_addr_maybe_unsized(fx);
667 let len = len.unwrap();
668 cplace = CPlace::for_addr_with_extra(
671 .iadd_imm(ptr, elem_layout.size.bytes() as i64 * from as i64),
672 fx.bcx.ins().iadd_imm(len, -(from as i64 + to as i64)),
679 PlaceElem::Downcast(_adt_def, variant) => {
680 cplace = cplace.downcast_variant(fx, variant);
688 pub fn trans_operand<'tcx>(
689 fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
690 operand: &Operand<'tcx>,
693 Operand::Move(place) | Operand::Copy(place) => {
694 let cplace = trans_place(fx, place);
697 Operand::Constant(const_) => crate::constant::trans_constant(fx, const_),