]> git.lizzy.rs Git - rust.git/blob - src/base.rs
[OPT] Push fx.monomorphize to the callers of fx.layout_of
[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, cx.module.isa().triple(), 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, instance, func_id, &name));
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     let local_map = fx.local_map;
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     // Write optimized function to file for debugging
78     #[cfg(debug_assertions)]
79     {
80         let value_ranges = context
81             .build_value_labels_ranges(cx.module.isa())
82             .expect("value location ranges");
83
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
94     // Define debuginfo for function
95     let isa = cx.module.isa();
96     debug_context
97         .as_mut()
98         .map(|x| x.define(context, isa, &source_info_set, local_map));
99
100     // Clear context to make it usable for the next function
101     context.clear();
102 }
103
104 fn verify_func(tcx: TyCtxt, writer: &crate::pretty_clif::CommentWriter, func: &Function) {
105     let flags = settings::Flags::new(settings::builder());
106     match ::cranelift::codegen::verify_function(&func, &flags) {
107         Ok(_) => {}
108         Err(err) => {
109             tcx.sess.err(&format!("{:?}", err));
110             let pretty_error = ::cranelift::codegen::print_errors::pretty_verifier_error(
111                 &func,
112                 None,
113                 Some(Box::new(writer)),
114                 err,
115             );
116             tcx.sess
117                 .fatal(&format!("cranelift verify error:\n{}", pretty_error));
118         }
119     }
120 }
121
122 fn codegen_fn_content(fx: &mut FunctionCx<'_, '_, impl Backend>) {
123     for (bb, bb_data) in fx.mir.basic_blocks().iter_enumerated() {
124         if bb_data.is_cleanup {
125             // Unwinding after panicking is not supported
126             continue;
127         }
128
129         let ebb = fx.get_ebb(bb);
130         fx.bcx.switch_to_block(ebb);
131
132         fx.bcx.ins().nop();
133         for stmt in &bb_data.statements {
134             fx.set_debug_loc(stmt.source_info);
135             trans_stmt(fx, ebb, stmt);
136         }
137
138         #[cfg(debug_assertions)]
139         {
140             let mut terminator_head = "\n".to_string();
141             bb_data
142                 .terminator()
143                 .kind
144                 .fmt_head(&mut terminator_head)
145                 .unwrap();
146             let inst = fx.bcx.func.layout.last_inst(ebb).unwrap();
147             fx.add_comment(inst, terminator_head);
148         }
149
150         fx.set_debug_loc(bb_data.terminator().source_info);
151
152         match &bb_data.terminator().kind {
153             TerminatorKind::Goto { target } => {
154                 let ebb = fx.get_ebb(*target);
155                 fx.bcx.ins().jump(ebb, &[]);
156             }
157             TerminatorKind::Return => {
158                 crate::abi::codegen_return(fx);
159             }
160             TerminatorKind::Assert {
161                 cond,
162                 expected,
163                 msg,
164                 target,
165                 cleanup: _,
166             } => {
167                 if !fx.tcx.sess.overflow_checks() {
168                     if let mir::interpret::PanicInfo::OverflowNeg = *msg {
169                         let target = fx.get_ebb(*target);
170                         fx.bcx.ins().jump(target, &[]);
171                         continue;
172                     }
173                 }
174                 let cond = trans_operand(fx, cond).load_scalar(fx);
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(
214                     fx,
215                     func,
216                     args,
217                     destination,
218                     bb_data.terminator().source_info.span,
219                 );
220             }
221             TerminatorKind::Resume | TerminatorKind::Abort => {
222                 trap_unreachable(fx, "[corruption] Unwinding bb reached.");
223             }
224             TerminatorKind::Unreachable => {
225                 trap_unreachable(fx, "[corruption] Hit unreachable code.");
226             }
227             TerminatorKind::Yield { .. }
228             | TerminatorKind::FalseEdges { .. }
229             | TerminatorKind::FalseUnwind { .. }
230             | TerminatorKind::DropAndReplace { .. }
231             | TerminatorKind::GeneratorDrop => {
232                 bug!("shouldn't exist at trans {:?}", bb_data.terminator());
233             }
234             TerminatorKind::Drop {
235                 location,
236                 target,
237                 unwind: _,
238             } => {
239                 let drop_place = trans_place(fx, location);
240                 crate::abi::codegen_drop(fx, drop_place);
241
242                 let target_ebb = fx.get_ebb(*target);
243                 fx.bcx.ins().jump(target_ebb, &[]);
244             }
245         };
246     }
247
248     fx.bcx.seal_all_blocks();
249     fx.bcx.finalize();
250 }
251
252 fn trans_stmt<'tcx>(
253     fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
254     cur_ebb: Ebb,
255     stmt: &Statement<'tcx>,
256 ) {
257     let _print_guard = PrintOnPanic(|| format!("stmt {:?}", stmt));
258
259     fx.set_debug_loc(stmt.source_info);
260
261     #[cfg(debug_assertions)]
262     match &stmt.kind {
263         StatementKind::StorageLive(..) | StatementKind::StorageDead(..) => {} // Those are not very useful
264         _ => {
265             let inst = fx.bcx.func.layout.last_inst(cur_ebb).unwrap();
266             fx.add_comment(inst, format!("{:?}", stmt));
267         }
268     }
269
270     match &stmt.kind {
271         StatementKind::SetDiscriminant {
272             place,
273             variant_index,
274         } => {
275             let place = trans_place(fx, place);
276             crate::discriminant::codegen_set_discriminant(fx, place, *variant_index);
277         }
278         StatementKind::Assign(to_place_and_rval) => {
279             let lval = trans_place(fx, &to_place_and_rval.0);
280             let dest_layout = lval.layout();
281             match &to_place_and_rval.1 {
282                 Rvalue::Use(operand) => {
283                     let val = trans_operand(fx, operand);
284                     lval.write_cvalue(fx, val);
285                 }
286                 Rvalue::Ref(_, _, place) => {
287                     let place = trans_place(fx, place);
288                     place.write_place_ref(fx, lval);
289                 }
290                 Rvalue::BinaryOp(bin_op, lhs, rhs) => {
291                     let lhs = trans_operand(fx, lhs);
292                     let rhs = trans_operand(fx, rhs);
293
294                     let res = crate::num::codegen_binop(fx, *bin_op, lhs, rhs);
295                     lval.write_cvalue(fx, res);
296                 }
297                 Rvalue::CheckedBinaryOp(bin_op, lhs, rhs) => {
298                     let lhs = trans_operand(fx, lhs);
299                     let rhs = trans_operand(fx, rhs);
300
301                     let res = if !fx.tcx.sess.overflow_checks() {
302                         let val =
303                             crate::num::trans_int_binop(fx, *bin_op, lhs, rhs).load_scalar(fx);
304                         let is_overflow = fx.bcx.ins().iconst(types::I8, 0);
305                         CValue::by_val_pair(val, is_overflow, lval.layout())
306                     } else {
307                         crate::num::trans_checked_int_binop(fx, *bin_op, lhs, rhs)
308                     };
309
310                     lval.write_cvalue(fx, res);
311                 }
312                 Rvalue::UnaryOp(un_op, operand) => {
313                     let operand = trans_operand(fx, operand);
314                     let layout = operand.layout();
315                     let val = operand.load_scalar(fx);
316                     let res = match un_op {
317                         UnOp::Not => {
318                             match layout.ty.kind {
319                                 ty::Bool => {
320                                     let val = fx.bcx.ins().uextend(types::I32, val); // WORKAROUND for CraneStation/cranelift#466
321                                     let res = fx.bcx.ins().icmp_imm(IntCC::Equal, val, 0);
322                                     CValue::by_val(fx.bcx.ins().bint(types::I8, res), layout)
323                                 }
324                                 ty::Uint(_) | ty::Int(_) => {
325                                     CValue::by_val(fx.bcx.ins().bnot(val), layout)
326                                 }
327                                 _ => unimplemented!("un op Not for {:?}", layout.ty),
328                             }
329                         }
330                         UnOp::Neg => match layout.ty.kind {
331                             ty::Int(_) => {
332                                 let zero = CValue::const_val(fx, layout.ty, 0);
333                                 crate::num::trans_int_binop(fx, BinOp::Sub, zero, operand)
334                             }
335                             ty::Float(_) => {
336                                 CValue::by_val(fx.bcx.ins().fneg(val), layout)
337                             }
338                             _ => unimplemented!("un op Neg for {:?}", layout.ty),
339                         },
340                     };
341                     lval.write_cvalue(fx, res);
342                 }
343                 Rvalue::Cast(CastKind::Pointer(PointerCast::ReifyFnPointer), operand, to_ty) => {
344                     let from_ty = fx.monomorphize(&operand.ty(&fx.mir.local_decls, fx.tcx));
345                     let to_layout = fx.layout_of(fx.monomorphize(to_ty));
346                     match from_ty.kind {
347                         ty::FnDef(def_id, substs) => {
348                             let func_ref = fx.get_function_ref(
349                                 Instance::resolve(fx.tcx, ParamEnv::reveal_all(), def_id, substs)
350                                     .unwrap(),
351                             );
352                             let func_addr = fx.bcx.ins().func_addr(fx.pointer_type, func_ref);
353                             lval.write_cvalue(fx, CValue::by_val(func_addr, to_layout));
354                         }
355                         _ => bug!("Trying to ReifyFnPointer on non FnDef {:?}", from_ty),
356                     }
357                 }
358                 Rvalue::Cast(CastKind::Pointer(PointerCast::UnsafeFnPointer), operand, to_ty)
359                 | Rvalue::Cast(CastKind::Pointer(PointerCast::MutToConstPointer), operand, to_ty)
360                 | Rvalue::Cast(CastKind::Pointer(PointerCast::ArrayToPointer), operand, to_ty) => {
361                     let to_layout = fx.layout_of(fx.monomorphize(to_ty));
362                     let operand = trans_operand(fx, operand);
363                     lval.write_cvalue(fx, operand.unchecked_cast_to(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                     let to_ty = fx.monomorphize(to_ty);
369
370                     fn is_fat_ptr<'tcx>(
371                         fx: &FunctionCx<'_, 'tcx, impl Backend>,
372                         ty: Ty<'tcx>,
373                     ) -> bool {
374                         ty.builtin_deref(true)
375                             .map(
376                                 |ty::TypeAndMut {
377                                      ty: pointee_ty,
378                                      mutbl: _,
379                                  }| has_ptr_meta(fx.tcx, pointee_ty),
380                             )
381                             .unwrap_or(false)
382                     }
383
384                     if is_fat_ptr(fx, from_ty) {
385                         if is_fat_ptr(fx, to_ty) {
386                             // fat-ptr -> fat-ptr
387                             lval.write_cvalue(fx, operand.unchecked_cast_to(dest_layout));
388                         } else {
389                             // fat-ptr -> thin-ptr
390                             let (ptr, _extra) = operand.load_scalar_pair(fx);
391                             lval.write_cvalue(fx, CValue::by_val(ptr, dest_layout))
392                         }
393                     } else if let ty::Adt(adt_def, _substs) = from_ty.kind {
394                         // enum -> discriminant value
395                         assert!(adt_def.is_enum());
396                         match to_ty.kind {
397                             ty::Uint(_) | ty::Int(_) => {}
398                             _ => unreachable!("cast adt {} -> {}", from_ty, to_ty),
399                         }
400
401                         let discr = crate::discriminant::codegen_get_discriminant(
402                             fx,
403                             operand,
404                             fx.layout_of(to_ty),
405                         );
406                         lval.write_cvalue(fx, discr);
407                     } else {
408                         let to_clif_ty = fx.clif_type(to_ty).unwrap();
409                         let from = operand.load_scalar(fx);
410
411                         let res = clif_int_or_float_cast(
412                             fx,
413                             from,
414                             type_sign(from_ty),
415                             to_clif_ty,
416                             type_sign(to_ty),
417                         );
418                         lval.write_cvalue(fx, CValue::by_val(res, dest_layout));
419                     }
420                 }
421                 Rvalue::Cast(CastKind::Pointer(PointerCast::ClosureFnPointer(_)), operand, _to_ty) => {
422                     let operand = trans_operand(fx, operand);
423                     match operand.layout().ty.kind {
424                         ty::Closure(def_id, substs) => {
425                             let instance = Instance::resolve_closure(
426                                 fx.tcx,
427                                 def_id,
428                                 substs,
429                                 ty::ClosureKind::FnOnce,
430                             );
431                             let func_ref = fx.get_function_ref(instance);
432                             let func_addr = fx.bcx.ins().func_addr(fx.pointer_type, func_ref);
433                             lval.write_cvalue(fx, CValue::by_val(func_addr, lval.layout()));
434                         }
435                         _ => bug!("{} cannot be cast to a fn ptr", operand.layout().ty),
436                     }
437                 }
438                 Rvalue::Cast(CastKind::Pointer(PointerCast::Unsize), operand, _to_ty) => {
439                     let operand = trans_operand(fx, operand);
440                     operand.unsize_value(fx, lval);
441                 }
442                 Rvalue::Discriminant(place) => {
443                     let place = trans_place(fx, place);
444                     let value = place.to_cvalue(fx);
445                     let discr =
446                         crate::discriminant::codegen_get_discriminant(fx, value, dest_layout);
447                     lval.write_cvalue(fx, discr);
448                 }
449                 Rvalue::Repeat(operand, times) => {
450                     let operand = trans_operand(fx, operand);
451                     for i in 0..*times {
452                         let index = fx.bcx.ins().iconst(fx.pointer_type, i as i64);
453                         let to = lval.place_index(fx, index);
454                         to.write_cvalue(fx, operand);
455                     }
456                 }
457                 Rvalue::Len(place) => {
458                     let place = trans_place(fx, place);
459                     let usize_layout = fx.layout_of(fx.tcx.types.usize);
460                     let len = codegen_array_len(fx, place);
461                     lval.write_cvalue(fx, CValue::by_val(len, usize_layout));
462                 }
463                 Rvalue::NullaryOp(NullOp::Box, content_ty) => {
464                     use rustc::middle::lang_items::ExchangeMallocFnLangItem;
465
466                     let usize_type = fx.clif_type(fx.tcx.types.usize).unwrap();
467                     let content_ty = fx.monomorphize(content_ty);
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(fx.monomorphize(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                     _ => unreachable!("shouldn't exist at trans {:?}", to_place_and_rval.1),
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::InlineAsmInner {
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                 "" => {
539                     assert_eq!(inputs, &[Name::intern("r")]);
540                     assert!(outputs.is_empty(), "{:?}", outputs);
541
542                     // Black box
543                 }
544                 "cpuid" | "cpuid\n" => {
545                     assert_eq!(inputs, &[Name::intern("{eax}"), Name::intern("{ecx}")]);
546
547                     assert_eq!(outputs.len(), 4);
548                     for (i, c) in (&["={eax}", "={ebx}", "={ecx}", "={edx}"])
549                         .iter()
550                         .enumerate()
551                     {
552                         assert_eq!(&outputs[i].constraint.as_str(), c);
553                         assert!(!outputs[i].is_rw);
554                         assert!(!outputs[i].is_indirect);
555                     }
556
557                     assert_eq!(clobbers, &[Name::intern("rbx")]);
558
559                     assert!(!volatile);
560                     assert!(!alignstack);
561
562                     crate::trap::trap_unimplemented(
563                         fx,
564                         "__cpuid_count arch intrinsic is not supported",
565                     );
566                 }
567                 "xgetbv" => {
568                     assert_eq!(inputs, &[Name::intern("{ecx}")]);
569
570                     assert_eq!(outputs.len(), 2);
571                     for (i, c) in (&["={eax}", "={edx}"]).iter().enumerate() {
572                         assert_eq!(&outputs[i].constraint.as_str(), c);
573                         assert!(!outputs[i].is_rw);
574                         assert!(!outputs[i].is_indirect);
575                     }
576
577                     assert_eq!(clobbers, &[]);
578
579                     assert!(!volatile);
580                     assert!(!alignstack);
581
582                     crate::trap::trap_unimplemented(fx, "_xgetbv arch intrinsic is not supported");
583                 }
584                 _ if fx.tcx.symbol_name(fx.instance).name.as_str() == "__rust_probestack" => {
585                     crate::trap::trap_unimplemented(fx, "__rust_probestack is not supported");
586                 }
587                 _ => unimpl!("Inline assembly is not supported"),
588             }
589         }
590     }
591 }
592
593 fn codegen_array_len<'tcx>(
594     fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
595     place: CPlace<'tcx>,
596 ) -> Value {
597     match place.layout().ty.kind {
598         ty::Array(_elem_ty, len) => {
599             let len = crate::constant::force_eval_const(fx, len)
600                 .eval_usize(fx.tcx, ParamEnv::reveal_all()) as i64;
601             fx.bcx.ins().iconst(fx.pointer_type, len)
602         }
603         ty::Slice(_elem_ty) => place
604             .to_addr_maybe_unsized(fx)
605             .1
606             .expect("Length metadata for slice place"),
607         _ => bug!("Rvalue::Len({:?})", place),
608     }
609 }
610
611 pub fn trans_place<'tcx>(
612     fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
613     place: &Place<'tcx>,
614 ) -> CPlace<'tcx> {
615     let mut cplace = match &place.base {
616         PlaceBase::Local(local) => fx.get_local_place(*local),
617         PlaceBase::Static(static_) => match static_.kind {
618             StaticKind::Static => {
619                 crate::constant::codegen_static_ref(fx, static_.def_id, static_.ty)
620             }
621             StaticKind::Promoted(promoted, substs) => {
622                 let instance = Instance::new(static_.def_id, fx.monomorphize(&substs));
623                 crate::constant::trans_promoted(fx, instance, promoted, static_.ty)
624             }
625         },
626     };
627
628     for elem in &*place.projection {
629         match *elem {
630             PlaceElem::Deref => {
631                 cplace = cplace.place_deref(fx);
632             }
633             PlaceElem::Field(field, _ty) => {
634                 cplace = cplace.place_field(fx, field);
635             }
636             PlaceElem::Index(local) => {
637                 let index = fx.get_local_place(local).to_cvalue(fx).load_scalar(fx);
638                 cplace = cplace.place_index(fx, index);
639             }
640             PlaceElem::ConstantIndex {
641                 offset,
642                 min_length: _,
643                 from_end,
644             } => {
645                 let index = if !from_end {
646                     fx.bcx.ins().iconst(fx.pointer_type, offset as i64)
647                 } else {
648                     let len = codegen_array_len(fx, cplace);
649                     fx.bcx.ins().iadd_imm(len, -(offset as i64))
650                 };
651                 cplace = cplace.place_index(fx, index);
652             }
653             PlaceElem::Subslice { from, to, from_end } => {
654                 // These indices are generated by slice patterns.
655                 // slice[from:-to] in Python terms.
656
657                 match cplace.layout().ty.kind {
658                     ty::Array(elem_ty, len) => {
659                         let elem_layout = fx.layout_of(elem_ty);
660                         let ptr = cplace.to_addr(fx);
661                         let len = crate::constant::force_eval_const(fx, len)
662                             .eval_usize(fx.tcx, ParamEnv::reveal_all());
663                         cplace = CPlace::for_addr(
664                             fx.bcx
665                                 .ins()
666                                 .iadd_imm(ptr, elem_layout.size.bytes() as i64 * from as i64),
667                             fx.layout_of(fx.tcx.mk_array(elem_ty, len - from as u64 - to as u64)),
668                         );
669                     }
670                     ty::Slice(elem_ty) => {
671                         assert!(from_end, "slice subslices should be `from_end`");
672                         let elem_layout = fx.layout_of(elem_ty);
673                         let (ptr, len) = cplace.to_addr_maybe_unsized(fx);
674                         let len = len.unwrap();
675                         cplace = CPlace::for_addr_with_extra(
676                             fx.bcx
677                                 .ins()
678                                 .iadd_imm(ptr, elem_layout.size.bytes() as i64 * from as i64),
679                             fx.bcx.ins().iadd_imm(len, -(from as i64 + to as i64)),
680                             cplace.layout(),
681                         );
682                     }
683                     _ => unreachable!(),
684                 }
685             }
686             PlaceElem::Downcast(_adt_def, variant) => {
687                 cplace = cplace.downcast_variant(fx, variant);
688             }
689         }
690     }
691
692     cplace
693 }
694
695 pub fn trans_operand<'tcx>(
696     fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
697     operand: &Operand<'tcx>,
698 ) -> CValue<'tcx> {
699     match operand {
700         Operand::Move(place) | Operand::Copy(place) => {
701             let cplace = trans_place(fx, place);
702             cplace.to_cvalue(fx)
703         }
704         Operand::Constant(const_) => crate::constant::trans_constant(fx, const_),
705     }
706 }