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