]> git.lizzy.rs Git - rust.git/blob - src/librustc_codegen_llvm/intrinsic.rs
Transfered memcpy and memset to BuilderMethods
[rust.git] / src / librustc_codegen_llvm / intrinsic.rs
1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 #![allow(non_upper_case_globals)]
12
13 use attributes;
14 use intrinsics::{self, Intrinsic};
15 use llvm;
16 use llvm_util;
17 use abi::{Abi, FnType, LlvmType, PassMode};
18 use mir::place::PlaceRef;
19 use mir::operand::{OperandRef, OperandValue};
20 use base::*;
21 use common::*;
22 use context::CodegenCx;
23 use declare;
24 use glue;
25 use type_::Type;
26 use type_of::LayoutLlvmExt;
27 use rustc::ty::{self, Ty};
28 use rustc::ty::layout::LayoutOf;
29 use rustc::hir;
30 use syntax::ast;
31 use syntax::symbol::Symbol;
32 use builder::{Builder, MemFlags};
33 use value::Value;
34
35 use interfaces::{
36     BuilderMethods, ConstMethods, BaseTypeMethods, DerivedTypeMethods, DerivedIntrinsicMethods,
37     StaticMethods,
38 };
39
40 use rustc::session::Session;
41 use syntax_pos::Span;
42
43 use std::cmp::Ordering;
44 use std::iter;
45
46 fn get_simple_intrinsic(cx: &CodegenCx<'ll, '_>, name: &str) -> Option<&'ll Value> {
47     let llvm_name = match name {
48         "sqrtf32" => "llvm.sqrt.f32",
49         "sqrtf64" => "llvm.sqrt.f64",
50         "powif32" => "llvm.powi.f32",
51         "powif64" => "llvm.powi.f64",
52         "sinf32" => "llvm.sin.f32",
53         "sinf64" => "llvm.sin.f64",
54         "cosf32" => "llvm.cos.f32",
55         "cosf64" => "llvm.cos.f64",
56         "powf32" => "llvm.pow.f32",
57         "powf64" => "llvm.pow.f64",
58         "expf32" => "llvm.exp.f32",
59         "expf64" => "llvm.exp.f64",
60         "exp2f32" => "llvm.exp2.f32",
61         "exp2f64" => "llvm.exp2.f64",
62         "logf32" => "llvm.log.f32",
63         "logf64" => "llvm.log.f64",
64         "log10f32" => "llvm.log10.f32",
65         "log10f64" => "llvm.log10.f64",
66         "log2f32" => "llvm.log2.f32",
67         "log2f64" => "llvm.log2.f64",
68         "fmaf32" => "llvm.fma.f32",
69         "fmaf64" => "llvm.fma.f64",
70         "fabsf32" => "llvm.fabs.f32",
71         "fabsf64" => "llvm.fabs.f64",
72         "copysignf32" => "llvm.copysign.f32",
73         "copysignf64" => "llvm.copysign.f64",
74         "floorf32" => "llvm.floor.f32",
75         "floorf64" => "llvm.floor.f64",
76         "ceilf32" => "llvm.ceil.f32",
77         "ceilf64" => "llvm.ceil.f64",
78         "truncf32" => "llvm.trunc.f32",
79         "truncf64" => "llvm.trunc.f64",
80         "rintf32" => "llvm.rint.f32",
81         "rintf64" => "llvm.rint.f64",
82         "nearbyintf32" => "llvm.nearbyint.f32",
83         "nearbyintf64" => "llvm.nearbyint.f64",
84         "roundf32" => "llvm.round.f32",
85         "roundf64" => "llvm.round.f64",
86         "assume" => "llvm.assume",
87         "abort" => "llvm.trap",
88         _ => return None
89     };
90     Some(cx.get_intrinsic(&llvm_name))
91 }
92
93 /// Remember to add all intrinsics here, in librustc_typeck/check/mod.rs,
94 /// and in libcore/intrinsics.rs; if you need access to any llvm intrinsics,
95 /// add them to librustc_codegen_llvm/context.rs
96 pub fn codegen_intrinsic_call(
97     bx: &Builder<'a, 'll, 'tcx>,
98     callee_ty: Ty<'tcx>,
99     fn_ty: &FnType<'tcx, Ty<'tcx>>,
100     args: &[OperandRef<'tcx, &'ll Value>],
101     llresult: &'ll Value,
102     span: Span,
103 ) {
104     let cx = bx.cx();
105     let tcx = cx.tcx;
106
107     let (def_id, substs) = match callee_ty.sty {
108         ty::FnDef(def_id, substs) => (def_id, substs),
109         _ => bug!("expected fn item type, found {}", callee_ty)
110     };
111
112     let sig = callee_ty.fn_sig(tcx);
113     let sig = tcx.normalize_erasing_late_bound_regions(ty::ParamEnv::reveal_all(), &sig);
114     let arg_tys = sig.inputs();
115     let ret_ty = sig.output();
116     let name = &*tcx.item_name(def_id).as_str();
117
118     let llret_ty = cx.layout_of(ret_ty).llvm_type(cx);
119     let result = PlaceRef::new_sized(llresult, fn_ty.ret.layout, fn_ty.ret.layout.align);
120
121     let simple = get_simple_intrinsic(cx, name);
122     let llval = match name {
123         _ if simple.is_some() => {
124             bx.call(simple.unwrap(),
125                     &args.iter().map(|arg| arg.immediate()).collect::<Vec<_>>(),
126                     None)
127         }
128         "unreachable" => {
129             return;
130         },
131         "likely" => {
132             let expect = cx.get_intrinsic(&("llvm.expect.i1"));
133             bx.call(expect, &[args[0].immediate(), bx.cx().const_bool(true)], None)
134         }
135         "unlikely" => {
136             let expect = cx.get_intrinsic(&("llvm.expect.i1"));
137             bx.call(expect, &[args[0].immediate(), bx.cx().const_bool(false)], None)
138         }
139         "try" => {
140             try_intrinsic(bx, cx,
141                           args[0].immediate(),
142                           args[1].immediate(),
143                           args[2].immediate(),
144                           llresult);
145             return;
146         }
147         "breakpoint" => {
148             let llfn = cx.get_intrinsic(&("llvm.debugtrap"));
149             bx.call(llfn, &[], None)
150         }
151         "size_of" => {
152             let tp_ty = substs.type_at(0);
153             cx.const_usize(cx.size_of(tp_ty).bytes())
154         }
155         "size_of_val" => {
156             let tp_ty = substs.type_at(0);
157             if let OperandValue::Pair(_, meta) = args[0].val {
158                 let (llsize, _) =
159                     glue::size_and_align_of_dst(bx, tp_ty, Some(meta));
160                 llsize
161             } else {
162                 cx.const_usize(cx.size_of(tp_ty).bytes())
163             }
164         }
165         "min_align_of" => {
166             let tp_ty = substs.type_at(0);
167             cx.const_usize(cx.align_of(tp_ty).abi())
168         }
169         "min_align_of_val" => {
170             let tp_ty = substs.type_at(0);
171             if let OperandValue::Pair(_, meta) = args[0].val {
172                 let (_, llalign) =
173                     glue::size_and_align_of_dst(bx, tp_ty, Some(meta));
174                 llalign
175             } else {
176                 cx.const_usize(cx.align_of(tp_ty).abi())
177             }
178         }
179         "pref_align_of" => {
180             let tp_ty = substs.type_at(0);
181             cx.const_usize(cx.align_of(tp_ty).pref())
182         }
183         "type_name" => {
184             let tp_ty = substs.type_at(0);
185             let ty_name = Symbol::intern(&tp_ty.to_string()).as_str();
186             cx.const_str_slice(ty_name)
187         }
188         "type_id" => {
189             cx.const_u64(cx.tcx.type_id_hash(substs.type_at(0)))
190         }
191         "init" => {
192             let ty = substs.type_at(0);
193             if !cx.layout_of(ty).is_zst() {
194                 // Just zero out the stack slot.
195                 // If we store a zero constant, LLVM will drown in vreg allocation for large data
196                 // structures, and the generated code will be awful. (A telltale sign of this is
197                 // large quantities of `mov [byte ptr foo],0` in the generated code.)
198                 memset_intrinsic(
199                     bx,
200                     false,
201                     ty,
202                     llresult,
203                     cx.const_u8(0),
204                     cx.const_usize(1)
205                 );
206             }
207             return;
208         }
209         // Effectively no-ops
210         "uninit" | "forget" => {
211             return;
212         }
213         "needs_drop" => {
214             let tp_ty = substs.type_at(0);
215
216             cx.const_bool(bx.cx().type_needs_drop(tp_ty))
217         }
218         "offset" => {
219             let ptr = args[0].immediate();
220             let offset = args[1].immediate();
221             bx.inbounds_gep(ptr, &[offset])
222         }
223         "arith_offset" => {
224             let ptr = args[0].immediate();
225             let offset = args[1].immediate();
226             bx.gep(ptr, &[offset])
227         }
228
229         "copy_nonoverlapping" => {
230             copy_intrinsic(bx, false, false, substs.type_at(0),
231                            args[1].immediate(), args[0].immediate(), args[2].immediate());
232             return;
233         }
234         "copy" => {
235             copy_intrinsic(bx, true, false, substs.type_at(0),
236                            args[1].immediate(), args[0].immediate(), args[2].immediate());
237             return;
238         }
239         "write_bytes" => {
240             memset_intrinsic(bx, false, substs.type_at(0),
241                              args[0].immediate(), args[1].immediate(), args[2].immediate());
242             return;
243         }
244
245         "volatile_copy_nonoverlapping_memory" => {
246             copy_intrinsic(bx, false, true, substs.type_at(0),
247                            args[0].immediate(), args[1].immediate(), args[2].immediate());
248             return;
249         }
250         "volatile_copy_memory" => {
251             copy_intrinsic(bx, true, true, substs.type_at(0),
252                            args[0].immediate(), args[1].immediate(), args[2].immediate());
253             return;
254         }
255         "volatile_set_memory" => {
256             memset_intrinsic(bx, true, substs.type_at(0),
257                              args[0].immediate(), args[1].immediate(), args[2].immediate());
258             return;
259         }
260         "volatile_load" | "unaligned_volatile_load" => {
261             let tp_ty = substs.type_at(0);
262             let mut ptr = args[0].immediate();
263             if let PassMode::Cast(ty) = fn_ty.ret.mode {
264                 ptr = bx.pointercast(ptr, bx.cx().type_ptr_to(ty.llvm_type(cx)));
265             }
266             let load = bx.volatile_load(ptr);
267             let align = if name == "unaligned_volatile_load" {
268                 1
269             } else {
270                 cx.align_of(tp_ty).abi() as u32
271             };
272             unsafe {
273                 llvm::LLVMSetAlignment(load, align);
274             }
275             to_immediate(bx, load, cx.layout_of(tp_ty))
276         },
277         "volatile_store" => {
278             let dst = args[0].deref(bx.cx());
279             args[1].val.volatile_store(bx, dst);
280             return;
281         },
282         "unaligned_volatile_store" => {
283             let dst = args[0].deref(bx.cx());
284             args[1].val.unaligned_volatile_store(bx, dst);
285             return;
286         },
287         "prefetch_read_data" | "prefetch_write_data" |
288         "prefetch_read_instruction" | "prefetch_write_instruction" => {
289             let expect = cx.get_intrinsic(&("llvm.prefetch"));
290             let (rw, cache_type) = match name {
291                 "prefetch_read_data" => (0, 1),
292                 "prefetch_write_data" => (1, 1),
293                 "prefetch_read_instruction" => (0, 0),
294                 "prefetch_write_instruction" => (1, 0),
295                 _ => bug!()
296             };
297             bx.call(expect, &[
298                 args[0].immediate(),
299                 cx.const_i32(rw),
300                 args[1].immediate(),
301                 cx.const_i32(cache_type)
302             ], None)
303         },
304         "ctlz" | "ctlz_nonzero" | "cttz" | "cttz_nonzero" | "ctpop" | "bswap" |
305         "bitreverse" | "add_with_overflow" | "sub_with_overflow" |
306         "mul_with_overflow" | "overflowing_add" | "overflowing_sub" | "overflowing_mul" |
307         "unchecked_div" | "unchecked_rem" | "unchecked_shl" | "unchecked_shr" | "exact_div" |
308         "rotate_left" | "rotate_right" => {
309             let ty = arg_tys[0];
310             match int_type_width_signed(ty, cx) {
311                 Some((width, signed)) =>
312                     match name {
313                         "ctlz" | "cttz" => {
314                             let y = cx.const_bool(false);
315                             let llfn = cx.get_intrinsic(&format!("llvm.{}.i{}", name, width));
316                             bx.call(llfn, &[args[0].immediate(), y], None)
317                         }
318                         "ctlz_nonzero" | "cttz_nonzero" => {
319                             let y = cx.const_bool(true);
320                             let llvm_name = &format!("llvm.{}.i{}", &name[..4], width);
321                             let llfn = cx.get_intrinsic(llvm_name);
322                             bx.call(llfn, &[args[0].immediate(), y], None)
323                         }
324                         "ctpop" => bx.call(cx.get_intrinsic(&format!("llvm.ctpop.i{}", width)),
325                                         &[args[0].immediate()], None),
326                         "bswap" => {
327                             if width == 8 {
328                                 args[0].immediate() // byte swap a u8/i8 is just a no-op
329                             } else {
330                                 bx.call(cx.get_intrinsic(&format!("llvm.bswap.i{}", width)),
331                                         &[args[0].immediate()], None)
332                             }
333                         }
334                         "bitreverse" => {
335                             bx.call(cx.get_intrinsic(&format!("llvm.bitreverse.i{}", width)),
336                                 &[args[0].immediate()], None)
337                         }
338                         "add_with_overflow" | "sub_with_overflow" | "mul_with_overflow" => {
339                             let intrinsic = format!("llvm.{}{}.with.overflow.i{}",
340                                                     if signed { 's' } else { 'u' },
341                                                     &name[..3], width);
342                             let llfn = bx.cx().get_intrinsic(&intrinsic);
343
344                             // Convert `i1` to a `bool`, and write it to the out parameter
345                             let pair = bx.call(llfn, &[
346                                 args[0].immediate(),
347                                 args[1].immediate()
348                             ], None);
349                             let val = bx.extract_value(pair, 0);
350                             let overflow = bx.zext(bx.extract_value(pair, 1), cx.type_bool());
351
352                             let dest = result.project_field(bx, 0);
353                             bx.store(val, dest.llval, dest.align);
354                             let dest = result.project_field(bx, 1);
355                             bx.store(overflow, dest.llval, dest.align);
356
357                             return;
358                         },
359                         "overflowing_add" => bx.add(args[0].immediate(), args[1].immediate()),
360                         "overflowing_sub" => bx.sub(args[0].immediate(), args[1].immediate()),
361                         "overflowing_mul" => bx.mul(args[0].immediate(), args[1].immediate()),
362                         "exact_div" =>
363                             if signed {
364                                 bx.exactsdiv(args[0].immediate(), args[1].immediate())
365                             } else {
366                                 bx.exactudiv(args[0].immediate(), args[1].immediate())
367                             },
368                         "unchecked_div" =>
369                             if signed {
370                                 bx.sdiv(args[0].immediate(), args[1].immediate())
371                             } else {
372                                 bx.udiv(args[0].immediate(), args[1].immediate())
373                             },
374                         "unchecked_rem" =>
375                             if signed {
376                                 bx.srem(args[0].immediate(), args[1].immediate())
377                             } else {
378                                 bx.urem(args[0].immediate(), args[1].immediate())
379                             },
380                         "unchecked_shl" => bx.shl(args[0].immediate(), args[1].immediate()),
381                         "unchecked_shr" =>
382                             if signed {
383                                 bx.ashr(args[0].immediate(), args[1].immediate())
384                             } else {
385                                 bx.lshr(args[0].immediate(), args[1].immediate())
386                             },
387                         "rotate_left" | "rotate_right" => {
388                             let is_left = name == "rotate_left";
389                             let val = args[0].immediate();
390                             let raw_shift = args[1].immediate();
391                             if llvm_util::get_major_version() >= 7 {
392                                 // rotate = funnel shift with first two args the same
393                                 let llvm_name = &format!("llvm.fsh{}.i{}",
394                                                          if is_left { 'l' } else { 'r' }, width);
395                                 let llfn = cx.get_intrinsic(llvm_name);
396                                 bx.call(llfn, &[val, val, raw_shift], None)
397                             } else {
398                                 // rotate_left: (X << (S % BW)) | (X >> ((BW - S) % BW))
399                                 // rotate_right: (X << ((BW - S) % BW)) | (X >> (S % BW))
400                                 let width = cx.const_uint(cx.type_ix(width), width);
401                                 let shift = bx.urem(raw_shift, width);
402                                 let inv_shift = bx.urem(bx.sub(width, raw_shift), width);
403                                 let shift1 = bx.shl(val, if is_left { shift } else { inv_shift });
404                                 let shift2 = bx.lshr(val, if !is_left { shift } else { inv_shift });
405                                 bx.or(shift1, shift2)
406                             }
407                         },
408                         _ => bug!(),
409                     },
410                 None => {
411                     span_invalid_monomorphization_error(
412                         tcx.sess, span,
413                         &format!("invalid monomorphization of `{}` intrinsic: \
414                                   expected basic integer type, found `{}`", name, ty));
415                     return;
416                 }
417             }
418         },
419         "fadd_fast" | "fsub_fast" | "fmul_fast" | "fdiv_fast" | "frem_fast" => {
420             let sty = &arg_tys[0].sty;
421             match float_type_width(sty) {
422                 Some(_width) =>
423                     match name {
424                         "fadd_fast" => bx.fadd_fast(args[0].immediate(), args[1].immediate()),
425                         "fsub_fast" => bx.fsub_fast(args[0].immediate(), args[1].immediate()),
426                         "fmul_fast" => bx.fmul_fast(args[0].immediate(), args[1].immediate()),
427                         "fdiv_fast" => bx.fdiv_fast(args[0].immediate(), args[1].immediate()),
428                         "frem_fast" => bx.frem_fast(args[0].immediate(), args[1].immediate()),
429                         _ => bug!(),
430                     },
431                 None => {
432                     span_invalid_monomorphization_error(
433                         tcx.sess, span,
434                         &format!("invalid monomorphization of `{}` intrinsic: \
435                                   expected basic float type, found `{}`", name, sty));
436                     return;
437                 }
438             }
439
440         },
441
442         "discriminant_value" => {
443             args[0].deref(bx.cx()).codegen_get_discr(bx, ret_ty)
444         }
445
446         name if name.starts_with("simd_") => {
447             match generic_simd_intrinsic(bx, name,
448                                          callee_ty,
449                                          args,
450                                          ret_ty, llret_ty,
451                                          span) {
452                 Ok(llval) => llval,
453                 Err(()) => return
454             }
455         }
456         // This requires that atomic intrinsics follow a specific naming pattern:
457         // "atomic_<operation>[_<ordering>]", and no ordering means SeqCst
458         name if name.starts_with("atomic_") => {
459             use self::AtomicOrdering::*;
460
461             let split: Vec<&str> = name.split('_').collect();
462
463             let is_cxchg = split[1] == "cxchg" || split[1] == "cxchgweak";
464             let (order, failorder) = match split.len() {
465                 2 => (SequentiallyConsistent, SequentiallyConsistent),
466                 3 => match split[2] {
467                     "unordered" => (Unordered, Unordered),
468                     "relaxed" => (Monotonic, Monotonic),
469                     "acq"     => (Acquire, Acquire),
470                     "rel"     => (Release, Monotonic),
471                     "acqrel"  => (AcquireRelease, Acquire),
472                     "failrelaxed" if is_cxchg =>
473                         (SequentiallyConsistent, Monotonic),
474                     "failacq" if is_cxchg =>
475                         (SequentiallyConsistent, Acquire),
476                     _ => cx.sess().fatal("unknown ordering in atomic intrinsic")
477                 },
478                 4 => match (split[2], split[3]) {
479                     ("acq", "failrelaxed") if is_cxchg =>
480                         (Acquire, Monotonic),
481                     ("acqrel", "failrelaxed") if is_cxchg =>
482                         (AcquireRelease, Monotonic),
483                     _ => cx.sess().fatal("unknown ordering in atomic intrinsic")
484                 },
485                 _ => cx.sess().fatal("Atomic intrinsic not in correct format"),
486             };
487
488             let invalid_monomorphization = |ty| {
489                 span_invalid_monomorphization_error(tcx.sess, span,
490                     &format!("invalid monomorphization of `{}` intrinsic: \
491                               expected basic integer type, found `{}`", name, ty));
492             };
493
494             match split[1] {
495                 "cxchg" | "cxchgweak" => {
496                     let ty = substs.type_at(0);
497                     if int_type_width_signed(ty, cx).is_some() {
498                         let weak = split[1] == "cxchgweak";
499                         let pair = bx.atomic_cmpxchg(
500                             args[0].immediate(),
501                             args[1].immediate(),
502                             args[2].immediate(),
503                             order,
504                             failorder,
505                             weak);
506                         let val = bx.extract_value(pair, 0);
507                         let success = bx.zext(bx.extract_value(pair, 1), bx.cx().type_bool());
508
509                         let dest = result.project_field(bx, 0);
510                         bx.store(val, dest.llval, dest.align);
511                         let dest = result.project_field(bx, 1);
512                         bx.store(success, dest.llval, dest.align);
513                         return;
514                     } else {
515                         return invalid_monomorphization(ty);
516                     }
517                 }
518
519                 "load" => {
520                     let ty = substs.type_at(0);
521                     if int_type_width_signed(ty, cx).is_some() {
522                         let size = cx.size_of(ty);
523                         bx.atomic_load(args[0].immediate(), order, size)
524                     } else {
525                         return invalid_monomorphization(ty);
526                     }
527                 }
528
529                 "store" => {
530                     let ty = substs.type_at(0);
531                     if int_type_width_signed(ty, cx).is_some() {
532                         let size = cx.size_of(ty);
533                         bx.atomic_store(args[1].immediate(), args[0].immediate(), order, size);
534                         return;
535                     } else {
536                         return invalid_monomorphization(ty);
537                     }
538                 }
539
540                 "fence" => {
541                     bx.atomic_fence(order, SynchronizationScope::CrossThread);
542                     return;
543                 }
544
545                 "singlethreadfence" => {
546                     bx.atomic_fence(order, SynchronizationScope::SingleThread);
547                     return;
548                 }
549
550                 // These are all AtomicRMW ops
551                 op => {
552                     let atom_op = match op {
553                         "xchg"  => AtomicRmwBinOp::AtomicXchg,
554                         "xadd"  => AtomicRmwBinOp::AtomicAdd,
555                         "xsub"  => AtomicRmwBinOp::AtomicSub,
556                         "and"   => AtomicRmwBinOp::AtomicAnd,
557                         "nand"  => AtomicRmwBinOp::AtomicNand,
558                         "or"    => AtomicRmwBinOp::AtomicOr,
559                         "xor"   => AtomicRmwBinOp::AtomicXor,
560                         "max"   => AtomicRmwBinOp::AtomicMax,
561                         "min"   => AtomicRmwBinOp::AtomicMin,
562                         "umax"  => AtomicRmwBinOp::AtomicUMax,
563                         "umin"  => AtomicRmwBinOp::AtomicUMin,
564                         _ => cx.sess().fatal("unknown atomic operation")
565                     };
566
567                     let ty = substs.type_at(0);
568                     if int_type_width_signed(ty, cx).is_some() {
569                         bx.atomic_rmw(atom_op, args[0].immediate(), args[1].immediate(), order)
570                     } else {
571                         return invalid_monomorphization(ty);
572                     }
573                 }
574             }
575         }
576
577         "nontemporal_store" => {
578             let dst = args[0].deref(bx.cx());
579             args[1].val.nontemporal_store(bx, dst);
580             return;
581         }
582
583         _ => {
584             let intr = Intrinsic::find(&name).unwrap_or_else(||
585                 bug!("unknown intrinsic '{}'", name));
586
587             fn one<T>(x: Vec<T>) -> T {
588                 assert_eq!(x.len(), 1);
589                 x.into_iter().next().unwrap()
590             }
591             fn ty_to_type(cx: &CodegenCx<'ll, '_>, t: &intrinsics::Type) -> Vec<&'ll Type> {
592                 use intrinsics::Type::*;
593                 match *t {
594                     Void => vec![cx.type_void()],
595                     Integer(_signed, _width, llvm_width) => {
596                         vec![cx.type_ix( llvm_width as u64)]
597                     }
598                     Float(x) => {
599                         match x {
600                             32 => vec![cx.type_f32()],
601                             64 => vec![cx.type_f64()],
602                             _ => bug!()
603                         }
604                     }
605                     Pointer(ref t, ref llvm_elem, _const) => {
606                         let t = llvm_elem.as_ref().unwrap_or(t);
607                         let elem = one(ty_to_type(cx, t));
608                         vec![cx.type_ptr_to(elem)]
609                     }
610                     Vector(ref t, ref llvm_elem, length) => {
611                         let t = llvm_elem.as_ref().unwrap_or(t);
612                         let elem = one(ty_to_type(cx, t));
613                         vec![cx.type_vector(elem, length as u64)]
614                     }
615                     Aggregate(false, ref contents) => {
616                         let elems = contents.iter()
617                                             .map(|t| one(ty_to_type(cx, t)))
618                                             .collect::<Vec<_>>();
619                         vec![cx.type_struct( &elems, false)]
620                     }
621                     Aggregate(true, ref contents) => {
622                         contents.iter()
623                                 .flat_map(|t| ty_to_type(cx, t))
624                                 .collect()
625                     }
626                 }
627             }
628
629             // This allows an argument list like `foo, (bar, baz),
630             // qux` to be converted into `foo, bar, baz, qux`, integer
631             // arguments to be truncated as needed and pointers to be
632             // cast.
633             fn modify_as_needed(
634                 bx: &Builder<'a, 'll, 'tcx>,
635                 t: &intrinsics::Type,
636                 arg: &OperandRef<'tcx, &'ll Value>,
637             ) -> Vec<&'ll Value> {
638                 match *t {
639                     intrinsics::Type::Aggregate(true, ref contents) => {
640                         // We found a tuple that needs squishing! So
641                         // run over the tuple and load each field.
642                         //
643                         // This assumes the type is "simple", i.e. no
644                         // destructors, and the contents are SIMD
645                         // etc.
646                         assert!(!bx.cx().type_needs_drop(arg.layout.ty));
647                         let (ptr, align) = match arg.val {
648                             OperandValue::Ref(ptr, None, align) => (ptr, align),
649                             _ => bug!()
650                         };
651                         let arg = PlaceRef::new_sized(ptr, arg.layout, align);
652                         (0..contents.len()).map(|i| {
653                             arg.project_field(bx, i).load(bx).immediate()
654                         }).collect()
655                     }
656                     intrinsics::Type::Pointer(_, Some(ref llvm_elem), _) => {
657                         let llvm_elem = one(ty_to_type(bx.cx(), llvm_elem));
658                         vec![bx.pointercast(arg.immediate(), bx.cx().type_ptr_to(llvm_elem))]
659                     }
660                     intrinsics::Type::Vector(_, Some(ref llvm_elem), length) => {
661                         let llvm_elem = one(ty_to_type(bx.cx(), llvm_elem));
662                         vec![
663                             bx.bitcast(arg.immediate(),
664                             bx.cx().type_vector(llvm_elem, length as u64))
665                         ]
666                     }
667                     intrinsics::Type::Integer(_, width, llvm_width) if width != llvm_width => {
668                         // the LLVM intrinsic uses a smaller integer
669                         // size than the C intrinsic's signature, so
670                         // we have to trim it down here.
671                         vec![bx.trunc(arg.immediate(), bx.cx().type_ix(llvm_width as u64))]
672                     }
673                     _ => vec![arg.immediate()],
674                 }
675             }
676
677
678             let inputs = intr.inputs.iter()
679                                     .flat_map(|t| ty_to_type(cx, t))
680                                     .collect::<Vec<_>>();
681
682             let outputs = one(ty_to_type(cx, &intr.output));
683
684             let llargs: Vec<_> = intr.inputs.iter().zip(args).flat_map(|(t, arg)| {
685                 modify_as_needed(bx, t, arg)
686             }).collect();
687             assert_eq!(inputs.len(), llargs.len());
688
689             let val = match intr.definition {
690                 intrinsics::IntrinsicDef::Named(name) => {
691                     let f = declare::declare_cfn(cx,
692                                                  name,
693                                                  cx.type_func(&inputs, outputs));
694                     bx.call(f, &llargs, None)
695                 }
696             };
697
698             match *intr.output {
699                 intrinsics::Type::Aggregate(flatten, ref elems) => {
700                     // the output is a tuple so we need to munge it properly
701                     assert!(!flatten);
702
703                     for i in 0..elems.len() {
704                         let dest = result.project_field(bx, i);
705                         let val = bx.extract_value(val, i as u64);
706                         bx.store(val, dest.llval, dest.align);
707                     }
708                     return;
709                 }
710                 _ => val,
711             }
712         }
713     };
714
715     if !fn_ty.ret.is_ignore() {
716         if let PassMode::Cast(ty) = fn_ty.ret.mode {
717             let ptr = bx.pointercast(result.llval, cx.type_ptr_to(ty.llvm_type(cx)));
718             bx.store(llval, ptr, result.align);
719         } else {
720             OperandRef::from_immediate_or_packed_pair(bx, llval, result.layout)
721                 .val.store(bx, result);
722         }
723     }
724 }
725
726 fn copy_intrinsic(
727     bx: &Builder<'a, 'll, 'tcx>,
728     allow_overlap: bool,
729     volatile: bool,
730     ty: Ty<'tcx>,
731     dst: &'ll Value,
732     src: &'ll Value,
733     count: &'ll Value,
734 ) {
735     let (size, align) = bx.cx().size_and_align_of(ty);
736     let size = bx.mul(bx.cx().const_usize(size.bytes()), count);
737     let flags = if volatile {
738         MemFlags::VOLATILE
739     } else {
740         MemFlags::empty()
741     };
742     if allow_overlap {
743         bx.memmove(dst, align, src, align, size, flags);
744     } else {
745         bx.memcpy(dst, align, src, align, size, flags);
746     }
747 }
748
749 fn memset_intrinsic(
750     bx: &Builder<'a, 'll, 'tcx>,
751     volatile: bool,
752     ty: Ty<'tcx>,
753     dst: &'ll Value,
754     val: &'ll Value,
755     count: &'ll Value
756 ) {
757     let (size, align) = bx.cx().size_and_align_of(ty);
758     let size = bx.cx().const_usize(size.bytes());
759     let flags = if volatile {
760         MemFlags::VOLATILE
761     } else {
762         MemFlags::empty()
763     };
764     bx.memset(dst, val, bx.mul(size, count), align, flags);
765 }
766
767 fn try_intrinsic(
768     bx: &Builder<'a, 'll, 'tcx>,
769     cx: &CodegenCx<'ll, 'tcx>,
770     func: &'ll Value,
771     data: &'ll Value,
772     local_ptr: &'ll Value,
773     dest: &'ll Value,
774 ) {
775     if bx.sess().no_landing_pads() {
776         bx.call(func, &[data], None);
777         let ptr_align = bx.tcx().data_layout.pointer_align;
778         bx.store(cx.const_null(cx.type_i8p()), dest, ptr_align);
779     } else if wants_msvc_seh(bx.sess()) {
780         codegen_msvc_try(bx, cx, func, data, local_ptr, dest);
781     } else {
782         codegen_gnu_try(bx, cx, func, data, local_ptr, dest);
783     }
784 }
785
786 // MSVC's definition of the `rust_try` function.
787 //
788 // This implementation uses the new exception handling instructions in LLVM
789 // which have support in LLVM for SEH on MSVC targets. Although these
790 // instructions are meant to work for all targets, as of the time of this
791 // writing, however, LLVM does not recommend the usage of these new instructions
792 // as the old ones are still more optimized.
793 fn codegen_msvc_try(
794     bx: &Builder<'a, 'll, 'tcx>,
795     cx: &CodegenCx<'ll, 'tcx>,
796     func: &'ll Value,
797     data: &'ll Value,
798     local_ptr: &'ll Value,
799     dest: &'ll Value,
800 ) {
801     let llfn = get_rust_try_fn(cx, &mut |bx| {
802         let cx = bx.cx();
803
804         bx.set_personality_fn(bx.cx().eh_personality());
805
806         let normal = bx.build_sibling_block("normal");
807         let catchswitch = bx.build_sibling_block("catchswitch");
808         let catchpad = bx.build_sibling_block("catchpad");
809         let caught = bx.build_sibling_block("caught");
810
811         let func = llvm::get_param(bx.llfn(), 0);
812         let data = llvm::get_param(bx.llfn(), 1);
813         let local_ptr = llvm::get_param(bx.llfn(), 2);
814
815         // We're generating an IR snippet that looks like:
816         //
817         //   declare i32 @rust_try(%func, %data, %ptr) {
818         //      %slot = alloca i64*
819         //      invoke %func(%data) to label %normal unwind label %catchswitch
820         //
821         //   normal:
822         //      ret i32 0
823         //
824         //   catchswitch:
825         //      %cs = catchswitch within none [%catchpad] unwind to caller
826         //
827         //   catchpad:
828         //      %tok = catchpad within %cs [%type_descriptor, 0, %slot]
829         //      %ptr[0] = %slot[0]
830         //      %ptr[1] = %slot[1]
831         //      catchret from %tok to label %caught
832         //
833         //   caught:
834         //      ret i32 1
835         //   }
836         //
837         // This structure follows the basic usage of throw/try/catch in LLVM.
838         // For example, compile this C++ snippet to see what LLVM generates:
839         //
840         //      #include <stdint.h>
841         //
842         //      int bar(void (*foo)(void), uint64_t *ret) {
843         //          try {
844         //              foo();
845         //              return 0;
846         //          } catch(uint64_t a[2]) {
847         //              ret[0] = a[0];
848         //              ret[1] = a[1];
849         //              return 1;
850         //          }
851         //      }
852         //
853         // More information can be found in libstd's seh.rs implementation.
854         let i64p = cx.type_ptr_to(cx.type_i64());
855         let ptr_align = bx.tcx().data_layout.pointer_align;
856         let slot = bx.alloca(i64p, "slot", ptr_align);
857         bx.invoke(func, &[data], normal.llbb(), catchswitch.llbb(), None);
858
859         normal.ret(cx.const_i32(0));
860
861         let cs = catchswitch.catch_switch(None, None, 1);
862         catchswitch.add_handler(cs, catchpad.llbb());
863
864         let tcx = cx.tcx;
865         let tydesc = match tcx.lang_items().msvc_try_filter() {
866             Some(did) => cx.get_static(did),
867             None => bug!("msvc_try_filter not defined"),
868         };
869         let tok = catchpad.catch_pad(cs, &[tydesc, cx.const_i32(0), slot]);
870         let addr = catchpad.load(slot, ptr_align);
871
872         let i64_align = bx.tcx().data_layout.i64_align;
873         let arg1 = catchpad.load(addr, i64_align);
874         let val1 = cx.const_i32(1);
875         let arg2 = catchpad.load(catchpad.inbounds_gep(addr, &[val1]), i64_align);
876         let local_ptr = catchpad.bitcast(local_ptr, i64p);
877         catchpad.store(arg1, local_ptr, i64_align);
878         catchpad.store(arg2, catchpad.inbounds_gep(local_ptr, &[val1]), i64_align);
879         catchpad.catch_ret(tok, caught.llbb());
880
881         caught.ret(cx.const_i32(1));
882     });
883
884     // Note that no invoke is used here because by definition this function
885     // can't panic (that's what it's catching).
886     let ret = bx.call(llfn, &[func, data, local_ptr], None);
887     let i32_align = bx.tcx().data_layout.i32_align;
888     bx.store(ret, dest, i32_align);
889 }
890
891 // Definition of the standard "try" function for Rust using the GNU-like model
892 // of exceptions (e.g. the normal semantics of LLVM's landingpad and invoke
893 // instructions).
894 //
895 // This codegen is a little surprising because we always call a shim
896 // function instead of inlining the call to `invoke` manually here. This is done
897 // because in LLVM we're only allowed to have one personality per function
898 // definition. The call to the `try` intrinsic is being inlined into the
899 // function calling it, and that function may already have other personality
900 // functions in play. By calling a shim we're guaranteed that our shim will have
901 // the right personality function.
902 fn codegen_gnu_try(
903     bx: &Builder<'a, 'll, 'tcx>,
904     cx: &CodegenCx<'ll, 'tcx>,
905     func: &'ll Value,
906     data: &'ll Value,
907     local_ptr: &'ll Value,
908     dest: &'ll Value,
909 ) {
910     let llfn = get_rust_try_fn(cx, &mut |bx| {
911         let cx = bx.cx();
912
913         // Codegens the shims described above:
914         //
915         //   bx:
916         //      invoke %func(%args...) normal %normal unwind %catch
917         //
918         //   normal:
919         //      ret 0
920         //
921         //   catch:
922         //      (ptr, _) = landingpad
923         //      store ptr, %local_ptr
924         //      ret 1
925         //
926         // Note that the `local_ptr` data passed into the `try` intrinsic is
927         // expected to be `*mut *mut u8` for this to actually work, but that's
928         // managed by the standard library.
929
930         let then = bx.build_sibling_block("then");
931         let catch = bx.build_sibling_block("catch");
932
933         let func = llvm::get_param(bx.llfn(), 0);
934         let data = llvm::get_param(bx.llfn(), 1);
935         let local_ptr = llvm::get_param(bx.llfn(), 2);
936         bx.invoke(func, &[data], then.llbb(), catch.llbb(), None);
937         then.ret(cx.const_i32(0));
938
939         // Type indicator for the exception being thrown.
940         //
941         // The first value in this tuple is a pointer to the exception object
942         // being thrown.  The second value is a "selector" indicating which of
943         // the landing pad clauses the exception's type had been matched to.
944         // rust_try ignores the selector.
945         let lpad_ty = cx.type_struct(&[cx.type_i8p(), cx.type_i32()], false);
946         let vals = catch.landing_pad(lpad_ty, bx.cx().eh_personality(), 1);
947         catch.add_clause(vals, bx.cx().const_null(cx.type_i8p()));
948         let ptr = catch.extract_value(vals, 0);
949         let ptr_align = bx.tcx().data_layout.pointer_align;
950         catch.store(ptr, catch.bitcast(local_ptr, cx.type_ptr_to(cx.type_i8p())), ptr_align);
951         catch.ret(cx.const_i32(1));
952     });
953
954     // Note that no invoke is used here because by definition this function
955     // can't panic (that's what it's catching).
956     let ret = bx.call(llfn, &[func, data, local_ptr], None);
957     let i32_align = bx.tcx().data_layout.i32_align;
958     bx.store(ret, dest, i32_align);
959 }
960
961 // Helper function to give a Block to a closure to codegen a shim function.
962 // This is currently primarily used for the `try` intrinsic functions above.
963 fn gen_fn<'ll, 'tcx>(
964     cx: &CodegenCx<'ll, 'tcx>,
965     name: &str,
966     inputs: Vec<Ty<'tcx>>,
967     output: Ty<'tcx>,
968     codegen: &mut dyn FnMut(Builder<'_, 'll, 'tcx>),
969 ) -> &'ll Value {
970     let rust_fn_sig = ty::Binder::bind(cx.tcx.mk_fn_sig(
971         inputs.into_iter(),
972         output,
973         false,
974         hir::Unsafety::Unsafe,
975         Abi::Rust
976     ));
977     let llfn = declare::define_internal_fn(cx, name, rust_fn_sig);
978     attributes::from_fn_attrs(cx, llfn, None);
979     let bx = Builder::new_block(cx, llfn, "entry-block");
980     codegen(bx);
981     llfn
982 }
983
984 // Helper function used to get a handle to the `__rust_try` function used to
985 // catch exceptions.
986 //
987 // This function is only generated once and is then cached.
988 fn get_rust_try_fn<'ll, 'tcx>(
989     cx: &CodegenCx<'ll, 'tcx>,
990     codegen: &mut dyn FnMut(Builder<'_, 'll, 'tcx>),
991 ) -> &'ll Value {
992     if let Some(llfn) = cx.rust_try_fn.get() {
993         return llfn;
994     }
995
996     // Define the type up front for the signature of the rust_try function.
997     let tcx = cx.tcx;
998     let i8p = tcx.mk_mut_ptr(tcx.types.i8);
999     let fn_ty = tcx.mk_fn_ptr(ty::Binder::bind(tcx.mk_fn_sig(
1000         iter::once(i8p),
1001         tcx.mk_unit(),
1002         false,
1003         hir::Unsafety::Unsafe,
1004         Abi::Rust
1005     )));
1006     let output = tcx.types.i32;
1007     let rust_try = gen_fn(cx, "__rust_try", vec![fn_ty, i8p, i8p], output, codegen);
1008     cx.rust_try_fn.set(Some(rust_try));
1009     rust_try
1010 }
1011
1012 fn span_invalid_monomorphization_error(a: &Session, b: Span, c: &str) {
1013     span_err!(a, b, E0511, "{}", c);
1014 }
1015
1016 fn generic_simd_intrinsic(
1017     bx: &Builder<'a, 'll, 'tcx>,
1018     name: &str,
1019     callee_ty: Ty<'tcx>,
1020     args: &[OperandRef<'tcx, &'ll Value>],
1021     ret_ty: Ty<'tcx>,
1022     llret_ty: &'ll Type,
1023     span: Span
1024 ) -> Result<&'ll Value, ()> {
1025     // macros for error handling:
1026     macro_rules! emit_error {
1027         ($msg: tt) => {
1028             emit_error!($msg, )
1029         };
1030         ($msg: tt, $($fmt: tt)*) => {
1031             span_invalid_monomorphization_error(
1032                 bx.sess(), span,
1033                 &format!(concat!("invalid monomorphization of `{}` intrinsic: ", $msg),
1034                          name, $($fmt)*));
1035         }
1036     }
1037
1038     macro_rules! return_error {
1039         ($($fmt: tt)*) => {
1040             {
1041                 emit_error!($($fmt)*);
1042                 return Err(());
1043             }
1044         }
1045     }
1046
1047     macro_rules! require {
1048         ($cond: expr, $($fmt: tt)*) => {
1049             if !$cond {
1050                 return_error!($($fmt)*);
1051             }
1052         };
1053     }
1054
1055     macro_rules! require_simd {
1056         ($ty: expr, $position: expr) => {
1057             require!($ty.is_simd(), "expected SIMD {} type, found non-SIMD `{}`", $position, $ty)
1058         }
1059     }
1060
1061     let tcx = bx.tcx();
1062     let sig = tcx.normalize_erasing_late_bound_regions(
1063         ty::ParamEnv::reveal_all(),
1064         &callee_ty.fn_sig(tcx),
1065     );
1066     let arg_tys = sig.inputs();
1067
1068     // every intrinsic takes a SIMD vector as its first argument
1069     require_simd!(arg_tys[0], "input");
1070     let in_ty = arg_tys[0];
1071     let in_elem = arg_tys[0].simd_type(tcx);
1072     let in_len = arg_tys[0].simd_size(tcx);
1073
1074     let comparison = match name {
1075         "simd_eq" => Some(hir::BinOpKind::Eq),
1076         "simd_ne" => Some(hir::BinOpKind::Ne),
1077         "simd_lt" => Some(hir::BinOpKind::Lt),
1078         "simd_le" => Some(hir::BinOpKind::Le),
1079         "simd_gt" => Some(hir::BinOpKind::Gt),
1080         "simd_ge" => Some(hir::BinOpKind::Ge),
1081         _ => None
1082     };
1083
1084     if let Some(cmp_op) = comparison {
1085         require_simd!(ret_ty, "return");
1086
1087         let out_len = ret_ty.simd_size(tcx);
1088         require!(in_len == out_len,
1089                  "expected return type with length {} (same as input type `{}`), \
1090                   found `{}` with length {}",
1091                  in_len, in_ty,
1092                  ret_ty, out_len);
1093         require!(bx.cx().type_kind(bx.cx().element_type(llret_ty)) == TypeKind::Integer,
1094                  "expected return type with integer elements, found `{}` with non-integer `{}`",
1095                  ret_ty,
1096                  ret_ty.simd_type(tcx));
1097
1098         return Ok(compare_simd_types(bx,
1099                                      args[0].immediate(),
1100                                      args[1].immediate(),
1101                                      in_elem,
1102                                      llret_ty,
1103                                      cmp_op))
1104     }
1105
1106     if name.starts_with("simd_shuffle") {
1107         let n: usize = name["simd_shuffle".len()..].parse().unwrap_or_else(|_|
1108             span_bug!(span, "bad `simd_shuffle` instruction only caught in codegen?"));
1109
1110         require_simd!(ret_ty, "return");
1111
1112         let out_len = ret_ty.simd_size(tcx);
1113         require!(out_len == n,
1114                  "expected return type of length {}, found `{}` with length {}",
1115                  n, ret_ty, out_len);
1116         require!(in_elem == ret_ty.simd_type(tcx),
1117                  "expected return element type `{}` (element of input `{}`), \
1118                   found `{}` with element type `{}`",
1119                  in_elem, in_ty,
1120                  ret_ty, ret_ty.simd_type(tcx));
1121
1122         let total_len = in_len as u128 * 2;
1123
1124         let vector = args[2].immediate();
1125
1126         let indices: Option<Vec<_>> = (0..n)
1127             .map(|i| {
1128                 let arg_idx = i;
1129                 let val = bx.cx().const_get_elt(vector, i as u64);
1130                 match bx.cx().const_to_opt_u128(val, true) {
1131                     None => {
1132                         emit_error!("shuffle index #{} is not a constant", arg_idx);
1133                         None
1134                     }
1135                     Some(idx) if idx >= total_len => {
1136                         emit_error!("shuffle index #{} is out of bounds (limit {})",
1137                                     arg_idx, total_len);
1138                         None
1139                     }
1140                     Some(idx) => Some(bx.cx().const_i32(idx as i32)),
1141                 }
1142             })
1143             .collect();
1144         let indices = match indices {
1145             Some(i) => i,
1146             None => return Ok(bx.cx().const_null(llret_ty))
1147         };
1148
1149         return Ok(bx.shuffle_vector(args[0].immediate(),
1150                                     args[1].immediate(),
1151                                     bx.cx().const_vector(&indices)))
1152     }
1153
1154     if name == "simd_insert" {
1155         require!(in_elem == arg_tys[2],
1156                  "expected inserted type `{}` (element of input `{}`), found `{}`",
1157                  in_elem, in_ty, arg_tys[2]);
1158         return Ok(bx.insert_element(args[0].immediate(),
1159                                     args[2].immediate(),
1160                                     args[1].immediate()))
1161     }
1162     if name == "simd_extract" {
1163         require!(ret_ty == in_elem,
1164                  "expected return type `{}` (element of input `{}`), found `{}`",
1165                  in_elem, in_ty, ret_ty);
1166         return Ok(bx.extract_element(args[0].immediate(), args[1].immediate()))
1167     }
1168
1169     if name == "simd_select" {
1170         let m_elem_ty = in_elem;
1171         let m_len = in_len;
1172         let v_len = arg_tys[1].simd_size(tcx);
1173         require!(m_len == v_len,
1174                  "mismatched lengths: mask length `{}` != other vector length `{}`",
1175                  m_len, v_len
1176         );
1177         match m_elem_ty.sty {
1178             ty::Int(_) => {},
1179             _ => return_error!("mask element type is `{}`, expected `i_`", m_elem_ty)
1180         }
1181         // truncate the mask to a vector of i1s
1182         let i1 = bx.cx().type_i1();
1183         let i1xn = bx.cx().type_vector(i1, m_len as u64);
1184         let m_i1s = bx.trunc(args[0].immediate(), i1xn);
1185         return Ok(bx.select(m_i1s, args[1].immediate(), args[2].immediate()));
1186     }
1187
1188     fn simd_simple_float_intrinsic(
1189         name: &str,
1190         in_elem: &::rustc::ty::TyS,
1191         in_ty: &::rustc::ty::TyS,
1192         in_len: usize,
1193         bx: &Builder<'a, 'll, 'tcx>,
1194         span: Span,
1195         args: &[OperandRef<'tcx, &'ll Value>],
1196     ) -> Result<&'ll Value, ()> {
1197         macro_rules! emit_error {
1198             ($msg: tt) => {
1199                 emit_error!($msg, )
1200             };
1201             ($msg: tt, $($fmt: tt)*) => {
1202                 span_invalid_monomorphization_error(
1203                     bx.sess(), span,
1204                     &format!(concat!("invalid monomorphization of `{}` intrinsic: ", $msg),
1205                              name, $($fmt)*));
1206             }
1207         }
1208         macro_rules! return_error {
1209             ($($fmt: tt)*) => {
1210                 {
1211                     emit_error!($($fmt)*);
1212                     return Err(());
1213                 }
1214             }
1215         }
1216         let ety = match in_elem.sty {
1217             ty::Float(f) if f.bit_width() == 32 => {
1218                 if in_len < 2 || in_len > 16 {
1219                     return_error!(
1220                         "unsupported floating-point vector `{}` with length `{}` \
1221                          out-of-range [2, 16]",
1222                         in_ty, in_len);
1223                 }
1224                 "f32"
1225             },
1226             ty::Float(f) if f.bit_width() == 64 => {
1227                 if in_len < 2 || in_len > 8 {
1228                     return_error!("unsupported floating-point vector `{}` with length `{}` \
1229                                    out-of-range [2, 8]",
1230                                   in_ty, in_len);
1231                 }
1232                 "f64"
1233             },
1234             ty::Float(f) => {
1235                 return_error!("unsupported element type `{}` of floating-point vector `{}`",
1236                               f, in_ty);
1237             },
1238             _ => {
1239                 return_error!("`{}` is not a floating-point type", in_ty);
1240             }
1241         };
1242
1243         let llvm_name = &format!("llvm.{0}.v{1}{2}", name, in_len, ety);
1244         let intrinsic = bx.cx().get_intrinsic(&llvm_name);
1245         let c = bx.call(intrinsic,
1246                         &args.iter().map(|arg| arg.immediate()).collect::<Vec<_>>(),
1247                         None);
1248         unsafe { llvm::LLVMRustSetHasUnsafeAlgebra(c) };
1249         Ok(c)
1250     }
1251
1252     match name {
1253         "simd_fsqrt" => {
1254             return simd_simple_float_intrinsic("sqrt", in_elem, in_ty, in_len, bx, span, args);
1255         }
1256         "simd_fsin" => {
1257             return simd_simple_float_intrinsic("sin", in_elem, in_ty, in_len, bx, span, args);
1258         }
1259         "simd_fcos" => {
1260             return simd_simple_float_intrinsic("cos", in_elem, in_ty, in_len, bx, span, args);
1261         }
1262         "simd_fabs" => {
1263             return simd_simple_float_intrinsic("fabs", in_elem, in_ty, in_len, bx, span, args);
1264         }
1265         "simd_floor" => {
1266             return simd_simple_float_intrinsic("floor", in_elem, in_ty, in_len, bx, span, args);
1267         }
1268         "simd_ceil" => {
1269             return simd_simple_float_intrinsic("ceil", in_elem, in_ty, in_len, bx, span, args);
1270         }
1271         "simd_fexp" => {
1272             return simd_simple_float_intrinsic("exp", in_elem, in_ty, in_len, bx, span, args);
1273         }
1274         "simd_fexp2" => {
1275             return simd_simple_float_intrinsic("exp2", in_elem, in_ty, in_len, bx, span, args);
1276         }
1277         "simd_flog10" => {
1278             return simd_simple_float_intrinsic("log10", in_elem, in_ty, in_len, bx, span, args);
1279         }
1280         "simd_flog2" => {
1281             return simd_simple_float_intrinsic("log2", in_elem, in_ty, in_len, bx, span, args);
1282         }
1283         "simd_flog" => {
1284             return simd_simple_float_intrinsic("log", in_elem, in_ty, in_len, bx, span, args);
1285         }
1286         "simd_fpowi" => {
1287             return simd_simple_float_intrinsic("powi", in_elem, in_ty, in_len, bx, span, args);
1288         }
1289         "simd_fpow" => {
1290             return simd_simple_float_intrinsic("pow", in_elem, in_ty, in_len, bx, span, args);
1291         }
1292         "simd_fma" => {
1293             return simd_simple_float_intrinsic("fma", in_elem, in_ty, in_len, bx, span, args);
1294         }
1295         _ => { /* fallthrough */ }
1296     }
1297
1298     // FIXME: use:
1299     //  https://github.com/llvm-mirror/llvm/blob/master/include/llvm/IR/Function.h#L182
1300     //  https://github.com/llvm-mirror/llvm/blob/master/include/llvm/IR/Intrinsics.h#L81
1301     fn llvm_vector_str(elem_ty: ty::Ty, vec_len: usize, no_pointers: usize) -> String {
1302         let p0s: String = "p0".repeat(no_pointers);
1303         match elem_ty.sty {
1304             ty::Int(v) => format!("v{}{}i{}", vec_len, p0s, v.bit_width().unwrap()),
1305             ty::Uint(v) => format!("v{}{}i{}", vec_len, p0s, v.bit_width().unwrap()),
1306             ty::Float(v) => format!("v{}{}f{}", vec_len, p0s, v.bit_width()),
1307             _ => unreachable!(),
1308         }
1309     }
1310
1311     fn llvm_vector_ty(cx: &CodegenCx<'ll, '_>, elem_ty: ty::Ty, vec_len: usize,
1312                       mut no_pointers: usize) -> &'ll Type {
1313         // FIXME: use cx.layout_of(ty).llvm_type() ?
1314         let mut elem_ty = match elem_ty.sty {
1315             ty::Int(v) => cx.type_int_from_ty( v),
1316             ty::Uint(v) => cx.type_uint_from_ty( v),
1317             ty::Float(v) => cx.type_float_from_ty( v),
1318             _ => unreachable!(),
1319         };
1320         while no_pointers > 0 {
1321             elem_ty = cx.type_ptr_to(elem_ty);
1322             no_pointers -= 1;
1323         }
1324         cx.type_vector(elem_ty, vec_len as u64)
1325     }
1326
1327
1328     if name == "simd_gather" {
1329         // simd_gather(values: <N x T>, pointers: <N x *_ T>,
1330         //             mask: <N x i{M}>) -> <N x T>
1331         // * N: number of elements in the input vectors
1332         // * T: type of the element to load
1333         // * M: any integer width is supported, will be truncated to i1
1334
1335         // All types must be simd vector types
1336         require_simd!(in_ty, "first");
1337         require_simd!(arg_tys[1], "second");
1338         require_simd!(arg_tys[2], "third");
1339         require_simd!(ret_ty, "return");
1340
1341         // Of the same length:
1342         require!(in_len == arg_tys[1].simd_size(tcx),
1343                  "expected {} argument with length {} (same as input type `{}`), \
1344                   found `{}` with length {}", "second", in_len, in_ty, arg_tys[1],
1345                  arg_tys[1].simd_size(tcx));
1346         require!(in_len == arg_tys[2].simd_size(tcx),
1347                  "expected {} argument with length {} (same as input type `{}`), \
1348                   found `{}` with length {}", "third", in_len, in_ty, arg_tys[2],
1349                  arg_tys[2].simd_size(tcx));
1350
1351         // The return type must match the first argument type
1352         require!(ret_ty == in_ty,
1353                  "expected return type `{}`, found `{}`",
1354                  in_ty, ret_ty);
1355
1356         // This counts how many pointers
1357         fn ptr_count(t: ty::Ty) -> usize {
1358             match t.sty {
1359                 ty::RawPtr(p) => 1 + ptr_count(p.ty),
1360                 _ => 0,
1361             }
1362         }
1363
1364         // Non-ptr type
1365         fn non_ptr(t: ty::Ty) -> ty::Ty {
1366             match t.sty {
1367                 ty::RawPtr(p) => non_ptr(p.ty),
1368                 _ => t,
1369             }
1370         }
1371
1372         // The second argument must be a simd vector with an element type that's a pointer
1373         // to the element type of the first argument
1374         let (pointer_count, underlying_ty) = match arg_tys[1].simd_type(tcx).sty {
1375             ty::RawPtr(p) if p.ty == in_elem => (ptr_count(arg_tys[1].simd_type(tcx)),
1376                                                  non_ptr(arg_tys[1].simd_type(tcx))),
1377             _ => {
1378                 require!(false, "expected element type `{}` of second argument `{}` \
1379                                  to be a pointer to the element type `{}` of the first \
1380                                  argument `{}`, found `{}` != `*_ {}`",
1381                          arg_tys[1].simd_type(tcx).sty, arg_tys[1], in_elem, in_ty,
1382                          arg_tys[1].simd_type(tcx).sty, in_elem);
1383                 unreachable!();
1384             }
1385         };
1386         assert!(pointer_count > 0);
1387         assert_eq!(pointer_count - 1, ptr_count(arg_tys[0].simd_type(tcx)));
1388         assert_eq!(underlying_ty, non_ptr(arg_tys[0].simd_type(tcx)));
1389
1390         // The element type of the third argument must be a signed integer type of any width:
1391         match arg_tys[2].simd_type(tcx).sty {
1392             ty::Int(_) => (),
1393             _ => {
1394                 require!(false, "expected element type `{}` of third argument `{}` \
1395                                  to be a signed integer type",
1396                          arg_tys[2].simd_type(tcx).sty, arg_tys[2]);
1397             }
1398         }
1399
1400         // Alignment of T, must be a constant integer value:
1401         let alignment_ty = bx.cx().type_i32();
1402         let alignment = bx.cx().const_i32(bx.cx().align_of(in_elem).abi() as i32);
1403
1404         // Truncate the mask vector to a vector of i1s:
1405         let (mask, mask_ty) = {
1406             let i1 = bx.cx().type_i1();
1407             let i1xn = bx.cx().type_vector(i1, in_len as u64);
1408             (bx.trunc(args[2].immediate(), i1xn), i1xn)
1409         };
1410
1411         // Type of the vector of pointers:
1412         let llvm_pointer_vec_ty = llvm_vector_ty(bx.cx(), underlying_ty, in_len, pointer_count);
1413         let llvm_pointer_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count);
1414
1415         // Type of the vector of elements:
1416         let llvm_elem_vec_ty = llvm_vector_ty(bx.cx(), underlying_ty, in_len, pointer_count - 1);
1417         let llvm_elem_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count - 1);
1418
1419         let llvm_intrinsic = format!("llvm.masked.gather.{}.{}",
1420                                      llvm_elem_vec_str, llvm_pointer_vec_str);
1421         let f = declare::declare_cfn(bx.cx(), &llvm_intrinsic,
1422                                      bx.cx().type_func(&[
1423                                          llvm_pointer_vec_ty,
1424                                          alignment_ty,
1425                                          mask_ty,
1426                                          llvm_elem_vec_ty], llvm_elem_vec_ty));
1427         llvm::SetUnnamedAddr(f, false);
1428         let v = bx.call(f, &[args[1].immediate(), alignment, mask, args[0].immediate()],
1429                         None);
1430         return Ok(v);
1431     }
1432
1433     if name == "simd_scatter" {
1434         // simd_scatter(values: <N x T>, pointers: <N x *mut T>,
1435         //             mask: <N x i{M}>) -> ()
1436         // * N: number of elements in the input vectors
1437         // * T: type of the element to load
1438         // * M: any integer width is supported, will be truncated to i1
1439
1440         // All types must be simd vector types
1441         require_simd!(in_ty, "first");
1442         require_simd!(arg_tys[1], "second");
1443         require_simd!(arg_tys[2], "third");
1444
1445         // Of the same length:
1446         require!(in_len == arg_tys[1].simd_size(tcx),
1447                  "expected {} argument with length {} (same as input type `{}`), \
1448                   found `{}` with length {}", "second", in_len, in_ty, arg_tys[1],
1449                  arg_tys[1].simd_size(tcx));
1450         require!(in_len == arg_tys[2].simd_size(tcx),
1451                  "expected {} argument with length {} (same as input type `{}`), \
1452                   found `{}` with length {}", "third", in_len, in_ty, arg_tys[2],
1453                  arg_tys[2].simd_size(tcx));
1454
1455         // This counts how many pointers
1456         fn ptr_count(t: ty::Ty) -> usize {
1457             match t.sty {
1458                 ty::RawPtr(p) => 1 + ptr_count(p.ty),
1459                 _ => 0,
1460             }
1461         }
1462
1463         // Non-ptr type
1464         fn non_ptr(t: ty::Ty) -> ty::Ty {
1465             match t.sty {
1466                 ty::RawPtr(p) => non_ptr(p.ty),
1467                 _ => t,
1468             }
1469         }
1470
1471         // The second argument must be a simd vector with an element type that's a pointer
1472         // to the element type of the first argument
1473         let (pointer_count, underlying_ty) = match arg_tys[1].simd_type(tcx).sty {
1474             ty::RawPtr(p) if p.ty == in_elem && p.mutbl == hir::MutMutable
1475                 => (ptr_count(arg_tys[1].simd_type(tcx)),
1476                     non_ptr(arg_tys[1].simd_type(tcx))),
1477             _ => {
1478                 require!(false, "expected element type `{}` of second argument `{}` \
1479                                  to be a pointer to the element type `{}` of the first \
1480                                  argument `{}`, found `{}` != `*mut {}`",
1481                          arg_tys[1].simd_type(tcx).sty, arg_tys[1], in_elem, in_ty,
1482                          arg_tys[1].simd_type(tcx).sty, in_elem);
1483                 unreachable!();
1484             }
1485         };
1486         assert!(pointer_count > 0);
1487         assert_eq!(pointer_count - 1, ptr_count(arg_tys[0].simd_type(tcx)));
1488         assert_eq!(underlying_ty, non_ptr(arg_tys[0].simd_type(tcx)));
1489
1490         // The element type of the third argument must be a signed integer type of any width:
1491         match arg_tys[2].simd_type(tcx).sty {
1492             ty::Int(_) => (),
1493             _ => {
1494                 require!(false, "expected element type `{}` of third argument `{}` \
1495                                  to be a signed integer type",
1496                          arg_tys[2].simd_type(tcx).sty, arg_tys[2]);
1497             }
1498         }
1499
1500         // Alignment of T, must be a constant integer value:
1501         let alignment_ty = bx.cx().type_i32();
1502         let alignment = bx.cx().const_i32(bx.cx().align_of(in_elem).abi() as i32);
1503
1504         // Truncate the mask vector to a vector of i1s:
1505         let (mask, mask_ty) = {
1506             let i1 = bx.cx().type_i1();
1507             let i1xn = bx.cx().type_vector(i1, in_len as u64);
1508             (bx.trunc(args[2].immediate(), i1xn), i1xn)
1509         };
1510
1511         let ret_t = bx.cx().type_void();
1512
1513         // Type of the vector of pointers:
1514         let llvm_pointer_vec_ty = llvm_vector_ty(bx.cx(), underlying_ty, in_len, pointer_count);
1515         let llvm_pointer_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count);
1516
1517         // Type of the vector of elements:
1518         let llvm_elem_vec_ty = llvm_vector_ty(bx.cx(), underlying_ty, in_len, pointer_count - 1);
1519         let llvm_elem_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count - 1);
1520
1521         let llvm_intrinsic = format!("llvm.masked.scatter.{}.{}",
1522                                      llvm_elem_vec_str, llvm_pointer_vec_str);
1523         let f = declare::declare_cfn(bx.cx(), &llvm_intrinsic,
1524                                      bx.cx().type_func(&[llvm_elem_vec_ty,
1525                                                   llvm_pointer_vec_ty,
1526                                                   alignment_ty,
1527                                                   mask_ty], ret_t));
1528         llvm::SetUnnamedAddr(f, false);
1529         let v = bx.call(f, &[args[0].immediate(), args[1].immediate(), alignment, mask],
1530                         None);
1531         return Ok(v);
1532     }
1533
1534     macro_rules! arith_red {
1535         ($name:tt : $integer_reduce:ident, $float_reduce:ident, $ordered:expr) => {
1536             if name == $name {
1537                 require!(ret_ty == in_elem,
1538                          "expected return type `{}` (element of input `{}`), found `{}`",
1539                          in_elem, in_ty, ret_ty);
1540                 return match in_elem.sty {
1541                     ty::Int(_) | ty::Uint(_) => {
1542                         let r = bx.$integer_reduce(args[0].immediate());
1543                         if $ordered {
1544                             // if overflow occurs, the result is the
1545                             // mathematical result modulo 2^n:
1546                             if name.contains("mul") {
1547                                 Ok(bx.mul(args[1].immediate(), r))
1548                             } else {
1549                                 Ok(bx.add(args[1].immediate(), r))
1550                             }
1551                         } else {
1552                             Ok(bx.$integer_reduce(args[0].immediate()))
1553                         }
1554                     },
1555                     ty::Float(f) => {
1556                         // ordered arithmetic reductions take an accumulator
1557                         let acc = if $ordered {
1558                             let acc = args[1].immediate();
1559                             // FIXME: https://bugs.llvm.org/show_bug.cgi?id=36734
1560                             // * if the accumulator of the fadd isn't 0, incorrect
1561                             //   code is generated
1562                             // * if the accumulator of the fmul isn't 1, incorrect
1563                             //   code is generated
1564                             match bx.cx().const_get_real(acc) {
1565                                 None => return_error!("accumulator of {} is not a constant", $name),
1566                                 Some((v, loses_info)) => {
1567                                     if $name.contains("mul") && v != 1.0_f64 {
1568                                         return_error!("accumulator of {} is not 1.0", $name);
1569                                     } else if $name.contains("add") && v != 0.0_f64 {
1570                                         return_error!("accumulator of {} is not 0.0", $name);
1571                                     } else if loses_info {
1572                                         return_error!("accumulator of {} loses information", $name);
1573                                     }
1574                                 }
1575                             }
1576                             acc
1577                         } else {
1578                             // unordered arithmetic reductions do not:
1579                             match f.bit_width() {
1580                                 32 => bx.cx().const_undef(bx.cx().type_f32()),
1581                                 64 => bx.cx().const_undef(bx.cx().type_f64()),
1582                                 v => {
1583                                     return_error!(r#"
1584 unsupported {} from `{}` with element `{}` of size `{}` to `{}`"#,
1585                                         $name, in_ty, in_elem, v, ret_ty
1586                                     )
1587                                 }
1588                             }
1589                         };
1590                         Ok(bx.$float_reduce(acc, args[0].immediate()))
1591                     }
1592                     _ => {
1593                         return_error!(
1594                             "unsupported {} from `{}` with element `{}` to `{}`",
1595                             $name, in_ty, in_elem, ret_ty
1596                         )
1597                     },
1598                 }
1599             }
1600         }
1601     }
1602
1603     arith_red!("simd_reduce_add_ordered": vector_reduce_add, vector_reduce_fadd_fast, true);
1604     arith_red!("simd_reduce_mul_ordered": vector_reduce_mul, vector_reduce_fmul_fast, true);
1605     arith_red!("simd_reduce_add_unordered": vector_reduce_add, vector_reduce_fadd_fast, false);
1606     arith_red!("simd_reduce_mul_unordered": vector_reduce_mul, vector_reduce_fmul_fast, false);
1607
1608     macro_rules! minmax_red {
1609         ($name:tt: $int_red:ident, $float_red:ident) => {
1610             if name == $name {
1611                 require!(ret_ty == in_elem,
1612                          "expected return type `{}` (element of input `{}`), found `{}`",
1613                          in_elem, in_ty, ret_ty);
1614                 return match in_elem.sty {
1615                     ty::Int(_i) => {
1616                         Ok(bx.$int_red(args[0].immediate(), true))
1617                     },
1618                     ty::Uint(_u) => {
1619                         Ok(bx.$int_red(args[0].immediate(), false))
1620                     },
1621                     ty::Float(_f) => {
1622                         Ok(bx.$float_red(args[0].immediate()))
1623                     }
1624                     _ => {
1625                         return_error!("unsupported {} from `{}` with element `{}` to `{}`",
1626                                       $name, in_ty, in_elem, ret_ty)
1627                     },
1628                 }
1629             }
1630
1631         }
1632     }
1633
1634     minmax_red!("simd_reduce_min": vector_reduce_min, vector_reduce_fmin);
1635     minmax_red!("simd_reduce_max": vector_reduce_max, vector_reduce_fmax);
1636
1637     minmax_red!("simd_reduce_min_nanless": vector_reduce_min, vector_reduce_fmin_fast);
1638     minmax_red!("simd_reduce_max_nanless": vector_reduce_max, vector_reduce_fmax_fast);
1639
1640     macro_rules! bitwise_red {
1641         ($name:tt : $red:ident, $boolean:expr) => {
1642             if name == $name {
1643                 let input = if !$boolean {
1644                     require!(ret_ty == in_elem,
1645                              "expected return type `{}` (element of input `{}`), found `{}`",
1646                              in_elem, in_ty, ret_ty);
1647                     args[0].immediate()
1648                 } else {
1649                     match in_elem.sty {
1650                         ty::Int(_) | ty::Uint(_) => {},
1651                         _ => {
1652                             return_error!("unsupported {} from `{}` with element `{}` to `{}`",
1653                                           $name, in_ty, in_elem, ret_ty)
1654                         }
1655                     }
1656
1657                     // boolean reductions operate on vectors of i1s:
1658                     let i1 = bx.cx().type_i1();
1659                     let i1xn = bx.cx().type_vector(i1, in_len as u64);
1660                     bx.trunc(args[0].immediate(), i1xn)
1661                 };
1662                 return match in_elem.sty {
1663                     ty::Int(_) | ty::Uint(_) => {
1664                         let r = bx.$red(input);
1665                         Ok(
1666                             if !$boolean {
1667                                 r
1668                             } else {
1669                                 bx.zext(r, bx.cx().type_bool())
1670                             }
1671                         )
1672                     },
1673                     _ => {
1674                         return_error!("unsupported {} from `{}` with element `{}` to `{}`",
1675                                       $name, in_ty, in_elem, ret_ty)
1676                     },
1677                 }
1678             }
1679         }
1680     }
1681
1682     bitwise_red!("simd_reduce_and": vector_reduce_and, false);
1683     bitwise_red!("simd_reduce_or": vector_reduce_or, false);
1684     bitwise_red!("simd_reduce_xor": vector_reduce_xor, false);
1685     bitwise_red!("simd_reduce_all": vector_reduce_and, true);
1686     bitwise_red!("simd_reduce_any": vector_reduce_or, true);
1687
1688     if name == "simd_cast" {
1689         require_simd!(ret_ty, "return");
1690         let out_len = ret_ty.simd_size(tcx);
1691         require!(in_len == out_len,
1692                  "expected return type with length {} (same as input type `{}`), \
1693                   found `{}` with length {}",
1694                  in_len, in_ty,
1695                  ret_ty, out_len);
1696         // casting cares about nominal type, not just structural type
1697         let out_elem = ret_ty.simd_type(tcx);
1698
1699         if in_elem == out_elem { return Ok(args[0].immediate()); }
1700
1701         enum Style { Float, Int(/* is signed? */ bool), Unsupported }
1702
1703         let (in_style, in_width) = match in_elem.sty {
1704             // vectors of pointer-sized integers should've been
1705             // disallowed before here, so this unwrap is safe.
1706             ty::Int(i) => (Style::Int(true), i.bit_width().unwrap()),
1707             ty::Uint(u) => (Style::Int(false), u.bit_width().unwrap()),
1708             ty::Float(f) => (Style::Float, f.bit_width()),
1709             _ => (Style::Unsupported, 0)
1710         };
1711         let (out_style, out_width) = match out_elem.sty {
1712             ty::Int(i) => (Style::Int(true), i.bit_width().unwrap()),
1713             ty::Uint(u) => (Style::Int(false), u.bit_width().unwrap()),
1714             ty::Float(f) => (Style::Float, f.bit_width()),
1715             _ => (Style::Unsupported, 0)
1716         };
1717
1718         match (in_style, out_style) {
1719             (Style::Int(in_is_signed), Style::Int(_)) => {
1720                 return Ok(match in_width.cmp(&out_width) {
1721                     Ordering::Greater => bx.trunc(args[0].immediate(), llret_ty),
1722                     Ordering::Equal => args[0].immediate(),
1723                     Ordering::Less => if in_is_signed {
1724                         bx.sext(args[0].immediate(), llret_ty)
1725                     } else {
1726                         bx.zext(args[0].immediate(), llret_ty)
1727                     }
1728                 })
1729             }
1730             (Style::Int(in_is_signed), Style::Float) => {
1731                 return Ok(if in_is_signed {
1732                     bx.sitofp(args[0].immediate(), llret_ty)
1733                 } else {
1734                     bx.uitofp(args[0].immediate(), llret_ty)
1735                 })
1736             }
1737             (Style::Float, Style::Int(out_is_signed)) => {
1738                 return Ok(if out_is_signed {
1739                     bx.fptosi(args[0].immediate(), llret_ty)
1740                 } else {
1741                     bx.fptoui(args[0].immediate(), llret_ty)
1742                 })
1743             }
1744             (Style::Float, Style::Float) => {
1745                 return Ok(match in_width.cmp(&out_width) {
1746                     Ordering::Greater => bx.fptrunc(args[0].immediate(), llret_ty),
1747                     Ordering::Equal => args[0].immediate(),
1748                     Ordering::Less => bx.fpext(args[0].immediate(), llret_ty)
1749                 })
1750             }
1751             _ => {/* Unsupported. Fallthrough. */}
1752         }
1753         require!(false,
1754                  "unsupported cast from `{}` with element `{}` to `{}` with element `{}`",
1755                  in_ty, in_elem,
1756                  ret_ty, out_elem);
1757     }
1758     macro_rules! arith {
1759         ($($name: ident: $($($p: ident),* => $call: ident),*;)*) => {
1760             $(if name == stringify!($name) {
1761                 match in_elem.sty {
1762                     $($(ty::$p(_))|* => {
1763                         return Ok(bx.$call(args[0].immediate(), args[1].immediate()))
1764                     })*
1765                     _ => {},
1766                 }
1767                 require!(false,
1768                          "unsupported operation on `{}` with element `{}`",
1769                          in_ty,
1770                          in_elem)
1771             })*
1772         }
1773     }
1774     arith! {
1775         simd_add: Uint, Int => add, Float => fadd;
1776         simd_sub: Uint, Int => sub, Float => fsub;
1777         simd_mul: Uint, Int => mul, Float => fmul;
1778         simd_div: Uint => udiv, Int => sdiv, Float => fdiv;
1779         simd_rem: Uint => urem, Int => srem, Float => frem;
1780         simd_shl: Uint, Int => shl;
1781         simd_shr: Uint => lshr, Int => ashr;
1782         simd_and: Uint, Int => and;
1783         simd_or: Uint, Int => or;
1784         simd_xor: Uint, Int => xor;
1785         simd_fmax: Float => maxnum;
1786         simd_fmin: Float => minnum;
1787     }
1788     span_bug!(span, "unknown SIMD intrinsic");
1789 }
1790
1791 // Returns the width of an int Ty, and if it's signed or not
1792 // Returns None if the type is not an integer
1793 // FIXME: there’s multiple of this functions, investigate using some of the already existing
1794 // stuffs.
1795 fn int_type_width_signed(ty: Ty, cx: &CodegenCx) -> Option<(u64, bool)> {
1796     match ty.sty {
1797         ty::Int(t) => Some((match t {
1798             ast::IntTy::Isize => cx.tcx.sess.target.isize_ty.bit_width().unwrap() as u64,
1799             ast::IntTy::I8 => 8,
1800             ast::IntTy::I16 => 16,
1801             ast::IntTy::I32 => 32,
1802             ast::IntTy::I64 => 64,
1803             ast::IntTy::I128 => 128,
1804         }, true)),
1805         ty::Uint(t) => Some((match t {
1806             ast::UintTy::Usize => cx.tcx.sess.target.usize_ty.bit_width().unwrap() as u64,
1807             ast::UintTy::U8 => 8,
1808             ast::UintTy::U16 => 16,
1809             ast::UintTy::U32 => 32,
1810             ast::UintTy::U64 => 64,
1811             ast::UintTy::U128 => 128,
1812         }, false)),
1813         _ => None,
1814     }
1815 }
1816
1817 // Returns the width of a float TypeVariant
1818 // Returns None if the type is not a float
1819 fn float_type_width<'tcx>(sty: &ty::TyKind<'tcx>) -> Option<u64> {
1820     match *sty {
1821         ty::Float(t) => Some(t.bit_width() as u64),
1822         _ => None,
1823     }
1824 }