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