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