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