]> git.lizzy.rs Git - rust.git/blob - src/base.rs
Rustup to rustc 1.39.0-nightly (2111aed0a 2019-08-17)
[rust.git] / src / base.rs
1 use rustc::ty::adjustment::PointerCast;
2
3 use crate::prelude::*;
4
5 pub fn trans_fn<'a, 'clif, 'tcx: 'a, B: Backend + 'static>(
6     cx: &mut crate::CodegenCx<'clif, 'tcx, B>,
7     instance: Instance<'tcx>,
8     linkage: Linkage,
9 ) {
10     let tcx = cx.tcx;
11
12     let mir = tcx.instance_mir(instance.def);
13
14     // Declare function
15     let (name, sig) = get_function_name_and_sig(tcx, instance, false);
16     let func_id = cx.module.declare_function(&name, linkage, &sig).unwrap();
17     let mut debug_context = cx
18         .debug_context
19         .as_mut()
20         .map(|debug_context| FunctionDebugContext::new(tcx, debug_context, mir, &name, &sig));
21
22     // Make FunctionBuilder
23     let mut func = Function::with_name_signature(ExternalName::user(0, 0), sig);
24     let mut func_ctx = FunctionBuilderContext::new();
25     let mut bcx = FunctionBuilder::new(&mut func, &mut func_ctx);
26
27     // Predefine ebb's
28     let start_ebb = bcx.create_ebb();
29     let mut ebb_map: HashMap<BasicBlock, Ebb> = HashMap::new();
30     for (bb, _bb_data) in mir.basic_blocks().iter_enumerated() {
31         ebb_map.insert(bb, bcx.create_ebb());
32     }
33
34     // Make FunctionCx
35     let pointer_type = cx.module.target_config().pointer_type();
36     let clif_comments = crate::pretty_clif::CommentWriter::new(tcx, instance);
37
38     let mut fx = FunctionCx {
39         tcx,
40         module: cx.module,
41         pointer_type,
42
43         instance,
44         mir,
45
46         bcx,
47         ebb_map,
48         local_map: HashMap::new(),
49
50         clif_comments,
51         constants: &mut cx.ccx,
52         caches: &mut cx.caches,
53         source_info_set: indexmap::IndexSet::new(),
54     };
55
56     with_unimpl_span(fx.mir.span, || {
57         crate::abi::codegen_fn_prelude(&mut fx, start_ebb);
58         codegen_fn_content(&mut fx);
59     });
60
61     // Recover all necessary data from fx, before accessing func will prevent future access to it.
62     let instance = fx.instance;
63     let clif_comments = fx.clif_comments;
64     let source_info_set = fx.source_info_set;
65
66     #[cfg(debug_assertions)]
67     crate::pretty_clif::write_clif_file(cx.tcx, "unopt", instance, &func, &clif_comments, None);
68
69     // Verify function
70     verify_func(tcx, &clif_comments, &func);
71
72     // Define function
73     let context = &mut cx.caches.context;
74     context.func = func;
75     cx.module
76         .define_function(func_id, context)
77         .unwrap();
78
79     let value_ranges = context.build_value_labels_ranges(cx.module.isa()).expect("value location ranges");
80
81     // Write optimized function to file for debugging
82     #[cfg(debug_assertions)]
83     crate::pretty_clif::write_clif_file(cx.tcx, "opt", instance, &context.func, &clif_comments, Some(&value_ranges));
84
85     // Define debuginfo for function
86     let isa = cx.module.isa();
87     debug_context
88         .as_mut()
89         .map(|x| x.define(tcx, context, isa, &source_info_set));
90
91     // Clear context to make it usable for the next function
92     context.clear();
93 }
94
95 fn verify_func(tcx: TyCtxt, writer: &crate::pretty_clif::CommentWriter, func: &Function) {
96     let flags = settings::Flags::new(settings::builder());
97     match ::cranelift::codegen::verify_function(&func, &flags) {
98         Ok(_) => {}
99         Err(err) => {
100             tcx.sess.err(&format!("{:?}", err));
101             let pretty_error = ::cranelift::codegen::print_errors::pretty_verifier_error(
102                 &func,
103                 None,
104                 Some(Box::new(writer)),
105                 err,
106             );
107             tcx.sess
108                 .fatal(&format!("cranelift verify error:\n{}", pretty_error));
109         }
110     }
111 }
112
113 fn codegen_fn_content<'a, 'tcx: 'a>(fx: &mut FunctionCx<'a, 'tcx, impl Backend>) {
114     for (bb, bb_data) in fx.mir.basic_blocks().iter_enumerated() {
115         if bb_data.is_cleanup {
116             // Unwinding after panicking is not supported
117             continue;
118         }
119
120         let ebb = fx.get_ebb(bb);
121         fx.bcx.switch_to_block(ebb);
122
123         fx.bcx.ins().nop();
124         for stmt in &bb_data.statements {
125             fx.set_debug_loc(stmt.source_info);
126             trans_stmt(fx, ebb, stmt);
127         }
128
129         #[cfg(debug_assertions)]
130         {
131             let mut terminator_head = "\n".to_string();
132             bb_data
133                 .terminator()
134                 .kind
135                 .fmt_head(&mut terminator_head)
136                 .unwrap();
137             let inst = fx.bcx.func.layout.last_inst(ebb).unwrap();
138             fx.add_comment(inst, terminator_head);
139         }
140
141         fx.set_debug_loc(bb_data.terminator().source_info);
142
143         match &bb_data.terminator().kind {
144             TerminatorKind::Goto { target } => {
145                 let ebb = fx.get_ebb(*target);
146                 fx.bcx.ins().jump(ebb, &[]);
147             }
148             TerminatorKind::Return => {
149                 crate::abi::codegen_return(fx);
150             }
151             TerminatorKind::Assert {
152                 cond,
153                 expected,
154                 msg,
155                 target,
156                 cleanup: _,
157             } => {
158                 let cond = trans_operand(fx, cond).load_scalar(fx);
159                 // TODO HACK brz/brnz for i8/i16 is not yet implemented
160                 let cond = fx.bcx.ins().uextend(types::I32, cond);
161                 let target = fx.get_ebb(*target);
162                 if *expected {
163                     fx.bcx.ins().brnz(cond, target, &[]);
164                 } else {
165                     fx.bcx.ins().brz(cond, target, &[]);
166                 };
167                 trap_panic(fx, format!("[panic] Assert {:?} at {:?} failed.", msg, bb_data.terminator().source_info.span));
168             }
169
170             TerminatorKind::SwitchInt {
171                 discr,
172                 switch_ty: _,
173                 values,
174                 targets,
175             } => {
176                 let discr = trans_operand(fx, discr).load_scalar(fx);
177                 let mut switch = ::cranelift::frontend::Switch::new();
178                 for (i, value) in values.iter().enumerate() {
179                     let ebb = fx.get_ebb(targets[i]);
180                     switch.set_entry(*value as u64, ebb);
181                 }
182                 let otherwise_ebb = fx.get_ebb(targets[targets.len() - 1]);
183                 switch.emit(&mut fx.bcx, discr, otherwise_ebb);
184             }
185             TerminatorKind::Call {
186                 func,
187                 args,
188                 destination,
189                 cleanup: _,
190                 from_hir_call: _,
191             } => {
192                 crate::abi::codegen_terminator_call(fx, func, args, destination);
193             }
194             TerminatorKind::Resume | TerminatorKind::Abort => {
195                 trap_unreachable(fx, "[corruption] Unwinding bb reached.");
196             }
197             TerminatorKind::Unreachable => {
198                 trap_unreachable(fx, "[corruption] Hit unreachable code.");
199             }
200             TerminatorKind::Yield { .. }
201             | TerminatorKind::FalseEdges { .. }
202             | TerminatorKind::FalseUnwind { .. }
203             | TerminatorKind::DropAndReplace { .. }
204             | TerminatorKind::GeneratorDrop => {
205                 bug!("shouldn't exist at trans {:?}", bb_data.terminator());
206             }
207             TerminatorKind::Drop {
208                 location,
209                 target,
210                 unwind: _,
211             } => {
212                 let drop_place = trans_place(fx, location);
213                 crate::abi::codegen_drop(fx, drop_place);
214
215                 let target_ebb = fx.get_ebb(*target);
216                 fx.bcx.ins().jump(target_ebb, &[]);
217             }
218         };
219     }
220
221     fx.bcx.seal_all_blocks();
222     fx.bcx.finalize();
223 }
224
225 fn trans_stmt<'a, 'tcx: 'a>(
226     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
227     cur_ebb: Ebb,
228     stmt: &Statement<'tcx>,
229 ) {
230     let _print_guard = PrintOnPanic(|| format!("stmt {:?}", stmt));
231
232     fx.set_debug_loc(stmt.source_info);
233
234     #[cfg(debug_assertions)]
235     match &stmt.kind {
236         StatementKind::StorageLive(..) | StatementKind::StorageDead(..) => {} // Those are not very useful
237         _ => {
238             let inst = fx.bcx.func.layout.last_inst(cur_ebb).unwrap();
239             fx.add_comment(inst, format!("{:?}", stmt));
240         }
241     }
242
243     match &stmt.kind {
244         StatementKind::SetDiscriminant {
245             place,
246             variant_index,
247         } => {
248             let place = trans_place(fx, place);
249             crate::discriminant::codegen_set_discriminant(fx, place, *variant_index);
250         }
251         StatementKind::Assign(to_place, rval) => {
252             let lval = trans_place(fx, to_place);
253             let dest_layout = lval.layout();
254             match &**rval {
255                 Rvalue::Use(operand) => {
256                     let val = trans_operand(fx, operand);
257                     lval.write_cvalue(fx, val);
258                 }
259                 Rvalue::Ref(_, _, place) => {
260                     let place = trans_place(fx, place);
261                     place.write_place_ref(fx, lval);
262                 }
263                 Rvalue::BinaryOp(bin_op, lhs, rhs) => {
264                     let lhs = trans_operand(fx, lhs);
265                     let rhs = trans_operand(fx, rhs);
266
267                     let res = crate::num::codegen_binop(fx, *bin_op, lhs, rhs);
268                     lval.write_cvalue(fx, res);
269                 }
270                 Rvalue::CheckedBinaryOp(bin_op, lhs, rhs) => {
271                     let lhs = trans_operand(fx, lhs);
272                     let rhs = trans_operand(fx, rhs);
273
274                     let res = if !fx.tcx.sess.overflow_checks() {
275                         let val = crate::num::trans_int_binop(fx, *bin_op, lhs, rhs).load_scalar(fx);
276                         let is_overflow = fx.bcx.ins().iconst(types::I8, 0);
277                         CValue::by_val_pair(val, is_overflow, lval.layout())
278                     } else {
279                         crate::num::trans_checked_int_binop(fx, *bin_op, lhs, rhs)
280                     };
281
282                     lval.write_cvalue(fx, res);
283                 }
284                 Rvalue::UnaryOp(un_op, operand) => {
285                     let operand = trans_operand(fx, operand);
286                     let layout = operand.layout();
287                     let val = operand.load_scalar(fx);
288                     let res = match un_op {
289                         UnOp::Not => {
290                             match layout.ty.sty {
291                                 ty::Bool => {
292                                     let val = fx.bcx.ins().uextend(types::I32, val); // WORKAROUND for CraneStation/cranelift#466
293                                     let res = fx.bcx.ins().icmp_imm(IntCC::Equal, val, 0);
294                                     fx.bcx.ins().bint(types::I8, res)
295                                 }
296                                 ty::Uint(_) | ty::Int(_) => {
297                                     fx.bcx.ins().bnot(val)
298                                 }
299                                 _ => unimplemented!("un op Not for {:?}", layout.ty),
300                             }
301                         }
302                         UnOp::Neg => match layout.ty.sty {
303                             ty::Int(_) => {
304                                 let clif_ty = fx.clif_type(layout.ty).unwrap();
305                                 if clif_ty == types::I128 {
306                                     // FIXME implement it
307                                     crate::trap::trap_unreachable_ret_value(fx, layout, "i128 neg is not yet supported").load_scalar(fx)
308                                 } else {
309                                     let zero = fx.bcx.ins().iconst(clif_ty, 0);
310                                     fx.bcx.ins().isub(zero, val)
311                                 }
312                             }
313                             ty::Float(_) => fx.bcx.ins().fneg(val),
314                             _ => unimplemented!("un op Neg for {:?}", layout.ty),
315                         },
316                     };
317                     lval.write_cvalue(fx, CValue::by_val(res, layout));
318                 }
319                 Rvalue::Cast(CastKind::Pointer(PointerCast::ReifyFnPointer), operand, ty) => {
320                     let layout = fx.layout_of(ty);
321                     match fx
322                         .monomorphize(&operand.ty(&fx.mir.local_decls, fx.tcx))
323                         .sty
324                     {
325                         ty::FnDef(def_id, substs) => {
326                             let func_ref = fx.get_function_ref(
327                                 Instance::resolve(fx.tcx, ParamEnv::reveal_all(), def_id, substs)
328                                     .unwrap(),
329                             );
330                             let func_addr = fx.bcx.ins().func_addr(fx.pointer_type, func_ref);
331                             lval.write_cvalue(fx, CValue::by_val(func_addr, layout));
332                         }
333                         _ => bug!("Trying to ReifyFnPointer on non FnDef {:?}", ty),
334                     }
335                 }
336                 Rvalue::Cast(CastKind::Pointer(PointerCast::UnsafeFnPointer), operand, ty)
337                 | Rvalue::Cast(CastKind::Pointer(PointerCast::MutToConstPointer), operand, ty) => {
338                     let operand = trans_operand(fx, operand);
339                     let layout = fx.layout_of(ty);
340                     lval.write_cvalue(fx, operand.unchecked_cast_to(layout));
341                 }
342                 Rvalue::Cast(CastKind::Misc, operand, to_ty) => {
343                     let operand = trans_operand(fx, operand);
344                     let from_ty = operand.layout().ty;
345
346                     fn is_fat_ptr<'a, 'tcx: 'a>(fx: &FunctionCx<'a, 'tcx, impl Backend>, ty: Ty<'tcx>) -> bool {
347                         ty
348                             .builtin_deref(true)
349                             .map(|ty::TypeAndMut {ty: pointee_ty, mutbl: _ }| fx.layout_of(pointee_ty).is_unsized())
350                             .unwrap_or(false)
351                     }
352
353                     if is_fat_ptr(fx, from_ty) {
354                         if is_fat_ptr(fx, to_ty) {
355                             // fat-ptr -> fat-ptr
356                             lval.write_cvalue(fx, operand.unchecked_cast_to(dest_layout));
357                         } else {
358                             // fat-ptr -> thin-ptr
359                             let (ptr, _extra) = operand.load_scalar_pair(fx);
360                             lval.write_cvalue(fx, CValue::by_val(ptr, dest_layout))
361                         }
362                     } else if let ty::Adt(adt_def, _substs) = from_ty.sty {
363                         // enum -> discriminant value
364                         assert!(adt_def.is_enum());
365                         match to_ty.sty {
366                             ty::Uint(_) | ty::Int(_) => {},
367                             _ => unreachable!("cast adt {} -> {}", from_ty, to_ty),
368                         }
369
370                         // FIXME avoid forcing to stack
371                         let place =
372                             CPlace::for_addr(operand.force_stack(fx), operand.layout());
373                         let discr = crate::discriminant::codegen_get_discriminant(fx, place, fx.layout_of(to_ty));
374                         lval.write_cvalue(fx, discr);
375                     } else {
376                         let to_clif_ty = fx.clif_type(to_ty).unwrap();
377                         let from = operand.load_scalar(fx);
378
379                         let res = clif_int_or_float_cast(fx, from, type_sign(from_ty), to_clif_ty, type_sign(to_ty));
380                         lval.write_cvalue(fx, CValue::by_val(res, dest_layout));
381                     }
382                 }
383                 Rvalue::Cast(CastKind::Pointer(PointerCast::ClosureFnPointer(_)), operand, _ty) => {
384                     let operand = trans_operand(fx, operand);
385                     match operand.layout().ty.sty {
386                         ty::Closure(def_id, substs) => {
387                             let instance = Instance::resolve_closure(
388                                 fx.tcx,
389                                 def_id,
390                                 substs,
391                                 ty::ClosureKind::FnOnce,
392                             );
393                             let func_ref = fx.get_function_ref(instance);
394                             let func_addr = fx.bcx.ins().func_addr(fx.pointer_type, func_ref);
395                             lval.write_cvalue(fx, CValue::by_val(func_addr, lval.layout()));
396                         }
397                         _ => {
398                             bug!("{} cannot be cast to a fn ptr", operand.layout().ty)
399                         }
400                     }
401                 }
402                 Rvalue::Cast(CastKind::Pointer(PointerCast::Unsize), operand, _ty) => {
403                     let operand = trans_operand(fx, operand);
404                     operand.unsize_value(fx, lval);
405                 }
406                 Rvalue::Discriminant(place) => {
407                     let place = trans_place(fx, place);
408                     let discr = crate::discriminant::codegen_get_discriminant(fx, place, dest_layout);
409                     lval.write_cvalue(fx, discr);
410                 }
411                 Rvalue::Repeat(operand, times) => {
412                     let operand = trans_operand(fx, operand);
413                     for i in 0..*times {
414                         let index = fx.bcx.ins().iconst(fx.pointer_type, i as i64);
415                         let to = lval.place_index(fx, index);
416                         to.write_cvalue(fx, operand);
417                     }
418                 }
419                 Rvalue::Len(place) => {
420                     let place = trans_place(fx, place);
421                     let usize_layout = fx.layout_of(fx.tcx.types.usize);
422                     let len = codegen_array_len(fx, place);
423                     lval.write_cvalue(fx, CValue::by_val(len, usize_layout));
424                 }
425                 Rvalue::NullaryOp(NullOp::Box, content_ty) => {
426                     use rustc::middle::lang_items::ExchangeMallocFnLangItem;
427
428                     let usize_type = fx.clif_type(fx.tcx.types.usize).unwrap();
429                     let layout = fx.layout_of(content_ty);
430                     let llsize = fx.bcx.ins().iconst(usize_type, layout.size.bytes() as i64);
431                     let llalign = fx
432                         .bcx
433                         .ins()
434                         .iconst(usize_type, layout.align.abi.bytes() as i64);
435                     let box_layout = fx.layout_of(fx.tcx.mk_box(content_ty));
436
437                     // Allocate space:
438                     let def_id = match fx.tcx.lang_items().require(ExchangeMallocFnLangItem) {
439                         Ok(id) => id,
440                         Err(s) => {
441                             fx.tcx
442                                 .sess
443                                 .fatal(&format!("allocation of `{}` {}", box_layout.ty, s));
444                         }
445                     };
446                     let instance = ty::Instance::mono(fx.tcx, def_id);
447                     let func_ref = fx.get_function_ref(instance);
448                     let call = fx.bcx.ins().call(func_ref, &[llsize, llalign]);
449                     let ptr = fx.bcx.inst_results(call)[0];
450                     lval.write_cvalue(fx, CValue::by_val(ptr, box_layout));
451                 }
452                 Rvalue::NullaryOp(NullOp::SizeOf, ty) => {
453                     assert!(lval
454                         .layout()
455                         .ty
456                         .is_sized(fx.tcx.at(DUMMY_SP), ParamEnv::reveal_all()));
457                     let ty_size = fx.layout_of(ty).size.bytes();
458                     let val = CValue::const_val(fx, fx.tcx.types.usize, ty_size.into());
459                     lval.write_cvalue(fx, val);
460                 }
461                 Rvalue::Aggregate(kind, operands) => match **kind {
462                     AggregateKind::Array(_ty) => {
463                         for (i, operand) in operands.into_iter().enumerate() {
464                             let operand = trans_operand(fx, operand);
465                             let index = fx.bcx.ins().iconst(fx.pointer_type, i as i64);
466                             let to = lval.place_index(fx, index);
467                             to.write_cvalue(fx, operand);
468                         }
469                     }
470                     _ => unimpl!("shouldn't exist at trans {:?}", rval),
471                 },
472             }
473         }
474         StatementKind::StorageLive(_)
475         | StatementKind::StorageDead(_)
476         | StatementKind::Nop
477         | StatementKind::FakeRead(..)
478         | StatementKind::Retag { .. }
479         | StatementKind::AscribeUserType(..) => {}
480
481         StatementKind::InlineAsm(asm) => {
482             use syntax::ast::Name;
483             let InlineAsm { asm, outputs: _, inputs: _ } = &**asm;
484             let rustc::hir::InlineAsm {
485                 asm: asm_code, // Name
486                 outputs, // Vec<Name>
487                 inputs, // Vec<Name>
488                 clobbers, // Vec<Name>
489                 volatile, // bool
490                 alignstack, // bool
491                 dialect: _, // syntax::ast::AsmDialect
492                 asm_str_style: _,
493             } = asm;
494             match &*asm_code.as_str() {
495                 "cpuid" | "cpuid\n" => {
496                     assert_eq!(inputs, &[Name::intern("{eax}"), Name::intern("{ecx}")]);
497
498                     assert_eq!(outputs.len(), 4);
499                     for (i, c) in (&["={eax}", "={ebx}", "={ecx}", "={edx}"]).iter().enumerate() {
500                         assert_eq!(&outputs[i].constraint.as_str(), c);
501                         assert!(!outputs[i].is_rw);
502                         assert!(!outputs[i].is_indirect);
503                     }
504
505                     assert_eq!(clobbers, &[Name::intern("rbx")]);
506
507                     assert!(!volatile);
508                     assert!(!alignstack);
509
510                     crate::trap::trap_unimplemented(fx, "__cpuid_count arch intrinsic is not supported");
511                 }
512                 "xgetbv" => {
513                     assert_eq!(inputs, &[Name::intern("{ecx}")]);
514
515                     assert_eq!(outputs.len(), 2);
516                     for (i, c) in (&["={eax}", "={edx}"]).iter().enumerate() {
517                         assert_eq!(&outputs[i].constraint.as_str(), c);
518                         assert!(!outputs[i].is_rw);
519                         assert!(!outputs[i].is_indirect);
520                     }
521
522                     assert_eq!(clobbers, &[]);
523
524                     assert!(!volatile);
525                     assert!(!alignstack);
526
527                     crate::trap::trap_unimplemented(fx, "_xgetbv arch intrinsic is not supported");
528                 }
529                 _ if fx.tcx.symbol_name(fx.instance).as_str() == "__rust_probestack" => {
530                     crate::trap::trap_unimplemented(fx, "__rust_probestack is not supported");
531                 }
532                 _ => unimpl!("Inline assembly is not supported"),
533             }
534         }
535     }
536 }
537
538 fn codegen_array_len<'a, 'tcx: 'a>(
539     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
540     place: CPlace<'tcx>,
541 ) -> Value {
542     match place.layout().ty.sty {
543         ty::Array(_elem_ty, len) => {
544             let len = crate::constant::force_eval_const(fx, len)
545                 .eval_usize(fx.tcx, ParamEnv::reveal_all()) as i64;
546             fx.bcx.ins().iconst(fx.pointer_type, len)
547         }
548         ty::Slice(_elem_ty) => place
549             .to_addr_maybe_unsized(fx)
550             .1
551             .expect("Length metadata for slice place"),
552         _ => bug!("Rvalue::Len({:?})", place),
553     }
554 }
555
556 pub fn trans_place<'a, 'tcx: 'a>(
557     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
558     place: &Place<'tcx>,
559 ) -> CPlace<'tcx> {
560     let base = match &place.base {
561         PlaceBase::Local(local) => fx.get_local_place(*local),
562         PlaceBase::Static(static_) => match static_.kind {
563             StaticKind::Static(def_id) => {
564                 crate::constant::codegen_static_ref(fx, def_id, static_.ty)
565             }
566             StaticKind::Promoted(promoted) => {
567                 crate::constant::trans_promoted(fx, promoted, static_.ty)
568             }
569         }
570     };
571
572     trans_place_projection(fx, base, &place.projection)
573 }
574
575 pub fn trans_place_projection<'a, 'tcx: 'a>(
576     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
577     base: CPlace<'tcx>,
578     projection: &Option<Box<Projection<'tcx>>>,
579 ) -> CPlace<'tcx> {
580     let projection = if let Some(projection) = projection {
581         projection
582     } else {
583         return base;
584     };
585
586     let base = trans_place_projection(fx, base, &projection.base);
587
588     match projection.elem {
589         ProjectionElem::Deref => base.place_deref(fx),
590         ProjectionElem::Field(field, _ty) => base.place_field(fx, field),
591         ProjectionElem::Index(local) => {
592             let index = fx.get_local_place(local).to_cvalue(fx).load_scalar(fx);
593             base.place_index(fx, index)
594         }
595         ProjectionElem::ConstantIndex {
596             offset,
597             min_length: _,
598             from_end,
599         } => {
600             let index = if !from_end {
601                 fx.bcx.ins().iconst(fx.pointer_type, offset as i64)
602             } else {
603                 let len = codegen_array_len(fx, base);
604                 fx.bcx.ins().iadd_imm(len, -(offset as i64))
605             };
606             base.place_index(fx, index)
607         }
608         ProjectionElem::Subslice { from, to } => {
609             // These indices are generated by slice patterns.
610             // slice[from:-to] in Python terms.
611
612             match base.layout().ty.sty {
613                 ty::Array(elem_ty, len) => {
614                     let elem_layout = fx.layout_of(elem_ty);
615                     let ptr = base.to_addr(fx);
616                     let len = crate::constant::force_eval_const(fx, len)
617                         .eval_usize(fx.tcx, ParamEnv::reveal_all());
618                     CPlace::for_addr(
619                         fx.bcx.ins().iadd_imm(ptr, elem_layout.size.bytes() as i64 * from as i64),
620                         fx.layout_of(fx.tcx.mk_array(elem_ty, len - from as u64 - to as u64)),
621                     )
622                 }
623                 ty::Slice(elem_ty) => {
624                     let elem_layout = fx.layout_of(elem_ty);
625                     let (ptr, len) = base.to_addr_maybe_unsized(fx);
626                     let len = len.unwrap();
627                     CPlace::for_addr_with_extra(
628                         fx.bcx.ins().iadd_imm(ptr, elem_layout.size.bytes() as i64 * from as i64),
629                         fx.bcx.ins().iadd_imm(len, -(from as i64 + to as i64)),
630                         base.layout(),
631                     )
632                 }
633                 _ => unreachable!(),
634             }
635         }
636         ProjectionElem::Downcast(_adt_def, variant) => base.downcast_variant(fx, variant),
637     }
638 }
639
640 pub fn trans_operand<'a, 'tcx>(
641     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
642     operand: &Operand<'tcx>,
643 ) -> CValue<'tcx> {
644     match operand {
645         Operand::Move(place) | Operand::Copy(place) => {
646             let cplace = trans_place(fx, place);
647             cplace.to_cvalue(fx)
648         }
649         Operand::Constant(const_) => crate::constant::trans_constant(fx, const_),
650     }
651 }