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