]> git.lizzy.rs Git - rust.git/blob - src/librustc_codegen_llvm/intrinsic.rs
Auto merge of #74526 - erikdesjardins:reftrack, r=Mark-Simulacrum
[rust.git] / src / librustc_codegen_llvm / intrinsic.rs
1 use crate::abi::{Abi, FnAbi, 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 log::debug;
11
12 use rustc_ast::ast;
13 use rustc_codegen_ssa::base::{compare_simd_types, to_immediate, wants_msvc_seh};
14 use rustc_codegen_ssa::common::span_invalid_monomorphization_error;
15 use rustc_codegen_ssa::common::{IntPredicate, TypeKind};
16 use rustc_codegen_ssa::coverageinfo::ExprKind;
17 use rustc_codegen_ssa::glue;
18 use rustc_codegen_ssa::mir::operand::{OperandRef, OperandValue};
19 use rustc_codegen_ssa::mir::place::PlaceRef;
20 use rustc_codegen_ssa::traits::*;
21 use rustc_codegen_ssa::MemFlags;
22 use rustc_hir as hir;
23 use rustc_middle::mir::coverage;
24 use rustc_middle::mir::Operand;
25 use rustc_middle::ty::layout::{FnAbiExt, HasTyCtxt};
26 use rustc_middle::ty::{self, Ty};
27 use rustc_middle::{bug, span_bug};
28 use rustc_span::{sym, symbol::kw, Span, Symbol};
29 use rustc_target::abi::{self, HasDataLayout, LayoutOf, Primitive};
30 use rustc_target::spec::PanicStrategy;
31
32 use std::cmp::Ordering;
33 use std::iter;
34
35 fn get_simple_intrinsic(cx: &CodegenCx<'ll, '_>, name: Symbol) -> Option<&'ll Value> {
36     let llvm_name = match name {
37         sym::sqrtf32 => "llvm.sqrt.f32",
38         sym::sqrtf64 => "llvm.sqrt.f64",
39         sym::powif32 => "llvm.powi.f32",
40         sym::powif64 => "llvm.powi.f64",
41         sym::sinf32 => "llvm.sin.f32",
42         sym::sinf64 => "llvm.sin.f64",
43         sym::cosf32 => "llvm.cos.f32",
44         sym::cosf64 => "llvm.cos.f64",
45         sym::powf32 => "llvm.pow.f32",
46         sym::powf64 => "llvm.pow.f64",
47         sym::expf32 => "llvm.exp.f32",
48         sym::expf64 => "llvm.exp.f64",
49         sym::exp2f32 => "llvm.exp2.f32",
50         sym::exp2f64 => "llvm.exp2.f64",
51         sym::logf32 => "llvm.log.f32",
52         sym::logf64 => "llvm.log.f64",
53         sym::log10f32 => "llvm.log10.f32",
54         sym::log10f64 => "llvm.log10.f64",
55         sym::log2f32 => "llvm.log2.f32",
56         sym::log2f64 => "llvm.log2.f64",
57         sym::fmaf32 => "llvm.fma.f32",
58         sym::fmaf64 => "llvm.fma.f64",
59         sym::fabsf32 => "llvm.fabs.f32",
60         sym::fabsf64 => "llvm.fabs.f64",
61         sym::minnumf32 => "llvm.minnum.f32",
62         sym::minnumf64 => "llvm.minnum.f64",
63         sym::maxnumf32 => "llvm.maxnum.f32",
64         sym::maxnumf64 => "llvm.maxnum.f64",
65         sym::copysignf32 => "llvm.copysign.f32",
66         sym::copysignf64 => "llvm.copysign.f64",
67         sym::floorf32 => "llvm.floor.f32",
68         sym::floorf64 => "llvm.floor.f64",
69         sym::ceilf32 => "llvm.ceil.f32",
70         sym::ceilf64 => "llvm.ceil.f64",
71         sym::truncf32 => "llvm.trunc.f32",
72         sym::truncf64 => "llvm.trunc.f64",
73         sym::rintf32 => "llvm.rint.f32",
74         sym::rintf64 => "llvm.rint.f64",
75         sym::nearbyintf32 => "llvm.nearbyint.f32",
76         sym::nearbyintf64 => "llvm.nearbyint.f64",
77         sym::roundf32 => "llvm.round.f32",
78         sym::roundf64 => "llvm.round.f64",
79         sym::assume => "llvm.assume",
80         sym::abort => "llvm.trap",
81         _ => return None,
82     };
83     Some(cx.get_intrinsic(&llvm_name))
84 }
85
86 impl IntrinsicCallMethods<'tcx> for Builder<'a, 'll, 'tcx> {
87     fn is_codegen_intrinsic(
88         &mut self,
89         intrinsic: Symbol,
90         args: &Vec<Operand<'tcx>>,
91         caller_instance: ty::Instance<'tcx>,
92     ) -> bool {
93         let mut is_codegen_intrinsic = true;
94         // Set `is_codegen_intrinsic` to `false` to bypass `codegen_intrinsic_call()`.
95
96         if self.tcx.sess.opts.debugging_opts.instrument_coverage {
97             // If the intrinsic is from the local MIR, add the coverage information to the Codegen
98             // context, to be encoded into the local crate's coverage map.
99             if caller_instance.def_id().is_local() {
100                 // FIXME(richkadel): Make sure to add coverage analysis tests on a crate with
101                 // external crate dependencies, where:
102                 //   1. Both binary and dependent crates are compiled with `-Zinstrument-coverage`
103                 //   2. Only binary is compiled with `-Zinstrument-coverage`
104                 //   3. Only dependent crates are compiled with `-Zinstrument-coverage`
105                 match intrinsic {
106                     sym::count_code_region => {
107                         use coverage::count_code_region_args::*;
108                         self.add_counter_region(
109                             caller_instance,
110                             op_to_u64(&args[FUNCTION_SOURCE_HASH]),
111                             op_to_u32(&args[COUNTER_ID]),
112                             op_to_u32(&args[START_BYTE_POS]),
113                             op_to_u32(&args[END_BYTE_POS]),
114                         );
115                     }
116                     sym::coverage_counter_add | sym::coverage_counter_subtract => {
117                         use coverage::coverage_counter_expression_args::*;
118                         self.add_counter_expression_region(
119                             caller_instance,
120                             op_to_u32(&args[EXPRESSION_ID]),
121                             op_to_u32(&args[LEFT_ID]),
122                             if intrinsic == sym::coverage_counter_add {
123                                 ExprKind::Add
124                             } else {
125                                 ExprKind::Subtract
126                             },
127                             op_to_u32(&args[RIGHT_ID]),
128                             op_to_u32(&args[START_BYTE_POS]),
129                             op_to_u32(&args[END_BYTE_POS]),
130                         );
131                     }
132                     sym::coverage_unreachable => {
133                         use coverage::coverage_unreachable_args::*;
134                         self.add_unreachable_region(
135                             caller_instance,
136                             op_to_u32(&args[START_BYTE_POS]),
137                             op_to_u32(&args[END_BYTE_POS]),
138                         );
139                     }
140                     _ => {}
141                 }
142             }
143
144             // Only the `count_code_region` coverage intrinsic is translated into an actual LLVM
145             // intrinsic call (local or not); otherwise, set `is_codegen_intrinsic` to `false`.
146             match intrinsic {
147                 sym::coverage_counter_add
148                 | sym::coverage_counter_subtract
149                 | sym::coverage_unreachable => {
150                     is_codegen_intrinsic = false;
151                 }
152                 _ => {}
153             }
154         }
155         is_codegen_intrinsic
156     }
157
158     fn codegen_intrinsic_call(
159         &mut self,
160         instance: ty::Instance<'tcx>,
161         fn_abi: &FnAbi<'tcx, Ty<'tcx>>,
162         args: &[OperandRef<'tcx, &'ll Value>],
163         llresult: &'ll Value,
164         span: Span,
165         caller_instance: ty::Instance<'tcx>,
166     ) {
167         let tcx = self.tcx;
168         let callee_ty = instance.ty(tcx, ty::ParamEnv::reveal_all());
169
170         let (def_id, substs) = match callee_ty.kind {
171             ty::FnDef(def_id, substs) => (def_id, substs),
172             _ => bug!("expected fn item type, found {}", callee_ty),
173         };
174
175         let sig = callee_ty.fn_sig(tcx);
176         let sig = tcx.normalize_erasing_late_bound_regions(ty::ParamEnv::reveal_all(), &sig);
177         let arg_tys = sig.inputs();
178         let ret_ty = sig.output();
179         let name = tcx.item_name(def_id);
180         let name_str = &*name.as_str();
181
182         let llret_ty = self.layout_of(ret_ty).llvm_type(self);
183         let result = PlaceRef::new_sized(llresult, fn_abi.ret.layout);
184
185         let simple = get_simple_intrinsic(self, name);
186         let llval = match name {
187             _ if simple.is_some() => self.call(
188                 simple.unwrap(),
189                 &args.iter().map(|arg| arg.immediate()).collect::<Vec<_>>(),
190                 None,
191             ),
192             sym::unreachable => {
193                 return;
194             }
195             sym::likely => {
196                 let expect = self.get_intrinsic(&("llvm.expect.i1"));
197                 self.call(expect, &[args[0].immediate(), self.const_bool(true)], None)
198             }
199             sym::unlikely => {
200                 let expect = self.get_intrinsic(&("llvm.expect.i1"));
201                 self.call(expect, &[args[0].immediate(), self.const_bool(false)], None)
202             }
203             kw::Try => {
204                 try_intrinsic(
205                     self,
206                     args[0].immediate(),
207                     args[1].immediate(),
208                     args[2].immediate(),
209                     llresult,
210                 );
211                 return;
212             }
213             sym::breakpoint => {
214                 let llfn = self.get_intrinsic(&("llvm.debugtrap"));
215                 self.call(llfn, &[], None)
216             }
217             sym::count_code_region => {
218                 // FIXME(richkadel): The current implementation assumes the MIR for the given
219                 // caller_instance represents a single function. Validate and/or correct if inlining
220                 // and/or monomorphization invalidates these assumptions.
221                 let coverageinfo = tcx.coverageinfo(caller_instance.def_id());
222                 let mangled_fn = tcx.symbol_name(caller_instance);
223                 let (mangled_fn_name, _len_val) = self.const_str(Symbol::intern(mangled_fn.name));
224                 let num_counters = self.const_u32(coverageinfo.num_counters);
225                 use coverage::count_code_region_args::*;
226                 let hash = args[FUNCTION_SOURCE_HASH].immediate();
227                 let index = args[COUNTER_ID].immediate();
228                 debug!(
229                     "translating Rust intrinsic `count_code_region()` to LLVM intrinsic: \
230                     instrprof.increment(fn_name={}, hash={:?}, num_counters={:?}, index={:?})",
231                     mangled_fn.name, hash, num_counters, index,
232                 );
233                 self.instrprof_increment(mangled_fn_name, hash, num_counters, index)
234             }
235             sym::va_start => self.va_start(args[0].immediate()),
236             sym::va_end => self.va_end(args[0].immediate()),
237             sym::va_copy => {
238                 let intrinsic = self.cx().get_intrinsic(&("llvm.va_copy"));
239                 self.call(intrinsic, &[args[0].immediate(), args[1].immediate()], None)
240             }
241             sym::va_arg => {
242                 match fn_abi.ret.layout.abi {
243                     abi::Abi::Scalar(ref scalar) => {
244                         match scalar.value {
245                             Primitive::Int(..) => {
246                                 if self.cx().size_of(ret_ty).bytes() < 4 {
247                                     // `va_arg` should not be called on a integer type
248                                     // less than 4 bytes in length. If it is, promote
249                                     // the integer to a `i32` and truncate the result
250                                     // back to the smaller type.
251                                     let promoted_result = emit_va_arg(self, args[0], tcx.types.i32);
252                                     self.trunc(promoted_result, llret_ty)
253                                 } else {
254                                     emit_va_arg(self, args[0], ret_ty)
255                                 }
256                             }
257                             Primitive::F64 | Primitive::Pointer => {
258                                 emit_va_arg(self, args[0], ret_ty)
259                             }
260                             // `va_arg` should never be used with the return type f32.
261                             Primitive::F32 => bug!("the va_arg intrinsic does not work with `f32`"),
262                         }
263                     }
264                     _ => bug!("the va_arg intrinsic does not work with non-scalar types"),
265                 }
266             }
267             sym::size_of_val => {
268                 let tp_ty = substs.type_at(0);
269                 if let OperandValue::Pair(_, meta) = args[0].val {
270                     let (llsize, _) = glue::size_and_align_of_dst(self, tp_ty, Some(meta));
271                     llsize
272                 } else {
273                     self.const_usize(self.size_of(tp_ty).bytes())
274                 }
275             }
276             sym::min_align_of_val => {
277                 let tp_ty = substs.type_at(0);
278                 if let OperandValue::Pair(_, meta) = args[0].val {
279                     let (_, llalign) = glue::size_and_align_of_dst(self, tp_ty, Some(meta));
280                     llalign
281                 } else {
282                     self.const_usize(self.align_of(tp_ty).bytes())
283                 }
284             }
285             sym::size_of
286             | sym::pref_align_of
287             | sym::min_align_of
288             | sym::needs_drop
289             | sym::type_id
290             | sym::type_name
291             | sym::variant_count => {
292                 let value = self
293                     .tcx
294                     .const_eval_instance(ty::ParamEnv::reveal_all(), instance, None)
295                     .unwrap();
296                 OperandRef::from_const(self, value, ret_ty).immediate_or_packed_pair(self)
297             }
298             // Effectively no-op
299             sym::forget => {
300                 return;
301             }
302             sym::offset => {
303                 let ptr = args[0].immediate();
304                 let offset = args[1].immediate();
305                 self.inbounds_gep(ptr, &[offset])
306             }
307             sym::arith_offset => {
308                 let ptr = args[0].immediate();
309                 let offset = args[1].immediate();
310                 self.gep(ptr, &[offset])
311             }
312
313             sym::copy_nonoverlapping => {
314                 copy_intrinsic(
315                     self,
316                     false,
317                     false,
318                     substs.type_at(0),
319                     args[1].immediate(),
320                     args[0].immediate(),
321                     args[2].immediate(),
322                 );
323                 return;
324             }
325             sym::copy => {
326                 copy_intrinsic(
327                     self,
328                     true,
329                     false,
330                     substs.type_at(0),
331                     args[1].immediate(),
332                     args[0].immediate(),
333                     args[2].immediate(),
334                 );
335                 return;
336             }
337             sym::write_bytes => {
338                 memset_intrinsic(
339                     self,
340                     false,
341                     substs.type_at(0),
342                     args[0].immediate(),
343                     args[1].immediate(),
344                     args[2].immediate(),
345                 );
346                 return;
347             }
348
349             sym::volatile_copy_nonoverlapping_memory => {
350                 copy_intrinsic(
351                     self,
352                     false,
353                     true,
354                     substs.type_at(0),
355                     args[0].immediate(),
356                     args[1].immediate(),
357                     args[2].immediate(),
358                 );
359                 return;
360             }
361             sym::volatile_copy_memory => {
362                 copy_intrinsic(
363                     self,
364                     true,
365                     true,
366                     substs.type_at(0),
367                     args[0].immediate(),
368                     args[1].immediate(),
369                     args[2].immediate(),
370                 );
371                 return;
372             }
373             sym::volatile_set_memory => {
374                 memset_intrinsic(
375                     self,
376                     true,
377                     substs.type_at(0),
378                     args[0].immediate(),
379                     args[1].immediate(),
380                     args[2].immediate(),
381                 );
382                 return;
383             }
384             sym::volatile_load | sym::unaligned_volatile_load => {
385                 let tp_ty = substs.type_at(0);
386                 let mut ptr = args[0].immediate();
387                 if let PassMode::Cast(ty) = fn_abi.ret.mode {
388                     ptr = self.pointercast(ptr, self.type_ptr_to(ty.llvm_type(self)));
389                 }
390                 let load = self.volatile_load(ptr);
391                 let align = if name == sym::unaligned_volatile_load {
392                     1
393                 } else {
394                     self.align_of(tp_ty).bytes() as u32
395                 };
396                 unsafe {
397                     llvm::LLVMSetAlignment(load, align);
398                 }
399                 to_immediate(self, load, self.layout_of(tp_ty))
400             }
401             sym::volatile_store => {
402                 let dst = args[0].deref(self.cx());
403                 args[1].val.volatile_store(self, dst);
404                 return;
405             }
406             sym::unaligned_volatile_store => {
407                 let dst = args[0].deref(self.cx());
408                 args[1].val.unaligned_volatile_store(self, dst);
409                 return;
410             }
411             sym::prefetch_read_data
412             | sym::prefetch_write_data
413             | sym::prefetch_read_instruction
414             | sym::prefetch_write_instruction => {
415                 let expect = self.get_intrinsic(&("llvm.prefetch"));
416                 let (rw, cache_type) = match name {
417                     sym::prefetch_read_data => (0, 1),
418                     sym::prefetch_write_data => (1, 1),
419                     sym::prefetch_read_instruction => (0, 0),
420                     sym::prefetch_write_instruction => (1, 0),
421                     _ => bug!(),
422                 };
423                 self.call(
424                     expect,
425                     &[
426                         args[0].immediate(),
427                         self.const_i32(rw),
428                         args[1].immediate(),
429                         self.const_i32(cache_type),
430                     ],
431                     None,
432                 )
433             }
434             sym::ctlz
435             | sym::ctlz_nonzero
436             | sym::cttz
437             | sym::cttz_nonzero
438             | sym::ctpop
439             | sym::bswap
440             | sym::bitreverse
441             | sym::add_with_overflow
442             | sym::sub_with_overflow
443             | sym::mul_with_overflow
444             | sym::wrapping_add
445             | sym::wrapping_sub
446             | sym::wrapping_mul
447             | sym::unchecked_div
448             | sym::unchecked_rem
449             | sym::unchecked_shl
450             | sym::unchecked_shr
451             | sym::unchecked_add
452             | sym::unchecked_sub
453             | sym::unchecked_mul
454             | sym::exact_div
455             | sym::rotate_left
456             | sym::rotate_right
457             | sym::saturating_add
458             | sym::saturating_sub => {
459                 let ty = arg_tys[0];
460                 match int_type_width_signed(ty, self) {
461                     Some((width, signed)) => match name {
462                         sym::ctlz | sym::cttz => {
463                             let y = self.const_bool(false);
464                             let llfn = self.get_intrinsic(&format!("llvm.{}.i{}", name, width));
465                             self.call(llfn, &[args[0].immediate(), y], None)
466                         }
467                         sym::ctlz_nonzero | sym::cttz_nonzero => {
468                             let y = self.const_bool(true);
469                             let llvm_name = &format!("llvm.{}.i{}", &name_str[..4], width);
470                             let llfn = self.get_intrinsic(llvm_name);
471                             self.call(llfn, &[args[0].immediate(), y], None)
472                         }
473                         sym::ctpop => self.call(
474                             self.get_intrinsic(&format!("llvm.ctpop.i{}", width)),
475                             &[args[0].immediate()],
476                             None,
477                         ),
478                         sym::bswap => {
479                             if width == 8 {
480                                 args[0].immediate() // byte swap a u8/i8 is just a no-op
481                             } else {
482                                 self.call(
483                                     self.get_intrinsic(&format!("llvm.bswap.i{}", width)),
484                                     &[args[0].immediate()],
485                                     None,
486                                 )
487                             }
488                         }
489                         sym::bitreverse => self.call(
490                             self.get_intrinsic(&format!("llvm.bitreverse.i{}", width)),
491                             &[args[0].immediate()],
492                             None,
493                         ),
494                         sym::add_with_overflow
495                         | sym::sub_with_overflow
496                         | sym::mul_with_overflow => {
497                             let intrinsic = format!(
498                                 "llvm.{}{}.with.overflow.i{}",
499                                 if signed { 's' } else { 'u' },
500                                 &name_str[..3],
501                                 width
502                             );
503                             let llfn = self.get_intrinsic(&intrinsic);
504
505                             // Convert `i1` to a `bool`, and write it to the out parameter
506                             let pair =
507                                 self.call(llfn, &[args[0].immediate(), args[1].immediate()], None);
508                             let val = self.extract_value(pair, 0);
509                             let overflow = self.extract_value(pair, 1);
510                             let overflow = self.zext(overflow, self.type_bool());
511
512                             let dest = result.project_field(self, 0);
513                             self.store(val, dest.llval, dest.align);
514                             let dest = result.project_field(self, 1);
515                             self.store(overflow, dest.llval, dest.align);
516
517                             return;
518                         }
519                         sym::wrapping_add => self.add(args[0].immediate(), args[1].immediate()),
520                         sym::wrapping_sub => self.sub(args[0].immediate(), args[1].immediate()),
521                         sym::wrapping_mul => self.mul(args[0].immediate(), args[1].immediate()),
522                         sym::exact_div => {
523                             if signed {
524                                 self.exactsdiv(args[0].immediate(), args[1].immediate())
525                             } else {
526                                 self.exactudiv(args[0].immediate(), args[1].immediate())
527                             }
528                         }
529                         sym::unchecked_div => {
530                             if signed {
531                                 self.sdiv(args[0].immediate(), args[1].immediate())
532                             } else {
533                                 self.udiv(args[0].immediate(), args[1].immediate())
534                             }
535                         }
536                         sym::unchecked_rem => {
537                             if signed {
538                                 self.srem(args[0].immediate(), args[1].immediate())
539                             } else {
540                                 self.urem(args[0].immediate(), args[1].immediate())
541                             }
542                         }
543                         sym::unchecked_shl => self.shl(args[0].immediate(), args[1].immediate()),
544                         sym::unchecked_shr => {
545                             if signed {
546                                 self.ashr(args[0].immediate(), args[1].immediate())
547                             } else {
548                                 self.lshr(args[0].immediate(), args[1].immediate())
549                             }
550                         }
551                         sym::unchecked_add => {
552                             if signed {
553                                 self.unchecked_sadd(args[0].immediate(), args[1].immediate())
554                             } else {
555                                 self.unchecked_uadd(args[0].immediate(), args[1].immediate())
556                             }
557                         }
558                         sym::unchecked_sub => {
559                             if signed {
560                                 self.unchecked_ssub(args[0].immediate(), args[1].immediate())
561                             } else {
562                                 self.unchecked_usub(args[0].immediate(), args[1].immediate())
563                             }
564                         }
565                         sym::unchecked_mul => {
566                             if signed {
567                                 self.unchecked_smul(args[0].immediate(), args[1].immediate())
568                             } else {
569                                 self.unchecked_umul(args[0].immediate(), args[1].immediate())
570                             }
571                         }
572                         sym::rotate_left | sym::rotate_right => {
573                             let is_left = name == sym::rotate_left;
574                             let val = args[0].immediate();
575                             let raw_shift = args[1].immediate();
576                             // rotate = funnel shift with first two args the same
577                             let llvm_name =
578                                 &format!("llvm.fsh{}.i{}", if is_left { 'l' } else { 'r' }, width);
579                             let llfn = self.get_intrinsic(llvm_name);
580                             self.call(llfn, &[val, val, raw_shift], None)
581                         }
582                         sym::saturating_add | sym::saturating_sub => {
583                             let is_add = name == sym::saturating_add;
584                             let lhs = args[0].immediate();
585                             let rhs = args[1].immediate();
586                             let llvm_name = &format!(
587                                 "llvm.{}{}.sat.i{}",
588                                 if signed { 's' } else { 'u' },
589                                 if is_add { "add" } else { "sub" },
590                                 width
591                             );
592                             let llfn = self.get_intrinsic(llvm_name);
593                             self.call(llfn, &[lhs, rhs], None)
594                         }
595                         _ => bug!(),
596                     },
597                     None => {
598                         span_invalid_monomorphization_error(
599                             tcx.sess,
600                             span,
601                             &format!(
602                                 "invalid monomorphization of `{}` intrinsic: \
603                                       expected basic integer type, found `{}`",
604                                 name, ty
605                             ),
606                         );
607                         return;
608                     }
609                 }
610             }
611             sym::fadd_fast | sym::fsub_fast | sym::fmul_fast | sym::fdiv_fast | sym::frem_fast => {
612                 match float_type_width(arg_tys[0]) {
613                     Some(_width) => match name {
614                         sym::fadd_fast => self.fadd_fast(args[0].immediate(), args[1].immediate()),
615                         sym::fsub_fast => self.fsub_fast(args[0].immediate(), args[1].immediate()),
616                         sym::fmul_fast => self.fmul_fast(args[0].immediate(), args[1].immediate()),
617                         sym::fdiv_fast => self.fdiv_fast(args[0].immediate(), args[1].immediate()),
618                         sym::frem_fast => self.frem_fast(args[0].immediate(), args[1].immediate()),
619                         _ => bug!(),
620                     },
621                     None => {
622                         span_invalid_monomorphization_error(
623                             tcx.sess,
624                             span,
625                             &format!(
626                                 "invalid monomorphization of `{}` intrinsic: \
627                                       expected basic float type, found `{}`",
628                                 name, arg_tys[0]
629                             ),
630                         );
631                         return;
632                     }
633                 }
634             }
635
636             sym::float_to_int_unchecked => {
637                 let float_width = match float_type_width(arg_tys[0]) {
638                     Some(width) => width,
639                     None => {
640                         span_invalid_monomorphization_error(
641                             tcx.sess,
642                             span,
643                             &format!(
644                                 "invalid monomorphization of `float_to_int_unchecked` \
645                                   intrinsic: expected basic float type, \
646                                   found `{}`",
647                                 arg_tys[0]
648                             ),
649                         );
650                         return;
651                     }
652                 };
653                 let (width, signed) = match int_type_width_signed(ret_ty, self.cx) {
654                     Some(pair) => pair,
655                     None => {
656                         span_invalid_monomorphization_error(
657                             tcx.sess,
658                             span,
659                             &format!(
660                                 "invalid monomorphization of `float_to_int_unchecked` \
661                                       intrinsic:  expected basic integer type, \
662                                       found `{}`",
663                                 ret_ty
664                             ),
665                         );
666                         return;
667                     }
668                 };
669
670                 // The LLVM backend can reorder and speculate `fptosi` and
671                 // `fptoui`, so on WebAssembly the codegen for this instruction
672                 // is quite heavyweight. To avoid this heavyweight codegen we
673                 // instead use the raw wasm intrinsics which will lower to one
674                 // instruction in WebAssembly (`iNN.trunc_fMM_{s,u}`). This one
675                 // instruction will trap if the operand is out of bounds, but
676                 // that's ok since this intrinsic is UB if the operands are out
677                 // of bounds, so the behavior can be different on WebAssembly
678                 // than other targets.
679                 //
680                 // Note, however, that when the `nontrapping-fptoint` feature is
681                 // enabled in LLVM then LLVM will lower `fptosi` to
682                 // `iNN.trunc_sat_fMM_{s,u}`, so if that's the case we don't
683                 // bother with intrinsics.
684                 let mut result = None;
685                 if self.sess().target.target.arch == "wasm32"
686                     && !self.sess().target_features.contains(&sym::nontrapping_dash_fptoint)
687                 {
688                     let name = match (width, float_width, signed) {
689                         (32, 32, true) => Some("llvm.wasm.trunc.signed.i32.f32"),
690                         (32, 64, true) => Some("llvm.wasm.trunc.signed.i32.f64"),
691                         (64, 32, true) => Some("llvm.wasm.trunc.signed.i64.f32"),
692                         (64, 64, true) => Some("llvm.wasm.trunc.signed.i64.f64"),
693                         (32, 32, false) => Some("llvm.wasm.trunc.unsigned.i32.f32"),
694                         (32, 64, false) => Some("llvm.wasm.trunc.unsigned.i32.f64"),
695                         (64, 32, false) => Some("llvm.wasm.trunc.unsigned.i64.f32"),
696                         (64, 64, false) => Some("llvm.wasm.trunc.unsigned.i64.f64"),
697                         _ => None,
698                     };
699                     if let Some(name) = name {
700                         let intrinsic = self.get_intrinsic(name);
701                         result = Some(self.call(intrinsic, &[args[0].immediate()], None));
702                     }
703                 }
704                 result.unwrap_or_else(|| {
705                     if signed {
706                         self.fptosi(args[0].immediate(), self.cx.type_ix(width))
707                     } else {
708                         self.fptoui(args[0].immediate(), self.cx.type_ix(width))
709                     }
710                 })
711             }
712
713             sym::discriminant_value => {
714                 if ret_ty.is_integral() {
715                     args[0].deref(self.cx()).codegen_get_discr(self, ret_ty)
716                 } else {
717                     span_bug!(span, "Invalid discriminant type for `{:?}`", arg_tys[0])
718                 }
719             }
720
721             _ if name_str.starts_with("simd_") => {
722                 match generic_simd_intrinsic(self, name, callee_ty, args, ret_ty, llret_ty, span) {
723                     Ok(llval) => llval,
724                     Err(()) => return,
725                 }
726             }
727             // This requires that atomic intrinsics follow a specific naming pattern:
728             // "atomic_<operation>[_<ordering>]", and no ordering means SeqCst
729             name if name_str.starts_with("atomic_") => {
730                 use rustc_codegen_ssa::common::AtomicOrdering::*;
731                 use rustc_codegen_ssa::common::{AtomicRmwBinOp, SynchronizationScope};
732
733                 let split: Vec<&str> = name_str.split('_').collect();
734
735                 let is_cxchg = split[1] == "cxchg" || split[1] == "cxchgweak";
736                 let (order, failorder) = match split.len() {
737                     2 => (SequentiallyConsistent, SequentiallyConsistent),
738                     3 => match split[2] {
739                         "unordered" => (Unordered, Unordered),
740                         "relaxed" => (Monotonic, Monotonic),
741                         "acq" => (Acquire, Acquire),
742                         "rel" => (Release, Monotonic),
743                         "acqrel" => (AcquireRelease, Acquire),
744                         "failrelaxed" if is_cxchg => (SequentiallyConsistent, Monotonic),
745                         "failacq" if is_cxchg => (SequentiallyConsistent, Acquire),
746                         _ => self.sess().fatal("unknown ordering in atomic intrinsic"),
747                     },
748                     4 => match (split[2], split[3]) {
749                         ("acq", "failrelaxed") if is_cxchg => (Acquire, Monotonic),
750                         ("acqrel", "failrelaxed") if is_cxchg => (AcquireRelease, Monotonic),
751                         _ => self.sess().fatal("unknown ordering in atomic intrinsic"),
752                     },
753                     _ => self.sess().fatal("Atomic intrinsic not in correct format"),
754                 };
755
756                 let invalid_monomorphization = |ty| {
757                     span_invalid_monomorphization_error(
758                         tcx.sess,
759                         span,
760                         &format!(
761                             "invalid monomorphization of `{}` intrinsic: \
762                                   expected basic integer type, found `{}`",
763                             name, ty
764                         ),
765                     );
766                 };
767
768                 match split[1] {
769                     "cxchg" | "cxchgweak" => {
770                         let ty = substs.type_at(0);
771                         if int_type_width_signed(ty, self).is_some() {
772                             let weak = split[1] == "cxchgweak";
773                             let pair = self.atomic_cmpxchg(
774                                 args[0].immediate(),
775                                 args[1].immediate(),
776                                 args[2].immediate(),
777                                 order,
778                                 failorder,
779                                 weak,
780                             );
781                             let val = self.extract_value(pair, 0);
782                             let success = self.extract_value(pair, 1);
783                             let success = self.zext(success, self.type_bool());
784
785                             let dest = result.project_field(self, 0);
786                             self.store(val, dest.llval, dest.align);
787                             let dest = result.project_field(self, 1);
788                             self.store(success, dest.llval, dest.align);
789                             return;
790                         } else {
791                             return invalid_monomorphization(ty);
792                         }
793                     }
794
795                     "load" => {
796                         let ty = substs.type_at(0);
797                         if int_type_width_signed(ty, self).is_some() {
798                             let size = self.size_of(ty);
799                             self.atomic_load(args[0].immediate(), order, size)
800                         } else {
801                             return invalid_monomorphization(ty);
802                         }
803                     }
804
805                     "store" => {
806                         let ty = substs.type_at(0);
807                         if int_type_width_signed(ty, self).is_some() {
808                             let size = self.size_of(ty);
809                             self.atomic_store(
810                                 args[1].immediate(),
811                                 args[0].immediate(),
812                                 order,
813                                 size,
814                             );
815                             return;
816                         } else {
817                             return invalid_monomorphization(ty);
818                         }
819                     }
820
821                     "fence" => {
822                         self.atomic_fence(order, SynchronizationScope::CrossThread);
823                         return;
824                     }
825
826                     "singlethreadfence" => {
827                         self.atomic_fence(order, SynchronizationScope::SingleThread);
828                         return;
829                     }
830
831                     // These are all AtomicRMW ops
832                     op => {
833                         let atom_op = match op {
834                             "xchg" => AtomicRmwBinOp::AtomicXchg,
835                             "xadd" => AtomicRmwBinOp::AtomicAdd,
836                             "xsub" => AtomicRmwBinOp::AtomicSub,
837                             "and" => AtomicRmwBinOp::AtomicAnd,
838                             "nand" => AtomicRmwBinOp::AtomicNand,
839                             "or" => AtomicRmwBinOp::AtomicOr,
840                             "xor" => AtomicRmwBinOp::AtomicXor,
841                             "max" => AtomicRmwBinOp::AtomicMax,
842                             "min" => AtomicRmwBinOp::AtomicMin,
843                             "umax" => AtomicRmwBinOp::AtomicUMax,
844                             "umin" => AtomicRmwBinOp::AtomicUMin,
845                             _ => self.sess().fatal("unknown atomic operation"),
846                         };
847
848                         let ty = substs.type_at(0);
849                         if int_type_width_signed(ty, self).is_some() {
850                             self.atomic_rmw(
851                                 atom_op,
852                                 args[0].immediate(),
853                                 args[1].immediate(),
854                                 order,
855                             )
856                         } else {
857                             return invalid_monomorphization(ty);
858                         }
859                     }
860                 }
861             }
862
863             sym::nontemporal_store => {
864                 let dst = args[0].deref(self.cx());
865                 args[1].val.nontemporal_store(self, dst);
866                 return;
867             }
868
869             sym::ptr_guaranteed_eq | sym::ptr_guaranteed_ne => {
870                 let a = args[0].immediate();
871                 let b = args[1].immediate();
872                 if name == sym::ptr_guaranteed_eq {
873                     self.icmp(IntPredicate::IntEQ, a, b)
874                 } else {
875                     self.icmp(IntPredicate::IntNE, a, b)
876                 }
877             }
878
879             sym::ptr_offset_from => {
880                 let ty = substs.type_at(0);
881                 let pointee_size = self.size_of(ty);
882
883                 // This is the same sequence that Clang emits for pointer subtraction.
884                 // It can be neither `nsw` nor `nuw` because the input is treated as
885                 // unsigned but then the output is treated as signed, so neither works.
886                 let a = args[0].immediate();
887                 let b = args[1].immediate();
888                 let a = self.ptrtoint(a, self.type_isize());
889                 let b = self.ptrtoint(b, self.type_isize());
890                 let d = self.sub(a, b);
891                 let pointee_size = self.const_usize(pointee_size.bytes());
892                 // this is where the signed magic happens (notice the `s` in `exactsdiv`)
893                 self.exactsdiv(d, pointee_size)
894             }
895
896             _ => bug!("unknown intrinsic '{}'", name),
897         };
898
899         if !fn_abi.ret.is_ignore() {
900             if let PassMode::Cast(ty) = fn_abi.ret.mode {
901                 let ptr_llty = self.type_ptr_to(ty.llvm_type(self));
902                 let ptr = self.pointercast(result.llval, ptr_llty);
903                 self.store(llval, ptr, result.align);
904             } else {
905                 OperandRef::from_immediate_or_packed_pair(self, llval, result.layout)
906                     .val
907                     .store(self, result);
908             }
909         }
910     }
911
912     fn abort(&mut self) {
913         let fnname = self.get_intrinsic(&("llvm.trap"));
914         self.call(fnname, &[], None);
915     }
916
917     fn assume(&mut self, val: Self::Value) {
918         let assume_intrinsic = self.get_intrinsic("llvm.assume");
919         self.call(assume_intrinsic, &[val], None);
920     }
921
922     fn expect(&mut self, cond: Self::Value, expected: bool) -> Self::Value {
923         let expect = self.get_intrinsic(&"llvm.expect.i1");
924         self.call(expect, &[cond, self.const_bool(expected)], None)
925     }
926
927     fn sideeffect(&mut self) {
928         if self.tcx.sess.opts.debugging_opts.insert_sideeffect {
929             let fnname = self.get_intrinsic(&("llvm.sideeffect"));
930             self.call(fnname, &[], None);
931         }
932     }
933
934     fn va_start(&mut self, va_list: &'ll Value) -> &'ll Value {
935         let intrinsic = self.cx().get_intrinsic("llvm.va_start");
936         self.call(intrinsic, &[va_list], None)
937     }
938
939     fn va_end(&mut self, va_list: &'ll Value) -> &'ll Value {
940         let intrinsic = self.cx().get_intrinsic("llvm.va_end");
941         self.call(intrinsic, &[va_list], None)
942     }
943 }
944
945 fn copy_intrinsic(
946     bx: &mut Builder<'a, 'll, 'tcx>,
947     allow_overlap: bool,
948     volatile: bool,
949     ty: Ty<'tcx>,
950     dst: &'ll Value,
951     src: &'ll Value,
952     count: &'ll Value,
953 ) {
954     let (size, align) = bx.size_and_align_of(ty);
955     let size = bx.mul(bx.const_usize(size.bytes()), count);
956     let flags = if volatile { MemFlags::VOLATILE } else { MemFlags::empty() };
957     if allow_overlap {
958         bx.memmove(dst, align, src, align, size, flags);
959     } else {
960         bx.memcpy(dst, align, src, align, size, flags);
961     }
962 }
963
964 fn memset_intrinsic(
965     bx: &mut Builder<'a, 'll, 'tcx>,
966     volatile: bool,
967     ty: Ty<'tcx>,
968     dst: &'ll Value,
969     val: &'ll Value,
970     count: &'ll Value,
971 ) {
972     let (size, align) = bx.size_and_align_of(ty);
973     let size = bx.mul(bx.const_usize(size.bytes()), count);
974     let flags = if volatile { MemFlags::VOLATILE } else { MemFlags::empty() };
975     bx.memset(dst, val, size, align, flags);
976 }
977
978 fn try_intrinsic(
979     bx: &mut Builder<'a, 'll, 'tcx>,
980     try_func: &'ll Value,
981     data: &'ll Value,
982     catch_func: &'ll Value,
983     dest: &'ll Value,
984 ) {
985     if bx.sess().panic_strategy() == PanicStrategy::Abort {
986         bx.call(try_func, &[data], None);
987         // Return 0 unconditionally from the intrinsic call;
988         // we can never unwind.
989         let ret_align = bx.tcx().data_layout.i32_align.abi;
990         bx.store(bx.const_i32(0), dest, ret_align);
991     } else if wants_msvc_seh(bx.sess()) {
992         codegen_msvc_try(bx, try_func, data, catch_func, dest);
993     } else {
994         codegen_gnu_try(bx, try_func, data, catch_func, dest);
995     }
996 }
997
998 // MSVC's definition of the `rust_try` function.
999 //
1000 // This implementation uses the new exception handling instructions in LLVM
1001 // which have support in LLVM for SEH on MSVC targets. Although these
1002 // instructions are meant to work for all targets, as of the time of this
1003 // writing, however, LLVM does not recommend the usage of these new instructions
1004 // as the old ones are still more optimized.
1005 fn codegen_msvc_try(
1006     bx: &mut Builder<'a, 'll, 'tcx>,
1007     try_func: &'ll Value,
1008     data: &'ll Value,
1009     catch_func: &'ll Value,
1010     dest: &'ll Value,
1011 ) {
1012     let llfn = get_rust_try_fn(bx, &mut |mut bx| {
1013         bx.set_personality_fn(bx.eh_personality());
1014         bx.sideeffect();
1015
1016         let mut normal = bx.build_sibling_block("normal");
1017         let mut catchswitch = bx.build_sibling_block("catchswitch");
1018         let mut catchpad = bx.build_sibling_block("catchpad");
1019         let mut caught = bx.build_sibling_block("caught");
1020
1021         let try_func = llvm::get_param(bx.llfn(), 0);
1022         let data = llvm::get_param(bx.llfn(), 1);
1023         let catch_func = llvm::get_param(bx.llfn(), 2);
1024
1025         // We're generating an IR snippet that looks like:
1026         //
1027         //   declare i32 @rust_try(%try_func, %data, %catch_func) {
1028         //      %slot = alloca u8*
1029         //      invoke %try_func(%data) to label %normal unwind label %catchswitch
1030         //
1031         //   normal:
1032         //      ret i32 0
1033         //
1034         //   catchswitch:
1035         //      %cs = catchswitch within none [%catchpad] unwind to caller
1036         //
1037         //   catchpad:
1038         //      %tok = catchpad within %cs [%type_descriptor, 0, %slot]
1039         //      %ptr = load %slot
1040         //      call %catch_func(%data, %ptr)
1041         //      catchret from %tok to label %caught
1042         //
1043         //   caught:
1044         //      ret i32 1
1045         //   }
1046         //
1047         // This structure follows the basic usage of throw/try/catch in LLVM.
1048         // For example, compile this C++ snippet to see what LLVM generates:
1049         //
1050         //      #include <stdint.h>
1051         //
1052         //      struct rust_panic {
1053         //          rust_panic(const rust_panic&);
1054         //          ~rust_panic();
1055         //
1056         //          uint64_t x[2];
1057         //      };
1058         //
1059         //      int __rust_try(
1060         //          void (*try_func)(void*),
1061         //          void *data,
1062         //          void (*catch_func)(void*, void*) noexcept
1063         //      ) {
1064         //          try {
1065         //              try_func(data);
1066         //              return 0;
1067         //          } catch(rust_panic& a) {
1068         //              catch_func(data, &a);
1069         //              return 1;
1070         //          }
1071         //      }
1072         //
1073         // More information can be found in libstd's seh.rs implementation.
1074         let ptr_align = bx.tcx().data_layout.pointer_align.abi;
1075         let slot = bx.alloca(bx.type_i8p(), ptr_align);
1076         bx.invoke(try_func, &[data], normal.llbb(), catchswitch.llbb(), None);
1077
1078         normal.ret(bx.const_i32(0));
1079
1080         let cs = catchswitch.catch_switch(None, None, 1);
1081         catchswitch.add_handler(cs, catchpad.llbb());
1082
1083         // We can't use the TypeDescriptor defined in libpanic_unwind because it
1084         // might be in another DLL and the SEH encoding only supports specifying
1085         // a TypeDescriptor from the current module.
1086         //
1087         // However this isn't an issue since the MSVC runtime uses string
1088         // comparison on the type name to match TypeDescriptors rather than
1089         // pointer equality.
1090         //
1091         // So instead we generate a new TypeDescriptor in each module that uses
1092         // `try` and let the linker merge duplicate definitions in the same
1093         // module.
1094         //
1095         // When modifying, make sure that the type_name string exactly matches
1096         // the one used in src/libpanic_unwind/seh.rs.
1097         let type_info_vtable = bx.declare_global("??_7type_info@@6B@", bx.type_i8p());
1098         let type_name = bx.const_bytes(b"rust_panic\0");
1099         let type_info =
1100             bx.const_struct(&[type_info_vtable, bx.const_null(bx.type_i8p()), type_name], false);
1101         let tydesc = bx.declare_global("__rust_panic_type_info", bx.val_ty(type_info));
1102         unsafe {
1103             llvm::LLVMRustSetLinkage(tydesc, llvm::Linkage::LinkOnceODRLinkage);
1104             llvm::SetUniqueComdat(bx.llmod, tydesc);
1105             llvm::LLVMSetInitializer(tydesc, type_info);
1106         }
1107
1108         // The flag value of 8 indicates that we are catching the exception by
1109         // reference instead of by value. We can't use catch by value because
1110         // that requires copying the exception object, which we don't support
1111         // since our exception object effectively contains a Box.
1112         //
1113         // Source: MicrosoftCXXABI::getAddrOfCXXCatchHandlerType in clang
1114         let flags = bx.const_i32(8);
1115         let funclet = catchpad.catch_pad(cs, &[tydesc, flags, slot]);
1116         let ptr = catchpad.load(slot, ptr_align);
1117         catchpad.call(catch_func, &[data, ptr], Some(&funclet));
1118
1119         catchpad.catch_ret(&funclet, caught.llbb());
1120
1121         caught.ret(bx.const_i32(1));
1122     });
1123
1124     // Note that no invoke is used here because by definition this function
1125     // can't panic (that's what it's catching).
1126     let ret = bx.call(llfn, &[try_func, data, catch_func], None);
1127     let i32_align = bx.tcx().data_layout.i32_align.abi;
1128     bx.store(ret, dest, i32_align);
1129 }
1130
1131 // Definition of the standard `try` function for Rust using the GNU-like model
1132 // of exceptions (e.g., the normal semantics of LLVM's `landingpad` and `invoke`
1133 // instructions).
1134 //
1135 // This codegen is a little surprising because we always call a shim
1136 // function instead of inlining the call to `invoke` manually here. This is done
1137 // because in LLVM we're only allowed to have one personality per function
1138 // definition. The call to the `try` intrinsic is being inlined into the
1139 // function calling it, and that function may already have other personality
1140 // functions in play. By calling a shim we're guaranteed that our shim will have
1141 // the right personality function.
1142 fn codegen_gnu_try(
1143     bx: &mut Builder<'a, 'll, 'tcx>,
1144     try_func: &'ll Value,
1145     data: &'ll Value,
1146     catch_func: &'ll Value,
1147     dest: &'ll Value,
1148 ) {
1149     let llfn = get_rust_try_fn(bx, &mut |mut bx| {
1150         // Codegens the shims described above:
1151         //
1152         //   bx:
1153         //      invoke %try_func(%data) normal %normal unwind %catch
1154         //
1155         //   normal:
1156         //      ret 0
1157         //
1158         //   catch:
1159         //      (%ptr, _) = landingpad
1160         //      call %catch_func(%data, %ptr)
1161         //      ret 1
1162
1163         bx.sideeffect();
1164
1165         let mut then = bx.build_sibling_block("then");
1166         let mut catch = bx.build_sibling_block("catch");
1167
1168         let try_func = llvm::get_param(bx.llfn(), 0);
1169         let data = llvm::get_param(bx.llfn(), 1);
1170         let catch_func = llvm::get_param(bx.llfn(), 2);
1171         bx.invoke(try_func, &[data], then.llbb(), catch.llbb(), None);
1172         then.ret(bx.const_i32(0));
1173
1174         // Type indicator for the exception being thrown.
1175         //
1176         // The first value in this tuple is a pointer to the exception object
1177         // being thrown.  The second value is a "selector" indicating which of
1178         // the landing pad clauses the exception's type had been matched to.
1179         // rust_try ignores the selector.
1180         let lpad_ty = bx.type_struct(&[bx.type_i8p(), bx.type_i32()], false);
1181         let vals = catch.landing_pad(lpad_ty, bx.eh_personality(), 1);
1182         let tydesc = match bx.tcx().lang_items().eh_catch_typeinfo() {
1183             Some(tydesc) => {
1184                 let tydesc = bx.get_static(tydesc);
1185                 bx.bitcast(tydesc, bx.type_i8p())
1186             }
1187             None => bx.const_null(bx.type_i8p()),
1188         };
1189         catch.add_clause(vals, tydesc);
1190         let ptr = catch.extract_value(vals, 0);
1191         catch.call(catch_func, &[data, ptr], None);
1192         catch.ret(bx.const_i32(1));
1193     });
1194
1195     // Note that no invoke is used here because by definition this function
1196     // can't panic (that's what it's catching).
1197     let ret = bx.call(llfn, &[try_func, data, catch_func], None);
1198     let i32_align = bx.tcx().data_layout.i32_align.abi;
1199     bx.store(ret, dest, i32_align);
1200 }
1201
1202 // Helper function to give a Block to a closure to codegen a shim function.
1203 // This is currently primarily used for the `try` intrinsic functions above.
1204 fn gen_fn<'ll, 'tcx>(
1205     cx: &CodegenCx<'ll, 'tcx>,
1206     name: &str,
1207     inputs: Vec<Ty<'tcx>>,
1208     output: Ty<'tcx>,
1209     codegen: &mut dyn FnMut(Builder<'_, 'll, 'tcx>),
1210 ) -> &'ll Value {
1211     let rust_fn_sig = ty::Binder::bind(cx.tcx.mk_fn_sig(
1212         inputs.into_iter(),
1213         output,
1214         false,
1215         hir::Unsafety::Unsafe,
1216         Abi::Rust,
1217     ));
1218     let fn_abi = FnAbi::of_fn_ptr(cx, rust_fn_sig, &[]);
1219     let llfn = cx.declare_fn(name, &fn_abi);
1220     cx.set_frame_pointer_elimination(llfn);
1221     cx.apply_target_cpu_attr(llfn);
1222     // FIXME(eddyb) find a nicer way to do this.
1223     unsafe { llvm::LLVMRustSetLinkage(llfn, llvm::Linkage::InternalLinkage) };
1224     let bx = Builder::new_block(cx, llfn, "entry-block");
1225     codegen(bx);
1226     llfn
1227 }
1228
1229 // Helper function used to get a handle to the `__rust_try` function used to
1230 // catch exceptions.
1231 //
1232 // This function is only generated once and is then cached.
1233 fn get_rust_try_fn<'ll, 'tcx>(
1234     cx: &CodegenCx<'ll, 'tcx>,
1235     codegen: &mut dyn FnMut(Builder<'_, 'll, 'tcx>),
1236 ) -> &'ll Value {
1237     if let Some(llfn) = cx.rust_try_fn.get() {
1238         return llfn;
1239     }
1240
1241     // Define the type up front for the signature of the rust_try function.
1242     let tcx = cx.tcx;
1243     let i8p = tcx.mk_mut_ptr(tcx.types.i8);
1244     let try_fn_ty = tcx.mk_fn_ptr(ty::Binder::bind(tcx.mk_fn_sig(
1245         iter::once(i8p),
1246         tcx.mk_unit(),
1247         false,
1248         hir::Unsafety::Unsafe,
1249         Abi::Rust,
1250     )));
1251     let catch_fn_ty = tcx.mk_fn_ptr(ty::Binder::bind(tcx.mk_fn_sig(
1252         [i8p, i8p].iter().cloned(),
1253         tcx.mk_unit(),
1254         false,
1255         hir::Unsafety::Unsafe,
1256         Abi::Rust,
1257     )));
1258     let output = tcx.types.i32;
1259     let rust_try = gen_fn(cx, "__rust_try", vec![try_fn_ty, i8p, catch_fn_ty], output, codegen);
1260     cx.rust_try_fn.set(Some(rust_try));
1261     rust_try
1262 }
1263
1264 fn generic_simd_intrinsic(
1265     bx: &mut Builder<'a, 'll, 'tcx>,
1266     name: Symbol,
1267     callee_ty: Ty<'tcx>,
1268     args: &[OperandRef<'tcx, &'ll Value>],
1269     ret_ty: Ty<'tcx>,
1270     llret_ty: &'ll Type,
1271     span: Span,
1272 ) -> Result<&'ll Value, ()> {
1273     // macros for error handling:
1274     macro_rules! emit_error {
1275         ($msg: tt) => {
1276             emit_error!($msg, )
1277         };
1278         ($msg: tt, $($fmt: tt)*) => {
1279             span_invalid_monomorphization_error(
1280                 bx.sess(), span,
1281                 &format!(concat!("invalid monomorphization of `{}` intrinsic: ", $msg),
1282                          name, $($fmt)*));
1283         }
1284     }
1285
1286     macro_rules! return_error {
1287         ($($fmt: tt)*) => {
1288             {
1289                 emit_error!($($fmt)*);
1290                 return Err(());
1291             }
1292         }
1293     }
1294
1295     macro_rules! require {
1296         ($cond: expr, $($fmt: tt)*) => {
1297             if !$cond {
1298                 return_error!($($fmt)*);
1299             }
1300         };
1301     }
1302
1303     macro_rules! require_simd {
1304         ($ty: expr, $position: expr) => {
1305             require!($ty.is_simd(), "expected SIMD {} type, found non-SIMD `{}`", $position, $ty)
1306         };
1307     }
1308
1309     let tcx = bx.tcx();
1310     let sig = tcx
1311         .normalize_erasing_late_bound_regions(ty::ParamEnv::reveal_all(), &callee_ty.fn_sig(tcx));
1312     let arg_tys = sig.inputs();
1313     let name_str = &*name.as_str();
1314
1315     if name == sym::simd_select_bitmask {
1316         let in_ty = arg_tys[0];
1317         let m_len = match in_ty.kind {
1318             // Note that this `.unwrap()` crashes for isize/usize, that's sort
1319             // of intentional as there's not currently a use case for that.
1320             ty::Int(i) => i.bit_width().unwrap(),
1321             ty::Uint(i) => i.bit_width().unwrap(),
1322             _ => return_error!("`{}` is not an integral type", in_ty),
1323         };
1324         require_simd!(arg_tys[1], "argument");
1325         let v_len = arg_tys[1].simd_size(tcx);
1326         require!(
1327             m_len == v_len,
1328             "mismatched lengths: mask length `{}` != other vector length `{}`",
1329             m_len,
1330             v_len
1331         );
1332         let i1 = bx.type_i1();
1333         let i1xn = bx.type_vector(i1, m_len);
1334         let m_i1s = bx.bitcast(args[0].immediate(), i1xn);
1335         return Ok(bx.select(m_i1s, args[1].immediate(), args[2].immediate()));
1336     }
1337
1338     // every intrinsic below takes a SIMD vector as its first argument
1339     require_simd!(arg_tys[0], "input");
1340     let in_ty = arg_tys[0];
1341     let in_elem = arg_tys[0].simd_type(tcx);
1342     let in_len = arg_tys[0].simd_size(tcx);
1343
1344     let comparison = match name {
1345         sym::simd_eq => Some(hir::BinOpKind::Eq),
1346         sym::simd_ne => Some(hir::BinOpKind::Ne),
1347         sym::simd_lt => Some(hir::BinOpKind::Lt),
1348         sym::simd_le => Some(hir::BinOpKind::Le),
1349         sym::simd_gt => Some(hir::BinOpKind::Gt),
1350         sym::simd_ge => Some(hir::BinOpKind::Ge),
1351         _ => None,
1352     };
1353
1354     if let Some(cmp_op) = comparison {
1355         require_simd!(ret_ty, "return");
1356
1357         let out_len = ret_ty.simd_size(tcx);
1358         require!(
1359             in_len == out_len,
1360             "expected return type with length {} (same as input type `{}`), \
1361                   found `{}` with length {}",
1362             in_len,
1363             in_ty,
1364             ret_ty,
1365             out_len
1366         );
1367         require!(
1368             bx.type_kind(bx.element_type(llret_ty)) == TypeKind::Integer,
1369             "expected return type with integer elements, found `{}` with non-integer `{}`",
1370             ret_ty,
1371             ret_ty.simd_type(tcx)
1372         );
1373
1374         return Ok(compare_simd_types(
1375             bx,
1376             args[0].immediate(),
1377             args[1].immediate(),
1378             in_elem,
1379             llret_ty,
1380             cmp_op,
1381         ));
1382     }
1383
1384     if name_str.starts_with("simd_shuffle") {
1385         let n: u64 = name_str["simd_shuffle".len()..].parse().unwrap_or_else(|_| {
1386             span_bug!(span, "bad `simd_shuffle` instruction only caught in codegen?")
1387         });
1388
1389         require_simd!(ret_ty, "return");
1390
1391         let out_len = ret_ty.simd_size(tcx);
1392         require!(
1393             out_len == n,
1394             "expected return type of length {}, found `{}` with length {}",
1395             n,
1396             ret_ty,
1397             out_len
1398         );
1399         require!(
1400             in_elem == ret_ty.simd_type(tcx),
1401             "expected return element type `{}` (element of input `{}`), \
1402                   found `{}` with element type `{}`",
1403             in_elem,
1404             in_ty,
1405             ret_ty,
1406             ret_ty.simd_type(tcx)
1407         );
1408
1409         let total_len = u128::from(in_len) * 2;
1410
1411         let vector = args[2].immediate();
1412
1413         let indices: Option<Vec<_>> = (0..n)
1414             .map(|i| {
1415                 let arg_idx = i;
1416                 let val = bx.const_get_elt(vector, i as u64);
1417                 match bx.const_to_opt_u128(val, true) {
1418                     None => {
1419                         emit_error!("shuffle index #{} is not a constant", arg_idx);
1420                         None
1421                     }
1422                     Some(idx) if idx >= total_len => {
1423                         emit_error!(
1424                             "shuffle index #{} is out of bounds (limit {})",
1425                             arg_idx,
1426                             total_len
1427                         );
1428                         None
1429                     }
1430                     Some(idx) => Some(bx.const_i32(idx as i32)),
1431                 }
1432             })
1433             .collect();
1434         let indices = match indices {
1435             Some(i) => i,
1436             None => return Ok(bx.const_null(llret_ty)),
1437         };
1438
1439         return Ok(bx.shuffle_vector(
1440             args[0].immediate(),
1441             args[1].immediate(),
1442             bx.const_vector(&indices),
1443         ));
1444     }
1445
1446     if name == sym::simd_insert {
1447         require!(
1448             in_elem == arg_tys[2],
1449             "expected inserted type `{}` (element of input `{}`), found `{}`",
1450             in_elem,
1451             in_ty,
1452             arg_tys[2]
1453         );
1454         return Ok(bx.insert_element(
1455             args[0].immediate(),
1456             args[2].immediate(),
1457             args[1].immediate(),
1458         ));
1459     }
1460     if name == sym::simd_extract {
1461         require!(
1462             ret_ty == in_elem,
1463             "expected return type `{}` (element of input `{}`), found `{}`",
1464             in_elem,
1465             in_ty,
1466             ret_ty
1467         );
1468         return Ok(bx.extract_element(args[0].immediate(), args[1].immediate()));
1469     }
1470
1471     if name == sym::simd_select {
1472         let m_elem_ty = in_elem;
1473         let m_len = in_len;
1474         require_simd!(arg_tys[1], "argument");
1475         let v_len = arg_tys[1].simd_size(tcx);
1476         require!(
1477             m_len == v_len,
1478             "mismatched lengths: mask length `{}` != other vector length `{}`",
1479             m_len,
1480             v_len
1481         );
1482         match m_elem_ty.kind {
1483             ty::Int(_) => {}
1484             _ => return_error!("mask element type is `{}`, expected `i_`", m_elem_ty),
1485         }
1486         // truncate the mask to a vector of i1s
1487         let i1 = bx.type_i1();
1488         let i1xn = bx.type_vector(i1, m_len as u64);
1489         let m_i1s = bx.trunc(args[0].immediate(), i1xn);
1490         return Ok(bx.select(m_i1s, args[1].immediate(), args[2].immediate()));
1491     }
1492
1493     if name == sym::simd_bitmask {
1494         // The `fn simd_bitmask(vector) -> unsigned integer` intrinsic takes a
1495         // vector mask and returns an unsigned integer containing the most
1496         // significant bit (MSB) of each lane.
1497
1498         // If the vector has less than 8 lanes, an u8 is returned with zeroed
1499         // trailing bits.
1500         let expected_int_bits = in_len.max(8);
1501         match ret_ty.kind {
1502             ty::Uint(i) if i.bit_width() == Some(expected_int_bits) => (),
1503             _ => return_error!("bitmask `{}`, expected `u{}`", ret_ty, expected_int_bits),
1504         }
1505
1506         // Integer vector <i{in_bitwidth} x in_len>:
1507         let (i_xn, in_elem_bitwidth) = match in_elem.kind {
1508             ty::Int(i) => {
1509                 (args[0].immediate(), i.bit_width().unwrap_or(bx.data_layout().pointer_size.bits()))
1510             }
1511             ty::Uint(i) => {
1512                 (args[0].immediate(), i.bit_width().unwrap_or(bx.data_layout().pointer_size.bits()))
1513             }
1514             _ => return_error!(
1515                 "vector argument `{}`'s element type `{}`, expected integer element type",
1516                 in_ty,
1517                 in_elem
1518             ),
1519         };
1520
1521         // Shift the MSB to the right by "in_elem_bitwidth - 1" into the first bit position.
1522         let shift_indices =
1523             vec![
1524                 bx.cx.const_int(bx.type_ix(in_elem_bitwidth), (in_elem_bitwidth - 1) as _);
1525                 in_len as _
1526             ];
1527         let i_xn_msb = bx.lshr(i_xn, bx.const_vector(shift_indices.as_slice()));
1528         // Truncate vector to an <i1 x N>
1529         let i1xn = bx.trunc(i_xn_msb, bx.type_vector(bx.type_i1(), in_len));
1530         // Bitcast <i1 x N> to iN:
1531         let i_ = bx.bitcast(i1xn, bx.type_ix(in_len));
1532         // Zero-extend iN to the bitmask type:
1533         return Ok(bx.zext(i_, bx.type_ix(expected_int_bits)));
1534     }
1535
1536     fn simd_simple_float_intrinsic(
1537         name: &str,
1538         in_elem: &::rustc_middle::ty::TyS<'_>,
1539         in_ty: &::rustc_middle::ty::TyS<'_>,
1540         in_len: u64,
1541         bx: &mut Builder<'a, 'll, 'tcx>,
1542         span: Span,
1543         args: &[OperandRef<'tcx, &'ll Value>],
1544     ) -> Result<&'ll Value, ()> {
1545         macro_rules! emit_error {
1546             ($msg: tt) => {
1547                 emit_error!($msg, )
1548             };
1549             ($msg: tt, $($fmt: tt)*) => {
1550                 span_invalid_monomorphization_error(
1551                     bx.sess(), span,
1552                     &format!(concat!("invalid monomorphization of `{}` intrinsic: ", $msg),
1553                              name, $($fmt)*));
1554             }
1555         }
1556         macro_rules! return_error {
1557             ($($fmt: tt)*) => {
1558                 {
1559                     emit_error!($($fmt)*);
1560                     return Err(());
1561                 }
1562             }
1563         }
1564         let ety = match in_elem.kind {
1565             ty::Float(f) if f.bit_width() == 32 => {
1566                 if in_len < 2 || in_len > 16 {
1567                     return_error!(
1568                         "unsupported floating-point vector `{}` with length `{}` \
1569                          out-of-range [2, 16]",
1570                         in_ty,
1571                         in_len
1572                     );
1573                 }
1574                 "f32"
1575             }
1576             ty::Float(f) if f.bit_width() == 64 => {
1577                 if in_len < 2 || in_len > 8 {
1578                     return_error!(
1579                         "unsupported floating-point vector `{}` with length `{}` \
1580                                    out-of-range [2, 8]",
1581                         in_ty,
1582                         in_len
1583                     );
1584                 }
1585                 "f64"
1586             }
1587             ty::Float(f) => {
1588                 return_error!(
1589                     "unsupported element type `{}` of floating-point vector `{}`",
1590                     f.name_str(),
1591                     in_ty
1592                 );
1593             }
1594             _ => {
1595                 return_error!("`{}` is not a floating-point type", in_ty);
1596             }
1597         };
1598
1599         let llvm_name = &format!("llvm.{0}.v{1}{2}", name, in_len, ety);
1600         let intrinsic = bx.get_intrinsic(&llvm_name);
1601         let c =
1602             bx.call(intrinsic, &args.iter().map(|arg| arg.immediate()).collect::<Vec<_>>(), None);
1603         unsafe { llvm::LLVMRustSetHasUnsafeAlgebra(c) };
1604         Ok(c)
1605     }
1606
1607     match name {
1608         sym::simd_fsqrt => {
1609             return simd_simple_float_intrinsic("sqrt", in_elem, in_ty, in_len, bx, span, args);
1610         }
1611         sym::simd_fsin => {
1612             return simd_simple_float_intrinsic("sin", in_elem, in_ty, in_len, bx, span, args);
1613         }
1614         sym::simd_fcos => {
1615             return simd_simple_float_intrinsic("cos", in_elem, in_ty, in_len, bx, span, args);
1616         }
1617         sym::simd_fabs => {
1618             return simd_simple_float_intrinsic("fabs", in_elem, in_ty, in_len, bx, span, args);
1619         }
1620         sym::simd_floor => {
1621             return simd_simple_float_intrinsic("floor", in_elem, in_ty, in_len, bx, span, args);
1622         }
1623         sym::simd_ceil => {
1624             return simd_simple_float_intrinsic("ceil", in_elem, in_ty, in_len, bx, span, args);
1625         }
1626         sym::simd_fexp => {
1627             return simd_simple_float_intrinsic("exp", in_elem, in_ty, in_len, bx, span, args);
1628         }
1629         sym::simd_fexp2 => {
1630             return simd_simple_float_intrinsic("exp2", in_elem, in_ty, in_len, bx, span, args);
1631         }
1632         sym::simd_flog10 => {
1633             return simd_simple_float_intrinsic("log10", in_elem, in_ty, in_len, bx, span, args);
1634         }
1635         sym::simd_flog2 => {
1636             return simd_simple_float_intrinsic("log2", in_elem, in_ty, in_len, bx, span, args);
1637         }
1638         sym::simd_flog => {
1639             return simd_simple_float_intrinsic("log", in_elem, in_ty, in_len, bx, span, args);
1640         }
1641         sym::simd_fpowi => {
1642             return simd_simple_float_intrinsic("powi", in_elem, in_ty, in_len, bx, span, args);
1643         }
1644         sym::simd_fpow => {
1645             return simd_simple_float_intrinsic("pow", in_elem, in_ty, in_len, bx, span, args);
1646         }
1647         sym::simd_fma => {
1648             return simd_simple_float_intrinsic("fma", in_elem, in_ty, in_len, bx, span, args);
1649         }
1650         _ => { /* fallthrough */ }
1651     }
1652
1653     // FIXME: use:
1654     //  https://github.com/llvm-mirror/llvm/blob/master/include/llvm/IR/Function.h#L182
1655     //  https://github.com/llvm-mirror/llvm/blob/master/include/llvm/IR/Intrinsics.h#L81
1656     fn llvm_vector_str(elem_ty: Ty<'_>, vec_len: u64, no_pointers: usize) -> String {
1657         let p0s: String = "p0".repeat(no_pointers);
1658         match elem_ty.kind {
1659             ty::Int(v) => format!("v{}{}i{}", vec_len, p0s, v.bit_width().unwrap()),
1660             ty::Uint(v) => format!("v{}{}i{}", vec_len, p0s, v.bit_width().unwrap()),
1661             ty::Float(v) => format!("v{}{}f{}", vec_len, p0s, v.bit_width()),
1662             _ => unreachable!(),
1663         }
1664     }
1665
1666     fn llvm_vector_ty(
1667         cx: &CodegenCx<'ll, '_>,
1668         elem_ty: Ty<'_>,
1669         vec_len: u64,
1670         mut no_pointers: usize,
1671     ) -> &'ll Type {
1672         // FIXME: use cx.layout_of(ty).llvm_type() ?
1673         let mut elem_ty = match elem_ty.kind {
1674             ty::Int(v) => cx.type_int_from_ty(v),
1675             ty::Uint(v) => cx.type_uint_from_ty(v),
1676             ty::Float(v) => cx.type_float_from_ty(v),
1677             _ => unreachable!(),
1678         };
1679         while no_pointers > 0 {
1680             elem_ty = cx.type_ptr_to(elem_ty);
1681             no_pointers -= 1;
1682         }
1683         cx.type_vector(elem_ty, vec_len)
1684     }
1685
1686     if name == sym::simd_gather {
1687         // simd_gather(values: <N x T>, pointers: <N x *_ T>,
1688         //             mask: <N x i{M}>) -> <N x T>
1689         // * N: number of elements in the input vectors
1690         // * T: type of the element to load
1691         // * M: any integer width is supported, will be truncated to i1
1692
1693         // All types must be simd vector types
1694         require_simd!(in_ty, "first");
1695         require_simd!(arg_tys[1], "second");
1696         require_simd!(arg_tys[2], "third");
1697         require_simd!(ret_ty, "return");
1698
1699         // Of the same length:
1700         require!(
1701             in_len == arg_tys[1].simd_size(tcx),
1702             "expected {} argument with length {} (same as input type `{}`), \
1703                   found `{}` with length {}",
1704             "second",
1705             in_len,
1706             in_ty,
1707             arg_tys[1],
1708             arg_tys[1].simd_size(tcx)
1709         );
1710         require!(
1711             in_len == arg_tys[2].simd_size(tcx),
1712             "expected {} argument with length {} (same as input type `{}`), \
1713                   found `{}` with length {}",
1714             "third",
1715             in_len,
1716             in_ty,
1717             arg_tys[2],
1718             arg_tys[2].simd_size(tcx)
1719         );
1720
1721         // The return type must match the first argument type
1722         require!(ret_ty == in_ty, "expected return type `{}`, found `{}`", in_ty, ret_ty);
1723
1724         // This counts how many pointers
1725         fn ptr_count(t: Ty<'_>) -> usize {
1726             match t.kind {
1727                 ty::RawPtr(p) => 1 + ptr_count(p.ty),
1728                 _ => 0,
1729             }
1730         }
1731
1732         // Non-ptr type
1733         fn non_ptr(t: Ty<'_>) -> Ty<'_> {
1734             match t.kind {
1735                 ty::RawPtr(p) => non_ptr(p.ty),
1736                 _ => t,
1737             }
1738         }
1739
1740         // The second argument must be a simd vector with an element type that's a pointer
1741         // to the element type of the first argument
1742         let (pointer_count, underlying_ty) = match arg_tys[1].simd_type(tcx).kind {
1743             ty::RawPtr(p) if p.ty == in_elem => {
1744                 (ptr_count(arg_tys[1].simd_type(tcx)), non_ptr(arg_tys[1].simd_type(tcx)))
1745             }
1746             _ => {
1747                 require!(
1748                     false,
1749                     "expected element type `{}` of second argument `{}` \
1750                                  to be a pointer to the element type `{}` of the first \
1751                                  argument `{}`, found `{}` != `*_ {}`",
1752                     arg_tys[1].simd_type(tcx),
1753                     arg_tys[1],
1754                     in_elem,
1755                     in_ty,
1756                     arg_tys[1].simd_type(tcx),
1757                     in_elem
1758                 );
1759                 unreachable!();
1760             }
1761         };
1762         assert!(pointer_count > 0);
1763         assert_eq!(pointer_count - 1, ptr_count(arg_tys[0].simd_type(tcx)));
1764         assert_eq!(underlying_ty, non_ptr(arg_tys[0].simd_type(tcx)));
1765
1766         // The element type of the third argument must be a signed integer type of any width:
1767         match arg_tys[2].simd_type(tcx).kind {
1768             ty::Int(_) => (),
1769             _ => {
1770                 require!(
1771                     false,
1772                     "expected element type `{}` of third argument `{}` \
1773                                  to be a signed integer type",
1774                     arg_tys[2].simd_type(tcx),
1775                     arg_tys[2]
1776                 );
1777             }
1778         }
1779
1780         // Alignment of T, must be a constant integer value:
1781         let alignment_ty = bx.type_i32();
1782         let alignment = bx.const_i32(bx.align_of(in_elem).bytes() as i32);
1783
1784         // Truncate the mask vector to a vector of i1s:
1785         let (mask, mask_ty) = {
1786             let i1 = bx.type_i1();
1787             let i1xn = bx.type_vector(i1, in_len);
1788             (bx.trunc(args[2].immediate(), i1xn), i1xn)
1789         };
1790
1791         // Type of the vector of pointers:
1792         let llvm_pointer_vec_ty = llvm_vector_ty(bx, underlying_ty, in_len, pointer_count);
1793         let llvm_pointer_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count);
1794
1795         // Type of the vector of elements:
1796         let llvm_elem_vec_ty = llvm_vector_ty(bx, underlying_ty, in_len, pointer_count - 1);
1797         let llvm_elem_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count - 1);
1798
1799         let llvm_intrinsic =
1800             format!("llvm.masked.gather.{}.{}", llvm_elem_vec_str, llvm_pointer_vec_str);
1801         let f = bx.declare_cfn(
1802             &llvm_intrinsic,
1803             bx.type_func(
1804                 &[llvm_pointer_vec_ty, alignment_ty, mask_ty, llvm_elem_vec_ty],
1805                 llvm_elem_vec_ty,
1806             ),
1807         );
1808         llvm::SetUnnamedAddress(f, llvm::UnnamedAddr::No);
1809         let v = bx.call(f, &[args[1].immediate(), alignment, mask, args[0].immediate()], None);
1810         return Ok(v);
1811     }
1812
1813     if name == sym::simd_scatter {
1814         // simd_scatter(values: <N x T>, pointers: <N x *mut T>,
1815         //             mask: <N x i{M}>) -> ()
1816         // * N: number of elements in the input vectors
1817         // * T: type of the element to load
1818         // * M: any integer width is supported, will be truncated to i1
1819
1820         // All types must be simd vector types
1821         require_simd!(in_ty, "first");
1822         require_simd!(arg_tys[1], "second");
1823         require_simd!(arg_tys[2], "third");
1824
1825         // Of the same length:
1826         require!(
1827             in_len == arg_tys[1].simd_size(tcx),
1828             "expected {} argument with length {} (same as input type `{}`), \
1829                   found `{}` with length {}",
1830             "second",
1831             in_len,
1832             in_ty,
1833             arg_tys[1],
1834             arg_tys[1].simd_size(tcx)
1835         );
1836         require!(
1837             in_len == arg_tys[2].simd_size(tcx),
1838             "expected {} argument with length {} (same as input type `{}`), \
1839                   found `{}` with length {}",
1840             "third",
1841             in_len,
1842             in_ty,
1843             arg_tys[2],
1844             arg_tys[2].simd_size(tcx)
1845         );
1846
1847         // This counts how many pointers
1848         fn ptr_count(t: Ty<'_>) -> usize {
1849             match t.kind {
1850                 ty::RawPtr(p) => 1 + ptr_count(p.ty),
1851                 _ => 0,
1852             }
1853         }
1854
1855         // Non-ptr type
1856         fn non_ptr(t: Ty<'_>) -> Ty<'_> {
1857             match t.kind {
1858                 ty::RawPtr(p) => non_ptr(p.ty),
1859                 _ => t,
1860             }
1861         }
1862
1863         // The second argument must be a simd vector with an element type that's a pointer
1864         // to the element type of the first argument
1865         let (pointer_count, underlying_ty) = match arg_tys[1].simd_type(tcx).kind {
1866             ty::RawPtr(p) if p.ty == in_elem && p.mutbl == hir::Mutability::Mut => {
1867                 (ptr_count(arg_tys[1].simd_type(tcx)), non_ptr(arg_tys[1].simd_type(tcx)))
1868             }
1869             _ => {
1870                 require!(
1871                     false,
1872                     "expected element type `{}` of second argument `{}` \
1873                                  to be a pointer to the element type `{}` of the first \
1874                                  argument `{}`, found `{}` != `*mut {}`",
1875                     arg_tys[1].simd_type(tcx),
1876                     arg_tys[1],
1877                     in_elem,
1878                     in_ty,
1879                     arg_tys[1].simd_type(tcx),
1880                     in_elem
1881                 );
1882                 unreachable!();
1883             }
1884         };
1885         assert!(pointer_count > 0);
1886         assert_eq!(pointer_count - 1, ptr_count(arg_tys[0].simd_type(tcx)));
1887         assert_eq!(underlying_ty, non_ptr(arg_tys[0].simd_type(tcx)));
1888
1889         // The element type of the third argument must be a signed integer type of any width:
1890         match arg_tys[2].simd_type(tcx).kind {
1891             ty::Int(_) => (),
1892             _ => {
1893                 require!(
1894                     false,
1895                     "expected element type `{}` of third argument `{}` \
1896                                  to be a signed integer type",
1897                     arg_tys[2].simd_type(tcx),
1898                     arg_tys[2]
1899                 );
1900             }
1901         }
1902
1903         // Alignment of T, must be a constant integer value:
1904         let alignment_ty = bx.type_i32();
1905         let alignment = bx.const_i32(bx.align_of(in_elem).bytes() as i32);
1906
1907         // Truncate the mask vector to a vector of i1s:
1908         let (mask, mask_ty) = {
1909             let i1 = bx.type_i1();
1910             let i1xn = bx.type_vector(i1, in_len);
1911             (bx.trunc(args[2].immediate(), i1xn), i1xn)
1912         };
1913
1914         let ret_t = bx.type_void();
1915
1916         // Type of the vector of pointers:
1917         let llvm_pointer_vec_ty = llvm_vector_ty(bx, underlying_ty, in_len, pointer_count);
1918         let llvm_pointer_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count);
1919
1920         // Type of the vector of elements:
1921         let llvm_elem_vec_ty = llvm_vector_ty(bx, underlying_ty, in_len, pointer_count - 1);
1922         let llvm_elem_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count - 1);
1923
1924         let llvm_intrinsic =
1925             format!("llvm.masked.scatter.{}.{}", llvm_elem_vec_str, llvm_pointer_vec_str);
1926         let f = bx.declare_cfn(
1927             &llvm_intrinsic,
1928             bx.type_func(&[llvm_elem_vec_ty, llvm_pointer_vec_ty, alignment_ty, mask_ty], ret_t),
1929         );
1930         llvm::SetUnnamedAddress(f, llvm::UnnamedAddr::No);
1931         let v = bx.call(f, &[args[0].immediate(), args[1].immediate(), alignment, mask], None);
1932         return Ok(v);
1933     }
1934
1935     macro_rules! arith_red {
1936         ($name:ident : $integer_reduce:ident, $float_reduce:ident, $ordered:expr, $op:ident,
1937          $identity:expr) => {
1938             if name == sym::$name {
1939                 require!(
1940                     ret_ty == in_elem,
1941                     "expected return type `{}` (element of input `{}`), found `{}`",
1942                     in_elem,
1943                     in_ty,
1944                     ret_ty
1945                 );
1946                 return match in_elem.kind {
1947                     ty::Int(_) | ty::Uint(_) => {
1948                         let r = bx.$integer_reduce(args[0].immediate());
1949                         if $ordered {
1950                             // if overflow occurs, the result is the
1951                             // mathematical result modulo 2^n:
1952                             Ok(bx.$op(args[1].immediate(), r))
1953                         } else {
1954                             Ok(bx.$integer_reduce(args[0].immediate()))
1955                         }
1956                     }
1957                     ty::Float(f) => {
1958                         let acc = if $ordered {
1959                             // ordered arithmetic reductions take an accumulator
1960                             args[1].immediate()
1961                         } else {
1962                             // unordered arithmetic reductions use the identity accumulator
1963                             match f.bit_width() {
1964                                 32 => bx.const_real(bx.type_f32(), $identity),
1965                                 64 => bx.const_real(bx.type_f64(), $identity),
1966                                 v => return_error!(
1967                                     r#"
1968 unsupported {} from `{}` with element `{}` of size `{}` to `{}`"#,
1969                                     sym::$name,
1970                                     in_ty,
1971                                     in_elem,
1972                                     v,
1973                                     ret_ty
1974                                 ),
1975                             }
1976                         };
1977                         Ok(bx.$float_reduce(acc, args[0].immediate()))
1978                     }
1979                     _ => return_error!(
1980                         "unsupported {} from `{}` with element `{}` to `{}`",
1981                         sym::$name,
1982                         in_ty,
1983                         in_elem,
1984                         ret_ty
1985                     ),
1986                 };
1987             }
1988         };
1989     }
1990
1991     arith_red!(simd_reduce_add_ordered: vector_reduce_add, vector_reduce_fadd, true, add, 0.0);
1992     arith_red!(simd_reduce_mul_ordered: vector_reduce_mul, vector_reduce_fmul, true, mul, 1.0);
1993     arith_red!(
1994         simd_reduce_add_unordered: vector_reduce_add,
1995         vector_reduce_fadd_fast,
1996         false,
1997         add,
1998         0.0
1999     );
2000     arith_red!(
2001         simd_reduce_mul_unordered: vector_reduce_mul,
2002         vector_reduce_fmul_fast,
2003         false,
2004         mul,
2005         1.0
2006     );
2007
2008     macro_rules! minmax_red {
2009         ($name:ident: $int_red:ident, $float_red:ident) => {
2010             if name == sym::$name {
2011                 require!(
2012                     ret_ty == in_elem,
2013                     "expected return type `{}` (element of input `{}`), found `{}`",
2014                     in_elem,
2015                     in_ty,
2016                     ret_ty
2017                 );
2018                 return match in_elem.kind {
2019                     ty::Int(_i) => Ok(bx.$int_red(args[0].immediate(), true)),
2020                     ty::Uint(_u) => Ok(bx.$int_red(args[0].immediate(), false)),
2021                     ty::Float(_f) => Ok(bx.$float_red(args[0].immediate())),
2022                     _ => return_error!(
2023                         "unsupported {} from `{}` with element `{}` to `{}`",
2024                         sym::$name,
2025                         in_ty,
2026                         in_elem,
2027                         ret_ty
2028                     ),
2029                 };
2030             }
2031         };
2032     }
2033
2034     minmax_red!(simd_reduce_min: vector_reduce_min, vector_reduce_fmin);
2035     minmax_red!(simd_reduce_max: vector_reduce_max, vector_reduce_fmax);
2036
2037     minmax_red!(simd_reduce_min_nanless: vector_reduce_min, vector_reduce_fmin_fast);
2038     minmax_red!(simd_reduce_max_nanless: vector_reduce_max, vector_reduce_fmax_fast);
2039
2040     macro_rules! bitwise_red {
2041         ($name:ident : $red:ident, $boolean:expr) => {
2042             if name == sym::$name {
2043                 let input = if !$boolean {
2044                     require!(
2045                         ret_ty == in_elem,
2046                         "expected return type `{}` (element of input `{}`), found `{}`",
2047                         in_elem,
2048                         in_ty,
2049                         ret_ty
2050                     );
2051                     args[0].immediate()
2052                 } else {
2053                     match in_elem.kind {
2054                         ty::Int(_) | ty::Uint(_) => {}
2055                         _ => return_error!(
2056                             "unsupported {} from `{}` with element `{}` to `{}`",
2057                             sym::$name,
2058                             in_ty,
2059                             in_elem,
2060                             ret_ty
2061                         ),
2062                     }
2063
2064                     // boolean reductions operate on vectors of i1s:
2065                     let i1 = bx.type_i1();
2066                     let i1xn = bx.type_vector(i1, in_len as u64);
2067                     bx.trunc(args[0].immediate(), i1xn)
2068                 };
2069                 return match in_elem.kind {
2070                     ty::Int(_) | ty::Uint(_) => {
2071                         let r = bx.$red(input);
2072                         Ok(if !$boolean { r } else { bx.zext(r, bx.type_bool()) })
2073                     }
2074                     _ => return_error!(
2075                         "unsupported {} from `{}` with element `{}` to `{}`",
2076                         sym::$name,
2077                         in_ty,
2078                         in_elem,
2079                         ret_ty
2080                     ),
2081                 };
2082             }
2083         };
2084     }
2085
2086     bitwise_red!(simd_reduce_and: vector_reduce_and, false);
2087     bitwise_red!(simd_reduce_or: vector_reduce_or, false);
2088     bitwise_red!(simd_reduce_xor: vector_reduce_xor, false);
2089     bitwise_red!(simd_reduce_all: vector_reduce_and, true);
2090     bitwise_red!(simd_reduce_any: vector_reduce_or, true);
2091
2092     if name == sym::simd_cast {
2093         require_simd!(ret_ty, "return");
2094         let out_len = ret_ty.simd_size(tcx);
2095         require!(
2096             in_len == out_len,
2097             "expected return type with length {} (same as input type `{}`), \
2098                   found `{}` with length {}",
2099             in_len,
2100             in_ty,
2101             ret_ty,
2102             out_len
2103         );
2104         // casting cares about nominal type, not just structural type
2105         let out_elem = ret_ty.simd_type(tcx);
2106
2107         if in_elem == out_elem {
2108             return Ok(args[0].immediate());
2109         }
2110
2111         enum Style {
2112             Float,
2113             Int(/* is signed? */ bool),
2114             Unsupported,
2115         }
2116
2117         let (in_style, in_width) = match in_elem.kind {
2118             // vectors of pointer-sized integers should've been
2119             // disallowed before here, so this unwrap is safe.
2120             ty::Int(i) => (Style::Int(true), i.bit_width().unwrap()),
2121             ty::Uint(u) => (Style::Int(false), u.bit_width().unwrap()),
2122             ty::Float(f) => (Style::Float, f.bit_width()),
2123             _ => (Style::Unsupported, 0),
2124         };
2125         let (out_style, out_width) = match out_elem.kind {
2126             ty::Int(i) => (Style::Int(true), i.bit_width().unwrap()),
2127             ty::Uint(u) => (Style::Int(false), u.bit_width().unwrap()),
2128             ty::Float(f) => (Style::Float, f.bit_width()),
2129             _ => (Style::Unsupported, 0),
2130         };
2131
2132         match (in_style, out_style) {
2133             (Style::Int(in_is_signed), Style::Int(_)) => {
2134                 return Ok(match in_width.cmp(&out_width) {
2135                     Ordering::Greater => bx.trunc(args[0].immediate(), llret_ty),
2136                     Ordering::Equal => args[0].immediate(),
2137                     Ordering::Less => {
2138                         if in_is_signed {
2139                             bx.sext(args[0].immediate(), llret_ty)
2140                         } else {
2141                             bx.zext(args[0].immediate(), llret_ty)
2142                         }
2143                     }
2144                 });
2145             }
2146             (Style::Int(in_is_signed), Style::Float) => {
2147                 return Ok(if in_is_signed {
2148                     bx.sitofp(args[0].immediate(), llret_ty)
2149                 } else {
2150                     bx.uitofp(args[0].immediate(), llret_ty)
2151                 });
2152             }
2153             (Style::Float, Style::Int(out_is_signed)) => {
2154                 return Ok(if out_is_signed {
2155                     bx.fptosi(args[0].immediate(), llret_ty)
2156                 } else {
2157                     bx.fptoui(args[0].immediate(), llret_ty)
2158                 });
2159             }
2160             (Style::Float, Style::Float) => {
2161                 return Ok(match in_width.cmp(&out_width) {
2162                     Ordering::Greater => bx.fptrunc(args[0].immediate(), llret_ty),
2163                     Ordering::Equal => args[0].immediate(),
2164                     Ordering::Less => bx.fpext(args[0].immediate(), llret_ty),
2165                 });
2166             }
2167             _ => { /* Unsupported. Fallthrough. */ }
2168         }
2169         require!(
2170             false,
2171             "unsupported cast from `{}` with element `{}` to `{}` with element `{}`",
2172             in_ty,
2173             in_elem,
2174             ret_ty,
2175             out_elem
2176         );
2177     }
2178     macro_rules! arith {
2179         ($($name: ident: $($($p: ident),* => $call: ident),*;)*) => {
2180             $(if name == sym::$name {
2181                 match in_elem.kind {
2182                     $($(ty::$p(_))|* => {
2183                         return Ok(bx.$call(args[0].immediate(), args[1].immediate()))
2184                     })*
2185                     _ => {},
2186                 }
2187                 require!(false,
2188                          "unsupported operation on `{}` with element `{}`",
2189                          in_ty,
2190                          in_elem)
2191             })*
2192         }
2193     }
2194     arith! {
2195         simd_add: Uint, Int => add, Float => fadd;
2196         simd_sub: Uint, Int => sub, Float => fsub;
2197         simd_mul: Uint, Int => mul, Float => fmul;
2198         simd_div: Uint => udiv, Int => sdiv, Float => fdiv;
2199         simd_rem: Uint => urem, Int => srem, Float => frem;
2200         simd_shl: Uint, Int => shl;
2201         simd_shr: Uint => lshr, Int => ashr;
2202         simd_and: Uint, Int => and;
2203         simd_or: Uint, Int => or;
2204         simd_xor: Uint, Int => xor;
2205         simd_fmax: Float => maxnum;
2206         simd_fmin: Float => minnum;
2207
2208     }
2209
2210     if name == sym::simd_saturating_add || name == sym::simd_saturating_sub {
2211         let lhs = args[0].immediate();
2212         let rhs = args[1].immediate();
2213         let is_add = name == sym::simd_saturating_add;
2214         let ptr_bits = bx.tcx().data_layout.pointer_size.bits() as _;
2215         let (signed, elem_width, elem_ty) = match in_elem.kind {
2216             ty::Int(i) => (true, i.bit_width().unwrap_or(ptr_bits), bx.cx.type_int_from_ty(i)),
2217             ty::Uint(i) => (false, i.bit_width().unwrap_or(ptr_bits), bx.cx.type_uint_from_ty(i)),
2218             _ => {
2219                 return_error!(
2220                     "expected element type `{}` of vector type `{}` \
2221                      to be a signed or unsigned integer type",
2222                     arg_tys[0].simd_type(tcx),
2223                     arg_tys[0]
2224                 );
2225             }
2226         };
2227         let llvm_intrinsic = &format!(
2228             "llvm.{}{}.sat.v{}i{}",
2229             if signed { 's' } else { 'u' },
2230             if is_add { "add" } else { "sub" },
2231             in_len,
2232             elem_width
2233         );
2234         let vec_ty = bx.cx.type_vector(elem_ty, in_len as u64);
2235
2236         let f = bx.declare_cfn(&llvm_intrinsic, bx.type_func(&[vec_ty, vec_ty], vec_ty));
2237         llvm::SetUnnamedAddress(f, llvm::UnnamedAddr::No);
2238         let v = bx.call(f, &[lhs, rhs], None);
2239         return Ok(v);
2240     }
2241
2242     span_bug!(span, "unknown SIMD intrinsic");
2243 }
2244
2245 // Returns the width of an int Ty, and if it's signed or not
2246 // Returns None if the type is not an integer
2247 // FIXME: there’s multiple of this functions, investigate using some of the already existing
2248 // stuffs.
2249 fn int_type_width_signed(ty: Ty<'_>, cx: &CodegenCx<'_, '_>) -> Option<(u64, bool)> {
2250     match ty.kind {
2251         ty::Int(t) => Some((
2252             match t {
2253                 ast::IntTy::Isize => u64::from(cx.tcx.sess.target.ptr_width),
2254                 ast::IntTy::I8 => 8,
2255                 ast::IntTy::I16 => 16,
2256                 ast::IntTy::I32 => 32,
2257                 ast::IntTy::I64 => 64,
2258                 ast::IntTy::I128 => 128,
2259             },
2260             true,
2261         )),
2262         ty::Uint(t) => Some((
2263             match t {
2264                 ast::UintTy::Usize => u64::from(cx.tcx.sess.target.ptr_width),
2265                 ast::UintTy::U8 => 8,
2266                 ast::UintTy::U16 => 16,
2267                 ast::UintTy::U32 => 32,
2268                 ast::UintTy::U64 => 64,
2269                 ast::UintTy::U128 => 128,
2270             },
2271             false,
2272         )),
2273         _ => None,
2274     }
2275 }
2276
2277 // Returns the width of a float Ty
2278 // Returns None if the type is not a float
2279 fn float_type_width(ty: Ty<'_>) -> Option<u64> {
2280     match ty.kind {
2281         ty::Float(t) => Some(t.bit_width()),
2282         _ => None,
2283     }
2284 }
2285
2286 fn op_to_u32<'tcx>(op: &Operand<'tcx>) -> u32 {
2287     Operand::scalar_from_const(op).to_u32().expect("Scalar is u32")
2288 }
2289
2290 fn op_to_u64<'tcx>(op: &Operand<'tcx>) -> u64 {
2291     Operand::scalar_from_const(op).to_u64().expect("Scalar is u64")
2292 }