]> git.lizzy.rs Git - rust.git/blob - src/base.rs
[WIP]
[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 {:?} failed at {:?}.", 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 as u64 as i64);
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 as u64 as i64)
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 res = match ty.sty {
338                         ty::Uint(_) => {
339                             trans_checked_int_binop(fx, *bin_op, lhs, rhs, lval.layout().ty, false)
340                         }
341                         ty::Int(_) => {
342                             trans_checked_int_binop(fx, *bin_op, lhs, rhs, lval.layout().ty, true)
343                         }
344                         _ => unimplemented!("checked binop {:?} for {:?}", bin_op, ty),
345                     };
346                     lval.write_cvalue(fx, res);
347                 }
348                 Rvalue::UnaryOp(un_op, operand) => {
349                     let operand = trans_operand(fx, operand);
350                     let layout = operand.layout();
351                     let val = operand.load_scalar(fx);
352                     let res = match un_op {
353                         UnOp::Not => {
354                             match layout.ty.sty {
355                                 ty::Bool => {
356                                     let val = fx.bcx.ins().uextend(types::I32, val); // WORKAROUND for CraneStation/cranelift#466
357                                     let res = fx.bcx.ins().icmp_imm(IntCC::Equal, val, 0);
358                                     fx.bcx.ins().bint(types::I8, res)
359                                 }
360                                 ty::Uint(_) | ty::Int(_) => fx.bcx.ins().bnot(val),
361                                 _ => unimplemented!("un op Not for {:?}", layout.ty),
362                             }
363                         }
364                         UnOp::Neg => match layout.ty.sty {
365                             ty::Int(_) => {
366                                 let clif_ty = fx.clif_type(layout.ty).unwrap();
367                                 let zero = fx.bcx.ins().iconst(clif_ty, 0);
368                                 fx.bcx.ins().isub(zero, val)
369                             }
370                             ty::Float(_) => fx.bcx.ins().fneg(val),
371                             _ => unimplemented!("un op Neg for {:?}", layout.ty),
372                         },
373                     };
374                     lval.write_cvalue(fx, CValue::by_val(res, layout));
375                 }
376                 Rvalue::Cast(CastKind::Pointer(PointerCast::ReifyFnPointer), operand, ty) => {
377                     let layout = fx.layout_of(ty);
378                     match fx
379                         .monomorphize(&operand.ty(&fx.mir.local_decls, fx.tcx))
380                         .sty
381                     {
382                         ty::FnDef(def_id, substs) => {
383                             let func_ref = fx.get_function_ref(
384                                 Instance::resolve(fx.tcx, ParamEnv::reveal_all(), def_id, substs)
385                                     .unwrap(),
386                             );
387                             let func_addr = fx.bcx.ins().func_addr(fx.pointer_type, func_ref);
388                             lval.write_cvalue(fx, CValue::by_val(func_addr, layout));
389                         }
390                         _ => bug!("Trying to ReifyFnPointer on non FnDef {:?}", ty),
391                     }
392                 }
393                 Rvalue::Cast(CastKind::Pointer(PointerCast::UnsafeFnPointer), operand, ty)
394                 | Rvalue::Cast(CastKind::Pointer(PointerCast::MutToConstPointer), operand, ty) => {
395                     let operand = trans_operand(fx, operand);
396                     let layout = fx.layout_of(ty);
397                     lval.write_cvalue(fx, operand.unchecked_cast_to(layout));
398                 }
399                 Rvalue::Cast(CastKind::Misc, operand, to_ty) => {
400                     let operand = trans_operand(fx, operand);
401                     let from_ty = operand.layout().ty;
402
403                     fn is_fat_ptr<'a, 'tcx: 'a>(fx: &FunctionCx<'a, 'tcx, impl Backend>, ty: Ty<'tcx>) -> bool {
404                         ty
405                             .builtin_deref(true)
406                             .map(|ty::TypeAndMut {ty: pointee_ty, mutbl: _ }| fx.layout_of(pointee_ty).is_unsized())
407                             .unwrap_or(false)
408                     }
409
410                     if is_fat_ptr(fx, from_ty) {
411                         if is_fat_ptr(fx, to_ty) {
412                             // fat-ptr -> fat-ptr
413                             lval.write_cvalue(fx, operand.unchecked_cast_to(dest_layout));
414                         } else {
415                             // fat-ptr -> thin-ptr
416                             let (ptr, _extra) = operand.load_scalar_pair(fx);
417                             lval.write_cvalue(fx, CValue::by_val(ptr, dest_layout))
418                         }
419                     } else if let ty::Adt(adt_def, _substs) = from_ty.sty {
420                         // enum -> discriminant value
421                         assert!(adt_def.is_enum());
422                         match to_ty.sty {
423                             ty::Uint(_) | ty::Int(_) => {},
424                             _ => unreachable!("cast adt {} -> {}", from_ty, to_ty),
425                         }
426
427                         // FIXME avoid forcing to stack
428                         let place =
429                             CPlace::for_addr(operand.force_stack(fx), operand.layout());
430                         let discr = trans_get_discriminant(fx, place, fx.layout_of(to_ty));
431                         lval.write_cvalue(fx, discr);
432                     } else {
433                         let from_clif_ty = fx.clif_type(from_ty).unwrap();
434                         let to_clif_ty = fx.clif_type(to_ty).unwrap();
435                         let from = operand.load_scalar(fx);
436
437                         let signed = match from_ty.sty {
438                             ty::Ref(..) | ty::RawPtr(..) | ty::FnPtr(..) | ty::Char | ty::Uint(..) | ty::Bool => false,
439                             ty::Int(..) => true,
440                             ty::Float(..) => false, // `signed` is unused for floats
441                             _ => panic!("{}", from_ty),
442                         };
443
444                         let res = if from_clif_ty.is_int() && to_clif_ty.is_int() {
445                             // int-like -> int-like
446                             crate::common::clif_intcast(
447                                 fx,
448                                 from,
449                                 to_clif_ty,
450                                 signed,
451                             )
452                         } else if from_clif_ty.is_int() && to_clif_ty.is_float() {
453                             // int-like -> float
454                             if signed {
455                                 fx.bcx.ins().fcvt_from_sint(to_clif_ty, from)
456                             } else {
457                                 fx.bcx.ins().fcvt_from_uint(to_clif_ty, from)
458                             }
459                         } else if from_clif_ty.is_float() && to_clif_ty.is_int() {
460                             // float -> int-like
461                             let from = operand.load_scalar(fx);
462                             if signed {
463                                 fx.bcx.ins().fcvt_to_sint_sat(to_clif_ty, from)
464                             } else {
465                                 fx.bcx.ins().fcvt_to_uint_sat(to_clif_ty, from)
466                             }
467                         } else if from_clif_ty.is_float() && to_clif_ty.is_float() {
468                             // float -> float
469                             match (from_clif_ty, to_clif_ty) {
470                                 (types::F32, types::F64) => {
471                                     fx.bcx.ins().fpromote(types::F64, from)
472                                 }
473                                 (types::F64, types::F32) => {
474                                     fx.bcx.ins().fdemote(types::F32, from)
475                                 }
476                                 _ => from,
477                             }
478                         } else {
479                             unimpl!("rval misc {:?} {:?}", from_ty, to_ty)
480                         };
481                         lval.write_cvalue(fx, CValue::by_val(res, dest_layout));
482                     }
483                 }
484                 Rvalue::Cast(CastKind::Pointer(PointerCast::ClosureFnPointer(_)), operand, _ty) => {
485                     let operand = trans_operand(fx, operand);
486                     match operand.layout().ty.sty {
487                         ty::Closure(def_id, substs) => {
488                             let instance = Instance::resolve_closure(
489                                 fx.tcx,
490                                 def_id,
491                                 substs,
492                                 ty::ClosureKind::FnOnce,
493                             );
494                             let func_ref = fx.get_function_ref(instance);
495                             let func_addr = fx.bcx.ins().func_addr(fx.pointer_type, func_ref);
496                             lval.write_cvalue(fx, CValue::by_val(func_addr, lval.layout()));
497                         }
498                         _ => {
499                             bug!("{} cannot be cast to a fn ptr", operand.layout().ty)
500                         }
501                     }
502                 }
503                 Rvalue::Cast(CastKind::Pointer(PointerCast::Unsize), operand, _ty) => {
504                     let operand = trans_operand(fx, operand);
505                     operand.unsize_value(fx, lval);
506                 }
507                 Rvalue::Discriminant(place) => {
508                     let place = trans_place(fx, place);
509                     let discr = trans_get_discriminant(fx, place, dest_layout);
510                     lval.write_cvalue(fx, discr);
511                 }
512                 Rvalue::Repeat(operand, times) => {
513                     let operand = trans_operand(fx, operand);
514                     for i in 0..*times {
515                         let index = fx.bcx.ins().iconst(fx.pointer_type, i as i64);
516                         let to = lval.place_index(fx, index);
517                         to.write_cvalue(fx, operand);
518                     }
519                 }
520                 Rvalue::Len(place) => {
521                     let place = trans_place(fx, place);
522                     let usize_layout = fx.layout_of(fx.tcx.types.usize);
523                     let len = codegen_array_len(fx, place);
524                     lval.write_cvalue(fx, CValue::by_val(len, usize_layout));
525                 }
526                 Rvalue::NullaryOp(NullOp::Box, content_ty) => {
527                     use rustc::middle::lang_items::ExchangeMallocFnLangItem;
528
529                     let usize_type = fx.clif_type(fx.tcx.types.usize).unwrap();
530                     let layout = fx.layout_of(content_ty);
531                     let llsize = fx.bcx.ins().iconst(usize_type, layout.size.bytes() as i64);
532                     let llalign = fx
533                         .bcx
534                         .ins()
535                         .iconst(usize_type, layout.align.abi.bytes() as i64);
536                     let box_layout = fx.layout_of(fx.tcx.mk_box(content_ty));
537
538                     // Allocate space:
539                     let def_id = match fx.tcx.lang_items().require(ExchangeMallocFnLangItem) {
540                         Ok(id) => id,
541                         Err(s) => {
542                             fx.tcx
543                                 .sess
544                                 .fatal(&format!("allocation of `{}` {}", box_layout.ty, s));
545                         }
546                     };
547                     let instance = ty::Instance::mono(fx.tcx, def_id);
548                     let func_ref = fx.get_function_ref(instance);
549                     let call = fx.bcx.ins().call(func_ref, &[llsize, llalign]);
550                     let ptr = fx.bcx.inst_results(call)[0];
551                     lval.write_cvalue(fx, CValue::by_val(ptr, box_layout));
552                 }
553                 Rvalue::NullaryOp(NullOp::SizeOf, ty) => {
554                     assert!(lval
555                         .layout()
556                         .ty
557                         .is_sized(fx.tcx.at(DUMMY_SP), ParamEnv::reveal_all()));
558                     let ty_size = fx.layout_of(ty).size.bytes();
559                     let val = CValue::const_val(fx, fx.tcx.types.usize, ty_size as i64);
560                     lval.write_cvalue(fx, val);
561                 }
562                 Rvalue::Aggregate(kind, operands) => match **kind {
563                     AggregateKind::Array(_ty) => {
564                         for (i, operand) in operands.into_iter().enumerate() {
565                             let operand = trans_operand(fx, operand);
566                             let index = fx.bcx.ins().iconst(fx.pointer_type, i as i64);
567                             let to = lval.place_index(fx, index);
568                             to.write_cvalue(fx, operand);
569                         }
570                     }
571                     _ => unimpl!("shouldn't exist at trans {:?}", rval),
572                 },
573             }
574         }
575         StatementKind::StorageLive(_)
576         | StatementKind::StorageDead(_)
577         | StatementKind::Nop
578         | StatementKind::FakeRead(..)
579         | StatementKind::Retag { .. }
580         | StatementKind::AscribeUserType(..) => {}
581
582         StatementKind::InlineAsm(asm) => {
583             use syntax::ast::Name;
584             let InlineAsm { asm, outputs: _, inputs: _ } = &**asm;
585             let rustc::hir::InlineAsm {
586                 asm: asm_code, // Name
587                 outputs, // Vec<Name>
588                 inputs, // Vec<Name>
589                 clobbers, // Vec<Name>
590                 volatile, // bool
591                 alignstack, // bool
592                 dialect: _, // syntax::ast::AsmDialect
593                 asm_str_style: _,
594                 ctxt: _,
595             } = asm;
596             match &*asm_code.as_str() {
597                 "cpuid" | "cpuid\n" => {
598                     assert_eq!(inputs, &[Name::intern("{eax}"), Name::intern("{ecx}")]);
599
600                     assert_eq!(outputs.len(), 4);
601                     for (i, c) in (&["={eax}", "={ebx}", "={ecx}", "={edx}"]).iter().enumerate() {
602                         assert_eq!(&outputs[i].constraint.as_str(), c);
603                         assert!(!outputs[i].is_rw);
604                         assert!(!outputs[i].is_indirect);
605                     }
606
607                     assert_eq!(clobbers, &[Name::intern("rbx")]);
608
609                     assert!(!volatile);
610                     assert!(!alignstack);
611
612                     crate::trap::trap_unimplemented(fx, "__cpuid_count arch intrinsic is not supported");
613                 }
614                 "xgetbv" => {
615                     assert_eq!(inputs, &[Name::intern("{ecx}")]);
616
617                     assert_eq!(outputs.len(), 2);
618                     for (i, c) in (&["={eax}", "={edx}"]).iter().enumerate() {
619                         assert_eq!(&outputs[i].constraint.as_str(), c);
620                         assert!(!outputs[i].is_rw);
621                         assert!(!outputs[i].is_indirect);
622                     }
623
624                     assert_eq!(clobbers, &[]);
625
626                     assert!(!volatile);
627                     assert!(!alignstack);
628
629                     crate::trap::trap_unimplemented(fx, "_xgetbv arch intrinsic is not supported");
630                 }
631                 _ if fx.tcx.symbol_name(fx.instance).as_str() == "__rust_probestack" => {
632                     crate::trap::trap_unimplemented(fx, "__rust_probestack is not supported");
633                 }
634                 _ => unimpl!("Inline assembly is not supported"),
635             }
636         }
637     }
638 }
639
640 fn codegen_array_len<'a, 'tcx: 'a>(
641     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
642     place: CPlace<'tcx>,
643 ) -> Value {
644     match place.layout().ty.sty {
645         ty::Array(_elem_ty, len) => {
646             let len = crate::constant::force_eval_const(fx, len).unwrap_usize(fx.tcx) as i64;
647             fx.bcx.ins().iconst(fx.pointer_type, len)
648         }
649         ty::Slice(_elem_ty) => place
650             .to_addr_maybe_unsized(fx)
651             .1
652             .expect("Length metadata for slice place"),
653         _ => bug!("Rvalue::Len({:?})", place),
654     }
655 }
656
657 pub fn trans_get_discriminant<'a, 'tcx: 'a>(
658     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
659     place: CPlace<'tcx>,
660     dest_layout: TyLayout<'tcx>,
661 ) -> CValue<'tcx> {
662     let layout = place.layout();
663
664     if layout.abi == layout::Abi::Uninhabited {
665         return trap_unreachable_ret_value(fx, dest_layout, "[panic] Tried to get discriminant for uninhabited type.");
666     }
667
668     let (discr_scalar, discr_index, discr_kind) = match &layout.variants {
669         layout::Variants::Single { index } => {
670             let discr_val = layout
671                 .ty
672                 .ty_adt_def()
673                 .map_or(index.as_u32() as u128, |def| {
674                     def.discriminant_for_variant(fx.tcx, *index).val
675                 });
676             return CValue::const_val(fx, dest_layout.ty, discr_val as u64 as i64);
677         }
678         layout::Variants::Multiple { discr, discr_index, discr_kind, variants: _ } => {
679             (discr, *discr_index, discr_kind)
680         }
681     };
682
683     let discr = place.place_field(fx, mir::Field::new(discr_index)).to_cvalue(fx);
684     let discr_ty = discr.layout().ty;
685     let lldiscr = discr.load_scalar(fx);
686     match discr_kind {
687         layout::DiscriminantKind::Tag => {
688             let signed = match discr_scalar.value {
689                 layout::Int(_, signed) => signed,
690                 _ => false,
691             };
692             let val = clif_intcast(fx, lldiscr, fx.clif_type(dest_layout.ty).unwrap(), signed);
693             return CValue::by_val(val, dest_layout);
694         }
695         layout::DiscriminantKind::Niche {
696             dataful_variant,
697             ref niche_variants,
698             niche_start,
699         } => {
700             let niche_llty = fx.clif_type(discr_ty).unwrap();
701             let dest_clif_ty = fx.clif_type(dest_layout.ty).unwrap();
702             if niche_variants.start() == niche_variants.end() {
703                 let b = fx
704                     .bcx
705                     .ins()
706                     .icmp_imm(IntCC::Equal, lldiscr, *niche_start as u64 as i64);
707                 let if_true = fx
708                     .bcx
709                     .ins()
710                     .iconst(dest_clif_ty, niche_variants.start().as_u32() as i64);
711                 let if_false = fx
712                     .bcx
713                     .ins()
714                     .iconst(dest_clif_ty, dataful_variant.as_u32() as i64);
715                 let val = fx.bcx.ins().select(b, if_true, if_false);
716                 return CValue::by_val(val, dest_layout);
717             } else {
718                 // Rebase from niche values to discriminant values.
719                 let delta = niche_start.wrapping_sub(niche_variants.start().as_u32() as u128);
720                 let delta = fx.bcx.ins().iconst(niche_llty, delta as u64 as i64);
721                 let lldiscr = fx.bcx.ins().isub(lldiscr, delta);
722                 let b = fx.bcx.ins().icmp_imm(
723                     IntCC::UnsignedLessThanOrEqual,
724                     lldiscr,
725                     niche_variants.end().as_u32() as i64,
726                 );
727                 let if_true =
728                     clif_intcast(fx, lldiscr, fx.clif_type(dest_layout.ty).unwrap(), false);
729                 let if_false = fx
730                     .bcx
731                     .ins()
732                     .iconst(dest_clif_ty, dataful_variant.as_u32() as i64);
733                 let val = fx.bcx.ins().select(b, if_true, if_false);
734                 return CValue::by_val(val, dest_layout);
735             }
736         }
737     }
738 }
739
740 macro_rules! binop_match {
741     (@single $fx:expr, $bug_fmt:expr, $var:expr, $signed:expr, $lhs:expr, $rhs:expr, $ret_ty:expr, bug) => {
742         bug!("binop {} on {} lhs: {:?} rhs: {:?}", stringify!($var), $bug_fmt, $lhs, $rhs)
743     };
744     (@single $fx:expr, $bug_fmt:expr, $var:expr, $signed:expr, $lhs:expr, $rhs:expr, $ret_ty:expr, icmp($cc:ident)) => {{
745         assert_eq!($fx.tcx.types.bool, $ret_ty);
746         let ret_layout = $fx.layout_of($ret_ty);
747
748         let b = $fx.bcx.ins().icmp(IntCC::$cc, $lhs, $rhs);
749         CValue::by_val($fx.bcx.ins().bint(types::I8, b), ret_layout)
750     }};
751     (@single $fx:expr, $bug_fmt:expr, $var:expr, $signed:expr, $lhs:expr, $rhs:expr, $ret_ty:expr, fcmp($cc:ident)) => {{
752         assert_eq!($fx.tcx.types.bool, $ret_ty);
753         let ret_layout = $fx.layout_of($ret_ty);
754         let b = $fx.bcx.ins().fcmp(FloatCC::$cc, $lhs, $rhs);
755         CValue::by_val($fx.bcx.ins().bint(types::I8, b), ret_layout)
756     }};
757     (@single $fx:expr, $bug_fmt:expr, $var:expr, $signed:expr, $lhs:expr, $rhs:expr, $ret_ty:expr, custom(|| $body:expr)) => {{
758         $body
759     }};
760     (@single $fx:expr, $bug_fmt:expr, $var:expr, $signed:expr, $lhs:expr, $rhs:expr, $ret_ty:expr, $name:ident) => {{
761         let ret_layout = $fx.layout_of($ret_ty);
762         CValue::by_val($fx.bcx.ins().$name($lhs, $rhs), ret_layout)
763     }};
764     (
765         $fx:expr, $bin_op:expr, $signed:expr, $lhs:expr, $rhs:expr, $ret_ty:expr, $bug_fmt:expr;
766         $(
767             $var:ident ($sign:pat) $name:tt $( ( $($next:tt)* ) )? ;
768         )*
769     ) => {{
770         let lhs = $lhs.load_scalar($fx);
771         let rhs = $rhs.load_scalar($fx);
772         match ($bin_op, $signed) {
773             $(
774                 (BinOp::$var, $sign) => binop_match!(@single $fx, $bug_fmt, $var, $signed, lhs, rhs, $ret_ty, $name $( ( $($next)* ) )?),
775             )*
776         }
777     }}
778 }
779
780 fn trans_bool_binop<'a, 'tcx: 'a>(
781     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
782     bin_op: BinOp,
783     lhs: CValue<'tcx>,
784     rhs: CValue<'tcx>,
785 ) -> CValue<'tcx> {
786     let res = binop_match! {
787         fx, bin_op, false, lhs, rhs, fx.tcx.types.bool, "bool";
788         Add (_) bug;
789         Sub (_) bug;
790         Mul (_) bug;
791         Div (_) bug;
792         Rem (_) bug;
793         BitXor (_) bxor;
794         BitAnd (_) band;
795         BitOr (_) bor;
796         Shl (_) bug;
797         Shr (_) bug;
798
799         Eq (_) icmp(Equal);
800         Lt (_) icmp(UnsignedLessThan);
801         Le (_) icmp(UnsignedLessThanOrEqual);
802         Ne (_) icmp(NotEqual);
803         Ge (_) icmp(UnsignedGreaterThanOrEqual);
804         Gt (_) icmp(UnsignedGreaterThan);
805
806         Offset (_) bug;
807     };
808
809     res
810 }
811
812 pub fn trans_int_binop<'a, 'tcx: 'a>(
813     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
814     bin_op: BinOp,
815     lhs: CValue<'tcx>,
816     rhs: CValue<'tcx>,
817     out_ty: Ty<'tcx>,
818     signed: bool,
819 ) -> CValue<'tcx> {
820     if bin_op != BinOp::Shl && bin_op != BinOp::Shr {
821         assert_eq!(
822             lhs.layout().ty,
823             rhs.layout().ty,
824             "int binop requires lhs and rhs of same type"
825         );
826     }
827
828     if lhs.layout().ty == fx.tcx.types.u128 || lhs.layout().ty == fx.tcx.types.i128 {
829         return match (bin_op, signed) {
830             _ => {
831                 let layout = fx.layout_of(out_ty);
832                 let a = fx.bcx.ins().iconst(types::I64, 42);
833                 let b = fx.bcx.ins().iconst(types::I64, 0);
834                 let val = fx.bcx.ins().iconcat(a, b);
835                 CValue::by_val(val, layout)
836             }
837         }
838     }
839
840     binop_match! {
841         fx, bin_op, signed, lhs, rhs, out_ty, "int/uint";
842         Add (_) iadd;
843         Sub (_) isub;
844         Mul (_) imul;
845         Div (false) udiv;
846         Div (true) sdiv;
847         Rem (false) urem;
848         Rem (true) srem;
849         BitXor (_) bxor;
850         BitAnd (_) band;
851         BitOr (_) bor;
852         Shl (_) ishl;
853         Shr (false) ushr;
854         Shr (true) sshr;
855
856         Eq (_) icmp(Equal);
857         Lt (false) icmp(UnsignedLessThan);
858         Lt (true) icmp(SignedLessThan);
859         Le (false) icmp(UnsignedLessThanOrEqual);
860         Le (true) icmp(SignedLessThanOrEqual);
861         Ne (_) icmp(NotEqual);
862         Ge (false) icmp(UnsignedGreaterThanOrEqual);
863         Ge (true) icmp(SignedGreaterThanOrEqual);
864         Gt (false) icmp(UnsignedGreaterThan);
865         Gt (true) icmp(SignedGreaterThan);
866
867         Offset (_) bug;
868     }
869 }
870
871 pub fn trans_checked_int_binop<'a, 'tcx: 'a>(
872     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
873     bin_op: BinOp,
874     in_lhs: CValue<'tcx>,
875     in_rhs: CValue<'tcx>,
876     out_ty: Ty<'tcx>,
877     signed: bool,
878 ) -> CValue<'tcx> {
879     if bin_op != BinOp::Shl && bin_op != BinOp::Shr {
880         assert_eq!(
881             in_lhs.layout().ty,
882             in_rhs.layout().ty,
883             "checked int binop requires lhs and rhs of same type"
884         );
885     }
886
887     let lhs = in_lhs.load_scalar(fx);
888     let rhs = in_rhs.load_scalar(fx);
889     let (res, has_overflow) = if in_lhs.layout().ty == fx.tcx.types.u128 || in_lhs.layout().ty == fx.tcx.types.i128 {
890         match (bin_op, signed) {
891             _ => {
892                 let a = fx.bcx.ins().iconst(types::I64, 42);
893                 let b = fx.bcx.ins().iconst(types::I64, 0);
894                 (fx.bcx.ins().iconcat(a, b), fx.bcx.ins().bconst(types::B1, false))
895             }
896         }
897     } else {
898         match bin_op {
899             BinOp::Add => {
900                 /*let (val, c_out) = fx.bcx.ins().iadd_cout(lhs, rhs);
901                 (val, c_out)*/
902                 // FIXME(CraneStation/cranelift#849) legalize iadd_cout for i8 and i16
903                 let val = fx.bcx.ins().iadd(lhs, rhs);
904                 let has_overflow = if !signed {
905                     fx.bcx.ins().icmp(IntCC::UnsignedLessThan, val, lhs)
906                 } else {
907                     let rhs_is_negative = fx.bcx.ins().icmp_imm(IntCC::SignedLessThan, rhs, 0);
908                     let slt = fx.bcx.ins().icmp(IntCC::SignedLessThan, val, lhs);
909                     fx.bcx.ins().bxor(rhs_is_negative, slt)
910                 };
911                 (val, has_overflow)
912             }
913             BinOp::Sub => {
914                 /*let (val, b_out) = fx.bcx.ins().isub_bout(lhs, rhs);
915                 (val, b_out)*/
916                 // FIXME(CraneStation/cranelift#849) legalize isub_bout for i8 and i16
917                 let val = fx.bcx.ins().isub(lhs, rhs);
918                 let has_overflow = if !signed {
919                     fx.bcx.ins().icmp(IntCC::UnsignedGreaterThan, val, lhs)
920                 } else {
921                     let rhs_is_negative = fx.bcx.ins().icmp_imm(IntCC::SignedLessThan, rhs, 0);
922                     let sgt = fx.bcx.ins().icmp(IntCC::SignedGreaterThan, val, lhs);
923                     fx.bcx.ins().bxor(rhs_is_negative, sgt)
924                 };
925                 (val, has_overflow)
926             }
927             BinOp::Mul => {
928                 let val = fx.bcx.ins().imul(lhs, rhs);
929                 /*let val_hi = if !signed {
930                     fx.bcx.ins().umulhi(lhs, rhs)
931                 } else {
932                     fx.bcx.ins().smulhi(lhs, rhs)
933                 };
934                 let has_overflow = fx.bcx.ins().icmp_imm(IntCC::NotEqual, val_hi, 0);*/
935                 // TODO: check for overflow
936                 let has_overflow = fx.bcx.ins().bconst(types::B1, false);
937                 (val, has_overflow)
938             }
939             BinOp::Shl => {
940                 let val = fx.bcx.ins().ishl(lhs, rhs);
941                 // TODO: check for overflow
942                 let has_overflow = fx.bcx.ins().bconst(types::B1, false);
943                 (val, has_overflow)
944             }
945             BinOp::Shr => {
946                 let val = if !signed {
947                     fx.bcx.ins().ushr(lhs, rhs)
948                 } else {
949                     fx.bcx.ins().sshr(lhs, rhs)
950                 };
951                 // TODO: check for overflow
952                 let has_overflow = fx.bcx.ins().bconst(types::B1, false);
953                 (val, has_overflow)
954             }
955             _ => bug!(
956                 "binop {:?} on checked int/uint lhs: {:?} rhs: {:?}",
957                 bin_op,
958                 in_lhs,
959                 in_rhs
960             ),
961         }
962     };
963
964     let has_overflow = fx.bcx.ins().bint(types::I8, has_overflow);
965     let out_place = CPlace::new_stack_slot(fx, out_ty);
966     let out_layout = out_place.layout();
967     out_place.write_cvalue(fx, CValue::by_val_pair(res, has_overflow, out_layout));
968
969     out_place.to_cvalue(fx)
970 }
971
972 fn trans_float_binop<'a, 'tcx: 'a>(
973     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
974     bin_op: BinOp,
975     lhs: CValue<'tcx>,
976     rhs: CValue<'tcx>,
977     ty: Ty<'tcx>,
978 ) -> CValue<'tcx> {
979     let res = binop_match! {
980         fx, bin_op, false, lhs, rhs, ty, "float";
981         Add (_) fadd;
982         Sub (_) fsub;
983         Mul (_) fmul;
984         Div (_) fdiv;
985         Rem (_) custom(|| {
986             assert_eq!(lhs.layout().ty, ty);
987             assert_eq!(rhs.layout().ty, ty);
988             match ty.sty {
989                 ty::Float(FloatTy::F32) => fx.easy_call("fmodf", &[lhs, rhs], ty),
990                 ty::Float(FloatTy::F64) => fx.easy_call("fmod", &[lhs, rhs], ty),
991                 _ => bug!(),
992             }
993         });
994         BitXor (_) bxor;
995         BitAnd (_) band;
996         BitOr (_) bor;
997         Shl (_) bug;
998         Shr (_) bug;
999
1000         Eq (_) fcmp(Equal);
1001         Lt (_) fcmp(LessThan);
1002         Le (_) fcmp(LessThanOrEqual);
1003         Ne (_) fcmp(NotEqual);
1004         Ge (_) fcmp(GreaterThanOrEqual);
1005         Gt (_) fcmp(GreaterThan);
1006
1007         Offset (_) bug;
1008     };
1009
1010     res
1011 }
1012
1013 fn trans_char_binop<'a, 'tcx: 'a>(
1014     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
1015     bin_op: BinOp,
1016     lhs: CValue<'tcx>,
1017     rhs: CValue<'tcx>,
1018     ty: Ty<'tcx>,
1019 ) -> CValue<'tcx> {
1020     let res = binop_match! {
1021         fx, bin_op, false, lhs, rhs, ty, "char";
1022         Add (_) bug;
1023         Sub (_) bug;
1024         Mul (_) bug;
1025         Div (_) bug;
1026         Rem (_) bug;
1027         BitXor (_) bug;
1028         BitAnd (_) bug;
1029         BitOr (_) bug;
1030         Shl (_) bug;
1031         Shr (_) bug;
1032
1033         Eq (_) icmp(Equal);
1034         Lt (_) icmp(UnsignedLessThan);
1035         Le (_) icmp(UnsignedLessThanOrEqual);
1036         Ne (_) icmp(NotEqual);
1037         Ge (_) icmp(UnsignedGreaterThanOrEqual);
1038         Gt (_) icmp(UnsignedGreaterThan);
1039
1040         Offset (_) bug;
1041     };
1042
1043     res
1044 }
1045
1046 fn trans_ptr_binop<'a, 'tcx: 'a>(
1047     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
1048     bin_op: BinOp,
1049     lhs: CValue<'tcx>,
1050     rhs: CValue<'tcx>,
1051     ret_ty: Ty<'tcx>,
1052 ) -> CValue<'tcx> {
1053     let not_fat = match lhs.layout().ty.sty {
1054         ty::RawPtr(TypeAndMut { ty, mutbl: _ }) => {
1055             ty.is_sized(fx.tcx.at(DUMMY_SP), ParamEnv::reveal_all())
1056         }
1057         ty::FnPtr(..) => true,
1058         _ => bug!("trans_ptr_binop on non ptr"),
1059     };
1060     if not_fat {
1061         if let BinOp::Offset = bin_op {
1062             let (base, offset) = (lhs, rhs.load_scalar(fx));
1063             let pointee_ty = base.layout().ty.builtin_deref(true).unwrap().ty;
1064             let pointee_size = fx.layout_of(pointee_ty).size.bytes();
1065             let ptr_diff = fx.bcx.ins().imul_imm(offset, pointee_size as i64);
1066             let base_val = base.load_scalar(fx);
1067             let res = fx.bcx.ins().iadd(base_val, ptr_diff);
1068             return CValue::by_val(res, base.layout());
1069         }
1070
1071         binop_match! {
1072             fx, bin_op, false, lhs, rhs, ret_ty, "ptr";
1073             Add (_) bug;
1074             Sub (_) bug;
1075             Mul (_) bug;
1076             Div (_) bug;
1077             Rem (_) bug;
1078             BitXor (_) bug;
1079             BitAnd (_) bug;
1080             BitOr (_) bug;
1081             Shl (_) bug;
1082             Shr (_) bug;
1083
1084             Eq (_) icmp(Equal);
1085             Lt (_) icmp(UnsignedLessThan);
1086             Le (_) icmp(UnsignedLessThanOrEqual);
1087             Ne (_) icmp(NotEqual);
1088             Ge (_) icmp(UnsignedGreaterThanOrEqual);
1089             Gt (_) icmp(UnsignedGreaterThan);
1090
1091             Offset (_) bug; // Handled above
1092         }
1093     } else {
1094         let (lhs_ptr, lhs_extra) = lhs.load_scalar_pair(fx);
1095         let (rhs_ptr, rhs_extra) = rhs.load_scalar_pair(fx);
1096
1097         let res = match bin_op {
1098             BinOp::Eq => {
1099                 let ptr_eq = fx.bcx.ins().icmp(IntCC::Equal, lhs_ptr, rhs_ptr);
1100                 let extra_eq = fx.bcx.ins().icmp(IntCC::Equal, lhs_extra, rhs_extra);
1101                 fx.bcx.ins().band(ptr_eq, extra_eq)
1102             }
1103             BinOp::Ne => {
1104                 let ptr_ne = fx.bcx.ins().icmp(IntCC::NotEqual, lhs_ptr, rhs_ptr);
1105                 let extra_ne = fx.bcx.ins().icmp(IntCC::NotEqual, lhs_extra, rhs_extra);
1106                 fx.bcx.ins().bor(ptr_ne, extra_ne)
1107             }
1108             BinOp::Lt | BinOp::Le | BinOp::Ge | BinOp::Gt => {
1109                 let ptr_eq = fx.bcx.ins().icmp(IntCC::Equal, lhs_ptr, rhs_ptr);
1110
1111                 let ptr_cmp = fx.bcx.ins().icmp(match bin_op {
1112                     BinOp::Lt => IntCC::UnsignedLessThan,
1113                     BinOp::Le => IntCC::UnsignedLessThanOrEqual,
1114                     BinOp::Ge => IntCC::UnsignedGreaterThanOrEqual,
1115                     BinOp::Gt => IntCC::UnsignedGreaterThan,
1116                     _ => unreachable!(),
1117                 }, lhs_ptr, rhs_ptr);
1118
1119                 let extra_cmp = fx.bcx.ins().icmp(match bin_op {
1120                     BinOp::Lt => IntCC::UnsignedLessThan,
1121                     BinOp::Le => IntCC::UnsignedLessThanOrEqual,
1122                     BinOp::Ge => IntCC::UnsignedGreaterThanOrEqual,
1123                     BinOp::Gt => IntCC::UnsignedGreaterThan,
1124                     _ => unreachable!(),
1125                 }, lhs_extra, rhs_extra);
1126
1127                 fx.bcx.ins().select(ptr_eq, extra_cmp, ptr_cmp)
1128             }
1129             _ => panic!("bin_op {:?} on ptr", bin_op),
1130         };
1131
1132         assert_eq!(fx.tcx.types.bool, ret_ty);
1133         let ret_layout = fx.layout_of(ret_ty);
1134         CValue::by_val(fx.bcx.ins().bint(types::I8, res), ret_layout)
1135     }
1136 }
1137
1138 pub fn trans_place<'a, 'tcx: 'a>(
1139     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
1140     place: &Place<'tcx>,
1141 ) -> CPlace<'tcx> {
1142     let base = match &place.base {
1143         PlaceBase::Local(local) => fx.get_local_place(*local),
1144         PlaceBase::Static(static_) => match static_.kind {
1145             StaticKind::Static(def_id) => {
1146                 crate::constant::codegen_static_ref(fx, def_id, static_.ty)
1147             }
1148             StaticKind::Promoted(promoted) => {
1149                 crate::constant::trans_promoted(fx, promoted, static_.ty)
1150             }
1151         }
1152     };
1153
1154     trans_place_projection(fx, base, &place.projection)
1155 }
1156
1157 pub fn trans_place_projection<'a, 'tcx: 'a>(
1158     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
1159     base: CPlace<'tcx>,
1160     projection: &Option<Box<Projection<'tcx>>>,
1161 ) -> CPlace<'tcx> {
1162     let projection = if let Some(projection) = projection {
1163         projection
1164     } else {
1165         return base;
1166     };
1167
1168     let base = trans_place_projection(fx, base, &projection.base);
1169
1170     match projection.elem {
1171         ProjectionElem::Deref => base.place_deref(fx),
1172         ProjectionElem::Field(field, _ty) => base.place_field(fx, field),
1173         ProjectionElem::Index(local) => {
1174             let index = fx.get_local_place(local).to_cvalue(fx).load_scalar(fx);
1175             base.place_index(fx, index)
1176         }
1177         ProjectionElem::ConstantIndex {
1178             offset,
1179             min_length: _,
1180             from_end,
1181         } => {
1182             let index = if !from_end {
1183                 fx.bcx.ins().iconst(fx.pointer_type, offset as i64)
1184             } else {
1185                 let len = codegen_array_len(fx, base);
1186                 fx.bcx.ins().iadd_imm(len, -(offset as i64))
1187             };
1188             base.place_index(fx, index)
1189         }
1190         ProjectionElem::Subslice { from, to } => {
1191             // These indices are generated by slice patterns.
1192             // slice[from:-to] in Python terms.
1193
1194             match base.layout().ty.sty {
1195                 ty::Array(elem_ty, len) => {
1196                     let elem_layout = fx.layout_of(elem_ty);
1197                     let ptr = base.to_addr(fx);
1198                     let len = crate::constant::force_eval_const(fx, len).unwrap_usize(fx.tcx);
1199                     CPlace::for_addr(
1200                         fx.bcx.ins().iadd_imm(ptr, elem_layout.size.bytes() as i64 * from as i64),
1201                         fx.layout_of(fx.tcx.mk_array(elem_ty, len - from as u64 - to as u64)),
1202                     )
1203                 }
1204                 ty::Slice(elem_ty) => {
1205                     let elem_layout = fx.layout_of(elem_ty);
1206                     let (ptr, len) = base.to_addr_maybe_unsized(fx);
1207                     let len = len.unwrap();
1208                     CPlace::for_addr_with_extra(
1209                         fx.bcx.ins().iadd_imm(ptr, elem_layout.size.bytes() as i64 * from as i64),
1210                         fx.bcx.ins().iadd_imm(len, -(from as i64 + to as i64)),
1211                         base.layout(),
1212                     )
1213                 }
1214                 _ => unreachable!(),
1215             }
1216         }
1217         ProjectionElem::Downcast(_adt_def, variant) => base.downcast_variant(fx, variant),
1218     }
1219 }
1220
1221 pub fn trans_operand<'a, 'tcx>(
1222     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
1223     operand: &Operand<'tcx>,
1224 ) -> CValue<'tcx> {
1225     match operand {
1226         Operand::Move(place) | Operand::Copy(place) => {
1227             let cplace = trans_place(fx, place);
1228             cplace.to_cvalue(fx)
1229         }
1230         Operand::Constant(const_) => crate::constant::trans_constant(fx, const_),
1231     }
1232 }