]> git.lizzy.rs Git - rust.git/blob - src/base.rs
Misc changes
[rust.git] / src / base.rs
1 use rustc::ty::adjustment::PointerCast;
2
3 use crate::prelude::*;
4
5 pub fn trans_fn<'a, 'clif, 'tcx: 'a, 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: &mut cx.ccx,
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
76         .define_function(func_id, context)
77         .unwrap();
78
79     let value_ranges = context.build_value_labels_ranges(cx.module.isa()).expect("value location ranges");
80
81     // Write optimized function to file for debugging
82     #[cfg(debug_assertions)]
83     crate::pretty_clif::write_clif_file(cx.tcx, "opt", instance, &context.func, &clif_comments, Some(&value_ranges));
84
85     // Define debuginfo for function
86     let isa = cx.module.isa();
87     debug_context
88         .as_mut()
89         .map(|x| x.define(tcx, context, isa, &source_info_set));
90
91     // Clear context to make it usable for the next function
92     context.clear();
93 }
94
95 fn verify_func(tcx: TyCtxt, writer: &crate::pretty_clif::CommentWriter, func: &Function) {
96     let flags = settings::Flags::new(settings::builder());
97     match ::cranelift::codegen::verify_function(&func, &flags) {
98         Ok(_) => {}
99         Err(err) => {
100             tcx.sess.err(&format!("{:?}", err));
101             let pretty_error = ::cranelift::codegen::print_errors::pretty_verifier_error(
102                 &func,
103                 None,
104                 Some(Box::new(writer)),
105                 err,
106             );
107             tcx.sess
108                 .fatal(&format!("cranelift verify error:\n{}", pretty_error));
109         }
110     }
111 }
112
113 fn codegen_fn_content<'a, 'tcx: 'a>(fx: &mut FunctionCx<'a, 'tcx, impl Backend>) {
114     for (bb, bb_data) in fx.mir.basic_blocks().iter_enumerated() {
115         if bb_data.is_cleanup {
116             // Unwinding after panicking is not supported
117             continue;
118         }
119
120         let ebb = fx.get_ebb(bb);
121         fx.bcx.switch_to_block(ebb);
122
123         fx.bcx.ins().nop();
124         for stmt in &bb_data.statements {
125             fx.set_debug_loc(stmt.source_info);
126             trans_stmt(fx, ebb, stmt);
127         }
128
129         #[cfg(debug_assertions)]
130         {
131             let mut terminator_head = "\n".to_string();
132             bb_data
133                 .terminator()
134                 .kind
135                 .fmt_head(&mut terminator_head)
136                 .unwrap();
137             let inst = fx.bcx.func.layout.last_inst(ebb).unwrap();
138             fx.add_comment(inst, terminator_head);
139         }
140
141         fx.set_debug_loc(bb_data.terminator().source_info);
142
143         match &bb_data.terminator().kind {
144             TerminatorKind::Goto { target } => {
145                 let ebb = fx.get_ebb(*target);
146                 fx.bcx.ins().jump(ebb, &[]);
147             }
148             TerminatorKind::Return => {
149                 crate::abi::codegen_return(fx);
150             }
151             TerminatorKind::Assert {
152                 cond,
153                 expected,
154                 msg,
155                 target,
156                 cleanup: _,
157             } => {
158                 let cond = trans_operand(fx, cond).load_scalar(fx);
159                 // TODO HACK brz/brnz for i8/i16 is not yet implemented
160                 let cond = fx.bcx.ins().uextend(types::I32, cond);
161                 let target = fx.get_ebb(*target);
162                 if *expected {
163                     fx.bcx.ins().brnz(cond, target, &[]);
164                 } else {
165                     fx.bcx.ins().brz(cond, target, &[]);
166                 };
167                 trap_panic(fx, format!("[panic] Assert {:?} at {:?} failed.", msg, bb_data.terminator().source_info.span));
168             }
169
170             TerminatorKind::SwitchInt {
171                 discr,
172                 switch_ty: _,
173                 values,
174                 targets,
175             } => {
176                 let discr = trans_operand(fx, discr).load_scalar(fx);
177                 let mut switch = ::cranelift::frontend::Switch::new();
178                 for (i, value) in values.iter().enumerate() {
179                     let ebb = fx.get_ebb(targets[i]);
180                     switch.set_entry(*value as u64, ebb);
181                 }
182                 let otherwise_ebb = fx.get_ebb(targets[targets.len() - 1]);
183                 switch.emit(&mut fx.bcx, discr, otherwise_ebb);
184             }
185             TerminatorKind::Call {
186                 func,
187                 args,
188                 destination,
189                 cleanup: _,
190                 from_hir_call: _,
191             } => {
192                 crate::abi::codegen_terminator_call(fx, func, args, destination);
193             }
194             TerminatorKind::Resume | TerminatorKind::Abort => {
195                 trap_unreachable(fx, "[corruption] Unwinding bb reached.");
196             }
197             TerminatorKind::Unreachable => {
198                 trap_unreachable(fx, "[corruption] Hit unreachable code.");
199             }
200             TerminatorKind::Yield { .. }
201             | TerminatorKind::FalseEdges { .. }
202             | TerminatorKind::FalseUnwind { .. }
203             | TerminatorKind::DropAndReplace { .. }
204             | TerminatorKind::GeneratorDrop => {
205                 bug!("shouldn't exist at trans {:?}", bb_data.terminator());
206             }
207             TerminatorKind::Drop {
208                 location,
209                 target,
210                 unwind: _,
211             } => {
212                 let drop_place = trans_place(fx, location);
213                 crate::abi::codegen_drop(fx, drop_place);
214
215                 let target_ebb = fx.get_ebb(*target);
216                 fx.bcx.ins().jump(target_ebb, &[]);
217             }
218         };
219     }
220
221     fx.bcx.seal_all_blocks();
222     fx.bcx.finalize();
223 }
224
225 fn trans_stmt<'a, 'tcx: 'a>(
226     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
227     cur_ebb: Ebb,
228     stmt: &Statement<'tcx>,
229 ) {
230     let _print_guard = PrintOnPanic(|| format!("stmt {:?}", stmt));
231
232     fx.set_debug_loc(stmt.source_info);
233
234     #[cfg(debug_assertions)]
235     match &stmt.kind {
236         StatementKind::StorageLive(..) | StatementKind::StorageDead(..) => {} // Those are not very useful
237         _ => {
238             let inst = fx.bcx.func.layout.last_inst(cur_ebb).unwrap();
239             fx.add_comment(inst, format!("{:?}", stmt));
240         }
241     }
242
243     match &stmt.kind {
244         StatementKind::SetDiscriminant {
245             place,
246             variant_index,
247         } => {
248             let place = trans_place(fx, place);
249             let layout = place.layout();
250             if layout.for_variant(&*fx, *variant_index).abi == layout::Abi::Uninhabited {
251                 return;
252             }
253             match layout.variants {
254                 layout::Variants::Single { index } => {
255                     assert_eq!(index, *variant_index);
256                 }
257                 layout::Variants::Multiple {
258                     discr: _,
259                     discr_index,
260                     discr_kind: layout::DiscriminantKind::Tag,
261                     variants: _,
262                 } => {
263                     let ptr = place.place_field(fx, mir::Field::new(discr_index));
264                     let to = layout
265                         .ty
266                         .discriminant_for_variant(fx.tcx, *variant_index)
267                         .unwrap()
268                         .val;
269                     let discr = CValue::const_val(fx, ptr.layout().ty, to);
270                     ptr.write_cvalue(fx, discr);
271                 }
272                 layout::Variants::Multiple {
273                     discr: _,
274                     discr_index,
275                     discr_kind: layout::DiscriminantKind::Niche {
276                         dataful_variant,
277                         ref niche_variants,
278                         niche_start,
279                     },
280                     variants: _,
281                 } => {
282                     if *variant_index != dataful_variant {
283                         let niche = place.place_field(fx, mir::Field::new(discr_index));
284                         //let niche_llty = niche.layout.immediate_llvm_type(bx.cx);
285                         let niche_value =
286                             ((variant_index.as_u32() - niche_variants.start().as_u32()) as u128)
287                                 .wrapping_add(niche_start);
288                         // FIXME(eddyb) Check the actual primitive type here.
289                         let niche_llval = if niche_value == 0 {
290                             CValue::const_val(fx, niche.layout().ty, 0)
291                         } else {
292                             CValue::const_val(fx, niche.layout().ty, niche_value)
293                         };
294                         niche.write_cvalue(fx, niche_llval);
295                     }
296                 }
297             }
298         }
299         StatementKind::Assign(to_place, rval) => {
300             let lval = trans_place(fx, to_place);
301             let dest_layout = lval.layout();
302             match &**rval {
303                 Rvalue::Use(operand) => {
304                     let val = trans_operand(fx, operand);
305                     lval.write_cvalue(fx, val);
306                 }
307                 Rvalue::Ref(_, _, place) => {
308                     let place = trans_place(fx, place);
309                     place.write_place_ref(fx, lval);
310                 }
311                 Rvalue::BinaryOp(bin_op, lhs, rhs) => {
312                     let ty = fx.monomorphize(&lhs.ty(fx.mir, fx.tcx));
313                     let lhs = trans_operand(fx, lhs);
314                     let rhs = trans_operand(fx, rhs);
315
316                     let res = match ty.sty {
317                         ty::Bool => trans_bool_binop(fx, *bin_op, lhs, rhs),
318                         ty::Uint(_) => {
319                             trans_int_binop(fx, *bin_op, lhs, rhs, lval.layout().ty, false)
320                         }
321                         ty::Int(_) => {
322                             trans_int_binop(fx, *bin_op, lhs, rhs, lval.layout().ty, true)
323                         }
324                         ty::Float(_) => trans_float_binop(fx, *bin_op, lhs, rhs, lval.layout().ty),
325                         ty::Char => trans_char_binop(fx, *bin_op, lhs, rhs, lval.layout().ty),
326                         ty::RawPtr(..) => trans_ptr_binop(fx, *bin_op, lhs, rhs, lval.layout().ty),
327                         ty::FnPtr(..) => trans_ptr_binop(fx, *bin_op, lhs, rhs, lval.layout().ty),
328                         _ => unimplemented!("binop {:?} for {:?}", bin_op, ty),
329                     };
330                     lval.write_cvalue(fx, res);
331                 }
332                 Rvalue::CheckedBinaryOp(bin_op, lhs, rhs) => {
333                     let ty = fx.monomorphize(&lhs.ty(fx.mir, fx.tcx));
334                     let lhs = trans_operand(fx, lhs);
335                     let rhs = trans_operand(fx, rhs);
336
337                     let signed = type_sign(ty);
338
339                     let res = if !fx.tcx.sess.overflow_checks() {
340                         let val = trans_int_binop(fx, *bin_op, lhs, rhs, lhs.layout().ty, signed).load_scalar(fx);
341                         let is_overflow = fx.bcx.ins().iconst(types::I8, 0);
342                         CValue::by_val_pair(val, is_overflow, lval.layout())
343                     } else {
344                         trans_checked_int_binop(fx, *bin_op, lhs, rhs, lval.layout().ty, signed)
345                     };
346
347                     lval.write_cvalue(fx, res);
348                 }
349                 Rvalue::UnaryOp(un_op, operand) => {
350                     let operand = trans_operand(fx, operand);
351                     let layout = operand.layout();
352                     let val = operand.load_scalar(fx);
353                     let res = match un_op {
354                         UnOp::Not => {
355                             match layout.ty.sty {
356                                 ty::Bool => {
357                                     let val = fx.bcx.ins().uextend(types::I32, val); // WORKAROUND for CraneStation/cranelift#466
358                                     let res = fx.bcx.ins().icmp_imm(IntCC::Equal, val, 0);
359                                     fx.bcx.ins().bint(types::I8, res)
360                                 }
361                                 ty::Uint(_) | ty::Int(_) => {
362                                     fx.bcx.ins().bnot(val)
363                                 }
364                                 _ => unimplemented!("un op Not for {:?}", layout.ty),
365                             }
366                         }
367                         UnOp::Neg => match layout.ty.sty {
368                             ty::Int(_) => {
369                                 let clif_ty = fx.clif_type(layout.ty).unwrap();
370                                 if clif_ty == types::I128 {
371                                     crate::trap::trap_unreachable_ret_value(fx, layout, "i128 neg is not yet supported").load_scalar(fx)
372                                 } else {
373                                     let zero = fx.bcx.ins().iconst(clif_ty, 0);
374                                     fx.bcx.ins().isub(zero, val)
375                                 }
376                             }
377                             ty::Float(_) => fx.bcx.ins().fneg(val),
378                             _ => unimplemented!("un op Neg for {:?}", layout.ty),
379                         },
380                     };
381                     lval.write_cvalue(fx, CValue::by_val(res, layout));
382                 }
383                 Rvalue::Cast(CastKind::Pointer(PointerCast::ReifyFnPointer), operand, ty) => {
384                     let layout = fx.layout_of(ty);
385                     match fx
386                         .monomorphize(&operand.ty(&fx.mir.local_decls, fx.tcx))
387                         .sty
388                     {
389                         ty::FnDef(def_id, substs) => {
390                             let func_ref = fx.get_function_ref(
391                                 Instance::resolve(fx.tcx, ParamEnv::reveal_all(), def_id, substs)
392                                     .unwrap(),
393                             );
394                             let func_addr = fx.bcx.ins().func_addr(fx.pointer_type, func_ref);
395                             lval.write_cvalue(fx, CValue::by_val(func_addr, layout));
396                         }
397                         _ => bug!("Trying to ReifyFnPointer on non FnDef {:?}", ty),
398                     }
399                 }
400                 Rvalue::Cast(CastKind::Pointer(PointerCast::UnsafeFnPointer), operand, ty)
401                 | Rvalue::Cast(CastKind::Pointer(PointerCast::MutToConstPointer), operand, ty) => {
402                     let operand = trans_operand(fx, operand);
403                     let layout = fx.layout_of(ty);
404                     lval.write_cvalue(fx, operand.unchecked_cast_to(layout));
405                 }
406                 Rvalue::Cast(CastKind::Misc, operand, to_ty) => {
407                     let operand = trans_operand(fx, operand);
408                     let from_ty = operand.layout().ty;
409
410                     fn is_fat_ptr<'a, 'tcx: 'a>(fx: &FunctionCx<'a, 'tcx, impl Backend>, ty: Ty<'tcx>) -> bool {
411                         ty
412                             .builtin_deref(true)
413                             .map(|ty::TypeAndMut {ty: pointee_ty, mutbl: _ }| fx.layout_of(pointee_ty).is_unsized())
414                             .unwrap_or(false)
415                     }
416
417                     if is_fat_ptr(fx, from_ty) {
418                         if is_fat_ptr(fx, to_ty) {
419                             // fat-ptr -> fat-ptr
420                             lval.write_cvalue(fx, operand.unchecked_cast_to(dest_layout));
421                         } else {
422                             // fat-ptr -> thin-ptr
423                             let (ptr, _extra) = operand.load_scalar_pair(fx);
424                             lval.write_cvalue(fx, CValue::by_val(ptr, dest_layout))
425                         }
426                     } else if let ty::Adt(adt_def, _substs) = from_ty.sty {
427                         // enum -> discriminant value
428                         assert!(adt_def.is_enum());
429                         match to_ty.sty {
430                             ty::Uint(_) | ty::Int(_) => {},
431                             _ => unreachable!("cast adt {} -> {}", from_ty, to_ty),
432                         }
433
434                         // FIXME avoid forcing to stack
435                         let place =
436                             CPlace::for_addr(operand.force_stack(fx), operand.layout());
437                         let discr = trans_get_discriminant(fx, place, fx.layout_of(to_ty));
438                         lval.write_cvalue(fx, discr);
439                     } else {
440                         let to_clif_ty = fx.clif_type(to_ty).unwrap();
441                         let from = operand.load_scalar(fx);
442
443                         let res = clif_int_or_float_cast(fx, from, type_sign(from_ty), to_clif_ty, type_sign(to_ty));
444                         lval.write_cvalue(fx, CValue::by_val(res, dest_layout));
445                     }
446                 }
447                 Rvalue::Cast(CastKind::Pointer(PointerCast::ClosureFnPointer(_)), operand, _ty) => {
448                     let operand = trans_operand(fx, operand);
449                     match operand.layout().ty.sty {
450                         ty::Closure(def_id, substs) => {
451                             let instance = Instance::resolve_closure(
452                                 fx.tcx,
453                                 def_id,
454                                 substs,
455                                 ty::ClosureKind::FnOnce,
456                             );
457                             let func_ref = fx.get_function_ref(instance);
458                             let func_addr = fx.bcx.ins().func_addr(fx.pointer_type, func_ref);
459                             lval.write_cvalue(fx, CValue::by_val(func_addr, lval.layout()));
460                         }
461                         _ => {
462                             bug!("{} cannot be cast to a fn ptr", operand.layout().ty)
463                         }
464                     }
465                 }
466                 Rvalue::Cast(CastKind::Pointer(PointerCast::Unsize), operand, _ty) => {
467                     let operand = trans_operand(fx, operand);
468                     operand.unsize_value(fx, lval);
469                 }
470                 Rvalue::Discriminant(place) => {
471                     let place = trans_place(fx, place);
472                     let discr = trans_get_discriminant(fx, place, dest_layout);
473                     lval.write_cvalue(fx, discr);
474                 }
475                 Rvalue::Repeat(operand, times) => {
476                     let operand = trans_operand(fx, operand);
477                     for i in 0..*times {
478                         let index = fx.bcx.ins().iconst(fx.pointer_type, i as i64);
479                         let to = lval.place_index(fx, index);
480                         to.write_cvalue(fx, operand);
481                     }
482                 }
483                 Rvalue::Len(place) => {
484                     let place = trans_place(fx, place);
485                     let usize_layout = fx.layout_of(fx.tcx.types.usize);
486                     let len = codegen_array_len(fx, place);
487                     lval.write_cvalue(fx, CValue::by_val(len, usize_layout));
488                 }
489                 Rvalue::NullaryOp(NullOp::Box, content_ty) => {
490                     use rustc::middle::lang_items::ExchangeMallocFnLangItem;
491
492                     let usize_type = fx.clif_type(fx.tcx.types.usize).unwrap();
493                     let layout = fx.layout_of(content_ty);
494                     let llsize = fx.bcx.ins().iconst(usize_type, layout.size.bytes() as i64);
495                     let llalign = fx
496                         .bcx
497                         .ins()
498                         .iconst(usize_type, layout.align.abi.bytes() as i64);
499                     let box_layout = fx.layout_of(fx.tcx.mk_box(content_ty));
500
501                     // Allocate space:
502                     let def_id = match fx.tcx.lang_items().require(ExchangeMallocFnLangItem) {
503                         Ok(id) => id,
504                         Err(s) => {
505                             fx.tcx
506                                 .sess
507                                 .fatal(&format!("allocation of `{}` {}", box_layout.ty, s));
508                         }
509                     };
510                     let instance = ty::Instance::mono(fx.tcx, def_id);
511                     let func_ref = fx.get_function_ref(instance);
512                     let call = fx.bcx.ins().call(func_ref, &[llsize, llalign]);
513                     let ptr = fx.bcx.inst_results(call)[0];
514                     lval.write_cvalue(fx, CValue::by_val(ptr, box_layout));
515                 }
516                 Rvalue::NullaryOp(NullOp::SizeOf, ty) => {
517                     assert!(lval
518                         .layout()
519                         .ty
520                         .is_sized(fx.tcx.at(DUMMY_SP), ParamEnv::reveal_all()));
521                     let ty_size = fx.layout_of(ty).size.bytes();
522                     let val = CValue::const_val(fx, fx.tcx.types.usize, ty_size.into());
523                     lval.write_cvalue(fx, val);
524                 }
525                 Rvalue::Aggregate(kind, operands) => match **kind {
526                     AggregateKind::Array(_ty) => {
527                         for (i, operand) in operands.into_iter().enumerate() {
528                             let operand = trans_operand(fx, operand);
529                             let index = fx.bcx.ins().iconst(fx.pointer_type, i as i64);
530                             let to = lval.place_index(fx, index);
531                             to.write_cvalue(fx, operand);
532                         }
533                     }
534                     _ => unimpl!("shouldn't exist at trans {:?}", rval),
535                 },
536             }
537         }
538         StatementKind::StorageLive(_)
539         | StatementKind::StorageDead(_)
540         | StatementKind::Nop
541         | StatementKind::FakeRead(..)
542         | StatementKind::Retag { .. }
543         | StatementKind::AscribeUserType(..) => {}
544
545         StatementKind::InlineAsm(asm) => {
546             use syntax::ast::Name;
547             let InlineAsm { asm, outputs: _, inputs: _ } = &**asm;
548             let rustc::hir::InlineAsm {
549                 asm: asm_code, // Name
550                 outputs, // Vec<Name>
551                 inputs, // Vec<Name>
552                 clobbers, // Vec<Name>
553                 volatile, // bool
554                 alignstack, // bool
555                 dialect: _, // syntax::ast::AsmDialect
556                 asm_str_style: _,
557                 ctxt: _,
558             } = asm;
559             match &*asm_code.as_str() {
560                 "cpuid" | "cpuid\n" => {
561                     assert_eq!(inputs, &[Name::intern("{eax}"), Name::intern("{ecx}")]);
562
563                     assert_eq!(outputs.len(), 4);
564                     for (i, c) in (&["={eax}", "={ebx}", "={ecx}", "={edx}"]).iter().enumerate() {
565                         assert_eq!(&outputs[i].constraint.as_str(), c);
566                         assert!(!outputs[i].is_rw);
567                         assert!(!outputs[i].is_indirect);
568                     }
569
570                     assert_eq!(clobbers, &[Name::intern("rbx")]);
571
572                     assert!(!volatile);
573                     assert!(!alignstack);
574
575                     crate::trap::trap_unimplemented(fx, "__cpuid_count arch intrinsic is not supported");
576                 }
577                 "xgetbv" => {
578                     assert_eq!(inputs, &[Name::intern("{ecx}")]);
579
580                     assert_eq!(outputs.len(), 2);
581                     for (i, c) in (&["={eax}", "={edx}"]).iter().enumerate() {
582                         assert_eq!(&outputs[i].constraint.as_str(), c);
583                         assert!(!outputs[i].is_rw);
584                         assert!(!outputs[i].is_indirect);
585                     }
586
587                     assert_eq!(clobbers, &[]);
588
589                     assert!(!volatile);
590                     assert!(!alignstack);
591
592                     crate::trap::trap_unimplemented(fx, "_xgetbv arch intrinsic is not supported");
593                 }
594                 _ if fx.tcx.symbol_name(fx.instance).as_str() == "__rust_probestack" => {
595                     crate::trap::trap_unimplemented(fx, "__rust_probestack is not supported");
596                 }
597                 _ => unimpl!("Inline assembly is not supported"),
598             }
599         }
600     }
601 }
602
603 fn codegen_array_len<'a, 'tcx: 'a>(
604     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
605     place: CPlace<'tcx>,
606 ) -> Value {
607     match place.layout().ty.sty {
608         ty::Array(_elem_ty, len) => {
609             let len = crate::constant::force_eval_const(fx, len)
610                 .eval_usize(fx.tcx, ParamEnv::reveal_all()) as i64;
611             fx.bcx.ins().iconst(fx.pointer_type, len)
612         }
613         ty::Slice(_elem_ty) => place
614             .to_addr_maybe_unsized(fx)
615             .1
616             .expect("Length metadata for slice place"),
617         _ => bug!("Rvalue::Len({:?})", place),
618     }
619 }
620
621 pub fn trans_get_discriminant<'a, 'tcx: 'a>(
622     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
623     place: CPlace<'tcx>,
624     dest_layout: TyLayout<'tcx>,
625 ) -> CValue<'tcx> {
626     let layout = place.layout();
627
628     if layout.abi == layout::Abi::Uninhabited {
629         return trap_unreachable_ret_value(fx, dest_layout, "[panic] Tried to get discriminant for uninhabited type.");
630     }
631
632     let (discr_scalar, discr_index, discr_kind) = match &layout.variants {
633         layout::Variants::Single { index } => {
634             let discr_val = layout
635                 .ty
636                 .ty_adt_def()
637                 .map_or(u128::from(index.as_u32()), |def| {
638                     def.discriminant_for_variant(fx.tcx, *index).val
639                 });
640             return CValue::const_val(fx, dest_layout.ty, discr_val);
641         }
642         layout::Variants::Multiple { discr, discr_index, discr_kind, variants: _ } => {
643             (discr, *discr_index, discr_kind)
644         }
645     };
646
647     let discr = place.place_field(fx, mir::Field::new(discr_index)).to_cvalue(fx);
648     let discr_ty = discr.layout().ty;
649     let lldiscr = discr.load_scalar(fx);
650     match discr_kind {
651         layout::DiscriminantKind::Tag => {
652             let signed = match discr_scalar.value {
653                 layout::Int(_, signed) => signed,
654                 _ => false,
655             };
656             let val = clif_intcast(fx, lldiscr, fx.clif_type(dest_layout.ty).unwrap(), signed);
657             return CValue::by_val(val, dest_layout);
658         }
659         layout::DiscriminantKind::Niche {
660             dataful_variant,
661             ref niche_variants,
662             niche_start,
663         } => {
664             let niche_llty = fx.clif_type(discr_ty).unwrap();
665             let dest_clif_ty = fx.clif_type(dest_layout.ty).unwrap();
666             if niche_variants.start() == niche_variants.end() {
667                 let b = fx
668                     .bcx
669                     .ins()
670                     .icmp_imm(IntCC::Equal, lldiscr, *niche_start as u64 as i64);
671                 let if_true = fx
672                     .bcx
673                     .ins()
674                     .iconst(dest_clif_ty, niche_variants.start().as_u32() as i64);
675                 let if_false = fx
676                     .bcx
677                     .ins()
678                     .iconst(dest_clif_ty, dataful_variant.as_u32() as i64);
679                 let val = fx.bcx.ins().select(b, if_true, if_false);
680                 return CValue::by_val(val, dest_layout);
681             } else {
682                 // Rebase from niche values to discriminant values.
683                 let delta = niche_start.wrapping_sub(niche_variants.start().as_u32() as u128);
684                 let delta = fx.bcx.ins().iconst(niche_llty, delta as u64 as i64);
685                 let lldiscr = fx.bcx.ins().isub(lldiscr, delta);
686                 let b = fx.bcx.ins().icmp_imm(
687                     IntCC::UnsignedLessThanOrEqual,
688                     lldiscr,
689                     niche_variants.end().as_u32() as i64,
690                 );
691                 let if_true =
692                     clif_intcast(fx, lldiscr, fx.clif_type(dest_layout.ty).unwrap(), false);
693                 let if_false = fx
694                     .bcx
695                     .ins()
696                     .iconst(dest_clif_ty, dataful_variant.as_u32() as i64);
697                 let val = fx.bcx.ins().select(b, if_true, if_false);
698                 return CValue::by_val(val, dest_layout);
699             }
700         }
701     }
702 }
703
704 macro_rules! binop_match {
705     (@single $fx:expr, $bug_fmt:expr, $var:expr, $signed:expr, $lhs:expr, $rhs:expr, $ret_ty:expr, bug) => {
706         bug!("binop {} on {} lhs: {:?} rhs: {:?}", stringify!($var), $bug_fmt, $lhs, $rhs)
707     };
708     (@single $fx:expr, $bug_fmt:expr, $var:expr, $signed:expr, $lhs:expr, $rhs:expr, $ret_ty:expr, icmp($cc:ident)) => {{
709         assert_eq!($fx.tcx.types.bool, $ret_ty);
710         let ret_layout = $fx.layout_of($ret_ty);
711
712         let b = $fx.bcx.ins().icmp(IntCC::$cc, $lhs, $rhs);
713         CValue::by_val($fx.bcx.ins().bint(types::I8, b), ret_layout)
714     }};
715     (@single $fx:expr, $bug_fmt:expr, $var:expr, $signed:expr, $lhs:expr, $rhs:expr, $ret_ty:expr, fcmp($cc:ident)) => {{
716         assert_eq!($fx.tcx.types.bool, $ret_ty);
717         let ret_layout = $fx.layout_of($ret_ty);
718         let b = $fx.bcx.ins().fcmp(FloatCC::$cc, $lhs, $rhs);
719         CValue::by_val($fx.bcx.ins().bint(types::I8, b), ret_layout)
720     }};
721     (@single $fx:expr, $bug_fmt:expr, $var:expr, $signed:expr, $lhs:expr, $rhs:expr, $ret_ty:expr, custom(|| $body:expr)) => {{
722         $body
723     }};
724     (@single $fx:expr, $bug_fmt:expr, $var:expr, $signed:expr, $lhs:expr, $rhs:expr, $ret_ty:expr, $name:ident) => {{
725         let ret_layout = $fx.layout_of($ret_ty);
726         CValue::by_val($fx.bcx.ins().$name($lhs, $rhs), ret_layout)
727     }};
728     (
729         $fx:expr, $bin_op:expr, $signed:expr, $lhs:expr, $rhs:expr, $ret_ty:expr, $bug_fmt:expr;
730         $(
731             $var:ident ($sign:pat) $name:tt $( ( $($next:tt)* ) )? ;
732         )*
733     ) => {{
734         let lhs = $lhs.load_scalar($fx);
735         let rhs = $rhs.load_scalar($fx);
736         match ($bin_op, $signed) {
737             $(
738                 (BinOp::$var, $sign) => binop_match!(@single $fx, $bug_fmt, $var, $signed, lhs, rhs, $ret_ty, $name $( ( $($next)* ) )?),
739             )*
740         }
741     }}
742 }
743
744 fn trans_bool_binop<'a, 'tcx: 'a>(
745     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
746     bin_op: BinOp,
747     lhs: CValue<'tcx>,
748     rhs: CValue<'tcx>,
749 ) -> CValue<'tcx> {
750     let res = binop_match! {
751         fx, bin_op, false, lhs, rhs, fx.tcx.types.bool, "bool";
752         Add (_) bug;
753         Sub (_) bug;
754         Mul (_) bug;
755         Div (_) bug;
756         Rem (_) bug;
757         BitXor (_) bxor;
758         BitAnd (_) band;
759         BitOr (_) bor;
760         Shl (_) bug;
761         Shr (_) bug;
762
763         Eq (_) icmp(Equal);
764         Lt (_) icmp(UnsignedLessThan);
765         Le (_) icmp(UnsignedLessThanOrEqual);
766         Ne (_) icmp(NotEqual);
767         Ge (_) icmp(UnsignedGreaterThanOrEqual);
768         Gt (_) icmp(UnsignedGreaterThan);
769
770         Offset (_) bug;
771     };
772
773     res
774 }
775
776 pub fn trans_int_binop<'a, 'tcx: 'a>(
777     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
778     bin_op: BinOp,
779     lhs: CValue<'tcx>,
780     rhs: CValue<'tcx>,
781     out_ty: Ty<'tcx>,
782     signed: bool,
783 ) -> CValue<'tcx> {
784     if bin_op != BinOp::Shl && bin_op != BinOp::Shr {
785         assert_eq!(
786             lhs.layout().ty,
787             rhs.layout().ty,
788             "int binop requires lhs and rhs of same type"
789         );
790     }
791
792     match out_ty.sty {
793         ty::Bool | ty::Uint(_) | ty::Int(_) => {}
794         _ => unreachable!("Out ty {:?} is not an integer or bool", out_ty),
795     }
796
797     if let Some(res) = crate::codegen_i128::maybe_codegen(fx, bin_op, false, signed, lhs, rhs, out_ty) {
798         return res;
799     }
800
801     let (lhs, rhs) = if
802         (bin_op == BinOp::Eq || bin_op == BinOp::Ne)
803         && (lhs.layout().ty.sty == fx.tcx.types.i8.sty || lhs.layout().ty.sty == fx.tcx.types.i16.sty)
804     {
805         // FIXME(CraneStation/cranelift#896) icmp_imm.i8/i16 with eq/ne for signed ints is implemented wrong.
806         let lhs = lhs.load_scalar(fx);
807         let rhs = rhs.load_scalar(fx);
808         (
809             CValue::by_val(fx.bcx.ins().sextend(types::I32, lhs), fx.layout_of(fx.tcx.types.i32)),
810             CValue::by_val(fx.bcx.ins().sextend(types::I32, rhs), fx.layout_of(fx.tcx.types.i32)),
811         )
812     } else {
813         (lhs, rhs)
814     };
815
816     binop_match! {
817         fx, bin_op, signed, lhs, rhs, out_ty, "int/uint";
818         Add (_) iadd;
819         Sub (_) isub;
820         Mul (_) imul;
821         Div (false) udiv;
822         Div (true) sdiv;
823         Rem (false) urem;
824         Rem (true) srem;
825         BitXor (_) bxor;
826         BitAnd (_) band;
827         BitOr (_) bor;
828         Shl (_) ishl;
829         Shr (false) ushr;
830         Shr (true) sshr;
831
832         Eq (_) icmp(Equal);
833         Lt (false) icmp(UnsignedLessThan);
834         Lt (true) icmp(SignedLessThan);
835         Le (false) icmp(UnsignedLessThanOrEqual);
836         Le (true) icmp(SignedLessThanOrEqual);
837         Ne (_) icmp(NotEqual);
838         Ge (false) icmp(UnsignedGreaterThanOrEqual);
839         Ge (true) icmp(SignedGreaterThanOrEqual);
840         Gt (false) icmp(UnsignedGreaterThan);
841         Gt (true) icmp(SignedGreaterThan);
842
843         Offset (_) bug;
844     }
845 }
846
847 pub fn trans_checked_int_binop<'a, 'tcx: 'a>(
848     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
849     bin_op: BinOp,
850     in_lhs: CValue<'tcx>,
851     in_rhs: CValue<'tcx>,
852     out_ty: Ty<'tcx>,
853     signed: bool,
854 ) -> CValue<'tcx> {
855     if bin_op != BinOp::Shl && bin_op != BinOp::Shr {
856         assert_eq!(
857             in_lhs.layout().ty,
858             in_rhs.layout().ty,
859             "checked int binop requires lhs and rhs of same type"
860         );
861     }
862
863     let lhs = in_lhs.load_scalar(fx);
864     let rhs = in_rhs.load_scalar(fx);
865
866     if let Some(res) = crate::codegen_i128::maybe_codegen(fx, bin_op, true, signed, in_lhs, in_rhs, out_ty) {
867         return res;
868     }
869
870     let (res, has_overflow) = match bin_op {
871         BinOp::Add => {
872             /*let (val, c_out) = fx.bcx.ins().iadd_cout(lhs, rhs);
873             (val, c_out)*/
874             // FIXME(CraneStation/cranelift#849) legalize iadd_cout for i8 and i16
875             let val = fx.bcx.ins().iadd(lhs, rhs);
876             let has_overflow = if !signed {
877                 fx.bcx.ins().icmp(IntCC::UnsignedLessThan, val, lhs)
878             } else {
879                 let rhs_is_negative = fx.bcx.ins().icmp_imm(IntCC::SignedLessThan, rhs, 0);
880                 let slt = fx.bcx.ins().icmp(IntCC::SignedLessThan, val, lhs);
881                 fx.bcx.ins().bxor(rhs_is_negative, slt)
882             };
883             (val, has_overflow)
884         }
885         BinOp::Sub => {
886             /*let (val, b_out) = fx.bcx.ins().isub_bout(lhs, rhs);
887             (val, b_out)*/
888             // FIXME(CraneStation/cranelift#849) legalize isub_bout for i8 and i16
889             let val = fx.bcx.ins().isub(lhs, rhs);
890             let has_overflow = if !signed {
891                 fx.bcx.ins().icmp(IntCC::UnsignedGreaterThan, val, lhs)
892             } else {
893                 let rhs_is_negative = fx.bcx.ins().icmp_imm(IntCC::SignedLessThan, rhs, 0);
894                 let sgt = fx.bcx.ins().icmp(IntCC::SignedGreaterThan, val, lhs);
895                 fx.bcx.ins().bxor(rhs_is_negative, sgt)
896             };
897             (val, has_overflow)
898         }
899         BinOp::Mul => {
900             let val = fx.bcx.ins().imul(lhs, rhs);
901             /*let val_hi = if !signed {
902                 fx.bcx.ins().umulhi(lhs, rhs)
903             } else {
904                 fx.bcx.ins().smulhi(lhs, rhs)
905             };
906             let has_overflow = fx.bcx.ins().icmp_imm(IntCC::NotEqual, val_hi, 0);*/
907             // TODO: check for overflow
908             let has_overflow = fx.bcx.ins().bconst(types::B1, false);
909             (val, has_overflow)
910         }
911         BinOp::Shl => {
912             let val = fx.bcx.ins().ishl(lhs, rhs);
913             // TODO: check for overflow
914             let has_overflow = fx.bcx.ins().bconst(types::B1, false);
915             (val, has_overflow)
916         }
917         BinOp::Shr => {
918             let val = if !signed {
919                 fx.bcx.ins().ushr(lhs, rhs)
920             } else {
921                 fx.bcx.ins().sshr(lhs, rhs)
922             };
923             // TODO: check for overflow
924             let has_overflow = fx.bcx.ins().bconst(types::B1, false);
925             (val, has_overflow)
926         }
927         _ => bug!(
928             "binop {:?} on checked int/uint lhs: {:?} rhs: {:?}",
929             bin_op,
930             in_lhs,
931             in_rhs
932         ),
933     };
934
935     let has_overflow = fx.bcx.ins().bint(types::I8, has_overflow);
936     let out_place = CPlace::new_stack_slot(fx, out_ty);
937     let out_layout = out_place.layout();
938     out_place.write_cvalue(fx, CValue::by_val_pair(res, has_overflow, out_layout));
939
940     out_place.to_cvalue(fx)
941 }
942
943 fn trans_float_binop<'a, 'tcx: 'a>(
944     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
945     bin_op: BinOp,
946     lhs: CValue<'tcx>,
947     rhs: CValue<'tcx>,
948     ty: Ty<'tcx>,
949 ) -> CValue<'tcx> {
950     let res = binop_match! {
951         fx, bin_op, false, lhs, rhs, ty, "float";
952         Add (_) fadd;
953         Sub (_) fsub;
954         Mul (_) fmul;
955         Div (_) fdiv;
956         Rem (_) custom(|| {
957             assert_eq!(lhs.layout().ty, ty);
958             assert_eq!(rhs.layout().ty, ty);
959             match ty.sty {
960                 ty::Float(FloatTy::F32) => fx.easy_call("fmodf", &[lhs, rhs], ty),
961                 ty::Float(FloatTy::F64) => fx.easy_call("fmod", &[lhs, rhs], ty),
962                 _ => bug!(),
963             }
964         });
965         BitXor (_) bxor;
966         BitAnd (_) band;
967         BitOr (_) bor;
968         Shl (_) bug;
969         Shr (_) bug;
970
971         Eq (_) fcmp(Equal);
972         Lt (_) fcmp(LessThan);
973         Le (_) fcmp(LessThanOrEqual);
974         Ne (_) fcmp(NotEqual);
975         Ge (_) fcmp(GreaterThanOrEqual);
976         Gt (_) fcmp(GreaterThan);
977
978         Offset (_) bug;
979     };
980
981     res
982 }
983
984 fn trans_char_binop<'a, 'tcx: 'a>(
985     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
986     bin_op: BinOp,
987     lhs: CValue<'tcx>,
988     rhs: CValue<'tcx>,
989     ty: Ty<'tcx>,
990 ) -> CValue<'tcx> {
991     let res = binop_match! {
992         fx, bin_op, false, lhs, rhs, ty, "char";
993         Add (_) bug;
994         Sub (_) bug;
995         Mul (_) bug;
996         Div (_) bug;
997         Rem (_) bug;
998         BitXor (_) bug;
999         BitAnd (_) bug;
1000         BitOr (_) bug;
1001         Shl (_) bug;
1002         Shr (_) bug;
1003
1004         Eq (_) icmp(Equal);
1005         Lt (_) icmp(UnsignedLessThan);
1006         Le (_) icmp(UnsignedLessThanOrEqual);
1007         Ne (_) icmp(NotEqual);
1008         Ge (_) icmp(UnsignedGreaterThanOrEqual);
1009         Gt (_) icmp(UnsignedGreaterThan);
1010
1011         Offset (_) bug;
1012     };
1013
1014     res
1015 }
1016
1017 fn trans_ptr_binop<'a, 'tcx: 'a>(
1018     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
1019     bin_op: BinOp,
1020     lhs: CValue<'tcx>,
1021     rhs: CValue<'tcx>,
1022     ret_ty: Ty<'tcx>,
1023 ) -> CValue<'tcx> {
1024     let not_fat = match lhs.layout().ty.sty {
1025         ty::RawPtr(TypeAndMut { ty, mutbl: _ }) => {
1026             ty.is_sized(fx.tcx.at(DUMMY_SP), ParamEnv::reveal_all())
1027         }
1028         ty::FnPtr(..) => true,
1029         _ => bug!("trans_ptr_binop on non ptr"),
1030     };
1031     if not_fat {
1032         if let BinOp::Offset = bin_op {
1033             let (base, offset) = (lhs, rhs.load_scalar(fx));
1034             let pointee_ty = base.layout().ty.builtin_deref(true).unwrap().ty;
1035             let pointee_size = fx.layout_of(pointee_ty).size.bytes();
1036             let ptr_diff = fx.bcx.ins().imul_imm(offset, pointee_size as i64);
1037             let base_val = base.load_scalar(fx);
1038             let res = fx.bcx.ins().iadd(base_val, ptr_diff);
1039             return CValue::by_val(res, base.layout());
1040         }
1041
1042         binop_match! {
1043             fx, bin_op, false, lhs, rhs, ret_ty, "ptr";
1044             Add (_) bug;
1045             Sub (_) bug;
1046             Mul (_) bug;
1047             Div (_) bug;
1048             Rem (_) bug;
1049             BitXor (_) bug;
1050             BitAnd (_) bug;
1051             BitOr (_) bug;
1052             Shl (_) bug;
1053             Shr (_) bug;
1054
1055             Eq (_) icmp(Equal);
1056             Lt (_) icmp(UnsignedLessThan);
1057             Le (_) icmp(UnsignedLessThanOrEqual);
1058             Ne (_) icmp(NotEqual);
1059             Ge (_) icmp(UnsignedGreaterThanOrEqual);
1060             Gt (_) icmp(UnsignedGreaterThan);
1061
1062             Offset (_) bug; // Handled above
1063         }
1064     } else {
1065         let (lhs_ptr, lhs_extra) = lhs.load_scalar_pair(fx);
1066         let (rhs_ptr, rhs_extra) = rhs.load_scalar_pair(fx);
1067
1068         let res = match bin_op {
1069             BinOp::Eq => {
1070                 let ptr_eq = fx.bcx.ins().icmp(IntCC::Equal, lhs_ptr, rhs_ptr);
1071                 let extra_eq = fx.bcx.ins().icmp(IntCC::Equal, lhs_extra, rhs_extra);
1072                 fx.bcx.ins().band(ptr_eq, extra_eq)
1073             }
1074             BinOp::Ne => {
1075                 let ptr_ne = fx.bcx.ins().icmp(IntCC::NotEqual, lhs_ptr, rhs_ptr);
1076                 let extra_ne = fx.bcx.ins().icmp(IntCC::NotEqual, lhs_extra, rhs_extra);
1077                 fx.bcx.ins().bor(ptr_ne, extra_ne)
1078             }
1079             BinOp::Lt | BinOp::Le | BinOp::Ge | BinOp::Gt => {
1080                 let ptr_eq = fx.bcx.ins().icmp(IntCC::Equal, lhs_ptr, rhs_ptr);
1081
1082                 let ptr_cmp = fx.bcx.ins().icmp(match bin_op {
1083                     BinOp::Lt => IntCC::UnsignedLessThan,
1084                     BinOp::Le => IntCC::UnsignedLessThanOrEqual,
1085                     BinOp::Ge => IntCC::UnsignedGreaterThanOrEqual,
1086                     BinOp::Gt => IntCC::UnsignedGreaterThan,
1087                     _ => unreachable!(),
1088                 }, lhs_ptr, rhs_ptr);
1089
1090                 let extra_cmp = fx.bcx.ins().icmp(match bin_op {
1091                     BinOp::Lt => IntCC::UnsignedLessThan,
1092                     BinOp::Le => IntCC::UnsignedLessThanOrEqual,
1093                     BinOp::Ge => IntCC::UnsignedGreaterThanOrEqual,
1094                     BinOp::Gt => IntCC::UnsignedGreaterThan,
1095                     _ => unreachable!(),
1096                 }, lhs_extra, rhs_extra);
1097
1098                 fx.bcx.ins().select(ptr_eq, extra_cmp, ptr_cmp)
1099             }
1100             _ => panic!("bin_op {:?} on ptr", bin_op),
1101         };
1102
1103         assert_eq!(fx.tcx.types.bool, ret_ty);
1104         let ret_layout = fx.layout_of(ret_ty);
1105         CValue::by_val(fx.bcx.ins().bint(types::I8, res), ret_layout)
1106     }
1107 }
1108
1109 pub fn trans_place<'a, 'tcx: 'a>(
1110     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
1111     place: &Place<'tcx>,
1112 ) -> CPlace<'tcx> {
1113     let base = match &place.base {
1114         PlaceBase::Local(local) => fx.get_local_place(*local),
1115         PlaceBase::Static(static_) => match static_.kind {
1116             StaticKind::Static(def_id) => {
1117                 crate::constant::codegen_static_ref(fx, def_id, static_.ty)
1118             }
1119             StaticKind::Promoted(promoted) => {
1120                 crate::constant::trans_promoted(fx, promoted, static_.ty)
1121             }
1122         }
1123     };
1124
1125     trans_place_projection(fx, base, &place.projection)
1126 }
1127
1128 pub fn trans_place_projection<'a, 'tcx: 'a>(
1129     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
1130     base: CPlace<'tcx>,
1131     projection: &Option<Box<Projection<'tcx>>>,
1132 ) -> CPlace<'tcx> {
1133     let projection = if let Some(projection) = projection {
1134         projection
1135     } else {
1136         return base;
1137     };
1138
1139     let base = trans_place_projection(fx, base, &projection.base);
1140
1141     match projection.elem {
1142         ProjectionElem::Deref => base.place_deref(fx),
1143         ProjectionElem::Field(field, _ty) => base.place_field(fx, field),
1144         ProjectionElem::Index(local) => {
1145             let index = fx.get_local_place(local).to_cvalue(fx).load_scalar(fx);
1146             base.place_index(fx, index)
1147         }
1148         ProjectionElem::ConstantIndex {
1149             offset,
1150             min_length: _,
1151             from_end,
1152         } => {
1153             let index = if !from_end {
1154                 fx.bcx.ins().iconst(fx.pointer_type, offset as i64)
1155             } else {
1156                 let len = codegen_array_len(fx, base);
1157                 fx.bcx.ins().iadd_imm(len, -(offset as i64))
1158             };
1159             base.place_index(fx, index)
1160         }
1161         ProjectionElem::Subslice { from, to } => {
1162             // These indices are generated by slice patterns.
1163             // slice[from:-to] in Python terms.
1164
1165             match base.layout().ty.sty {
1166                 ty::Array(elem_ty, len) => {
1167                     let elem_layout = fx.layout_of(elem_ty);
1168                     let ptr = base.to_addr(fx);
1169                     let len = crate::constant::force_eval_const(fx, len)
1170                         .eval_usize(fx.tcx, ParamEnv::reveal_all());
1171                     CPlace::for_addr(
1172                         fx.bcx.ins().iadd_imm(ptr, elem_layout.size.bytes() as i64 * from as i64),
1173                         fx.layout_of(fx.tcx.mk_array(elem_ty, len - from as u64 - to as u64)),
1174                     )
1175                 }
1176                 ty::Slice(elem_ty) => {
1177                     let elem_layout = fx.layout_of(elem_ty);
1178                     let (ptr, len) = base.to_addr_maybe_unsized(fx);
1179                     let len = len.unwrap();
1180                     CPlace::for_addr_with_extra(
1181                         fx.bcx.ins().iadd_imm(ptr, elem_layout.size.bytes() as i64 * from as i64),
1182                         fx.bcx.ins().iadd_imm(len, -(from as i64 + to as i64)),
1183                         base.layout(),
1184                     )
1185                 }
1186                 _ => unreachable!(),
1187             }
1188         }
1189         ProjectionElem::Downcast(_adt_def, variant) => base.downcast_variant(fx, variant),
1190     }
1191 }
1192
1193 pub fn trans_operand<'a, 'tcx>(
1194     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
1195     operand: &Operand<'tcx>,
1196 ) -> CValue<'tcx> {
1197     match operand {
1198         Operand::Move(place) | Operand::Copy(place) => {
1199             let cplace = trans_place(fx, place);
1200             cplace.to_cvalue(fx)
1201         }
1202         Operand::Constant(const_) => crate::constant::trans_constant(fx, const_),
1203     }
1204 }