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