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