]> git.lizzy.rs Git - rust.git/blob - src/base.rs
Remove all non-tcx references from CodegenCx
[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     let mut debug_context = cx
19         .debug_context
20         .as_mut()
21         .map(|debug_context| FunctionDebugContext::new(debug_context, instance, func_id, &name));
22
23     // Make FunctionBuilder
24     let context = &mut cx.cached_context;
25     context.clear();
26     context.func.name = ExternalName::user(0, func_id.as_u32());
27     context.func.signature = sig;
28     context.func.collect_debug_info();
29     let mut func_ctx = FunctionBuilderContext::new();
30     let mut bcx = FunctionBuilder::new(&mut context.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()).map(|_| bcx.create_block()).collect();
35
36     // Make FunctionCx
37     let pointer_type = cx.module.target_config().pointer_type();
38     let clif_comments = crate::pretty_clif::CommentWriter::new(tcx, instance);
39
40     let mut fx = FunctionCx {
41         tcx,
42         module: &mut cx.module,
43         pointer_type,
44
45         instance,
46         mir,
47
48         bcx,
49         block_map,
50         local_map: FxHashMap::with_capacity_and_hasher(mir.local_decls.len(), Default::default()),
51         caller_location: None, // set by `codegen_fn_prelude`
52         cold_blocks: EntitySet::new(),
53
54         clif_comments,
55         constants_cx: &mut cx.constants_cx,
56         vtables: &mut cx.vtables,
57         source_info_set: indexmap::IndexSet::new(),
58     };
59
60     let arg_uninhabited = fx.mir.args_iter().any(|arg| fx.layout_of(fx.monomorphize(&fx.mir.local_decls[arg].ty)).abi.is_uninhabited());
61
62     if arg_uninhabited {
63         fx.bcx.append_block_params_for_function_params(fx.block_map[START_BLOCK]);
64         fx.bcx.switch_to_block(fx.block_map[START_BLOCK]);
65         crate::trap::trap_unreachable(&mut fx, "function has uninhabited argument");
66     } else {
67         tcx.sess.time("codegen clif ir", || {
68             tcx.sess.time("codegen prelude", || crate::abi::codegen_fn_prelude(&mut fx, start_block, true));
69             codegen_fn_content(&mut fx);
70         });
71     }
72
73     // Recover all necessary data from fx, before accessing func will prevent future access to it.
74     let instance = fx.instance;
75     let mut clif_comments = fx.clif_comments;
76     let source_info_set = fx.source_info_set;
77     let local_map = fx.local_map;
78     let cold_blocks = fx.cold_blocks;
79
80     crate::pretty_clif::write_clif_file(cx.tcx, "unopt", instance, &context.func, &clif_comments, None);
81
82     // Verify function
83     verify_func(tcx, &clif_comments, &context.func);
84
85     // Perform rust specific optimizations
86     tcx.sess.time("optimize clif ir", || {
87         crate::optimize::optimize_function(tcx, instance, context, &cold_blocks, &mut clif_comments);
88     });
89
90     // If the return block is not reachable, then the SSA builder may have inserted a `iconst.i128`
91     // instruction, which doesn't have an encoding.
92     context.compute_cfg();
93     context.compute_domtree();
94     context.eliminate_unreachable_code(cx.module.isa()).unwrap();
95
96     // Define function
97     let module = &mut cx.module;
98     tcx.sess.time(
99         "define function",
100         || module.define_function(
101             func_id,
102             context,
103             &mut cranelift_codegen::binemit::NullTrapSink {},
104         ).unwrap(),
105     );
106
107     // Write optimized function to file for debugging
108     {
109         let value_ranges = context
110             .build_value_labels_ranges(cx.module.isa())
111             .expect("value location ranges");
112
113         crate::pretty_clif::write_clif_file(
114             cx.tcx,
115             "opt",
116             instance,
117             &context.func,
118             &clif_comments,
119             Some(&value_ranges),
120         );
121     }
122
123     // Define debuginfo for function
124     let isa = cx.module.isa();
125     let unwind_context = &mut cx.unwind_context;
126     tcx.sess.time("generate debug info", || {
127         debug_context
128             .as_mut()
129             .map(|x| x.define(context, isa, &source_info_set, local_map));
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 = settings::Flags::new(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 as u64, 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                 match template {
316                     &[] => {
317                         assert_eq!(operands, &[]);
318                         match *destination {
319                             Some(destination) => {
320                                 let destination_block = fx.get_block(destination);
321                                 fx.bcx.ins().jump(destination_block, &[]);
322                             }
323                             None => bug!(),
324                         }
325
326                         // Black box
327                     }
328                     _ => unimpl_fatal!(fx.tcx, bb_data.terminator().source_info.span, "Inline assembly is not supported"),
329                 }
330             }
331             TerminatorKind::Resume | TerminatorKind::Abort => {
332                 trap_unreachable(fx, "[corruption] Unwinding bb reached.");
333             }
334             TerminatorKind::Unreachable => {
335                 trap_unreachable(fx, "[corruption] Hit unreachable code.");
336             }
337             TerminatorKind::Yield { .. }
338             | TerminatorKind::FalseEdge { .. }
339             | TerminatorKind::FalseUnwind { .. }
340             | TerminatorKind::DropAndReplace { .. }
341             | TerminatorKind::GeneratorDrop => {
342                 bug!("shouldn't exist at trans {:?}", bb_data.terminator());
343             }
344             TerminatorKind::Drop {
345                 location,
346                 target,
347                 unwind: _,
348             } => {
349                 let drop_place = trans_place(fx, *location);
350                 crate::abi::codegen_drop(fx, bb_data.terminator().source_info.span, drop_place);
351
352                 let target_block = fx.get_block(*target);
353                 fx.bcx.ins().jump(target_block, &[]);
354             }
355         };
356     }
357
358     fx.bcx.seal_all_blocks();
359     fx.bcx.finalize();
360 }
361
362 fn trans_stmt<'tcx>(
363     fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
364     #[allow(unused_variables)]
365     cur_block: Block,
366     stmt: &Statement<'tcx>,
367 ) {
368     let _print_guard = PrintOnPanic(|| format!("stmt {:?}", stmt));
369
370     fx.set_debug_loc(stmt.source_info);
371
372     #[cfg(false_debug_assertions)]
373     match &stmt.kind {
374         StatementKind::StorageLive(..) | StatementKind::StorageDead(..) => {} // Those are not very useful
375         _ => {
376             let inst = fx.bcx.func.layout.last_inst(cur_block).unwrap();
377             fx.add_comment(inst, format!("{:?}", stmt));
378         }
379     }
380
381     match &stmt.kind {
382         StatementKind::SetDiscriminant {
383             place,
384             variant_index,
385         } => {
386             let place = trans_place(fx, **place);
387             crate::discriminant::codegen_set_discriminant(fx, place, *variant_index);
388         }
389         StatementKind::Assign(to_place_and_rval) => {
390             let lval = trans_place(fx, to_place_and_rval.0);
391             let dest_layout = lval.layout();
392             match &to_place_and_rval.1 {
393                 Rvalue::Use(operand) => {
394                     let val = trans_operand(fx, operand);
395                     lval.write_cvalue(fx, val);
396                 }
397                 Rvalue::Ref(_, _, place) | Rvalue::AddressOf(_, place) => {
398                     let place = trans_place(fx, *place);
399                     place.write_place_ref(fx, lval);
400                 }
401                 Rvalue::ThreadLocalRef(def_id) => {
402                     let val = crate::constant::codegen_tls_ref(fx, *def_id, lval.layout());
403                     lval.write_cvalue(fx, val);
404                 }
405                 Rvalue::BinaryOp(bin_op, lhs, rhs) => {
406                     let lhs = trans_operand(fx, lhs);
407                     let rhs = trans_operand(fx, rhs);
408
409                     let res = crate::num::codegen_binop(fx, *bin_op, lhs, rhs);
410                     lval.write_cvalue(fx, res);
411                 }
412                 Rvalue::CheckedBinaryOp(bin_op, lhs, rhs) => {
413                     let lhs = trans_operand(fx, lhs);
414                     let rhs = trans_operand(fx, rhs);
415
416                     let res = if !fx.tcx.sess.overflow_checks() {
417                         let val =
418                             crate::num::trans_int_binop(fx, *bin_op, lhs, rhs).load_scalar(fx);
419                         let is_overflow = fx.bcx.ins().iconst(types::I8, 0);
420                         CValue::by_val_pair(val, is_overflow, lval.layout())
421                     } else {
422                         crate::num::trans_checked_int_binop(fx, *bin_op, lhs, rhs)
423                     };
424
425                     lval.write_cvalue(fx, res);
426                 }
427                 Rvalue::UnaryOp(un_op, operand) => {
428                     let operand = trans_operand(fx, operand);
429                     let layout = operand.layout();
430                     let val = operand.load_scalar(fx);
431                     let res = match un_op {
432                         UnOp::Not => {
433                             match layout.ty.kind {
434                                 ty::Bool => {
435                                     let res = fx.bcx.ins().icmp_imm(IntCC::Equal, val, 0);
436                                     CValue::by_val(fx.bcx.ins().bint(types::I8, res), layout)
437                                 }
438                                 ty::Uint(_) | ty::Int(_) => {
439                                     CValue::by_val(fx.bcx.ins().bnot(val), layout)
440                                 }
441                                 _ => unreachable!("un op Not for {:?}", layout.ty),
442                             }
443                         }
444                         UnOp::Neg => match layout.ty.kind {
445                             ty::Int(IntTy::I128) => {
446                                 // FIXME remove this case once ineg.i128 works
447                                 let zero = CValue::const_val(fx, layout, 0);
448                                 crate::num::trans_int_binop(fx, BinOp::Sub, zero, operand)
449                             }
450                             ty::Int(_) => {
451                                 CValue::by_val(fx.bcx.ins().ineg(val), layout)
452                             }
453                             ty::Float(_) => {
454                                 CValue::by_val(fx.bcx.ins().fneg(val), layout)
455                             }
456                             _ => unreachable!("un op Neg for {:?}", layout.ty),
457                         },
458                     };
459                     lval.write_cvalue(fx, res);
460                 }
461                 Rvalue::Cast(CastKind::Pointer(PointerCast::ReifyFnPointer), operand, to_ty) => {
462                     let from_ty = fx.monomorphize(&operand.ty(&fx.mir.local_decls, fx.tcx));
463                     let to_layout = fx.layout_of(fx.monomorphize(to_ty));
464                     match from_ty.kind {
465                         ty::FnDef(def_id, substs) => {
466                             let func_ref = fx.get_function_ref(
467                                 Instance::resolve_for_fn_ptr(fx.tcx, ParamEnv::reveal_all(), def_id, substs)
468                                     .unwrap(),
469                             );
470                             let func_addr = fx.bcx.ins().func_addr(fx.pointer_type, func_ref);
471                             lval.write_cvalue(fx, CValue::by_val(func_addr, to_layout));
472                         }
473                         _ => bug!("Trying to ReifyFnPointer on non FnDef {:?}", from_ty),
474                     }
475                 }
476                 Rvalue::Cast(CastKind::Pointer(PointerCast::UnsafeFnPointer), operand, to_ty)
477                 | Rvalue::Cast(CastKind::Pointer(PointerCast::MutToConstPointer), operand, to_ty)
478                 | Rvalue::Cast(CastKind::Pointer(PointerCast::ArrayToPointer), operand, to_ty) => {
479                     let to_layout = fx.layout_of(fx.monomorphize(to_ty));
480                     let operand = trans_operand(fx, operand);
481                     lval.write_cvalue(fx, operand.cast_pointer_to(to_layout));
482                 }
483                 Rvalue::Cast(CastKind::Misc, operand, to_ty) => {
484                     let operand = trans_operand(fx, operand);
485                     let from_ty = operand.layout().ty;
486                     let to_ty = fx.monomorphize(to_ty);
487
488                     fn is_fat_ptr<'tcx>(
489                         fx: &FunctionCx<'_, 'tcx, impl Backend>,
490                         ty: Ty<'tcx>,
491                     ) -> bool {
492                         ty.builtin_deref(true)
493                             .map(
494                                 |ty::TypeAndMut {
495                                      ty: pointee_ty,
496                                      mutbl: _,
497                                  }| has_ptr_meta(fx.tcx, pointee_ty),
498                             )
499                             .unwrap_or(false)
500                     }
501
502                     if is_fat_ptr(fx, from_ty) {
503                         if is_fat_ptr(fx, to_ty) {
504                             // fat-ptr -> fat-ptr
505                             lval.write_cvalue(fx, operand.cast_pointer_to(dest_layout));
506                         } else {
507                             // fat-ptr -> thin-ptr
508                             let (ptr, _extra) = operand.load_scalar_pair(fx);
509                             lval.write_cvalue(fx, CValue::by_val(ptr, dest_layout))
510                         }
511                     } else if let ty::Adt(adt_def, _substs) = from_ty.kind {
512                         // enum -> discriminant value
513                         assert!(adt_def.is_enum());
514                         match to_ty.kind {
515                             ty::Uint(_) | ty::Int(_) => {}
516                             _ => unreachable!("cast adt {} -> {}", from_ty, to_ty),
517                         }
518
519                         let discr = crate::discriminant::codegen_get_discriminant(
520                             fx,
521                             operand,
522                             fx.layout_of(to_ty),
523                         );
524                         lval.write_cvalue(fx, discr);
525                     } else {
526                         let to_clif_ty = fx.clif_type(to_ty).unwrap();
527                         let from = operand.load_scalar(fx);
528
529                         let res = clif_int_or_float_cast(
530                             fx,
531                             from,
532                             type_sign(from_ty),
533                             to_clif_ty,
534                             type_sign(to_ty),
535                         );
536                         lval.write_cvalue(fx, CValue::by_val(res, dest_layout));
537                     }
538                 }
539                 Rvalue::Cast(CastKind::Pointer(PointerCast::ClosureFnPointer(_)), operand, _to_ty) => {
540                     let operand = trans_operand(fx, operand);
541                     match operand.layout().ty.kind {
542                         ty::Closure(def_id, substs) => {
543                             let instance = Instance::resolve_closure(
544                                 fx.tcx,
545                                 def_id,
546                                 substs,
547                                 ty::ClosureKind::FnOnce,
548                             );
549                             let func_ref = fx.get_function_ref(instance);
550                             let func_addr = fx.bcx.ins().func_addr(fx.pointer_type, func_ref);
551                             lval.write_cvalue(fx, CValue::by_val(func_addr, lval.layout()));
552                         }
553                         _ => bug!("{} cannot be cast to a fn ptr", operand.layout().ty),
554                     }
555                 }
556                 Rvalue::Cast(CastKind::Pointer(PointerCast::Unsize), operand, _to_ty) => {
557                     let operand = trans_operand(fx, operand);
558                     operand.unsize_value(fx, lval);
559                 }
560                 Rvalue::Discriminant(place) => {
561                     let place = trans_place(fx, *place);
562                     let value = place.to_cvalue(fx);
563                     let discr =
564                         crate::discriminant::codegen_get_discriminant(fx, value, dest_layout);
565                     lval.write_cvalue(fx, discr);
566                 }
567                 Rvalue::Repeat(operand, times) => {
568                     let operand = trans_operand(fx, operand);
569                     let times = fx
570                         .monomorphize(times)
571                         .eval(fx.tcx, ParamEnv::reveal_all())
572                         .val
573                         .try_to_bits(fx.tcx.data_layout.pointer_size)
574                         .unwrap();
575                     for i in 0..times {
576                         let index = fx.bcx.ins().iconst(fx.pointer_type, i as i64);
577                         let to = lval.place_index(fx, index);
578                         to.write_cvalue(fx, operand);
579                     }
580                 }
581                 Rvalue::Len(place) => {
582                     let place = trans_place(fx, *place);
583                     let usize_layout = fx.layout_of(fx.tcx.types.usize);
584                     let len = codegen_array_len(fx, place);
585                     lval.write_cvalue(fx, CValue::by_val(len, usize_layout));
586                 }
587                 Rvalue::NullaryOp(NullOp::Box, content_ty) => {
588                     use rustc_hir::lang_items::ExchangeMallocFnLangItem;
589
590                     let usize_type = fx.clif_type(fx.tcx.types.usize).unwrap();
591                     let content_ty = fx.monomorphize(content_ty);
592                     let layout = fx.layout_of(content_ty);
593                     let llsize = fx.bcx.ins().iconst(usize_type, layout.size.bytes() as i64);
594                     let llalign = fx
595                         .bcx
596                         .ins()
597                         .iconst(usize_type, layout.align.abi.bytes() as i64);
598                     let box_layout = fx.layout_of(fx.tcx.mk_box(content_ty));
599
600                     // Allocate space:
601                     let def_id = match fx.tcx.lang_items().require(ExchangeMallocFnLangItem) {
602                         Ok(id) => id,
603                         Err(s) => {
604                             fx.tcx
605                                 .sess
606                                 .fatal(&format!("allocation of `{}` {}", box_layout.ty, s));
607                         }
608                     };
609                     let instance = ty::Instance::mono(fx.tcx, def_id);
610                     let func_ref = fx.get_function_ref(instance);
611                     let call = fx.bcx.ins().call(func_ref, &[llsize, llalign]);
612                     let ptr = fx.bcx.inst_results(call)[0];
613                     lval.write_cvalue(fx, CValue::by_val(ptr, box_layout));
614                 }
615                 Rvalue::NullaryOp(NullOp::SizeOf, ty) => {
616                     assert!(lval
617                         .layout()
618                         .ty
619                         .is_sized(fx.tcx.at(stmt.source_info.span), ParamEnv::reveal_all()));
620                     let ty_size = fx.layout_of(fx.monomorphize(ty)).size.bytes();
621                     let val = CValue::const_val(fx, fx.layout_of(fx.tcx.types.usize), ty_size.into());
622                     lval.write_cvalue(fx, val);
623                 }
624                 Rvalue::Aggregate(kind, operands) => match **kind {
625                     AggregateKind::Array(_ty) => {
626                         for (i, operand) in operands.into_iter().enumerate() {
627                             let operand = trans_operand(fx, operand);
628                             let index = fx.bcx.ins().iconst(fx.pointer_type, i as i64);
629                             let to = lval.place_index(fx, index);
630                             to.write_cvalue(fx, operand);
631                         }
632                     }
633                     _ => unreachable!("shouldn't exist at trans {:?}", to_place_and_rval.1),
634                 },
635             }
636         }
637         StatementKind::StorageLive(_)
638         | StatementKind::StorageDead(_)
639         | StatementKind::Nop
640         | StatementKind::FakeRead(..)
641         | StatementKind::Retag { .. }
642         | StatementKind::AscribeUserType(..) => {}
643
644         StatementKind::LlvmInlineAsm(asm) => {
645             use rustc_span::symbol::Symbol;
646             let LlvmInlineAsm {
647                 asm,
648                 outputs: _,
649                 inputs: _,
650             } = &**asm;
651             let rustc_hir::LlvmInlineAsmInner {
652                 asm: asm_code, // Name
653                 outputs,       // Vec<Name>
654                 inputs,        // Vec<Name>
655                 clobbers,      // Vec<Name>
656                 volatile,      // bool
657                 alignstack,    // bool
658                 dialect: _,    // rustc_ast::ast::AsmDialect
659                 asm_str_style: _,
660             } = asm;
661             match &*asm_code.as_str() {
662                 cpuid if cpuid.contains("cpuid") => {
663                     crate::trap::trap_unimplemented(
664                         fx,
665                         "__cpuid_count arch intrinsic is not supported",
666                     );
667                 }
668                 "xgetbv" => {
669                     assert_eq!(inputs, &[Symbol::intern("{ecx}")]);
670
671                     assert_eq!(outputs.len(), 2);
672                     for (i, c) in (&["={eax}", "={edx}"]).iter().enumerate() {
673                         assert_eq!(&outputs[i].constraint.as_str(), c);
674                         assert!(!outputs[i].is_rw);
675                         assert!(!outputs[i].is_indirect);
676                     }
677
678                     assert_eq!(clobbers, &[]);
679
680                     assert!(!volatile);
681                     assert!(!alignstack);
682
683                     crate::trap::trap_unimplemented(fx, "_xgetbv arch intrinsic is not supported");
684                 }
685                 _ => unimpl_fatal!(fx.tcx, stmt.source_info.span, "Inline assembly is not supported"),
686             }
687         }
688     }
689 }
690
691 fn codegen_array_len<'tcx>(
692     fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
693     place: CPlace<'tcx>,
694 ) -> Value {
695     match place.layout().ty.kind {
696         ty::Array(_elem_ty, len) => {
697             let len = fx.monomorphize(&len)
698                 .eval(fx.tcx, ParamEnv::reveal_all())
699                 .eval_usize(fx.tcx, ParamEnv::reveal_all()) as i64;
700             fx.bcx.ins().iconst(fx.pointer_type, len)
701         }
702         ty::Slice(_elem_ty) => place
703             .to_ptr_maybe_unsized()
704             .1
705             .expect("Length metadata for slice place"),
706         _ => bug!("Rvalue::Len({:?})", place),
707     }
708 }
709
710 pub(crate) fn trans_place<'tcx>(
711     fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
712     place: Place<'tcx>,
713 ) -> CPlace<'tcx> {
714     let mut cplace = fx.get_local_place(place.local);
715
716     for elem in place.projection {
717         match elem {
718             PlaceElem::Deref => {
719                 cplace = cplace.place_deref(fx);
720             }
721             PlaceElem::Field(field, _ty) => {
722                 cplace = cplace.place_field(fx, field);
723             }
724             PlaceElem::Index(local) => {
725                 let index = fx.get_local_place(local).to_cvalue(fx).load_scalar(fx);
726                 cplace = cplace.place_index(fx, index);
727             }
728             PlaceElem::ConstantIndex {
729                 offset,
730                 min_length: _,
731                 from_end,
732             } => {
733                 let index = if !from_end {
734                     fx.bcx.ins().iconst(fx.pointer_type, offset as i64)
735                 } else {
736                     let len = codegen_array_len(fx, cplace);
737                     fx.bcx.ins().iadd_imm(len, -(offset as i64))
738                 };
739                 cplace = cplace.place_index(fx, index);
740             }
741             PlaceElem::Subslice { from, to, from_end } => {
742                 // These indices are generated by slice patterns.
743                 // slice[from:-to] in Python terms.
744
745                 match cplace.layout().ty.kind {
746                     ty::Array(elem_ty, _len) => {
747                         assert!(!from_end, "array subslices are never `from_end`");
748                         let elem_layout = fx.layout_of(elem_ty);
749                         let ptr = cplace.to_ptr();
750                         cplace = CPlace::for_ptr(
751                             ptr.offset_i64(fx, elem_layout.size.bytes() as i64 * from as i64),
752                             fx.layout_of(fx.tcx.mk_array(elem_ty, to as u64 - from as u64)),
753                         );
754                     }
755                     ty::Slice(elem_ty) => {
756                         assert!(from_end, "slice subslices should be `from_end`");
757                         let elem_layout = fx.layout_of(elem_ty);
758                         let (ptr, len) = cplace.to_ptr_maybe_unsized();
759                         let len = len.unwrap();
760                         cplace = CPlace::for_ptr_with_extra(
761                             ptr.offset_i64(fx, elem_layout.size.bytes() as i64 * from as i64),
762                             fx.bcx.ins().iadd_imm(len, -(from as i64 + to as i64)),
763                             cplace.layout(),
764                         );
765                     }
766                     _ => unreachable!(),
767                 }
768             }
769             PlaceElem::Downcast(_adt_def, variant) => {
770                 cplace = cplace.downcast_variant(fx, variant);
771             }
772         }
773     }
774
775     cplace
776 }
777
778 pub(crate) fn trans_operand<'tcx>(
779     fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
780     operand: &Operand<'tcx>,
781 ) -> CValue<'tcx> {
782     match operand {
783         Operand::Move(place) | Operand::Copy(place) => {
784             let cplace = trans_place(fx, *place);
785             cplace.to_cvalue(fx)
786         }
787         Operand::Constant(const_) => crate::constant::trans_constant(fx, const_),
788     }
789 }