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