]> git.lizzy.rs Git - rust.git/blob - src/base.rs
Rustup to rustc 1.44.0-nightly (3360cc3a0 2020-04-24)
[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<'clif, 'tcx, B: Backend + 'static>(
7     cx: &mut crate::CodegenCx<'clif, '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: 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     #[cfg(debug_assertions)]
81     crate::pretty_clif::write_clif_file(cx.tcx, "unopt", instance, &context.func, &clif_comments, None);
82
83     // Verify function
84     verify_func(tcx, &clif_comments, &context.func);
85
86     // Perform rust specific optimizations
87     tcx.sess.time("optimize clif ir", || {
88         crate::optimize::optimize_function(tcx, instance, context, &cold_blocks, &mut clif_comments);
89     });
90
91     // If the return block is not reachable, then the SSA builder may have inserted a `iconst.i128`
92     // instruction, which doesn't have an encoding.
93     context.compute_cfg();
94     context.compute_domtree();
95     context.eliminate_unreachable_code(cx.module.isa()).unwrap();
96
97     // Define function
98     let module = &mut cx.module;
99     tcx.sess.time(
100         "define function",
101         || module.define_function(
102             func_id,
103             context,
104             &mut cranelift_codegen::binemit::NullTrapSink {},
105         ).unwrap(),
106     );
107
108     // Write optimized function to file for debugging
109     #[cfg(debug_assertions)]
110     {
111         let value_ranges = context
112             .build_value_labels_ranges(cx.module.isa())
113             .expect("value location ranges");
114
115         crate::pretty_clif::write_clif_file(
116             cx.tcx,
117             "opt",
118             instance,
119             &context.func,
120             &clif_comments,
121             Some(&value_ranges),
122         );
123     }
124
125     // Define debuginfo for function
126     let isa = cx.module.isa();
127     tcx.sess.time("generate debug info", || {
128         debug_context
129             .as_mut()
130             .map(|x| x.define(context, isa, &source_info_set, local_map));
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                 trap_panic(
245                     fx,
246                     format!(
247                         "[panic] Assert {:?} at {:?} failed.",
248                         msg,
249                         bb_data.terminator().source_info.span
250                     ),
251                 );
252             }
253
254             TerminatorKind::SwitchInt {
255                 discr,
256                 switch_ty: _,
257                 values,
258                 targets,
259             } => {
260                 let discr = trans_operand(fx, discr).load_scalar(fx);
261                 let mut switch = ::cranelift_frontend::Switch::new();
262                 for (i, value) in values.iter().enumerate() {
263                     let block = fx.get_block(targets[i]);
264                     switch.set_entry(*value as u64, block);
265                 }
266                 let otherwise_block = fx.get_block(targets[targets.len() - 1]);
267                 switch.emit(&mut fx.bcx, discr, otherwise_block);
268             }
269             TerminatorKind::Call {
270                 func,
271                 args,
272                 destination,
273                 cleanup: _,
274                 from_hir_call: _,
275             } => {
276                 fx.tcx.sess.time("codegen call", || crate::abi::codegen_terminator_call(
277                     fx,
278                     bb_data.terminator().source_info.span,
279                     func,
280                     args,
281                     *destination,
282                 ));
283             }
284             TerminatorKind::Resume | TerminatorKind::Abort => {
285                 trap_unreachable(fx, "[corruption] Unwinding bb reached.");
286             }
287             TerminatorKind::Unreachable => {
288                 trap_unreachable(fx, "[corruption] Hit unreachable code.");
289             }
290             TerminatorKind::Yield { .. }
291             | TerminatorKind::FalseEdges { .. }
292             | TerminatorKind::FalseUnwind { .. }
293             | TerminatorKind::DropAndReplace { .. }
294             | TerminatorKind::GeneratorDrop => {
295                 bug!("shouldn't exist at trans {:?}", bb_data.terminator());
296             }
297             TerminatorKind::Drop {
298                 location,
299                 target,
300                 unwind: _,
301             } => {
302                 let drop_place = trans_place(fx, *location);
303                 crate::abi::codegen_drop(fx, bb_data.terminator().source_info.span, drop_place);
304
305                 let target_block = fx.get_block(*target);
306                 fx.bcx.ins().jump(target_block, &[]);
307             }
308         };
309     }
310
311     fx.bcx.seal_all_blocks();
312     fx.bcx.finalize();
313 }
314
315 fn trans_stmt<'tcx>(
316     fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
317     #[allow(unused_variables)]
318     cur_block: Block,
319     stmt: &Statement<'tcx>,
320 ) {
321     let _print_guard = PrintOnPanic(|| format!("stmt {:?}", stmt));
322
323     fx.set_debug_loc(stmt.source_info);
324
325     #[cfg(false_debug_assertions)]
326     match &stmt.kind {
327         StatementKind::StorageLive(..) | StatementKind::StorageDead(..) => {} // Those are not very useful
328         _ => {
329             let inst = fx.bcx.func.layout.last_inst(cur_block).unwrap();
330             fx.add_comment(inst, format!("{:?}", stmt));
331         }
332     }
333
334     match &stmt.kind {
335         StatementKind::SetDiscriminant {
336             place,
337             variant_index,
338         } => {
339             let place = trans_place(fx, **place);
340             crate::discriminant::codegen_set_discriminant(fx, place, *variant_index);
341         }
342         StatementKind::Assign(to_place_and_rval) => {
343             let lval = trans_place(fx, to_place_and_rval.0);
344             let dest_layout = lval.layout();
345             match &to_place_and_rval.1 {
346                 Rvalue::Use(operand) => {
347                     let val = trans_operand(fx, operand);
348                     lval.write_cvalue(fx, val);
349                 }
350                 Rvalue::Ref(_, _, place) | Rvalue::AddressOf(_, place) => {
351                     let place = trans_place(fx, *place);
352                     place.write_place_ref(fx, lval);
353                 }
354                 Rvalue::BinaryOp(bin_op, lhs, rhs) => {
355                     let lhs = trans_operand(fx, lhs);
356                     let rhs = trans_operand(fx, rhs);
357
358                     let res = crate::num::codegen_binop(fx, *bin_op, lhs, rhs);
359                     lval.write_cvalue(fx, res);
360                 }
361                 Rvalue::CheckedBinaryOp(bin_op, lhs, rhs) => {
362                     let lhs = trans_operand(fx, lhs);
363                     let rhs = trans_operand(fx, rhs);
364
365                     let res = if !fx.tcx.sess.overflow_checks() {
366                         let val =
367                             crate::num::trans_int_binop(fx, *bin_op, lhs, rhs).load_scalar(fx);
368                         let is_overflow = fx.bcx.ins().iconst(types::I8, 0);
369                         CValue::by_val_pair(val, is_overflow, lval.layout())
370                     } else {
371                         crate::num::trans_checked_int_binop(fx, *bin_op, lhs, rhs)
372                     };
373
374                     lval.write_cvalue(fx, res);
375                 }
376                 Rvalue::UnaryOp(un_op, operand) => {
377                     let operand = trans_operand(fx, operand);
378                     let layout = operand.layout();
379                     let val = operand.load_scalar(fx);
380                     let res = match un_op {
381                         UnOp::Not => {
382                             match layout.ty.kind {
383                                 ty::Bool => {
384                                     let res = fx.bcx.ins().icmp_imm(IntCC::Equal, val, 0);
385                                     CValue::by_val(fx.bcx.ins().bint(types::I8, res), layout)
386                                 }
387                                 ty::Uint(_) | ty::Int(_) => {
388                                     CValue::by_val(fx.bcx.ins().bnot(val), layout)
389                                 }
390                                 _ => unreachable!("un op Not for {:?}", layout.ty),
391                             }
392                         }
393                         UnOp::Neg => match layout.ty.kind {
394                             ty::Int(IntTy::I128) => {
395                                 // FIXME remove this case once ineg.i128 works
396                                 let zero = CValue::const_val(fx, layout, 0);
397                                 crate::num::trans_int_binop(fx, BinOp::Sub, zero, operand)
398                             }
399                             ty::Int(_) => {
400                                 CValue::by_val(fx.bcx.ins().ineg(val), layout)
401                             }
402                             ty::Float(_) => {
403                                 CValue::by_val(fx.bcx.ins().fneg(val), layout)
404                             }
405                             _ => unreachable!("un op Neg for {:?}", layout.ty),
406                         },
407                     };
408                     lval.write_cvalue(fx, res);
409                 }
410                 Rvalue::Cast(CastKind::Pointer(PointerCast::ReifyFnPointer), operand, to_ty) => {
411                     let from_ty = fx.monomorphize(&operand.ty(&fx.mir.local_decls, fx.tcx));
412                     let to_layout = fx.layout_of(fx.monomorphize(to_ty));
413                     match from_ty.kind {
414                         ty::FnDef(def_id, substs) => {
415                             let func_ref = fx.get_function_ref(
416                                 Instance::resolve_for_fn_ptr(fx.tcx, ParamEnv::reveal_all(), def_id, substs)
417                                     .unwrap(),
418                             );
419                             let func_addr = fx.bcx.ins().func_addr(fx.pointer_type, func_ref);
420                             lval.write_cvalue(fx, CValue::by_val(func_addr, to_layout));
421                         }
422                         _ => bug!("Trying to ReifyFnPointer on non FnDef {:?}", from_ty),
423                     }
424                 }
425                 Rvalue::Cast(CastKind::Pointer(PointerCast::UnsafeFnPointer), operand, to_ty)
426                 | Rvalue::Cast(CastKind::Pointer(PointerCast::MutToConstPointer), operand, to_ty)
427                 | Rvalue::Cast(CastKind::Pointer(PointerCast::ArrayToPointer), operand, to_ty) => {
428                     let to_layout = fx.layout_of(fx.monomorphize(to_ty));
429                     let operand = trans_operand(fx, operand);
430                     lval.write_cvalue(fx, operand.cast_pointer_to(to_layout));
431                 }
432                 Rvalue::Cast(CastKind::Misc, operand, to_ty) => {
433                     let operand = trans_operand(fx, operand);
434                     let from_ty = operand.layout().ty;
435                     let to_ty = fx.monomorphize(to_ty);
436
437                     fn is_fat_ptr<'tcx>(
438                         fx: &FunctionCx<'_, 'tcx, impl Backend>,
439                         ty: Ty<'tcx>,
440                     ) -> bool {
441                         ty.builtin_deref(true)
442                             .map(
443                                 |ty::TypeAndMut {
444                                      ty: pointee_ty,
445                                      mutbl: _,
446                                  }| has_ptr_meta(fx.tcx, pointee_ty),
447                             )
448                             .unwrap_or(false)
449                     }
450
451                     if is_fat_ptr(fx, from_ty) {
452                         if is_fat_ptr(fx, to_ty) {
453                             // fat-ptr -> fat-ptr
454                             lval.write_cvalue(fx, operand.cast_pointer_to(dest_layout));
455                         } else {
456                             // fat-ptr -> thin-ptr
457                             let (ptr, _extra) = operand.load_scalar_pair(fx);
458                             lval.write_cvalue(fx, CValue::by_val(ptr, dest_layout))
459                         }
460                     } else if let ty::Adt(adt_def, _substs) = from_ty.kind {
461                         // enum -> discriminant value
462                         assert!(adt_def.is_enum());
463                         match to_ty.kind {
464                             ty::Uint(_) | ty::Int(_) => {}
465                             _ => unreachable!("cast adt {} -> {}", from_ty, to_ty),
466                         }
467
468                         let discr = crate::discriminant::codegen_get_discriminant(
469                             fx,
470                             operand,
471                             fx.layout_of(to_ty),
472                         );
473                         lval.write_cvalue(fx, discr);
474                     } else {
475                         let to_clif_ty = fx.clif_type(to_ty).unwrap();
476                         let from = operand.load_scalar(fx);
477
478                         let res = clif_int_or_float_cast(
479                             fx,
480                             from,
481                             type_sign(from_ty),
482                             to_clif_ty,
483                             type_sign(to_ty),
484                         );
485                         lval.write_cvalue(fx, CValue::by_val(res, dest_layout));
486                     }
487                 }
488                 Rvalue::Cast(CastKind::Pointer(PointerCast::ClosureFnPointer(_)), operand, _to_ty) => {
489                     let operand = trans_operand(fx, operand);
490                     match operand.layout().ty.kind {
491                         ty::Closure(def_id, substs) => {
492                             let instance = Instance::resolve_closure(
493                                 fx.tcx,
494                                 def_id,
495                                 substs,
496                                 ty::ClosureKind::FnOnce,
497                             );
498                             let func_ref = fx.get_function_ref(instance);
499                             let func_addr = fx.bcx.ins().func_addr(fx.pointer_type, func_ref);
500                             lval.write_cvalue(fx, CValue::by_val(func_addr, lval.layout()));
501                         }
502                         _ => bug!("{} cannot be cast to a fn ptr", operand.layout().ty),
503                     }
504                 }
505                 Rvalue::Cast(CastKind::Pointer(PointerCast::Unsize), operand, _to_ty) => {
506                     let operand = trans_operand(fx, operand);
507                     operand.unsize_value(fx, lval);
508                 }
509                 Rvalue::Discriminant(place) => {
510                     let place = trans_place(fx, *place);
511                     let value = place.to_cvalue(fx);
512                     let discr =
513                         crate::discriminant::codegen_get_discriminant(fx, value, dest_layout);
514                     lval.write_cvalue(fx, discr);
515                 }
516                 Rvalue::Repeat(operand, times) => {
517                     let operand = trans_operand(fx, operand);
518                     let times = fx
519                         .monomorphize(times)
520                         .eval(fx.tcx, ParamEnv::reveal_all())
521                         .val
522                         .try_to_bits(fx.tcx.data_layout.pointer_size)
523                         .unwrap();
524                     for i in 0..times {
525                         let index = fx.bcx.ins().iconst(fx.pointer_type, i as i64);
526                         let to = lval.place_index(fx, index);
527                         to.write_cvalue(fx, operand);
528                     }
529                 }
530                 Rvalue::Len(place) => {
531                     let place = trans_place(fx, *place);
532                     let usize_layout = fx.layout_of(fx.tcx.types.usize);
533                     let len = codegen_array_len(fx, place);
534                     lval.write_cvalue(fx, CValue::by_val(len, usize_layout));
535                 }
536                 Rvalue::NullaryOp(NullOp::Box, content_ty) => {
537                     use rustc_hir::lang_items::ExchangeMallocFnLangItem;
538
539                     let usize_type = fx.clif_type(fx.tcx.types.usize).unwrap();
540                     let content_ty = fx.monomorphize(content_ty);
541                     let layout = fx.layout_of(content_ty);
542                     let llsize = fx.bcx.ins().iconst(usize_type, layout.size.bytes() as i64);
543                     let llalign = fx
544                         .bcx
545                         .ins()
546                         .iconst(usize_type, layout.align.abi.bytes() as i64);
547                     let box_layout = fx.layout_of(fx.tcx.mk_box(content_ty));
548
549                     // Allocate space:
550                     let def_id = match fx.tcx.lang_items().require(ExchangeMallocFnLangItem) {
551                         Ok(id) => id,
552                         Err(s) => {
553                             fx.tcx
554                                 .sess
555                                 .fatal(&format!("allocation of `{}` {}", box_layout.ty, s));
556                         }
557                     };
558                     let instance = ty::Instance::mono(fx.tcx, def_id);
559                     let func_ref = fx.get_function_ref(instance);
560                     let call = fx.bcx.ins().call(func_ref, &[llsize, llalign]);
561                     let ptr = fx.bcx.inst_results(call)[0];
562                     lval.write_cvalue(fx, CValue::by_val(ptr, box_layout));
563                 }
564                 Rvalue::NullaryOp(NullOp::SizeOf, ty) => {
565                     assert!(lval
566                         .layout()
567                         .ty
568                         .is_sized(fx.tcx.at(stmt.source_info.span), ParamEnv::reveal_all()));
569                     let ty_size = fx.layout_of(fx.monomorphize(ty)).size.bytes();
570                     let val = CValue::const_val(fx, fx.layout_of(fx.tcx.types.usize), ty_size.into());
571                     lval.write_cvalue(fx, val);
572                 }
573                 Rvalue::Aggregate(kind, operands) => match **kind {
574                     AggregateKind::Array(_ty) => {
575                         for (i, operand) in operands.into_iter().enumerate() {
576                             let operand = trans_operand(fx, operand);
577                             let index = fx.bcx.ins().iconst(fx.pointer_type, i as i64);
578                             let to = lval.place_index(fx, index);
579                             to.write_cvalue(fx, operand);
580                         }
581                     }
582                     _ => unreachable!("shouldn't exist at trans {:?}", to_place_and_rval.1),
583                 },
584             }
585         }
586         StatementKind::StorageLive(_)
587         | StatementKind::StorageDead(_)
588         | StatementKind::Nop
589         | StatementKind::FakeRead(..)
590         | StatementKind::Retag { .. }
591         | StatementKind::AscribeUserType(..) => {}
592
593         StatementKind::LlvmInlineAsm(asm) => {
594             use rustc_ast::ast::Name;
595             let LlvmInlineAsm {
596                 asm,
597                 outputs: _,
598                 inputs: _,
599             } = &**asm;
600             let rustc_hir::LlvmInlineAsmInner {
601                 asm: asm_code, // Name
602                 outputs,       // Vec<Name>
603                 inputs,        // Vec<Name>
604                 clobbers,      // Vec<Name>
605                 volatile,      // bool
606                 alignstack,    // bool
607                 dialect: _,    // rustc_ast::ast::AsmDialect
608                 asm_str_style: _,
609             } = asm;
610             match &*asm_code.as_str() {
611                 "" => {
612                     assert_eq!(inputs, &[Name::intern("r")]);
613                     assert!(outputs.is_empty(), "{:?}", outputs);
614
615                     // Black box
616                 }
617                 "cpuid" | "cpuid\n" => {
618                     assert_eq!(inputs, &[Name::intern("{eax}"), Name::intern("{ecx}")]);
619
620                     assert_eq!(outputs.len(), 4);
621                     for (i, c) in (&["={eax}", "={ebx}", "={ecx}", "={edx}"])
622                         .iter()
623                         .enumerate()
624                     {
625                         assert_eq!(&outputs[i].constraint.as_str(), c);
626                         assert!(!outputs[i].is_rw);
627                         assert!(!outputs[i].is_indirect);
628                     }
629
630                     assert_eq!(clobbers, &[Name::intern("rbx")]);
631
632                     assert!(!volatile);
633                     assert!(!alignstack);
634
635                     crate::trap::trap_unimplemented(
636                         fx,
637                         "__cpuid_count arch intrinsic is not supported",
638                     );
639                 }
640                 "xgetbv" => {
641                     assert_eq!(inputs, &[Name::intern("{ecx}")]);
642
643                     assert_eq!(outputs.len(), 2);
644                     for (i, c) in (&["={eax}", "={edx}"]).iter().enumerate() {
645                         assert_eq!(&outputs[i].constraint.as_str(), c);
646                         assert!(!outputs[i].is_rw);
647                         assert!(!outputs[i].is_indirect);
648                     }
649
650                     assert_eq!(clobbers, &[]);
651
652                     assert!(!volatile);
653                     assert!(!alignstack);
654
655                     crate::trap::trap_unimplemented(fx, "_xgetbv arch intrinsic is not supported");
656                 }
657                 _ => unimpl_fatal!(fx.tcx, stmt.source_info.span, "Inline assembly is not supported"),
658             }
659         }
660     }
661 }
662
663 fn codegen_array_len<'tcx>(
664     fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
665     place: CPlace<'tcx>,
666 ) -> Value {
667     match place.layout().ty.kind {
668         ty::Array(_elem_ty, len) => {
669             let len = fx.monomorphize(&len)
670                 .eval(fx.tcx, ParamEnv::reveal_all())
671                 .eval_usize(fx.tcx, ParamEnv::reveal_all()) as i64;
672             fx.bcx.ins().iconst(fx.pointer_type, len)
673         }
674         ty::Slice(_elem_ty) => place
675             .to_ptr_maybe_unsized()
676             .1
677             .expect("Length metadata for slice place"),
678         _ => bug!("Rvalue::Len({:?})", place),
679     }
680 }
681
682 pub(crate) fn trans_place<'tcx>(
683     fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
684     place: Place<'tcx>,
685 ) -> CPlace<'tcx> {
686     let mut cplace = fx.get_local_place(place.local);
687
688     for elem in place.projection {
689         match *elem {
690             PlaceElem::Deref => {
691                 cplace = cplace.place_deref(fx);
692             }
693             PlaceElem::Field(field, _ty) => {
694                 cplace = cplace.place_field(fx, field);
695             }
696             PlaceElem::Index(local) => {
697                 let index = fx.get_local_place(local).to_cvalue(fx).load_scalar(fx);
698                 cplace = cplace.place_index(fx, index);
699             }
700             PlaceElem::ConstantIndex {
701                 offset,
702                 min_length: _,
703                 from_end,
704             } => {
705                 let index = if !from_end {
706                     fx.bcx.ins().iconst(fx.pointer_type, offset as i64)
707                 } else {
708                     let len = codegen_array_len(fx, cplace);
709                     fx.bcx.ins().iadd_imm(len, -(offset as i64))
710                 };
711                 cplace = cplace.place_index(fx, index);
712             }
713             PlaceElem::Subslice { from, to, from_end } => {
714                 // These indices are generated by slice patterns.
715                 // slice[from:-to] in Python terms.
716
717                 match cplace.layout().ty.kind {
718                     ty::Array(elem_ty, _len) => {
719                         assert!(!from_end, "array subslices are never `from_end`");
720                         let elem_layout = fx.layout_of(elem_ty);
721                         let ptr = cplace.to_ptr();
722                         cplace = CPlace::for_ptr(
723                             ptr.offset_i64(fx, elem_layout.size.bytes() as i64 * from as i64),
724                             fx.layout_of(fx.tcx.mk_array(elem_ty, to as u64 - from as u64)),
725                         );
726                     }
727                     ty::Slice(elem_ty) => {
728                         assert!(from_end, "slice subslices should be `from_end`");
729                         let elem_layout = fx.layout_of(elem_ty);
730                         let (ptr, len) = cplace.to_ptr_maybe_unsized();
731                         let len = len.unwrap();
732                         cplace = CPlace::for_ptr_with_extra(
733                             ptr.offset_i64(fx, elem_layout.size.bytes() as i64 * from as i64),
734                             fx.bcx.ins().iadd_imm(len, -(from as i64 + to as i64)),
735                             cplace.layout(),
736                         );
737                     }
738                     _ => unreachable!(),
739                 }
740             }
741             PlaceElem::Downcast(_adt_def, variant) => {
742                 cplace = cplace.downcast_variant(fx, variant);
743             }
744         }
745     }
746
747     cplace
748 }
749
750 pub(crate) fn trans_operand<'tcx>(
751     fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
752     operand: &Operand<'tcx>,
753 ) -> CValue<'tcx> {
754     match operand {
755         Operand::Move(place) | Operand::Copy(place) => {
756             let cplace = trans_place(fx, *place);
757             cplace.to_cvalue(fx)
758         }
759         Operand::Constant(const_) => crate::constant::trans_constant(fx, const_),
760     }
761 }