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