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