]> git.lizzy.rs Git - rust.git/blob - src/base.rs
Rustup to rustc 1.37.0-nightly (7cdaffd79 2019-06-05)
[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<'a, '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<'a, 'tcx: 'a>(TyCtxt<'a, 'tcx, 'tcx>, bool);
22
23         impl<'a, 'tcx: 'a> rustc::ty::fold::TypeVisitor<'tcx> for UI128Visitor<'a, '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.", msg));
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 ty = location.ty(fx.mir, fx.tcx).ty;
290                 let ty = fx.monomorphize(&ty);
291                 let drop_fn = Instance::resolve_drop_in_place(fx.tcx, ty);
292
293                 if let ty::InstanceDef::DropGlue(_, None) = drop_fn.def {
294                     // we don't actually need to drop anything
295                 } else {
296                     let drop_place = trans_place(fx, location);
297                     let drop_fn_ty = drop_fn.ty(fx.tcx);
298                     match ty.sty {
299                         ty::Dynamic(..) => {
300                             crate::abi::codegen_drop(fx, drop_place, drop_fn_ty);
301                         }
302                         _ => {
303                             let arg_place = CPlace::new_stack_slot(
304                                 fx,
305                                 fx.tcx.mk_ref(
306                                     &ty::RegionKind::ReErased,
307                                     TypeAndMut {
308                                         ty,
309                                         mutbl: crate::rustc::hir::Mutability::MutMutable,
310                                     },
311                                 ),
312                             );
313                             drop_place.write_place_ref(fx, arg_place);
314                             let arg_value = arg_place.to_cvalue(fx);
315                             crate::abi::codegen_call_inner(
316                                 fx,
317                                 None,
318                                 drop_fn_ty,
319                                 vec![arg_value],
320                                 None,
321                             );
322                         }
323                     }
324                 }
325
326                 let target_ebb = fx.get_ebb(*target);
327                 fx.bcx.ins().jump(target_ebb, &[]);
328             }
329         };
330     }
331
332     fx.bcx.seal_all_blocks();
333     fx.bcx.finalize();
334 }
335
336 fn trans_stmt<'a, 'tcx: 'a>(
337     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
338     cur_ebb: Ebb,
339     stmt: &Statement<'tcx>,
340 ) {
341     let _print_guard = PrintOnPanic(|| format!("stmt {:?}", stmt));
342
343     fx.set_debug_loc(stmt.source_info);
344
345     #[cfg(debug_assertions)]
346     match &stmt.kind {
347         StatementKind::StorageLive(..) | StatementKind::StorageDead(..) => {} // Those are not very useful
348         _ => {
349             let inst = fx.bcx.func.layout.last_inst(cur_ebb).unwrap();
350             fx.add_comment(inst, format!("{:?}", stmt));
351         }
352     }
353
354     match &stmt.kind {
355         StatementKind::SetDiscriminant {
356             place,
357             variant_index,
358         } => {
359             let place = trans_place(fx, place);
360             let layout = place.layout();
361             if layout.for_variant(&*fx, *variant_index).abi == layout::Abi::Uninhabited {
362                 return;
363             }
364             match layout.variants {
365                 layout::Variants::Single { index } => {
366                     assert_eq!(index, *variant_index);
367                 }
368                 layout::Variants::Multiple {
369                     discr: _,
370                     discr_index,
371                     discr_kind: layout::DiscriminantKind::Tag,
372                     variants: _,
373                 } => {
374                     let ptr = place.place_field(fx, mir::Field::new(discr_index));
375                     let to = layout
376                         .ty
377                         .ty_adt_def()
378                         .unwrap()
379                         .discriminant_for_variant(fx.tcx, *variant_index)
380                         .val;
381                     let discr = CValue::const_val(fx, ptr.layout().ty, to as u64 as i64);
382                     ptr.write_cvalue(fx, discr);
383                 }
384                 layout::Variants::Multiple {
385                     discr: _,
386                     discr_index,
387                     discr_kind: layout::DiscriminantKind::Niche {
388                         dataful_variant,
389                         ref niche_variants,
390                         niche_start,
391                     },
392                     variants: _,
393                 } => {
394                     if *variant_index != dataful_variant {
395                         let niche = place.place_field(fx, mir::Field::new(discr_index));
396                         //let niche_llty = niche.layout.immediate_llvm_type(bx.cx);
397                         let niche_value =
398                             ((variant_index.as_u32() - niche_variants.start().as_u32()) as u128)
399                                 .wrapping_add(niche_start);
400                         // FIXME(eddyb) Check the actual primitive type here.
401                         let niche_llval = if niche_value == 0 {
402                             CValue::const_val(fx, niche.layout().ty, 0)
403                         } else {
404                             CValue::const_val(fx, niche.layout().ty, niche_value as u64 as i64)
405                         };
406                         niche.write_cvalue(fx, niche_llval);
407                     }
408                 }
409             }
410         }
411         StatementKind::Assign(to_place, rval) => {
412             let lval = trans_place(fx, to_place);
413             let dest_layout = lval.layout();
414             match &**rval {
415                 Rvalue::Use(operand) => {
416                     let val = trans_operand(fx, operand);
417                     lval.write_cvalue(fx, val);
418                 }
419                 Rvalue::Ref(_, _, place) => {
420                     let place = trans_place(fx, place);
421                     place.write_place_ref(fx, lval);
422                 }
423                 Rvalue::BinaryOp(bin_op, lhs, rhs) => {
424                     let ty = fx.monomorphize(&lhs.ty(fx.mir, fx.tcx));
425                     let lhs = trans_operand(fx, lhs);
426                     let rhs = trans_operand(fx, rhs);
427
428                     let res = match ty.sty {
429                         ty::Bool => trans_bool_binop(fx, *bin_op, lhs, rhs, lval.layout().ty),
430                         ty::Uint(_) => {
431                             trans_int_binop(fx, *bin_op, lhs, rhs, lval.layout().ty, false)
432                         }
433                         ty::Int(_) => {
434                             trans_int_binop(fx, *bin_op, lhs, rhs, lval.layout().ty, true)
435                         }
436                         ty::Float(_) => trans_float_binop(fx, *bin_op, lhs, rhs, lval.layout().ty),
437                         ty::Char => trans_char_binop(fx, *bin_op, lhs, rhs, lval.layout().ty),
438                         ty::RawPtr(..) => trans_ptr_binop(fx, *bin_op, lhs, rhs, lval.layout().ty),
439                         ty::FnPtr(..) => trans_ptr_binop(fx, *bin_op, lhs, rhs, lval.layout().ty),
440                         _ => unimplemented!("binop {:?} for {:?}", bin_op, ty),
441                     };
442                     lval.write_cvalue(fx, res);
443                 }
444                 Rvalue::CheckedBinaryOp(bin_op, lhs, rhs) => {
445                     let ty = fx.monomorphize(&lhs.ty(fx.mir, fx.tcx));
446                     let lhs = trans_operand(fx, lhs);
447                     let rhs = trans_operand(fx, rhs);
448
449                     let res = match ty.sty {
450                         ty::Uint(_) => {
451                             trans_checked_int_binop(fx, *bin_op, lhs, rhs, lval.layout().ty, false)
452                         }
453                         ty::Int(_) => {
454                             trans_checked_int_binop(fx, *bin_op, lhs, rhs, lval.layout().ty, true)
455                         }
456                         _ => unimplemented!("checked binop {:?} for {:?}", bin_op, ty),
457                     };
458                     lval.write_cvalue(fx, res);
459                 }
460                 Rvalue::UnaryOp(un_op, operand) => {
461                     let operand = trans_operand(fx, operand);
462                     let layout = operand.layout();
463                     let val = operand.load_scalar(fx);
464                     let res = match un_op {
465                         UnOp::Not => {
466                             match layout.ty.sty {
467                                 ty::Bool => {
468                                     let val = fx.bcx.ins().uextend(types::I32, val); // WORKAROUND for CraneStation/cranelift#466
469                                     let res = fx.bcx.ins().icmp_imm(IntCC::Equal, val, 0);
470                                     fx.bcx.ins().bint(types::I8, res)
471                                 }
472                                 ty::Uint(_) | ty::Int(_) => fx.bcx.ins().bnot(val),
473                                 _ => unimplemented!("un op Not for {:?}", layout.ty),
474                             }
475                         }
476                         UnOp::Neg => match layout.ty.sty {
477                             ty::Int(_) => {
478                                 let clif_ty = fx.clif_type(layout.ty).unwrap();
479                                 let zero = fx.bcx.ins().iconst(clif_ty, 0);
480                                 fx.bcx.ins().isub(zero, val)
481                             }
482                             ty::Float(_) => fx.bcx.ins().fneg(val),
483                             _ => unimplemented!("un op Neg for {:?}", layout.ty),
484                         },
485                     };
486                     lval.write_cvalue(fx, CValue::ByVal(res, layout));
487                 }
488                 Rvalue::Cast(CastKind::Pointer(PointerCast::ReifyFnPointer), operand, ty) => {
489                     let layout = fx.layout_of(ty);
490                     match fx
491                         .monomorphize(&operand.ty(&fx.mir.local_decls, fx.tcx))
492                         .sty
493                     {
494                         ty::FnDef(def_id, substs) => {
495                             let func_ref = fx.get_function_ref(
496                                 Instance::resolve(fx.tcx, ParamEnv::reveal_all(), def_id, substs)
497                                     .unwrap(),
498                             );
499                             let func_addr = fx.bcx.ins().func_addr(fx.pointer_type, func_ref);
500                             lval.write_cvalue(fx, CValue::ByVal(func_addr, layout));
501                         }
502                         _ => bug!("Trying to ReifyFnPointer on non FnDef {:?}", ty),
503                     }
504                 }
505                 Rvalue::Cast(CastKind::Pointer(PointerCast::UnsafeFnPointer), operand, ty)
506                 | Rvalue::Cast(CastKind::Pointer(PointerCast::MutToConstPointer), operand, ty) => {
507                     let operand = trans_operand(fx, operand);
508                     let layout = fx.layout_of(ty);
509                     lval.write_cvalue(fx, operand.unchecked_cast_to(layout));
510                 }
511                 Rvalue::Cast(CastKind::Misc, operand, to_ty) => {
512                     let operand = trans_operand(fx, operand);
513                     let from_ty = operand.layout().ty;
514
515                     fn is_fat_ptr<'a, 'tcx: 'a>(fx: &FunctionCx<'a, 'tcx, impl Backend>, ty: Ty<'tcx>) -> bool {
516                         ty
517                             .builtin_deref(true)
518                             .map(|ty::TypeAndMut {ty: pointee_ty, mutbl: _ }| fx.layout_of(pointee_ty).is_unsized())
519                             .unwrap_or(false)
520                     }
521
522                     if is_fat_ptr(fx, from_ty) {
523                         if is_fat_ptr(fx, to_ty) {
524                             // fat-ptr -> fat-ptr
525                             lval.write_cvalue(fx, operand.unchecked_cast_to(dest_layout));
526                         } else {
527                             // fat-ptr -> thin-ptr
528                             let (ptr, _extra) = operand.load_scalar_pair(fx);
529                             lval.write_cvalue(fx, CValue::ByVal(ptr, dest_layout))
530                         }
531                     } else if let ty::Adt(adt_def, _substs) = from_ty.sty {
532                         // enum -> discriminant value
533                         assert!(adt_def.is_enum());
534                         match to_ty.sty {
535                             ty::Uint(_) | ty::Int(_) => {},
536                             _ => unreachable!("cast adt {} -> {}", from_ty, to_ty),
537                         }
538
539                         // FIXME avoid forcing to stack
540                         let place =
541                             CPlace::Addr(operand.force_stack(fx), None, operand.layout());
542                         let discr = trans_get_discriminant(fx, place, fx.layout_of(to_ty));
543                         lval.write_cvalue(fx, discr);
544                     } else {
545                         let from_clif_ty = fx.clif_type(from_ty).unwrap();
546                         let to_clif_ty = fx.clif_type(to_ty).unwrap();
547                         let from = operand.load_scalar(fx);
548
549                         let signed = match from_ty.sty {
550                             ty::Ref(..) | ty::RawPtr(..) | ty::FnPtr(..) | ty::Char | ty::Uint(..) | ty::Bool => false,
551                             ty::Int(..) => true,
552                             ty::Float(..) => false, // `signed` is unused for floats
553                             _ => panic!("{}", from_ty),
554                         };
555
556                         let res = if from_clif_ty.is_int() && to_clif_ty.is_int() {
557                             // int-like -> int-like
558                             crate::common::clif_intcast(
559                                 fx,
560                                 from,
561                                 to_clif_ty,
562                                 signed,
563                             )
564                         } else if from_clif_ty.is_int() && to_clif_ty.is_float() {
565                             // int-like -> float
566                             // FIXME missing encoding for fcvt_from_sint.f32.i8
567                             let from = if from_clif_ty == types::I8 || from_clif_ty == types::I16 {
568                                 fx.bcx.ins().uextend(types::I32, from)
569                             } else {
570                                 from
571                             };
572                             if signed {
573                                 fx.bcx.ins().fcvt_from_sint(to_clif_ty, from)
574                             } else {
575                                 fx.bcx.ins().fcvt_from_uint(to_clif_ty, from)
576                             }
577                         } else if from_clif_ty.is_float() && to_clif_ty.is_int() {
578                             // float -> int-like
579                             let from = operand.load_scalar(fx);
580                             if signed {
581                                 fx.bcx.ins().fcvt_to_sint_sat(to_clif_ty, from)
582                             } else {
583                                 fx.bcx.ins().fcvt_to_uint_sat(to_clif_ty, from)
584                             }
585                         } else if from_clif_ty.is_float() && to_clif_ty.is_float() {
586                             // float -> float
587                             match (from_clif_ty, to_clif_ty) {
588                                 (types::F32, types::F64) => {
589                                     fx.bcx.ins().fpromote(types::F64, from)
590                                 }
591                                 (types::F64, types::F32) => {
592                                     fx.bcx.ins().fdemote(types::F32, from)
593                                 }
594                                 _ => from,
595                             }
596                         } else {
597                             unimpl!("rval misc {:?} {:?}", from_ty, to_ty)
598                         };
599                         lval.write_cvalue(fx, CValue::ByVal(res, dest_layout));
600                     }
601                 }
602                 Rvalue::Cast(CastKind::Pointer(PointerCast::ClosureFnPointer(_)), operand, _ty) => {
603                     let operand = trans_operand(fx, operand);
604                     match operand.layout().ty.sty {
605                         ty::Closure(def_id, substs) => {
606                             let instance = Instance::resolve_closure(
607                                 fx.tcx,
608                                 def_id,
609                                 substs,
610                                 ty::ClosureKind::FnOnce,
611                             );
612                             let func_ref = fx.get_function_ref(instance);
613                             let func_addr = fx.bcx.ins().func_addr(fx.pointer_type, func_ref);
614                             lval.write_cvalue(fx, CValue::ByVal(func_addr, lval.layout()));
615                         }
616                         _ => {
617                             bug!("{} cannot be cast to a fn ptr", operand.layout().ty)
618                         }
619                     }
620                 }
621                 Rvalue::Cast(CastKind::Pointer(PointerCast::Unsize), operand, _ty) => {
622                     let operand = trans_operand(fx, operand);
623                     operand.unsize_value(fx, lval);
624                 }
625                 Rvalue::Discriminant(place) => {
626                     let place = trans_place(fx, place);
627                     let discr = trans_get_discriminant(fx, place, dest_layout);
628                     lval.write_cvalue(fx, discr);
629                 }
630                 Rvalue::Repeat(operand, times) => {
631                     let operand = trans_operand(fx, operand);
632                     for i in 0..*times {
633                         let index = fx.bcx.ins().iconst(fx.pointer_type, i as i64);
634                         let to = lval.place_index(fx, index);
635                         to.write_cvalue(fx, operand);
636                     }
637                 }
638                 Rvalue::Len(place) => {
639                     let place = trans_place(fx, place);
640                     let usize_layout = fx.layout_of(fx.tcx.types.usize);
641                     let len = codegen_array_len(fx, place);
642                     lval.write_cvalue(fx, CValue::ByVal(len, usize_layout));
643                 }
644                 Rvalue::NullaryOp(NullOp::Box, content_ty) => {
645                     use rustc::middle::lang_items::ExchangeMallocFnLangItem;
646
647                     let usize_type = fx.clif_type(fx.tcx.types.usize).unwrap();
648                     let layout = fx.layout_of(content_ty);
649                     let llsize = fx.bcx.ins().iconst(usize_type, layout.size.bytes() as i64);
650                     let llalign = fx
651                         .bcx
652                         .ins()
653                         .iconst(usize_type, layout.align.abi.bytes() as i64);
654                     let box_layout = fx.layout_of(fx.tcx.mk_box(content_ty));
655
656                     // Allocate space:
657                     let def_id = match fx.tcx.lang_items().require(ExchangeMallocFnLangItem) {
658                         Ok(id) => id,
659                         Err(s) => {
660                             fx.tcx
661                                 .sess
662                                 .fatal(&format!("allocation of `{}` {}", box_layout.ty, s));
663                         }
664                     };
665                     let instance = ty::Instance::mono(fx.tcx, def_id);
666                     let func_ref = fx.get_function_ref(instance);
667                     let call = fx.bcx.ins().call(func_ref, &[llsize, llalign]);
668                     let ptr = fx.bcx.inst_results(call)[0];
669                     lval.write_cvalue(fx, CValue::ByVal(ptr, box_layout));
670                 }
671                 Rvalue::NullaryOp(NullOp::SizeOf, ty) => {
672                     assert!(lval
673                         .layout()
674                         .ty
675                         .is_sized(fx.tcx.at(DUMMY_SP), ParamEnv::reveal_all()));
676                     let ty_size = fx.layout_of(ty).size.bytes();
677                     let val = CValue::const_val(fx, fx.tcx.types.usize, ty_size as i64);
678                     lval.write_cvalue(fx, val);
679                 }
680                 Rvalue::Aggregate(kind, operands) => match **kind {
681                     AggregateKind::Array(_ty) => {
682                         for (i, operand) in operands.into_iter().enumerate() {
683                             let operand = trans_operand(fx, operand);
684                             let index = fx.bcx.ins().iconst(fx.pointer_type, i as i64);
685                             let to = lval.place_index(fx, index);
686                             to.write_cvalue(fx, operand);
687                         }
688                     }
689                     _ => unimpl!("shouldn't exist at trans {:?}", rval),
690                 },
691             }
692         }
693         StatementKind::StorageLive(_)
694         | StatementKind::StorageDead(_)
695         | StatementKind::Nop
696         | StatementKind::FakeRead(..)
697         | StatementKind::Retag { .. }
698         | StatementKind::AscribeUserType(..) => {}
699
700         StatementKind::InlineAsm { .. } => unimpl!("Inline assembly is not supported"),
701     }
702 }
703
704 fn codegen_array_len<'a, 'tcx: 'a>(
705     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
706     place: CPlace<'tcx>,
707 ) -> Value {
708     match place.layout().ty.sty {
709         ty::Array(_elem_ty, len) => {
710             let len = crate::constant::force_eval_const(fx, len).unwrap_usize(fx.tcx) as i64;
711             fx.bcx.ins().iconst(fx.pointer_type, len)
712         }
713         ty::Slice(_elem_ty) => place
714             .to_addr_maybe_unsized(fx)
715             .1
716             .expect("Length metadata for slice place"),
717         _ => bug!("Rvalue::Len({:?})", place),
718     }
719 }
720
721 pub fn trans_get_discriminant<'a, 'tcx: 'a>(
722     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
723     place: CPlace<'tcx>,
724     dest_layout: TyLayout<'tcx>,
725 ) -> CValue<'tcx> {
726     let layout = place.layout();
727
728     if layout.abi == layout::Abi::Uninhabited {
729         return trap_unreachable_ret_value(fx, dest_layout, "[panic] Tried to get discriminant for uninhabited type.");
730     }
731
732     let (discr_scalar, discr_index, discr_kind) = match &layout.variants {
733         layout::Variants::Single { index } => {
734             let discr_val = layout
735                 .ty
736                 .ty_adt_def()
737                 .map_or(index.as_u32() as u128, |def| {
738                     def.discriminant_for_variant(fx.tcx, *index).val
739                 });
740             return CValue::const_val(fx, dest_layout.ty, discr_val as u64 as i64);
741         }
742         layout::Variants::Multiple { discr, discr_index, discr_kind, variants: _ } => {
743             (discr, *discr_index, discr_kind)
744         }
745     };
746
747     let discr = place.place_field(fx, mir::Field::new(discr_index)).to_cvalue(fx);
748     let discr_ty = discr.layout().ty;
749     let lldiscr = discr.load_scalar(fx);
750     match discr_kind {
751         layout::DiscriminantKind::Tag => {
752             let signed = match discr_scalar.value {
753                 layout::Int(_, signed) => signed,
754                 _ => false,
755             };
756             let val = clif_intcast(fx, lldiscr, fx.clif_type(dest_layout.ty).unwrap(), signed);
757             return CValue::ByVal(val, dest_layout);
758         }
759         layout::DiscriminantKind::Niche {
760             dataful_variant,
761             ref niche_variants,
762             niche_start,
763         } => {
764             let niche_llty = fx.clif_type(discr_ty).unwrap();
765             let dest_clif_ty = fx.clif_type(dest_layout.ty).unwrap();
766             if niche_variants.start() == niche_variants.end() {
767                 let b = fx
768                     .bcx
769                     .ins()
770                     .icmp_imm(IntCC::Equal, lldiscr, *niche_start as u64 as i64);
771                 let if_true = fx
772                     .bcx
773                     .ins()
774                     .iconst(dest_clif_ty, niche_variants.start().as_u32() as i64);
775                 let if_false = fx
776                     .bcx
777                     .ins()
778                     .iconst(dest_clif_ty, dataful_variant.as_u32() as i64);
779                 let val = fx.bcx.ins().select(b, if_true, if_false);
780                 return CValue::ByVal(val, dest_layout);
781             } else {
782                 // Rebase from niche values to discriminant values.
783                 let delta = niche_start.wrapping_sub(niche_variants.start().as_u32() as u128);
784                 let delta = fx.bcx.ins().iconst(niche_llty, delta as u64 as i64);
785                 let lldiscr = fx.bcx.ins().isub(lldiscr, delta);
786                 let b = fx.bcx.ins().icmp_imm(
787                     IntCC::UnsignedLessThanOrEqual,
788                     lldiscr,
789                     niche_variants.end().as_u32() as i64,
790                 );
791                 let if_true =
792                     clif_intcast(fx, lldiscr, fx.clif_type(dest_layout.ty).unwrap(), false);
793                 let if_false = fx
794                     .bcx
795                     .ins()
796                     .iconst(dest_clif_ty, dataful_variant.as_u32() as i64);
797                 let val = fx.bcx.ins().select(b, if_true, if_false);
798                 return CValue::ByVal(val, dest_layout);
799             }
800         }
801     }
802 }
803
804 macro_rules! binop_match {
805     (@single $fx:expr, $bug_fmt:expr, $var:expr, $signed:expr, $lhs:expr, $rhs:expr, $ret_ty:expr, bug) => {
806         bug!("binop {} on {} lhs: {:?} rhs: {:?}", stringify!($var), $bug_fmt, $lhs, $rhs)
807     };
808     (@single $fx:expr, $bug_fmt:expr, $var:expr, $signed:expr, $lhs:expr, $rhs:expr, $ret_ty:expr, icmp($cc:ident)) => {{
809         assert_eq!($fx.tcx.types.bool, $ret_ty);
810         let ret_layout = $fx.layout_of($ret_ty);
811
812         let b = $fx.bcx.ins().icmp(IntCC::$cc, $lhs, $rhs);
813         CValue::ByVal($fx.bcx.ins().bint(types::I8, b), ret_layout)
814     }};
815     (@single $fx:expr, $bug_fmt:expr, $var:expr, $signed:expr, $lhs:expr, $rhs:expr, $ret_ty:expr, fcmp($cc:ident)) => {{
816         assert_eq!($fx.tcx.types.bool, $ret_ty);
817         let ret_layout = $fx.layout_of($ret_ty);
818         let b = $fx.bcx.ins().fcmp(FloatCC::$cc, $lhs, $rhs);
819         CValue::ByVal($fx.bcx.ins().bint(types::I8, b), ret_layout)
820     }};
821     (@single $fx:expr, $bug_fmt:expr, $var:expr, $signed:expr, $lhs:expr, $rhs:expr, $ret_ty:expr, custom(|| $body:expr)) => {{
822         $body
823     }};
824     (@single $fx:expr, $bug_fmt:expr, $var:expr, $signed:expr, $lhs:expr, $rhs:expr, $ret_ty:expr, $name:ident) => {{
825         let ret_layout = $fx.layout_of($ret_ty);
826         CValue::ByVal($fx.bcx.ins().$name($lhs, $rhs), ret_layout)
827     }};
828     (
829         $fx:expr, $bin_op:expr, $signed:expr, $lhs:expr, $rhs:expr, $ret_ty:expr, $bug_fmt:expr;
830         $(
831             $var:ident ($sign:pat) $name:tt $( ( $($next:tt)* ) )? ;
832         )*
833     ) => {{
834         let lhs = $lhs.load_scalar($fx);
835         let rhs = $rhs.load_scalar($fx);
836         match ($bin_op, $signed) {
837             $(
838                 (BinOp::$var, $sign) => binop_match!(@single $fx, $bug_fmt, $var, $signed, lhs, rhs, $ret_ty, $name $( ( $($next)* ) )?),
839             )*
840         }
841     }}
842 }
843
844 fn trans_bool_binop<'a, 'tcx: 'a>(
845     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
846     bin_op: BinOp,
847     lhs: CValue<'tcx>,
848     rhs: CValue<'tcx>,
849     ty: Ty<'tcx>,
850 ) -> CValue<'tcx> {
851     let res = binop_match! {
852         fx, bin_op, false, lhs, rhs, ty, "bool";
853         Add (_) bug;
854         Sub (_) bug;
855         Mul (_) bug;
856         Div (_) bug;
857         Rem (_) bug;
858         BitXor (_) bxor;
859         BitAnd (_) band;
860         BitOr (_) bor;
861         Shl (_) bug;
862         Shr (_) bug;
863
864         Eq (_) icmp(Equal);
865         Lt (_) icmp(UnsignedLessThan);
866         Le (_) icmp(UnsignedLessThanOrEqual);
867         Ne (_) icmp(NotEqual);
868         Ge (_) icmp(UnsignedGreaterThanOrEqual);
869         Gt (_) icmp(UnsignedGreaterThan);
870
871         Offset (_) bug;
872     };
873
874     res
875 }
876
877 pub fn trans_int_binop<'a, 'tcx: 'a>(
878     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
879     bin_op: BinOp,
880     lhs: CValue<'tcx>,
881     rhs: CValue<'tcx>,
882     out_ty: Ty<'tcx>,
883     signed: bool,
884 ) -> CValue<'tcx> {
885     if bin_op != BinOp::Shl && bin_op != BinOp::Shr {
886         assert_eq!(
887             lhs.layout().ty,
888             rhs.layout().ty,
889             "int binop requires lhs and rhs of same type"
890         );
891     }
892     binop_match! {
893         fx, bin_op, signed, lhs, rhs, out_ty, "int/uint";
894         Add (_) iadd;
895         Sub (_) isub;
896         Mul (_) imul;
897         Div (false) udiv;
898         Div (true) sdiv;
899         Rem (false) urem;
900         Rem (true) srem;
901         BitXor (_) bxor;
902         BitAnd (_) band;
903         BitOr (_) bor;
904         Shl (_) ishl;
905         Shr (false) ushr;
906         Shr (true) sshr;
907
908         Eq (_) icmp(Equal);
909         Lt (false) icmp(UnsignedLessThan);
910         Lt (true) icmp(SignedLessThan);
911         Le (false) icmp(UnsignedLessThanOrEqual);
912         Le (true) icmp(SignedLessThanOrEqual);
913         Ne (_) icmp(NotEqual);
914         Ge (false) icmp(UnsignedGreaterThanOrEqual);
915         Ge (true) icmp(SignedGreaterThanOrEqual);
916         Gt (false) icmp(UnsignedGreaterThan);
917         Gt (true) icmp(SignedGreaterThan);
918
919         Offset (_) bug;
920     }
921 }
922
923 pub fn trans_checked_int_binop<'a, 'tcx: 'a>(
924     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
925     bin_op: BinOp,
926     in_lhs: CValue<'tcx>,
927     in_rhs: CValue<'tcx>,
928     out_ty: Ty<'tcx>,
929     signed: bool,
930 ) -> CValue<'tcx> {
931     if bin_op != BinOp::Shl && bin_op != BinOp::Shr {
932         assert_eq!(
933             in_lhs.layout().ty,
934             in_rhs.layout().ty,
935             "checked int binop requires lhs and rhs of same type"
936         );
937     }
938
939     let lhs = in_lhs.load_scalar(fx);
940     let rhs = in_rhs.load_scalar(fx);
941     let res = match bin_op {
942         BinOp::Add => fx.bcx.ins().iadd(lhs, rhs),
943         BinOp::Sub => fx.bcx.ins().isub(lhs, rhs),
944         BinOp::Mul => fx.bcx.ins().imul(lhs, rhs),
945         BinOp::Shl => fx.bcx.ins().ishl(lhs, rhs),
946         BinOp::Shr => {
947             if !signed {
948                 fx.bcx.ins().ushr(lhs, rhs)
949             } else {
950                 fx.bcx.ins().sshr(lhs, rhs)
951             }
952         }
953         _ => bug!(
954             "binop {:?} on checked int/uint lhs: {:?} rhs: {:?}",
955             bin_op,
956             in_lhs,
957             in_rhs
958         ),
959     };
960
961     // TODO: check for overflow
962     let has_overflow = fx.bcx.ins().iconst(types::I8, 0);
963
964     let out_place = CPlace::new_stack_slot(fx, out_ty);
965     let out_layout = out_place.layout();
966     out_place.write_cvalue(fx, CValue::ByValPair(res, has_overflow, out_layout));
967
968     out_place.to_cvalue(fx)
969 }
970
971 fn trans_float_binop<'a, 'tcx: 'a>(
972     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
973     bin_op: BinOp,
974     lhs: CValue<'tcx>,
975     rhs: CValue<'tcx>,
976     ty: Ty<'tcx>,
977 ) -> CValue<'tcx> {
978     let res = binop_match! {
979         fx, bin_op, false, lhs, rhs, ty, "float";
980         Add (_) fadd;
981         Sub (_) fsub;
982         Mul (_) fmul;
983         Div (_) fdiv;
984         Rem (_) custom(|| {
985             assert_eq!(lhs.layout().ty, ty);
986             assert_eq!(rhs.layout().ty, ty);
987             match ty.sty {
988                 ty::Float(FloatTy::F32) => fx.easy_call("fmodf", &[lhs, rhs], ty),
989                 ty::Float(FloatTy::F64) => fx.easy_call("fmod", &[lhs, rhs], ty),
990                 _ => bug!(),
991             }
992         });
993         BitXor (_) bxor;
994         BitAnd (_) band;
995         BitOr (_) bor;
996         Shl (_) bug;
997         Shr (_) bug;
998
999         Eq (_) fcmp(Equal);
1000         Lt (_) fcmp(LessThan);
1001         Le (_) fcmp(LessThanOrEqual);
1002         Ne (_) fcmp(NotEqual);
1003         Ge (_) fcmp(GreaterThanOrEqual);
1004         Gt (_) fcmp(GreaterThan);
1005
1006         Offset (_) bug;
1007     };
1008
1009     res
1010 }
1011
1012 fn trans_char_binop<'a, 'tcx: 'a>(
1013     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
1014     bin_op: BinOp,
1015     lhs: CValue<'tcx>,
1016     rhs: CValue<'tcx>,
1017     ty: Ty<'tcx>,
1018 ) -> CValue<'tcx> {
1019     let res = binop_match! {
1020         fx, bin_op, false, lhs, rhs, ty, "char";
1021         Add (_) bug;
1022         Sub (_) bug;
1023         Mul (_) bug;
1024         Div (_) bug;
1025         Rem (_) bug;
1026         BitXor (_) bug;
1027         BitAnd (_) bug;
1028         BitOr (_) bug;
1029         Shl (_) bug;
1030         Shr (_) bug;
1031
1032         Eq (_) icmp(Equal);
1033         Lt (_) icmp(UnsignedLessThan);
1034         Le (_) icmp(UnsignedLessThanOrEqual);
1035         Ne (_) icmp(NotEqual);
1036         Ge (_) icmp(UnsignedGreaterThanOrEqual);
1037         Gt (_) icmp(UnsignedGreaterThan);
1038
1039         Offset (_) bug;
1040     };
1041
1042     res
1043 }
1044
1045 fn trans_ptr_binop<'a, 'tcx: 'a>(
1046     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
1047     bin_op: BinOp,
1048     lhs: CValue<'tcx>,
1049     rhs: CValue<'tcx>,
1050     ret_ty: Ty<'tcx>,
1051 ) -> CValue<'tcx> {
1052     let not_fat = match lhs.layout().ty.sty {
1053         ty::RawPtr(TypeAndMut { ty, mutbl: _ }) => {
1054             ty.is_sized(fx.tcx.at(DUMMY_SP), ParamEnv::reveal_all())
1055         }
1056         ty::FnPtr(..) => true,
1057         _ => bug!("trans_ptr_binop on non ptr"),
1058     };
1059     if not_fat {
1060         if let BinOp::Offset = bin_op {
1061             let (base, offset) = (lhs, rhs.load_scalar(fx));
1062             let pointee_ty = base.layout().ty.builtin_deref(true).unwrap().ty;
1063             let pointee_size = fx.layout_of(pointee_ty).size.bytes();
1064             let ptr_diff = fx.bcx.ins().imul_imm(offset, pointee_size as i64);
1065             let base_val = base.load_scalar(fx);
1066             let res = fx.bcx.ins().iadd(base_val, ptr_diff);
1067             return CValue::ByVal(res, base.layout());
1068         }
1069
1070         binop_match! {
1071             fx, bin_op, false, lhs, rhs, ret_ty, "ptr";
1072             Add (_) bug;
1073             Sub (_) bug;
1074             Mul (_) bug;
1075             Div (_) bug;
1076             Rem (_) bug;
1077             BitXor (_) bug;
1078             BitAnd (_) bug;
1079             BitOr (_) bug;
1080             Shl (_) bug;
1081             Shr (_) bug;
1082
1083             Eq (_) icmp(Equal);
1084             Lt (_) icmp(UnsignedLessThan);
1085             Le (_) icmp(UnsignedLessThanOrEqual);
1086             Ne (_) icmp(NotEqual);
1087             Ge (_) icmp(UnsignedGreaterThanOrEqual);
1088             Gt (_) icmp(UnsignedGreaterThan);
1089
1090             Offset (_) bug; // Handled above
1091         }
1092     } else {
1093         let (lhs_ptr, lhs_extra) = lhs.load_scalar_pair(fx);
1094         let (rhs_ptr, rhs_extra) = rhs.load_scalar_pair(fx);
1095         let res = match bin_op {
1096             BinOp::Eq => {
1097                 let ptr_eq = fx.bcx.ins().icmp(IntCC::Equal, lhs_ptr, rhs_ptr);
1098                 let extra_eq = fx.bcx.ins().icmp(IntCC::Equal, lhs_extra, rhs_extra);
1099                 fx.bcx.ins().band(ptr_eq, extra_eq)
1100             }
1101             BinOp::Ne => {
1102                 let ptr_ne = fx.bcx.ins().icmp(IntCC::NotEqual, lhs_ptr, rhs_ptr);
1103                 let extra_ne = fx.bcx.ins().icmp(IntCC::NotEqual, lhs_extra, rhs_extra);
1104                 fx.bcx.ins().bor(ptr_ne, extra_ne)
1105             }
1106             _ => unimplemented!(
1107                 "trans_ptr_binop({:?}, <fat ptr>, <fat ptr>) not implemented",
1108                 bin_op
1109             ),
1110         };
1111
1112         assert_eq!(fx.tcx.types.bool, ret_ty);
1113         let ret_layout = fx.layout_of(ret_ty);
1114         CValue::ByVal(fx.bcx.ins().bint(types::I8, res), ret_layout)
1115     }
1116 }
1117
1118 pub fn trans_place<'a, 'tcx: 'a>(
1119     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
1120     place: &Place<'tcx>,
1121 ) -> CPlace<'tcx> {
1122     match place {
1123         Place::Base(base) => match base {
1124             PlaceBase::Local(local) => fx.get_local_place(*local),
1125             PlaceBase::Static(static_) => match static_.kind {
1126                 StaticKind::Static(def_id) => {
1127                     crate::constant::codegen_static_ref(fx, def_id, static_.ty)
1128                 }
1129                 StaticKind::Promoted(promoted) => {
1130                     crate::constant::trans_promoted(fx, promoted, static_.ty)
1131                 }
1132             }
1133         }
1134         Place::Projection(projection) => {
1135             let base = trans_place(fx, &projection.base);
1136             match projection.elem {
1137                 ProjectionElem::Deref => base.place_deref(fx),
1138                 ProjectionElem::Field(field, _ty) => base.place_field(fx, field),
1139                 ProjectionElem::Index(local) => {
1140                     let index = fx.get_local_place(local).to_cvalue(fx).load_scalar(fx);
1141                     base.place_index(fx, index)
1142                 }
1143                 ProjectionElem::ConstantIndex {
1144                     offset,
1145                     min_length: _,
1146                     from_end,
1147                 } => {
1148                     let index = if !from_end {
1149                         fx.bcx.ins().iconst(fx.pointer_type, offset as i64)
1150                     } else {
1151                         let len = codegen_array_len(fx, base);
1152                         fx.bcx.ins().iadd_imm(len, -(offset as i64))
1153                     };
1154                     base.place_index(fx, index)
1155                 }
1156                 ProjectionElem::Subslice { from, to } => {
1157                     // These indices are generated by slice patterns.
1158                     // slice[from:-to] in Python terms.
1159
1160                     match base.layout().ty.sty {
1161                         ty::Array(elem_ty, len) => {
1162                             let elem_layout = fx.layout_of(elem_ty);
1163                             let ptr = base.to_addr(fx);
1164                             let len = crate::constant::force_eval_const(fx, len).unwrap_usize(fx.tcx);
1165                             CPlace::Addr(
1166                                 fx.bcx.ins().iadd_imm(ptr, elem_layout.size.bytes() as i64 * from as i64),
1167                                 None,
1168                                 fx.layout_of(fx.tcx.mk_array(elem_ty, len - from as u64 - to as u64)),
1169                             )
1170                         }
1171                         ty::Slice(elem_ty) => {
1172                             let elem_layout = fx.layout_of(elem_ty);
1173                             let (ptr, len) = base.to_addr_maybe_unsized(fx);
1174                             let len = len.unwrap();
1175                             CPlace::Addr(
1176                                 fx.bcx.ins().iadd_imm(ptr, elem_layout.size.bytes() as i64 * from as i64),
1177                                 Some(fx.bcx.ins().iadd_imm(len, -(from as i64 + to as i64))),
1178                                 base.layout(),
1179                             )
1180                         }
1181                         _ => unreachable!(),
1182                     }
1183                 }
1184                 ProjectionElem::Downcast(_adt_def, variant) => base.downcast_variant(fx, variant),
1185             }
1186         }
1187     }
1188 }
1189
1190 pub fn trans_operand<'a, 'tcx>(
1191     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
1192     operand: &Operand<'tcx>,
1193 ) -> CValue<'tcx> {
1194     match operand {
1195         Operand::Move(place) | Operand::Copy(place) => {
1196             let cplace = trans_place(fx, place);
1197             cplace.to_cvalue(fx)
1198         }
1199         Operand::Constant(const_) => crate::constant::trans_constant(fx, const_),
1200     }
1201 }