]> git.lizzy.rs Git - rust.git/blob - src/base.rs
Sync from rust f99f9e48ed77a99747c6d07b42fdfe500f1a7de0
[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     #[cfg(any())] // This is never true
179     let _clif_guard = {
180         use std::fmt::Write;
181
182         let func_clone = context.func.clone();
183         let clif_comments_clone = clif_comments.clone();
184         let mut clif = String::new();
185         for flag in module.isa().flags().iter() {
186             writeln!(clif, "set {}", flag).unwrap();
187         }
188         write!(clif, "target {}", module.isa().triple().architecture.to_string()).unwrap();
189         for isa_flag in module.isa().isa_flags().iter() {
190             write!(clif, " {}", isa_flag).unwrap();
191         }
192         writeln!(clif, "\n").unwrap();
193         crate::PrintOnPanic(move || {
194             let mut clif = clif.clone();
195             ::cranelift_codegen::write::decorate_function(
196                 &mut &clif_comments_clone,
197                 &mut clif,
198                 &func_clone,
199             )
200             .unwrap();
201             clif
202         })
203     };
204
205     // Define function
206     tcx.sess.time("define function", || {
207         context.want_disasm = crate::pretty_clif::should_write_ir(tcx);
208         module.define_function(func_id, context).unwrap();
209     });
210
211     // Write optimized function to file for debugging
212     crate::pretty_clif::write_clif_file(
213         tcx,
214         "opt",
215         module.isa(),
216         instance,
217         &context.func,
218         &clif_comments,
219     );
220
221     if let Some(disasm) = &context.mach_compile_result.as_ref().unwrap().disasm {
222         crate::pretty_clif::write_ir_file(
223             tcx,
224             || format!("{}.vcode", tcx.symbol_name(instance).name),
225             |file| file.write_all(disasm.as_bytes()),
226         )
227     }
228
229     // Define debuginfo for function
230     let isa = module.isa();
231     let debug_context = &mut cx.debug_context;
232     let unwind_context = &mut cx.unwind_context;
233     tcx.sess.time("generate debug info", || {
234         if let Some(debug_context) = debug_context {
235             debug_context.define_function(
236                 instance,
237                 func_id,
238                 symbol_name,
239                 isa,
240                 context,
241                 &source_info_set,
242                 local_map,
243             );
244         }
245         unwind_context.add_function(func_id, &context, isa);
246     });
247 }
248
249 pub(crate) fn verify_func(
250     tcx: TyCtxt<'_>,
251     writer: &crate::pretty_clif::CommentWriter,
252     func: &Function,
253 ) {
254     tcx.sess.time("verify clif ir", || {
255         let flags = cranelift_codegen::settings::Flags::new(cranelift_codegen::settings::builder());
256         match cranelift_codegen::verify_function(&func, &flags) {
257             Ok(_) => {}
258             Err(err) => {
259                 tcx.sess.err(&format!("{:?}", err));
260                 let pretty_error = cranelift_codegen::print_errors::pretty_verifier_error(
261                     &func,
262                     Some(Box::new(writer)),
263                     err,
264                 );
265                 tcx.sess.fatal(&format!("cranelift verify error:\n{}", pretty_error));
266             }
267         }
268     });
269 }
270
271 fn codegen_fn_content(fx: &mut FunctionCx<'_, '_, '_>) {
272     for (bb, bb_data) in fx.mir.basic_blocks().iter_enumerated() {
273         let block = fx.get_block(bb);
274         fx.bcx.switch_to_block(block);
275
276         if bb_data.is_cleanup {
277             // Unwinding after panicking is not supported
278             continue;
279
280             // FIXME Once unwinding is supported and Cranelift supports marking blocks as cold, do
281             // so for cleanup blocks.
282         }
283
284         fx.bcx.ins().nop();
285         for stmt in &bb_data.statements {
286             fx.set_debug_loc(stmt.source_info);
287             codegen_stmt(fx, block, stmt);
288         }
289
290         if fx.clif_comments.enabled() {
291             let mut terminator_head = "\n".to_string();
292             with_no_trimmed_paths!({
293                 bb_data.terminator().kind.fmt_head(&mut terminator_head).unwrap();
294             });
295             let inst = fx.bcx.func.layout.last_inst(block).unwrap();
296             fx.add_comment(inst, terminator_head);
297         }
298
299         let source_info = bb_data.terminator().source_info;
300         fx.set_debug_loc(source_info);
301
302         match &bb_data.terminator().kind {
303             TerminatorKind::Goto { target } => {
304                 if let TerminatorKind::Return = fx.mir[*target].terminator().kind {
305                     let mut can_immediately_return = true;
306                     for stmt in &fx.mir[*target].statements {
307                         if let StatementKind::StorageDead(_) = stmt.kind {
308                         } else {
309                             // FIXME Can sometimes happen, see rust-lang/rust#70531
310                             can_immediately_return = false;
311                             break;
312                         }
313                     }
314
315                     if can_immediately_return {
316                         crate::abi::codegen_return(fx);
317                         continue;
318                     }
319                 }
320
321                 let block = fx.get_block(*target);
322                 fx.bcx.ins().jump(block, &[]);
323             }
324             TerminatorKind::Return => {
325                 crate::abi::codegen_return(fx);
326             }
327             TerminatorKind::Assert { cond, expected, msg, target, cleanup: _ } => {
328                 if !fx.tcx.sess.overflow_checks() {
329                     if let mir::AssertKind::OverflowNeg(_) = *msg {
330                         let target = fx.get_block(*target);
331                         fx.bcx.ins().jump(target, &[]);
332                         continue;
333                     }
334                 }
335                 let cond = codegen_operand(fx, cond).load_scalar(fx);
336
337                 let target = fx.get_block(*target);
338                 let failure = fx.bcx.create_block();
339                 fx.bcx.set_cold_block(failure);
340
341                 if *expected {
342                     fx.bcx.ins().brz(cond, failure, &[]);
343                 } else {
344                     fx.bcx.ins().brnz(cond, failure, &[]);
345                 };
346                 fx.bcx.ins().jump(target, &[]);
347
348                 fx.bcx.switch_to_block(failure);
349                 fx.bcx.ins().nop();
350
351                 match msg {
352                     AssertKind::BoundsCheck { ref len, ref index } => {
353                         let len = codegen_operand(fx, len).load_scalar(fx);
354                         let index = codegen_operand(fx, index).load_scalar(fx);
355                         let location = fx.get_caller_location(source_info).load_scalar(fx);
356
357                         codegen_panic_inner(
358                             fx,
359                             rustc_hir::LangItem::PanicBoundsCheck,
360                             &[index, len, location],
361                             source_info.span,
362                         );
363                     }
364                     _ => {
365                         let msg_str = msg.description();
366                         codegen_panic(fx, msg_str, source_info);
367                     }
368                 }
369             }
370
371             TerminatorKind::SwitchInt { discr, switch_ty, targets } => {
372                 let discr = codegen_operand(fx, discr).load_scalar(fx);
373
374                 let use_bool_opt = switch_ty.kind() == fx.tcx.types.bool.kind()
375                     || (targets.iter().count() == 1 && targets.iter().next().unwrap().0 == 0);
376                 if use_bool_opt {
377                     assert_eq!(targets.iter().count(), 1);
378                     let (then_value, then_block) = targets.iter().next().unwrap();
379                     let then_block = fx.get_block(then_block);
380                     let else_block = fx.get_block(targets.otherwise());
381                     let test_zero = match then_value {
382                         0 => true,
383                         1 => false,
384                         _ => unreachable!("{:?}", targets),
385                     };
386
387                     let discr = crate::optimize::peephole::maybe_unwrap_bint(&mut fx.bcx, discr);
388                     let (discr, is_inverted) =
389                         crate::optimize::peephole::maybe_unwrap_bool_not(&mut fx.bcx, discr);
390                     let test_zero = if is_inverted { !test_zero } else { test_zero };
391                     let discr = crate::optimize::peephole::maybe_unwrap_bint(&mut fx.bcx, discr);
392                     if let Some(taken) = crate::optimize::peephole::maybe_known_branch_taken(
393                         &fx.bcx, discr, test_zero,
394                     ) {
395                         if taken {
396                             fx.bcx.ins().jump(then_block, &[]);
397                         } else {
398                             fx.bcx.ins().jump(else_block, &[]);
399                         }
400                     } else {
401                         if test_zero {
402                             fx.bcx.ins().brz(discr, then_block, &[]);
403                             fx.bcx.ins().jump(else_block, &[]);
404                         } else {
405                             fx.bcx.ins().brnz(discr, then_block, &[]);
406                             fx.bcx.ins().jump(else_block, &[]);
407                         }
408                     }
409                 } else {
410                     let mut switch = ::cranelift_frontend::Switch::new();
411                     for (value, block) in targets.iter() {
412                         let block = fx.get_block(block);
413                         switch.set_entry(value, block);
414                     }
415                     let otherwise_block = fx.get_block(targets.otherwise());
416                     switch.emit(&mut fx.bcx, discr, otherwise_block);
417                 }
418             }
419             TerminatorKind::Call {
420                 func,
421                 args,
422                 destination,
423                 target,
424                 fn_span,
425                 cleanup: _,
426                 from_hir_call: _,
427             } => {
428                 fx.tcx.sess.time("codegen call", || {
429                     crate::abi::codegen_terminator_call(
430                         fx,
431                         mir::SourceInfo { span: *fn_span, ..source_info },
432                         func,
433                         args,
434                         *destination,
435                         *target,
436                     )
437                 });
438             }
439             TerminatorKind::InlineAsm {
440                 template,
441                 operands,
442                 options,
443                 destination,
444                 line_spans: _,
445                 cleanup: _,
446             } => {
447                 if options.contains(InlineAsmOptions::MAY_UNWIND) {
448                     fx.tcx.sess.span_fatal(
449                         source_info.span,
450                         "cranelift doesn't support unwinding from inline assembly.",
451                     );
452                 }
453
454                 crate::inline_asm::codegen_inline_asm(
455                     fx,
456                     source_info.span,
457                     template,
458                     operands,
459                     *options,
460                 );
461
462                 match *destination {
463                     Some(destination) => {
464                         let destination_block = fx.get_block(destination);
465                         fx.bcx.ins().jump(destination_block, &[]);
466                     }
467                     None => {
468                         fx.bcx.ins().trap(TrapCode::UnreachableCodeReached);
469                     }
470                 }
471             }
472             TerminatorKind::Resume | TerminatorKind::Abort => {
473                 // FIXME implement unwinding
474                 fx.bcx.ins().trap(TrapCode::UnreachableCodeReached);
475             }
476             TerminatorKind::Unreachable => {
477                 fx.bcx.ins().trap(TrapCode::UnreachableCodeReached);
478             }
479             TerminatorKind::Yield { .. }
480             | TerminatorKind::FalseEdge { .. }
481             | TerminatorKind::FalseUnwind { .. }
482             | TerminatorKind::DropAndReplace { .. }
483             | TerminatorKind::GeneratorDrop => {
484                 bug!("shouldn't exist at codegen {:?}", bb_data.terminator());
485             }
486             TerminatorKind::Drop { place, target, unwind: _ } => {
487                 let drop_place = codegen_place(fx, *place);
488                 crate::abi::codegen_drop(fx, source_info, drop_place);
489
490                 let target_block = fx.get_block(*target);
491                 fx.bcx.ins().jump(target_block, &[]);
492             }
493         };
494     }
495
496     fx.bcx.seal_all_blocks();
497     fx.bcx.finalize();
498 }
499
500 fn codegen_stmt<'tcx>(
501     fx: &mut FunctionCx<'_, '_, 'tcx>,
502     #[allow(unused_variables)] cur_block: Block,
503     stmt: &Statement<'tcx>,
504 ) {
505     let _print_guard = crate::PrintOnPanic(|| format!("stmt {:?}", stmt));
506
507     fx.set_debug_loc(stmt.source_info);
508
509     #[cfg(any())] // This is never true
510     match &stmt.kind {
511         StatementKind::StorageLive(..) | StatementKind::StorageDead(..) => {} // Those are not very useful
512         _ => {
513             if fx.clif_comments.enabled() {
514                 let inst = fx.bcx.func.layout.last_inst(cur_block).unwrap();
515                 fx.add_comment(inst, format!("{:?}", stmt));
516             }
517         }
518     }
519
520     match &stmt.kind {
521         StatementKind::SetDiscriminant { place, variant_index } => {
522             let place = codegen_place(fx, **place);
523             crate::discriminant::codegen_set_discriminant(fx, place, *variant_index);
524         }
525         StatementKind::Assign(to_place_and_rval) => {
526             let lval = codegen_place(fx, to_place_and_rval.0);
527             let dest_layout = lval.layout();
528             match to_place_and_rval.1 {
529                 Rvalue::Use(ref operand) => {
530                     let val = codegen_operand(fx, operand);
531                     lval.write_cvalue(fx, val);
532                 }
533                 Rvalue::Ref(_, _, place) | Rvalue::AddressOf(_, place) => {
534                     let place = codegen_place(fx, place);
535                     let ref_ = place.place_ref(fx, lval.layout());
536                     lval.write_cvalue(fx, ref_);
537                 }
538                 Rvalue::ThreadLocalRef(def_id) => {
539                     let val = crate::constant::codegen_tls_ref(fx, def_id, lval.layout());
540                     lval.write_cvalue(fx, val);
541                 }
542                 Rvalue::BinaryOp(bin_op, ref lhs_rhs) => {
543                     let lhs = codegen_operand(fx, &lhs_rhs.0);
544                     let rhs = codegen_operand(fx, &lhs_rhs.1);
545
546                     let res = crate::num::codegen_binop(fx, bin_op, lhs, rhs);
547                     lval.write_cvalue(fx, res);
548                 }
549                 Rvalue::CheckedBinaryOp(bin_op, ref lhs_rhs) => {
550                     let lhs = codegen_operand(fx, &lhs_rhs.0);
551                     let rhs = codegen_operand(fx, &lhs_rhs.1);
552
553                     let res = if !fx.tcx.sess.overflow_checks() {
554                         let val =
555                             crate::num::codegen_int_binop(fx, bin_op, lhs, rhs).load_scalar(fx);
556                         let is_overflow = fx.bcx.ins().iconst(types::I8, 0);
557                         CValue::by_val_pair(val, is_overflow, lval.layout())
558                     } else {
559                         crate::num::codegen_checked_int_binop(fx, bin_op, lhs, rhs)
560                     };
561
562                     lval.write_cvalue(fx, res);
563                 }
564                 Rvalue::UnaryOp(un_op, ref operand) => {
565                     let operand = codegen_operand(fx, operand);
566                     let layout = operand.layout();
567                     let val = operand.load_scalar(fx);
568                     let res = match un_op {
569                         UnOp::Not => match layout.ty.kind() {
570                             ty::Bool => {
571                                 let res = fx.bcx.ins().icmp_imm(IntCC::Equal, val, 0);
572                                 CValue::by_val(fx.bcx.ins().bint(types::I8, res), layout)
573                             }
574                             ty::Uint(_) | ty::Int(_) => {
575                                 CValue::by_val(fx.bcx.ins().bnot(val), layout)
576                             }
577                             _ => unreachable!("un op Not for {:?}", layout.ty),
578                         },
579                         UnOp::Neg => match layout.ty.kind() {
580                             ty::Int(IntTy::I128) => {
581                                 // FIXME remove this case once ineg.i128 works
582                                 let zero =
583                                     CValue::const_val(fx, layout, ty::ScalarInt::null(layout.size));
584                                 crate::num::codegen_int_binop(fx, BinOp::Sub, zero, operand)
585                             }
586                             ty::Int(_) => CValue::by_val(fx.bcx.ins().ineg(val), layout),
587                             ty::Float(_) => CValue::by_val(fx.bcx.ins().fneg(val), layout),
588                             _ => unreachable!("un op Neg for {:?}", layout.ty),
589                         },
590                     };
591                     lval.write_cvalue(fx, res);
592                 }
593                 Rvalue::Cast(
594                     CastKind::Pointer(PointerCast::ReifyFnPointer),
595                     ref operand,
596                     to_ty,
597                 ) => {
598                     let from_ty = fx.monomorphize(operand.ty(&fx.mir.local_decls, fx.tcx));
599                     let to_layout = fx.layout_of(fx.monomorphize(to_ty));
600                     match *from_ty.kind() {
601                         ty::FnDef(def_id, substs) => {
602                             let func_ref = fx.get_function_ref(
603                                 Instance::resolve_for_fn_ptr(
604                                     fx.tcx,
605                                     ParamEnv::reveal_all(),
606                                     def_id,
607                                     substs,
608                                 )
609                                 .unwrap()
610                                 .polymorphize(fx.tcx),
611                             );
612                             let func_addr = fx.bcx.ins().func_addr(fx.pointer_type, func_ref);
613                             lval.write_cvalue(fx, CValue::by_val(func_addr, to_layout));
614                         }
615                         _ => bug!("Trying to ReifyFnPointer on non FnDef {:?}", from_ty),
616                     }
617                 }
618                 Rvalue::Cast(
619                     CastKind::Pointer(PointerCast::UnsafeFnPointer),
620                     ref operand,
621                     to_ty,
622                 )
623                 | Rvalue::Cast(
624                     CastKind::Pointer(PointerCast::MutToConstPointer),
625                     ref operand,
626                     to_ty,
627                 )
628                 | Rvalue::Cast(
629                     CastKind::Pointer(PointerCast::ArrayToPointer),
630                     ref operand,
631                     to_ty,
632                 ) => {
633                     let to_layout = fx.layout_of(fx.monomorphize(to_ty));
634                     let operand = codegen_operand(fx, operand);
635                     lval.write_cvalue(fx, operand.cast_pointer_to(to_layout));
636                 }
637                 Rvalue::Cast(
638                     CastKind::Misc
639                     | CastKind::PointerExposeAddress
640                     | CastKind::PointerFromExposedAddress,
641                     ref operand,
642                     to_ty,
643                 ) => {
644                     let operand = codegen_operand(fx, operand);
645                     let from_ty = operand.layout().ty;
646                     let to_ty = fx.monomorphize(to_ty);
647
648                     fn is_fat_ptr<'tcx>(fx: &FunctionCx<'_, '_, 'tcx>, ty: Ty<'tcx>) -> bool {
649                         ty.builtin_deref(true)
650                             .map(|ty::TypeAndMut { ty: pointee_ty, mutbl: _ }| {
651                                 has_ptr_meta(fx.tcx, pointee_ty)
652                             })
653                             .unwrap_or(false)
654                     }
655
656                     if is_fat_ptr(fx, from_ty) {
657                         if is_fat_ptr(fx, to_ty) {
658                             // fat-ptr -> fat-ptr
659                             lval.write_cvalue(fx, operand.cast_pointer_to(dest_layout));
660                         } else {
661                             // fat-ptr -> thin-ptr
662                             let (ptr, _extra) = operand.load_scalar_pair(fx);
663                             lval.write_cvalue(fx, CValue::by_val(ptr, dest_layout))
664                         }
665                     } else if let ty::Adt(adt_def, _substs) = from_ty.kind() {
666                         // enum -> discriminant value
667                         assert!(adt_def.is_enum());
668                         match to_ty.kind() {
669                             ty::Uint(_) | ty::Int(_) => {}
670                             _ => unreachable!("cast adt {} -> {}", from_ty, to_ty),
671                         }
672                         let to_clif_ty = fx.clif_type(to_ty).unwrap();
673
674                         let discriminant = crate::discriminant::codegen_get_discriminant(
675                             fx,
676                             operand,
677                             fx.layout_of(operand.layout().ty.discriminant_ty(fx.tcx)),
678                         )
679                         .load_scalar(fx);
680
681                         let res = crate::cast::clif_intcast(
682                             fx,
683                             discriminant,
684                             to_clif_ty,
685                             to_ty.is_signed(),
686                         );
687                         lval.write_cvalue(fx, CValue::by_val(res, dest_layout));
688                     } else {
689                         let to_clif_ty = fx.clif_type(to_ty).unwrap();
690                         let from = operand.load_scalar(fx);
691
692                         let res = clif_int_or_float_cast(
693                             fx,
694                             from,
695                             type_sign(from_ty),
696                             to_clif_ty,
697                             type_sign(to_ty),
698                         );
699                         lval.write_cvalue(fx, CValue::by_val(res, dest_layout));
700                     }
701                 }
702                 Rvalue::Cast(
703                     CastKind::Pointer(PointerCast::ClosureFnPointer(_)),
704                     ref operand,
705                     _to_ty,
706                 ) => {
707                     let operand = codegen_operand(fx, operand);
708                     match *operand.layout().ty.kind() {
709                         ty::Closure(def_id, substs) => {
710                             let instance = Instance::resolve_closure(
711                                 fx.tcx,
712                                 def_id,
713                                 substs,
714                                 ty::ClosureKind::FnOnce,
715                             )
716                             .expect("failed to normalize and resolve closure during codegen")
717                             .polymorphize(fx.tcx);
718                             let func_ref = fx.get_function_ref(instance);
719                             let func_addr = fx.bcx.ins().func_addr(fx.pointer_type, func_ref);
720                             lval.write_cvalue(fx, CValue::by_val(func_addr, lval.layout()));
721                         }
722                         _ => bug!("{} cannot be cast to a fn ptr", operand.layout().ty),
723                     }
724                 }
725                 Rvalue::Cast(CastKind::Pointer(PointerCast::Unsize), ref operand, _to_ty) => {
726                     let operand = codegen_operand(fx, operand);
727                     operand.unsize_value(fx, lval);
728                 }
729                 Rvalue::Discriminant(place) => {
730                     let place = codegen_place(fx, place);
731                     let value = place.to_cvalue(fx);
732                     let discr =
733                         crate::discriminant::codegen_get_discriminant(fx, value, dest_layout);
734                     lval.write_cvalue(fx, discr);
735                 }
736                 Rvalue::Repeat(ref operand, times) => {
737                     let operand = codegen_operand(fx, operand);
738                     let times = fx
739                         .monomorphize(times)
740                         .eval(fx.tcx, ParamEnv::reveal_all())
741                         .kind()
742                         .try_to_bits(fx.tcx.data_layout.pointer_size)
743                         .unwrap();
744                     if operand.layout().size.bytes() == 0 {
745                         // Do nothing for ZST's
746                     } else if fx.clif_type(operand.layout().ty) == Some(types::I8) {
747                         let times = fx.bcx.ins().iconst(fx.pointer_type, times as i64);
748                         // FIXME use emit_small_memset where possible
749                         let addr = lval.to_ptr().get_addr(fx);
750                         let val = operand.load_scalar(fx);
751                         fx.bcx.call_memset(fx.target_config, addr, val, times);
752                     } else {
753                         let loop_block = fx.bcx.create_block();
754                         let loop_block2 = fx.bcx.create_block();
755                         let done_block = fx.bcx.create_block();
756                         let index = fx.bcx.append_block_param(loop_block, fx.pointer_type);
757                         let zero = fx.bcx.ins().iconst(fx.pointer_type, 0);
758                         fx.bcx.ins().jump(loop_block, &[zero]);
759
760                         fx.bcx.switch_to_block(loop_block);
761                         let done = fx.bcx.ins().icmp_imm(IntCC::Equal, index, times as i64);
762                         fx.bcx.ins().brnz(done, done_block, &[]);
763                         fx.bcx.ins().jump(loop_block2, &[]);
764
765                         fx.bcx.switch_to_block(loop_block2);
766                         let to = lval.place_index(fx, index);
767                         to.write_cvalue(fx, operand);
768                         let index = fx.bcx.ins().iadd_imm(index, 1);
769                         fx.bcx.ins().jump(loop_block, &[index]);
770
771                         fx.bcx.switch_to_block(done_block);
772                         fx.bcx.ins().nop();
773                     }
774                 }
775                 Rvalue::Len(place) => {
776                     let place = codegen_place(fx, place);
777                     let usize_layout = fx.layout_of(fx.tcx.types.usize);
778                     let len = codegen_array_len(fx, place);
779                     lval.write_cvalue(fx, CValue::by_val(len, usize_layout));
780                 }
781                 Rvalue::ShallowInitBox(ref operand, content_ty) => {
782                     let content_ty = fx.monomorphize(content_ty);
783                     let box_layout = fx.layout_of(fx.tcx.mk_box(content_ty));
784                     let operand = codegen_operand(fx, operand);
785                     let operand = operand.load_scalar(fx);
786                     lval.write_cvalue(fx, CValue::by_val(operand, box_layout));
787                 }
788                 Rvalue::NullaryOp(null_op, ty) => {
789                     assert!(
790                         lval.layout()
791                             .ty
792                             .is_sized(fx.tcx.at(stmt.source_info.span), ParamEnv::reveal_all())
793                     );
794                     let layout = fx.layout_of(fx.monomorphize(ty));
795                     let val = match null_op {
796                         NullOp::SizeOf => layout.size.bytes(),
797                         NullOp::AlignOf => layout.align.abi.bytes(),
798                     };
799                     let val = CValue::const_val(fx, fx.layout_of(fx.tcx.types.usize), val.into());
800                     lval.write_cvalue(fx, val);
801                 }
802                 Rvalue::Aggregate(ref kind, ref operands) => match kind.as_ref() {
803                     AggregateKind::Array(_ty) => {
804                         for (i, operand) in operands.iter().enumerate() {
805                             let operand = codegen_operand(fx, operand);
806                             let index = fx.bcx.ins().iconst(fx.pointer_type, i as i64);
807                             let to = lval.place_index(fx, index);
808                             to.write_cvalue(fx, operand);
809                         }
810                     }
811                     _ => unreachable!("shouldn't exist at codegen {:?}", to_place_and_rval.1),
812                 },
813             }
814         }
815         StatementKind::StorageLive(_)
816         | StatementKind::StorageDead(_)
817         | StatementKind::Deinit(_)
818         | StatementKind::Nop
819         | StatementKind::FakeRead(..)
820         | StatementKind::Retag { .. }
821         | StatementKind::AscribeUserType(..) => {}
822
823         StatementKind::Coverage { .. } => fx.tcx.sess.fatal("-Zcoverage is unimplemented"),
824         StatementKind::CopyNonOverlapping(inner) => {
825             let dst = codegen_operand(fx, &inner.dst);
826             let pointee = dst
827                 .layout()
828                 .pointee_info_at(fx, rustc_target::abi::Size::ZERO)
829                 .expect("Expected pointer");
830             let dst = dst.load_scalar(fx);
831             let src = codegen_operand(fx, &inner.src).load_scalar(fx);
832             let count = codegen_operand(fx, &inner.count).load_scalar(fx);
833             let elem_size: u64 = pointee.size.bytes();
834             let bytes =
835                 if elem_size != 1 { fx.bcx.ins().imul_imm(count, elem_size as i64) } else { count };
836             fx.bcx.call_memcpy(fx.target_config, dst, src, bytes);
837         }
838     }
839 }
840
841 fn codegen_array_len<'tcx>(fx: &mut FunctionCx<'_, '_, 'tcx>, place: CPlace<'tcx>) -> Value {
842     match *place.layout().ty.kind() {
843         ty::Array(_elem_ty, len) => {
844             let len = fx.monomorphize(len).eval_usize(fx.tcx, ParamEnv::reveal_all()) as i64;
845             fx.bcx.ins().iconst(fx.pointer_type, len)
846         }
847         ty::Slice(_elem_ty) => {
848             place.to_ptr_maybe_unsized().1.expect("Length metadata for slice place")
849         }
850         _ => bug!("Rvalue::Len({:?})", place),
851     }
852 }
853
854 pub(crate) fn codegen_place<'tcx>(
855     fx: &mut FunctionCx<'_, '_, 'tcx>,
856     place: Place<'tcx>,
857 ) -> CPlace<'tcx> {
858     let mut cplace = fx.get_local_place(place.local);
859
860     for elem in place.projection {
861         match elem {
862             PlaceElem::Deref => {
863                 cplace = cplace.place_deref(fx);
864             }
865             PlaceElem::Field(field, _ty) => {
866                 cplace = cplace.place_field(fx, field);
867             }
868             PlaceElem::Index(local) => {
869                 let index = fx.get_local_place(local).to_cvalue(fx).load_scalar(fx);
870                 cplace = cplace.place_index(fx, index);
871             }
872             PlaceElem::ConstantIndex { offset, min_length: _, from_end } => {
873                 let offset: u64 = offset;
874                 let index = if !from_end {
875                     fx.bcx.ins().iconst(fx.pointer_type, offset as i64)
876                 } else {
877                     let len = codegen_array_len(fx, cplace);
878                     fx.bcx.ins().iadd_imm(len, -(offset as i64))
879                 };
880                 cplace = cplace.place_index(fx, index);
881             }
882             PlaceElem::Subslice { from, to, from_end } => {
883                 // These indices are generated by slice patterns.
884                 // slice[from:-to] in Python terms.
885
886                 let from: u64 = from;
887                 let to: u64 = to;
888
889                 match cplace.layout().ty.kind() {
890                     ty::Array(elem_ty, _len) => {
891                         assert!(!from_end, "array subslices are never `from_end`");
892                         let elem_layout = fx.layout_of(*elem_ty);
893                         let ptr = cplace.to_ptr();
894                         cplace = CPlace::for_ptr(
895                             ptr.offset_i64(fx, elem_layout.size.bytes() as i64 * (from as i64)),
896                             fx.layout_of(fx.tcx.mk_array(*elem_ty, to - from)),
897                         );
898                     }
899                     ty::Slice(elem_ty) => {
900                         assert!(from_end, "slice subslices should be `from_end`");
901                         let elem_layout = fx.layout_of(*elem_ty);
902                         let (ptr, len) = cplace.to_ptr_maybe_unsized();
903                         let len = len.unwrap();
904                         cplace = CPlace::for_ptr_with_extra(
905                             ptr.offset_i64(fx, elem_layout.size.bytes() as i64 * (from as i64)),
906                             fx.bcx.ins().iadd_imm(len, -(from as i64 + to as i64)),
907                             cplace.layout(),
908                         );
909                     }
910                     _ => unreachable!(),
911                 }
912             }
913             PlaceElem::Downcast(_adt_def, variant) => {
914                 cplace = cplace.downcast_variant(fx, variant);
915             }
916         }
917     }
918
919     cplace
920 }
921
922 pub(crate) fn codegen_operand<'tcx>(
923     fx: &mut FunctionCx<'_, '_, 'tcx>,
924     operand: &Operand<'tcx>,
925 ) -> CValue<'tcx> {
926     match operand {
927         Operand::Move(place) | Operand::Copy(place) => {
928             let cplace = codegen_place(fx, *place);
929             cplace.to_cvalue(fx)
930         }
931         Operand::Constant(const_) => crate::constant::codegen_constant(fx, const_),
932     }
933 }
934
935 pub(crate) fn codegen_panic<'tcx>(
936     fx: &mut FunctionCx<'_, '_, 'tcx>,
937     msg_str: &str,
938     source_info: mir::SourceInfo,
939 ) {
940     let location = fx.get_caller_location(source_info).load_scalar(fx);
941
942     let msg_ptr = fx.anonymous_str(msg_str);
943     let msg_len = fx.bcx.ins().iconst(fx.pointer_type, i64::try_from(msg_str.len()).unwrap());
944     let args = [msg_ptr, msg_len, location];
945
946     codegen_panic_inner(fx, rustc_hir::LangItem::Panic, &args, source_info.span);
947 }
948
949 pub(crate) fn codegen_panic_inner<'tcx>(
950     fx: &mut FunctionCx<'_, '_, 'tcx>,
951     lang_item: rustc_hir::LangItem,
952     args: &[Value],
953     span: Span,
954 ) {
955     let def_id =
956         fx.tcx.lang_items().require(lang_item).unwrap_or_else(|s| fx.tcx.sess.span_fatal(span, &s));
957
958     let instance = Instance::mono(fx.tcx, def_id).polymorphize(fx.tcx);
959     let symbol_name = fx.tcx.symbol_name(instance).name;
960
961     fx.lib_call(
962         &*symbol_name,
963         vec![
964             AbiParam::new(fx.pointer_type),
965             AbiParam::new(fx.pointer_type),
966             AbiParam::new(fx.pointer_type),
967         ],
968         vec![],
969         args,
970     );
971
972     fx.bcx.ins().trap(TrapCode::UnreachableCodeReached);
973 }