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