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