1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 #![allow(non_upper_case_globals)]
14 use intrinsics::{self, Intrinsic};
17 use abi::{Abi, FnType, LlvmType, PassMode};
18 use rustc_codegen_ssa::MemFlags;
19 use rustc_codegen_ssa::mir::place::PlaceRef;
20 use rustc_codegen_ssa::mir::operand::{OperandRef, OperandValue};
21 use rustc_codegen_ssa::glue;
22 use rustc_codegen_ssa::base::{to_immediate, wants_msvc_seh, compare_simd_types};
23 use context::CodegenCx;
25 use type_of::LayoutLlvmExt;
26 use rustc::ty::{self, Ty};
27 use rustc::ty::layout::{self, LayoutOf, HasTyCtxt, Primitive};
28 use rustc_codegen_ssa::common::TypeKind;
30 use syntax::ast::{self, FloatTy};
31 use syntax::symbol::Symbol;
34 use va_arg::emit_va_arg;
36 use rustc_codegen_ssa::traits::*;
38 use rustc::session::Session;
41 use std::cmp::Ordering;
44 fn get_simple_intrinsic(cx: &CodegenCx<'ll, '_>, name: &str) -> Option<&'ll Value> {
45 let llvm_name = match name {
46 "sqrtf32" => "llvm.sqrt.f32",
47 "sqrtf64" => "llvm.sqrt.f64",
48 "powif32" => "llvm.powi.f32",
49 "powif64" => "llvm.powi.f64",
50 "sinf32" => "llvm.sin.f32",
51 "sinf64" => "llvm.sin.f64",
52 "cosf32" => "llvm.cos.f32",
53 "cosf64" => "llvm.cos.f64",
54 "powf32" => "llvm.pow.f32",
55 "powf64" => "llvm.pow.f64",
56 "expf32" => "llvm.exp.f32",
57 "expf64" => "llvm.exp.f64",
58 "exp2f32" => "llvm.exp2.f32",
59 "exp2f64" => "llvm.exp2.f64",
60 "logf32" => "llvm.log.f32",
61 "logf64" => "llvm.log.f64",
62 "log10f32" => "llvm.log10.f32",
63 "log10f64" => "llvm.log10.f64",
64 "log2f32" => "llvm.log2.f32",
65 "log2f64" => "llvm.log2.f64",
66 "fmaf32" => "llvm.fma.f32",
67 "fmaf64" => "llvm.fma.f64",
68 "fabsf32" => "llvm.fabs.f32",
69 "fabsf64" => "llvm.fabs.f64",
70 "copysignf32" => "llvm.copysign.f32",
71 "copysignf64" => "llvm.copysign.f64",
72 "floorf32" => "llvm.floor.f32",
73 "floorf64" => "llvm.floor.f64",
74 "ceilf32" => "llvm.ceil.f32",
75 "ceilf64" => "llvm.ceil.f64",
76 "truncf32" => "llvm.trunc.f32",
77 "truncf64" => "llvm.trunc.f64",
78 "rintf32" => "llvm.rint.f32",
79 "rintf64" => "llvm.rint.f64",
80 "nearbyintf32" => "llvm.nearbyint.f32",
81 "nearbyintf64" => "llvm.nearbyint.f64",
82 "roundf32" => "llvm.round.f32",
83 "roundf64" => "llvm.round.f64",
84 "assume" => "llvm.assume",
85 "abort" => "llvm.trap",
88 Some(cx.get_intrinsic(&llvm_name))
91 impl IntrinsicCallMethods<'tcx> for Builder<'a, 'll, 'tcx> {
92 fn codegen_intrinsic_call(
95 fn_ty: &FnType<'tcx, Ty<'tcx>>,
96 args: &[OperandRef<'tcx, &'ll Value>],
102 let (def_id, substs) = match callee_ty.sty {
103 ty::FnDef(def_id, substs) => (def_id, substs),
104 _ => bug!("expected fn item type, found {}", callee_ty)
107 let sig = callee_ty.fn_sig(tcx);
108 let sig = tcx.normalize_erasing_late_bound_regions(ty::ParamEnv::reveal_all(), &sig);
109 let arg_tys = sig.inputs();
110 let ret_ty = sig.output();
111 let name = &*tcx.item_name(def_id).as_str();
113 let llret_ty = self.layout_of(ret_ty).llvm_type(self);
114 let result = PlaceRef::new_sized(llresult, fn_ty.ret.layout, fn_ty.ret.layout.align.abi);
116 let simple = get_simple_intrinsic(self, name);
117 let llval = match name {
118 _ if simple.is_some() => {
119 self.call(simple.unwrap(),
120 &args.iter().map(|arg| arg.immediate()).collect::<Vec<_>>(),
127 let expect = self.get_intrinsic(&("llvm.expect.i1"));
128 self.call(expect, &[args[0].immediate(), self.const_bool(true)], None)
131 let expect = self.get_intrinsic(&("llvm.expect.i1"));
132 self.call(expect, &[args[0].immediate(), self.const_bool(false)], None)
143 let llfn = self.get_intrinsic(&("llvm.debugtrap"));
144 self.call(llfn, &[], None)
147 let tp_ty = substs.type_at(0);
148 self.const_usize(self.size_of(tp_ty).bytes())
150 func @ "va_start" | func @ "va_end" => {
151 let va_list = match (tcx.lang_items().va_list(), &result.layout.ty.sty) {
152 (Some(did), ty::Adt(def, _)) if def.did == did => args[0].immediate(),
153 (Some(_), _) => self.load(args[0].immediate(),
154 tcx.data_layout.pointer_align.abi),
155 (None, _) => bug!("va_list language item must be defined")
157 let intrinsic = self.cx().get_intrinsic(&format!("llvm.{}", func));
158 self.call(intrinsic, &[va_list], None)
161 let va_list = match (tcx.lang_items().va_list(), &result.layout.ty.sty) {
162 (Some(did), ty::Adt(def, _)) if def.did == did => args[0].immediate(),
163 (Some(_), _) => self.load(args[0].immediate(),
164 tcx.data_layout.pointer_align.abi),
165 (None, _) => bug!("va_list language item must be defined")
167 let intrinsic = self.cx().get_intrinsic(&("llvm.va_copy"));
168 self.call(intrinsic, &[llresult, va_list], None);
172 match fn_ty.ret.layout.abi {
173 layout::Abi::Scalar(ref scalar) => {
175 Primitive::Int(..) => {
176 if self.cx().size_of(ret_ty).bytes() < 4 {
177 // va_arg should not be called on a integer type
178 // less than 4 bytes in length. If it is, promote
179 // the integer to a `i32` and truncate the result
180 // back to the smaller type.
181 let promoted_result = emit_va_arg(self, args[0],
183 self.trunc(promoted_result, llret_ty)
185 emit_va_arg(self, args[0], ret_ty)
188 Primitive::Float(FloatTy::F64) |
189 Primitive::Pointer => {
190 emit_va_arg(self, args[0], ret_ty)
192 // `va_arg` should never be used with the return type f32.
193 Primitive::Float(FloatTy::F32) => {
194 bug!("the va_arg intrinsic does not work with `f32`")
199 bug!("the va_arg intrinsic does not work with non-scalar types")
204 let tp_ty = substs.type_at(0);
205 if let OperandValue::Pair(_, meta) = args[0].val {
207 glue::size_and_align_of_dst(self, tp_ty, Some(meta));
210 self.const_usize(self.size_of(tp_ty).bytes())
214 let tp_ty = substs.type_at(0);
215 self.const_usize(self.align_of(tp_ty).bytes())
217 "min_align_of_val" => {
218 let tp_ty = substs.type_at(0);
219 if let OperandValue::Pair(_, meta) = args[0].val {
221 glue::size_and_align_of_dst(self, tp_ty, Some(meta));
224 self.const_usize(self.align_of(tp_ty).bytes())
228 let tp_ty = substs.type_at(0);
229 self.const_usize(self.layout_of(tp_ty).align.pref.bytes())
232 let tp_ty = substs.type_at(0);
233 let ty_name = Symbol::intern(&tp_ty.to_string()).as_str();
234 self.const_str_slice(ty_name)
237 self.const_u64(self.tcx.type_id_hash(substs.type_at(0)))
240 let ty = substs.type_at(0);
241 if !self.layout_of(ty).is_zst() {
242 // Just zero out the stack slot.
243 // If we store a zero constant, LLVM will drown in vreg allocation for large
244 // data structures, and the generated code will be awful. (A telltale sign of
245 // this is large quantities of `mov [byte ptr foo],0` in the generated code.)
257 // Effectively no-ops
258 "uninit" | "forget" => {
262 let tp_ty = substs.type_at(0);
264 self.const_bool(self.type_needs_drop(tp_ty))
267 let ptr = args[0].immediate();
268 let offset = args[1].immediate();
269 self.inbounds_gep(ptr, &[offset])
272 let ptr = args[0].immediate();
273 let offset = args[1].immediate();
274 self.gep(ptr, &[offset])
277 "copy_nonoverlapping" => {
278 copy_intrinsic(self, false, false, substs.type_at(0),
279 args[1].immediate(), args[0].immediate(), args[2].immediate());
283 copy_intrinsic(self, true, false, substs.type_at(0),
284 args[1].immediate(), args[0].immediate(), args[2].immediate());
288 memset_intrinsic(self, false, substs.type_at(0),
289 args[0].immediate(), args[1].immediate(), args[2].immediate());
293 "volatile_copy_nonoverlapping_memory" => {
294 copy_intrinsic(self, false, true, substs.type_at(0),
295 args[0].immediate(), args[1].immediate(), args[2].immediate());
298 "volatile_copy_memory" => {
299 copy_intrinsic(self, true, true, substs.type_at(0),
300 args[0].immediate(), args[1].immediate(), args[2].immediate());
303 "volatile_set_memory" => {
304 memset_intrinsic(self, true, substs.type_at(0),
305 args[0].immediate(), args[1].immediate(), args[2].immediate());
308 "volatile_load" | "unaligned_volatile_load" => {
309 let tp_ty = substs.type_at(0);
310 let mut ptr = args[0].immediate();
311 if let PassMode::Cast(ty) = fn_ty.ret.mode {
312 ptr = self.pointercast(ptr, self.type_ptr_to(ty.llvm_type(self)));
314 let load = self.volatile_load(ptr);
315 let align = if name == "unaligned_volatile_load" {
318 self.align_of(tp_ty).bytes() as u32
321 llvm::LLVMSetAlignment(load, align);
323 to_immediate(self, load, self.layout_of(tp_ty))
325 "volatile_store" => {
326 let dst = args[0].deref(self.cx());
327 args[1].val.volatile_store(self, dst);
330 "unaligned_volatile_store" => {
331 let dst = args[0].deref(self.cx());
332 args[1].val.unaligned_volatile_store(self, dst);
335 "prefetch_read_data" | "prefetch_write_data" |
336 "prefetch_read_instruction" | "prefetch_write_instruction" => {
337 let expect = self.get_intrinsic(&("llvm.prefetch"));
338 let (rw, cache_type) = match name {
339 "prefetch_read_data" => (0, 1),
340 "prefetch_write_data" => (1, 1),
341 "prefetch_read_instruction" => (0, 0),
342 "prefetch_write_instruction" => (1, 0),
349 self.const_i32(cache_type)
352 "ctlz" | "ctlz_nonzero" | "cttz" | "cttz_nonzero" | "ctpop" | "bswap" |
353 "bitreverse" | "add_with_overflow" | "sub_with_overflow" |
354 "mul_with_overflow" | "overflowing_add" | "overflowing_sub" | "overflowing_mul" |
355 "unchecked_div" | "unchecked_rem" | "unchecked_shl" | "unchecked_shr" | "exact_div" |
356 "rotate_left" | "rotate_right" => {
358 match int_type_width_signed(ty, self) {
359 Some((width, signed)) =>
362 let y = self.const_bool(false);
363 let llfn = self.get_intrinsic(
364 &format!("llvm.{}.i{}", name, width),
366 self.call(llfn, &[args[0].immediate(), y], None)
368 "ctlz_nonzero" | "cttz_nonzero" => {
369 let y = self.const_bool(true);
370 let llvm_name = &format!("llvm.{}.i{}", &name[..4], width);
371 let llfn = self.get_intrinsic(llvm_name);
372 self.call(llfn, &[args[0].immediate(), y], None)
374 "ctpop" => self.call(
375 self.get_intrinsic(&format!("llvm.ctpop.i{}", width)),
376 &[args[0].immediate()],
381 args[0].immediate() // byte swap a u8/i8 is just a no-op
385 &format!("llvm.bswap.i{}", width),
387 &[args[0].immediate()],
395 &format!("llvm.bitreverse.i{}", width),
397 &[args[0].immediate()],
401 "add_with_overflow" | "sub_with_overflow" | "mul_with_overflow" => {
402 let intrinsic = format!("llvm.{}{}.with.overflow.i{}",
403 if signed { 's' } else { 'u' },
405 let llfn = self.get_intrinsic(&intrinsic);
407 // Convert `i1` to a `bool`, and write it to the out parameter
408 let pair = self.call(llfn, &[
412 let val = self.extract_value(pair, 0);
413 let overflow = self.extract_value(pair, 1);
414 let overflow = self.zext(overflow, self.type_bool());
416 let dest = result.project_field(self, 0);
417 self.store(val, dest.llval, dest.align);
418 let dest = result.project_field(self, 1);
419 self.store(overflow, dest.llval, dest.align);
423 "overflowing_add" => self.add(args[0].immediate(), args[1].immediate()),
424 "overflowing_sub" => self.sub(args[0].immediate(), args[1].immediate()),
425 "overflowing_mul" => self.mul(args[0].immediate(), args[1].immediate()),
428 self.exactsdiv(args[0].immediate(), args[1].immediate())
430 self.exactudiv(args[0].immediate(), args[1].immediate())
434 self.sdiv(args[0].immediate(), args[1].immediate())
436 self.udiv(args[0].immediate(), args[1].immediate())
440 self.srem(args[0].immediate(), args[1].immediate())
442 self.urem(args[0].immediate(), args[1].immediate())
444 "unchecked_shl" => self.shl(args[0].immediate(), args[1].immediate()),
447 self.ashr(args[0].immediate(), args[1].immediate())
449 self.lshr(args[0].immediate(), args[1].immediate())
451 "rotate_left" | "rotate_right" => {
452 let is_left = name == "rotate_left";
453 let val = args[0].immediate();
454 let raw_shift = args[1].immediate();
455 if llvm_util::get_major_version() >= 7 {
456 // rotate = funnel shift with first two args the same
457 let llvm_name = &format!("llvm.fsh{}.i{}",
458 if is_left { 'l' } else { 'r' }, width);
459 let llfn = self.get_intrinsic(llvm_name);
460 self.call(llfn, &[val, val, raw_shift], None)
462 // rotate_left: (X << (S % BW)) | (X >> ((BW - S) % BW))
463 // rotate_right: (X << ((BW - S) % BW)) | (X >> (S % BW))
464 let width = self.const_uint(
468 let shift = self.urem(raw_shift, width);
469 let width_minus_raw_shift = self.sub(width, raw_shift);
470 let inv_shift = self.urem(width_minus_raw_shift, width);
471 let shift1 = self.shl(
473 if is_left { shift } else { inv_shift },
475 let shift2 = self.lshr(
477 if !is_left { shift } else { inv_shift },
479 self.or(shift1, shift2)
485 span_invalid_monomorphization_error(
487 &format!("invalid monomorphization of `{}` intrinsic: \
488 expected basic integer type, found `{}`", name, ty));
494 "fadd_fast" | "fsub_fast" | "fmul_fast" | "fdiv_fast" | "frem_fast" => {
495 let sty = &arg_tys[0].sty;
496 match float_type_width(sty) {
499 "fadd_fast" => self.fadd_fast(args[0].immediate(), args[1].immediate()),
500 "fsub_fast" => self.fsub_fast(args[0].immediate(), args[1].immediate()),
501 "fmul_fast" => self.fmul_fast(args[0].immediate(), args[1].immediate()),
502 "fdiv_fast" => self.fdiv_fast(args[0].immediate(), args[1].immediate()),
503 "frem_fast" => self.frem_fast(args[0].immediate(), args[1].immediate()),
507 span_invalid_monomorphization_error(
509 &format!("invalid monomorphization of `{}` intrinsic: \
510 expected basic float type, found `{}`", name, sty));
517 "discriminant_value" => {
518 args[0].deref(self.cx()).codegen_get_discr(self, ret_ty)
521 name if name.starts_with("simd_") => {
522 match generic_simd_intrinsic(self, name,
531 // This requires that atomic intrinsics follow a specific naming pattern:
532 // "atomic_<operation>[_<ordering>]", and no ordering means SeqCst
533 name if name.starts_with("atomic_") => {
534 use rustc_codegen_ssa::common::AtomicOrdering::*;
535 use rustc_codegen_ssa::common::
536 {SynchronizationScope, AtomicRmwBinOp};
538 let split: Vec<&str> = name.split('_').collect();
540 let is_cxchg = split[1] == "cxchg" || split[1] == "cxchgweak";
541 let (order, failorder) = match split.len() {
542 2 => (SequentiallyConsistent, SequentiallyConsistent),
543 3 => match split[2] {
544 "unordered" => (Unordered, Unordered),
545 "relaxed" => (Monotonic, Monotonic),
546 "acq" => (Acquire, Acquire),
547 "rel" => (Release, Monotonic),
548 "acqrel" => (AcquireRelease, Acquire),
549 "failrelaxed" if is_cxchg =>
550 (SequentiallyConsistent, Monotonic),
551 "failacq" if is_cxchg =>
552 (SequentiallyConsistent, Acquire),
553 _ => self.sess().fatal("unknown ordering in atomic intrinsic")
555 4 => match (split[2], split[3]) {
556 ("acq", "failrelaxed") if is_cxchg =>
557 (Acquire, Monotonic),
558 ("acqrel", "failrelaxed") if is_cxchg =>
559 (AcquireRelease, Monotonic),
560 _ => self.sess().fatal("unknown ordering in atomic intrinsic")
562 _ => self.sess().fatal("Atomic intrinsic not in correct format"),
565 let invalid_monomorphization = |ty| {
566 span_invalid_monomorphization_error(tcx.sess, span,
567 &format!("invalid monomorphization of `{}` intrinsic: \
568 expected basic integer type, found `{}`", name, ty));
572 "cxchg" | "cxchgweak" => {
573 let ty = substs.type_at(0);
574 if int_type_width_signed(ty, self).is_some() {
575 let weak = split[1] == "cxchgweak";
576 let pair = self.atomic_cmpxchg(
583 let val = self.extract_value(pair, 0);
584 let success = self.extract_value(pair, 1);
585 let success = self.zext(success, self.type_bool());
587 let dest = result.project_field(self, 0);
588 self.store(val, dest.llval, dest.align);
589 let dest = result.project_field(self, 1);
590 self.store(success, dest.llval, dest.align);
593 return invalid_monomorphization(ty);
598 let ty = substs.type_at(0);
599 if int_type_width_signed(ty, self).is_some() {
600 let size = self.size_of(ty);
601 self.atomic_load(args[0].immediate(), order, size)
603 return invalid_monomorphization(ty);
608 let ty = substs.type_at(0);
609 if int_type_width_signed(ty, self).is_some() {
610 let size = self.size_of(ty);
619 return invalid_monomorphization(ty);
624 self.atomic_fence(order, SynchronizationScope::CrossThread);
628 "singlethreadfence" => {
629 self.atomic_fence(order, SynchronizationScope::SingleThread);
633 // These are all AtomicRMW ops
635 let atom_op = match op {
636 "xchg" => AtomicRmwBinOp::AtomicXchg,
637 "xadd" => AtomicRmwBinOp::AtomicAdd,
638 "xsub" => AtomicRmwBinOp::AtomicSub,
639 "and" => AtomicRmwBinOp::AtomicAnd,
640 "nand" => AtomicRmwBinOp::AtomicNand,
641 "or" => AtomicRmwBinOp::AtomicOr,
642 "xor" => AtomicRmwBinOp::AtomicXor,
643 "max" => AtomicRmwBinOp::AtomicMax,
644 "min" => AtomicRmwBinOp::AtomicMin,
645 "umax" => AtomicRmwBinOp::AtomicUMax,
646 "umin" => AtomicRmwBinOp::AtomicUMin,
647 _ => self.sess().fatal("unknown atomic operation")
650 let ty = substs.type_at(0);
651 if int_type_width_signed(ty, self).is_some() {
659 return invalid_monomorphization(ty);
665 "nontemporal_store" => {
666 let dst = args[0].deref(self.cx());
667 args[1].val.nontemporal_store(self, dst);
672 let intr = match Intrinsic::find(&name) {
674 None => bug!("unknown intrinsic '{}'", name),
676 fn one<T>(x: Vec<T>) -> T {
677 assert_eq!(x.len(), 1);
678 x.into_iter().next().unwrap()
681 cx: &CodegenCx<'ll, '_>,
683 ) -> Vec<&'ll Type> {
684 use intrinsics::Type::*;
686 Void => vec![cx.type_void()],
687 Integer(_signed, _width, llvm_width) => {
688 vec![cx.type_ix( llvm_width as u64)]
692 32 => vec![cx.type_f32()],
693 64 => vec![cx.type_f64()],
697 Pointer(ref t, ref llvm_elem, _const) => {
698 let t = llvm_elem.as_ref().unwrap_or(t);
699 let elem = one(ty_to_type(cx, t));
700 vec![cx.type_ptr_to(elem)]
702 Vector(ref t, ref llvm_elem, length) => {
703 let t = llvm_elem.as_ref().unwrap_or(t);
704 let elem = one(ty_to_type(cx, t));
705 vec![cx.type_vector(elem, length as u64)]
707 Aggregate(false, ref contents) => {
708 let elems = contents.iter()
709 .map(|t| one(ty_to_type(cx, t)))
710 .collect::<Vec<_>>();
711 vec![cx.type_struct( &elems, false)]
713 Aggregate(true, ref contents) => {
715 .flat_map(|t| ty_to_type(cx, t))
721 // This allows an argument list like `foo, (bar, baz),
722 // qux` to be converted into `foo, bar, baz, qux`, integer
723 // arguments to be truncated as needed and pointers to be
725 fn modify_as_needed<'ll, 'tcx>(
726 bx: &mut Builder<'_, 'll, 'tcx>,
727 t: &intrinsics::Type,
728 arg: &OperandRef<'tcx, &'ll Value>,
729 ) -> Vec<&'ll Value> {
731 intrinsics::Type::Aggregate(true, ref contents) => {
732 // We found a tuple that needs squishing! So
733 // run over the tuple and load each field.
735 // This assumes the type is "simple", i.e., no
736 // destructors, and the contents are SIMD
738 assert!(!bx.type_needs_drop(arg.layout.ty));
739 let (ptr, align) = match arg.val {
740 OperandValue::Ref(ptr, None, align) => (ptr, align),
743 let arg = PlaceRef::new_sized(ptr, arg.layout, align);
744 (0..contents.len()).map(|i| {
745 let field = arg.project_field(bx, i);
746 bx.load_operand(field).immediate()
749 intrinsics::Type::Pointer(_, Some(ref llvm_elem), _) => {
750 let llvm_elem = one(ty_to_type(bx, llvm_elem));
751 vec![bx.pointercast(arg.immediate(), bx.type_ptr_to(llvm_elem))]
753 intrinsics::Type::Vector(_, Some(ref llvm_elem), length) => {
754 let llvm_elem = one(ty_to_type(bx, llvm_elem));
756 bx.bitcast(arg.immediate(),
757 bx.type_vector(llvm_elem, length as u64))
760 intrinsics::Type::Integer(_, width, llvm_width) if width != llvm_width => {
761 // the LLVM intrinsic uses a smaller integer
762 // size than the C intrinsic's signature, so
763 // we have to trim it down here.
764 vec![bx.trunc(arg.immediate(), bx.type_ix(llvm_width as u64))]
766 _ => vec![arg.immediate()],
771 let inputs = intr.inputs.iter()
772 .flat_map(|t| ty_to_type(self, t))
773 .collect::<Vec<_>>();
775 let outputs = one(ty_to_type(self, &intr.output));
777 let llargs: Vec<_> = intr.inputs.iter().zip(args).flat_map(|(t, arg)| {
778 modify_as_needed(self, t, arg)
780 assert_eq!(inputs.len(), llargs.len());
782 let val = match intr.definition {
783 intrinsics::IntrinsicDef::Named(name) => {
784 let f = self.declare_cfn(
786 self.type_func(&inputs, outputs),
788 self.call(f, &llargs, None)
793 intrinsics::Type::Aggregate(flatten, ref elems) => {
794 // the output is a tuple so we need to munge it properly
797 for i in 0..elems.len() {
798 let dest = result.project_field(self, i);
799 let val = self.extract_value(val, i as u64);
800 self.store(val, dest.llval, dest.align);
809 if !fn_ty.ret.is_ignore() {
810 if let PassMode::Cast(ty) = fn_ty.ret.mode {
811 let ptr_llty = self.type_ptr_to(ty.llvm_type(self));
812 let ptr = self.pointercast(result.llval, ptr_llty);
813 self.store(llval, ptr, result.align);
815 OperandRef::from_immediate_or_packed_pair(self, llval, result.layout)
816 .val.store(self, result);
821 fn abort(&mut self) {
822 let fnname = self.get_intrinsic(&("llvm.trap"));
823 self.call(fnname, &[], None);
826 fn assume(&mut self, val: Self::Value) {
827 let assume_intrinsic = self.get_intrinsic("llvm.assume");
828 self.call(assume_intrinsic, &[val], None);
831 fn expect(&mut self, cond: Self::Value, expected: bool) -> Self::Value {
832 let expect = self.get_intrinsic(&"llvm.expect.i1");
833 self.call(expect, &[cond, self.const_bool(expected)], None)
838 bx: &mut Builder<'a, 'll, 'tcx>,
846 let (size, align) = bx.size_and_align_of(ty);
847 let size = bx.mul(bx.const_usize(size.bytes()), count);
848 let flags = if volatile {
854 bx.memmove(dst, align, src, align, size, flags);
856 bx.memcpy(dst, align, src, align, size, flags);
861 bx: &mut Builder<'a, 'll, 'tcx>,
868 let (size, align) = bx.size_and_align_of(ty);
869 let size = bx.mul(bx.const_usize(size.bytes()), count);
870 let flags = if volatile {
875 bx.memset(dst, val, size, align, flags);
879 bx: &mut Builder<'a, 'll, 'tcx>,
882 local_ptr: &'ll Value,
885 if bx.sess().no_landing_pads() {
886 bx.call(func, &[data], None);
887 let ptr_align = bx.tcx().data_layout.pointer_align.abi;
888 bx.store(bx.const_null(bx.type_i8p()), dest, ptr_align);
889 } else if wants_msvc_seh(bx.sess()) {
890 codegen_msvc_try(bx, func, data, local_ptr, dest);
892 codegen_gnu_try(bx, func, data, local_ptr, dest);
896 // MSVC's definition of the `rust_try` function.
898 // This implementation uses the new exception handling instructions in LLVM
899 // which have support in LLVM for SEH on MSVC targets. Although these
900 // instructions are meant to work for all targets, as of the time of this
901 // writing, however, LLVM does not recommend the usage of these new instructions
902 // as the old ones are still more optimized.
904 bx: &mut Builder<'a, 'll, 'tcx>,
907 local_ptr: &'ll Value,
910 let llfn = get_rust_try_fn(bx, &mut |mut bx| {
911 bx.set_personality_fn(bx.eh_personality());
913 let mut normal = bx.build_sibling_block("normal");
914 let mut catchswitch = bx.build_sibling_block("catchswitch");
915 let mut catchpad = bx.build_sibling_block("catchpad");
916 let mut caught = bx.build_sibling_block("caught");
918 let func = llvm::get_param(bx.llfn(), 0);
919 let data = llvm::get_param(bx.llfn(), 1);
920 let local_ptr = llvm::get_param(bx.llfn(), 2);
922 // We're generating an IR snippet that looks like:
924 // declare i32 @rust_try(%func, %data, %ptr) {
925 // %slot = alloca i64*
926 // invoke %func(%data) to label %normal unwind label %catchswitch
932 // %cs = catchswitch within none [%catchpad] unwind to caller
935 // %tok = catchpad within %cs [%type_descriptor, 0, %slot]
936 // %ptr[0] = %slot[0]
937 // %ptr[1] = %slot[1]
938 // catchret from %tok to label %caught
944 // This structure follows the basic usage of throw/try/catch in LLVM.
945 // For example, compile this C++ snippet to see what LLVM generates:
947 // #include <stdint.h>
949 // int bar(void (*foo)(void), uint64_t *ret) {
953 // } catch(uint64_t a[2]) {
960 // More information can be found in libstd's seh.rs implementation.
961 let i64p = bx.type_ptr_to(bx.type_i64());
962 let ptr_align = bx.tcx().data_layout.pointer_align.abi;
963 let slot = bx.alloca(i64p, "slot", ptr_align);
964 bx.invoke(func, &[data], normal.llbb(), catchswitch.llbb(), None);
966 normal.ret(bx.const_i32(0));
968 let cs = catchswitch.catch_switch(None, None, 1);
969 catchswitch.add_handler(cs, catchpad.llbb());
971 let tydesc = match bx.tcx().lang_items().msvc_try_filter() {
972 Some(did) => bx.get_static(did),
973 None => bug!("msvc_try_filter not defined"),
975 let funclet = catchpad.catch_pad(cs, &[tydesc, bx.const_i32(0), slot]);
976 let addr = catchpad.load(slot, ptr_align);
978 let i64_align = bx.tcx().data_layout.i64_align.abi;
979 let arg1 = catchpad.load(addr, i64_align);
980 let val1 = bx.const_i32(1);
981 let gep1 = catchpad.inbounds_gep(addr, &[val1]);
982 let arg2 = catchpad.load(gep1, i64_align);
983 let local_ptr = catchpad.bitcast(local_ptr, i64p);
984 let gep2 = catchpad.inbounds_gep(local_ptr, &[val1]);
985 catchpad.store(arg1, local_ptr, i64_align);
986 catchpad.store(arg2, gep2, i64_align);
987 catchpad.catch_ret(&funclet, caught.llbb());
989 caught.ret(bx.const_i32(1));
992 // Note that no invoke is used here because by definition this function
993 // can't panic (that's what it's catching).
994 let ret = bx.call(llfn, &[func, data, local_ptr], None);
995 let i32_align = bx.tcx().data_layout.i32_align.abi;
996 bx.store(ret, dest, i32_align);
999 // Definition of the standard "try" function for Rust using the GNU-like model
1000 // of exceptions (e.g., the normal semantics of LLVM's landingpad and invoke
1003 // This codegen is a little surprising because we always call a shim
1004 // function instead of inlining the call to `invoke` manually here. This is done
1005 // because in LLVM we're only allowed to have one personality per function
1006 // definition. The call to the `try` intrinsic is being inlined into the
1007 // function calling it, and that function may already have other personality
1008 // functions in play. By calling a shim we're guaranteed that our shim will have
1009 // the right personality function.
1011 bx: &mut Builder<'a, 'll, 'tcx>,
1014 local_ptr: &'ll Value,
1017 let llfn = get_rust_try_fn(bx, &mut |mut bx| {
1018 // Codegens the shims described above:
1021 // invoke %func(%args...) normal %normal unwind %catch
1027 // (ptr, _) = landingpad
1028 // store ptr, %local_ptr
1031 // Note that the `local_ptr` data passed into the `try` intrinsic is
1032 // expected to be `*mut *mut u8` for this to actually work, but that's
1033 // managed by the standard library.
1035 let mut then = bx.build_sibling_block("then");
1036 let mut catch = bx.build_sibling_block("catch");
1038 let func = llvm::get_param(bx.llfn(), 0);
1039 let data = llvm::get_param(bx.llfn(), 1);
1040 let local_ptr = llvm::get_param(bx.llfn(), 2);
1041 bx.invoke(func, &[data], then.llbb(), catch.llbb(), None);
1042 then.ret(bx.const_i32(0));
1044 // Type indicator for the exception being thrown.
1046 // The first value in this tuple is a pointer to the exception object
1047 // being thrown. The second value is a "selector" indicating which of
1048 // the landing pad clauses the exception's type had been matched to.
1049 // rust_try ignores the selector.
1050 let lpad_ty = bx.type_struct(&[bx.type_i8p(), bx.type_i32()], false);
1051 let vals = catch.landing_pad(lpad_ty, bx.eh_personality(), 1);
1052 catch.add_clause(vals, bx.const_null(bx.type_i8p()));
1053 let ptr = catch.extract_value(vals, 0);
1054 let ptr_align = bx.tcx().data_layout.pointer_align.abi;
1055 let bitcast = catch.bitcast(local_ptr, bx.type_ptr_to(bx.type_i8p()));
1056 catch.store(ptr, bitcast, ptr_align);
1057 catch.ret(bx.const_i32(1));
1060 // Note that no invoke is used here because by definition this function
1061 // can't panic (that's what it's catching).
1062 let ret = bx.call(llfn, &[func, data, local_ptr], None);
1063 let i32_align = bx.tcx().data_layout.i32_align.abi;
1064 bx.store(ret, dest, i32_align);
1067 // Helper function to give a Block to a closure to codegen a shim function.
1068 // This is currently primarily used for the `try` intrinsic functions above.
1069 fn gen_fn<'ll, 'tcx>(
1070 cx: &CodegenCx<'ll, 'tcx>,
1072 inputs: Vec<Ty<'tcx>>,
1074 codegen: &mut dyn FnMut(Builder<'_, 'll, 'tcx>),
1076 let rust_fn_sig = ty::Binder::bind(cx.tcx.mk_fn_sig(
1080 hir::Unsafety::Unsafe,
1083 let llfn = cx.define_internal_fn(name, rust_fn_sig);
1084 attributes::from_fn_attrs(cx, llfn, None);
1085 let bx = Builder::new_block(cx, llfn, "entry-block");
1090 // Helper function used to get a handle to the `__rust_try` function used to
1091 // catch exceptions.
1093 // This function is only generated once and is then cached.
1094 fn get_rust_try_fn<'ll, 'tcx>(
1095 cx: &CodegenCx<'ll, 'tcx>,
1096 codegen: &mut dyn FnMut(Builder<'_, 'll, 'tcx>),
1098 if let Some(llfn) = cx.rust_try_fn.get() {
1102 // Define the type up front for the signature of the rust_try function.
1104 let i8p = tcx.mk_mut_ptr(tcx.types.i8);
1105 let fn_ty = tcx.mk_fn_ptr(ty::Binder::bind(tcx.mk_fn_sig(
1109 hir::Unsafety::Unsafe,
1112 let output = tcx.types.i32;
1113 let rust_try = gen_fn(cx, "__rust_try", vec![fn_ty, i8p, i8p], output, codegen);
1114 cx.rust_try_fn.set(Some(rust_try));
1118 fn span_invalid_monomorphization_error(a: &Session, b: Span, c: &str) {
1119 span_err!(a, b, E0511, "{}", c);
1122 fn generic_simd_intrinsic(
1123 bx: &mut Builder<'a, 'll, 'tcx>,
1125 callee_ty: Ty<'tcx>,
1126 args: &[OperandRef<'tcx, &'ll Value>],
1128 llret_ty: &'ll Type,
1130 ) -> Result<&'ll Value, ()> {
1131 // macros for error handling:
1132 macro_rules! emit_error {
1136 ($msg: tt, $($fmt: tt)*) => {
1137 span_invalid_monomorphization_error(
1139 &format!(concat!("invalid monomorphization of `{}` intrinsic: ", $msg),
1144 macro_rules! return_error {
1147 emit_error!($($fmt)*);
1153 macro_rules! require {
1154 ($cond: expr, $($fmt: tt)*) => {
1156 return_error!($($fmt)*);
1161 macro_rules! require_simd {
1162 ($ty: expr, $position: expr) => {
1163 require!($ty.is_simd(), "expected SIMD {} type, found non-SIMD `{}`", $position, $ty)
1168 let sig = tcx.normalize_erasing_late_bound_regions(
1169 ty::ParamEnv::reveal_all(),
1170 &callee_ty.fn_sig(tcx),
1172 let arg_tys = sig.inputs();
1174 // every intrinsic takes a SIMD vector as its first argument
1175 require_simd!(arg_tys[0], "input");
1176 let in_ty = arg_tys[0];
1177 let in_elem = arg_tys[0].simd_type(tcx);
1178 let in_len = arg_tys[0].simd_size(tcx);
1180 let comparison = match name {
1181 "simd_eq" => Some(hir::BinOpKind::Eq),
1182 "simd_ne" => Some(hir::BinOpKind::Ne),
1183 "simd_lt" => Some(hir::BinOpKind::Lt),
1184 "simd_le" => Some(hir::BinOpKind::Le),
1185 "simd_gt" => Some(hir::BinOpKind::Gt),
1186 "simd_ge" => Some(hir::BinOpKind::Ge),
1190 if let Some(cmp_op) = comparison {
1191 require_simd!(ret_ty, "return");
1193 let out_len = ret_ty.simd_size(tcx);
1194 require!(in_len == out_len,
1195 "expected return type with length {} (same as input type `{}`), \
1196 found `{}` with length {}",
1199 require!(bx.type_kind(bx.element_type(llret_ty)) == TypeKind::Integer,
1200 "expected return type with integer elements, found `{}` with non-integer `{}`",
1202 ret_ty.simd_type(tcx));
1204 return Ok(compare_simd_types(bx,
1205 args[0].immediate(),
1206 args[1].immediate(),
1212 if name.starts_with("simd_shuffle") {
1213 let n: usize = name["simd_shuffle".len()..].parse().unwrap_or_else(|_|
1214 span_bug!(span, "bad `simd_shuffle` instruction only caught in codegen?"));
1216 require_simd!(ret_ty, "return");
1218 let out_len = ret_ty.simd_size(tcx);
1219 require!(out_len == n,
1220 "expected return type of length {}, found `{}` with length {}",
1221 n, ret_ty, out_len);
1222 require!(in_elem == ret_ty.simd_type(tcx),
1223 "expected return element type `{}` (element of input `{}`), \
1224 found `{}` with element type `{}`",
1226 ret_ty, ret_ty.simd_type(tcx));
1228 let total_len = in_len as u128 * 2;
1230 let vector = args[2].immediate();
1232 let indices: Option<Vec<_>> = (0..n)
1235 let val = bx.const_get_elt(vector, i as u64);
1236 match bx.const_to_opt_u128(val, true) {
1238 emit_error!("shuffle index #{} is not a constant", arg_idx);
1241 Some(idx) if idx >= total_len => {
1242 emit_error!("shuffle index #{} is out of bounds (limit {})",
1243 arg_idx, total_len);
1246 Some(idx) => Some(bx.const_i32(idx as i32)),
1250 let indices = match indices {
1252 None => return Ok(bx.const_null(llret_ty))
1255 return Ok(bx.shuffle_vector(args[0].immediate(),
1256 args[1].immediate(),
1257 bx.const_vector(&indices)))
1260 if name == "simd_insert" {
1261 require!(in_elem == arg_tys[2],
1262 "expected inserted type `{}` (element of input `{}`), found `{}`",
1263 in_elem, in_ty, arg_tys[2]);
1264 return Ok(bx.insert_element(args[0].immediate(),
1265 args[2].immediate(),
1266 args[1].immediate()))
1268 if name == "simd_extract" {
1269 require!(ret_ty == in_elem,
1270 "expected return type `{}` (element of input `{}`), found `{}`",
1271 in_elem, in_ty, ret_ty);
1272 return Ok(bx.extract_element(args[0].immediate(), args[1].immediate()))
1275 if name == "simd_select" {
1276 let m_elem_ty = in_elem;
1278 let v_len = arg_tys[1].simd_size(tcx);
1279 require!(m_len == v_len,
1280 "mismatched lengths: mask length `{}` != other vector length `{}`",
1283 match m_elem_ty.sty {
1285 _ => return_error!("mask element type is `{}`, expected `i_`", m_elem_ty)
1287 // truncate the mask to a vector of i1s
1288 let i1 = bx.type_i1();
1289 let i1xn = bx.type_vector(i1, m_len as u64);
1290 let m_i1s = bx.trunc(args[0].immediate(), i1xn);
1291 return Ok(bx.select(m_i1s, args[1].immediate(), args[2].immediate()));
1294 fn simd_simple_float_intrinsic(
1296 in_elem: &::rustc::ty::TyS,
1297 in_ty: &::rustc::ty::TyS,
1299 bx: &mut Builder<'a, 'll, 'tcx>,
1301 args: &[OperandRef<'tcx, &'ll Value>],
1302 ) -> Result<&'ll Value, ()> {
1303 macro_rules! emit_error {
1307 ($msg: tt, $($fmt: tt)*) => {
1308 span_invalid_monomorphization_error(
1310 &format!(concat!("invalid monomorphization of `{}` intrinsic: ", $msg),
1314 macro_rules! return_error {
1317 emit_error!($($fmt)*);
1322 let ety = match in_elem.sty {
1323 ty::Float(f) if f.bit_width() == 32 => {
1324 if in_len < 2 || in_len > 16 {
1326 "unsupported floating-point vector `{}` with length `{}` \
1327 out-of-range [2, 16]",
1332 ty::Float(f) if f.bit_width() == 64 => {
1333 if in_len < 2 || in_len > 8 {
1334 return_error!("unsupported floating-point vector `{}` with length `{}` \
1335 out-of-range [2, 8]",
1341 return_error!("unsupported element type `{}` of floating-point vector `{}`",
1345 return_error!("`{}` is not a floating-point type", in_ty);
1349 let llvm_name = &format!("llvm.{0}.v{1}{2}", name, in_len, ety);
1350 let intrinsic = bx.get_intrinsic(&llvm_name);
1351 let c = bx.call(intrinsic,
1352 &args.iter().map(|arg| arg.immediate()).collect::<Vec<_>>(),
1354 unsafe { llvm::LLVMRustSetHasUnsafeAlgebra(c) };
1360 return simd_simple_float_intrinsic("sqrt", in_elem, in_ty, in_len, bx, span, args);
1363 return simd_simple_float_intrinsic("sin", in_elem, in_ty, in_len, bx, span, args);
1366 return simd_simple_float_intrinsic("cos", in_elem, in_ty, in_len, bx, span, args);
1369 return simd_simple_float_intrinsic("fabs", in_elem, in_ty, in_len, bx, span, args);
1372 return simd_simple_float_intrinsic("floor", in_elem, in_ty, in_len, bx, span, args);
1375 return simd_simple_float_intrinsic("ceil", in_elem, in_ty, in_len, bx, span, args);
1378 return simd_simple_float_intrinsic("exp", in_elem, in_ty, in_len, bx, span, args);
1381 return simd_simple_float_intrinsic("exp2", in_elem, in_ty, in_len, bx, span, args);
1384 return simd_simple_float_intrinsic("log10", in_elem, in_ty, in_len, bx, span, args);
1387 return simd_simple_float_intrinsic("log2", in_elem, in_ty, in_len, bx, span, args);
1390 return simd_simple_float_intrinsic("log", in_elem, in_ty, in_len, bx, span, args);
1393 return simd_simple_float_intrinsic("powi", in_elem, in_ty, in_len, bx, span, args);
1396 return simd_simple_float_intrinsic("pow", in_elem, in_ty, in_len, bx, span, args);
1399 return simd_simple_float_intrinsic("fma", in_elem, in_ty, in_len, bx, span, args);
1401 _ => { /* fallthrough */ }
1405 // https://github.com/llvm-mirror/llvm/blob/master/include/llvm/IR/Function.h#L182
1406 // https://github.com/llvm-mirror/llvm/blob/master/include/llvm/IR/Intrinsics.h#L81
1407 fn llvm_vector_str(elem_ty: ty::Ty, vec_len: usize, no_pointers: usize) -> String {
1408 let p0s: String = "p0".repeat(no_pointers);
1410 ty::Int(v) => format!("v{}{}i{}", vec_len, p0s, v.bit_width().unwrap()),
1411 ty::Uint(v) => format!("v{}{}i{}", vec_len, p0s, v.bit_width().unwrap()),
1412 ty::Float(v) => format!("v{}{}f{}", vec_len, p0s, v.bit_width()),
1413 _ => unreachable!(),
1417 fn llvm_vector_ty(cx: &CodegenCx<'ll, '_>, elem_ty: ty::Ty, vec_len: usize,
1418 mut no_pointers: usize) -> &'ll Type {
1419 // FIXME: use cx.layout_of(ty).llvm_type() ?
1420 let mut elem_ty = match elem_ty.sty {
1421 ty::Int(v) => cx.type_int_from_ty( v),
1422 ty::Uint(v) => cx.type_uint_from_ty( v),
1423 ty::Float(v) => cx.type_float_from_ty( v),
1424 _ => unreachable!(),
1426 while no_pointers > 0 {
1427 elem_ty = cx.type_ptr_to(elem_ty);
1430 cx.type_vector(elem_ty, vec_len as u64)
1434 if name == "simd_gather" {
1435 // simd_gather(values: <N x T>, pointers: <N x *_ T>,
1436 // mask: <N x i{M}>) -> <N x T>
1437 // * N: number of elements in the input vectors
1438 // * T: type of the element to load
1439 // * M: any integer width is supported, will be truncated to i1
1441 // All types must be simd vector types
1442 require_simd!(in_ty, "first");
1443 require_simd!(arg_tys[1], "second");
1444 require_simd!(arg_tys[2], "third");
1445 require_simd!(ret_ty, "return");
1447 // Of the same length:
1448 require!(in_len == arg_tys[1].simd_size(tcx),
1449 "expected {} argument with length {} (same as input type `{}`), \
1450 found `{}` with length {}", "second", in_len, in_ty, arg_tys[1],
1451 arg_tys[1].simd_size(tcx));
1452 require!(in_len == arg_tys[2].simd_size(tcx),
1453 "expected {} argument with length {} (same as input type `{}`), \
1454 found `{}` with length {}", "third", in_len, in_ty, arg_tys[2],
1455 arg_tys[2].simd_size(tcx));
1457 // The return type must match the first argument type
1458 require!(ret_ty == in_ty,
1459 "expected return type `{}`, found `{}`",
1462 // This counts how many pointers
1463 fn ptr_count(t: ty::Ty) -> usize {
1465 ty::RawPtr(p) => 1 + ptr_count(p.ty),
1471 fn non_ptr(t: ty::Ty) -> ty::Ty {
1473 ty::RawPtr(p) => non_ptr(p.ty),
1478 // The second argument must be a simd vector with an element type that's a pointer
1479 // to the element type of the first argument
1480 let (pointer_count, underlying_ty) = match arg_tys[1].simd_type(tcx).sty {
1481 ty::RawPtr(p) if p.ty == in_elem => (ptr_count(arg_tys[1].simd_type(tcx)),
1482 non_ptr(arg_tys[1].simd_type(tcx))),
1484 require!(false, "expected element type `{}` of second argument `{}` \
1485 to be a pointer to the element type `{}` of the first \
1486 argument `{}`, found `{}` != `*_ {}`",
1487 arg_tys[1].simd_type(tcx).sty, arg_tys[1], in_elem, in_ty,
1488 arg_tys[1].simd_type(tcx).sty, in_elem);
1492 assert!(pointer_count > 0);
1493 assert_eq!(pointer_count - 1, ptr_count(arg_tys[0].simd_type(tcx)));
1494 assert_eq!(underlying_ty, non_ptr(arg_tys[0].simd_type(tcx)));
1496 // The element type of the third argument must be a signed integer type of any width:
1497 match arg_tys[2].simd_type(tcx).sty {
1500 require!(false, "expected element type `{}` of third argument `{}` \
1501 to be a signed integer type",
1502 arg_tys[2].simd_type(tcx).sty, arg_tys[2]);
1506 // Alignment of T, must be a constant integer value:
1507 let alignment_ty = bx.type_i32();
1508 let alignment = bx.const_i32(bx.align_of(in_elem).bytes() as i32);
1510 // Truncate the mask vector to a vector of i1s:
1511 let (mask, mask_ty) = {
1512 let i1 = bx.type_i1();
1513 let i1xn = bx.type_vector(i1, in_len as u64);
1514 (bx.trunc(args[2].immediate(), i1xn), i1xn)
1517 // Type of the vector of pointers:
1518 let llvm_pointer_vec_ty = llvm_vector_ty(bx, underlying_ty, in_len, pointer_count);
1519 let llvm_pointer_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count);
1521 // Type of the vector of elements:
1522 let llvm_elem_vec_ty = llvm_vector_ty(bx, underlying_ty, in_len, pointer_count - 1);
1523 let llvm_elem_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count - 1);
1525 let llvm_intrinsic = format!("llvm.masked.gather.{}.{}",
1526 llvm_elem_vec_str, llvm_pointer_vec_str);
1527 let f = bx.declare_cfn(&llvm_intrinsic,
1529 llvm_pointer_vec_ty,
1532 llvm_elem_vec_ty], llvm_elem_vec_ty));
1533 llvm::SetUnnamedAddr(f, false);
1534 let v = bx.call(f, &[args[1].immediate(), alignment, mask, args[0].immediate()],
1539 if name == "simd_scatter" {
1540 // simd_scatter(values: <N x T>, pointers: <N x *mut T>,
1541 // mask: <N x i{M}>) -> ()
1542 // * N: number of elements in the input vectors
1543 // * T: type of the element to load
1544 // * M: any integer width is supported, will be truncated to i1
1546 // All types must be simd vector types
1547 require_simd!(in_ty, "first");
1548 require_simd!(arg_tys[1], "second");
1549 require_simd!(arg_tys[2], "third");
1551 // Of the same length:
1552 require!(in_len == arg_tys[1].simd_size(tcx),
1553 "expected {} argument with length {} (same as input type `{}`), \
1554 found `{}` with length {}", "second", in_len, in_ty, arg_tys[1],
1555 arg_tys[1].simd_size(tcx));
1556 require!(in_len == arg_tys[2].simd_size(tcx),
1557 "expected {} argument with length {} (same as input type `{}`), \
1558 found `{}` with length {}", "third", in_len, in_ty, arg_tys[2],
1559 arg_tys[2].simd_size(tcx));
1561 // This counts how many pointers
1562 fn ptr_count(t: ty::Ty) -> usize {
1564 ty::RawPtr(p) => 1 + ptr_count(p.ty),
1570 fn non_ptr(t: ty::Ty) -> ty::Ty {
1572 ty::RawPtr(p) => non_ptr(p.ty),
1577 // The second argument must be a simd vector with an element type that's a pointer
1578 // to the element type of the first argument
1579 let (pointer_count, underlying_ty) = match arg_tys[1].simd_type(tcx).sty {
1580 ty::RawPtr(p) if p.ty == in_elem && p.mutbl == hir::MutMutable
1581 => (ptr_count(arg_tys[1].simd_type(tcx)),
1582 non_ptr(arg_tys[1].simd_type(tcx))),
1584 require!(false, "expected element type `{}` of second argument `{}` \
1585 to be a pointer to the element type `{}` of the first \
1586 argument `{}`, found `{}` != `*mut {}`",
1587 arg_tys[1].simd_type(tcx).sty, arg_tys[1], in_elem, in_ty,
1588 arg_tys[1].simd_type(tcx).sty, in_elem);
1592 assert!(pointer_count > 0);
1593 assert_eq!(pointer_count - 1, ptr_count(arg_tys[0].simd_type(tcx)));
1594 assert_eq!(underlying_ty, non_ptr(arg_tys[0].simd_type(tcx)));
1596 // The element type of the third argument must be a signed integer type of any width:
1597 match arg_tys[2].simd_type(tcx).sty {
1600 require!(false, "expected element type `{}` of third argument `{}` \
1601 to be a signed integer type",
1602 arg_tys[2].simd_type(tcx).sty, arg_tys[2]);
1606 // Alignment of T, must be a constant integer value:
1607 let alignment_ty = bx.type_i32();
1608 let alignment = bx.const_i32(bx.align_of(in_elem).bytes() as i32);
1610 // Truncate the mask vector to a vector of i1s:
1611 let (mask, mask_ty) = {
1612 let i1 = bx.type_i1();
1613 let i1xn = bx.type_vector(i1, in_len as u64);
1614 (bx.trunc(args[2].immediate(), i1xn), i1xn)
1617 let ret_t = bx.type_void();
1619 // Type of the vector of pointers:
1620 let llvm_pointer_vec_ty = llvm_vector_ty(bx, underlying_ty, in_len, pointer_count);
1621 let llvm_pointer_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count);
1623 // Type of the vector of elements:
1624 let llvm_elem_vec_ty = llvm_vector_ty(bx, underlying_ty, in_len, pointer_count - 1);
1625 let llvm_elem_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count - 1);
1627 let llvm_intrinsic = format!("llvm.masked.scatter.{}.{}",
1628 llvm_elem_vec_str, llvm_pointer_vec_str);
1629 let f = bx.declare_cfn(&llvm_intrinsic,
1630 bx.type_func(&[llvm_elem_vec_ty,
1631 llvm_pointer_vec_ty,
1634 llvm::SetUnnamedAddr(f, false);
1635 let v = bx.call(f, &[args[0].immediate(), args[1].immediate(), alignment, mask],
1640 macro_rules! arith_red {
1641 ($name:tt : $integer_reduce:ident, $float_reduce:ident, $ordered:expr) => {
1643 require!(ret_ty == in_elem,
1644 "expected return type `{}` (element of input `{}`), found `{}`",
1645 in_elem, in_ty, ret_ty);
1646 return match in_elem.sty {
1647 ty::Int(_) | ty::Uint(_) => {
1648 let r = bx.$integer_reduce(args[0].immediate());
1650 // if overflow occurs, the result is the
1651 // mathematical result modulo 2^n:
1652 if name.contains("mul") {
1653 Ok(bx.mul(args[1].immediate(), r))
1655 Ok(bx.add(args[1].immediate(), r))
1658 Ok(bx.$integer_reduce(args[0].immediate()))
1662 // ordered arithmetic reductions take an accumulator
1663 let acc = if $ordered {
1664 let acc = args[1].immediate();
1665 // FIXME: https://bugs.llvm.org/show_bug.cgi?id=36734
1666 // * if the accumulator of the fadd isn't 0, incorrect
1667 // code is generated
1668 // * if the accumulator of the fmul isn't 1, incorrect
1669 // code is generated
1670 match bx.const_get_real(acc) {
1671 None => return_error!("accumulator of {} is not a constant", $name),
1672 Some((v, loses_info)) => {
1673 if $name.contains("mul") && v != 1.0_f64 {
1674 return_error!("accumulator of {} is not 1.0", $name);
1675 } else if $name.contains("add") && v != 0.0_f64 {
1676 return_error!("accumulator of {} is not 0.0", $name);
1677 } else if loses_info {
1678 return_error!("accumulator of {} loses information", $name);
1684 // unordered arithmetic reductions do not:
1685 match f.bit_width() {
1686 32 => bx.const_undef(bx.type_f32()),
1687 64 => bx.const_undef(bx.type_f64()),
1690 unsupported {} from `{}` with element `{}` of size `{}` to `{}`"#,
1691 $name, in_ty, in_elem, v, ret_ty
1696 Ok(bx.$float_reduce(acc, args[0].immediate()))
1700 "unsupported {} from `{}` with element `{}` to `{}`",
1701 $name, in_ty, in_elem, ret_ty
1709 arith_red!("simd_reduce_add_ordered": vector_reduce_add, vector_reduce_fadd_fast, true);
1710 arith_red!("simd_reduce_mul_ordered": vector_reduce_mul, vector_reduce_fmul_fast, true);
1711 arith_red!("simd_reduce_add_unordered": vector_reduce_add, vector_reduce_fadd_fast, false);
1712 arith_red!("simd_reduce_mul_unordered": vector_reduce_mul, vector_reduce_fmul_fast, false);
1714 macro_rules! minmax_red {
1715 ($name:tt: $int_red:ident, $float_red:ident) => {
1717 require!(ret_ty == in_elem,
1718 "expected return type `{}` (element of input `{}`), found `{}`",
1719 in_elem, in_ty, ret_ty);
1720 return match in_elem.sty {
1722 Ok(bx.$int_red(args[0].immediate(), true))
1725 Ok(bx.$int_red(args[0].immediate(), false))
1728 Ok(bx.$float_red(args[0].immediate()))
1731 return_error!("unsupported {} from `{}` with element `{}` to `{}`",
1732 $name, in_ty, in_elem, ret_ty)
1740 minmax_red!("simd_reduce_min": vector_reduce_min, vector_reduce_fmin);
1741 minmax_red!("simd_reduce_max": vector_reduce_max, vector_reduce_fmax);
1743 minmax_red!("simd_reduce_min_nanless": vector_reduce_min, vector_reduce_fmin_fast);
1744 minmax_red!("simd_reduce_max_nanless": vector_reduce_max, vector_reduce_fmax_fast);
1746 macro_rules! bitwise_red {
1747 ($name:tt : $red:ident, $boolean:expr) => {
1749 let input = if !$boolean {
1750 require!(ret_ty == in_elem,
1751 "expected return type `{}` (element of input `{}`), found `{}`",
1752 in_elem, in_ty, ret_ty);
1756 ty::Int(_) | ty::Uint(_) => {},
1758 return_error!("unsupported {} from `{}` with element `{}` to `{}`",
1759 $name, in_ty, in_elem, ret_ty)
1763 // boolean reductions operate on vectors of i1s:
1764 let i1 = bx.type_i1();
1765 let i1xn = bx.type_vector(i1, in_len as u64);
1766 bx.trunc(args[0].immediate(), i1xn)
1768 return match in_elem.sty {
1769 ty::Int(_) | ty::Uint(_) => {
1770 let r = bx.$red(input);
1775 bx.zext(r, bx.type_bool())
1780 return_error!("unsupported {} from `{}` with element `{}` to `{}`",
1781 $name, in_ty, in_elem, ret_ty)
1788 bitwise_red!("simd_reduce_and": vector_reduce_and, false);
1789 bitwise_red!("simd_reduce_or": vector_reduce_or, false);
1790 bitwise_red!("simd_reduce_xor": vector_reduce_xor, false);
1791 bitwise_red!("simd_reduce_all": vector_reduce_and, true);
1792 bitwise_red!("simd_reduce_any": vector_reduce_or, true);
1794 if name == "simd_cast" {
1795 require_simd!(ret_ty, "return");
1796 let out_len = ret_ty.simd_size(tcx);
1797 require!(in_len == out_len,
1798 "expected return type with length {} (same as input type `{}`), \
1799 found `{}` with length {}",
1802 // casting cares about nominal type, not just structural type
1803 let out_elem = ret_ty.simd_type(tcx);
1805 if in_elem == out_elem { return Ok(args[0].immediate()); }
1807 enum Style { Float, Int(/* is signed? */ bool), Unsupported }
1809 let (in_style, in_width) = match in_elem.sty {
1810 // vectors of pointer-sized integers should've been
1811 // disallowed before here, so this unwrap is safe.
1812 ty::Int(i) => (Style::Int(true), i.bit_width().unwrap()),
1813 ty::Uint(u) => (Style::Int(false), u.bit_width().unwrap()),
1814 ty::Float(f) => (Style::Float, f.bit_width()),
1815 _ => (Style::Unsupported, 0)
1817 let (out_style, out_width) = match out_elem.sty {
1818 ty::Int(i) => (Style::Int(true), i.bit_width().unwrap()),
1819 ty::Uint(u) => (Style::Int(false), u.bit_width().unwrap()),
1820 ty::Float(f) => (Style::Float, f.bit_width()),
1821 _ => (Style::Unsupported, 0)
1824 match (in_style, out_style) {
1825 (Style::Int(in_is_signed), Style::Int(_)) => {
1826 return Ok(match in_width.cmp(&out_width) {
1827 Ordering::Greater => bx.trunc(args[0].immediate(), llret_ty),
1828 Ordering::Equal => args[0].immediate(),
1829 Ordering::Less => if in_is_signed {
1830 bx.sext(args[0].immediate(), llret_ty)
1832 bx.zext(args[0].immediate(), llret_ty)
1836 (Style::Int(in_is_signed), Style::Float) => {
1837 return Ok(if in_is_signed {
1838 bx.sitofp(args[0].immediate(), llret_ty)
1840 bx.uitofp(args[0].immediate(), llret_ty)
1843 (Style::Float, Style::Int(out_is_signed)) => {
1844 return Ok(if out_is_signed {
1845 bx.fptosi(args[0].immediate(), llret_ty)
1847 bx.fptoui(args[0].immediate(), llret_ty)
1850 (Style::Float, Style::Float) => {
1851 return Ok(match in_width.cmp(&out_width) {
1852 Ordering::Greater => bx.fptrunc(args[0].immediate(), llret_ty),
1853 Ordering::Equal => args[0].immediate(),
1854 Ordering::Less => bx.fpext(args[0].immediate(), llret_ty)
1857 _ => {/* Unsupported. Fallthrough. */}
1860 "unsupported cast from `{}` with element `{}` to `{}` with element `{}`",
1864 macro_rules! arith {
1865 ($($name: ident: $($($p: ident),* => $call: ident),*;)*) => {
1866 $(if name == stringify!($name) {
1868 $($(ty::$p(_))|* => {
1869 return Ok(bx.$call(args[0].immediate(), args[1].immediate()))
1874 "unsupported operation on `{}` with element `{}`",
1881 simd_add: Uint, Int => add, Float => fadd;
1882 simd_sub: Uint, Int => sub, Float => fsub;
1883 simd_mul: Uint, Int => mul, Float => fmul;
1884 simd_div: Uint => udiv, Int => sdiv, Float => fdiv;
1885 simd_rem: Uint => urem, Int => srem, Float => frem;
1886 simd_shl: Uint, Int => shl;
1887 simd_shr: Uint => lshr, Int => ashr;
1888 simd_and: Uint, Int => and;
1889 simd_or: Uint, Int => or;
1890 simd_xor: Uint, Int => xor;
1891 simd_fmax: Float => maxnum;
1892 simd_fmin: Float => minnum;
1894 span_bug!(span, "unknown SIMD intrinsic");
1897 // Returns the width of an int Ty, and if it's signed or not
1898 // Returns None if the type is not an integer
1899 // FIXME: there’s multiple of this functions, investigate using some of the already existing
1901 fn int_type_width_signed(ty: Ty, cx: &CodegenCx) -> Option<(u64, bool)> {
1903 ty::Int(t) => Some((match t {
1904 ast::IntTy::Isize => cx.tcx.sess.target.isize_ty.bit_width().unwrap() as u64,
1905 ast::IntTy::I8 => 8,
1906 ast::IntTy::I16 => 16,
1907 ast::IntTy::I32 => 32,
1908 ast::IntTy::I64 => 64,
1909 ast::IntTy::I128 => 128,
1911 ty::Uint(t) => Some((match t {
1912 ast::UintTy::Usize => cx.tcx.sess.target.usize_ty.bit_width().unwrap() as u64,
1913 ast::UintTy::U8 => 8,
1914 ast::UintTy::U16 => 16,
1915 ast::UintTy::U32 => 32,
1916 ast::UintTy::U64 => 64,
1917 ast::UintTy::U128 => 128,
1923 // Returns the width of a float TypeVariant
1924 // Returns None if the type is not a float
1925 fn float_type_width<'tcx>(sty: &ty::TyKind<'tcx>) -> Option<u64> {
1927 ty::Float(t) => Some(t.bit_width() as u64),