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