]> git.lizzy.rs Git - rust.git/blob - src/base.rs
Fix assert_assignable for array types
[rust.git] / src / base.rs
1 //! Codegen of a single function
2
3 use rustc_ast::InlineAsmOptions;
4 use rustc_index::vec::IndexVec;
5 use rustc_middle::ty::adjustment::PointerCast;
6 use rustc_middle::ty::layout::FnAbiOf;
7 use rustc_middle::ty::print::with_no_trimmed_paths;
8
9 use indexmap::IndexSet;
10
11 use crate::constant::ConstantCx;
12 use crate::prelude::*;
13 use crate::pretty_clif::CommentWriter;
14
15 pub(crate) fn codegen_fn<'tcx>(
16     cx: &mut crate::CodegenCx<'tcx>,
17     module: &mut dyn Module,
18     instance: Instance<'tcx>,
19 ) {
20     let tcx = cx.tcx;
21
22     let _inst_guard =
23         crate::PrintOnPanic(|| format!("{:?} {}", instance, tcx.symbol_name(instance).name));
24     debug_assert!(!instance.substs.needs_infer());
25
26     let mir = tcx.instance_mir(instance.def);
27     let _mir_guard = crate::PrintOnPanic(|| {
28         let mut buf = Vec::new();
29         with_no_trimmed_paths!({
30             rustc_middle::mir::pretty::write_mir_fn(tcx, mir, &mut |_, _| Ok(()), &mut buf)
31                 .unwrap();
32         });
33         String::from_utf8_lossy(&buf).into_owned()
34     });
35
36     // Declare function
37     let symbol_name = tcx.symbol_name(instance);
38     let sig = get_function_sig(tcx, module.isa().triple(), instance);
39     let func_id = module.declare_function(symbol_name.name, Linkage::Local, &sig).unwrap();
40
41     cx.cached_context.clear();
42
43     // Make the FunctionBuilder
44     let mut func_ctx = FunctionBuilderContext::new();
45     let mut func = std::mem::replace(&mut cx.cached_context.func, Function::new());
46     func.name = ExternalName::user(0, func_id.as_u32());
47     func.signature = sig;
48     func.collect_debug_info();
49
50     let mut bcx = FunctionBuilder::new(&mut func, &mut func_ctx);
51
52     // Predefine blocks
53     let start_block = bcx.create_block();
54     let block_map: IndexVec<BasicBlock, Block> =
55         (0..mir.basic_blocks().len()).map(|_| bcx.create_block()).collect();
56
57     // Make FunctionCx
58     let target_config = module.target_config();
59     let pointer_type = target_config.pointer_type();
60     let clif_comments = crate::pretty_clif::CommentWriter::new(tcx, instance);
61
62     let mut fx = FunctionCx {
63         cx,
64         module,
65         tcx,
66         target_config,
67         pointer_type,
68         constants_cx: ConstantCx::new(),
69
70         instance,
71         symbol_name,
72         mir,
73         fn_abi: Some(RevealAllLayoutCx(tcx).fn_abi_of_instance(instance, ty::List::empty())),
74
75         bcx,
76         block_map,
77         local_map: IndexVec::with_capacity(mir.local_decls.len()),
78         caller_location: None, // set by `codegen_fn_prelude`
79
80         clif_comments,
81         source_info_set: indexmap::IndexSet::new(),
82         next_ssa_var: 0,
83     };
84
85     let arg_uninhabited = fx
86         .mir
87         .args_iter()
88         .any(|arg| fx.layout_of(fx.monomorphize(fx.mir.local_decls[arg].ty)).abi.is_uninhabited());
89
90     if !crate::constant::check_constants(&mut fx) {
91         fx.bcx.append_block_params_for_function_params(fx.block_map[START_BLOCK]);
92         fx.bcx.switch_to_block(fx.block_map[START_BLOCK]);
93         crate::trap::trap_unreachable(&mut fx, "compilation should have been aborted");
94     } else if arg_uninhabited {
95         fx.bcx.append_block_params_for_function_params(fx.block_map[START_BLOCK]);
96         fx.bcx.switch_to_block(fx.block_map[START_BLOCK]);
97         fx.bcx.ins().trap(TrapCode::UnreachableCodeReached);
98     } else {
99         tcx.sess.time("codegen clif ir", || {
100             tcx.sess
101                 .time("codegen prelude", || crate::abi::codegen_fn_prelude(&mut fx, start_block));
102             codegen_fn_content(&mut fx);
103         });
104     }
105
106     // Recover all necessary data from fx, before accessing func will prevent future access to it.
107     let instance = fx.instance;
108     let clif_comments = fx.clif_comments;
109     let source_info_set = fx.source_info_set;
110     let local_map = fx.local_map;
111
112     fx.constants_cx.finalize(fx.tcx, &mut *fx.module);
113
114     crate::pretty_clif::write_clif_file(
115         tcx,
116         "unopt",
117         module.isa(),
118         instance,
119         &func,
120         &clif_comments,
121     );
122
123     // Verify function
124     verify_func(tcx, &clif_comments, &func);
125
126     compile_fn(
127         cx,
128         module,
129         instance,
130         symbol_name.name,
131         func_id,
132         func,
133         clif_comments,
134         source_info_set,
135         local_map,
136     );
137 }
138
139 fn compile_fn<'tcx>(
140     cx: &mut crate::CodegenCx<'tcx>,
141     module: &mut dyn Module,
142     instance: Instance<'tcx>,
143     symbol_name: &str,
144     func_id: FuncId,
145     func: Function,
146     mut clif_comments: CommentWriter,
147     source_info_set: IndexSet<SourceInfo>,
148     local_map: IndexVec<mir::Local, CPlace<'tcx>>,
149 ) {
150     let tcx = cx.tcx;
151
152     // Store function in context
153     let context = &mut cx.cached_context;
154     context.clear();
155     context.func = func;
156
157     // If the return block is not reachable, then the SSA builder may have inserted an `iconst.i128`
158     // instruction, which doesn't have an encoding.
159     context.compute_cfg();
160     context.compute_domtree();
161     context.eliminate_unreachable_code(module.isa()).unwrap();
162     context.dce(module.isa()).unwrap();
163     // Some Cranelift optimizations expect the domtree to not yet be computed and as such don't
164     // invalidate it when it would change.
165     context.domtree.clear();
166
167     // Perform rust specific optimizations
168     tcx.sess.time("optimize clif ir", || {
169         crate::optimize::optimize_function(
170             tcx,
171             module.isa(),
172             instance,
173             context,
174             &mut clif_comments,
175         );
176     });
177
178     // Define function
179     tcx.sess.time("define function", || {
180         context.want_disasm = crate::pretty_clif::should_write_ir(tcx);
181         module.define_function(func_id, context).unwrap()
182     });
183
184     // Write optimized function to file for debugging
185     crate::pretty_clif::write_clif_file(
186         tcx,
187         "opt",
188         module.isa(),
189         instance,
190         &context.func,
191         &clif_comments,
192     );
193
194     if let Some(disasm) = &context.mach_compile_result.as_ref().unwrap().disasm {
195         crate::pretty_clif::write_ir_file(
196             tcx,
197             || format!("{}.vcode", tcx.symbol_name(instance).name),
198             |file| file.write_all(disasm.as_bytes()),
199         )
200     }
201
202     // Define debuginfo for function
203     let isa = module.isa();
204     let debug_context = &mut cx.debug_context;
205     let unwind_context = &mut cx.unwind_context;
206     tcx.sess.time("generate debug info", || {
207         if let Some(debug_context) = debug_context {
208             debug_context.define_function(
209                 instance,
210                 func_id,
211                 symbol_name,
212                 isa,
213                 context,
214                 &source_info_set,
215                 local_map,
216             );
217         }
218         unwind_context.add_function(func_id, &context, isa);
219     });
220 }
221
222 pub(crate) fn verify_func(
223     tcx: TyCtxt<'_>,
224     writer: &crate::pretty_clif::CommentWriter,
225     func: &Function,
226 ) {
227     tcx.sess.time("verify clif ir", || {
228         let flags = cranelift_codegen::settings::Flags::new(cranelift_codegen::settings::builder());
229         match cranelift_codegen::verify_function(&func, &flags) {
230             Ok(_) => {}
231             Err(err) => {
232                 tcx.sess.err(&format!("{:?}", err));
233                 let pretty_error = cranelift_codegen::print_errors::pretty_verifier_error(
234                     &func,
235                     Some(Box::new(writer)),
236                     err,
237                 );
238                 tcx.sess.fatal(&format!("cranelift verify error:\n{}", pretty_error));
239             }
240         }
241     });
242 }
243
244 fn codegen_fn_content(fx: &mut FunctionCx<'_, '_, '_>) {
245     for (bb, bb_data) in fx.mir.basic_blocks().iter_enumerated() {
246         let block = fx.get_block(bb);
247         fx.bcx.switch_to_block(block);
248
249         if bb_data.is_cleanup {
250             // Unwinding after panicking is not supported
251             continue;
252
253             // FIXME Once unwinding is supported and Cranelift supports marking blocks as cold, do
254             // so for cleanup blocks.
255         }
256
257         fx.bcx.ins().nop();
258         for stmt in &bb_data.statements {
259             fx.set_debug_loc(stmt.source_info);
260             codegen_stmt(fx, block, stmt);
261         }
262
263         if fx.clif_comments.enabled() {
264             let mut terminator_head = "\n".to_string();
265             with_no_trimmed_paths!({
266                 bb_data.terminator().kind.fmt_head(&mut terminator_head).unwrap();
267             });
268             let inst = fx.bcx.func.layout.last_inst(block).unwrap();
269             fx.add_comment(inst, terminator_head);
270         }
271
272         let source_info = bb_data.terminator().source_info;
273         fx.set_debug_loc(source_info);
274
275         match &bb_data.terminator().kind {
276             TerminatorKind::Goto { target } => {
277                 if let TerminatorKind::Return = fx.mir[*target].terminator().kind {
278                     let mut can_immediately_return = true;
279                     for stmt in &fx.mir[*target].statements {
280                         if let StatementKind::StorageDead(_) = stmt.kind {
281                         } else {
282                             // FIXME Can sometimes happen, see rust-lang/rust#70531
283                             can_immediately_return = false;
284                             break;
285                         }
286                     }
287
288                     if can_immediately_return {
289                         crate::abi::codegen_return(fx);
290                         continue;
291                     }
292                 }
293
294                 let block = fx.get_block(*target);
295                 fx.bcx.ins().jump(block, &[]);
296             }
297             TerminatorKind::Return => {
298                 crate::abi::codegen_return(fx);
299             }
300             TerminatorKind::Assert { cond, expected, msg, target, cleanup: _ } => {
301                 if !fx.tcx.sess.overflow_checks() {
302                     if let mir::AssertKind::OverflowNeg(_) = *msg {
303                         let target = fx.get_block(*target);
304                         fx.bcx.ins().jump(target, &[]);
305                         continue;
306                     }
307                 }
308                 let cond = codegen_operand(fx, cond).load_scalar(fx);
309
310                 let target = fx.get_block(*target);
311                 let failure = fx.bcx.create_block();
312                 fx.bcx.set_cold_block(failure);
313
314                 if *expected {
315                     fx.bcx.ins().brz(cond, failure, &[]);
316                 } else {
317                     fx.bcx.ins().brnz(cond, failure, &[]);
318                 };
319                 fx.bcx.ins().jump(target, &[]);
320
321                 fx.bcx.switch_to_block(failure);
322                 fx.bcx.ins().nop();
323
324                 match msg {
325                     AssertKind::BoundsCheck { ref len, ref index } => {
326                         let len = codegen_operand(fx, len).load_scalar(fx);
327                         let index = codegen_operand(fx, index).load_scalar(fx);
328                         let location = fx.get_caller_location(source_info).load_scalar(fx);
329
330                         codegen_panic_inner(
331                             fx,
332                             rustc_hir::LangItem::PanicBoundsCheck,
333                             &[index, len, location],
334                             source_info.span,
335                         );
336                     }
337                     _ => {
338                         let msg_str = msg.description();
339                         codegen_panic(fx, msg_str, source_info);
340                     }
341                 }
342             }
343
344             TerminatorKind::SwitchInt { discr, switch_ty, targets } => {
345                 let discr = codegen_operand(fx, discr).load_scalar(fx);
346
347                 let use_bool_opt = switch_ty.kind() == fx.tcx.types.bool.kind()
348                     || (targets.iter().count() == 1 && targets.iter().next().unwrap().0 == 0);
349                 if use_bool_opt {
350                     assert_eq!(targets.iter().count(), 1);
351                     let (then_value, then_block) = targets.iter().next().unwrap();
352                     let then_block = fx.get_block(then_block);
353                     let else_block = fx.get_block(targets.otherwise());
354                     let test_zero = match then_value {
355                         0 => true,
356                         1 => false,
357                         _ => unreachable!("{:?}", targets),
358                     };
359
360                     let discr = crate::optimize::peephole::maybe_unwrap_bint(&mut fx.bcx, discr);
361                     let (discr, is_inverted) =
362                         crate::optimize::peephole::maybe_unwrap_bool_not(&mut fx.bcx, discr);
363                     let test_zero = if is_inverted { !test_zero } else { test_zero };
364                     let discr = crate::optimize::peephole::maybe_unwrap_bint(&mut fx.bcx, discr);
365                     if let Some(taken) = crate::optimize::peephole::maybe_known_branch_taken(
366                         &fx.bcx, discr, test_zero,
367                     ) {
368                         if taken {
369                             fx.bcx.ins().jump(then_block, &[]);
370                         } else {
371                             fx.bcx.ins().jump(else_block, &[]);
372                         }
373                     } else {
374                         if test_zero {
375                             fx.bcx.ins().brz(discr, then_block, &[]);
376                             fx.bcx.ins().jump(else_block, &[]);
377                         } else {
378                             fx.bcx.ins().brnz(discr, then_block, &[]);
379                             fx.bcx.ins().jump(else_block, &[]);
380                         }
381                     }
382                 } else {
383                     let mut switch = ::cranelift_frontend::Switch::new();
384                     for (value, block) in targets.iter() {
385                         let block = fx.get_block(block);
386                         switch.set_entry(value, block);
387                     }
388                     let otherwise_block = fx.get_block(targets.otherwise());
389                     switch.emit(&mut fx.bcx, discr, otherwise_block);
390                 }
391             }
392             TerminatorKind::Call {
393                 func,
394                 args,
395                 destination,
396                 fn_span,
397                 cleanup: _,
398                 from_hir_call: _,
399             } => {
400                 fx.tcx.sess.time("codegen call", || {
401                     crate::abi::codegen_terminator_call(
402                         fx,
403                         mir::SourceInfo { span: *fn_span, ..source_info },
404                         func,
405                         args,
406                         *destination,
407                     )
408                 });
409             }
410             TerminatorKind::InlineAsm {
411                 template,
412                 operands,
413                 options,
414                 destination,
415                 line_spans: _,
416                 cleanup: _,
417             } => {
418                 if options.contains(InlineAsmOptions::MAY_UNWIND) {
419                     fx.tcx.sess.span_fatal(
420                         source_info.span,
421                         "cranelift doesn't support unwinding from inline assembly.",
422                     );
423                 }
424
425                 crate::inline_asm::codegen_inline_asm(
426                     fx,
427                     source_info.span,
428                     template,
429                     operands,
430                     *options,
431                 );
432
433                 match *destination {
434                     Some(destination) => {
435                         let destination_block = fx.get_block(destination);
436                         fx.bcx.ins().jump(destination_block, &[]);
437                     }
438                     None => {
439                         fx.bcx.ins().trap(TrapCode::UnreachableCodeReached);
440                     }
441                 }
442             }
443             TerminatorKind::Resume | TerminatorKind::Abort => {
444                 // FIXME implement unwinding
445                 fx.bcx.ins().trap(TrapCode::UnreachableCodeReached);
446             }
447             TerminatorKind::Unreachable => {
448                 fx.bcx.ins().trap(TrapCode::UnreachableCodeReached);
449             }
450             TerminatorKind::Yield { .. }
451             | TerminatorKind::FalseEdge { .. }
452             | TerminatorKind::FalseUnwind { .. }
453             | TerminatorKind::DropAndReplace { .. }
454             | TerminatorKind::GeneratorDrop => {
455                 bug!("shouldn't exist at codegen {:?}", bb_data.terminator());
456             }
457             TerminatorKind::Drop { place, target, unwind: _ } => {
458                 let drop_place = codegen_place(fx, *place);
459                 crate::abi::codegen_drop(fx, source_info, drop_place);
460
461                 let target_block = fx.get_block(*target);
462                 fx.bcx.ins().jump(target_block, &[]);
463             }
464         };
465     }
466
467     fx.bcx.seal_all_blocks();
468     fx.bcx.finalize();
469 }
470
471 fn codegen_stmt<'tcx>(
472     fx: &mut FunctionCx<'_, '_, 'tcx>,
473     #[allow(unused_variables)] cur_block: Block,
474     stmt: &Statement<'tcx>,
475 ) {
476     let _print_guard = crate::PrintOnPanic(|| format!("stmt {:?}", stmt));
477
478     fx.set_debug_loc(stmt.source_info);
479
480     #[cfg(disabled)]
481     match &stmt.kind {
482         StatementKind::StorageLive(..) | StatementKind::StorageDead(..) => {} // Those are not very useful
483         _ => {
484             if fx.clif_comments.enabled() {
485                 let inst = fx.bcx.func.layout.last_inst(cur_block).unwrap();
486                 fx.add_comment(inst, format!("{:?}", stmt));
487             }
488         }
489     }
490
491     match &stmt.kind {
492         StatementKind::SetDiscriminant { place, variant_index } => {
493             let place = codegen_place(fx, **place);
494             crate::discriminant::codegen_set_discriminant(fx, place, *variant_index);
495         }
496         StatementKind::Assign(to_place_and_rval) => {
497             let lval = codegen_place(fx, to_place_and_rval.0);
498             let dest_layout = lval.layout();
499             match to_place_and_rval.1 {
500                 Rvalue::Use(ref operand) => {
501                     let val = codegen_operand(fx, operand);
502                     lval.write_cvalue(fx, val);
503                 }
504                 Rvalue::Ref(_, _, place) | Rvalue::AddressOf(_, place) => {
505                     let place = codegen_place(fx, place);
506                     let ref_ = place.place_ref(fx, lval.layout());
507                     lval.write_cvalue(fx, ref_);
508                 }
509                 Rvalue::ThreadLocalRef(def_id) => {
510                     let val = crate::constant::codegen_tls_ref(fx, def_id, lval.layout());
511                     lval.write_cvalue(fx, val);
512                 }
513                 Rvalue::BinaryOp(bin_op, ref lhs_rhs) => {
514                     let lhs = codegen_operand(fx, &lhs_rhs.0);
515                     let rhs = codegen_operand(fx, &lhs_rhs.1);
516
517                     let res = crate::num::codegen_binop(fx, bin_op, lhs, rhs);
518                     lval.write_cvalue(fx, res);
519                 }
520                 Rvalue::CheckedBinaryOp(bin_op, ref lhs_rhs) => {
521                     let lhs = codegen_operand(fx, &lhs_rhs.0);
522                     let rhs = codegen_operand(fx, &lhs_rhs.1);
523
524                     let res = if !fx.tcx.sess.overflow_checks() {
525                         let val =
526                             crate::num::codegen_int_binop(fx, bin_op, lhs, rhs).load_scalar(fx);
527                         let is_overflow = fx.bcx.ins().iconst(types::I8, 0);
528                         CValue::by_val_pair(val, is_overflow, lval.layout())
529                     } else {
530                         crate::num::codegen_checked_int_binop(fx, bin_op, lhs, rhs)
531                     };
532
533                     lval.write_cvalue(fx, res);
534                 }
535                 Rvalue::UnaryOp(un_op, ref operand) => {
536                     let operand = codegen_operand(fx, operand);
537                     let layout = operand.layout();
538                     let val = operand.load_scalar(fx);
539                     let res = match un_op {
540                         UnOp::Not => match layout.ty.kind() {
541                             ty::Bool => {
542                                 let res = fx.bcx.ins().icmp_imm(IntCC::Equal, val, 0);
543                                 CValue::by_val(fx.bcx.ins().bint(types::I8, res), layout)
544                             }
545                             ty::Uint(_) | ty::Int(_) => {
546                                 CValue::by_val(fx.bcx.ins().bnot(val), layout)
547                             }
548                             _ => unreachable!("un op Not for {:?}", layout.ty),
549                         },
550                         UnOp::Neg => match layout.ty.kind() {
551                             ty::Int(IntTy::I128) => {
552                                 // FIXME remove this case once ineg.i128 works
553                                 let zero =
554                                     CValue::const_val(fx, layout, ty::ScalarInt::null(layout.size));
555                                 crate::num::codegen_int_binop(fx, BinOp::Sub, zero, operand)
556                             }
557                             ty::Int(_) => CValue::by_val(fx.bcx.ins().ineg(val), layout),
558                             ty::Float(_) => CValue::by_val(fx.bcx.ins().fneg(val), layout),
559                             _ => unreachable!("un op Neg for {:?}", layout.ty),
560                         },
561                     };
562                     lval.write_cvalue(fx, res);
563                 }
564                 Rvalue::Cast(
565                     CastKind::Pointer(PointerCast::ReifyFnPointer),
566                     ref operand,
567                     to_ty,
568                 ) => {
569                     let from_ty = fx.monomorphize(operand.ty(&fx.mir.local_decls, fx.tcx));
570                     let to_layout = fx.layout_of(fx.monomorphize(to_ty));
571                     match *from_ty.kind() {
572                         ty::FnDef(def_id, substs) => {
573                             let func_ref = fx.get_function_ref(
574                                 Instance::resolve_for_fn_ptr(
575                                     fx.tcx,
576                                     ParamEnv::reveal_all(),
577                                     def_id,
578                                     substs,
579                                 )
580                                 .unwrap()
581                                 .polymorphize(fx.tcx),
582                             );
583                             let func_addr = fx.bcx.ins().func_addr(fx.pointer_type, func_ref);
584                             lval.write_cvalue(fx, CValue::by_val(func_addr, to_layout));
585                         }
586                         _ => bug!("Trying to ReifyFnPointer on non FnDef {:?}", from_ty),
587                     }
588                 }
589                 Rvalue::Cast(
590                     CastKind::Pointer(PointerCast::UnsafeFnPointer),
591                     ref operand,
592                     to_ty,
593                 )
594                 | Rvalue::Cast(
595                     CastKind::Pointer(PointerCast::MutToConstPointer),
596                     ref operand,
597                     to_ty,
598                 )
599                 | Rvalue::Cast(
600                     CastKind::Pointer(PointerCast::ArrayToPointer),
601                     ref operand,
602                     to_ty,
603                 ) => {
604                     let to_layout = fx.layout_of(fx.monomorphize(to_ty));
605                     let operand = codegen_operand(fx, operand);
606                     lval.write_cvalue(fx, operand.cast_pointer_to(to_layout));
607                 }
608                 Rvalue::Cast(CastKind::Misc, ref operand, to_ty) => {
609                     let operand = codegen_operand(fx, operand);
610                     let from_ty = operand.layout().ty;
611                     let to_ty = fx.monomorphize(to_ty);
612
613                     fn is_fat_ptr<'tcx>(fx: &FunctionCx<'_, '_, 'tcx>, ty: Ty<'tcx>) -> bool {
614                         ty.builtin_deref(true)
615                             .map(|ty::TypeAndMut { ty: pointee_ty, mutbl: _ }| {
616                                 has_ptr_meta(fx.tcx, pointee_ty)
617                             })
618                             .unwrap_or(false)
619                     }
620
621                     if is_fat_ptr(fx, from_ty) {
622                         if is_fat_ptr(fx, to_ty) {
623                             // fat-ptr -> fat-ptr
624                             lval.write_cvalue(fx, operand.cast_pointer_to(dest_layout));
625                         } else {
626                             // fat-ptr -> thin-ptr
627                             let (ptr, _extra) = operand.load_scalar_pair(fx);
628                             lval.write_cvalue(fx, CValue::by_val(ptr, dest_layout))
629                         }
630                     } else if let ty::Adt(adt_def, _substs) = from_ty.kind() {
631                         // enum -> discriminant value
632                         assert!(adt_def.is_enum());
633                         match to_ty.kind() {
634                             ty::Uint(_) | ty::Int(_) => {}
635                             _ => unreachable!("cast adt {} -> {}", from_ty, to_ty),
636                         }
637                         let to_clif_ty = fx.clif_type(to_ty).unwrap();
638
639                         let discriminant = crate::discriminant::codegen_get_discriminant(
640                             fx,
641                             operand,
642                             fx.layout_of(operand.layout().ty.discriminant_ty(fx.tcx)),
643                         )
644                         .load_scalar(fx);
645
646                         let res = crate::cast::clif_intcast(
647                             fx,
648                             discriminant,
649                             to_clif_ty,
650                             to_ty.is_signed(),
651                         );
652                         lval.write_cvalue(fx, CValue::by_val(res, dest_layout));
653                     } else {
654                         let to_clif_ty = fx.clif_type(to_ty).unwrap();
655                         let from = operand.load_scalar(fx);
656
657                         let res = clif_int_or_float_cast(
658                             fx,
659                             from,
660                             type_sign(from_ty),
661                             to_clif_ty,
662                             type_sign(to_ty),
663                         );
664                         lval.write_cvalue(fx, CValue::by_val(res, dest_layout));
665                     }
666                 }
667                 Rvalue::Cast(
668                     CastKind::Pointer(PointerCast::ClosureFnPointer(_)),
669                     ref operand,
670                     _to_ty,
671                 ) => {
672                     let operand = codegen_operand(fx, operand);
673                     match *operand.layout().ty.kind() {
674                         ty::Closure(def_id, substs) => {
675                             let instance = Instance::resolve_closure(
676                                 fx.tcx,
677                                 def_id,
678                                 substs,
679                                 ty::ClosureKind::FnOnce,
680                             )
681                             .polymorphize(fx.tcx);
682                             let func_ref = fx.get_function_ref(instance);
683                             let func_addr = fx.bcx.ins().func_addr(fx.pointer_type, func_ref);
684                             lval.write_cvalue(fx, CValue::by_val(func_addr, lval.layout()));
685                         }
686                         _ => bug!("{} cannot be cast to a fn ptr", operand.layout().ty),
687                     }
688                 }
689                 Rvalue::Cast(CastKind::Pointer(PointerCast::Unsize), ref operand, _to_ty) => {
690                     let operand = codegen_operand(fx, operand);
691                     operand.unsize_value(fx, lval);
692                 }
693                 Rvalue::Discriminant(place) => {
694                     let place = codegen_place(fx, place);
695                     let value = place.to_cvalue(fx);
696                     let discr =
697                         crate::discriminant::codegen_get_discriminant(fx, value, dest_layout);
698                     lval.write_cvalue(fx, discr);
699                 }
700                 Rvalue::Repeat(ref operand, times) => {
701                     let operand = codegen_operand(fx, operand);
702                     let times = fx
703                         .monomorphize(times)
704                         .eval(fx.tcx, ParamEnv::reveal_all())
705                         .val()
706                         .try_to_bits(fx.tcx.data_layout.pointer_size)
707                         .unwrap();
708                     if operand.layout().size.bytes() == 0 {
709                         // Do nothing for ZST's
710                     } else if fx.clif_type(operand.layout().ty) == Some(types::I8) {
711                         let times = fx.bcx.ins().iconst(fx.pointer_type, times as i64);
712                         // FIXME use emit_small_memset where possible
713                         let addr = lval.to_ptr().get_addr(fx);
714                         let val = operand.load_scalar(fx);
715                         fx.bcx.call_memset(fx.target_config, addr, val, times);
716                     } else {
717                         let loop_block = fx.bcx.create_block();
718                         let loop_block2 = fx.bcx.create_block();
719                         let done_block = fx.bcx.create_block();
720                         let index = fx.bcx.append_block_param(loop_block, fx.pointer_type);
721                         let zero = fx.bcx.ins().iconst(fx.pointer_type, 0);
722                         fx.bcx.ins().jump(loop_block, &[zero]);
723
724                         fx.bcx.switch_to_block(loop_block);
725                         let done = fx.bcx.ins().icmp_imm(IntCC::Equal, index, times as i64);
726                         fx.bcx.ins().brnz(done, done_block, &[]);
727                         fx.bcx.ins().jump(loop_block2, &[]);
728
729                         fx.bcx.switch_to_block(loop_block2);
730                         let to = lval.place_index(fx, index);
731                         to.write_cvalue(fx, operand);
732                         let index = fx.bcx.ins().iadd_imm(index, 1);
733                         fx.bcx.ins().jump(loop_block, &[index]);
734
735                         fx.bcx.switch_to_block(done_block);
736                         fx.bcx.ins().nop();
737                     }
738                 }
739                 Rvalue::Len(place) => {
740                     let place = codegen_place(fx, place);
741                     let usize_layout = fx.layout_of(fx.tcx.types.usize);
742                     let len = codegen_array_len(fx, place);
743                     lval.write_cvalue(fx, CValue::by_val(len, usize_layout));
744                 }
745                 Rvalue::ShallowInitBox(ref operand, content_ty) => {
746                     let content_ty = fx.monomorphize(content_ty);
747                     let box_layout = fx.layout_of(fx.tcx.mk_box(content_ty));
748                     let operand = codegen_operand(fx, operand);
749                     let operand = operand.load_scalar(fx);
750                     lval.write_cvalue(fx, CValue::by_val(operand, box_layout));
751                 }
752                 Rvalue::NullaryOp(null_op, ty) => {
753                     assert!(
754                         lval.layout()
755                             .ty
756                             .is_sized(fx.tcx.at(stmt.source_info.span), ParamEnv::reveal_all())
757                     );
758                     let layout = fx.layout_of(fx.monomorphize(ty));
759                     let val = match null_op {
760                         NullOp::SizeOf => layout.size.bytes(),
761                         NullOp::AlignOf => layout.align.abi.bytes(),
762                     };
763                     let val = CValue::const_val(fx, fx.layout_of(fx.tcx.types.usize), val.into());
764                     lval.write_cvalue(fx, val);
765                 }
766                 Rvalue::Aggregate(ref kind, ref operands) => match kind.as_ref() {
767                     AggregateKind::Array(_ty) => {
768                         for (i, operand) in operands.iter().enumerate() {
769                             let operand = codegen_operand(fx, operand);
770                             let index = fx.bcx.ins().iconst(fx.pointer_type, i as i64);
771                             let to = lval.place_index(fx, index);
772                             to.write_cvalue(fx, operand);
773                         }
774                     }
775                     _ => unreachable!("shouldn't exist at codegen {:?}", to_place_and_rval.1),
776                 },
777             }
778         }
779         StatementKind::StorageLive(_)
780         | StatementKind::StorageDead(_)
781         | StatementKind::Deinit(_)
782         | StatementKind::Nop
783         | StatementKind::FakeRead(..)
784         | StatementKind::Retag { .. }
785         | StatementKind::AscribeUserType(..) => {}
786
787         StatementKind::Coverage { .. } => fx.tcx.sess.fatal("-Zcoverage is unimplemented"),
788         StatementKind::CopyNonOverlapping(inner) => {
789             let dst = codegen_operand(fx, &inner.dst);
790             let pointee = dst
791                 .layout()
792                 .pointee_info_at(fx, rustc_target::abi::Size::ZERO)
793                 .expect("Expected pointer");
794             let dst = dst.load_scalar(fx);
795             let src = codegen_operand(fx, &inner.src).load_scalar(fx);
796             let count = codegen_operand(fx, &inner.count).load_scalar(fx);
797             let elem_size: u64 = pointee.size.bytes();
798             let bytes =
799                 if elem_size != 1 { fx.bcx.ins().imul_imm(count, elem_size as i64) } else { count };
800             fx.bcx.call_memcpy(fx.target_config, dst, src, bytes);
801         }
802     }
803 }
804
805 fn codegen_array_len<'tcx>(fx: &mut FunctionCx<'_, '_, 'tcx>, place: CPlace<'tcx>) -> Value {
806     match *place.layout().ty.kind() {
807         ty::Array(_elem_ty, len) => {
808             let len = fx.monomorphize(len).eval_usize(fx.tcx, ParamEnv::reveal_all()) as i64;
809             fx.bcx.ins().iconst(fx.pointer_type, len)
810         }
811         ty::Slice(_elem_ty) => {
812             place.to_ptr_maybe_unsized().1.expect("Length metadata for slice place")
813         }
814         _ => bug!("Rvalue::Len({:?})", place),
815     }
816 }
817
818 pub(crate) fn codegen_place<'tcx>(
819     fx: &mut FunctionCx<'_, '_, 'tcx>,
820     place: Place<'tcx>,
821 ) -> CPlace<'tcx> {
822     let mut cplace = fx.get_local_place(place.local);
823
824     for elem in place.projection {
825         match elem {
826             PlaceElem::Deref => {
827                 if cplace.layout().ty.is_box() {
828                     cplace = cplace
829                         .place_field(fx, Field::new(0)) // Box<T> -> Unique<T>
830                         .place_field(fx, Field::new(0)) // Unique<T> -> NonNull<T>
831                         .place_field(fx, Field::new(0)) // NonNull<T> -> *mut T
832                         .place_deref(fx);
833                 } else {
834                     cplace = cplace.place_deref(fx);
835                 }
836             }
837             PlaceElem::Field(field, _ty) => {
838                 cplace = cplace.place_field(fx, field);
839             }
840             PlaceElem::Index(local) => {
841                 let index = fx.get_local_place(local).to_cvalue(fx).load_scalar(fx);
842                 cplace = cplace.place_index(fx, index);
843             }
844             PlaceElem::ConstantIndex { offset, min_length: _, from_end } => {
845                 let offset: u64 = offset;
846                 let index = if !from_end {
847                     fx.bcx.ins().iconst(fx.pointer_type, offset as i64)
848                 } else {
849                     let len = codegen_array_len(fx, cplace);
850                     fx.bcx.ins().iadd_imm(len, -(offset as i64))
851                 };
852                 cplace = cplace.place_index(fx, index);
853             }
854             PlaceElem::Subslice { from, to, from_end } => {
855                 // These indices are generated by slice patterns.
856                 // slice[from:-to] in Python terms.
857
858                 let from: u64 = from;
859                 let to: u64 = to;
860
861                 match cplace.layout().ty.kind() {
862                     ty::Array(elem_ty, _len) => {
863                         assert!(!from_end, "array subslices are never `from_end`");
864                         let elem_layout = fx.layout_of(*elem_ty);
865                         let ptr = cplace.to_ptr();
866                         cplace = CPlace::for_ptr(
867                             ptr.offset_i64(fx, elem_layout.size.bytes() as i64 * (from as i64)),
868                             fx.layout_of(fx.tcx.mk_array(*elem_ty, to - from)),
869                         );
870                     }
871                     ty::Slice(elem_ty) => {
872                         assert!(from_end, "slice subslices should be `from_end`");
873                         let elem_layout = fx.layout_of(*elem_ty);
874                         let (ptr, len) = cplace.to_ptr_maybe_unsized();
875                         let len = len.unwrap();
876                         cplace = CPlace::for_ptr_with_extra(
877                             ptr.offset_i64(fx, elem_layout.size.bytes() as i64 * (from as i64)),
878                             fx.bcx.ins().iadd_imm(len, -(from as i64 + to as i64)),
879                             cplace.layout(),
880                         );
881                     }
882                     _ => unreachable!(),
883                 }
884             }
885             PlaceElem::Downcast(_adt_def, variant) => {
886                 cplace = cplace.downcast_variant(fx, variant);
887             }
888         }
889     }
890
891     cplace
892 }
893
894 pub(crate) fn codegen_operand<'tcx>(
895     fx: &mut FunctionCx<'_, '_, 'tcx>,
896     operand: &Operand<'tcx>,
897 ) -> CValue<'tcx> {
898     match operand {
899         Operand::Move(place) | Operand::Copy(place) => {
900             let cplace = codegen_place(fx, *place);
901             cplace.to_cvalue(fx)
902         }
903         Operand::Constant(const_) => crate::constant::codegen_constant(fx, const_),
904     }
905 }
906
907 pub(crate) fn codegen_panic<'tcx>(
908     fx: &mut FunctionCx<'_, '_, 'tcx>,
909     msg_str: &str,
910     source_info: mir::SourceInfo,
911 ) {
912     let location = fx.get_caller_location(source_info).load_scalar(fx);
913
914     let msg_ptr = fx.anonymous_str(msg_str);
915     let msg_len = fx.bcx.ins().iconst(fx.pointer_type, i64::try_from(msg_str.len()).unwrap());
916     let args = [msg_ptr, msg_len, location];
917
918     codegen_panic_inner(fx, rustc_hir::LangItem::Panic, &args, source_info.span);
919 }
920
921 pub(crate) fn codegen_panic_inner<'tcx>(
922     fx: &mut FunctionCx<'_, '_, 'tcx>,
923     lang_item: rustc_hir::LangItem,
924     args: &[Value],
925     span: Span,
926 ) {
927     let def_id =
928         fx.tcx.lang_items().require(lang_item).unwrap_or_else(|s| fx.tcx.sess.span_fatal(span, &s));
929
930     let instance = Instance::mono(fx.tcx, def_id).polymorphize(fx.tcx);
931     let symbol_name = fx.tcx.symbol_name(instance).name;
932
933     fx.lib_call(
934         &*symbol_name,
935         vec![
936             AbiParam::new(fx.pointer_type),
937             AbiParam::new(fx.pointer_type),
938             AbiParam::new(fx.pointer_type),
939         ],
940         vec![],
941         args,
942     );
943
944     fx.bcx.ins().trap(TrapCode::UnreachableCodeReached);
945 }