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