]> git.lizzy.rs Git - rust.git/blob - src/abi.rs
Merge branch 'wip_unsized_types'
[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)).into_iter() // First param is place to put return val
94                     .chain(inputs)
95                     .map(AbiParam::new)
96                     .collect(),
97                 vec![],
98             )
99         }
100     };
101
102     Signature {
103         params,
104         returns,
105         call_conv,
106         argument_bytes: None,
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: vec![AbiParam::new(output_ty.unwrap_or(types::VOID))],
187             call_conv: CallConv::SystemV,
188             argument_bytes: None,
189         };
190         let func_id = self
191             .module
192             .declare_function(&name, Linkage::Import, &sig)
193             .unwrap();
194         let func_ref = self
195             .module
196             .declare_func_in_func(func_id, &mut self.bcx.func);
197         let call_inst = self.bcx.ins().call(func_ref, args);
198         if output_ty.is_none() {
199             return None;
200         }
201         let results = self.bcx.inst_results(call_inst);
202         assert_eq!(results.len(), 1);
203         Some(results[0])
204     }
205
206     pub fn easy_call(
207         &mut self,
208         name: &str,
209         args: &[CValue<'tcx>],
210         return_ty: Ty<'tcx>,
211     ) -> CValue<'tcx> {
212         let (input_tys, args): (Vec<_>, Vec<_>) = args
213             .into_iter()
214             .map(|arg| {
215                 (
216                     self.cton_type(arg.layout().ty).unwrap(),
217                     arg.load_value(self),
218                 )
219             }).unzip();
220         let return_layout = self.layout_of(return_ty);
221         let return_ty = if let ty::Tuple(tup) = return_ty.sty {
222             if !tup.is_empty() {
223                 bug!("easy_call( (...) -> <non empty tuple> ) is not allowed");
224             }
225             None
226         } else {
227             Some(self.cton_type(return_ty).unwrap())
228         };
229         if let Some(val) = self.lib_call(name, input_tys, return_ty, &args) {
230             CValue::ByVal(val, return_layout)
231         } else {
232             CValue::ByRef(
233                 self.bcx.ins().iconst(self.module.pointer_type(), 0),
234                 return_layout,
235             )
236         }
237     }
238
239     fn self_sig(&self) -> FnSig<'tcx> {
240         ty_fn_sig(self.tcx, self.instance.ty(self.tcx))
241     }
242
243     fn return_type(&self) -> Ty<'tcx> {
244         self.self_sig().output()
245     }
246 }
247
248 pub fn codegen_fn_prelude<'a, 'tcx: 'a>(
249     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
250     start_ebb: Ebb,
251 ) {
252     let ssa_analyzed = crate::analyze::analyze(fx);
253
254     match fx.self_sig().abi {
255         Abi::Rust | Abi::RustCall => {}
256         _ => unimplemented!("declared function with non \"rust\" or \"rust-call\" abi"),
257     }
258
259     let ret_layout = fx.layout_of(fx.return_type());
260     let output_pass_mode = get_pass_mode(fx.tcx, fx.self_sig().abi, fx.return_type(), true);
261     let ret_param = match output_pass_mode {
262         PassMode::NoPass => None,
263         PassMode::ByVal(_) => None,
264         PassMode::ByRef => Some(fx.bcx.append_ebb_param(start_ebb, fx.module.pointer_type())),
265     };
266
267     enum ArgKind {
268         Normal(Value),
269         Spread(Vec<Value>),
270     }
271
272     let func_params = fx
273         .mir
274         .args_iter()
275         .map(|local| {
276             let arg_ty = fx.monomorphize(&fx.mir.local_decls[local].ty);
277
278             // Adapted from https://github.com/rust-lang/rust/blob/145155dc96757002c7b2e9de8489416e2fdbbd57/src/librustc_codegen_llvm/mir/mod.rs#L442-L482
279             if Some(local) == fx.mir.spread_arg {
280                 // This argument (e.g. the last argument in the "rust-call" ABI)
281                 // is a tuple that was spread at the ABI level and now we have
282                 // to reconstruct it into a tuple local variable, from multiple
283                 // individual function arguments.
284
285                 let tupled_arg_tys = match arg_ty.sty {
286                     ty::Tuple(ref tys) => tys,
287                     _ => bug!("spread argument isn't a tuple?! but {:?}", arg_ty),
288                 };
289
290                 let mut ebb_params = Vec::new();
291                 for arg_ty in tupled_arg_tys.iter() {
292                     let cton_type =
293                         get_pass_mode(fx.tcx, fx.self_sig().abi, arg_ty, false).get_param_ty(fx);
294                     ebb_params.push(fx.bcx.append_ebb_param(start_ebb, cton_type));
295                 }
296
297                 (local, ArgKind::Spread(ebb_params), arg_ty)
298             } else {
299                 let cton_type =
300                     get_pass_mode(fx.tcx, fx.self_sig().abi, arg_ty, false).get_param_ty(fx);
301                 (
302                     local,
303                     ArgKind::Normal(fx.bcx.append_ebb_param(start_ebb, cton_type)),
304                     arg_ty,
305                 )
306             }
307         }).collect::<Vec<(Local, ArgKind, Ty)>>();
308
309     fx.bcx.switch_to_block(start_ebb);
310
311     fx.top_nop = Some(fx.bcx.ins().nop());
312     fx.add_global_comment(format!("ssa {:?}", ssa_analyzed));
313
314     match output_pass_mode {
315         PassMode::NoPass => {
316             let null = fx.bcx.ins().iconst(fx.module.pointer_type(), 0);
317             //unimplemented!("pass mode nopass");
318             fx.local_map.insert(
319                 RETURN_PLACE,
320                 CPlace::Addr(null, None, fx.layout_of(fx.return_type())),
321             );
322         }
323         PassMode::ByVal(ret_ty) => {
324             fx.bcx.declare_var(mir_var(RETURN_PLACE), ret_ty);
325             fx.local_map
326                 .insert(RETURN_PLACE, CPlace::Var(RETURN_PLACE, ret_layout));
327         }
328         PassMode::ByRef => {
329             fx.local_map.insert(
330                 RETURN_PLACE,
331                 CPlace::Addr(ret_param.unwrap(), None, ret_layout),
332             );
333         }
334     }
335
336     for (local, arg_kind, ty) in func_params {
337         let layout = fx.layout_of(ty);
338
339         if let ArgKind::Normal(ebb_param) = arg_kind {
340             if !ssa_analyzed
341                 .get(&local)
342                 .unwrap()
343                 .contains(crate::analyze::Flags::NOT_SSA)
344             {
345                 fx.bcx
346                     .declare_var(mir_var(local), fx.cton_type(ty).unwrap());
347                 match get_pass_mode(fx.tcx, fx.self_sig().abi, ty, false) {
348                     PassMode::NoPass => unimplemented!("pass mode nopass"),
349                     PassMode::ByVal(_) => fx.bcx.def_var(mir_var(local), ebb_param),
350                     PassMode::ByRef => {
351                         let val = CValue::ByRef(ebb_param, fx.layout_of(ty)).load_value(fx);
352                         fx.bcx.def_var(mir_var(local), val);
353                     }
354                 }
355                 fx.local_map.insert(local, CPlace::Var(local, layout));
356                 continue;
357             }
358         }
359
360         let stack_slot = fx.bcx.create_stack_slot(StackSlotData {
361             kind: StackSlotKind::ExplicitSlot,
362             size: layout.size.bytes() as u32,
363             offset: None,
364         });
365
366         let place = CPlace::from_stack_slot(fx, stack_slot, ty);
367
368         match arg_kind {
369             ArgKind::Normal(ebb_param) => match get_pass_mode(fx.tcx, fx.self_sig().abi, ty, false)
370             {
371                 PassMode::NoPass => unimplemented!("pass mode nopass"),
372                 PassMode::ByVal(_) => {
373                     place.write_cvalue(fx, CValue::ByVal(ebb_param, place.layout()))
374                 }
375                 PassMode::ByRef => place.write_cvalue(fx, CValue::ByRef(ebb_param, place.layout())),
376             },
377             ArgKind::Spread(ebb_params) => {
378                 for (i, ebb_param) in ebb_params.into_iter().enumerate() {
379                     let sub_place = place.place_field(fx, mir::Field::new(i));
380                     match get_pass_mode(fx.tcx, fx.self_sig().abi, sub_place.layout().ty, false) {
381                         PassMode::NoPass => unimplemented!("pass mode nopass"),
382                         PassMode::ByVal(_) => {
383                             sub_place.write_cvalue(fx, CValue::ByVal(ebb_param, sub_place.layout()))
384                         }
385                         PassMode::ByRef => {
386                             sub_place.write_cvalue(fx, CValue::ByRef(ebb_param, sub_place.layout()))
387                         }
388                     }
389                 }
390             }
391         }
392         fx.local_map.insert(local, place);
393     }
394
395     for local in fx.mir.vars_and_temps_iter() {
396         let ty = fx.mir.local_decls[local].ty;
397         let layout = fx.layout_of(ty);
398
399         let place = if ssa_analyzed
400             .get(&local)
401             .unwrap()
402             .contains(crate::analyze::Flags::NOT_SSA)
403         {
404             let stack_slot = fx.bcx.create_stack_slot(StackSlotData {
405                 kind: StackSlotKind::ExplicitSlot,
406                 size: layout.size.bytes() as u32,
407                 offset: None,
408             });
409             CPlace::from_stack_slot(fx, stack_slot, ty)
410         } else {
411             fx.bcx
412                 .declare_var(mir_var(local), fx.cton_type(ty).unwrap());
413             CPlace::Var(local, layout)
414         };
415
416         fx.local_map.insert(local, place);
417     }
418
419     fx.bcx
420         .ins()
421         .jump(*fx.ebb_map.get(&START_BLOCK).unwrap(), &[]);
422 }
423
424 pub fn codegen_call<'a, 'tcx: 'a>(
425     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
426     func: &Operand<'tcx>,
427     args: &[Operand<'tcx>],
428     destination: &Option<(Place<'tcx>, BasicBlock)>,
429 ) {
430     let fn_ty = fx.monomorphize(&func.ty(&fx.mir.local_decls, fx.tcx));
431     let sig = ty_fn_sig(fx.tcx, fn_ty);
432
433     // Unpack arguments tuple for closures
434     let args = if sig.abi == Abi::RustCall {
435         assert_eq!(args.len(), 2, "rust-call abi requires two arguments");
436         let self_arg = trans_operand(fx, &args[0]);
437         let pack_arg = trans_operand(fx, &args[1]);
438         let mut args = Vec::new();
439         args.push(self_arg);
440         match pack_arg.layout().ty.sty {
441             ty::Tuple(ref tupled_arguments) => {
442                 for (i, _) in tupled_arguments.iter().enumerate() {
443                     args.push(pack_arg.value_field(fx, mir::Field::new(i)));
444                 }
445             }
446             _ => bug!("argument to function with \"rust-call\" ABI is not a tuple"),
447         }
448         args
449     } else {
450         args.into_iter()
451             .map(|arg| trans_operand(fx, arg))
452             .collect::<Vec<_>>()
453     };
454
455     let destination = destination
456         .as_ref()
457         .map(|(place, bb)| (trans_place(fx, place), *bb));
458
459     if codegen_intrinsic_call(fx, fn_ty, sig, &args, destination) {
460         return;
461     }
462
463     let ret_layout = fx.layout_of(sig.output());
464
465     let output_pass_mode = get_pass_mode(fx.tcx, sig.abi, sig.output(), true);
466     let return_ptr = match output_pass_mode {
467         PassMode::NoPass => None,
468         PassMode::ByRef => match destination {
469             Some((place, _)) => Some(place.expect_addr()),
470             None => Some(fx.bcx.ins().iconst(fx.module.pointer_type(), 0)),
471         },
472         PassMode::ByVal(_) => None,
473     };
474
475     let call_args: Vec<Value> = return_ptr
476         .into_iter()
477         .chain(args.into_iter().map(|arg| {
478             match get_pass_mode(fx.tcx, sig.abi, arg.layout().ty, false) {
479                 PassMode::NoPass => unimplemented!("pass mode nopass"),
480                 PassMode::ByVal(_) => arg.load_value(fx),
481                 PassMode::ByRef => arg.force_stack(fx),
482             }
483         })).collect::<Vec<_>>();
484
485     let call_inst = match fn_ty.sty {
486         ty::FnDef(def_id, substs) => {
487             let func_ref = fx.get_function_ref(
488                 Instance::resolve(fx.tcx, ParamEnv::reveal_all(), def_id, substs).unwrap(),
489             );
490             fx.bcx.ins().call(func_ref, &call_args)
491         }
492         _ => {
493             let func = trans_operand(fx, func);
494             let func = func.load_value(fx);
495             let sig = fx.bcx.import_signature(cton_sig_from_fn_ty(fx.tcx, fn_ty));
496             fx.bcx.ins().call_indirect(sig, func, &call_args)
497         }
498     };
499
500     match output_pass_mode {
501         PassMode::NoPass => {}
502         PassMode::ByVal(_) => {
503             if let Some((ret_place, _)) = destination {
504                 let results = fx.bcx.inst_results(call_inst);
505                 ret_place.write_cvalue(fx, CValue::ByVal(results[0], ret_layout));
506             }
507         }
508         PassMode::ByRef => {}
509     }
510     if let Some((_, dest)) = destination {
511         let ret_ebb = fx.get_ebb(dest);
512         fx.bcx.ins().jump(ret_ebb, &[]);
513     } else {
514         fx.bcx.ins().trap(TrapCode::User(!0));
515     }
516 }
517
518 pub fn codegen_return(fx: &mut FunctionCx<impl Backend>) {
519     match get_pass_mode(fx.tcx, fx.self_sig().abi, fx.return_type(), true) {
520         PassMode::NoPass | PassMode::ByRef => {
521             fx.bcx.ins().return_(&[]);
522         }
523         PassMode::ByVal(_) => {
524             let place = fx.get_local_place(RETURN_PLACE);
525             let ret_val = place.to_cvalue(fx).load_value(fx);
526             fx.bcx.ins().return_(&[ret_val]);
527         }
528     }
529 }
530
531 fn codegen_intrinsic_call<'a, 'tcx: 'a>(
532     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
533     fn_ty: Ty<'tcx>,
534     sig: FnSig<'tcx>,
535     args: &[CValue<'tcx>],
536     destination: Option<(CPlace<'tcx>, BasicBlock)>,
537 ) -> bool {
538     if let ty::FnDef(def_id, substs) = fn_ty.sty {
539         if sig.abi == Abi::RustIntrinsic {
540             let intrinsic = fx.tcx.item_name(def_id).as_str();
541             let intrinsic = &intrinsic[..];
542
543             let ret = match destination {
544                 Some((place, _)) => place,
545                 None => {
546                     // Insert non returning intrinsics here
547                     match intrinsic {
548                         "abort" => {
549                             fx.bcx.ins().trap(TrapCode::User(!0 - 1));
550                         }
551                         "unreachable" => {
552                             fx.bcx.ins().trap(TrapCode::User(!0 - 1));
553                         }
554                         _ => unimplemented!("unsupported instrinsic {}", intrinsic),
555                     }
556                     return true;
557                 }
558             };
559
560             let nil_ty = fx.tcx.mk_nil();
561             let u64_layout = fx.layout_of(fx.tcx.types.u64);
562             let usize_layout = fx.layout_of(fx.tcx.types.usize);
563
564             match intrinsic {
565                 "assume" => {
566                     assert_eq!(args.len(), 1);
567                 }
568                 "arith_offset" => {
569                     assert_eq!(args.len(), 2);
570                     let base = args[0].load_value(fx);
571                     let offset = args[1].load_value(fx);
572                     let res = fx.bcx.ins().iadd(base, offset);
573                     let res = CValue::ByVal(res, ret.layout());
574                     ret.write_cvalue(fx, res);
575                 }
576                 "likely" | "unlikely" => {
577                     assert_eq!(args.len(), 1);
578                     ret.write_cvalue(fx, args[0]);
579                 }
580                 "copy" | "copy_nonoverlapping" => {
581                     let elem_ty = substs.type_at(0);
582                     let elem_size: u64 = fx.layout_of(elem_ty).size.bytes();
583                     let elem_size = fx
584                         .bcx
585                         .ins()
586                         .iconst(fx.module.pointer_type(), elem_size as i64);
587                     assert_eq!(args.len(), 3);
588                     let src = args[0];
589                     let dst = args[1];
590                     let count = args[2].load_value(fx);
591                     let byte_amount = fx.bcx.ins().imul(count, elem_size);
592                     fx.easy_call(
593                         "memmove",
594                         &[dst, src, CValue::ByVal(byte_amount, usize_layout)],
595                         nil_ty,
596                     );
597                 }
598                 "discriminant_value" => {
599                     assert_eq!(args.len(), 1);
600                     let discr = crate::base::trans_get_discriminant(fx, args[0], ret.layout());
601                     ret.write_cvalue(fx, discr);
602                 }
603                 "size_of" => {
604                     assert_eq!(args.len(), 0);
605                     let size_of = fx.layout_of(substs.type_at(0)).size.bytes();
606                     let size_of = CValue::const_val(fx, usize_layout.ty, size_of as i64);
607                     ret.write_cvalue(fx, size_of);
608                 }
609                 "type_id" => {
610                     assert_eq!(args.len(), 0);
611                     let type_id = fx.tcx.type_id_hash(substs.type_at(0));
612                     let type_id = CValue::const_val(fx, u64_layout.ty, type_id as i64);
613                     ret.write_cvalue(fx, type_id);
614                 }
615                 "min_align_of" => {
616                     assert_eq!(args.len(), 0);
617                     let min_align = fx.layout_of(substs.type_at(0)).align.abi();
618                     let min_align = CValue::const_val(fx, usize_layout.ty, min_align as i64);
619                     ret.write_cvalue(fx, min_align);
620                 }
621                 _ if intrinsic.starts_with("unchecked_") => {
622                     assert_eq!(args.len(), 2);
623                     let bin_op = match intrinsic {
624                         "unchecked_div" => BinOp::Div,
625                         "unchecked_rem" => BinOp::Rem,
626                         "unchecked_shl" => BinOp::Shl,
627                         "unchecked_shr" => BinOp::Shr,
628                         _ => unimplemented!("intrinsic {}", intrinsic),
629                     };
630                     let res = match ret.layout().ty.sty {
631                         ty::Uint(_) => crate::base::trans_int_binop(
632                             fx,
633                             bin_op,
634                             args[0],
635                             args[1],
636                             ret.layout().ty,
637                             false,
638                         ),
639                         ty::Int(_) => crate::base::trans_int_binop(
640                             fx,
641                             bin_op,
642                             args[0],
643                             args[1],
644                             ret.layout().ty,
645                             true,
646                         ),
647                         _ => panic!(),
648                     };
649                     ret.write_cvalue(fx, res);
650                 }
651                 _ if intrinsic.ends_with("_with_overflow") => {
652                     assert_eq!(args.len(), 2);
653                     assert_eq!(args[0].layout().ty, args[1].layout().ty);
654                     let bin_op = match intrinsic {
655                         "add_with_overflow" => BinOp::Add,
656                         "sub_with_overflow" => BinOp::Sub,
657                         "mul_with_overflow" => BinOp::Mul,
658                         _ => unimplemented!("intrinsic {}", intrinsic),
659                     };
660                     let res = match args[0].layout().ty.sty {
661                         ty::Uint(_) => crate::base::trans_checked_int_binop(
662                             fx,
663                             bin_op,
664                             args[0],
665                             args[1],
666                             ret.layout().ty,
667                             false,
668                         ),
669                         ty::Int(_) => crate::base::trans_checked_int_binop(
670                             fx,
671                             bin_op,
672                             args[0],
673                             args[1],
674                             ret.layout().ty,
675                             true,
676                         ),
677                         _ => panic!(),
678                     };
679                     ret.write_cvalue(fx, res);
680                 }
681                 _ if intrinsic.starts_with("overflowing_") => {
682                     assert_eq!(args.len(), 2);
683                     assert_eq!(args[0].layout().ty, args[1].layout().ty);
684                     let bin_op = match intrinsic {
685                         "overflowing_add" => BinOp::Add,
686                         "overflowing_sub" => BinOp::Sub,
687                         "overflowing_mul" => BinOp::Mul,
688                         _ => unimplemented!("intrinsic {}", intrinsic),
689                     };
690                     let res = match args[0].layout().ty.sty {
691                         ty::Uint(_) => crate::base::trans_int_binop(
692                             fx,
693                             bin_op,
694                             args[0],
695                             args[1],
696                             ret.layout().ty,
697                             false,
698                         ),
699                         ty::Int(_) => crate::base::trans_int_binop(
700                             fx,
701                             bin_op,
702                             args[0],
703                             args[1],
704                             ret.layout().ty,
705                             true,
706                         ),
707                         _ => panic!(),
708                     };
709                     ret.write_cvalue(fx, res);
710                 }
711                 "offset" => {
712                     assert_eq!(args.len(), 2);
713                     let base = args[0].load_value(fx);
714                     let offset = args[1].load_value(fx);
715                     let res = fx.bcx.ins().iadd(base, offset);
716                     ret.write_cvalue(fx, CValue::ByVal(res, args[0].layout()));
717                 }
718                 "transmute" => {
719                     assert_eq!(args.len(), 1);
720                     let src_ty = substs.type_at(0);
721                     let dst_ty = substs.type_at(1);
722                     assert_eq!(args[0].layout().ty, src_ty);
723                     let addr = args[0].force_stack(fx);
724                     let dst_layout = fx.layout_of(dst_ty);
725                     ret.write_cvalue(fx, CValue::ByRef(addr, dst_layout))
726                 }
727                 "uninit" => {
728                     assert_eq!(args.len(), 0);
729                     let ty = substs.type_at(0);
730                     let layout = fx.layout_of(ty);
731                     let stack_slot = fx.bcx.create_stack_slot(StackSlotData {
732                         kind: StackSlotKind::ExplicitSlot,
733                         size: layout.size.bytes() as u32,
734                         offset: None,
735                     });
736
737                     let uninit_place = CPlace::from_stack_slot(fx, stack_slot, ty);
738                     let uninit_val = uninit_place.to_cvalue(fx);
739                     ret.write_cvalue(fx, uninit_val);
740                 }
741                 "ctlz" | "ctlz_nonzero" => {
742                     assert_eq!(args.len(), 1);
743                     let arg = args[0].load_value(fx);
744                     let res = CValue::ByVal(fx.bcx.ins().clz(arg), args[0].layout());
745                     ret.write_cvalue(fx, res);
746                 }
747                 "cttz" | "cttz_nonzero" => {
748                     assert_eq!(args.len(), 1);
749                     let arg = args[0].load_value(fx);
750                     let res = CValue::ByVal(fx.bcx.ins().clz(arg), args[0].layout());
751                     ret.write_cvalue(fx, res);
752                 }
753                 "ctpop" => {
754                     assert_eq!(args.len(), 1);
755                     let arg = args[0].load_value(fx);
756                     let res = CValue::ByVal(fx.bcx.ins().popcnt(arg), args[0].layout());
757                     ret.write_cvalue(fx, res);
758                 }
759                 _ => unimpl!("unsupported intrinsic {}", intrinsic),
760             }
761
762             if let Some((_, dest)) = destination {
763                 let ret_ebb = fx.get_ebb(dest);
764                 fx.bcx.ins().jump(ret_ebb, &[]);
765             } else {
766                 fx.bcx.ins().trap(TrapCode::User(!0));
767             }
768             return true;
769         }
770     }
771
772     false
773 }