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