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