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