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