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