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