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