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