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 mir::place::PlaceRef;
19 use mir::operand::{OperandRef, OperandValue};
22 use context::CodegenCx;
25 use type_of::LayoutLlvmExt;
26 use rustc::ty::{self, Ty};
27 use rustc::ty::layout::{LayoutOf, HasTyCtxt};
30 use syntax::symbol::Symbol;
31 use builder::{Builder, MemFlags};
36 use rustc::session::Session;
39 use std::cmp::Ordering;
42 fn get_simple_intrinsic(cx: &CodegenCx<'ll, '_>, name: &str) -> Option<&'ll Value> {
43 let llvm_name = match name {
44 "sqrtf32" => "llvm.sqrt.f32",
45 "sqrtf64" => "llvm.sqrt.f64",
46 "powif32" => "llvm.powi.f32",
47 "powif64" => "llvm.powi.f64",
48 "sinf32" => "llvm.sin.f32",
49 "sinf64" => "llvm.sin.f64",
50 "cosf32" => "llvm.cos.f32",
51 "cosf64" => "llvm.cos.f64",
52 "powf32" => "llvm.pow.f32",
53 "powf64" => "llvm.pow.f64",
54 "expf32" => "llvm.exp.f32",
55 "expf64" => "llvm.exp.f64",
56 "exp2f32" => "llvm.exp2.f32",
57 "exp2f64" => "llvm.exp2.f64",
58 "logf32" => "llvm.log.f32",
59 "logf64" => "llvm.log.f64",
60 "log10f32" => "llvm.log10.f32",
61 "log10f64" => "llvm.log10.f64",
62 "log2f32" => "llvm.log2.f32",
63 "log2f64" => "llvm.log2.f64",
64 "fmaf32" => "llvm.fma.f32",
65 "fmaf64" => "llvm.fma.f64",
66 "fabsf32" => "llvm.fabs.f32",
67 "fabsf64" => "llvm.fabs.f64",
68 "copysignf32" => "llvm.copysign.f32",
69 "copysignf64" => "llvm.copysign.f64",
70 "floorf32" => "llvm.floor.f32",
71 "floorf64" => "llvm.floor.f64",
72 "ceilf32" => "llvm.ceil.f32",
73 "ceilf64" => "llvm.ceil.f64",
74 "truncf32" => "llvm.trunc.f32",
75 "truncf64" => "llvm.trunc.f64",
76 "rintf32" => "llvm.rint.f32",
77 "rintf64" => "llvm.rint.f64",
78 "nearbyintf32" => "llvm.nearbyint.f32",
79 "nearbyintf64" => "llvm.nearbyint.f64",
80 "roundf32" => "llvm.round.f32",
81 "roundf64" => "llvm.round.f64",
82 "assume" => "llvm.assume",
83 "abort" => "llvm.trap",
86 Some(cx.get_intrinsic(&llvm_name))
89 impl IntrinsicCallMethods<'tcx> for Builder<'a, 'll, 'tcx> {
90 fn codegen_intrinsic_call(
93 fn_ty: &FnType<'tcx, Ty<'tcx>>,
94 args: &[OperandRef<'tcx, &'ll Value>],
101 let (def_id, substs) = match callee_ty.sty {
102 ty::FnDef(def_id, substs) => (def_id, substs),
103 _ => bug!("expected fn item type, found {}", callee_ty)
106 let sig = callee_ty.fn_sig(tcx);
107 let sig = tcx.normalize_erasing_late_bound_regions(ty::ParamEnv::reveal_all(), &sig);
108 let arg_tys = sig.inputs();
109 let ret_ty = sig.output();
110 let name = &*tcx.item_name(def_id).as_str();
112 let llret_ty = cx.layout_of(ret_ty).llvm_type(cx);
113 let result = PlaceRef::new_sized(llresult, fn_ty.ret.layout, fn_ty.ret.layout.align);
115 let simple = get_simple_intrinsic(cx, name);
116 let llval = match name {
117 _ if simple.is_some() => {
118 self.call(simple.unwrap(),
119 &args.iter().map(|arg| arg.immediate()).collect::<Vec<_>>(),
126 let expect = cx.get_intrinsic(&("llvm.expect.i1"));
127 self.call(expect, &[args[0].immediate(), cx.const_bool(true)], None)
130 let expect = cx.get_intrinsic(&("llvm.expect.i1"));
131 self.call(expect, &[args[0].immediate(), cx.const_bool(false)], None)
134 try_intrinsic(self, cx,
142 let llfn = cx.get_intrinsic(&("llvm.debugtrap"));
143 self.call(llfn, &[], None)
146 let tp_ty = substs.type_at(0);
147 cx.const_usize(cx.size_of(tp_ty).bytes())
150 let tp_ty = substs.type_at(0);
151 if let OperandValue::Pair(_, meta) = args[0].val {
153 glue::size_and_align_of_dst(self, tp_ty, Some(meta));
156 cx.const_usize(cx.size_of(tp_ty).bytes())
160 let tp_ty = substs.type_at(0);
161 cx.const_usize(cx.align_of(tp_ty).abi())
163 "min_align_of_val" => {
164 let tp_ty = substs.type_at(0);
165 if let OperandValue::Pair(_, meta) = args[0].val {
167 glue::size_and_align_of_dst(self, tp_ty, Some(meta));
170 cx.const_usize(cx.align_of(tp_ty).abi())
174 let tp_ty = substs.type_at(0);
175 cx.const_usize(cx.align_of(tp_ty).pref())
178 let tp_ty = substs.type_at(0);
179 let ty_name = Symbol::intern(&tp_ty.to_string()).as_str();
180 cx.const_str_slice(ty_name)
183 cx.const_u64(cx.tcx.type_id_hash(substs.type_at(0)))
186 let ty = substs.type_at(0);
187 if !cx.layout_of(ty).is_zst() {
188 // Just zero out the stack slot.
189 // If we store a zero constant, LLVM will drown in vreg allocation for large
190 // data structures, and the generated code will be awful. (A telltale sign of
191 // this is large quantities of `mov [byte ptr foo],0` in the generated code.)
203 // Effectively no-ops
204 "uninit" | "forget" => {
208 let tp_ty = substs.type_at(0);
210 cx.const_bool(cx.type_needs_drop(tp_ty))
213 let ptr = args[0].immediate();
214 let offset = args[1].immediate();
215 self.inbounds_gep(ptr, &[offset])
218 let ptr = args[0].immediate();
219 let offset = args[1].immediate();
220 self.gep(ptr, &[offset])
223 "copy_nonoverlapping" => {
224 copy_intrinsic(&self, false, false, substs.type_at(0),
225 args[1].immediate(), args[0].immediate(), args[2].immediate());
229 copy_intrinsic(&self, true, false, substs.type_at(0),
230 args[1].immediate(), args[0].immediate(), args[2].immediate());
234 memset_intrinsic(&self, false, substs.type_at(0),
235 args[0].immediate(), args[1].immediate(), args[2].immediate());
239 "volatile_copy_nonoverlapping_memory" => {
240 copy_intrinsic(&self, false, true, substs.type_at(0),
241 args[0].immediate(), args[1].immediate(), args[2].immediate());
244 "volatile_copy_memory" => {
245 copy_intrinsic(&self, true, true, substs.type_at(0),
246 args[0].immediate(), args[1].immediate(), args[2].immediate());
249 "volatile_set_memory" => {
250 memset_intrinsic(&self, true, substs.type_at(0),
251 args[0].immediate(), args[1].immediate(), args[2].immediate());
254 "volatile_load" | "unaligned_volatile_load" => {
255 let tp_ty = substs.type_at(0);
256 let mut ptr = args[0].immediate();
257 if let PassMode::Cast(ty) = fn_ty.ret.mode {
258 ptr = self.pointercast(ptr, cx.type_ptr_to(ty.llvm_type(cx)));
260 let load = self.volatile_load(ptr);
261 let align = if name == "unaligned_volatile_load" {
264 cx.align_of(tp_ty).abi() as u32
267 llvm::LLVMSetAlignment(load, align);
269 to_immediate(self, load, cx.layout_of(tp_ty))
271 "volatile_store" => {
272 let dst = args[0].deref(cx);
273 args[1].val.volatile_store(self, dst);
276 "unaligned_volatile_store" => {
277 let dst = args[0].deref(cx);
278 args[1].val.unaligned_volatile_store(self, dst);
281 "prefetch_read_data" | "prefetch_write_data" |
282 "prefetch_read_instruction" | "prefetch_write_instruction" => {
283 let expect = cx.get_intrinsic(&("llvm.prefetch"));
284 let (rw, cache_type) = match name {
285 "prefetch_read_data" => (0, 1),
286 "prefetch_write_data" => (1, 1),
287 "prefetch_read_instruction" => (0, 0),
288 "prefetch_write_instruction" => (1, 0),
295 cx.const_i32(cache_type)
298 "ctlz" | "ctlz_nonzero" | "cttz" | "cttz_nonzero" | "ctpop" | "bswap" |
299 "bitreverse" | "add_with_overflow" | "sub_with_overflow" |
300 "mul_with_overflow" | "overflowing_add" | "overflowing_sub" | "overflowing_mul" |
301 "unchecked_div" | "unchecked_rem" | "unchecked_shl" | "unchecked_shr" | "exact_div" |
302 "rotate_left" | "rotate_right" => {
304 match int_type_width_signed(ty, cx) {
305 Some((width, signed)) =>
308 let y = cx.const_bool(false);
309 let llfn = cx.get_intrinsic(&format!("llvm.{}.i{}", name, width));
310 self.call(llfn, &[args[0].immediate(), y], None)
312 "ctlz_nonzero" | "cttz_nonzero" => {
313 let y = cx.const_bool(true);
314 let llvm_name = &format!("llvm.{}.i{}", &name[..4], width);
315 let llfn = cx.get_intrinsic(llvm_name);
316 self.call(llfn, &[args[0].immediate(), y], None)
318 "ctpop" => self.call(
319 cx.get_intrinsic(&format!("llvm.ctpop.i{}", width)),
320 &[args[0].immediate()],
325 args[0].immediate() // byte swap a u8/i8 is just a no-op
327 self.call(cx.get_intrinsic(&format!("llvm.bswap.i{}", width)),
328 &[args[0].immediate()], None)
332 self.call(cx.get_intrinsic(&format!("llvm.bitreverse.i{}", width)),
333 &[args[0].immediate()], None)
335 "add_with_overflow" | "sub_with_overflow" | "mul_with_overflow" => {
336 let intrinsic = format!("llvm.{}{}.with.overflow.i{}",
337 if signed { 's' } else { 'u' },
339 let llfn = cx.get_intrinsic(&intrinsic);
341 // Convert `i1` to a `bool`, and write it to the out parameter
342 let pair = self.call(llfn, &[
346 let val = self.extract_value(pair, 0);
347 let overflow = self.zext(
348 self.extract_value(pair, 1),
352 let dest = result.project_field(self, 0);
353 self.store(val, dest.llval, dest.align);
354 let dest = result.project_field(self, 1);
355 self.store(overflow, dest.llval, dest.align);
359 "overflowing_add" => self.add(args[0].immediate(), args[1].immediate()),
360 "overflowing_sub" => self.sub(args[0].immediate(), args[1].immediate()),
361 "overflowing_mul" => self.mul(args[0].immediate(), args[1].immediate()),
364 self.exactsdiv(args[0].immediate(), args[1].immediate())
366 self.exactudiv(args[0].immediate(), args[1].immediate())
370 self.sdiv(args[0].immediate(), args[1].immediate())
372 self.udiv(args[0].immediate(), args[1].immediate())
376 self.srem(args[0].immediate(), args[1].immediate())
378 self.urem(args[0].immediate(), args[1].immediate())
380 "unchecked_shl" => self.shl(args[0].immediate(), args[1].immediate()),
383 self.ashr(args[0].immediate(), args[1].immediate())
385 self.lshr(args[0].immediate(), args[1].immediate())
387 "rotate_left" | "rotate_right" => {
388 let is_left = name == "rotate_left";
389 let val = args[0].immediate();
390 let raw_shift = args[1].immediate();
391 if llvm_util::get_major_version() >= 7 {
392 // rotate = funnel shift with first two args the same
393 let llvm_name = &format!("llvm.fsh{}.i{}",
394 if is_left { 'l' } else { 'r' }, width);
395 let llfn = cx.get_intrinsic(llvm_name);
396 self.call(llfn, &[val, val, raw_shift], None)
398 // rotate_left: (X << (S % BW)) | (X >> ((BW - S) % BW))
399 // rotate_right: (X << ((BW - S) % BW)) | (X >> (S % BW))
400 let width = cx.const_uint(cx.type_ix(width), width);
401 let shift = self.urem(raw_shift, width);
402 let inv_shift = self.urem(self.sub(width, raw_shift), width);
403 let shift1 = self.shl(
405 if is_left { shift } else { inv_shift },
407 let shift2 = self.lshr(
409 if !is_left { shift } else { inv_shift },
411 self.or(shift1, shift2)
417 span_invalid_monomorphization_error(
419 &format!("invalid monomorphization of `{}` intrinsic: \
420 expected basic integer type, found `{}`", name, ty));
426 "fadd_fast" | "fsub_fast" | "fmul_fast" | "fdiv_fast" | "frem_fast" => {
427 let sty = &arg_tys[0].sty;
428 match float_type_width(sty) {
431 "fadd_fast" => self.fadd_fast(args[0].immediate(), args[1].immediate()),
432 "fsub_fast" => self.fsub_fast(args[0].immediate(), args[1].immediate()),
433 "fmul_fast" => self.fmul_fast(args[0].immediate(), args[1].immediate()),
434 "fdiv_fast" => self.fdiv_fast(args[0].immediate(), args[1].immediate()),
435 "frem_fast" => self.frem_fast(args[0].immediate(), args[1].immediate()),
439 span_invalid_monomorphization_error(
441 &format!("invalid monomorphization of `{}` intrinsic: \
442 expected basic float type, found `{}`", name, sty));
449 "discriminant_value" => {
450 args[0].deref(cx).codegen_get_discr(self, ret_ty)
453 name if name.starts_with("simd_") => {
454 match generic_simd_intrinsic(&self, name,
463 // This requires that atomic intrinsics follow a specific naming pattern:
464 // "atomic_<operation>[_<ordering>]", and no ordering means SeqCst
465 name if name.starts_with("atomic_") => {
466 use self::AtomicOrdering::*;
468 let split: Vec<&str> = name.split('_').collect();
470 let is_cxchg = split[1] == "cxchg" || split[1] == "cxchgweak";
471 let (order, failorder) = match split.len() {
472 2 => (SequentiallyConsistent, SequentiallyConsistent),
473 3 => match split[2] {
474 "unordered" => (Unordered, Unordered),
475 "relaxed" => (Monotonic, Monotonic),
476 "acq" => (Acquire, Acquire),
477 "rel" => (Release, Monotonic),
478 "acqrel" => (AcquireRelease, Acquire),
479 "failrelaxed" if is_cxchg =>
480 (SequentiallyConsistent, Monotonic),
481 "failacq" if is_cxchg =>
482 (SequentiallyConsistent, Acquire),
483 _ => cx.sess().fatal("unknown ordering in atomic intrinsic")
485 4 => match (split[2], split[3]) {
486 ("acq", "failrelaxed") if is_cxchg =>
487 (Acquire, Monotonic),
488 ("acqrel", "failrelaxed") if is_cxchg =>
489 (AcquireRelease, Monotonic),
490 _ => cx.sess().fatal("unknown ordering in atomic intrinsic")
492 _ => cx.sess().fatal("Atomic intrinsic not in correct format"),
495 let invalid_monomorphization = |ty| {
496 span_invalid_monomorphization_error(tcx.sess, span,
497 &format!("invalid monomorphization of `{}` intrinsic: \
498 expected basic integer type, found `{}`", name, ty));
502 "cxchg" | "cxchgweak" => {
503 let ty = substs.type_at(0);
504 if int_type_width_signed(ty, cx).is_some() {
505 let weak = split[1] == "cxchgweak";
506 let pair = self.atomic_cmpxchg(
513 let val = self.extract_value(pair, 0);
514 let success = self.zext(
515 self.extract_value(pair, 1),
519 let dest = result.project_field(self, 0);
520 self.store(val, dest.llval, dest.align);
521 let dest = result.project_field(self, 1);
522 self.store(success, dest.llval, dest.align);
525 return invalid_monomorphization(ty);
530 let ty = substs.type_at(0);
531 if int_type_width_signed(ty, cx).is_some() {
532 let size = cx.size_of(ty);
533 self.atomic_load(args[0].immediate(), order, size)
535 return invalid_monomorphization(ty);
540 let ty = substs.type_at(0);
541 if int_type_width_signed(ty, cx).is_some() {
542 let size = cx.size_of(ty);
551 return invalid_monomorphization(ty);
556 self.atomic_fence(order, SynchronizationScope::CrossThread);
560 "singlethreadfence" => {
561 self.atomic_fence(order, SynchronizationScope::SingleThread);
565 // These are all AtomicRMW ops
567 let atom_op = match op {
568 "xchg" => AtomicRmwBinOp::AtomicXchg,
569 "xadd" => AtomicRmwBinOp::AtomicAdd,
570 "xsub" => AtomicRmwBinOp::AtomicSub,
571 "and" => AtomicRmwBinOp::AtomicAnd,
572 "nand" => AtomicRmwBinOp::AtomicNand,
573 "or" => AtomicRmwBinOp::AtomicOr,
574 "xor" => AtomicRmwBinOp::AtomicXor,
575 "max" => AtomicRmwBinOp::AtomicMax,
576 "min" => AtomicRmwBinOp::AtomicMin,
577 "umax" => AtomicRmwBinOp::AtomicUMax,
578 "umin" => AtomicRmwBinOp::AtomicUMin,
579 _ => cx.sess().fatal("unknown atomic operation")
582 let ty = substs.type_at(0);
583 if int_type_width_signed(ty, cx).is_some() {
591 return invalid_monomorphization(ty);
597 "nontemporal_store" => {
598 let dst = args[0].deref(cx);
599 args[1].val.nontemporal_store(self, dst);
604 let intr = match Intrinsic::find(&name) {
606 None => bug!("unknown intrinsic '{}'", name),
608 fn one<T>(x: Vec<T>) -> T {
609 assert_eq!(x.len(), 1);
610 x.into_iter().next().unwrap()
613 cx: &CodegenCx<'ll, '_>,
615 ) -> Vec<&'ll Type> {
616 use intrinsics::Type::*;
618 Void => vec![cx.type_void()],
619 Integer(_signed, _width, llvm_width) => {
620 vec![cx.type_ix( llvm_width as u64)]
624 32 => vec![cx.type_f32()],
625 64 => vec![cx.type_f64()],
629 Pointer(ref t, ref llvm_elem, _const) => {
630 let t = llvm_elem.as_ref().unwrap_or(t);
631 let elem = one(ty_to_type(cx, t));
632 vec![cx.type_ptr_to(elem)]
634 Vector(ref t, ref llvm_elem, length) => {
635 let t = llvm_elem.as_ref().unwrap_or(t);
636 let elem = one(ty_to_type(cx, t));
637 vec![cx.type_vector(elem, length as u64)]
639 Aggregate(false, ref contents) => {
640 let elems = contents.iter()
641 .map(|t| one(ty_to_type(cx, t)))
642 .collect::<Vec<_>>();
643 vec![cx.type_struct( &elems, false)]
645 Aggregate(true, ref contents) => {
647 .flat_map(|t| ty_to_type(cx, t))
653 // This allows an argument list like `foo, (bar, baz),
654 // qux` to be converted into `foo, bar, baz, qux`, integer
655 // arguments to be truncated as needed and pointers to be
657 fn modify_as_needed<'ll, 'tcx>(
658 bx: &Builder<'_, 'll, 'tcx>,
659 t: &intrinsics::Type,
660 arg: &OperandRef<'tcx, &'ll Value>,
661 ) -> Vec<&'ll Value> {
663 intrinsics::Type::Aggregate(true, ref contents) => {
664 // We found a tuple that needs squishing! So
665 // run over the tuple and load each field.
667 // This assumes the type is "simple", i.e. no
668 // destructors, and the contents are SIMD
670 assert!(!bx.cx().type_needs_drop(arg.layout.ty));
671 let (ptr, align) = match arg.val {
672 OperandValue::Ref(ptr, None, align) => (ptr, align),
675 let arg = PlaceRef::new_sized(ptr, arg.layout, align);
676 (0..contents.len()).map(|i| {
677 bx.load_operand(arg.project_field(bx, i)).immediate()
680 intrinsics::Type::Pointer(_, Some(ref llvm_elem), _) => {
681 let llvm_elem = one(ty_to_type(bx.cx(), llvm_elem));
682 vec![bx.pointercast(arg.immediate(), bx.cx().type_ptr_to(llvm_elem))]
684 intrinsics::Type::Vector(_, Some(ref llvm_elem), length) => {
685 let llvm_elem = one(ty_to_type(bx.cx(), llvm_elem));
687 bx.bitcast(arg.immediate(),
688 bx.cx().type_vector(llvm_elem, length as u64))
691 intrinsics::Type::Integer(_, width, llvm_width) if width != llvm_width => {
692 // the LLVM intrinsic uses a smaller integer
693 // size than the C intrinsic's signature, so
694 // we have to trim it down here.
695 vec![bx.trunc(arg.immediate(), bx.cx().type_ix(llvm_width as u64))]
697 _ => vec![arg.immediate()],
702 let inputs = intr.inputs.iter()
703 .flat_map(|t| ty_to_type(cx, t))
704 .collect::<Vec<_>>();
706 let outputs = one(ty_to_type(cx, &intr.output));
708 let llargs: Vec<_> = intr.inputs.iter().zip(args).flat_map(|(t, arg)| {
709 modify_as_needed(&self, t, arg)
711 assert_eq!(inputs.len(), llargs.len());
713 let val = match intr.definition {
714 intrinsics::IntrinsicDef::Named(name) => {
715 let f = cx.declare_cfn(
717 cx.type_func(&inputs, outputs),
719 self.call(f, &llargs, None)
724 intrinsics::Type::Aggregate(flatten, ref elems) => {
725 // the output is a tuple so we need to munge it properly
728 for i in 0..elems.len() {
729 let dest = result.project_field(self, i);
730 let val = self.extract_value(val, i as u64);
731 self.store(val, dest.llval, dest.align);
740 if !fn_ty.ret.is_ignore() {
741 if let PassMode::Cast(ty) = fn_ty.ret.mode {
742 let ptr = self.pointercast(result.llval, cx.type_ptr_to(ty.llvm_type(cx)));
743 self.store(llval, ptr, result.align);
745 OperandRef::from_immediate_or_packed_pair(self, llval, result.layout)
746 .val.store(self, result);
753 bx: &Builder<'a, 'll, 'tcx>,
761 let (size, align) = bx.cx().size_and_align_of(ty);
762 let size = bx.mul(bx.cx().const_usize(size.bytes()), count);
763 let flags = if volatile {
769 bx.memmove(dst, align, src, align, size, flags);
771 bx.memcpy(dst, align, src, align, size, flags);
776 bx: &Builder<'a, 'll, 'tcx>,
783 let (size, align) = bx.cx().size_and_align_of(ty);
784 let size = bx.cx().const_usize(size.bytes());
785 let flags = if volatile {
790 bx.memset(dst, val, bx.mul(size, count), align, flags);
794 bx: &Builder<'a, 'll, 'tcx>,
795 cx: &CodegenCx<'ll, 'tcx>,
798 local_ptr: &'ll Value,
801 if bx.cx().sess().no_landing_pads() {
802 bx.call(func, &[data], None);
803 let ptr_align = bx.tcx().data_layout.pointer_align;
804 bx.store(cx.const_null(cx.type_i8p()), dest, ptr_align);
805 } else if wants_msvc_seh(bx.cx().sess()) {
806 codegen_msvc_try(bx, cx, func, data, local_ptr, dest);
808 codegen_gnu_try(bx, cx, func, data, local_ptr, dest);
812 // MSVC's definition of the `rust_try` function.
814 // This implementation uses the new exception handling instructions in LLVM
815 // which have support in LLVM for SEH on MSVC targets. Although these
816 // instructions are meant to work for all targets, as of the time of this
817 // writing, however, LLVM does not recommend the usage of these new instructions
818 // as the old ones are still more optimized.
820 bx: &Builder<'a, 'll, 'tcx>,
821 cx: &CodegenCx<'ll, 'tcx>,
824 local_ptr: &'ll Value,
827 let llfn = get_rust_try_fn(cx, &mut |bx| {
830 bx.set_personality_fn(bx.cx().eh_personality());
832 let normal = bx.build_sibling_block("normal");
833 let catchswitch = bx.build_sibling_block("catchswitch");
834 let catchpad = bx.build_sibling_block("catchpad");
835 let caught = bx.build_sibling_block("caught");
837 let func = llvm::get_param(bx.llfn(), 0);
838 let data = llvm::get_param(bx.llfn(), 1);
839 let local_ptr = llvm::get_param(bx.llfn(), 2);
841 // We're generating an IR snippet that looks like:
843 // declare i32 @rust_try(%func, %data, %ptr) {
844 // %slot = alloca i64*
845 // invoke %func(%data) to label %normal unwind label %catchswitch
851 // %cs = catchswitch within none [%catchpad] unwind to caller
854 // %tok = catchpad within %cs [%type_descriptor, 0, %slot]
855 // %ptr[0] = %slot[0]
856 // %ptr[1] = %slot[1]
857 // catchret from %tok to label %caught
863 // This structure follows the basic usage of throw/try/catch in LLVM.
864 // For example, compile this C++ snippet to see what LLVM generates:
866 // #include <stdint.h>
868 // int bar(void (*foo)(void), uint64_t *ret) {
872 // } catch(uint64_t a[2]) {
879 // More information can be found in libstd's seh.rs implementation.
880 let i64p = cx.type_ptr_to(cx.type_i64());
881 let ptr_align = bx.tcx().data_layout.pointer_align;
882 let slot = bx.alloca(i64p, "slot", ptr_align);
883 bx.invoke(func, &[data], normal.llbb(), catchswitch.llbb(), None);
885 normal.ret(cx.const_i32(0));
887 let cs = catchswitch.catch_switch(None, None, 1);
888 catchswitch.add_handler(cs, catchpad.llbb());
891 let tydesc = match tcx.lang_items().msvc_try_filter() {
892 Some(did) => cx.get_static(did),
893 None => bug!("msvc_try_filter not defined"),
895 let tok = catchpad.catch_pad(cs, &[tydesc, cx.const_i32(0), slot]);
896 let addr = catchpad.load(slot, ptr_align);
898 let i64_align = bx.tcx().data_layout.i64_align;
899 let arg1 = catchpad.load(addr, i64_align);
900 let val1 = cx.const_i32(1);
901 let arg2 = catchpad.load(catchpad.inbounds_gep(addr, &[val1]), i64_align);
902 let local_ptr = catchpad.bitcast(local_ptr, i64p);
903 catchpad.store(arg1, local_ptr, i64_align);
904 catchpad.store(arg2, catchpad.inbounds_gep(local_ptr, &[val1]), i64_align);
905 catchpad.catch_ret(tok, caught.llbb());
907 caught.ret(cx.const_i32(1));
910 // Note that no invoke is used here because by definition this function
911 // can't panic (that's what it's catching).
912 let ret = bx.call(llfn, &[func, data, local_ptr], None);
913 let i32_align = bx.tcx().data_layout.i32_align;
914 bx.store(ret, dest, i32_align);
917 // Definition of the standard "try" function for Rust using the GNU-like model
918 // of exceptions (e.g. the normal semantics of LLVM's landingpad and invoke
921 // This codegen is a little surprising because we always call a shim
922 // function instead of inlining the call to `invoke` manually here. This is done
923 // because in LLVM we're only allowed to have one personality per function
924 // definition. The call to the `try` intrinsic is being inlined into the
925 // function calling it, and that function may already have other personality
926 // functions in play. By calling a shim we're guaranteed that our shim will have
927 // the right personality function.
929 bx: &Builder<'a, 'll, 'tcx>,
930 cx: &CodegenCx<'ll, 'tcx>,
933 local_ptr: &'ll Value,
936 let llfn = get_rust_try_fn(cx, &mut |bx| {
939 // Codegens the shims described above:
942 // invoke %func(%args...) normal %normal unwind %catch
948 // (ptr, _) = landingpad
949 // store ptr, %local_ptr
952 // Note that the `local_ptr` data passed into the `try` intrinsic is
953 // expected to be `*mut *mut u8` for this to actually work, but that's
954 // managed by the standard library.
956 let then = bx.build_sibling_block("then");
957 let catch = bx.build_sibling_block("catch");
959 let func = llvm::get_param(bx.llfn(), 0);
960 let data = llvm::get_param(bx.llfn(), 1);
961 let local_ptr = llvm::get_param(bx.llfn(), 2);
962 bx.invoke(func, &[data], then.llbb(), catch.llbb(), None);
963 then.ret(cx.const_i32(0));
965 // Type indicator for the exception being thrown.
967 // The first value in this tuple is a pointer to the exception object
968 // being thrown. The second value is a "selector" indicating which of
969 // the landing pad clauses the exception's type had been matched to.
970 // rust_try ignores the selector.
971 let lpad_ty = cx.type_struct(&[cx.type_i8p(), cx.type_i32()], false);
972 let vals = catch.landing_pad(lpad_ty, bx.cx().eh_personality(), 1);
973 catch.add_clause(vals, bx.cx().const_null(cx.type_i8p()));
974 let ptr = catch.extract_value(vals, 0);
975 let ptr_align = bx.tcx().data_layout.pointer_align;
976 catch.store(ptr, catch.bitcast(local_ptr, cx.type_ptr_to(cx.type_i8p())), ptr_align);
977 catch.ret(cx.const_i32(1));
980 // Note that no invoke is used here because by definition this function
981 // can't panic (that's what it's catching).
982 let ret = bx.call(llfn, &[func, data, local_ptr], None);
983 let i32_align = bx.tcx().data_layout.i32_align;
984 bx.store(ret, dest, i32_align);
987 // Helper function to give a Block to a closure to codegen a shim function.
988 // This is currently primarily used for the `try` intrinsic functions above.
989 fn gen_fn<'ll, 'tcx>(
990 cx: &CodegenCx<'ll, 'tcx>,
992 inputs: Vec<Ty<'tcx>>,
994 codegen: &mut dyn FnMut(Builder<'_, 'll, 'tcx>),
996 let rust_fn_sig = ty::Binder::bind(cx.tcx.mk_fn_sig(
1000 hir::Unsafety::Unsafe,
1003 let llfn = cx.define_internal_fn(name, rust_fn_sig);
1004 attributes::from_fn_attrs(cx, llfn, None);
1005 let bx = Builder::new_block(cx, llfn, "entry-block");
1010 // Helper function used to get a handle to the `__rust_try` function used to
1011 // catch exceptions.
1013 // This function is only generated once and is then cached.
1014 fn get_rust_try_fn<'ll, 'tcx>(
1015 cx: &CodegenCx<'ll, 'tcx>,
1016 codegen: &mut dyn FnMut(Builder<'_, 'll, 'tcx>),
1018 if let Some(llfn) = cx.rust_try_fn.get() {
1022 // Define the type up front for the signature of the rust_try function.
1024 let i8p = tcx.mk_mut_ptr(tcx.types.i8);
1025 let fn_ty = tcx.mk_fn_ptr(ty::Binder::bind(tcx.mk_fn_sig(
1029 hir::Unsafety::Unsafe,
1032 let output = tcx.types.i32;
1033 let rust_try = gen_fn(cx, "__rust_try", vec![fn_ty, i8p, i8p], output, codegen);
1034 cx.rust_try_fn.set(Some(rust_try));
1038 fn span_invalid_monomorphization_error(a: &Session, b: Span, c: &str) {
1039 span_err!(a, b, E0511, "{}", c);
1042 fn generic_simd_intrinsic(
1043 bx: &Builder<'a, 'll, 'tcx>,
1045 callee_ty: Ty<'tcx>,
1046 args: &[OperandRef<'tcx, &'ll Value>],
1048 llret_ty: &'ll Type,
1050 ) -> Result<&'ll Value, ()> {
1051 // macros for error handling:
1052 macro_rules! emit_error {
1056 ($msg: tt, $($fmt: tt)*) => {
1057 span_invalid_monomorphization_error(
1058 bx.cx().sess(), span,
1059 &format!(concat!("invalid monomorphization of `{}` intrinsic: ", $msg),
1064 macro_rules! return_error {
1067 emit_error!($($fmt)*);
1073 macro_rules! require {
1074 ($cond: expr, $($fmt: tt)*) => {
1076 return_error!($($fmt)*);
1081 macro_rules! require_simd {
1082 ($ty: expr, $position: expr) => {
1083 require!($ty.is_simd(), "expected SIMD {} type, found non-SIMD `{}`", $position, $ty)
1088 let sig = tcx.normalize_erasing_late_bound_regions(
1089 ty::ParamEnv::reveal_all(),
1090 &callee_ty.fn_sig(tcx),
1092 let arg_tys = sig.inputs();
1094 // every intrinsic takes a SIMD vector as its first argument
1095 require_simd!(arg_tys[0], "input");
1096 let in_ty = arg_tys[0];
1097 let in_elem = arg_tys[0].simd_type(tcx);
1098 let in_len = arg_tys[0].simd_size(tcx);
1100 let comparison = match name {
1101 "simd_eq" => Some(hir::BinOpKind::Eq),
1102 "simd_ne" => Some(hir::BinOpKind::Ne),
1103 "simd_lt" => Some(hir::BinOpKind::Lt),
1104 "simd_le" => Some(hir::BinOpKind::Le),
1105 "simd_gt" => Some(hir::BinOpKind::Gt),
1106 "simd_ge" => Some(hir::BinOpKind::Ge),
1110 if let Some(cmp_op) = comparison {
1111 require_simd!(ret_ty, "return");
1113 let out_len = ret_ty.simd_size(tcx);
1114 require!(in_len == out_len,
1115 "expected return type with length {} (same as input type `{}`), \
1116 found `{}` with length {}",
1119 require!(bx.cx().type_kind(bx.cx().element_type(llret_ty)) == TypeKind::Integer,
1120 "expected return type with integer elements, found `{}` with non-integer `{}`",
1122 ret_ty.simd_type(tcx));
1124 return Ok(compare_simd_types(bx,
1125 args[0].immediate(),
1126 args[1].immediate(),
1132 if name.starts_with("simd_shuffle") {
1133 let n: usize = name["simd_shuffle".len()..].parse().unwrap_or_else(|_|
1134 span_bug!(span, "bad `simd_shuffle` instruction only caught in codegen?"));
1136 require_simd!(ret_ty, "return");
1138 let out_len = ret_ty.simd_size(tcx);
1139 require!(out_len == n,
1140 "expected return type of length {}, found `{}` with length {}",
1141 n, ret_ty, out_len);
1142 require!(in_elem == ret_ty.simd_type(tcx),
1143 "expected return element type `{}` (element of input `{}`), \
1144 found `{}` with element type `{}`",
1146 ret_ty, ret_ty.simd_type(tcx));
1148 let total_len = in_len as u128 * 2;
1150 let vector = args[2].immediate();
1152 let indices: Option<Vec<_>> = (0..n)
1155 let val = bx.cx().const_get_elt(vector, i as u64);
1156 match bx.cx().const_to_opt_u128(val, true) {
1158 emit_error!("shuffle index #{} is not a constant", arg_idx);
1161 Some(idx) if idx >= total_len => {
1162 emit_error!("shuffle index #{} is out of bounds (limit {})",
1163 arg_idx, total_len);
1166 Some(idx) => Some(bx.cx().const_i32(idx as i32)),
1170 let indices = match indices {
1172 None => return Ok(bx.cx().const_null(llret_ty))
1175 return Ok(bx.shuffle_vector(args[0].immediate(),
1176 args[1].immediate(),
1177 bx.cx().const_vector(&indices)))
1180 if name == "simd_insert" {
1181 require!(in_elem == arg_tys[2],
1182 "expected inserted type `{}` (element of input `{}`), found `{}`",
1183 in_elem, in_ty, arg_tys[2]);
1184 return Ok(bx.insert_element(args[0].immediate(),
1185 args[2].immediate(),
1186 args[1].immediate()))
1188 if name == "simd_extract" {
1189 require!(ret_ty == in_elem,
1190 "expected return type `{}` (element of input `{}`), found `{}`",
1191 in_elem, in_ty, ret_ty);
1192 return Ok(bx.extract_element(args[0].immediate(), args[1].immediate()))
1195 if name == "simd_select" {
1196 let m_elem_ty = in_elem;
1198 let v_len = arg_tys[1].simd_size(tcx);
1199 require!(m_len == v_len,
1200 "mismatched lengths: mask length `{}` != other vector length `{}`",
1203 match m_elem_ty.sty {
1205 _ => return_error!("mask element type is `{}`, expected `i_`", m_elem_ty)
1207 // truncate the mask to a vector of i1s
1208 let i1 = bx.cx().type_i1();
1209 let i1xn = bx.cx().type_vector(i1, m_len as u64);
1210 let m_i1s = bx.trunc(args[0].immediate(), i1xn);
1211 return Ok(bx.select(m_i1s, args[1].immediate(), args[2].immediate()));
1214 fn simd_simple_float_intrinsic(
1216 in_elem: &::rustc::ty::TyS,
1217 in_ty: &::rustc::ty::TyS,
1219 bx: &Builder<'a, 'll, 'tcx>,
1221 args: &[OperandRef<'tcx, &'ll Value>],
1222 ) -> Result<&'ll Value, ()> {
1223 macro_rules! emit_error {
1227 ($msg: tt, $($fmt: tt)*) => {
1228 span_invalid_monomorphization_error(
1229 bx.cx().sess(), span,
1230 &format!(concat!("invalid monomorphization of `{}` intrinsic: ", $msg),
1234 macro_rules! return_error {
1237 emit_error!($($fmt)*);
1242 let ety = match in_elem.sty {
1243 ty::Float(f) if f.bit_width() == 32 => {
1244 if in_len < 2 || in_len > 16 {
1246 "unsupported floating-point vector `{}` with length `{}` \
1247 out-of-range [2, 16]",
1252 ty::Float(f) if f.bit_width() == 64 => {
1253 if in_len < 2 || in_len > 8 {
1254 return_error!("unsupported floating-point vector `{}` with length `{}` \
1255 out-of-range [2, 8]",
1261 return_error!("unsupported element type `{}` of floating-point vector `{}`",
1265 return_error!("`{}` is not a floating-point type", in_ty);
1269 let llvm_name = &format!("llvm.{0}.v{1}{2}", name, in_len, ety);
1270 let intrinsic = bx.cx().get_intrinsic(&llvm_name);
1271 let c = bx.call(intrinsic,
1272 &args.iter().map(|arg| arg.immediate()).collect::<Vec<_>>(),
1274 unsafe { llvm::LLVMRustSetHasUnsafeAlgebra(c) };
1280 return simd_simple_float_intrinsic("sqrt", in_elem, in_ty, in_len, bx, span, args);
1283 return simd_simple_float_intrinsic("sin", in_elem, in_ty, in_len, bx, span, args);
1286 return simd_simple_float_intrinsic("cos", in_elem, in_ty, in_len, bx, span, args);
1289 return simd_simple_float_intrinsic("fabs", in_elem, in_ty, in_len, bx, span, args);
1292 return simd_simple_float_intrinsic("floor", in_elem, in_ty, in_len, bx, span, args);
1295 return simd_simple_float_intrinsic("ceil", in_elem, in_ty, in_len, bx, span, args);
1298 return simd_simple_float_intrinsic("exp", in_elem, in_ty, in_len, bx, span, args);
1301 return simd_simple_float_intrinsic("exp2", in_elem, in_ty, in_len, bx, span, args);
1304 return simd_simple_float_intrinsic("log10", in_elem, in_ty, in_len, bx, span, args);
1307 return simd_simple_float_intrinsic("log2", in_elem, in_ty, in_len, bx, span, args);
1310 return simd_simple_float_intrinsic("log", in_elem, in_ty, in_len, bx, span, args);
1313 return simd_simple_float_intrinsic("powi", in_elem, in_ty, in_len, bx, span, args);
1316 return simd_simple_float_intrinsic("pow", in_elem, in_ty, in_len, bx, span, args);
1319 return simd_simple_float_intrinsic("fma", in_elem, in_ty, in_len, bx, span, args);
1321 _ => { /* fallthrough */ }
1325 // https://github.com/llvm-mirror/llvm/blob/master/include/llvm/IR/Function.h#L182
1326 // https://github.com/llvm-mirror/llvm/blob/master/include/llvm/IR/Intrinsics.h#L81
1327 fn llvm_vector_str(elem_ty: ty::Ty, vec_len: usize, no_pointers: usize) -> String {
1328 let p0s: String = "p0".repeat(no_pointers);
1330 ty::Int(v) => format!("v{}{}i{}", vec_len, p0s, v.bit_width().unwrap()),
1331 ty::Uint(v) => format!("v{}{}i{}", vec_len, p0s, v.bit_width().unwrap()),
1332 ty::Float(v) => format!("v{}{}f{}", vec_len, p0s, v.bit_width()),
1333 _ => unreachable!(),
1337 fn llvm_vector_ty(cx: &CodegenCx<'ll, '_>, elem_ty: ty::Ty, vec_len: usize,
1338 mut no_pointers: usize) -> &'ll Type {
1339 // FIXME: use cx.layout_of(ty).llvm_type() ?
1340 let mut elem_ty = match elem_ty.sty {
1341 ty::Int(v) => cx.type_int_from_ty( v),
1342 ty::Uint(v) => cx.type_uint_from_ty( v),
1343 ty::Float(v) => cx.type_float_from_ty( v),
1344 _ => unreachable!(),
1346 while no_pointers > 0 {
1347 elem_ty = cx.type_ptr_to(elem_ty);
1350 cx.type_vector(elem_ty, vec_len as u64)
1354 if name == "simd_gather" {
1355 // simd_gather(values: <N x T>, pointers: <N x *_ T>,
1356 // mask: <N x i{M}>) -> <N x T>
1357 // * N: number of elements in the input vectors
1358 // * T: type of the element to load
1359 // * M: any integer width is supported, will be truncated to i1
1361 // All types must be simd vector types
1362 require_simd!(in_ty, "first");
1363 require_simd!(arg_tys[1], "second");
1364 require_simd!(arg_tys[2], "third");
1365 require_simd!(ret_ty, "return");
1367 // Of the same length:
1368 require!(in_len == arg_tys[1].simd_size(tcx),
1369 "expected {} argument with length {} (same as input type `{}`), \
1370 found `{}` with length {}", "second", in_len, in_ty, arg_tys[1],
1371 arg_tys[1].simd_size(tcx));
1372 require!(in_len == arg_tys[2].simd_size(tcx),
1373 "expected {} argument with length {} (same as input type `{}`), \
1374 found `{}` with length {}", "third", in_len, in_ty, arg_tys[2],
1375 arg_tys[2].simd_size(tcx));
1377 // The return type must match the first argument type
1378 require!(ret_ty == in_ty,
1379 "expected return type `{}`, found `{}`",
1382 // This counts how many pointers
1383 fn ptr_count(t: ty::Ty) -> usize {
1385 ty::RawPtr(p) => 1 + ptr_count(p.ty),
1391 fn non_ptr(t: ty::Ty) -> ty::Ty {
1393 ty::RawPtr(p) => non_ptr(p.ty),
1398 // The second argument must be a simd vector with an element type that's a pointer
1399 // to the element type of the first argument
1400 let (pointer_count, underlying_ty) = match arg_tys[1].simd_type(tcx).sty {
1401 ty::RawPtr(p) if p.ty == in_elem => (ptr_count(arg_tys[1].simd_type(tcx)),
1402 non_ptr(arg_tys[1].simd_type(tcx))),
1404 require!(false, "expected element type `{}` of second argument `{}` \
1405 to be a pointer to the element type `{}` of the first \
1406 argument `{}`, found `{}` != `*_ {}`",
1407 arg_tys[1].simd_type(tcx).sty, arg_tys[1], in_elem, in_ty,
1408 arg_tys[1].simd_type(tcx).sty, in_elem);
1412 assert!(pointer_count > 0);
1413 assert_eq!(pointer_count - 1, ptr_count(arg_tys[0].simd_type(tcx)));
1414 assert_eq!(underlying_ty, non_ptr(arg_tys[0].simd_type(tcx)));
1416 // The element type of the third argument must be a signed integer type of any width:
1417 match arg_tys[2].simd_type(tcx).sty {
1420 require!(false, "expected element type `{}` of third argument `{}` \
1421 to be a signed integer type",
1422 arg_tys[2].simd_type(tcx).sty, arg_tys[2]);
1426 // Alignment of T, must be a constant integer value:
1427 let alignment_ty = bx.cx().type_i32();
1428 let alignment = bx.cx().const_i32(bx.cx().align_of(in_elem).abi() as i32);
1430 // Truncate the mask vector to a vector of i1s:
1431 let (mask, mask_ty) = {
1432 let i1 = bx.cx().type_i1();
1433 let i1xn = bx.cx().type_vector(i1, in_len as u64);
1434 (bx.trunc(args[2].immediate(), i1xn), i1xn)
1437 // Type of the vector of pointers:
1438 let llvm_pointer_vec_ty = llvm_vector_ty(bx.cx(), underlying_ty, in_len, pointer_count);
1439 let llvm_pointer_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count);
1441 // Type of the vector of elements:
1442 let llvm_elem_vec_ty = llvm_vector_ty(bx.cx(), underlying_ty, in_len, pointer_count - 1);
1443 let llvm_elem_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count - 1);
1445 let llvm_intrinsic = format!("llvm.masked.gather.{}.{}",
1446 llvm_elem_vec_str, llvm_pointer_vec_str);
1447 let f = bx.cx().declare_cfn(&llvm_intrinsic,
1448 bx.cx().type_func(&[
1449 llvm_pointer_vec_ty,
1452 llvm_elem_vec_ty], llvm_elem_vec_ty));
1453 llvm::SetUnnamedAddr(f, false);
1454 let v = bx.call(f, &[args[1].immediate(), alignment, mask, args[0].immediate()],
1459 if name == "simd_scatter" {
1460 // simd_scatter(values: <N x T>, pointers: <N x *mut T>,
1461 // mask: <N x i{M}>) -> ()
1462 // * N: number of elements in the input vectors
1463 // * T: type of the element to load
1464 // * M: any integer width is supported, will be truncated to i1
1466 // All types must be simd vector types
1467 require_simd!(in_ty, "first");
1468 require_simd!(arg_tys[1], "second");
1469 require_simd!(arg_tys[2], "third");
1471 // Of the same length:
1472 require!(in_len == arg_tys[1].simd_size(tcx),
1473 "expected {} argument with length {} (same as input type `{}`), \
1474 found `{}` with length {}", "second", in_len, in_ty, arg_tys[1],
1475 arg_tys[1].simd_size(tcx));
1476 require!(in_len == arg_tys[2].simd_size(tcx),
1477 "expected {} argument with length {} (same as input type `{}`), \
1478 found `{}` with length {}", "third", in_len, in_ty, arg_tys[2],
1479 arg_tys[2].simd_size(tcx));
1481 // This counts how many pointers
1482 fn ptr_count(t: ty::Ty) -> usize {
1484 ty::RawPtr(p) => 1 + ptr_count(p.ty),
1490 fn non_ptr(t: ty::Ty) -> ty::Ty {
1492 ty::RawPtr(p) => non_ptr(p.ty),
1497 // The second argument must be a simd vector with an element type that's a pointer
1498 // to the element type of the first argument
1499 let (pointer_count, underlying_ty) = match arg_tys[1].simd_type(tcx).sty {
1500 ty::RawPtr(p) if p.ty == in_elem && p.mutbl == hir::MutMutable
1501 => (ptr_count(arg_tys[1].simd_type(tcx)),
1502 non_ptr(arg_tys[1].simd_type(tcx))),
1504 require!(false, "expected element type `{}` of second argument `{}` \
1505 to be a pointer to the element type `{}` of the first \
1506 argument `{}`, found `{}` != `*mut {}`",
1507 arg_tys[1].simd_type(tcx).sty, arg_tys[1], in_elem, in_ty,
1508 arg_tys[1].simd_type(tcx).sty, in_elem);
1512 assert!(pointer_count > 0);
1513 assert_eq!(pointer_count - 1, ptr_count(arg_tys[0].simd_type(tcx)));
1514 assert_eq!(underlying_ty, non_ptr(arg_tys[0].simd_type(tcx)));
1516 // The element type of the third argument must be a signed integer type of any width:
1517 match arg_tys[2].simd_type(tcx).sty {
1520 require!(false, "expected element type `{}` of third argument `{}` \
1521 to be a signed integer type",
1522 arg_tys[2].simd_type(tcx).sty, arg_tys[2]);
1526 // Alignment of T, must be a constant integer value:
1527 let alignment_ty = bx.cx().type_i32();
1528 let alignment = bx.cx().const_i32(bx.cx().align_of(in_elem).abi() as i32);
1530 // Truncate the mask vector to a vector of i1s:
1531 let (mask, mask_ty) = {
1532 let i1 = bx.cx().type_i1();
1533 let i1xn = bx.cx().type_vector(i1, in_len as u64);
1534 (bx.trunc(args[2].immediate(), i1xn), i1xn)
1537 let ret_t = bx.cx().type_void();
1539 // Type of the vector of pointers:
1540 let llvm_pointer_vec_ty = llvm_vector_ty(bx.cx(), underlying_ty, in_len, pointer_count);
1541 let llvm_pointer_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count);
1543 // Type of the vector of elements:
1544 let llvm_elem_vec_ty = llvm_vector_ty(bx.cx(), underlying_ty, in_len, pointer_count - 1);
1545 let llvm_elem_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count - 1);
1547 let llvm_intrinsic = format!("llvm.masked.scatter.{}.{}",
1548 llvm_elem_vec_str, llvm_pointer_vec_str);
1549 let f = bx.cx().declare_cfn(&llvm_intrinsic,
1550 bx.cx().type_func(&[llvm_elem_vec_ty,
1551 llvm_pointer_vec_ty,
1554 llvm::SetUnnamedAddr(f, false);
1555 let v = bx.call(f, &[args[0].immediate(), args[1].immediate(), alignment, mask],
1560 macro_rules! arith_red {
1561 ($name:tt : $integer_reduce:ident, $float_reduce:ident, $ordered:expr) => {
1563 require!(ret_ty == in_elem,
1564 "expected return type `{}` (element of input `{}`), found `{}`",
1565 in_elem, in_ty, ret_ty);
1566 return match in_elem.sty {
1567 ty::Int(_) | ty::Uint(_) => {
1568 let r = bx.$integer_reduce(args[0].immediate());
1570 // if overflow occurs, the result is the
1571 // mathematical result modulo 2^n:
1572 if name.contains("mul") {
1573 Ok(bx.mul(args[1].immediate(), r))
1575 Ok(bx.add(args[1].immediate(), r))
1578 Ok(bx.$integer_reduce(args[0].immediate()))
1582 // ordered arithmetic reductions take an accumulator
1583 let acc = if $ordered {
1584 let acc = args[1].immediate();
1585 // FIXME: https://bugs.llvm.org/show_bug.cgi?id=36734
1586 // * if the accumulator of the fadd isn't 0, incorrect
1587 // code is generated
1588 // * if the accumulator of the fmul isn't 1, incorrect
1589 // code is generated
1590 match bx.cx().const_get_real(acc) {
1591 None => return_error!("accumulator of {} is not a constant", $name),
1592 Some((v, loses_info)) => {
1593 if $name.contains("mul") && v != 1.0_f64 {
1594 return_error!("accumulator of {} is not 1.0", $name);
1595 } else if $name.contains("add") && v != 0.0_f64 {
1596 return_error!("accumulator of {} is not 0.0", $name);
1597 } else if loses_info {
1598 return_error!("accumulator of {} loses information", $name);
1604 // unordered arithmetic reductions do not:
1605 match f.bit_width() {
1606 32 => bx.cx().const_undef(bx.cx().type_f32()),
1607 64 => bx.cx().const_undef(bx.cx().type_f64()),
1610 unsupported {} from `{}` with element `{}` of size `{}` to `{}`"#,
1611 $name, in_ty, in_elem, v, ret_ty
1616 Ok(bx.$float_reduce(acc, args[0].immediate()))
1620 "unsupported {} from `{}` with element `{}` to `{}`",
1621 $name, in_ty, in_elem, ret_ty
1629 arith_red!("simd_reduce_add_ordered": vector_reduce_add, vector_reduce_fadd_fast, true);
1630 arith_red!("simd_reduce_mul_ordered": vector_reduce_mul, vector_reduce_fmul_fast, true);
1631 arith_red!("simd_reduce_add_unordered": vector_reduce_add, vector_reduce_fadd_fast, false);
1632 arith_red!("simd_reduce_mul_unordered": vector_reduce_mul, vector_reduce_fmul_fast, false);
1634 macro_rules! minmax_red {
1635 ($name:tt: $int_red:ident, $float_red:ident) => {
1637 require!(ret_ty == in_elem,
1638 "expected return type `{}` (element of input `{}`), found `{}`",
1639 in_elem, in_ty, ret_ty);
1640 return match in_elem.sty {
1642 Ok(bx.$int_red(args[0].immediate(), true))
1645 Ok(bx.$int_red(args[0].immediate(), false))
1648 Ok(bx.$float_red(args[0].immediate()))
1651 return_error!("unsupported {} from `{}` with element `{}` to `{}`",
1652 $name, in_ty, in_elem, ret_ty)
1660 minmax_red!("simd_reduce_min": vector_reduce_min, vector_reduce_fmin);
1661 minmax_red!("simd_reduce_max": vector_reduce_max, vector_reduce_fmax);
1663 minmax_red!("simd_reduce_min_nanless": vector_reduce_min, vector_reduce_fmin_fast);
1664 minmax_red!("simd_reduce_max_nanless": vector_reduce_max, vector_reduce_fmax_fast);
1666 macro_rules! bitwise_red {
1667 ($name:tt : $red:ident, $boolean:expr) => {
1669 let input = if !$boolean {
1670 require!(ret_ty == in_elem,
1671 "expected return type `{}` (element of input `{}`), found `{}`",
1672 in_elem, in_ty, ret_ty);
1676 ty::Int(_) | ty::Uint(_) => {},
1678 return_error!("unsupported {} from `{}` with element `{}` to `{}`",
1679 $name, in_ty, in_elem, ret_ty)
1683 // boolean reductions operate on vectors of i1s:
1684 let i1 = bx.cx().type_i1();
1685 let i1xn = bx.cx().type_vector(i1, in_len as u64);
1686 bx.trunc(args[0].immediate(), i1xn)
1688 return match in_elem.sty {
1689 ty::Int(_) | ty::Uint(_) => {
1690 let r = bx.$red(input);
1695 bx.zext(r, bx.cx().type_bool())
1700 return_error!("unsupported {} from `{}` with element `{}` to `{}`",
1701 $name, in_ty, in_elem, ret_ty)
1708 bitwise_red!("simd_reduce_and": vector_reduce_and, false);
1709 bitwise_red!("simd_reduce_or": vector_reduce_or, false);
1710 bitwise_red!("simd_reduce_xor": vector_reduce_xor, false);
1711 bitwise_red!("simd_reduce_all": vector_reduce_and, true);
1712 bitwise_red!("simd_reduce_any": vector_reduce_or, true);
1714 if name == "simd_cast" {
1715 require_simd!(ret_ty, "return");
1716 let out_len = ret_ty.simd_size(tcx);
1717 require!(in_len == out_len,
1718 "expected return type with length {} (same as input type `{}`), \
1719 found `{}` with length {}",
1722 // casting cares about nominal type, not just structural type
1723 let out_elem = ret_ty.simd_type(tcx);
1725 if in_elem == out_elem { return Ok(args[0].immediate()); }
1727 enum Style { Float, Int(/* is signed? */ bool), Unsupported }
1729 let (in_style, in_width) = match in_elem.sty {
1730 // vectors of pointer-sized integers should've been
1731 // disallowed before here, so this unwrap is safe.
1732 ty::Int(i) => (Style::Int(true), i.bit_width().unwrap()),
1733 ty::Uint(u) => (Style::Int(false), u.bit_width().unwrap()),
1734 ty::Float(f) => (Style::Float, f.bit_width()),
1735 _ => (Style::Unsupported, 0)
1737 let (out_style, out_width) = match out_elem.sty {
1738 ty::Int(i) => (Style::Int(true), i.bit_width().unwrap()),
1739 ty::Uint(u) => (Style::Int(false), u.bit_width().unwrap()),
1740 ty::Float(f) => (Style::Float, f.bit_width()),
1741 _ => (Style::Unsupported, 0)
1744 match (in_style, out_style) {
1745 (Style::Int(in_is_signed), Style::Int(_)) => {
1746 return Ok(match in_width.cmp(&out_width) {
1747 Ordering::Greater => bx.trunc(args[0].immediate(), llret_ty),
1748 Ordering::Equal => args[0].immediate(),
1749 Ordering::Less => if in_is_signed {
1750 bx.sext(args[0].immediate(), llret_ty)
1752 bx.zext(args[0].immediate(), llret_ty)
1756 (Style::Int(in_is_signed), Style::Float) => {
1757 return Ok(if in_is_signed {
1758 bx.sitofp(args[0].immediate(), llret_ty)
1760 bx.uitofp(args[0].immediate(), llret_ty)
1763 (Style::Float, Style::Int(out_is_signed)) => {
1764 return Ok(if out_is_signed {
1765 bx.fptosi(args[0].immediate(), llret_ty)
1767 bx.fptoui(args[0].immediate(), llret_ty)
1770 (Style::Float, Style::Float) => {
1771 return Ok(match in_width.cmp(&out_width) {
1772 Ordering::Greater => bx.fptrunc(args[0].immediate(), llret_ty),
1773 Ordering::Equal => args[0].immediate(),
1774 Ordering::Less => bx.fpext(args[0].immediate(), llret_ty)
1777 _ => {/* Unsupported. Fallthrough. */}
1780 "unsupported cast from `{}` with element `{}` to `{}` with element `{}`",
1784 macro_rules! arith {
1785 ($($name: ident: $($($p: ident),* => $call: ident),*;)*) => {
1786 $(if name == stringify!($name) {
1788 $($(ty::$p(_))|* => {
1789 return Ok(bx.$call(args[0].immediate(), args[1].immediate()))
1794 "unsupported operation on `{}` with element `{}`",
1801 simd_add: Uint, Int => add, Float => fadd;
1802 simd_sub: Uint, Int => sub, Float => fsub;
1803 simd_mul: Uint, Int => mul, Float => fmul;
1804 simd_div: Uint => udiv, Int => sdiv, Float => fdiv;
1805 simd_rem: Uint => urem, Int => srem, Float => frem;
1806 simd_shl: Uint, Int => shl;
1807 simd_shr: Uint => lshr, Int => ashr;
1808 simd_and: Uint, Int => and;
1809 simd_or: Uint, Int => or;
1810 simd_xor: Uint, Int => xor;
1811 simd_fmax: Float => maxnum;
1812 simd_fmin: Float => minnum;
1814 span_bug!(span, "unknown SIMD intrinsic");
1817 // Returns the width of an int Ty, and if it's signed or not
1818 // Returns None if the type is not an integer
1819 // FIXME: there’s multiple of this functions, investigate using some of the already existing
1821 fn int_type_width_signed(ty: Ty, cx: &CodegenCx) -> Option<(u64, bool)> {
1823 ty::Int(t) => Some((match t {
1824 ast::IntTy::Isize => cx.tcx.sess.target.isize_ty.bit_width().unwrap() as u64,
1825 ast::IntTy::I8 => 8,
1826 ast::IntTy::I16 => 16,
1827 ast::IntTy::I32 => 32,
1828 ast::IntTy::I64 => 64,
1829 ast::IntTy::I128 => 128,
1831 ty::Uint(t) => Some((match t {
1832 ast::UintTy::Usize => cx.tcx.sess.target.usize_ty.bit_width().unwrap() as u64,
1833 ast::UintTy::U8 => 8,
1834 ast::UintTy::U16 => 16,
1835 ast::UintTy::U32 => 32,
1836 ast::UintTy::U64 => 64,
1837 ast::UintTy::U128 => 128,
1843 // Returns the width of a float TypeVariant
1844 // Returns None if the type is not a float
1845 fn float_type_width<'tcx>(sty: &ty::TyKind<'tcx>) -> Option<u64> {
1847 ty::Float(t) => Some(t.bit_width() as u64),