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