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