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