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