]> git.lizzy.rs Git - rust.git/blob - src/abi.rs
Rustfmt
[rust.git] / src / abi.rs
1 use std::iter;
2
3 use rustc::hir;
4 use rustc_target::spec::abi::Abi;
5
6 use crate::prelude::*;
7
8 #[derive(Debug)]
9 enum PassMode {
10     NoPass,
11     ByVal(Type),
12     ByRef,
13 }
14
15 impl PassMode {
16     fn get_param_ty(self, fx: &FunctionCx<impl Backend>) -> Type {
17         match self {
18             PassMode::NoPass => unimplemented!("pass mode nopass"),
19             PassMode::ByVal(cton_type) => cton_type,
20             PassMode::ByRef => fx.module.pointer_type(),
21         }
22     }
23 }
24
25 fn get_pass_mode<'a, 'tcx: 'a>(
26     tcx: TyCtxt<'a, 'tcx, 'tcx>,
27     abi: Abi,
28     ty: Ty<'tcx>,
29     is_return: bool,
30 ) -> PassMode {
31     assert!(
32         !tcx.layout_of(ParamEnv::reveal_all().and(ty))
33             .unwrap()
34             .is_unsized()
35     );
36     if ty.sty == tcx.mk_nil().sty {
37         if is_return {
38             //if false {
39             PassMode::NoPass
40         } else {
41             PassMode::ByRef
42         }
43     } else if let Some(ret_ty) = crate::common::cton_type_from_ty(tcx, ty) {
44         PassMode::ByVal(ret_ty)
45     } else {
46         if abi == Abi::C {
47             unimplemented!("Non scalars are not yet supported for \"C\" abi");
48         }
49         PassMode::ByRef
50     }
51 }
52
53 pub fn cton_sig_from_fn_ty<'a, 'tcx: 'a>(
54     tcx: TyCtxt<'a, 'tcx, 'tcx>,
55     fn_ty: Ty<'tcx>,
56 ) -> Signature {
57     let sig = ty_fn_sig(tcx, fn_ty);
58     assert!(!sig.variadic, "Variadic function are not yet supported");
59     let (call_conv, inputs, output): (CallConv, Vec<Ty>, Ty) = match sig.abi {
60         Abi::Rust => (CallConv::Fast, sig.inputs().to_vec(), sig.output()),
61         Abi::C => (CallConv::SystemV, sig.inputs().to_vec(), sig.output()),
62         Abi::RustCall => {
63             assert_eq!(sig.inputs().len(), 2);
64             let extra_args = match sig.inputs().last().unwrap().sty {
65                 ty::Tuple(ref tupled_arguments) => tupled_arguments,
66                 _ => bug!("argument to function with \"rust-call\" ABI is not a tuple"),
67             };
68             let mut inputs: Vec<Ty> = vec![sig.inputs()[0]];
69             inputs.extend(extra_args.into_iter());
70             (CallConv::Fast, inputs, sig.output())
71         }
72         Abi::System => bug!("system abi should be selected elsewhere"),
73         Abi::RustIntrinsic => (CallConv::SystemV, sig.inputs().to_vec(), sig.output()),
74         _ => unimplemented!("unsupported abi {:?}", sig.abi),
75     };
76
77     let inputs = inputs
78         .into_iter()
79         .filter_map(|ty| match get_pass_mode(tcx, sig.abi, ty, false) {
80             PassMode::ByVal(cton_ty) => Some(cton_ty),
81             PassMode::NoPass => unimplemented!("pass mode nopass"),
82             PassMode::ByRef => Some(pointer_ty(tcx)),
83         });
84
85     let (params, returns) = match get_pass_mode(tcx, sig.abi, output, true) {
86         PassMode::NoPass => (inputs.map(AbiParam::new).collect(), vec![]),
87         PassMode::ByVal(ret_ty) => (
88             inputs.map(AbiParam::new).collect(),
89             vec![AbiParam::new(ret_ty)],
90         ),
91         PassMode::ByRef => {
92             (
93                 Some(pointer_ty(tcx)) // First param is place to put return val
94                     .into_iter()
95                     .chain(inputs)
96                     .map(AbiParam::new)
97                     .collect(),
98                 vec![],
99             )
100         }
101     };
102
103     Signature {
104         params,
105         returns,
106         call_conv,
107     }
108 }
109
110 fn ty_fn_sig<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, ty: Ty<'tcx>) -> ty::FnSig<'tcx> {
111     let sig = match ty.sty {
112         ty::FnDef(..) |
113         // Shims currently have type TyFnPtr. Not sure this should remain.
114         ty::FnPtr(_) => ty.fn_sig(tcx),
115         ty::Closure(def_id, substs) => {
116             let sig = substs.closure_sig(def_id, tcx);
117
118             let env_ty = tcx.closure_env_ty(def_id, substs).unwrap();
119             sig.map_bound(|sig| tcx.mk_fn_sig(
120                 iter::once(*env_ty.skip_binder()).chain(sig.inputs().iter().cloned()),
121                 sig.output(),
122                 sig.variadic,
123                 sig.unsafety,
124                 sig.abi
125             ))
126         }
127         ty::Generator(def_id, substs, _) => {
128             let sig = substs.poly_sig(def_id, tcx);
129
130             let env_region = ty::ReLateBound(ty::INNERMOST, ty::BrEnv);
131             let env_ty = tcx.mk_mut_ref(tcx.mk_region(env_region), ty);
132
133             sig.map_bound(|sig| {
134                 let state_did = tcx.lang_items().gen_state().unwrap();
135                 let state_adt_ref = tcx.adt_def(state_did);
136                 let state_substs = tcx.intern_substs(&[
137                     sig.yield_ty.into(),
138                     sig.return_ty.into(),
139                 ]);
140                 let ret_ty = tcx.mk_adt(state_adt_ref, state_substs);
141
142                 tcx.mk_fn_sig(iter::once(env_ty),
143                     ret_ty,
144                     false,
145                     hir::Unsafety::Normal,
146                     Abi::Rust
147                 )
148             })
149         }
150         _ => bug!("unexpected type {:?} to ty_fn_sig", ty)
151     };
152     tcx.normalize_erasing_late_bound_regions(ParamEnv::reveal_all(), &sig)
153 }
154
155 pub fn get_function_name_and_sig<'a, 'tcx>(
156     tcx: TyCtxt<'a, 'tcx, 'tcx>,
157     inst: Instance<'tcx>,
158 ) -> (String, Signature) {
159     assert!(!inst.substs.needs_infer() && !inst.substs.has_param_types());
160     let fn_ty = inst.ty(tcx);
161     let sig = cton_sig_from_fn_ty(tcx, fn_ty);
162     (tcx.symbol_name(inst).as_str().to_string(), sig)
163 }
164
165 impl<'a, 'tcx: 'a, B: Backend + 'a> FunctionCx<'a, 'tcx, B> {
166     /// Instance must be monomorphized
167     pub fn get_function_ref(&mut self, inst: Instance<'tcx>) -> FuncRef {
168         let (name, sig) = get_function_name_and_sig(self.tcx, inst);
169         let func_id = self
170             .module
171             .declare_function(&name, Linkage::Import, &sig)
172             .unwrap();
173         self.module
174             .declare_func_in_func(func_id, &mut self.bcx.func)
175     }
176
177     fn lib_call(
178         &mut self,
179         name: &str,
180         input_tys: Vec<types::Type>,
181         output_ty: Option<types::Type>,
182         args: &[Value],
183     ) -> Option<Value> {
184         let sig = Signature {
185             params: input_tys.iter().cloned().map(AbiParam::new).collect(),
186             returns: output_ty
187                 .map(|output_ty| vec![AbiParam::new(output_ty)])
188                 .unwrap_or(Vec::new()),
189             call_conv: CallConv::SystemV,
190         };
191         let func_id = self
192             .module
193             .declare_function(&name, Linkage::Import, &sig)
194             .unwrap();
195         let func_ref = self
196             .module
197             .declare_func_in_func(func_id, &mut self.bcx.func);
198         let call_inst = self.bcx.ins().call(func_ref, args);
199         if output_ty.is_none() {
200             return None;
201         }
202         let results = self.bcx.inst_results(call_inst);
203         assert_eq!(results.len(), 1);
204         Some(results[0])
205     }
206
207     pub fn easy_call(
208         &mut self,
209         name: &str,
210         args: &[CValue<'tcx>],
211         return_ty: Ty<'tcx>,
212     ) -> CValue<'tcx> {
213         let (input_tys, args): (Vec<_>, Vec<_>) = args
214             .into_iter()
215             .map(|arg| {
216                 (
217                     self.cton_type(arg.layout().ty).unwrap(),
218                     arg.load_value(self),
219                 )
220             }).unzip();
221         let return_layout = self.layout_of(return_ty);
222         let return_ty = if let ty::Tuple(tup) = return_ty.sty {
223             if !tup.is_empty() {
224                 bug!("easy_call( (...) -> <non empty tuple> ) is not allowed");
225             }
226             None
227         } else {
228             Some(self.cton_type(return_ty).unwrap())
229         };
230         if let Some(val) = self.lib_call(name, input_tys, return_ty, &args) {
231             CValue::ByVal(val, return_layout)
232         } else {
233             CValue::ByRef(
234                 self.bcx.ins().iconst(self.module.pointer_type(), 0),
235                 return_layout,
236             )
237         }
238     }
239
240     fn self_sig(&self) -> FnSig<'tcx> {
241         ty_fn_sig(self.tcx, self.instance.ty(self.tcx))
242     }
243
244     fn return_type(&self) -> Ty<'tcx> {
245         self.self_sig().output()
246     }
247 }
248
249 pub fn codegen_fn_prelude<'a, 'tcx: 'a>(
250     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
251     start_ebb: Ebb,
252 ) {
253     let ssa_analyzed = crate::analyze::analyze(fx);
254
255     let ret_layout = fx.layout_of(fx.return_type());
256     let output_pass_mode = get_pass_mode(fx.tcx, fx.self_sig().abi, fx.return_type(), true);
257     let ret_param = match output_pass_mode {
258         PassMode::NoPass => None,
259         PassMode::ByVal(_) => None,
260         PassMode::ByRef => Some(fx.bcx.append_ebb_param(start_ebb, fx.module.pointer_type())),
261     };
262
263     enum ArgKind {
264         Normal(Value),
265         Spread(Vec<Value>),
266     }
267
268     let func_params = fx
269         .mir
270         .args_iter()
271         .map(|local| {
272             let arg_ty = fx.monomorphize(&fx.mir.local_decls[local].ty);
273
274             // Adapted from https://github.com/rust-lang/rust/blob/145155dc96757002c7b2e9de8489416e2fdbbd57/src/librustc_codegen_llvm/mir/mod.rs#L442-L482
275             if Some(local) == fx.mir.spread_arg {
276                 // This argument (e.g. the last argument in the "rust-call" ABI)
277                 // is a tuple that was spread at the ABI level and now we have
278                 // to reconstruct it into a tuple local variable, from multiple
279                 // individual function arguments.
280
281                 let tupled_arg_tys = match arg_ty.sty {
282                     ty::Tuple(ref tys) => tys,
283                     _ => bug!("spread argument isn't a tuple?! but {:?}", arg_ty),
284                 };
285
286                 let mut ebb_params = Vec::new();
287                 for arg_ty in tupled_arg_tys.iter() {
288                     let cton_type =
289                         get_pass_mode(fx.tcx, fx.self_sig().abi, arg_ty, false).get_param_ty(fx);
290                     ebb_params.push(fx.bcx.append_ebb_param(start_ebb, cton_type));
291                 }
292
293                 (local, ArgKind::Spread(ebb_params), arg_ty)
294             } else {
295                 let cton_type =
296                     get_pass_mode(fx.tcx, fx.self_sig().abi, arg_ty, false).get_param_ty(fx);
297                 (
298                     local,
299                     ArgKind::Normal(fx.bcx.append_ebb_param(start_ebb, cton_type)),
300                     arg_ty,
301                 )
302             }
303         }).collect::<Vec<(Local, ArgKind, Ty)>>();
304
305     fx.bcx.switch_to_block(start_ebb);
306
307     fx.top_nop = Some(fx.bcx.ins().nop());
308     fx.add_global_comment(format!("ssa {:?}", ssa_analyzed));
309
310     match output_pass_mode {
311         PassMode::NoPass => {
312             let null = fx.bcx.ins().iconst(fx.module.pointer_type(), 0);
313             //unimplemented!("pass mode nopass");
314             fx.local_map.insert(
315                 RETURN_PLACE,
316                 CPlace::Addr(null, None, fx.layout_of(fx.return_type())),
317             );
318         }
319         PassMode::ByVal(ret_ty) => {
320             fx.bcx.declare_var(mir_var(RETURN_PLACE), ret_ty);
321             fx.local_map
322                 .insert(RETURN_PLACE, CPlace::Var(RETURN_PLACE, ret_layout));
323         }
324         PassMode::ByRef => {
325             fx.local_map.insert(
326                 RETURN_PLACE,
327                 CPlace::Addr(ret_param.unwrap(), None, ret_layout),
328             );
329         }
330     }
331
332     for (local, arg_kind, ty) in func_params {
333         let layout = fx.layout_of(ty);
334
335         if let ArgKind::Normal(ebb_param) = arg_kind {
336             if !ssa_analyzed
337                 .get(&local)
338                 .unwrap()
339                 .contains(crate::analyze::Flags::NOT_SSA)
340             {
341                 fx.bcx
342                     .declare_var(mir_var(local), fx.cton_type(ty).unwrap());
343                 match get_pass_mode(fx.tcx, fx.self_sig().abi, ty, false) {
344                     PassMode::NoPass => unimplemented!("pass mode nopass"),
345                     PassMode::ByVal(_) => fx.bcx.def_var(mir_var(local), ebb_param),
346                     PassMode::ByRef => {
347                         let val = CValue::ByRef(ebb_param, fx.layout_of(ty)).load_value(fx);
348                         fx.bcx.def_var(mir_var(local), val);
349                     }
350                 }
351                 fx.local_map.insert(local, CPlace::Var(local, layout));
352                 continue;
353             }
354         }
355
356         let stack_slot = fx.bcx.create_stack_slot(StackSlotData {
357             kind: StackSlotKind::ExplicitSlot,
358             size: layout.size.bytes() as u32,
359             offset: None,
360         });
361
362         let place = CPlace::from_stack_slot(fx, stack_slot, ty);
363
364         match arg_kind {
365             ArgKind::Normal(ebb_param) => match get_pass_mode(fx.tcx, fx.self_sig().abi, ty, false)
366             {
367                 PassMode::NoPass => unimplemented!("pass mode nopass"),
368                 PassMode::ByVal(_) => {
369                     place.write_cvalue(fx, CValue::ByVal(ebb_param, place.layout()))
370                 }
371                 PassMode::ByRef => place.write_cvalue(fx, CValue::ByRef(ebb_param, place.layout())),
372             },
373             ArgKind::Spread(ebb_params) => {
374                 for (i, ebb_param) in ebb_params.into_iter().enumerate() {
375                     let sub_place = place.place_field(fx, mir::Field::new(i));
376                     match get_pass_mode(fx.tcx, fx.self_sig().abi, sub_place.layout().ty, false) {
377                         PassMode::NoPass => unimplemented!("pass mode nopass"),
378                         PassMode::ByVal(_) => {
379                             sub_place.write_cvalue(fx, CValue::ByVal(ebb_param, sub_place.layout()))
380                         }
381                         PassMode::ByRef => {
382                             sub_place.write_cvalue(fx, CValue::ByRef(ebb_param, sub_place.layout()))
383                         }
384                     }
385                 }
386             }
387         }
388         fx.local_map.insert(local, place);
389     }
390
391     for local in fx.mir.vars_and_temps_iter() {
392         let ty = fx.mir.local_decls[local].ty;
393         let layout = fx.layout_of(ty);
394
395         let place = if ssa_analyzed
396             .get(&local)
397             .unwrap()
398             .contains(crate::analyze::Flags::NOT_SSA)
399         {
400             let stack_slot = fx.bcx.create_stack_slot(StackSlotData {
401                 kind: StackSlotKind::ExplicitSlot,
402                 size: layout.size.bytes() as u32,
403                 offset: None,
404             });
405             CPlace::from_stack_slot(fx, stack_slot, ty)
406         } else {
407             fx.bcx
408                 .declare_var(mir_var(local), fx.cton_type(ty).unwrap());
409             CPlace::Var(local, layout)
410         };
411
412         fx.local_map.insert(local, place);
413     }
414
415     fx.bcx
416         .ins()
417         .jump(*fx.ebb_map.get(&START_BLOCK).unwrap(), &[]);
418 }
419
420 pub fn codegen_call<'a, 'tcx: 'a>(
421     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
422     func: &Operand<'tcx>,
423     args: &[Operand<'tcx>],
424     destination: &Option<(Place<'tcx>, BasicBlock)>,
425 ) {
426     let fn_ty = fx.monomorphize(&func.ty(&fx.mir.local_decls, fx.tcx));
427     let sig = ty_fn_sig(fx.tcx, fn_ty);
428
429     // Unpack arguments tuple for closures
430     let args = if sig.abi == Abi::RustCall {
431         assert_eq!(args.len(), 2, "rust-call abi requires two arguments");
432         let self_arg = trans_operand(fx, &args[0]);
433         let pack_arg = trans_operand(fx, &args[1]);
434         let mut args = Vec::new();
435         args.push(self_arg);
436         match pack_arg.layout().ty.sty {
437             ty::Tuple(ref tupled_arguments) => {
438                 for (i, _) in tupled_arguments.iter().enumerate() {
439                     args.push(pack_arg.value_field(fx, mir::Field::new(i)));
440                 }
441             }
442             _ => bug!("argument to function with \"rust-call\" ABI is not a tuple"),
443         }
444         args
445     } else {
446         args.into_iter()
447             .map(|arg| trans_operand(fx, arg))
448             .collect::<Vec<_>>()
449     };
450
451     let destination = destination
452         .as_ref()
453         .map(|(place, bb)| (trans_place(fx, place), *bb));
454
455     if codegen_intrinsic_call(fx, fn_ty, sig, &args, destination) {
456         return;
457     }
458
459     let ret_layout = fx.layout_of(sig.output());
460
461     let output_pass_mode = get_pass_mode(fx.tcx, sig.abi, sig.output(), true);
462     let return_ptr = match output_pass_mode {
463         PassMode::NoPass => None,
464         PassMode::ByRef => match destination {
465             Some((place, _)) => Some(place.expect_addr()),
466             None => Some(fx.bcx.ins().iconst(fx.module.pointer_type(), 0)),
467         },
468         PassMode::ByVal(_) => None,
469     };
470
471     let call_args: Vec<Value> = return_ptr
472         .into_iter()
473         .chain(args.into_iter().map(|arg| {
474             match get_pass_mode(fx.tcx, sig.abi, arg.layout().ty, false) {
475                 PassMode::NoPass => unimplemented!("pass mode nopass"),
476                 PassMode::ByVal(_) => arg.load_value(fx),
477                 PassMode::ByRef => arg.force_stack(fx),
478             }
479         })).collect::<Vec<_>>();
480
481     let call_inst = match fn_ty.sty {
482         ty::FnDef(def_id, substs) => {
483             let inst = Instance::resolve(fx.tcx, ParamEnv::reveal_all(), def_id, substs).unwrap();
484             let func_ref = fx.get_function_ref(inst);
485             fx.bcx.ins().call(func_ref, &call_args)
486         }
487         ty::FnPtr(_) => {
488             let func = trans_operand(fx, func);
489             let func = func.load_value(fx);
490             let sig = fx.bcx.import_signature(cton_sig_from_fn_ty(fx.tcx, fn_ty));
491             fx.bcx.ins().call_indirect(sig, func, &call_args)
492         }
493         _ => bug!("{:?}", fn_ty),
494     };
495
496     match output_pass_mode {
497         PassMode::NoPass => {}
498         PassMode::ByVal(_) => {
499             if let Some((ret_place, _)) = destination {
500                 let results = fx.bcx.inst_results(call_inst);
501                 ret_place.write_cvalue(fx, CValue::ByVal(results[0], ret_layout));
502             }
503         }
504         PassMode::ByRef => {}
505     }
506     if let Some((_, dest)) = destination {
507         let ret_ebb = fx.get_ebb(dest);
508         fx.bcx.ins().jump(ret_ebb, &[]);
509     } else {
510         fx.bcx.ins().trap(TrapCode::User(!0));
511     }
512 }
513
514 pub fn codegen_return(fx: &mut FunctionCx<impl Backend>) {
515     match get_pass_mode(fx.tcx, fx.self_sig().abi, fx.return_type(), true) {
516         PassMode::NoPass | PassMode::ByRef => {
517             fx.bcx.ins().return_(&[]);
518         }
519         PassMode::ByVal(_) => {
520             let place = fx.get_local_place(RETURN_PLACE);
521             let ret_val = place.to_cvalue(fx).load_value(fx);
522             fx.bcx.ins().return_(&[ret_val]);
523         }
524     }
525 }
526
527 fn codegen_intrinsic_call<'a, 'tcx: 'a>(
528     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
529     fn_ty: Ty<'tcx>,
530     sig: FnSig<'tcx>,
531     args: &[CValue<'tcx>],
532     destination: Option<(CPlace<'tcx>, BasicBlock)>,
533 ) -> bool {
534     if let ty::FnDef(def_id, substs) = fn_ty.sty {
535         if sig.abi == Abi::RustIntrinsic {
536             let intrinsic = fx.tcx.item_name(def_id).as_str();
537             let intrinsic = &intrinsic[..];
538
539             let ret = match destination {
540                 Some((place, _)) => place,
541                 None => {
542                     // Insert non returning intrinsics here
543                     match intrinsic {
544                         "abort" => {
545                             fx.bcx.ins().trap(TrapCode::User(!0 - 1));
546                         }
547                         "unreachable" => {
548                             fx.bcx.ins().trap(TrapCode::User(!0 - 1));
549                         }
550                         _ => unimplemented!("unsupported instrinsic {}", intrinsic),
551                     }
552                     return true;
553                 }
554             };
555
556             let nil_ty = fx.tcx.mk_nil();
557             let u64_layout = fx.layout_of(fx.tcx.types.u64);
558             let usize_layout = fx.layout_of(fx.tcx.types.usize);
559
560             match intrinsic {
561                 "assume" => {
562                     assert_eq!(args.len(), 1);
563                 }
564                 "arith_offset" => {
565                     assert_eq!(args.len(), 2);
566                     let base = args[0].load_value(fx);
567                     let offset = args[1].load_value(fx);
568                     let res = fx.bcx.ins().iadd(base, offset);
569                     let res = CValue::ByVal(res, ret.layout());
570                     ret.write_cvalue(fx, res);
571                 }
572                 "likely" | "unlikely" => {
573                     assert_eq!(args.len(), 1);
574                     ret.write_cvalue(fx, args[0]);
575                 }
576                 "copy" | "copy_nonoverlapping" => {
577                     let elem_ty = substs.type_at(0);
578                     let elem_size: u64 = fx.layout_of(elem_ty).size.bytes();
579                     let elem_size = fx
580                         .bcx
581                         .ins()
582                         .iconst(fx.module.pointer_type(), elem_size as i64);
583                     assert_eq!(args.len(), 3);
584                     let src = args[0];
585                     let dst = args[1];
586                     let count = args[2].load_value(fx);
587                     let byte_amount = fx.bcx.ins().imul(count, elem_size);
588                     fx.easy_call(
589                         "memmove",
590                         &[dst, src, CValue::ByVal(byte_amount, usize_layout)],
591                         nil_ty,
592                     );
593                 }
594                 "discriminant_value" => {
595                     assert_eq!(args.len(), 1);
596                     let discr = crate::base::trans_get_discriminant(fx, args[0], ret.layout());
597                     ret.write_cvalue(fx, discr);
598                 }
599                 "size_of" => {
600                     assert_eq!(args.len(), 0);
601                     let size_of = fx.layout_of(substs.type_at(0)).size.bytes();
602                     let size_of = CValue::const_val(fx, usize_layout.ty, size_of as i64);
603                     ret.write_cvalue(fx, size_of);
604                 }
605                 "size_of_val" => {
606                     assert_eq!(args.len(), 1);
607                     let size = match &substs.type_at(0).sty {
608                         ty::Slice(elem) => {
609                             let len = args[0].load_value_pair(fx).1;
610                             let elem_size = fx.layout_of(elem).size.bytes();
611                             fx.bcx.ins().imul_imm(len, elem_size as i64)
612                         }
613                         ty => unimplemented!("size_of_val for {:?}", ty),
614                     };
615                     ret.write_cvalue(fx, CValue::ByVal(size, usize_layout));
616                 }
617                 "type_id" => {
618                     assert_eq!(args.len(), 0);
619                     let type_id = fx.tcx.type_id_hash(substs.type_at(0));
620                     let type_id = CValue::const_val(fx, u64_layout.ty, type_id as i64);
621                     ret.write_cvalue(fx, type_id);
622                 }
623                 "min_align_of" => {
624                     assert_eq!(args.len(), 0);
625                     let min_align = fx.layout_of(substs.type_at(0)).align.abi();
626                     let min_align = CValue::const_val(fx, usize_layout.ty, min_align as i64);
627                     ret.write_cvalue(fx, min_align);
628                 }
629                 _ if intrinsic.starts_with("unchecked_") => {
630                     assert_eq!(args.len(), 2);
631                     let bin_op = match intrinsic {
632                         "unchecked_div" => BinOp::Div,
633                         "unchecked_rem" => BinOp::Rem,
634                         "unchecked_shl" => BinOp::Shl,
635                         "unchecked_shr" => BinOp::Shr,
636                         _ => unimplemented!("intrinsic {}", intrinsic),
637                     };
638                     let res = match ret.layout().ty.sty {
639                         ty::Uint(_) => crate::base::trans_int_binop(
640                             fx,
641                             bin_op,
642                             args[0],
643                             args[1],
644                             ret.layout().ty,
645                             false,
646                         ),
647                         ty::Int(_) => crate::base::trans_int_binop(
648                             fx,
649                             bin_op,
650                             args[0],
651                             args[1],
652                             ret.layout().ty,
653                             true,
654                         ),
655                         _ => panic!(),
656                     };
657                     ret.write_cvalue(fx, res);
658                 }
659                 _ if intrinsic.ends_with("_with_overflow") => {
660                     assert_eq!(args.len(), 2);
661                     assert_eq!(args[0].layout().ty, args[1].layout().ty);
662                     let bin_op = match intrinsic {
663                         "add_with_overflow" => BinOp::Add,
664                         "sub_with_overflow" => BinOp::Sub,
665                         "mul_with_overflow" => BinOp::Mul,
666                         _ => unimplemented!("intrinsic {}", intrinsic),
667                     };
668                     let res = match args[0].layout().ty.sty {
669                         ty::Uint(_) => crate::base::trans_checked_int_binop(
670                             fx,
671                             bin_op,
672                             args[0],
673                             args[1],
674                             ret.layout().ty,
675                             false,
676                         ),
677                         ty::Int(_) => crate::base::trans_checked_int_binop(
678                             fx,
679                             bin_op,
680                             args[0],
681                             args[1],
682                             ret.layout().ty,
683                             true,
684                         ),
685                         _ => panic!(),
686                     };
687                     ret.write_cvalue(fx, res);
688                 }
689                 _ if intrinsic.starts_with("overflowing_") => {
690                     assert_eq!(args.len(), 2);
691                     assert_eq!(args[0].layout().ty, args[1].layout().ty);
692                     let bin_op = match intrinsic {
693                         "overflowing_add" => BinOp::Add,
694                         "overflowing_sub" => BinOp::Sub,
695                         "overflowing_mul" => BinOp::Mul,
696                         _ => unimplemented!("intrinsic {}", intrinsic),
697                     };
698                     let res = match args[0].layout().ty.sty {
699                         ty::Uint(_) => crate::base::trans_int_binop(
700                             fx,
701                             bin_op,
702                             args[0],
703                             args[1],
704                             ret.layout().ty,
705                             false,
706                         ),
707                         ty::Int(_) => crate::base::trans_int_binop(
708                             fx,
709                             bin_op,
710                             args[0],
711                             args[1],
712                             ret.layout().ty,
713                             true,
714                         ),
715                         _ => panic!(),
716                     };
717                     ret.write_cvalue(fx, res);
718                 }
719                 "offset" => {
720                     assert_eq!(args.len(), 2);
721                     let base = args[0].load_value(fx);
722                     let offset = args[1].load_value(fx);
723                     let res = fx.bcx.ins().iadd(base, offset);
724                     ret.write_cvalue(fx, CValue::ByVal(res, args[0].layout()));
725                 }
726                 "transmute" => {
727                     assert_eq!(args.len(), 1);
728                     let src_ty = substs.type_at(0);
729                     let dst_ty = substs.type_at(1);
730                     assert_eq!(args[0].layout().ty, src_ty);
731                     let addr = args[0].force_stack(fx);
732                     let dst_layout = fx.layout_of(dst_ty);
733                     ret.write_cvalue(fx, CValue::ByRef(addr, dst_layout))
734                 }
735                 "uninit" => {
736                     assert_eq!(args.len(), 0);
737                     let ty = substs.type_at(0);
738                     let layout = fx.layout_of(ty);
739                     let stack_slot = fx.bcx.create_stack_slot(StackSlotData {
740                         kind: StackSlotKind::ExplicitSlot,
741                         size: layout.size.bytes() as u32,
742                         offset: None,
743                     });
744
745                     let uninit_place = CPlace::from_stack_slot(fx, stack_slot, ty);
746                     let uninit_val = uninit_place.to_cvalue(fx);
747                     ret.write_cvalue(fx, uninit_val);
748                 }
749                 "ctlz" | "ctlz_nonzero" => {
750                     assert_eq!(args.len(), 1);
751                     let arg = args[0].load_value(fx);
752                     let res = CValue::ByVal(fx.bcx.ins().clz(arg), args[0].layout());
753                     ret.write_cvalue(fx, res);
754                 }
755                 "cttz" | "cttz_nonzero" => {
756                     assert_eq!(args.len(), 1);
757                     let arg = args[0].load_value(fx);
758                     let res = CValue::ByVal(fx.bcx.ins().clz(arg), args[0].layout());
759                     ret.write_cvalue(fx, res);
760                 }
761                 "ctpop" => {
762                     assert_eq!(args.len(), 1);
763                     let arg = args[0].load_value(fx);
764                     let res = CValue::ByVal(fx.bcx.ins().popcnt(arg), args[0].layout());
765                     ret.write_cvalue(fx, res);
766                 }
767                 _ => unimpl!("unsupported intrinsic {}", intrinsic),
768             }
769
770             if let Some((_, dest)) = destination {
771                 let ret_ebb = fx.get_ebb(dest);
772                 fx.bcx.ins().jump(ret_ebb, &[]);
773             } else {
774                 fx.bcx.ins().trap(TrapCode::User(!0));
775             }
776             return true;
777         }
778     }
779
780     false
781 }