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