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