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