]> git.lizzy.rs Git - rust.git/blob - src/base.rs
Fix some more stuff
[rust.git] / src / base.rs
1 use rustc::ty::adjustment::PointerCast;
2
3 use crate::prelude::*;
4
5 pub fn trans_fn<'a, 'clif, 'tcx: 'a, B: Backend + 'static>(
6     cx: &mut crate::CodegenCx<'clif, 'tcx, B>,
7     instance: Instance<'tcx>,
8     linkage: Linkage,
9 ) {
10     let tcx = cx.tcx;
11
12     let mir = tcx.instance_mir(instance.def);
13
14     // Declare function
15     let (name, sig) = get_function_name_and_sig(tcx, instance, false);
16     let func_id = cx.module.declare_function(&name, linkage, &sig).unwrap();
17     let mut debug_context = cx
18         .debug_context
19         .as_mut()
20         .map(|debug_context| FunctionDebugContext::new(tcx, debug_context, mir, &name, &sig));
21
22     // Make FunctionBuilder
23     let mut func = Function::with_name_signature(ExternalName::user(0, 0), sig);
24     let mut func_ctx = FunctionBuilderContext::new();
25     let mut bcx = FunctionBuilder::new(&mut func, &mut func_ctx);
26
27     // Predefine ebb's
28     let start_ebb = bcx.create_ebb();
29     let mut ebb_map: HashMap<BasicBlock, Ebb> = HashMap::new();
30     for (bb, _bb_data) in mir.basic_blocks().iter_enumerated() {
31         ebb_map.insert(bb, bcx.create_ebb());
32     }
33
34     // Make FunctionCx
35     let pointer_type = cx.module.target_config().pointer_type();
36     let clif_comments = crate::pretty_clif::CommentWriter::new(tcx, instance);
37
38     let mut fx = FunctionCx {
39         tcx,
40         module: cx.module,
41         pointer_type,
42
43         instance,
44         mir,
45
46         bcx,
47         ebb_map,
48         local_map: HashMap::new(),
49
50         clif_comments,
51         constants: &mut cx.ccx,
52         caches: &mut cx.caches,
53         source_info_set: indexmap::IndexSet::new(),
54     };
55
56     with_unimpl_span(fx.mir.span, || {
57         crate::abi::codegen_fn_prelude(&mut fx, start_ebb);
58         codegen_fn_content(&mut fx);
59     });
60
61     // Recover all necessary data from fx, before accessing func will prevent future access to it.
62     let instance = fx.instance;
63     let clif_comments = fx.clif_comments;
64     let source_info_set = fx.source_info_set;
65
66     #[cfg(debug_assertions)]
67     crate::pretty_clif::write_clif_file(cx.tcx, "unopt", instance, &func, &clif_comments, None);
68
69     // Verify function
70     verify_func(tcx, &clif_comments, &func);
71
72     // Define function
73     let context = &mut cx.caches.context;
74     context.func = func;
75     cx.module
76         .define_function(func_id, context)
77         .unwrap();
78
79     let value_ranges = context.build_value_labels_ranges(cx.module.isa()).expect("value location ranges");
80
81     // Write optimized function to file for debugging
82     #[cfg(debug_assertions)]
83     crate::pretty_clif::write_clif_file(cx.tcx, "opt", instance, &context.func, &clif_comments, Some(&value_ranges));
84
85     // Define debuginfo for function
86     let isa = cx.module.isa();
87     debug_context
88         .as_mut()
89         .map(|x| x.define(tcx, context, isa, &source_info_set));
90
91     // Clear context to make it usable for the next function
92     context.clear();
93 }
94
95 fn verify_func(tcx: TyCtxt, writer: &crate::pretty_clif::CommentWriter, func: &Function) {
96     let flags = settings::Flags::new(settings::builder());
97     match ::cranelift::codegen::verify_function(&func, &flags) {
98         Ok(_) => {}
99         Err(err) => {
100             tcx.sess.err(&format!("{:?}", err));
101             let pretty_error = ::cranelift::codegen::print_errors::pretty_verifier_error(
102                 &func,
103                 None,
104                 Some(Box::new(writer)),
105                 err,
106             );
107             tcx.sess
108                 .fatal(&format!("cranelift verify error:\n{}", pretty_error));
109         }
110     }
111 }
112
113 fn codegen_fn_content<'a, 'tcx: 'a>(fx: &mut FunctionCx<'a, 'tcx, impl Backend>) {
114     for (bb, bb_data) in fx.mir.basic_blocks().iter_enumerated() {
115         if bb_data.is_cleanup {
116             // Unwinding after panicking is not supported
117             continue;
118         }
119
120         let ebb = fx.get_ebb(bb);
121         fx.bcx.switch_to_block(ebb);
122
123         fx.bcx.ins().nop();
124         for stmt in &bb_data.statements {
125             fx.set_debug_loc(stmt.source_info);
126             trans_stmt(fx, ebb, stmt);
127         }
128
129         #[cfg(debug_assertions)]
130         {
131             let mut terminator_head = "\n".to_string();
132             bb_data
133                 .terminator()
134                 .kind
135                 .fmt_head(&mut terminator_head)
136                 .unwrap();
137             let inst = fx.bcx.func.layout.last_inst(ebb).unwrap();
138             fx.add_comment(inst, terminator_head);
139         }
140
141         fx.set_debug_loc(bb_data.terminator().source_info);
142
143         match &bb_data.terminator().kind {
144             TerminatorKind::Goto { target } => {
145                 let ebb = fx.get_ebb(*target);
146                 fx.bcx.ins().jump(ebb, &[]);
147             }
148             TerminatorKind::Return => {
149                 crate::abi::codegen_return(fx);
150             }
151             TerminatorKind::Assert {
152                 cond,
153                 expected,
154                 msg,
155                 target,
156                 cleanup: _,
157             } => {
158                 let cond = trans_operand(fx, cond).load_scalar(fx);
159                 // TODO HACK brz/brnz for i8/i16 is not yet implemented
160                 let cond = fx.bcx.ins().uextend(types::I32, cond);
161                 let target = fx.get_ebb(*target);
162                 if *expected {
163                     fx.bcx.ins().brnz(cond, target, &[]);
164                 } else {
165                     fx.bcx.ins().brz(cond, target, &[]);
166                 };
167                 trap_panic(fx, format!("[panic] Assert {:?} failed at {:?}.", msg, bb_data.terminator().source_info.span));
168             }
169
170             TerminatorKind::SwitchInt {
171                 discr,
172                 switch_ty: _,
173                 values,
174                 targets,
175             } => {
176                 let discr = trans_operand(fx, discr).load_scalar(fx);
177                 let mut switch = ::cranelift::frontend::Switch::new();
178                 for (i, value) in values.iter().enumerate() {
179                     let ebb = fx.get_ebb(targets[i]);
180                     switch.set_entry(*value as u64, ebb);
181                 }
182                 let otherwise_ebb = fx.get_ebb(targets[targets.len() - 1]);
183                 switch.emit(&mut fx.bcx, discr, otherwise_ebb);
184             }
185             TerminatorKind::Call {
186                 func,
187                 args,
188                 destination,
189                 cleanup: _,
190                 from_hir_call: _,
191             } => {
192                 crate::abi::codegen_terminator_call(fx, func, args, destination);
193             }
194             TerminatorKind::Resume | TerminatorKind::Abort => {
195                 trap_unreachable(fx, "[corruption] Unwinding bb reached.");
196             }
197             TerminatorKind::Unreachable => {
198                 trap_unreachable(fx, "[corruption] Hit unreachable code.");
199             }
200             TerminatorKind::Yield { .. }
201             | TerminatorKind::FalseEdges { .. }
202             | TerminatorKind::FalseUnwind { .. }
203             | TerminatorKind::DropAndReplace { .. }
204             | TerminatorKind::GeneratorDrop => {
205                 bug!("shouldn't exist at trans {:?}", bb_data.terminator());
206             }
207             TerminatorKind::Drop {
208                 location,
209                 target,
210                 unwind: _,
211             } => {
212                 let drop_place = trans_place(fx, location);
213                 crate::abi::codegen_drop(fx, drop_place);
214
215                 let target_ebb = fx.get_ebb(*target);
216                 fx.bcx.ins().jump(target_ebb, &[]);
217             }
218         };
219     }
220
221     fx.bcx.seal_all_blocks();
222     fx.bcx.finalize();
223 }
224
225 fn trans_stmt<'a, 'tcx: 'a>(
226     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
227     cur_ebb: Ebb,
228     stmt: &Statement<'tcx>,
229 ) {
230     let _print_guard = PrintOnPanic(|| format!("stmt {:?}", stmt));
231
232     fx.set_debug_loc(stmt.source_info);
233
234     #[cfg(debug_assertions)]
235     match &stmt.kind {
236         StatementKind::StorageLive(..) | StatementKind::StorageDead(..) => {} // Those are not very useful
237         _ => {
238             let inst = fx.bcx.func.layout.last_inst(cur_ebb).unwrap();
239             fx.add_comment(inst, format!("{:?}", stmt));
240         }
241     }
242
243     match &stmt.kind {
244         StatementKind::SetDiscriminant {
245             place,
246             variant_index,
247         } => {
248             let place = trans_place(fx, place);
249             let layout = place.layout();
250             if layout.for_variant(&*fx, *variant_index).abi == layout::Abi::Uninhabited {
251                 return;
252             }
253             match layout.variants {
254                 layout::Variants::Single { index } => {
255                     assert_eq!(index, *variant_index);
256                 }
257                 layout::Variants::Multiple {
258                     discr: _,
259                     discr_index,
260                     discr_kind: layout::DiscriminantKind::Tag,
261                     variants: _,
262                 } => {
263                     let ptr = place.place_field(fx, mir::Field::new(discr_index));
264                     let to = layout
265                         .ty
266                         .discriminant_for_variant(fx.tcx, *variant_index)
267                         .unwrap()
268                         .val;
269                     let discr = CValue::const_val(fx, ptr.layout().ty, to as u64 as i64);
270                     ptr.write_cvalue(fx, discr);
271                 }
272                 layout::Variants::Multiple {
273                     discr: _,
274                     discr_index,
275                     discr_kind: layout::DiscriminantKind::Niche {
276                         dataful_variant,
277                         ref niche_variants,
278                         niche_start,
279                     },
280                     variants: _,
281                 } => {
282                     if *variant_index != dataful_variant {
283                         let niche = place.place_field(fx, mir::Field::new(discr_index));
284                         //let niche_llty = niche.layout.immediate_llvm_type(bx.cx);
285                         let niche_value =
286                             ((variant_index.as_u32() - niche_variants.start().as_u32()) as u128)
287                                 .wrapping_add(niche_start);
288                         // FIXME(eddyb) Check the actual primitive type here.
289                         let niche_llval = if niche_value == 0 {
290                             CValue::const_val(fx, niche.layout().ty, 0)
291                         } else {
292                             CValue::const_val(fx, niche.layout().ty, niche_value as u64 as i64)
293                         };
294                         niche.write_cvalue(fx, niche_llval);
295                     }
296                 }
297             }
298         }
299         StatementKind::Assign(to_place, rval) => {
300             let lval = trans_place(fx, to_place);
301             let dest_layout = lval.layout();
302             match &**rval {
303                 Rvalue::Use(operand) => {
304                     let val = trans_operand(fx, operand);
305                     lval.write_cvalue(fx, val);
306                 }
307                 Rvalue::Ref(_, _, place) => {
308                     let place = trans_place(fx, place);
309                     place.write_place_ref(fx, lval);
310                 }
311                 Rvalue::BinaryOp(bin_op, lhs, rhs) => {
312                     let ty = fx.monomorphize(&lhs.ty(fx.mir, fx.tcx));
313                     let lhs = trans_operand(fx, lhs);
314                     let rhs = trans_operand(fx, rhs);
315
316                     let res = match ty.sty {
317                         ty::Bool => trans_bool_binop(fx, *bin_op, lhs, rhs),
318                         ty::Uint(_) => {
319                             trans_int_binop(fx, *bin_op, lhs, rhs, lval.layout().ty, false)
320                         }
321                         ty::Int(_) => {
322                             trans_int_binop(fx, *bin_op, lhs, rhs, lval.layout().ty, true)
323                         }
324                         ty::Float(_) => trans_float_binop(fx, *bin_op, lhs, rhs, lval.layout().ty),
325                         ty::Char => trans_char_binop(fx, *bin_op, lhs, rhs, lval.layout().ty),
326                         ty::RawPtr(..) => trans_ptr_binop(fx, *bin_op, lhs, rhs, lval.layout().ty),
327                         ty::FnPtr(..) => trans_ptr_binop(fx, *bin_op, lhs, rhs, lval.layout().ty),
328                         _ => unimplemented!("binop {:?} for {:?}", bin_op, ty),
329                     };
330                     lval.write_cvalue(fx, res);
331                 }
332                 Rvalue::CheckedBinaryOp(bin_op, lhs, rhs) => {
333                     let ty = fx.monomorphize(&lhs.ty(fx.mir, fx.tcx));
334                     let lhs = trans_operand(fx, lhs);
335                     let rhs = trans_operand(fx, rhs);
336
337                     let res = match ty.sty {
338                         ty::Uint(_) => {
339                             trans_checked_int_binop(fx, *bin_op, lhs, rhs, lval.layout().ty, false)
340                         }
341                         ty::Int(_) => {
342                             trans_checked_int_binop(fx, *bin_op, lhs, rhs, lval.layout().ty, true)
343                         }
344                         _ => unimplemented!("checked binop {:?} for {:?}", bin_op, ty),
345                     };
346                     lval.write_cvalue(fx, res);
347                 }
348                 Rvalue::UnaryOp(un_op, operand) => {
349                     let operand = trans_operand(fx, operand);
350                     let layout = operand.layout();
351                     let val = operand.load_scalar(fx);
352                     let res = match un_op {
353                         UnOp::Not => {
354                             match layout.ty.sty {
355                                 ty::Bool => {
356                                     let val = fx.bcx.ins().uextend(types::I32, val); // WORKAROUND for CraneStation/cranelift#466
357                                     let res = fx.bcx.ins().icmp_imm(IntCC::Equal, val, 0);
358                                     fx.bcx.ins().bint(types::I8, res)
359                                 }
360                                 ty::Uint(_) | ty::Int(_) => {
361                                     if fx.bcx.func.dfg.value_type(val) == types::I128 {
362                                         let (a, b) = fx.bcx.ins().isplit(val);
363                                         let a = fx.bcx.ins().bnot(a);
364                                         let b = fx.bcx.ins().bnot(b);
365                                         fx.bcx.ins().iconcat(a, b)
366                                     } else {
367                                         fx.bcx.ins().bnot(val)
368                                     }
369                                 }
370                                 _ => unimplemented!("un op Not for {:?}", layout.ty),
371                             }
372                         }
373                         UnOp::Neg => match layout.ty.sty {
374                             ty::Int(_) => {
375                                 let clif_ty = fx.clif_type(layout.ty).unwrap();
376                                 if clif_ty == types::I128 {
377                                     crate::trap::trap_unreachable_ret_value(fx, layout, "i128 neg is not yet supported").load_scalar(fx)
378                                 } else {
379                                     let zero = fx.bcx.ins().iconst(clif_ty, 0);
380                                     fx.bcx.ins().isub(zero, val)
381                                 }
382                             }
383                             ty::Float(_) => fx.bcx.ins().fneg(val),
384                             _ => unimplemented!("un op Neg for {:?}", layout.ty),
385                         },
386                     };
387                     lval.write_cvalue(fx, CValue::by_val(res, layout));
388                 }
389                 Rvalue::Cast(CastKind::Pointer(PointerCast::ReifyFnPointer), operand, ty) => {
390                     let layout = fx.layout_of(ty);
391                     match fx
392                         .monomorphize(&operand.ty(&fx.mir.local_decls, fx.tcx))
393                         .sty
394                     {
395                         ty::FnDef(def_id, substs) => {
396                             let func_ref = fx.get_function_ref(
397                                 Instance::resolve(fx.tcx, ParamEnv::reveal_all(), def_id, substs)
398                                     .unwrap(),
399                             );
400                             let func_addr = fx.bcx.ins().func_addr(fx.pointer_type, func_ref);
401                             lval.write_cvalue(fx, CValue::by_val(func_addr, layout));
402                         }
403                         _ => bug!("Trying to ReifyFnPointer on non FnDef {:?}", ty),
404                     }
405                 }
406                 Rvalue::Cast(CastKind::Pointer(PointerCast::UnsafeFnPointer), operand, ty)
407                 | Rvalue::Cast(CastKind::Pointer(PointerCast::MutToConstPointer), operand, ty) => {
408                     let operand = trans_operand(fx, operand);
409                     let layout = fx.layout_of(ty);
410                     lval.write_cvalue(fx, operand.unchecked_cast_to(layout));
411                 }
412                 Rvalue::Cast(CastKind::Misc, operand, to_ty) => {
413                     let operand = trans_operand(fx, operand);
414                     let from_ty = operand.layout().ty;
415
416                     fn is_fat_ptr<'a, 'tcx: 'a>(fx: &FunctionCx<'a, 'tcx, impl Backend>, ty: Ty<'tcx>) -> bool {
417                         ty
418                             .builtin_deref(true)
419                             .map(|ty::TypeAndMut {ty: pointee_ty, mutbl: _ }| fx.layout_of(pointee_ty).is_unsized())
420                             .unwrap_or(false)
421                     }
422
423                     if is_fat_ptr(fx, from_ty) {
424                         if is_fat_ptr(fx, to_ty) {
425                             // fat-ptr -> fat-ptr
426                             lval.write_cvalue(fx, operand.unchecked_cast_to(dest_layout));
427                         } else {
428                             // fat-ptr -> thin-ptr
429                             let (ptr, _extra) = operand.load_scalar_pair(fx);
430                             lval.write_cvalue(fx, CValue::by_val(ptr, dest_layout))
431                         }
432                     } else if let ty::Adt(adt_def, _substs) = from_ty.sty {
433                         // enum -> discriminant value
434                         assert!(adt_def.is_enum());
435                         match to_ty.sty {
436                             ty::Uint(_) | ty::Int(_) => {},
437                             _ => unreachable!("cast adt {} -> {}", from_ty, to_ty),
438                         }
439
440                         // FIXME avoid forcing to stack
441                         let place =
442                             CPlace::for_addr(operand.force_stack(fx), operand.layout());
443                         let discr = trans_get_discriminant(fx, place, fx.layout_of(to_ty));
444                         lval.write_cvalue(fx, discr);
445                     } else {
446                         let from_clif_ty = fx.clif_type(from_ty).unwrap();
447                         let to_clif_ty = fx.clif_type(to_ty).unwrap();
448                         let from = operand.load_scalar(fx);
449
450                         let signed = match from_ty.sty {
451                             ty::Ref(..) | ty::RawPtr(..) | ty::FnPtr(..) | ty::Char | ty::Uint(..) | ty::Bool => false,
452                             ty::Int(..) => true,
453                             ty::Float(..) => false, // `signed` is unused for floats
454                             _ => panic!("{}", from_ty),
455                         };
456
457                         let res = if from_clif_ty.is_int() && to_clif_ty.is_int() {
458                             // int-like -> int-like
459                             crate::common::clif_intcast(
460                                 fx,
461                                 from,
462                                 to_clif_ty,
463                                 signed,
464                             )
465                         } else if from_clif_ty.is_int() && to_clif_ty.is_float() {
466                             // int-like -> float
467                             if signed {
468                                 fx.bcx.ins().fcvt_from_sint(to_clif_ty, from)
469                             } else {
470                                 fx.bcx.ins().fcvt_from_uint(to_clif_ty, from)
471                             }
472                         } else if from_clif_ty.is_float() && to_clif_ty.is_int() {
473                             // float -> int-like
474                             let from = operand.load_scalar(fx);
475                             if signed {
476                                 fx.bcx.ins().fcvt_to_sint_sat(to_clif_ty, from)
477                             } else {
478                                 fx.bcx.ins().fcvt_to_uint_sat(to_clif_ty, from)
479                             }
480                         } else if from_clif_ty.is_float() && to_clif_ty.is_float() {
481                             // float -> float
482                             match (from_clif_ty, to_clif_ty) {
483                                 (types::F32, types::F64) => {
484                                     fx.bcx.ins().fpromote(types::F64, from)
485                                 }
486                                 (types::F64, types::F32) => {
487                                     fx.bcx.ins().fdemote(types::F32, from)
488                                 }
489                                 _ => from,
490                             }
491                         } else {
492                             unimpl!("rval misc {:?} {:?}", from_ty, to_ty)
493                         };
494                         lval.write_cvalue(fx, CValue::by_val(res, dest_layout));
495                     }
496                 }
497                 Rvalue::Cast(CastKind::Pointer(PointerCast::ClosureFnPointer(_)), operand, _ty) => {
498                     let operand = trans_operand(fx, operand);
499                     match operand.layout().ty.sty {
500                         ty::Closure(def_id, substs) => {
501                             let instance = Instance::resolve_closure(
502                                 fx.tcx,
503                                 def_id,
504                                 substs,
505                                 ty::ClosureKind::FnOnce,
506                             );
507                             let func_ref = fx.get_function_ref(instance);
508                             let func_addr = fx.bcx.ins().func_addr(fx.pointer_type, func_ref);
509                             lval.write_cvalue(fx, CValue::by_val(func_addr, lval.layout()));
510                         }
511                         _ => {
512                             bug!("{} cannot be cast to a fn ptr", operand.layout().ty)
513                         }
514                     }
515                 }
516                 Rvalue::Cast(CastKind::Pointer(PointerCast::Unsize), operand, _ty) => {
517                     let operand = trans_operand(fx, operand);
518                     operand.unsize_value(fx, lval);
519                 }
520                 Rvalue::Discriminant(place) => {
521                     let place = trans_place(fx, place);
522                     let discr = trans_get_discriminant(fx, place, dest_layout);
523                     lval.write_cvalue(fx, discr);
524                 }
525                 Rvalue::Repeat(operand, times) => {
526                     let operand = trans_operand(fx, operand);
527                     for i in 0..*times {
528                         let index = fx.bcx.ins().iconst(fx.pointer_type, i as i64);
529                         let to = lval.place_index(fx, index);
530                         to.write_cvalue(fx, operand);
531                     }
532                 }
533                 Rvalue::Len(place) => {
534                     let place = trans_place(fx, place);
535                     let usize_layout = fx.layout_of(fx.tcx.types.usize);
536                     let len = codegen_array_len(fx, place);
537                     lval.write_cvalue(fx, CValue::by_val(len, usize_layout));
538                 }
539                 Rvalue::NullaryOp(NullOp::Box, content_ty) => {
540                     use rustc::middle::lang_items::ExchangeMallocFnLangItem;
541
542                     let usize_type = fx.clif_type(fx.tcx.types.usize).unwrap();
543                     let layout = fx.layout_of(content_ty);
544                     let llsize = fx.bcx.ins().iconst(usize_type, layout.size.bytes() as i64);
545                     let llalign = fx
546                         .bcx
547                         .ins()
548                         .iconst(usize_type, layout.align.abi.bytes() as i64);
549                     let box_layout = fx.layout_of(fx.tcx.mk_box(content_ty));
550
551                     // Allocate space:
552                     let def_id = match fx.tcx.lang_items().require(ExchangeMallocFnLangItem) {
553                         Ok(id) => id,
554                         Err(s) => {
555                             fx.tcx
556                                 .sess
557                                 .fatal(&format!("allocation of `{}` {}", box_layout.ty, s));
558                         }
559                     };
560                     let instance = ty::Instance::mono(fx.tcx, def_id);
561                     let func_ref = fx.get_function_ref(instance);
562                     let call = fx.bcx.ins().call(func_ref, &[llsize, llalign]);
563                     let ptr = fx.bcx.inst_results(call)[0];
564                     lval.write_cvalue(fx, CValue::by_val(ptr, box_layout));
565                 }
566                 Rvalue::NullaryOp(NullOp::SizeOf, ty) => {
567                     assert!(lval
568                         .layout()
569                         .ty
570                         .is_sized(fx.tcx.at(DUMMY_SP), ParamEnv::reveal_all()));
571                     let ty_size = fx.layout_of(ty).size.bytes();
572                     let val = CValue::const_val(fx, fx.tcx.types.usize, ty_size as i64);
573                     lval.write_cvalue(fx, val);
574                 }
575                 Rvalue::Aggregate(kind, operands) => match **kind {
576                     AggregateKind::Array(_ty) => {
577                         for (i, operand) in operands.into_iter().enumerate() {
578                             let operand = trans_operand(fx, operand);
579                             let index = fx.bcx.ins().iconst(fx.pointer_type, i as i64);
580                             let to = lval.place_index(fx, index);
581                             to.write_cvalue(fx, operand);
582                         }
583                     }
584                     _ => unimpl!("shouldn't exist at trans {:?}", rval),
585                 },
586             }
587         }
588         StatementKind::StorageLive(_)
589         | StatementKind::StorageDead(_)
590         | StatementKind::Nop
591         | StatementKind::FakeRead(..)
592         | StatementKind::Retag { .. }
593         | StatementKind::AscribeUserType(..) => {}
594
595         StatementKind::InlineAsm(asm) => {
596             use syntax::ast::Name;
597             let InlineAsm { asm, outputs: _, inputs: _ } = &**asm;
598             let rustc::hir::InlineAsm {
599                 asm: asm_code, // Name
600                 outputs, // Vec<Name>
601                 inputs, // Vec<Name>
602                 clobbers, // Vec<Name>
603                 volatile, // bool
604                 alignstack, // bool
605                 dialect: _, // syntax::ast::AsmDialect
606                 asm_str_style: _,
607                 ctxt: _,
608             } = asm;
609             match &*asm_code.as_str() {
610                 "cpuid" | "cpuid\n" => {
611                     assert_eq!(inputs, &[Name::intern("{eax}"), Name::intern("{ecx}")]);
612
613                     assert_eq!(outputs.len(), 4);
614                     for (i, c) in (&["={eax}", "={ebx}", "={ecx}", "={edx}"]).iter().enumerate() {
615                         assert_eq!(&outputs[i].constraint.as_str(), c);
616                         assert!(!outputs[i].is_rw);
617                         assert!(!outputs[i].is_indirect);
618                     }
619
620                     assert_eq!(clobbers, &[Name::intern("rbx")]);
621
622                     assert!(!volatile);
623                     assert!(!alignstack);
624
625                     crate::trap::trap_unimplemented(fx, "__cpuid_count arch intrinsic is not supported");
626                 }
627                 "xgetbv" => {
628                     assert_eq!(inputs, &[Name::intern("{ecx}")]);
629
630                     assert_eq!(outputs.len(), 2);
631                     for (i, c) in (&["={eax}", "={edx}"]).iter().enumerate() {
632                         assert_eq!(&outputs[i].constraint.as_str(), c);
633                         assert!(!outputs[i].is_rw);
634                         assert!(!outputs[i].is_indirect);
635                     }
636
637                     assert_eq!(clobbers, &[]);
638
639                     assert!(!volatile);
640                     assert!(!alignstack);
641
642                     crate::trap::trap_unimplemented(fx, "_xgetbv arch intrinsic is not supported");
643                 }
644                 _ if fx.tcx.symbol_name(fx.instance).as_str() == "__rust_probestack" => {
645                     crate::trap::trap_unimplemented(fx, "__rust_probestack is not supported");
646                 }
647                 _ => unimpl!("Inline assembly is not supported"),
648             }
649         }
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) => place
663             .to_addr_maybe_unsized(fx)
664             .1
665             .expect("Length metadata for slice place"),
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     place: CPlace<'tcx>,
673     dest_layout: TyLayout<'tcx>,
674 ) -> CValue<'tcx> {
675     let layout = place.layout();
676
677     if layout.abi == layout::Abi::Uninhabited {
678         return trap_unreachable_ret_value(fx, dest_layout, "[panic] Tried to get discriminant for uninhabited type.");
679     }
680
681     let (discr_scalar, discr_index, discr_kind) = match &layout.variants {
682         layout::Variants::Single { index } => {
683             let discr_val = layout
684                 .ty
685                 .ty_adt_def()
686                 .map_or(index.as_u32() as u128, |def| {
687                     def.discriminant_for_variant(fx.tcx, *index).val
688                 });
689             return CValue::const_val(fx, dest_layout.ty, discr_val as u64 as i64);
690         }
691         layout::Variants::Multiple { discr, discr_index, discr_kind, variants: _ } => {
692             (discr, *discr_index, discr_kind)
693         }
694     };
695
696     let discr = place.place_field(fx, mir::Field::new(discr_index)).to_cvalue(fx);
697     let discr_ty = discr.layout().ty;
698     let lldiscr = discr.load_scalar(fx);
699     match discr_kind {
700         layout::DiscriminantKind::Tag => {
701             let signed = match discr_scalar.value {
702                 layout::Int(_, signed) => signed,
703                 _ => false,
704             };
705             let val = clif_intcast(fx, lldiscr, fx.clif_type(dest_layout.ty).unwrap(), signed);
706             return CValue::by_val(val, dest_layout);
707         }
708         layout::DiscriminantKind::Niche {
709             dataful_variant,
710             ref niche_variants,
711             niche_start,
712         } => {
713             let niche_llty = fx.clif_type(discr_ty).unwrap();
714             let dest_clif_ty = fx.clif_type(dest_layout.ty).unwrap();
715             if niche_variants.start() == niche_variants.end() {
716                 let b = fx
717                     .bcx
718                     .ins()
719                     .icmp_imm(IntCC::Equal, lldiscr, *niche_start as u64 as i64);
720                 let if_true = fx
721                     .bcx
722                     .ins()
723                     .iconst(dest_clif_ty, niche_variants.start().as_u32() as i64);
724                 let if_false = fx
725                     .bcx
726                     .ins()
727                     .iconst(dest_clif_ty, dataful_variant.as_u32() as i64);
728                 let val = fx.bcx.ins().select(b, if_true, if_false);
729                 return CValue::by_val(val, dest_layout);
730             } else {
731                 // Rebase from niche values to discriminant values.
732                 let delta = niche_start.wrapping_sub(niche_variants.start().as_u32() as u128);
733                 let delta = fx.bcx.ins().iconst(niche_llty, delta as u64 as i64);
734                 let lldiscr = fx.bcx.ins().isub(lldiscr, delta);
735                 let b = fx.bcx.ins().icmp_imm(
736                     IntCC::UnsignedLessThanOrEqual,
737                     lldiscr,
738                     niche_variants.end().as_u32() as i64,
739                 );
740                 let if_true =
741                     clif_intcast(fx, lldiscr, fx.clif_type(dest_layout.ty).unwrap(), false);
742                 let if_false = fx
743                     .bcx
744                     .ins()
745                     .iconst(dest_clif_ty, dataful_variant.as_u32() as i64);
746                 let val = fx.bcx.ins().select(b, if_true, if_false);
747                 return CValue::by_val(val, dest_layout);
748             }
749         }
750     }
751 }
752
753 macro_rules! binop_match {
754     (@single $fx:expr, $bug_fmt:expr, $var:expr, $signed:expr, $lhs:expr, $rhs:expr, $ret_ty:expr, bug) => {
755         bug!("binop {} on {} lhs: {:?} rhs: {:?}", stringify!($var), $bug_fmt, $lhs, $rhs)
756     };
757     (@single $fx:expr, $bug_fmt:expr, $var:expr, $signed:expr, $lhs:expr, $rhs:expr, $ret_ty:expr, icmp($cc:ident)) => {{
758         assert_eq!($fx.tcx.types.bool, $ret_ty);
759         let ret_layout = $fx.layout_of($ret_ty);
760
761         let b = $fx.bcx.ins().icmp(IntCC::$cc, $lhs, $rhs);
762         CValue::by_val($fx.bcx.ins().bint(types::I8, b), ret_layout)
763     }};
764     (@single $fx:expr, $bug_fmt:expr, $var:expr, $signed:expr, $lhs:expr, $rhs:expr, $ret_ty:expr, fcmp($cc:ident)) => {{
765         assert_eq!($fx.tcx.types.bool, $ret_ty);
766         let ret_layout = $fx.layout_of($ret_ty);
767         let b = $fx.bcx.ins().fcmp(FloatCC::$cc, $lhs, $rhs);
768         CValue::by_val($fx.bcx.ins().bint(types::I8, b), ret_layout)
769     }};
770     (@single $fx:expr, $bug_fmt:expr, $var:expr, $signed:expr, $lhs:expr, $rhs:expr, $ret_ty:expr, custom(|| $body:expr)) => {{
771         $body
772     }};
773     (@single $fx:expr, $bug_fmt:expr, $var:expr, $signed:expr, $lhs:expr, $rhs:expr, $ret_ty:expr, $name:ident) => {{
774         let ret_layout = $fx.layout_of($ret_ty);
775         CValue::by_val($fx.bcx.ins().$name($lhs, $rhs), ret_layout)
776     }};
777     (
778         $fx:expr, $bin_op:expr, $signed:expr, $lhs:expr, $rhs:expr, $ret_ty:expr, $bug_fmt:expr;
779         $(
780             $var:ident ($sign:pat) $name:tt $( ( $($next:tt)* ) )? ;
781         )*
782     ) => {{
783         let lhs = $lhs.load_scalar($fx);
784         let rhs = $rhs.load_scalar($fx);
785         match ($bin_op, $signed) {
786             $(
787                 (BinOp::$var, $sign) => binop_match!(@single $fx, $bug_fmt, $var, $signed, lhs, rhs, $ret_ty, $name $( ( $($next)* ) )?),
788             )*
789         }
790     }}
791 }
792
793 fn trans_bool_binop<'a, 'tcx: 'a>(
794     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
795     bin_op: BinOp,
796     lhs: CValue<'tcx>,
797     rhs: CValue<'tcx>,
798 ) -> CValue<'tcx> {
799     let res = binop_match! {
800         fx, bin_op, false, lhs, rhs, fx.tcx.types.bool, "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
841     if lhs.layout().ty == fx.tcx.types.u128 || lhs.layout().ty == fx.tcx.types.i128 {
842         if out_ty == fx.tcx.types.bool {
843             let layout = fx.layout_of(fx.tcx.types.bool);
844             let val = fx.bcx.ins().iconst(types::I8, 0);
845             return CValue::by_val(val, layout);
846         } else {
847             let layout = fx.layout_of(out_ty);
848             let a = fx.bcx.ins().iconst(types::I64, 42);
849             let b = fx.bcx.ins().iconst(types::I64, 0);
850             let val = fx.bcx.ins().iconcat(a, b);
851             return CValue::by_val(val, layout);
852         }
853     }
854
855     binop_match! {
856         fx, bin_op, signed, lhs, rhs, out_ty, "int/uint";
857         Add (_) iadd;
858         Sub (_) isub;
859         Mul (_) imul;
860         Div (false) udiv;
861         Div (true) sdiv;
862         Rem (false) urem;
863         Rem (true) srem;
864         BitXor (_) bxor;
865         BitAnd (_) band;
866         BitOr (_) bor;
867         Shl (_) ishl;
868         Shr (false) ushr;
869         Shr (true) sshr;
870
871         Eq (_) icmp(Equal);
872         Lt (false) icmp(UnsignedLessThan);
873         Lt (true) icmp(SignedLessThan);
874         Le (false) icmp(UnsignedLessThanOrEqual);
875         Le (true) icmp(SignedLessThanOrEqual);
876         Ne (_) icmp(NotEqual);
877         Ge (false) icmp(UnsignedGreaterThanOrEqual);
878         Ge (true) icmp(SignedGreaterThanOrEqual);
879         Gt (false) icmp(UnsignedGreaterThan);
880         Gt (true) icmp(SignedGreaterThan);
881
882         Offset (_) bug;
883     }
884 }
885
886 pub fn trans_checked_int_binop<'a, 'tcx: 'a>(
887     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
888     bin_op: BinOp,
889     in_lhs: CValue<'tcx>,
890     in_rhs: CValue<'tcx>,
891     out_ty: Ty<'tcx>,
892     signed: bool,
893 ) -> CValue<'tcx> {
894     if bin_op != BinOp::Shl && bin_op != BinOp::Shr {
895         assert_eq!(
896             in_lhs.layout().ty,
897             in_rhs.layout().ty,
898             "checked int binop requires lhs and rhs of same type"
899         );
900     }
901
902     let lhs = in_lhs.load_scalar(fx);
903     let rhs = in_rhs.load_scalar(fx);
904     let (res, has_overflow) = if in_lhs.layout().ty == fx.tcx.types.u128 || in_lhs.layout().ty == fx.tcx.types.i128 {
905         match (bin_op, signed) {
906             _ => {
907                 let a = fx.bcx.ins().iconst(types::I64, 42);
908                 let b = fx.bcx.ins().iconst(types::I64, 0);
909                 (fx.bcx.ins().iconcat(a, b), fx.bcx.ins().bconst(types::B1, false))
910             }
911         }
912     } else {
913         match bin_op {
914             BinOp::Add => {
915                 /*let (val, c_out) = fx.bcx.ins().iadd_cout(lhs, rhs);
916                 (val, c_out)*/
917                 // FIXME(CraneStation/cranelift#849) legalize iadd_cout for i8 and i16
918                 let val = fx.bcx.ins().iadd(lhs, rhs);
919                 let has_overflow = if !signed {
920                     fx.bcx.ins().icmp(IntCC::UnsignedLessThan, val, lhs)
921                 } else {
922                     let rhs_is_negative = fx.bcx.ins().icmp_imm(IntCC::SignedLessThan, rhs, 0);
923                     let slt = fx.bcx.ins().icmp(IntCC::SignedLessThan, val, lhs);
924                     fx.bcx.ins().bxor(rhs_is_negative, slt)
925                 };
926                 (val, has_overflow)
927             }
928             BinOp::Sub => {
929                 /*let (val, b_out) = fx.bcx.ins().isub_bout(lhs, rhs);
930                 (val, b_out)*/
931                 // FIXME(CraneStation/cranelift#849) legalize isub_bout for i8 and i16
932                 let val = fx.bcx.ins().isub(lhs, rhs);
933                 let has_overflow = if !signed {
934                     fx.bcx.ins().icmp(IntCC::UnsignedGreaterThan, val, lhs)
935                 } else {
936                     let rhs_is_negative = fx.bcx.ins().icmp_imm(IntCC::SignedLessThan, rhs, 0);
937                     let sgt = fx.bcx.ins().icmp(IntCC::SignedGreaterThan, val, lhs);
938                     fx.bcx.ins().bxor(rhs_is_negative, sgt)
939                 };
940                 (val, has_overflow)
941             }
942             BinOp::Mul => {
943                 let val = fx.bcx.ins().imul(lhs, rhs);
944                 /*let val_hi = if !signed {
945                     fx.bcx.ins().umulhi(lhs, rhs)
946                 } else {
947                     fx.bcx.ins().smulhi(lhs, rhs)
948                 };
949                 let has_overflow = fx.bcx.ins().icmp_imm(IntCC::NotEqual, val_hi, 0);*/
950                 // TODO: check for overflow
951                 let has_overflow = fx.bcx.ins().bconst(types::B1, false);
952                 (val, has_overflow)
953             }
954             BinOp::Shl => {
955                 let val = fx.bcx.ins().ishl(lhs, rhs);
956                 // TODO: check for overflow
957                 let has_overflow = fx.bcx.ins().bconst(types::B1, false);
958                 (val, has_overflow)
959             }
960             BinOp::Shr => {
961                 let val = if !signed {
962                     fx.bcx.ins().ushr(lhs, rhs)
963                 } else {
964                     fx.bcx.ins().sshr(lhs, rhs)
965                 };
966                 // TODO: check for overflow
967                 let has_overflow = fx.bcx.ins().bconst(types::B1, false);
968                 (val, has_overflow)
969             }
970             _ => bug!(
971                 "binop {:?} on checked int/uint lhs: {:?} rhs: {:?}",
972                 bin_op,
973                 in_lhs,
974                 in_rhs
975             ),
976         }
977     };
978
979     let has_overflow = fx.bcx.ins().bint(types::I8, has_overflow);
980     let out_place = CPlace::new_stack_slot(fx, out_ty);
981     let out_layout = out_place.layout();
982     out_place.write_cvalue(fx, CValue::by_val_pair(res, has_overflow, out_layout));
983
984     out_place.to_cvalue(fx)
985 }
986
987 fn trans_float_binop<'a, 'tcx: 'a>(
988     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
989     bin_op: BinOp,
990     lhs: CValue<'tcx>,
991     rhs: CValue<'tcx>,
992     ty: Ty<'tcx>,
993 ) -> CValue<'tcx> {
994     let res = binop_match! {
995         fx, bin_op, false, lhs, rhs, ty, "float";
996         Add (_) fadd;
997         Sub (_) fsub;
998         Mul (_) fmul;
999         Div (_) fdiv;
1000         Rem (_) custom(|| {
1001             assert_eq!(lhs.layout().ty, ty);
1002             assert_eq!(rhs.layout().ty, ty);
1003             match ty.sty {
1004                 ty::Float(FloatTy::F32) => fx.easy_call("fmodf", &[lhs, rhs], ty),
1005                 ty::Float(FloatTy::F64) => fx.easy_call("fmod", &[lhs, rhs], ty),
1006                 _ => bug!(),
1007             }
1008         });
1009         BitXor (_) bxor;
1010         BitAnd (_) band;
1011         BitOr (_) bor;
1012         Shl (_) bug;
1013         Shr (_) bug;
1014
1015         Eq (_) fcmp(Equal);
1016         Lt (_) fcmp(LessThan);
1017         Le (_) fcmp(LessThanOrEqual);
1018         Ne (_) fcmp(NotEqual);
1019         Ge (_) fcmp(GreaterThanOrEqual);
1020         Gt (_) fcmp(GreaterThan);
1021
1022         Offset (_) bug;
1023     };
1024
1025     res
1026 }
1027
1028 fn trans_char_binop<'a, 'tcx: 'a>(
1029     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
1030     bin_op: BinOp,
1031     lhs: CValue<'tcx>,
1032     rhs: CValue<'tcx>,
1033     ty: Ty<'tcx>,
1034 ) -> CValue<'tcx> {
1035     let res = binop_match! {
1036         fx, bin_op, false, lhs, rhs, ty, "char";
1037         Add (_) bug;
1038         Sub (_) bug;
1039         Mul (_) bug;
1040         Div (_) bug;
1041         Rem (_) bug;
1042         BitXor (_) bug;
1043         BitAnd (_) bug;
1044         BitOr (_) bug;
1045         Shl (_) bug;
1046         Shr (_) bug;
1047
1048         Eq (_) icmp(Equal);
1049         Lt (_) icmp(UnsignedLessThan);
1050         Le (_) icmp(UnsignedLessThanOrEqual);
1051         Ne (_) icmp(NotEqual);
1052         Ge (_) icmp(UnsignedGreaterThanOrEqual);
1053         Gt (_) icmp(UnsignedGreaterThan);
1054
1055         Offset (_) bug;
1056     };
1057
1058     res
1059 }
1060
1061 fn trans_ptr_binop<'a, 'tcx: 'a>(
1062     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
1063     bin_op: BinOp,
1064     lhs: CValue<'tcx>,
1065     rhs: CValue<'tcx>,
1066     ret_ty: Ty<'tcx>,
1067 ) -> CValue<'tcx> {
1068     let not_fat = match lhs.layout().ty.sty {
1069         ty::RawPtr(TypeAndMut { ty, mutbl: _ }) => {
1070             ty.is_sized(fx.tcx.at(DUMMY_SP), ParamEnv::reveal_all())
1071         }
1072         ty::FnPtr(..) => true,
1073         _ => bug!("trans_ptr_binop on non ptr"),
1074     };
1075     if not_fat {
1076         if let BinOp::Offset = bin_op {
1077             let (base, offset) = (lhs, rhs.load_scalar(fx));
1078             let pointee_ty = base.layout().ty.builtin_deref(true).unwrap().ty;
1079             let pointee_size = fx.layout_of(pointee_ty).size.bytes();
1080             let ptr_diff = fx.bcx.ins().imul_imm(offset, pointee_size as i64);
1081             let base_val = base.load_scalar(fx);
1082             let res = fx.bcx.ins().iadd(base_val, ptr_diff);
1083             return CValue::by_val(res, base.layout());
1084         }
1085
1086         binop_match! {
1087             fx, bin_op, false, lhs, rhs, ret_ty, "ptr";
1088             Add (_) bug;
1089             Sub (_) bug;
1090             Mul (_) bug;
1091             Div (_) bug;
1092             Rem (_) bug;
1093             BitXor (_) bug;
1094             BitAnd (_) bug;
1095             BitOr (_) bug;
1096             Shl (_) bug;
1097             Shr (_) bug;
1098
1099             Eq (_) icmp(Equal);
1100             Lt (_) icmp(UnsignedLessThan);
1101             Le (_) icmp(UnsignedLessThanOrEqual);
1102             Ne (_) icmp(NotEqual);
1103             Ge (_) icmp(UnsignedGreaterThanOrEqual);
1104             Gt (_) icmp(UnsignedGreaterThan);
1105
1106             Offset (_) bug; // Handled above
1107         }
1108     } else {
1109         let (lhs_ptr, lhs_extra) = lhs.load_scalar_pair(fx);
1110         let (rhs_ptr, rhs_extra) = rhs.load_scalar_pair(fx);
1111
1112         let res = match bin_op {
1113             BinOp::Eq => {
1114                 let ptr_eq = fx.bcx.ins().icmp(IntCC::Equal, lhs_ptr, rhs_ptr);
1115                 let extra_eq = fx.bcx.ins().icmp(IntCC::Equal, lhs_extra, rhs_extra);
1116                 fx.bcx.ins().band(ptr_eq, extra_eq)
1117             }
1118             BinOp::Ne => {
1119                 let ptr_ne = fx.bcx.ins().icmp(IntCC::NotEqual, lhs_ptr, rhs_ptr);
1120                 let extra_ne = fx.bcx.ins().icmp(IntCC::NotEqual, lhs_extra, rhs_extra);
1121                 fx.bcx.ins().bor(ptr_ne, extra_ne)
1122             }
1123             BinOp::Lt | BinOp::Le | BinOp::Ge | BinOp::Gt => {
1124                 let ptr_eq = fx.bcx.ins().icmp(IntCC::Equal, lhs_ptr, rhs_ptr);
1125
1126                 let ptr_cmp = fx.bcx.ins().icmp(match bin_op {
1127                     BinOp::Lt => IntCC::UnsignedLessThan,
1128                     BinOp::Le => IntCC::UnsignedLessThanOrEqual,
1129                     BinOp::Ge => IntCC::UnsignedGreaterThanOrEqual,
1130                     BinOp::Gt => IntCC::UnsignedGreaterThan,
1131                     _ => unreachable!(),
1132                 }, lhs_ptr, rhs_ptr);
1133
1134                 let extra_cmp = fx.bcx.ins().icmp(match bin_op {
1135                     BinOp::Lt => IntCC::UnsignedLessThan,
1136                     BinOp::Le => IntCC::UnsignedLessThanOrEqual,
1137                     BinOp::Ge => IntCC::UnsignedGreaterThanOrEqual,
1138                     BinOp::Gt => IntCC::UnsignedGreaterThan,
1139                     _ => unreachable!(),
1140                 }, lhs_extra, rhs_extra);
1141
1142                 fx.bcx.ins().select(ptr_eq, extra_cmp, ptr_cmp)
1143             }
1144             _ => panic!("bin_op {:?} on ptr", bin_op),
1145         };
1146
1147         assert_eq!(fx.tcx.types.bool, ret_ty);
1148         let ret_layout = fx.layout_of(ret_ty);
1149         CValue::by_val(fx.bcx.ins().bint(types::I8, res), ret_layout)
1150     }
1151 }
1152
1153 pub fn trans_place<'a, 'tcx: 'a>(
1154     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
1155     place: &Place<'tcx>,
1156 ) -> CPlace<'tcx> {
1157     let base = match &place.base {
1158         PlaceBase::Local(local) => fx.get_local_place(*local),
1159         PlaceBase::Static(static_) => match static_.kind {
1160             StaticKind::Static(def_id) => {
1161                 crate::constant::codegen_static_ref(fx, def_id, static_.ty)
1162             }
1163             StaticKind::Promoted(promoted) => {
1164                 crate::constant::trans_promoted(fx, promoted, static_.ty)
1165             }
1166         }
1167     };
1168
1169     trans_place_projection(fx, base, &place.projection)
1170 }
1171
1172 pub fn trans_place_projection<'a, 'tcx: 'a>(
1173     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
1174     base: CPlace<'tcx>,
1175     projection: &Option<Box<Projection<'tcx>>>,
1176 ) -> CPlace<'tcx> {
1177     let projection = if let Some(projection) = projection {
1178         projection
1179     } else {
1180         return base;
1181     };
1182
1183     let base = trans_place_projection(fx, base, &projection.base);
1184
1185     match projection.elem {
1186         ProjectionElem::Deref => base.place_deref(fx),
1187         ProjectionElem::Field(field, _ty) => base.place_field(fx, field),
1188         ProjectionElem::Index(local) => {
1189             let index = fx.get_local_place(local).to_cvalue(fx).load_scalar(fx);
1190             base.place_index(fx, index)
1191         }
1192         ProjectionElem::ConstantIndex {
1193             offset,
1194             min_length: _,
1195             from_end,
1196         } => {
1197             let index = if !from_end {
1198                 fx.bcx.ins().iconst(fx.pointer_type, offset as i64)
1199             } else {
1200                 let len = codegen_array_len(fx, base);
1201                 fx.bcx.ins().iadd_imm(len, -(offset as i64))
1202             };
1203             base.place_index(fx, index)
1204         }
1205         ProjectionElem::Subslice { from, to } => {
1206             // These indices are generated by slice patterns.
1207             // slice[from:-to] in Python terms.
1208
1209             match base.layout().ty.sty {
1210                 ty::Array(elem_ty, len) => {
1211                     let elem_layout = fx.layout_of(elem_ty);
1212                     let ptr = base.to_addr(fx);
1213                     let len = crate::constant::force_eval_const(fx, len).unwrap_usize(fx.tcx);
1214                     CPlace::for_addr(
1215                         fx.bcx.ins().iadd_imm(ptr, elem_layout.size.bytes() as i64 * from as i64),
1216                         fx.layout_of(fx.tcx.mk_array(elem_ty, len - from as u64 - to as u64)),
1217                     )
1218                 }
1219                 ty::Slice(elem_ty) => {
1220                     let elem_layout = fx.layout_of(elem_ty);
1221                     let (ptr, len) = base.to_addr_maybe_unsized(fx);
1222                     let len = len.unwrap();
1223                     CPlace::for_addr_with_extra(
1224                         fx.bcx.ins().iadd_imm(ptr, elem_layout.size.bytes() as i64 * from as i64),
1225                         fx.bcx.ins().iadd_imm(len, -(from as i64 + to as i64)),
1226                         base.layout(),
1227                     )
1228                 }
1229                 _ => unreachable!(),
1230             }
1231         }
1232         ProjectionElem::Downcast(_adt_def, variant) => base.downcast_variant(fx, variant),
1233     }
1234 }
1235
1236 pub fn trans_operand<'a, 'tcx>(
1237     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
1238     operand: &Operand<'tcx>,
1239 ) -> CValue<'tcx> {
1240     match operand {
1241         Operand::Move(place) | Operand::Copy(place) => {
1242             let cplace = trans_place(fx, place);
1243             cplace.to_cvalue(fx)
1244         }
1245         Operand::Constant(const_) => crate::constant::trans_constant(fx, const_),
1246     }
1247 }