]> git.lizzy.rs Git - rust.git/blob - src/base.rs
Improve debug messages in generated clif files
[rust.git] / src / base.rs
1 use crate::prelude::*;
2
3 struct PrintOnPanic<F: Fn() -> String>(F);
4 impl<F: Fn() -> String> Drop for PrintOnPanic<F> {
5     fn drop(&mut self) {
6         if ::std::thread::panicking() {
7             println!("{}", (self.0)());
8         }
9     }
10 }
11
12 pub fn trans_mono_item<'a, 'clif, 'tcx: 'a, B: Backend + 'static>(
13     cx: &mut crate::CodegenCx<'a, 'clif, 'tcx, B>,
14     mono_item: MonoItem<'tcx>,
15 ) {
16     let tcx = cx.tcx;
17     match mono_item {
18         MonoItem::Fn(inst) => {
19             let _inst_guard =
20                 PrintOnPanic(|| format!("{:?} {}", inst, tcx.symbol_name(inst).as_str()));
21             debug_assert!(!inst.substs.needs_infer());
22             let _mir_guard = PrintOnPanic(|| {
23                 match inst.def {
24                     InstanceDef::Item(_)
25                     | InstanceDef::DropGlue(_, _)
26                     | InstanceDef::Virtual(_, _)
27                         if inst.def_id().krate == LOCAL_CRATE =>
28                     {
29                         let mut mir = ::std::io::Cursor::new(Vec::new());
30                         crate::rustc_mir::util::write_mir_pretty(
31                             tcx,
32                             Some(inst.def_id()),
33                             &mut mir,
34                         )
35                         .unwrap();
36                         String::from_utf8(mir.into_inner()).unwrap()
37                     }
38                     _ => {
39                         // FIXME fix write_mir_pretty for these instances
40                         format!("{:#?}", tcx.instance_mir(inst.def))
41                     }
42                 }
43             });
44
45             trans_fn(cx, inst);
46         }
47         MonoItem::Static(def_id) => {
48             crate::constant::codegen_static(&mut cx.ccx, def_id);
49         }
50         MonoItem::GlobalAsm(node_id) => tcx
51             .sess
52             .fatal(&format!("Unimplemented global asm mono item {:?}", node_id)),
53     }
54 }
55
56 fn trans_fn<'a, 'clif, 'tcx: 'a, B: Backend + 'static>(
57     cx: &mut crate::CodegenCx<'a, 'clif, 'tcx, B>,
58     instance: Instance<'tcx>,
59 ) {
60     let tcx = cx.tcx;
61
62     // Step 1. Get mir
63     let mir = tcx.instance_mir(instance.def);
64
65     // Step 2. Declare function
66     let (name, sig) = get_function_name_and_sig(tcx, instance);
67     let func_id = cx.module
68         .declare_function(&name, Linkage::Export, &sig)
69         .unwrap();
70
71     // Step 3. Make FunctionBuilder
72     let mut func = Function::with_name_signature(ExternalName::user(0, 0), sig);
73     let mut func_ctx = FunctionBuilderContext::new();
74     let mut bcx = FunctionBuilder::new(&mut func, &mut func_ctx);
75
76     // Step 4. Predefine ebb's
77     let start_ebb = bcx.create_ebb();
78     let mut ebb_map: HashMap<BasicBlock, Ebb> = HashMap::new();
79     for (bb, _bb_data) in mir.basic_blocks().iter_enumerated() {
80         ebb_map.insert(bb, bcx.create_ebb());
81     }
82
83     // Step 5. Make FunctionCx
84     let pointer_type = cx.module.target_config().pointer_type();
85     let clif_comments = crate::pretty_clif::CommentWriter::new(tcx, instance);
86
87     let mut fx = FunctionCx {
88         tcx,
89         module: cx.module,
90         pointer_type,
91
92         instance,
93         mir,
94
95         bcx,
96         ebb_map,
97         local_map: HashMap::new(),
98
99         clif_comments,
100         constants: &mut cx.ccx,
101         caches: &mut cx.caches,
102     };
103
104     // Step 6. Codegen function
105     with_unimpl_span(fx.mir.span, || {
106         crate::abi::codegen_fn_prelude(&mut fx, start_ebb);
107         codegen_fn_content(&mut fx);
108     });
109
110     // Step 7. Write function to file for debugging
111     if cfg!(debug_assertions) {
112         fx.write_clif_file();
113     }
114
115     // Step 8. Verify function
116     verify_func(tcx, fx.clif_comments, &func);
117
118     // Step 9. Define function
119     cx.caches.context.func = func;
120     cx.module
121         .define_function(func_id, &mut cx.caches.context)
122         .unwrap();
123     cx.caches.context.clear();
124 }
125
126 fn verify_func(tcx: TyCtxt, writer: crate::pretty_clif::CommentWriter, func: &Function) {
127     let flags = settings::Flags::new(settings::builder());
128     match ::cranelift::codegen::verify_function(&func, &flags) {
129         Ok(_) => {}
130         Err(err) => {
131             tcx.sess.err(&format!("{:?}", err));
132             let pretty_error = ::cranelift::codegen::print_errors::pretty_verifier_error(
133                 &func,
134                 None,
135                 Some(Box::new(&writer)),
136                 err,
137             );
138             tcx.sess
139                 .fatal(&format!("cranelift verify error:\n{}", pretty_error));
140         }
141     }
142 }
143
144 fn codegen_fn_content<'a, 'tcx: 'a>(fx: &mut FunctionCx<'a, 'tcx, impl Backend>) {
145     for (bb, bb_data) in fx.mir.basic_blocks().iter_enumerated() {
146         if bb_data.is_cleanup {
147             // Unwinding after panicking is not supported
148             continue;
149         }
150
151         let ebb = fx.get_ebb(bb);
152         fx.bcx.switch_to_block(ebb);
153
154         fx.bcx.ins().nop();
155         for stmt in &bb_data.statements {
156             trans_stmt(fx, ebb, stmt);
157         }
158
159         let mut terminator_head = "\n".to_string();
160         bb_data
161             .terminator()
162             .kind
163             .fmt_head(&mut terminator_head)
164             .unwrap();
165         let inst = fx.bcx.func.layout.last_inst(ebb).unwrap();
166         fx.add_comment(inst, terminator_head);
167
168         match &bb_data.terminator().kind {
169             TerminatorKind::Goto { target } => {
170                 let ebb = fx.get_ebb(*target);
171                 fx.bcx.ins().jump(ebb, &[]);
172             }
173             TerminatorKind::Return => {
174                 crate::abi::codegen_return(fx);
175             }
176             TerminatorKind::Assert {
177                 cond,
178                 expected,
179                 msg: _,
180                 target,
181                 cleanup: _,
182             } => {
183                 let cond = trans_operand(fx, cond).load_value(fx);
184                 // TODO HACK brz/brnz for i8/i16 is not yet implemented
185                 let cond = fx.bcx.ins().uextend(types::I32, cond);
186                 let target = fx.get_ebb(*target);
187                 if *expected {
188                     fx.bcx.ins().brnz(cond, target, &[]);
189                 } else {
190                     fx.bcx.ins().brz(cond, target, &[]);
191                 };
192                 trap_panic(&mut fx.bcx);
193             }
194
195             TerminatorKind::SwitchInt {
196                 discr,
197                 switch_ty: _,
198                 values,
199                 targets,
200             } => {
201                 let discr = trans_operand(fx, discr).load_value(fx);
202                 let mut switch = ::cranelift::frontend::Switch::new();
203                 for (i, value) in values.iter().enumerate() {
204                     let ebb = fx.get_ebb(targets[i]);
205                     switch.set_entry(*value as u64, ebb);
206                 }
207                 let otherwise_ebb = fx.get_ebb(targets[targets.len() - 1]);
208                 switch.emit(&mut fx.bcx, discr, otherwise_ebb);
209             }
210             TerminatorKind::Call {
211                 func,
212                 args,
213                 destination,
214                 cleanup: _,
215                 from_hir_call: _,
216             } => {
217                 crate::abi::codegen_terminator_call(fx, func, args, destination);
218             }
219             TerminatorKind::Resume | TerminatorKind::Abort | TerminatorKind::Unreachable => {
220                 trap_unreachable(&mut fx.bcx);
221             }
222             TerminatorKind::Yield { .. }
223             | TerminatorKind::FalseEdges { .. }
224             | TerminatorKind::FalseUnwind { .. }
225             | TerminatorKind::DropAndReplace { .. } => {
226                 bug!("shouldn't exist at trans {:?}", bb_data.terminator());
227             }
228             TerminatorKind::Drop {
229                 location,
230                 target,
231                 unwind: _,
232             } => {
233                 let ty = location.ty(fx.mir, fx.tcx).to_ty(fx.tcx);
234                 let ty = fx.monomorphize(&ty);
235                 let drop_fn = crate::rustc_mir::monomorphize::resolve_drop_in_place(fx.tcx, ty);
236
237                 if let ty::InstanceDef::DropGlue(_, None) = drop_fn.def {
238                     // we don't actually need to drop anything
239                 } else {
240                     let drop_place = trans_place(fx, location);
241                     let arg_place = CPlace::temp(
242                         fx,
243                         fx.tcx.mk_ref(
244                             &ty::RegionKind::ReErased,
245                             TypeAndMut {
246                                 ty,
247                                 mutbl: crate::rustc::hir::Mutability::MutMutable,
248                             },
249                         ),
250                     );
251                     drop_place.write_place_ref(fx, arg_place);
252                     match ty.sty {
253                         ty::Dynamic(..) => {
254                             fx.tcx.sess.warn("Drop for trait object");
255                         }
256                         _ => {
257                             let drop_fn_ty = drop_fn.ty(fx.tcx);
258                             let arg_value = arg_place.to_cvalue(fx);
259                             crate::abi::codegen_call_inner(
260                                 fx,
261                                 None,
262                                 drop_fn_ty,
263                                 vec![arg_value],
264                                 None,
265                             );
266                         }
267                     }
268                     /*
269                     let (args1, args2);
270                     /*let mut args = if let Some(llextra) = place.llextra {
271                         args2 = [place.llval, llextra];
272                         &args2[..]
273                     } else {
274                         args1 = [place.llval];
275                         &args1[..]
276                     };*/
277                     let (drop_fn, fn_ty) = match ty.sty {
278                     ty::Dynamic(..) => {
279                     let fn_ty = drop_fn.ty(bx.cx.tcx);
280                     let sig = common::ty_fn_sig(bx.cx, fn_ty);
281                     let sig = bx.tcx().normalize_erasing_late_bound_regions(
282                     ty::ParamEnv::reveal_all(),
283                     &sig,
284                     );
285                     let fn_ty = FnType::new_vtable(bx.cx, sig, &[]);
286                     let vtable = args[1];
287                     args = &args[..1];
288                     (meth::DESTRUCTOR.get_fn(&bx, vtable, &fn_ty), fn_ty)
289                     }
290                     _ => {
291                     let value = place.to_cvalue(fx);
292                     (callee::get_fn(bx.cx, drop_fn),
293                     FnType::of_instance(bx.cx, &drop_fn))
294                     }
295                     };
296                     do_call(self, bx, fn_ty, drop_fn, args,
297                     Some((ReturnDest::Nothing, target)),
298                     unwind);*/
299                 }
300
301                 let target_ebb = fx.get_ebb(*target);
302                 fx.bcx.ins().jump(target_ebb, &[]);
303             }
304             TerminatorKind::GeneratorDrop => {
305                 unimplemented!("terminator GeneratorDrop");
306             }
307         };
308     }
309
310     fx.bcx.seal_all_blocks();
311     fx.bcx.finalize();
312 }
313
314 fn trans_stmt<'a, 'tcx: 'a>(
315     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
316     cur_ebb: Ebb,
317     stmt: &Statement<'tcx>,
318 ) {
319     let _print_guard = PrintOnPanic(|| format!("stmt {:?}", stmt));
320
321     match &stmt.kind {
322         StatementKind::StorageLive(..) | StatementKind::StorageDead(..) => {} // Those are not very useful
323         _ => {
324             let inst = fx.bcx.func.layout.last_inst(cur_ebb).unwrap();
325             fx.add_comment(inst, format!("{:?}", stmt));
326         }
327     }
328
329     match &stmt.kind {
330         StatementKind::SetDiscriminant {
331             place,
332             variant_index,
333         } => {
334             let place = trans_place(fx, place);
335             let layout = place.layout();
336             if layout.for_variant(&*fx, *variant_index).abi == layout::Abi::Uninhabited {
337                 return;
338             }
339             match layout.variants {
340                 layout::Variants::Single { index } => {
341                     assert_eq!(index, *variant_index);
342                 }
343                 layout::Variants::Tagged { .. } => {
344                     let ptr = place.place_field(fx, mir::Field::new(0));
345                     let to = layout
346                         .ty
347                         .ty_adt_def()
348                         .unwrap()
349                         .discriminant_for_variant(fx.tcx, *variant_index)
350                         .val;
351                     let discr = CValue::const_val(fx, ptr.layout().ty, to as u64 as i64);
352                     ptr.write_cvalue(fx, discr);
353                 }
354                 layout::Variants::NicheFilling {
355                     dataful_variant,
356                     ref niche_variants,
357                     niche_start,
358                     ..
359                 } => {
360                     if *variant_index != dataful_variant {
361                         let niche = place.place_field(fx, mir::Field::new(0));
362                         //let niche_llty = niche.layout.immediate_llvm_type(bx.cx);
363                         let niche_value =
364                             ((variant_index.as_u32() - niche_variants.start().as_u32()) as u128)
365                                 .wrapping_add(niche_start);
366                         // FIXME(eddyb) Check the actual primitive type here.
367                         let niche_llval = if niche_value == 0 {
368                             CValue::const_val(fx, niche.layout().ty, 0)
369                         } else {
370                             CValue::const_val(fx, niche.layout().ty, niche_value as u64 as i64)
371                         };
372                         niche.write_cvalue(fx, niche_llval);
373                     }
374                 }
375             }
376         }
377         StatementKind::Assign(to_place, rval) => {
378             let lval = trans_place(fx, to_place);
379             let dest_layout = lval.layout();
380             match &**rval {
381                 Rvalue::Use(operand) => {
382                     let val = trans_operand(fx, operand);
383                     lval.write_cvalue(fx, val);
384                 }
385                 Rvalue::Ref(_, _, place) => {
386                     let place = trans_place(fx, place);
387                     place.write_place_ref(fx, lval);
388                 }
389                 Rvalue::BinaryOp(bin_op, lhs, rhs) => {
390                     let ty = fx.monomorphize(&lhs.ty(fx.mir, fx.tcx));
391                     let lhs = trans_operand(fx, lhs);
392                     let rhs = trans_operand(fx, rhs);
393
394                     let res = match ty.sty {
395                         ty::Bool => trans_bool_binop(fx, *bin_op, lhs, rhs, lval.layout().ty),
396                         ty::Uint(_) => {
397                             trans_int_binop(fx, *bin_op, lhs, rhs, lval.layout().ty, false)
398                         }
399                         ty::Int(_) => {
400                             trans_int_binop(fx, *bin_op, lhs, rhs, lval.layout().ty, true)
401                         }
402                         ty::Float(_) => trans_float_binop(fx, *bin_op, lhs, rhs, lval.layout().ty),
403                         ty::Char => trans_char_binop(fx, *bin_op, lhs, rhs, lval.layout().ty),
404                         ty::RawPtr(..) => trans_ptr_binop(fx, *bin_op, lhs, rhs, lval.layout().ty),
405                         _ => unimplemented!("binop {:?} for {:?}", bin_op, ty),
406                     };
407                     lval.write_cvalue(fx, res);
408                 }
409                 Rvalue::CheckedBinaryOp(bin_op, lhs, rhs) => {
410                     let ty = fx.monomorphize(&lhs.ty(fx.mir, fx.tcx));
411                     let lhs = trans_operand(fx, lhs);
412                     let rhs = trans_operand(fx, rhs);
413
414                     let res = match ty.sty {
415                         ty::Uint(_) => {
416                             trans_checked_int_binop(fx, *bin_op, lhs, rhs, lval.layout().ty, false)
417                         }
418                         ty::Int(_) => {
419                             trans_checked_int_binop(fx, *bin_op, lhs, rhs, lval.layout().ty, true)
420                         }
421                         _ => unimplemented!("checked binop {:?} for {:?}", bin_op, ty),
422                     };
423                     lval.write_cvalue(fx, res);
424                 }
425                 Rvalue::UnaryOp(un_op, operand) => {
426                     let operand = trans_operand(fx, operand);
427                     let layout = operand.layout();
428                     let val = operand.load_value(fx);
429                     let res = match un_op {
430                         UnOp::Not => {
431                             match layout.ty.sty {
432                                 ty::Bool => {
433                                     let val = fx.bcx.ins().uextend(types::I32, val); // WORKAROUND for CraneStation/cranelift#466
434                                     let res = fx.bcx.ins().icmp_imm(IntCC::Equal, val, 0);
435                                     fx.bcx.ins().bint(types::I8, res)
436                                 }
437                                 ty::Uint(_) | ty::Int(_) => fx.bcx.ins().bnot(val),
438                                 _ => unimplemented!("un op Not for {:?}", layout.ty),
439                             }
440                         }
441                         UnOp::Neg => match layout.ty.sty {
442                             ty::Int(_) => {
443                                 let clif_ty = fx.clif_type(layout.ty).unwrap();
444                                 let zero = fx.bcx.ins().iconst(clif_ty, 0);
445                                 fx.bcx.ins().isub(zero, val)
446                             }
447                             ty::Float(_) => fx.bcx.ins().fneg(val),
448                             _ => unimplemented!("un op Neg for {:?}", layout.ty),
449                         },
450                     };
451                     lval.write_cvalue(fx, CValue::ByVal(res, layout));
452                 }
453                 Rvalue::Cast(CastKind::ReifyFnPointer, operand, ty) => {
454                     let operand = trans_operand(fx, operand);
455                     let layout = fx.layout_of(ty);
456                     lval.write_cvalue(fx, operand.unchecked_cast_to(layout));
457                 }
458                 Rvalue::Cast(CastKind::UnsafeFnPointer, operand, ty) => {
459                     let operand = trans_operand(fx, operand);
460                     let layout = fx.layout_of(ty);
461                     lval.write_cvalue(fx, operand.unchecked_cast_to(layout));
462                 }
463                 Rvalue::Cast(CastKind::Misc, operand, to_ty) => {
464                     let operand = trans_operand(fx, operand);
465                     let from_ty = operand.layout().ty;
466                     match (&from_ty.sty, &to_ty.sty) {
467                         (ty::Ref(..), ty::Ref(..))
468                         | (ty::Ref(..), ty::RawPtr(..))
469                         | (ty::RawPtr(..), ty::Ref(..))
470                         | (ty::RawPtr(..), ty::RawPtr(..))
471                         | (ty::FnPtr(..), ty::RawPtr(..)) => {
472                             lval.write_cvalue(fx, operand.unchecked_cast_to(dest_layout));
473                         }
474                         (ty::RawPtr(..), ty::Uint(_))
475                         | (ty::RawPtr(..), ty::Int(_))
476                         | (ty::FnPtr(..), ty::Uint(_))
477                             if to_ty.sty == fx.tcx.types.usize.sty
478                                 || to_ty.sty == fx.tcx.types.isize.sty
479                                 || fx.clif_type(to_ty).unwrap() == pointer_ty(fx.tcx) =>
480                         {
481                             lval.write_cvalue(fx, operand.unchecked_cast_to(dest_layout));
482                         }
483                         (ty::Uint(_), ty::RawPtr(..)) if from_ty.sty == fx.tcx.types.usize.sty => {
484                             lval.write_cvalue(fx, operand.unchecked_cast_to(dest_layout));
485                         }
486                         (ty::Char, ty::Uint(_))
487                         | (ty::Uint(_), ty::Char)
488                         | (ty::Uint(_), ty::Int(_))
489                         | (ty::Uint(_), ty::Uint(_)) => {
490                             let from = operand.load_value(fx);
491                             let res = crate::common::clif_intcast(
492                                 fx,
493                                 from,
494                                 fx.clif_type(to_ty).unwrap(),
495                                 false,
496                             );
497                             lval.write_cvalue(fx, CValue::ByVal(res, dest_layout));
498                         }
499                         (ty::Int(_), ty::Int(_)) | (ty::Int(_), ty::Uint(_)) => {
500                             let from = operand.load_value(fx);
501                             let res = crate::common::clif_intcast(
502                                 fx,
503                                 from,
504                                 fx.clif_type(to_ty).unwrap(),
505                                 true,
506                             );
507                             lval.write_cvalue(fx, CValue::ByVal(res, dest_layout));
508                         }
509                         (ty::Float(from_flt), ty::Float(to_flt)) => {
510                             let from = operand.load_value(fx);
511                             let res = match (from_flt, to_flt) {
512                                 (FloatTy::F32, FloatTy::F64) => {
513                                     fx.bcx.ins().fpromote(types::F64, from)
514                                 }
515                                 (FloatTy::F64, FloatTy::F32) => {
516                                     fx.bcx.ins().fdemote(types::F32, from)
517                                 }
518                                 _ => from,
519                             };
520                             lval.write_cvalue(fx, CValue::ByVal(res, dest_layout));
521                         }
522                         (ty::Int(_), ty::Float(_)) => {
523                             let from_ty = fx.clif_type(from_ty).unwrap();
524                             let from = operand.load_value(fx);
525                             // FIXME missing encoding for fcvt_from_sint.f32.i8
526                             let from = if from_ty == types::I8 || from_ty == types::I16 {
527                                 fx.bcx.ins().sextend(types::I32, from)
528                             } else {
529                                 from
530                             };
531                             let f_type = fx.clif_type(to_ty).unwrap();
532                             let res = fx.bcx.ins().fcvt_from_sint(f_type, from);
533                             lval.write_cvalue(fx, CValue::ByVal(res, dest_layout));
534                         }
535                         (ty::Uint(_), ty::Float(_)) => {
536                             let from_ty = fx.clif_type(from_ty).unwrap();
537                             let from = operand.load_value(fx);
538                             // FIXME missing encoding for fcvt_from_uint.f32.i8
539                             let from = if from_ty == types::I8 || from_ty == types::I16 {
540                                 fx.bcx.ins().uextend(types::I32, from)
541                             } else {
542                                 from
543                             };
544                             let f_type = fx.clif_type(to_ty).unwrap();
545                             let res = fx.bcx.ins().fcvt_from_uint(f_type, from);
546                             lval.write_cvalue(fx, CValue::ByVal(res, dest_layout));
547                         }
548                         (ty::Bool, ty::Uint(_)) | (ty::Bool, ty::Int(_)) => {
549                             let to_ty = fx.clif_type(to_ty).unwrap();
550                             let from = operand.load_value(fx);
551                             let res = if to_ty != types::I8 {
552                                 fx.bcx.ins().uextend(to_ty, from)
553                             } else {
554                                 from
555                             };
556                             lval.write_cvalue(fx, CValue::ByVal(res, dest_layout));
557                         }
558                         (ty::Adt(adt_def, _substs), ty::Uint(_)) | (ty::Adt(adt_def, _substs), ty::Int(_)) if adt_def.is_enum() => {
559                             let discr = trans_get_discriminant(fx, operand, fx.layout_of(to_ty));
560                             lval.write_cvalue(fx, discr);
561                         }
562                         _ => unimpl!("rval misc {:?} {:?}", from_ty, to_ty),
563                     }
564                 }
565                 Rvalue::Cast(CastKind::ClosureFnPointer, operand, ty) => {
566                     unimplemented!("rval closure_fn_ptr {:?} {:?}", operand, ty)
567                 }
568                 Rvalue::Cast(CastKind::Unsize, operand, _ty) => {
569                     let operand = trans_operand(fx, operand);
570                     operand.unsize_value(fx, lval);
571                 }
572                 Rvalue::Discriminant(place) => {
573                     let place = trans_place(fx, place).to_cvalue(fx);
574                     let discr = trans_get_discriminant(fx, place, dest_layout);
575                     lval.write_cvalue(fx, discr);
576                 }
577                 Rvalue::Repeat(operand, times) => {
578                     let operand = trans_operand(fx, operand);
579                     for i in 0..*times {
580                         let index = fx.bcx.ins().iconst(fx.pointer_type, i as i64);
581                         let to = lval.place_index(fx, index);
582                         to.write_cvalue(fx, operand);
583                     }
584                 }
585                 Rvalue::Len(place) => {
586                     let place = trans_place(fx, place);
587                     let usize_layout = fx.layout_of(fx.tcx.types.usize);
588                     let len = codegen_array_len(fx, place);
589                     lval.write_cvalue(fx, CValue::ByVal(len, usize_layout));
590                 }
591                 Rvalue::NullaryOp(NullOp::Box, content_ty) => {
592                     use rustc::middle::lang_items::ExchangeMallocFnLangItem;
593
594                     let usize_type = fx.clif_type(fx.tcx.types.usize).unwrap();
595                     let layout = fx.layout_of(content_ty);
596                     let llsize = fx.bcx.ins().iconst(usize_type, layout.size.bytes() as i64);
597                     let llalign = fx
598                         .bcx
599                         .ins()
600                         .iconst(usize_type, layout.align.abi.bytes() as i64);
601                     let box_layout = fx.layout_of(fx.tcx.mk_box(content_ty));
602
603                     // Allocate space:
604                     let def_id = match fx.tcx.lang_items().require(ExchangeMallocFnLangItem) {
605                         Ok(id) => id,
606                         Err(s) => {
607                             fx.tcx
608                                 .sess
609                                 .fatal(&format!("allocation of `{}` {}", box_layout.ty, s));
610                         }
611                     };
612                     let instance = ty::Instance::mono(fx.tcx, def_id);
613                     let func_ref = fx.get_function_ref(instance);
614                     let call = fx.bcx.ins().call(func_ref, &[llsize, llalign]);
615                     let ptr = fx.bcx.inst_results(call)[0];
616                     lval.write_cvalue(fx, CValue::ByVal(ptr, box_layout));
617                 }
618                 Rvalue::NullaryOp(NullOp::SizeOf, ty) => {
619                     assert!(lval
620                         .layout()
621                         .ty
622                         .is_sized(fx.tcx.at(DUMMY_SP), ParamEnv::reveal_all()));
623                     let ty_size = fx.layout_of(ty).size.bytes();
624                     let val = CValue::const_val(fx, fx.tcx.types.usize, ty_size as i64);
625                     lval.write_cvalue(fx, val);
626                 }
627                 Rvalue::Aggregate(kind, operands) => match **kind {
628                     AggregateKind::Array(_ty) => {
629                         for (i, operand) in operands.into_iter().enumerate() {
630                             let operand = trans_operand(fx, operand);
631                             let index = fx.bcx.ins().iconst(fx.pointer_type, i as i64);
632                             let to = lval.place_index(fx, index);
633                             to.write_cvalue(fx, operand);
634                         }
635                     }
636                     _ => unimpl!("shouldn't exist at trans {:?}", rval),
637                 },
638             }
639         }
640         StatementKind::StorageLive(_)
641         | StatementKind::StorageDead(_)
642         | StatementKind::Nop
643         | StatementKind::FakeRead(..)
644         | StatementKind::Retag { .. }
645         | StatementKind::AscribeUserType(..) => {}
646
647         StatementKind::InlineAsm { .. } => unimpl!("Inline assembly is not supported"),
648     }
649 }
650
651 fn codegen_array_len<'a, 'tcx: 'a>(
652     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
653     place: CPlace<'tcx>,
654 ) -> Value {
655     match place.layout().ty.sty {
656         ty::Array(_elem_ty, len) => {
657             let len = crate::constant::force_eval_const(fx, len).unwrap_usize(fx.tcx) as i64;
658             fx.bcx.ins().iconst(fx.pointer_type, len)
659         }
660         ty::Slice(_elem_ty) => match place {
661             CPlace::Addr(_, size, _) => size.unwrap(),
662             CPlace::Var(_, _) => unreachable!(),
663         },
664         _ => bug!("Rvalue::Len({:?})", place),
665     }
666 }
667
668 pub fn trans_get_discriminant<'a, 'tcx: 'a>(
669     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
670     value: CValue<'tcx>,
671     dest_layout: TyLayout<'tcx>,
672 ) -> CValue<'tcx> {
673     let layout = value.layout();
674
675     if layout.abi == layout::Abi::Uninhabited {
676         trap_unreachable(&mut fx.bcx);
677     }
678     match layout.variants {
679         layout::Variants::Single { index } => {
680             let discr_val = layout
681                 .ty
682                 .ty_adt_def()
683                 .map_or(index.as_u32() as u128, |def| {
684                     def.discriminant_for_variant(fx.tcx, index).val
685                 });
686             return CValue::const_val(fx, dest_layout.ty, discr_val as u64 as i64);
687         }
688         layout::Variants::Tagged { .. } | layout::Variants::NicheFilling { .. } => {}
689     }
690
691     let discr = value.value_field(fx, mir::Field::new(0));
692     let discr_ty = discr.layout().ty;
693     let lldiscr = discr.load_value(fx);
694     match layout.variants {
695         layout::Variants::Single { .. } => bug!(),
696         layout::Variants::Tagged { ref tag, .. } => {
697             let signed = match tag.value {
698                 layout::Int(_, signed) => signed,
699                 _ => false,
700             };
701             let val = clif_intcast(fx, lldiscr, fx.clif_type(dest_layout.ty).unwrap(), signed);
702             return CValue::ByVal(val, dest_layout);
703         }
704         layout::Variants::NicheFilling {
705             dataful_variant,
706             ref niche_variants,
707             niche_start,
708             ..
709         } => {
710             let niche_llty = fx.clif_type(discr_ty).unwrap();
711             let dest_clif_ty = fx.clif_type(dest_layout.ty).unwrap();
712             if niche_variants.start() == niche_variants.end() {
713                 let b = fx
714                     .bcx
715                     .ins()
716                     .icmp_imm(IntCC::Equal, lldiscr, niche_start as u64 as i64);
717                 let if_true = fx
718                     .bcx
719                     .ins()
720                     .iconst(dest_clif_ty, niche_variants.start().as_u32() as i64);
721                 let if_false = fx
722                     .bcx
723                     .ins()
724                     .iconst(dest_clif_ty, dataful_variant.as_u32() as i64);
725                 let val = fx.bcx.ins().select(b, if_true, if_false);
726                 return CValue::ByVal(val, dest_layout);
727             } else {
728                 // Rebase from niche values to discriminant values.
729                 let delta = niche_start.wrapping_sub(niche_variants.start().as_u32() as u128);
730                 let delta = fx.bcx.ins().iconst(niche_llty, delta as u64 as i64);
731                 let lldiscr = fx.bcx.ins().isub(lldiscr, delta);
732                 let b = fx.bcx.ins().icmp_imm(
733                     IntCC::UnsignedLessThanOrEqual,
734                     lldiscr,
735                     niche_variants.end().as_u32() as i64,
736                 );
737                 let if_true =
738                     clif_intcast(fx, lldiscr, fx.clif_type(dest_layout.ty).unwrap(), false);
739                 let if_false = fx
740                     .bcx
741                     .ins()
742                     .iconst(dest_clif_ty, dataful_variant.as_u32() as i64);
743                 let val = fx.bcx.ins().select(b, if_true, if_false);
744                 return CValue::ByVal(val, dest_layout);
745             }
746         }
747     }
748 }
749
750 macro_rules! binop_match {
751     (@single $fx:expr, $bug_fmt:expr, $var:expr, $signed:expr, $lhs:expr, $rhs:expr, $ret_ty:expr, bug) => {
752         bug!("binop {} on {} lhs: {:?} rhs: {:?}", stringify!($var), $bug_fmt, $lhs, $rhs)
753     };
754     (@single $fx:expr, $bug_fmt:expr, $var:expr, $signed:expr, $lhs:expr, $rhs:expr, $ret_ty:expr, icmp($cc:ident)) => {{
755         assert_eq!($fx.tcx.types.bool, $ret_ty);
756         let ret_layout = $fx.layout_of($ret_ty);
757
758         let b = $fx.bcx.ins().icmp(IntCC::$cc, $lhs, $rhs);
759         CValue::ByVal($fx.bcx.ins().bint(types::I8, b), ret_layout)
760     }};
761     (@single $fx:expr, $bug_fmt:expr, $var:expr, $signed:expr, $lhs:expr, $rhs:expr, $ret_ty:expr, fcmp($cc:ident)) => {{
762         assert_eq!($fx.tcx.types.bool, $ret_ty);
763         let ret_layout = $fx.layout_of($ret_ty);
764         let b = $fx.bcx.ins().fcmp(FloatCC::$cc, $lhs, $rhs);
765         CValue::ByVal($fx.bcx.ins().bint(types::I8, b), ret_layout)
766     }};
767     (@single $fx:expr, $bug_fmt:expr, $var:expr, $signed:expr, $lhs:expr, $rhs:expr, $ret_ty:expr, custom(|| $body:expr)) => {{
768         $body
769     }};
770     (@single $fx:expr, $bug_fmt:expr, $var:expr, $signed:expr, $lhs:expr, $rhs:expr, $ret_ty:expr, $name:ident) => {{
771         let ret_layout = $fx.layout_of($ret_ty);
772         CValue::ByVal($fx.bcx.ins().$name($lhs, $rhs), ret_layout)
773     }};
774     (
775         $fx:expr, $bin_op:expr, $signed:expr, $lhs:expr, $rhs:expr, $ret_ty:expr, $bug_fmt:expr;
776         $(
777             $var:ident ($sign:pat) $name:tt $( ( $($next:tt)* ) )? ;
778         )*
779     ) => {{
780         let lhs = $lhs.load_value($fx);
781         let rhs = $rhs.load_value($fx);
782         match ($bin_op, $signed) {
783             $(
784                 (BinOp::$var, $sign) => binop_match!(@single $fx, $bug_fmt, $var, $signed, lhs, rhs, $ret_ty, $name $( ( $($next)* ) )?),
785             )*
786         }
787     }}
788 }
789
790 fn trans_bool_binop<'a, 'tcx: 'a>(
791     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
792     bin_op: BinOp,
793     lhs: CValue<'tcx>,
794     rhs: CValue<'tcx>,
795     ty: Ty<'tcx>,
796 ) -> CValue<'tcx> {
797     let res = binop_match! {
798         fx, bin_op, false, lhs, rhs, ty, "bool";
799         Add (_) bug;
800         Sub (_) bug;
801         Mul (_) bug;
802         Div (_) bug;
803         Rem (_) bug;
804         BitXor (_) bxor;
805         BitAnd (_) band;
806         BitOr (_) bor;
807         Shl (_) bug;
808         Shr (_) bug;
809
810         Eq (_) icmp(Equal);
811         Lt (_) icmp(UnsignedLessThan);
812         Le (_) icmp(UnsignedLessThanOrEqual);
813         Ne (_) icmp(NotEqual);
814         Ge (_) icmp(UnsignedGreaterThanOrEqual);
815         Gt (_) icmp(UnsignedGreaterThan);
816
817         Offset (_) bug;
818     };
819
820     res
821 }
822
823 pub fn trans_int_binop<'a, 'tcx: 'a>(
824     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
825     bin_op: BinOp,
826     lhs: CValue<'tcx>,
827     rhs: CValue<'tcx>,
828     out_ty: Ty<'tcx>,
829     signed: bool,
830 ) -> CValue<'tcx> {
831     if bin_op != BinOp::Shl && bin_op != BinOp::Shr {
832         assert_eq!(
833             lhs.layout().ty,
834             rhs.layout().ty,
835             "int binop requires lhs and rhs of same type"
836         );
837     }
838     binop_match! {
839         fx, bin_op, signed, lhs, rhs, out_ty, "int/uint";
840         Add (_) iadd;
841         Sub (_) isub;
842         Mul (_) imul;
843         Div (false) udiv;
844         Div (true) sdiv;
845         Rem (false) urem;
846         Rem (true) srem;
847         BitXor (_) bxor;
848         BitAnd (_) band;
849         BitOr (_) bor;
850         Shl (_) ishl;
851         Shr (false) ushr;
852         Shr (true) sshr;
853
854         Eq (_) icmp(Equal);
855         Lt (false) icmp(UnsignedLessThan);
856         Lt (true) icmp(SignedLessThan);
857         Le (false) icmp(UnsignedLessThanOrEqual);
858         Le (true) icmp(SignedLessThanOrEqual);
859         Ne (_) icmp(NotEqual);
860         Ge (false) icmp(UnsignedGreaterThanOrEqual);
861         Ge (true) icmp(SignedGreaterThanOrEqual);
862         Gt (false) icmp(UnsignedGreaterThan);
863         Gt (true) icmp(SignedGreaterThan);
864
865         Offset (_) bug;
866     }
867 }
868
869 pub fn trans_checked_int_binop<'a, 'tcx: 'a>(
870     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
871     bin_op: BinOp,
872     in_lhs: CValue<'tcx>,
873     in_rhs: CValue<'tcx>,
874     out_ty: Ty<'tcx>,
875     signed: bool,
876 ) -> CValue<'tcx> {
877     if bin_op != BinOp::Shl && bin_op != BinOp::Shr {
878         assert_eq!(
879             in_lhs.layout().ty,
880             in_rhs.layout().ty,
881             "checked int binop requires lhs and rhs of same type"
882         );
883     }
884
885     let lhs = in_lhs.load_value(fx);
886     let rhs = in_rhs.load_value(fx);
887     let res = match bin_op {
888         BinOp::Add => fx.bcx.ins().iadd(lhs, rhs),
889         BinOp::Sub => fx.bcx.ins().isub(lhs, rhs),
890         BinOp::Mul => fx.bcx.ins().imul(lhs, rhs),
891         BinOp::Shl => fx.bcx.ins().ishl(lhs, rhs),
892         BinOp::Shr => {
893             if !signed {
894                 fx.bcx.ins().ushr(lhs, rhs)
895             } else {
896                 fx.bcx.ins().sshr(lhs, rhs)
897             }
898         }
899         _ => bug!(
900             "binop {:?} on checked int/uint lhs: {:?} rhs: {:?}",
901             bin_op,
902             in_lhs,
903             in_rhs
904         ),
905     };
906
907     // TODO: check for overflow
908     let has_overflow = fx.bcx.ins().iconst(types::I8, 0);
909
910     let out_place = CPlace::temp(fx, out_ty);
911     let out_layout = out_place.layout();
912     out_place.write_cvalue(fx, CValue::ByValPair(res, has_overflow, out_layout));
913
914     out_place.to_cvalue(fx)
915 }
916
917 fn trans_float_binop<'a, 'tcx: 'a>(
918     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
919     bin_op: BinOp,
920     lhs: CValue<'tcx>,
921     rhs: CValue<'tcx>,
922     ty: Ty<'tcx>,
923 ) -> CValue<'tcx> {
924     let res = binop_match! {
925         fx, bin_op, false, lhs, rhs, ty, "float";
926         Add (_) fadd;
927         Sub (_) fsub;
928         Mul (_) fmul;
929         Div (_) fdiv;
930         Rem (_) custom(|| {
931             assert_eq!(lhs.layout().ty, ty);
932             assert_eq!(rhs.layout().ty, ty);
933             match ty.sty {
934                 ty::Float(FloatTy::F32) => fx.easy_call("fmodf", &[lhs, rhs], ty),
935                 ty::Float(FloatTy::F64) => fx.easy_call("fmod", &[lhs, rhs], ty),
936                 _ => bug!(),
937             }
938         });
939         BitXor (_) bxor;
940         BitAnd (_) band;
941         BitOr (_) bor;
942         Shl (_) bug;
943         Shr (_) bug;
944
945         Eq (_) fcmp(Equal);
946         Lt (_) fcmp(LessThan);
947         Le (_) fcmp(LessThanOrEqual);
948         Ne (_) fcmp(NotEqual);
949         Ge (_) fcmp(GreaterThanOrEqual);
950         Gt (_) fcmp(GreaterThan);
951
952         Offset (_) bug;
953     };
954
955     res
956 }
957
958 fn trans_char_binop<'a, 'tcx: 'a>(
959     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
960     bin_op: BinOp,
961     lhs: CValue<'tcx>,
962     rhs: CValue<'tcx>,
963     ty: Ty<'tcx>,
964 ) -> CValue<'tcx> {
965     let res = binop_match! {
966         fx, bin_op, false, lhs, rhs, ty, "char";
967         Add (_) bug;
968         Sub (_) bug;
969         Mul (_) bug;
970         Div (_) bug;
971         Rem (_) bug;
972         BitXor (_) bug;
973         BitAnd (_) bug;
974         BitOr (_) bug;
975         Shl (_) bug;
976         Shr (_) bug;
977
978         Eq (_) icmp(Equal);
979         Lt (_) icmp(UnsignedLessThan);
980         Le (_) icmp(UnsignedLessThanOrEqual);
981         Ne (_) icmp(NotEqual);
982         Ge (_) icmp(UnsignedGreaterThanOrEqual);
983         Gt (_) icmp(UnsignedGreaterThan);
984
985         Offset (_) bug;
986     };
987
988     res
989 }
990
991 fn trans_ptr_binop<'a, 'tcx: 'a>(
992     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
993     bin_op: BinOp,
994     lhs: CValue<'tcx>,
995     rhs: CValue<'tcx>,
996     ret_ty: Ty<'tcx>,
997 ) -> CValue<'tcx> {
998     match lhs.layout().ty.sty {
999         ty::RawPtr(TypeAndMut { ty, mutbl: _ }) => {
1000             if ty.is_sized(fx.tcx.at(DUMMY_SP), ParamEnv::reveal_all()) {
1001                 binop_match! {
1002                     fx, bin_op, false, lhs, rhs, ret_ty, "ptr";
1003                     Add (_) bug;
1004                     Sub (_) bug;
1005                     Mul (_) bug;
1006                     Div (_) bug;
1007                     Rem (_) bug;
1008                     BitXor (_) bug;
1009                     BitAnd (_) bug;
1010                     BitOr (_) bug;
1011                     Shl (_) bug;
1012                     Shr (_) bug;
1013
1014                     Eq (_) icmp(Equal);
1015                     Lt (_) icmp(UnsignedLessThan);
1016                     Le (_) icmp(UnsignedLessThanOrEqual);
1017                     Ne (_) icmp(NotEqual);
1018                     Ge (_) icmp(UnsignedGreaterThanOrEqual);
1019                     Gt (_) icmp(UnsignedGreaterThan);
1020
1021                     Offset (_) iadd;
1022                 }
1023             } else {
1024                 let lhs = lhs.load_value_pair(fx).0;
1025                 let rhs = rhs.load_value_pair(fx).0;
1026                 let res = match bin_op {
1027                     BinOp::Eq => fx.bcx.ins().icmp(IntCC::Equal, lhs, rhs),
1028                     BinOp::Ne => fx.bcx.ins().icmp(IntCC::NotEqual, lhs, rhs),
1029                     _ => unimplemented!(
1030                         "trans_ptr_binop({:?}, <fat ptr>, <fat ptr>) not implemented",
1031                         bin_op
1032                     ),
1033                 };
1034
1035                 assert_eq!(fx.tcx.types.bool, ret_ty);
1036                 let ret_layout = fx.layout_of(ret_ty);
1037                 CValue::ByVal(fx.bcx.ins().bint(types::I8, res), ret_layout)
1038             }
1039         }
1040         _ => bug!("trans_ptr_binop on non ptr"),
1041     }
1042 }
1043
1044 pub fn trans_place<'a, 'tcx: 'a>(
1045     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
1046     place: &Place<'tcx>,
1047 ) -> CPlace<'tcx> {
1048     match place {
1049         Place::Local(local) => fx.get_local_place(*local),
1050         Place::Promoted(promoted) => crate::constant::trans_promoted(fx, promoted.0),
1051         Place::Static(static_) => crate::constant::codegen_static_ref(fx, static_),
1052         Place::Projection(projection) => {
1053             let base = trans_place(fx, &projection.base);
1054             match projection.elem {
1055                 ProjectionElem::Deref => base.place_deref(fx),
1056                 ProjectionElem::Field(field, _ty) => base.place_field(fx, field),
1057                 ProjectionElem::Index(local) => {
1058                     let index = fx.get_local_place(local).to_cvalue(fx).load_value(fx);
1059                     base.place_index(fx, index)
1060                 }
1061                 ProjectionElem::ConstantIndex {
1062                     offset,
1063                     min_length: _,
1064                     from_end,
1065                 } => {
1066                     let index = if !from_end {
1067                         fx.bcx.ins().iconst(fx.pointer_type, offset as i64)
1068                     } else {
1069                         let len = codegen_array_len(fx, base);
1070                         fx.bcx.ins().iadd_imm(len, -(offset as i64))
1071                     };
1072                     base.place_index(fx, index)
1073                 }
1074                 ProjectionElem::Subslice { from, to } => unimpl!(
1075                     "projection subslice {:?} from {} to {}",
1076                     projection.base,
1077                     from,
1078                     to
1079                 ),
1080                 ProjectionElem::Downcast(_adt_def, variant) => base.downcast_variant(fx, variant),
1081             }
1082         }
1083     }
1084 }
1085
1086 pub fn trans_operand<'a, 'tcx>(
1087     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
1088     operand: &Operand<'tcx>,
1089 ) -> CValue<'tcx> {
1090     match operand {
1091         Operand::Move(place) | Operand::Copy(place) => {
1092             let cplace = trans_place(fx, place);
1093             cplace.to_cvalue(fx)
1094         }
1095         Operand::Constant(const_) => crate::constant::trans_constant(fx, const_),
1096     }
1097 }