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