]> git.lizzy.rs Git - rust.git/blob - src/base.rs
Rustup to rustc 1.43.0-nightly (8aa9d2014 2020-02-21)
[rust.git] / src / base.rs
1 use rustc::ty::adjustment::PointerCast;
2 use rustc_index::vec::IndexVec;
3
4 use crate::prelude::*;
5
6 pub 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 block's
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: HashMap::new(),
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     if fx.mir.args_iter().any(|arg| fx.layout_of(fx.monomorphize(&fx.mir.local_decls[arg].ty)).abi.is_uninhabited()) {
61         let entry_block = fx.bcx.create_block();
62         fx.bcx.append_block_params_for_function_params(entry_block);
63         fx.bcx.switch_to_block(entry_block);
64         crate::trap::trap_unreachable(&mut fx, "function has uninhabited argument");
65     } else {
66         tcx.sess.time("codegen clif ir", || {
67             tcx.sess.time("codegen prelude", || crate::abi::codegen_fn_prelude(&mut fx, start_block));
68             codegen_fn_content(&mut fx);
69         });
70     }
71
72     // Recover all necessary data from fx, before accessing func will prevent future access to it.
73     let instance = fx.instance;
74     let mut clif_comments = fx.clif_comments;
75     let source_info_set = fx.source_info_set;
76     let local_map = fx.local_map;
77     let cold_blocks = fx.cold_blocks;
78
79     #[cfg(debug_assertions)]
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     // Define function
91     let module = &mut cx.module;
92     tcx.sess.time("define function", || module.define_function(func_id, context).unwrap());
93
94     // Write optimized function to file for debugging
95     #[cfg(debug_assertions)]
96     {
97         let value_ranges = context
98             .build_value_labels_ranges(cx.module.isa())
99             .expect("value location ranges");
100
101         crate::pretty_clif::write_clif_file(
102             cx.tcx,
103             "opt",
104             instance,
105             &context.func,
106             &clif_comments,
107             Some(&value_ranges),
108         );
109     }
110
111     // Define debuginfo for function
112     let isa = cx.module.isa();
113     tcx.sess.time("generate debug info", || {
114         debug_context
115             .as_mut()
116             .map(|x| x.define(context, isa, &source_info_set, local_map));
117     });
118
119     // Clear context to make it usable for the next function
120     context.clear();
121 }
122
123 pub fn verify_func(tcx: TyCtxt, writer: &crate::pretty_clif::CommentWriter, func: &Function) {
124     tcx.sess.time("verify clif ir", || {
125         let flags = settings::Flags::new(settings::builder());
126         match ::cranelift_codegen::verify_function(&func, &flags) {
127             Ok(_) => {}
128             Err(err) => {
129                 tcx.sess.err(&format!("{:?}", err));
130                 let pretty_error = ::cranelift_codegen::print_errors::pretty_verifier_error(
131                     &func,
132                     None,
133                     Some(Box::new(writer)),
134                     err,
135                 );
136                 tcx.sess
137                     .fatal(&format!("cranelift verify error:\n{}", pretty_error));
138             }
139         }
140     });
141 }
142
143 fn codegen_fn_content(fx: &mut FunctionCx<'_, '_, impl Backend>) {
144     for (bb, bb_data) in fx.mir.basic_blocks().iter_enumerated() {
145         let block = fx.get_block(bb);
146         fx.bcx.switch_to_block(block);
147
148         if bb_data.is_cleanup {
149             // Unwinding after panicking is not supported
150             continue;
151
152             // FIXME once unwinding is supported uncomment next lines
153             // // Unwinding is unlikely to happen, so mark cleanup block's as cold.
154             // fx.cold_blocks.insert(block);
155         }
156
157         fx.bcx.ins().nop();
158         for stmt in &bb_data.statements {
159             fx.set_debug_loc(stmt.source_info);
160             trans_stmt(fx, block, stmt);
161         }
162
163         #[cfg(debug_assertions)]
164         {
165             let mut terminator_head = "\n".to_string();
166             bb_data
167                 .terminator()
168                 .kind
169                 .fmt_head(&mut terminator_head)
170                 .unwrap();
171             let inst = fx.bcx.func.layout.last_inst(block).unwrap();
172             fx.add_comment(inst, terminator_head);
173         }
174
175         fx.set_debug_loc(bb_data.terminator().source_info);
176
177         match &bb_data.terminator().kind {
178             TerminatorKind::Goto { target } => {
179                 let block = fx.get_block(*target);
180                 fx.bcx.ins().jump(block, &[]);
181             }
182             TerminatorKind::Return => {
183                 crate::abi::codegen_return(fx);
184             }
185             TerminatorKind::Assert {
186                 cond,
187                 expected,
188                 msg,
189                 target,
190                 cleanup: _,
191             } => {
192                 if !fx.tcx.sess.overflow_checks() {
193                     if let mir::AssertKind::OverflowNeg = *msg {
194                         let target = fx.get_block(*target);
195                         fx.bcx.ins().jump(target, &[]);
196                         continue;
197                     }
198                 }
199                 let cond = trans_operand(fx, cond).load_scalar(fx);
200
201                 let target = fx.get_block(*target);
202                 let failure = fx.bcx.create_block();
203                 fx.cold_blocks.insert(failure);
204
205                 if *expected {
206                     fx.bcx.ins().brz(cond, failure, &[]);
207                 } else {
208                     fx.bcx.ins().brnz(cond, failure, &[]);
209                 };
210                 fx.bcx.ins().jump(target, &[]);
211
212                 fx.bcx.switch_to_block(failure);
213                 trap_panic(
214                     fx,
215                     format!(
216                         "[panic] Assert {:?} at {:?} failed.",
217                         msg,
218                         bb_data.terminator().source_info.span
219                     ),
220                 );
221             }
222
223             TerminatorKind::SwitchInt {
224                 discr,
225                 switch_ty: _,
226                 values,
227                 targets,
228             } => {
229                 let discr = trans_operand(fx, discr).load_scalar(fx);
230                 let mut switch = ::cranelift_frontend::Switch::new();
231                 for (i, value) in values.iter().enumerate() {
232                     let block = fx.get_block(targets[i]);
233                     switch.set_entry(*value as u64, block);
234                 }
235                 let otherwise_block = fx.get_block(targets[targets.len() - 1]);
236                 switch.emit(&mut fx.bcx, discr, otherwise_block);
237             }
238             TerminatorKind::Call {
239                 func,
240                 args,
241                 destination,
242                 cleanup: _,
243                 from_hir_call: _,
244             } => {
245                 fx.tcx.sess.time("codegen call", || crate::abi::codegen_terminator_call(
246                     fx,
247                     bb_data.terminator().source_info.span,
248                     func,
249                     args,
250                     destination,
251                 ));
252             }
253             TerminatorKind::Resume | TerminatorKind::Abort => {
254                 trap_unreachable(fx, "[corruption] Unwinding bb reached.");
255             }
256             TerminatorKind::Unreachable => {
257                 trap_unreachable(fx, "[corruption] Hit unreachable code.");
258             }
259             TerminatorKind::Yield { .. }
260             | TerminatorKind::FalseEdges { .. }
261             | TerminatorKind::FalseUnwind { .. }
262             | TerminatorKind::DropAndReplace { .. }
263             | TerminatorKind::GeneratorDrop => {
264                 bug!("shouldn't exist at trans {:?}", bb_data.terminator());
265             }
266             TerminatorKind::Drop {
267                 location,
268                 target,
269                 unwind: _,
270             } => {
271                 let drop_place = trans_place(fx, location);
272                 crate::abi::codegen_drop(fx, bb_data.terminator().source_info.span, drop_place);
273
274                 let target_block = fx.get_block(*target);
275                 fx.bcx.ins().jump(target_block, &[]);
276             }
277         };
278     }
279
280     fx.bcx.seal_all_blocks();
281     fx.bcx.finalize();
282 }
283
284 fn trans_stmt<'tcx>(
285     fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
286     cur_block: Block,
287     stmt: &Statement<'tcx>,
288 ) {
289     let _print_guard = PrintOnPanic(|| format!("stmt {:?}", stmt));
290
291     fx.set_debug_loc(stmt.source_info);
292
293     #[cfg(false_debug_assertions)]
294     match &stmt.kind {
295         StatementKind::StorageLive(..) | StatementKind::StorageDead(..) => {} // Those are not very useful
296         _ => {
297             let inst = fx.bcx.func.layout.last_inst(cur_block).unwrap();
298             fx.add_comment(inst, format!("{:?}", stmt));
299         }
300     }
301
302     match &stmt.kind {
303         StatementKind::SetDiscriminant {
304             place,
305             variant_index,
306         } => {
307             let place = trans_place(fx, place);
308             crate::discriminant::codegen_set_discriminant(fx, place, *variant_index);
309         }
310         StatementKind::Assign(to_place_and_rval) => {
311             let lval = trans_place(fx, &to_place_and_rval.0);
312             let dest_layout = lval.layout();
313             match &to_place_and_rval.1 {
314                 Rvalue::Use(operand) => {
315                     let val = trans_operand(fx, operand);
316                     lval.write_cvalue(fx, val);
317                 }
318                 Rvalue::Ref(_, _, place) | Rvalue::AddressOf(_, place) => {
319                     let place = trans_place(fx, place);
320                     place.write_place_ref(fx, lval);
321                 }
322                 Rvalue::BinaryOp(bin_op, lhs, rhs) => {
323                     let lhs = trans_operand(fx, lhs);
324                     let rhs = trans_operand(fx, rhs);
325
326                     let res = crate::num::codegen_binop(fx, *bin_op, lhs, rhs);
327                     lval.write_cvalue(fx, res);
328                 }
329                 Rvalue::CheckedBinaryOp(bin_op, lhs, rhs) => {
330                     let lhs = trans_operand(fx, lhs);
331                     let rhs = trans_operand(fx, rhs);
332
333                     let res = if !fx.tcx.sess.overflow_checks() {
334                         let val =
335                             crate::num::trans_int_binop(fx, *bin_op, lhs, rhs).load_scalar(fx);
336                         let is_overflow = fx.bcx.ins().iconst(types::I8, 0);
337                         CValue::by_val_pair(val, is_overflow, lval.layout())
338                     } else {
339                         crate::num::trans_checked_int_binop(fx, *bin_op, lhs, rhs)
340                     };
341
342                     lval.write_cvalue(fx, res);
343                 }
344                 Rvalue::UnaryOp(un_op, operand) => {
345                     let operand = trans_operand(fx, operand);
346                     let layout = operand.layout();
347                     let val = operand.load_scalar(fx);
348                     let res = match un_op {
349                         UnOp::Not => {
350                             match layout.ty.kind {
351                                 ty::Bool => {
352                                     let val = fx.bcx.ins().uextend(types::I32, val); // WORKAROUND for CraneStation/cranelift#466
353                                     let res = fx.bcx.ins().icmp_imm(IntCC::Equal, val, 0);
354                                     CValue::by_val(fx.bcx.ins().bint(types::I8, res), layout)
355                                 }
356                                 ty::Uint(_) | ty::Int(_) => {
357                                     CValue::by_val(fx.bcx.ins().bnot(val), layout)
358                                 }
359                                 _ => unreachable!("un op Not for {:?}", layout.ty),
360                             }
361                         }
362                         UnOp::Neg => match layout.ty.kind {
363                             ty::Int(IntTy::I128) => {
364                                 // FIXME remove this case once ineg.i128 works
365                                 let zero = CValue::const_val(fx, layout, 0);
366                                 crate::num::trans_int_binop(fx, BinOp::Sub, zero, operand)
367                             }
368                             ty::Int(_) => {
369                                 CValue::by_val(fx.bcx.ins().ineg(val), layout)
370                             }
371                             ty::Float(_) => {
372                                 CValue::by_val(fx.bcx.ins().fneg(val), layout)
373                             }
374                             _ => unreachable!("un op Neg for {:?}", layout.ty),
375                         },
376                     };
377                     lval.write_cvalue(fx, res);
378                 }
379                 Rvalue::Cast(CastKind::Pointer(PointerCast::ReifyFnPointer), operand, to_ty) => {
380                     let from_ty = fx.monomorphize(&operand.ty(&fx.mir.local_decls, fx.tcx));
381                     let to_layout = fx.layout_of(fx.monomorphize(to_ty));
382                     match from_ty.kind {
383                         ty::FnDef(def_id, substs) => {
384                             let func_ref = fx.get_function_ref(
385                                 Instance::resolve_for_fn_ptr(fx.tcx, ParamEnv::reveal_all(), def_id, substs)
386                                     .unwrap(),
387                             );
388                             let func_addr = fx.bcx.ins().func_addr(fx.pointer_type, func_ref);
389                             lval.write_cvalue(fx, CValue::by_val(func_addr, to_layout));
390                         }
391                         _ => bug!("Trying to ReifyFnPointer on non FnDef {:?}", from_ty),
392                     }
393                 }
394                 Rvalue::Cast(CastKind::Pointer(PointerCast::UnsafeFnPointer), operand, to_ty)
395                 | Rvalue::Cast(CastKind::Pointer(PointerCast::MutToConstPointer), operand, to_ty)
396                 | Rvalue::Cast(CastKind::Pointer(PointerCast::ArrayToPointer), operand, to_ty) => {
397                     let to_layout = fx.layout_of(fx.monomorphize(to_ty));
398                     let operand = trans_operand(fx, operand);
399                     lval.write_cvalue(fx, operand.unchecked_cast_to(to_layout));
400                 }
401                 Rvalue::Cast(CastKind::Misc, operand, to_ty) => {
402                     let operand = trans_operand(fx, operand);
403                     let from_ty = operand.layout().ty;
404                     let to_ty = fx.monomorphize(to_ty);
405
406                     fn is_fat_ptr<'tcx>(
407                         fx: &FunctionCx<'_, 'tcx, impl Backend>,
408                         ty: Ty<'tcx>,
409                     ) -> bool {
410                         ty.builtin_deref(true)
411                             .map(
412                                 |ty::TypeAndMut {
413                                      ty: pointee_ty,
414                                      mutbl: _,
415                                  }| has_ptr_meta(fx.tcx, pointee_ty),
416                             )
417                             .unwrap_or(false)
418                     }
419
420                     if is_fat_ptr(fx, from_ty) {
421                         if is_fat_ptr(fx, to_ty) {
422                             // fat-ptr -> fat-ptr
423                             lval.write_cvalue(fx, operand.unchecked_cast_to(dest_layout));
424                         } else {
425                             // fat-ptr -> thin-ptr
426                             let (ptr, _extra) = operand.load_scalar_pair(fx);
427                             lval.write_cvalue(fx, CValue::by_val(ptr, dest_layout))
428                         }
429                     } else if let ty::Adt(adt_def, _substs) = from_ty.kind {
430                         // enum -> discriminant value
431                         assert!(adt_def.is_enum());
432                         match to_ty.kind {
433                             ty::Uint(_) | ty::Int(_) => {}
434                             _ => unreachable!("cast adt {} -> {}", from_ty, to_ty),
435                         }
436
437                         let discr = crate::discriminant::codegen_get_discriminant(
438                             fx,
439                             operand,
440                             fx.layout_of(to_ty),
441                         );
442                         lval.write_cvalue(fx, discr);
443                     } else {
444                         let to_clif_ty = fx.clif_type(to_ty).unwrap();
445                         let from = operand.load_scalar(fx);
446
447                         let res = clif_int_or_float_cast(
448                             fx,
449                             from,
450                             type_sign(from_ty),
451                             to_clif_ty,
452                             type_sign(to_ty),
453                         );
454                         lval.write_cvalue(fx, CValue::by_val(res, dest_layout));
455                     }
456                 }
457                 Rvalue::Cast(CastKind::Pointer(PointerCast::ClosureFnPointer(_)), operand, _to_ty) => {
458                     let operand = trans_operand(fx, operand);
459                     match operand.layout().ty.kind {
460                         ty::Closure(def_id, substs) => {
461                             let instance = Instance::resolve_closure(
462                                 fx.tcx,
463                                 def_id,
464                                 substs,
465                                 ty::ClosureKind::FnOnce,
466                             );
467                             let func_ref = fx.get_function_ref(instance);
468                             let func_addr = fx.bcx.ins().func_addr(fx.pointer_type, func_ref);
469                             lval.write_cvalue(fx, CValue::by_val(func_addr, lval.layout()));
470                         }
471                         _ => bug!("{} cannot be cast to a fn ptr", operand.layout().ty),
472                     }
473                 }
474                 Rvalue::Cast(CastKind::Pointer(PointerCast::Unsize), operand, _to_ty) => {
475                     let operand = trans_operand(fx, operand);
476                     operand.unsize_value(fx, lval);
477                 }
478                 Rvalue::Discriminant(place) => {
479                     let place = trans_place(fx, place);
480                     let value = place.to_cvalue(fx);
481                     let discr =
482                         crate::discriminant::codegen_get_discriminant(fx, value, dest_layout);
483                     lval.write_cvalue(fx, discr);
484                 }
485                 Rvalue::Repeat(operand, times) => {
486                     let operand = trans_operand(fx, operand);
487                     for i in 0..*times {
488                         let index = fx.bcx.ins().iconst(fx.pointer_type, i as i64);
489                         let to = lval.place_index(fx, index);
490                         to.write_cvalue(fx, operand);
491                     }
492                 }
493                 Rvalue::Len(place) => {
494                     let place = trans_place(fx, place);
495                     let usize_layout = fx.layout_of(fx.tcx.types.usize);
496                     let len = codegen_array_len(fx, place);
497                     lval.write_cvalue(fx, CValue::by_val(len, usize_layout));
498                 }
499                 Rvalue::NullaryOp(NullOp::Box, content_ty) => {
500                     use rustc::middle::lang_items::ExchangeMallocFnLangItem;
501
502                     let usize_type = fx.clif_type(fx.tcx.types.usize).unwrap();
503                     let content_ty = fx.monomorphize(content_ty);
504                     let layout = fx.layout_of(content_ty);
505                     let llsize = fx.bcx.ins().iconst(usize_type, layout.size.bytes() as i64);
506                     let llalign = fx
507                         .bcx
508                         .ins()
509                         .iconst(usize_type, layout.align.abi.bytes() as i64);
510                     let box_layout = fx.layout_of(fx.tcx.mk_box(content_ty));
511
512                     // Allocate space:
513                     let def_id = match fx.tcx.lang_items().require(ExchangeMallocFnLangItem) {
514                         Ok(id) => id,
515                         Err(s) => {
516                             fx.tcx
517                                 .sess
518                                 .fatal(&format!("allocation of `{}` {}", box_layout.ty, s));
519                         }
520                     };
521                     let instance = ty::Instance::mono(fx.tcx, def_id);
522                     let func_ref = fx.get_function_ref(instance);
523                     let call = fx.bcx.ins().call(func_ref, &[llsize, llalign]);
524                     let ptr = fx.bcx.inst_results(call)[0];
525                     lval.write_cvalue(fx, CValue::by_val(ptr, box_layout));
526                 }
527                 Rvalue::NullaryOp(NullOp::SizeOf, ty) => {
528                     assert!(lval
529                         .layout()
530                         .ty
531                         .is_sized(fx.tcx.at(stmt.source_info.span), ParamEnv::reveal_all()));
532                     let ty_size = fx.layout_of(fx.monomorphize(ty)).size.bytes();
533                     let val = CValue::const_val(fx, fx.layout_of(fx.tcx.types.usize), ty_size.into());
534                     lval.write_cvalue(fx, val);
535                 }
536                 Rvalue::Aggregate(kind, operands) => match **kind {
537                     AggregateKind::Array(_ty) => {
538                         for (i, operand) in operands.into_iter().enumerate() {
539                             let operand = trans_operand(fx, operand);
540                             let index = fx.bcx.ins().iconst(fx.pointer_type, i as i64);
541                             let to = lval.place_index(fx, index);
542                             to.write_cvalue(fx, operand);
543                         }
544                     }
545                     _ => unreachable!("shouldn't exist at trans {:?}", to_place_and_rval.1),
546                 },
547             }
548         }
549         StatementKind::StorageLive(_)
550         | StatementKind::StorageDead(_)
551         | StatementKind::Nop
552         | StatementKind::FakeRead(..)
553         | StatementKind::Retag { .. }
554         | StatementKind::AscribeUserType(..) => {}
555
556         StatementKind::InlineAsm(asm) => {
557             use syntax::ast::Name;
558             let InlineAsm {
559                 asm,
560                 outputs: _,
561                 inputs: _,
562             } = &**asm;
563             let rustc_hir::InlineAsmInner {
564                 asm: asm_code, // Name
565                 outputs,       // Vec<Name>
566                 inputs,        // Vec<Name>
567                 clobbers,      // Vec<Name>
568                 volatile,      // bool
569                 alignstack,    // bool
570                 dialect: _,    // syntax::ast::AsmDialect
571                 asm_str_style: _,
572             } = asm;
573             match &*asm_code.as_str() {
574                 "" => {
575                     assert_eq!(inputs, &[Name::intern("r")]);
576                     assert!(outputs.is_empty(), "{:?}", outputs);
577
578                     // Black box
579                 }
580                 "cpuid" | "cpuid\n" => {
581                     assert_eq!(inputs, &[Name::intern("{eax}"), Name::intern("{ecx}")]);
582
583                     assert_eq!(outputs.len(), 4);
584                     for (i, c) in (&["={eax}", "={ebx}", "={ecx}", "={edx}"])
585                         .iter()
586                         .enumerate()
587                     {
588                         assert_eq!(&outputs[i].constraint.as_str(), c);
589                         assert!(!outputs[i].is_rw);
590                         assert!(!outputs[i].is_indirect);
591                     }
592
593                     assert_eq!(clobbers, &[Name::intern("rbx")]);
594
595                     assert!(!volatile);
596                     assert!(!alignstack);
597
598                     crate::trap::trap_unimplemented(
599                         fx,
600                         "__cpuid_count arch intrinsic is not supported",
601                     );
602                 }
603                 "xgetbv" => {
604                     assert_eq!(inputs, &[Name::intern("{ecx}")]);
605
606                     assert_eq!(outputs.len(), 2);
607                     for (i, c) in (&["={eax}", "={edx}"]).iter().enumerate() {
608                         assert_eq!(&outputs[i].constraint.as_str(), c);
609                         assert!(!outputs[i].is_rw);
610                         assert!(!outputs[i].is_indirect);
611                     }
612
613                     assert_eq!(clobbers, &[]);
614
615                     assert!(!volatile);
616                     assert!(!alignstack);
617
618                     crate::trap::trap_unimplemented(fx, "_xgetbv arch intrinsic is not supported");
619                 }
620                 _ if fx.tcx.symbol_name(fx.instance).name.as_str() == "__rust_probestack" => {
621                     crate::trap::trap_unimplemented(fx, "__rust_probestack is not supported");
622                 }
623                 _ => unimpl!("Inline assembly is not supported"),
624             }
625         }
626     }
627 }
628
629 fn codegen_array_len<'tcx>(
630     fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
631     place: CPlace<'tcx>,
632 ) -> Value {
633     match place.layout().ty.kind {
634         ty::Array(_elem_ty, len) => {
635             let len = fx.monomorphize(&len)
636                 .eval(fx.tcx, ParamEnv::reveal_all())
637                 .eval_usize(fx.tcx, ParamEnv::reveal_all()) as i64;
638             fx.bcx.ins().iconst(fx.pointer_type, len)
639         }
640         ty::Slice(_elem_ty) => place
641             .to_ptr_maybe_unsized(fx)
642             .1
643             .expect("Length metadata for slice place"),
644         _ => bug!("Rvalue::Len({:?})", place),
645     }
646 }
647
648 pub fn trans_place<'tcx>(
649     fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
650     place: &Place<'tcx>,
651 ) -> CPlace<'tcx> {
652     let mut cplace = fx.get_local_place(place.local);
653
654     for elem in &*place.projection {
655         match *elem {
656             PlaceElem::Deref => {
657                 cplace = cplace.place_deref(fx);
658             }
659             PlaceElem::Field(field, _ty) => {
660                 cplace = cplace.place_field(fx, field);
661             }
662             PlaceElem::Index(local) => {
663                 let index = fx.get_local_place(local).to_cvalue(fx).load_scalar(fx);
664                 cplace = cplace.place_index(fx, index);
665             }
666             PlaceElem::ConstantIndex {
667                 offset,
668                 min_length: _,
669                 from_end,
670             } => {
671                 let index = if !from_end {
672                     fx.bcx.ins().iconst(fx.pointer_type, offset as i64)
673                 } else {
674                     let len = codegen_array_len(fx, cplace);
675                     fx.bcx.ins().iadd_imm(len, -(offset as i64))
676                 };
677                 cplace = cplace.place_index(fx, index);
678             }
679             PlaceElem::Subslice { from, to, from_end } => {
680                 // These indices are generated by slice patterns.
681                 // slice[from:-to] in Python terms.
682
683                 match cplace.layout().ty.kind {
684                     ty::Array(elem_ty, _len) => {
685                         assert!(!from_end, "array subslices are never `from_end`");
686                         let elem_layout = fx.layout_of(elem_ty);
687                         let ptr = cplace.to_ptr(fx);
688                         cplace = CPlace::for_ptr(
689                             ptr.offset_i64(fx, elem_layout.size.bytes() as i64 * from as i64),
690                             fx.layout_of(fx.tcx.mk_array(elem_ty, to as u64 - from as u64)),
691                         );
692                     }
693                     ty::Slice(elem_ty) => {
694                         assert!(from_end, "slice subslices should be `from_end`");
695                         let elem_layout = fx.layout_of(elem_ty);
696                         let (ptr, len) = cplace.to_ptr_maybe_unsized(fx);
697                         let len = len.unwrap();
698                         cplace = CPlace::for_ptr_with_extra(
699                             ptr.offset_i64(fx, elem_layout.size.bytes() as i64 * from as i64),
700                             fx.bcx.ins().iadd_imm(len, -(from as i64 + to as i64)),
701                             cplace.layout(),
702                         );
703                     }
704                     _ => unreachable!(),
705                 }
706             }
707             PlaceElem::Downcast(_adt_def, variant) => {
708                 cplace = cplace.downcast_variant(fx, variant);
709             }
710         }
711     }
712
713     cplace
714 }
715
716 pub fn trans_operand<'tcx>(
717     fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
718     operand: &Operand<'tcx>,
719 ) -> CValue<'tcx> {
720     match operand {
721         Operand::Move(place) | Operand::Copy(place) => {
722             let cplace = trans_place(fx, place);
723             cplace.to_cvalue(fx)
724         }
725         Operand::Constant(const_) => crate::constant::trans_constant(fx, const_),
726     }
727 }