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