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