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::{LayoutOf, HasTyCtxt};
28 use rustc_codegen_ssa::common::TypeKind;
31 use syntax::symbol::Symbol;
35 use rustc_codegen_ssa::interfaces::*;
37 use rustc::session::Session;
40 use std::cmp::Ordering;
43 fn get_simple_intrinsic(cx: &CodegenCx<'ll, '_>, name: &str) -> Option<&'ll Value> {
44 let llvm_name = match name {
45 "sqrtf32" => "llvm.sqrt.f32",
46 "sqrtf64" => "llvm.sqrt.f64",
47 "powif32" => "llvm.powi.f32",
48 "powif64" => "llvm.powi.f64",
49 "sinf32" => "llvm.sin.f32",
50 "sinf64" => "llvm.sin.f64",
51 "cosf32" => "llvm.cos.f32",
52 "cosf64" => "llvm.cos.f64",
53 "powf32" => "llvm.pow.f32",
54 "powf64" => "llvm.pow.f64",
55 "expf32" => "llvm.exp.f32",
56 "expf64" => "llvm.exp.f64",
57 "exp2f32" => "llvm.exp2.f32",
58 "exp2f64" => "llvm.exp2.f64",
59 "logf32" => "llvm.log.f32",
60 "logf64" => "llvm.log.f64",
61 "log10f32" => "llvm.log10.f32",
62 "log10f64" => "llvm.log10.f64",
63 "log2f32" => "llvm.log2.f32",
64 "log2f64" => "llvm.log2.f64",
65 "fmaf32" => "llvm.fma.f32",
66 "fmaf64" => "llvm.fma.f64",
67 "fabsf32" => "llvm.fabs.f32",
68 "fabsf64" => "llvm.fabs.f64",
69 "copysignf32" => "llvm.copysign.f32",
70 "copysignf64" => "llvm.copysign.f64",
71 "floorf32" => "llvm.floor.f32",
72 "floorf64" => "llvm.floor.f64",
73 "ceilf32" => "llvm.ceil.f32",
74 "ceilf64" => "llvm.ceil.f64",
75 "truncf32" => "llvm.trunc.f32",
76 "truncf64" => "llvm.trunc.f64",
77 "rintf32" => "llvm.rint.f32",
78 "rintf64" => "llvm.rint.f64",
79 "nearbyintf32" => "llvm.nearbyint.f32",
80 "nearbyintf64" => "llvm.nearbyint.f64",
81 "roundf32" => "llvm.round.f32",
82 "roundf64" => "llvm.round.f64",
83 "assume" => "llvm.assume",
84 "abort" => "llvm.trap",
87 Some(cx.get_intrinsic(&llvm_name))
90 impl IntrinsicCallMethods<'tcx> for Builder<'a, 'll, 'tcx> {
91 fn codegen_intrinsic_call(
94 fn_ty: &FnType<'tcx, Ty<'tcx>>,
95 args: &[OperandRef<'tcx, &'ll Value>],
99 let tcx = self.cx().tcx;
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 = self.cx().layout_of(ret_ty).llvm_type(self.cx());
113 let result = PlaceRef::new_sized(llresult, fn_ty.ret.layout, fn_ty.ret.layout.align);
115 let simple = get_simple_intrinsic(self.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 = self.cx().get_intrinsic(&("llvm.expect.i1"));
127 self.call(expect, &[args[0].immediate(), self.cx().const_bool(true)], None)
130 let expect = self.cx().get_intrinsic(&("llvm.expect.i1"));
131 self.call(expect, &[args[0].immediate(), self.cx().const_bool(false)], None)
142 let llfn = self.cx().get_intrinsic(&("llvm.debugtrap"));
143 self.call(llfn, &[], None)
146 let tp_ty = substs.type_at(0);
147 self.cx().const_usize(self.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 self.cx().const_usize(self.cx().size_of(tp_ty).bytes())
160 let tp_ty = substs.type_at(0);
161 self.cx().const_usize(self.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 self.cx().const_usize(self.cx().align_of(tp_ty).abi())
174 let tp_ty = substs.type_at(0);
175 self.cx().const_usize(self.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 self.cx().const_str_slice(ty_name)
183 self.cx().const_u64(self.cx().tcx.type_id_hash(substs.type_at(0)))
186 let ty = substs.type_at(0);
187 if !self.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.)
197 self.cx().const_u8(0),
198 self.cx().const_usize(1)
203 // Effectively no-ops
204 "uninit" | "forget" => {
208 let tp_ty = substs.type_at(0);
210 self.cx().const_bool(self.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, self.cx().type_ptr_to(ty.llvm_type(self.cx())));
260 let load = self.volatile_load(ptr);
261 let align = if name == "unaligned_volatile_load" {
264 self.cx().align_of(tp_ty).abi() as u32
267 llvm::LLVMSetAlignment(load, align);
269 to_immediate(self, load, self.cx().layout_of(tp_ty))
271 "volatile_store" => {
272 let dst = args[0].deref(self.cx());
273 args[1].val.volatile_store(self, dst);
276 "unaligned_volatile_store" => {
277 let dst = args[0].deref(self.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 = self.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),
293 self.cx().const_i32(rw),
295 self.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, self.cx()) {
305 Some((width, signed)) =>
308 let y = self.cx().const_bool(false);
309 let llfn = self.cx().get_intrinsic(
310 &format!("llvm.{}.i{}", name, width),
312 self.call(llfn, &[args[0].immediate(), y], None)
314 "ctlz_nonzero" | "cttz_nonzero" => {
315 let y = self.cx().const_bool(true);
316 let llvm_name = &format!("llvm.{}.i{}", &name[..4], width);
317 let llfn = self.cx().get_intrinsic(llvm_name);
318 self.call(llfn, &[args[0].immediate(), y], None)
320 "ctpop" => self.call(
321 self.cx().get_intrinsic(&format!("llvm.ctpop.i{}", width)),
322 &[args[0].immediate()],
327 args[0].immediate() // byte swap a u8/i8 is just a no-op
330 self.cx().get_intrinsic(
331 &format!("llvm.bswap.i{}", width),
333 &[args[0].immediate()],
340 self.cx().get_intrinsic(
341 &format!("llvm.bitreverse.i{}", width),
343 &[args[0].immediate()],
347 "add_with_overflow" | "sub_with_overflow" | "mul_with_overflow" => {
348 let intrinsic = format!("llvm.{}{}.with.overflow.i{}",
349 if signed { 's' } else { 'u' },
351 let llfn = self.cx().get_intrinsic(&intrinsic);
353 // Convert `i1` to a `bool`, and write it to the out parameter
354 let pair = self.call(llfn, &[
358 let val = self.extract_value(pair, 0);
359 let overflow = self.extract_value(pair, 1);
360 let overflow = self.zext(overflow, self.cx().type_bool());
362 let dest = result.project_field(self, 0);
363 self.store(val, dest.llval, dest.align);
364 let dest = result.project_field(self, 1);
365 self.store(overflow, dest.llval, dest.align);
369 "overflowing_add" => self.add(args[0].immediate(), args[1].immediate()),
370 "overflowing_sub" => self.sub(args[0].immediate(), args[1].immediate()),
371 "overflowing_mul" => self.mul(args[0].immediate(), args[1].immediate()),
374 self.exactsdiv(args[0].immediate(), args[1].immediate())
376 self.exactudiv(args[0].immediate(), args[1].immediate())
380 self.sdiv(args[0].immediate(), args[1].immediate())
382 self.udiv(args[0].immediate(), args[1].immediate())
386 self.srem(args[0].immediate(), args[1].immediate())
388 self.urem(args[0].immediate(), args[1].immediate())
390 "unchecked_shl" => self.shl(args[0].immediate(), args[1].immediate()),
393 self.ashr(args[0].immediate(), args[1].immediate())
395 self.lshr(args[0].immediate(), args[1].immediate())
397 "rotate_left" | "rotate_right" => {
398 let is_left = name == "rotate_left";
399 let val = args[0].immediate();
400 let raw_shift = args[1].immediate();
401 if llvm_util::get_major_version() >= 7 {
402 // rotate = funnel shift with first two args the same
403 let llvm_name = &format!("llvm.fsh{}.i{}",
404 if is_left { 'l' } else { 'r' }, width);
405 let llfn = self.cx().get_intrinsic(llvm_name);
406 self.call(llfn, &[val, val, raw_shift], None)
408 // rotate_left: (X << (S % BW)) | (X >> ((BW - S) % BW))
409 // rotate_right: (X << ((BW - S) % BW)) | (X >> (S % BW))
410 let width = self.cx().const_uint(
411 self.cx().type_ix(width),
414 let shift = self.urem(raw_shift, width);
415 let width_minus_raw_shift = self.sub(width, raw_shift);
416 let inv_shift = self.urem(width_minus_raw_shift, width);
417 let shift1 = self.shl(
419 if is_left { shift } else { inv_shift },
421 let shift2 = self.lshr(
423 if !is_left { shift } else { inv_shift },
425 self.or(shift1, shift2)
431 span_invalid_monomorphization_error(
433 &format!("invalid monomorphization of `{}` intrinsic: \
434 expected basic integer type, found `{}`", name, ty));
440 "fadd_fast" | "fsub_fast" | "fmul_fast" | "fdiv_fast" | "frem_fast" => {
441 let sty = &arg_tys[0].sty;
442 match float_type_width(sty) {
445 "fadd_fast" => self.fadd_fast(args[0].immediate(), args[1].immediate()),
446 "fsub_fast" => self.fsub_fast(args[0].immediate(), args[1].immediate()),
447 "fmul_fast" => self.fmul_fast(args[0].immediate(), args[1].immediate()),
448 "fdiv_fast" => self.fdiv_fast(args[0].immediate(), args[1].immediate()),
449 "frem_fast" => self.frem_fast(args[0].immediate(), args[1].immediate()),
453 span_invalid_monomorphization_error(
455 &format!("invalid monomorphization of `{}` intrinsic: \
456 expected basic float type, found `{}`", name, sty));
463 "discriminant_value" => {
464 args[0].deref(self.cx()).codegen_get_discr(self, ret_ty)
467 name if name.starts_with("simd_") => {
468 match generic_simd_intrinsic(self, name,
477 // This requires that atomic intrinsics follow a specific naming pattern:
478 // "atomic_<operation>[_<ordering>]", and no ordering means SeqCst
479 name if name.starts_with("atomic_") => {
480 use rustc_codegen_ssa::common::AtomicOrdering::*;
481 use rustc_codegen_ssa::common::
482 {SynchronizationScope, AtomicRmwBinOp};
484 let split: Vec<&str> = name.split('_').collect();
486 let is_cxchg = split[1] == "cxchg" || split[1] == "cxchgweak";
487 let (order, failorder) = match split.len() {
488 2 => (SequentiallyConsistent, SequentiallyConsistent),
489 3 => match split[2] {
490 "unordered" => (Unordered, Unordered),
491 "relaxed" => (Monotonic, Monotonic),
492 "acq" => (Acquire, Acquire),
493 "rel" => (Release, Monotonic),
494 "acqrel" => (AcquireRelease, Acquire),
495 "failrelaxed" if is_cxchg =>
496 (SequentiallyConsistent, Monotonic),
497 "failacq" if is_cxchg =>
498 (SequentiallyConsistent, Acquire),
499 _ => self.cx().sess().fatal("unknown ordering in atomic intrinsic")
501 4 => match (split[2], split[3]) {
502 ("acq", "failrelaxed") if is_cxchg =>
503 (Acquire, Monotonic),
504 ("acqrel", "failrelaxed") if is_cxchg =>
505 (AcquireRelease, Monotonic),
506 _ => self.cx().sess().fatal("unknown ordering in atomic intrinsic")
508 _ => self.cx().sess().fatal("Atomic intrinsic not in correct format"),
511 let invalid_monomorphization = |ty| {
512 span_invalid_monomorphization_error(tcx.sess, span,
513 &format!("invalid monomorphization of `{}` intrinsic: \
514 expected basic integer type, found `{}`", name, ty));
518 "cxchg" | "cxchgweak" => {
519 let ty = substs.type_at(0);
520 if int_type_width_signed(ty, self.cx()).is_some() {
521 let weak = split[1] == "cxchgweak";
522 let pair = self.atomic_cmpxchg(
529 let val = self.extract_value(pair, 0);
530 let success = self.extract_value(pair, 1);
531 let success = self.zext(success, self.cx().type_bool());
533 let dest = result.project_field(self, 0);
534 self.store(val, dest.llval, dest.align);
535 let dest = result.project_field(self, 1);
536 self.store(success, dest.llval, dest.align);
539 return invalid_monomorphization(ty);
544 let ty = substs.type_at(0);
545 if int_type_width_signed(ty, self.cx()).is_some() {
546 let size = self.cx().size_of(ty);
547 self.atomic_load(args[0].immediate(), order, size)
549 return invalid_monomorphization(ty);
554 let ty = substs.type_at(0);
555 if int_type_width_signed(ty, self.cx()).is_some() {
556 let size = self.cx().size_of(ty);
565 return invalid_monomorphization(ty);
570 self.atomic_fence(order, SynchronizationScope::CrossThread);
574 "singlethreadfence" => {
575 self.atomic_fence(order, SynchronizationScope::SingleThread);
579 // These are all AtomicRMW ops
581 let atom_op = match op {
582 "xchg" => AtomicRmwBinOp::AtomicXchg,
583 "xadd" => AtomicRmwBinOp::AtomicAdd,
584 "xsub" => AtomicRmwBinOp::AtomicSub,
585 "and" => AtomicRmwBinOp::AtomicAnd,
586 "nand" => AtomicRmwBinOp::AtomicNand,
587 "or" => AtomicRmwBinOp::AtomicOr,
588 "xor" => AtomicRmwBinOp::AtomicXor,
589 "max" => AtomicRmwBinOp::AtomicMax,
590 "min" => AtomicRmwBinOp::AtomicMin,
591 "umax" => AtomicRmwBinOp::AtomicUMax,
592 "umin" => AtomicRmwBinOp::AtomicUMin,
593 _ => self.cx().sess().fatal("unknown atomic operation")
596 let ty = substs.type_at(0);
597 if int_type_width_signed(ty, self.cx()).is_some() {
605 return invalid_monomorphization(ty);
611 "nontemporal_store" => {
612 let dst = args[0].deref(self.cx());
613 args[1].val.nontemporal_store(self, dst);
618 let intr = match Intrinsic::find(&name) {
620 None => bug!("unknown intrinsic '{}'", name),
622 fn one<T>(x: Vec<T>) -> T {
623 assert_eq!(x.len(), 1);
624 x.into_iter().next().unwrap()
627 cx: &CodegenCx<'ll, '_>,
629 ) -> Vec<&'ll Type> {
630 use intrinsics::Type::*;
632 Void => vec![cx.type_void()],
633 Integer(_signed, _width, llvm_width) => {
634 vec![cx.type_ix( llvm_width as u64)]
638 32 => vec![cx.type_f32()],
639 64 => vec![cx.type_f64()],
643 Pointer(ref t, ref llvm_elem, _const) => {
644 let t = llvm_elem.as_ref().unwrap_or(t);
645 let elem = one(ty_to_type(cx, t));
646 vec![cx.type_ptr_to(elem)]
648 Vector(ref t, ref llvm_elem, length) => {
649 let t = llvm_elem.as_ref().unwrap_or(t);
650 let elem = one(ty_to_type(cx, t));
651 vec![cx.type_vector(elem, length as u64)]
653 Aggregate(false, ref contents) => {
654 let elems = contents.iter()
655 .map(|t| one(ty_to_type(cx, t)))
656 .collect::<Vec<_>>();
657 vec![cx.type_struct( &elems, false)]
659 Aggregate(true, ref contents) => {
661 .flat_map(|t| ty_to_type(cx, t))
667 // This allows an argument list like `foo, (bar, baz),
668 // qux` to be converted into `foo, bar, baz, qux`, integer
669 // arguments to be truncated as needed and pointers to be
671 fn modify_as_needed<'ll, 'tcx>(
672 bx: &mut Builder<'_, 'll, 'tcx>,
673 t: &intrinsics::Type,
674 arg: &OperandRef<'tcx, &'ll Value>,
675 ) -> Vec<&'ll Value> {
677 intrinsics::Type::Aggregate(true, ref contents) => {
678 // We found a tuple that needs squishing! So
679 // run over the tuple and load each field.
681 // This assumes the type is "simple", i.e. no
682 // destructors, and the contents are SIMD
684 assert!(!bx.cx().type_needs_drop(arg.layout.ty));
685 let (ptr, align) = match arg.val {
686 OperandValue::Ref(ptr, None, align) => (ptr, align),
689 let arg = PlaceRef::new_sized(ptr, arg.layout, align);
690 (0..contents.len()).map(|i| {
691 let field = arg.project_field(bx, i);
692 bx.load_operand(field).immediate()
695 intrinsics::Type::Pointer(_, Some(ref llvm_elem), _) => {
696 let llvm_elem = one(ty_to_type(bx.cx(), llvm_elem));
697 vec![bx.pointercast(arg.immediate(), bx.cx().type_ptr_to(llvm_elem))]
699 intrinsics::Type::Vector(_, Some(ref llvm_elem), length) => {
700 let llvm_elem = one(ty_to_type(bx.cx(), llvm_elem));
702 bx.bitcast(arg.immediate(),
703 bx.cx().type_vector(llvm_elem, length as u64))
706 intrinsics::Type::Integer(_, width, llvm_width) if width != llvm_width => {
707 // the LLVM intrinsic uses a smaller integer
708 // size than the C intrinsic's signature, so
709 // we have to trim it down here.
710 vec![bx.trunc(arg.immediate(), bx.cx().type_ix(llvm_width as u64))]
712 _ => vec![arg.immediate()],
717 let inputs = intr.inputs.iter()
718 .flat_map(|t| ty_to_type(self.cx(), t))
719 .collect::<Vec<_>>();
721 let outputs = one(ty_to_type(self.cx(), &intr.output));
723 let llargs: Vec<_> = intr.inputs.iter().zip(args).flat_map(|(t, arg)| {
724 modify_as_needed(self, t, arg)
726 assert_eq!(inputs.len(), llargs.len());
728 let val = match intr.definition {
729 intrinsics::IntrinsicDef::Named(name) => {
730 let f = self.cx().declare_cfn(
732 self.cx().type_func(&inputs, outputs),
734 self.call(f, &llargs, None)
739 intrinsics::Type::Aggregate(flatten, ref elems) => {
740 // the output is a tuple so we need to munge it properly
743 for i in 0..elems.len() {
744 let dest = result.project_field(self, i);
745 let val = self.extract_value(val, i as u64);
746 self.store(val, dest.llval, dest.align);
755 if !fn_ty.ret.is_ignore() {
756 if let PassMode::Cast(ty) = fn_ty.ret.mode {
757 let ptr_llty = self.cx().type_ptr_to(ty.llvm_type(self.cx()));
758 let ptr = self.pointercast(result.llval, ptr_llty);
759 self.store(llval, ptr, result.align);
761 OperandRef::from_immediate_or_packed_pair(self, llval, result.layout)
762 .val.store(self, result);
769 bx: &mut Builder<'a, 'll, 'tcx>,
777 let (size, align) = bx.cx().size_and_align_of(ty);
778 let size = bx.mul(bx.cx().const_usize(size.bytes()), count);
779 let flags = if volatile {
785 bx.memmove(dst, align, src, align, size, flags);
787 bx.memcpy(dst, align, src, align, size, flags);
792 bx: &mut Builder<'a, 'll, 'tcx>,
799 let (size, align) = bx.cx().size_and_align_of(ty);
800 let size = bx.mul(bx.cx().const_usize(size.bytes()), count);
801 let flags = if volatile {
806 bx.memset(dst, val, size, align, flags);
810 bx: &mut Builder<'a, 'll, 'tcx>,
813 local_ptr: &'ll Value,
816 if bx.cx().sess().no_landing_pads() {
817 bx.call(func, &[data], None);
818 let ptr_align = bx.tcx().data_layout.pointer_align;
819 bx.store(bx.cx().const_null(bx.cx().type_i8p()), dest, ptr_align);
820 } else if wants_msvc_seh(bx.cx().sess()) {
821 codegen_msvc_try(bx, func, data, local_ptr, dest);
823 codegen_gnu_try(bx, func, data, local_ptr, dest);
827 // MSVC's definition of the `rust_try` function.
829 // This implementation uses the new exception handling instructions in LLVM
830 // which have support in LLVM for SEH on MSVC targets. Although these
831 // instructions are meant to work for all targets, as of the time of this
832 // writing, however, LLVM does not recommend the usage of these new instructions
833 // as the old ones are still more optimized.
835 bx: &mut Builder<'a, 'll, 'tcx>,
838 local_ptr: &'ll Value,
841 let llfn = get_rust_try_fn(bx.cx(), &mut |mut bx| {
842 bx.set_personality_fn(bx.cx().eh_personality());
844 let mut normal = bx.build_sibling_block("normal");
845 let mut catchswitch = bx.build_sibling_block("catchswitch");
846 let mut catchpad = bx.build_sibling_block("catchpad");
847 let mut caught = bx.build_sibling_block("caught");
849 let func = llvm::get_param(bx.llfn(), 0);
850 let data = llvm::get_param(bx.llfn(), 1);
851 let local_ptr = llvm::get_param(bx.llfn(), 2);
853 // We're generating an IR snippet that looks like:
855 // declare i32 @rust_try(%func, %data, %ptr) {
856 // %slot = alloca i64*
857 // invoke %func(%data) to label %normal unwind label %catchswitch
863 // %cs = catchswitch within none [%catchpad] unwind to caller
866 // %tok = catchpad within %cs [%type_descriptor, 0, %slot]
867 // %ptr[0] = %slot[0]
868 // %ptr[1] = %slot[1]
869 // catchret from %tok to label %caught
875 // This structure follows the basic usage of throw/try/catch in LLVM.
876 // For example, compile this C++ snippet to see what LLVM generates:
878 // #include <stdint.h>
880 // int bar(void (*foo)(void), uint64_t *ret) {
884 // } catch(uint64_t a[2]) {
891 // More information can be found in libstd's seh.rs implementation.
892 let i64p = bx.cx().type_ptr_to(bx.cx().type_i64());
893 let ptr_align = bx.tcx().data_layout.pointer_align;
894 let slot = bx.alloca(i64p, "slot", ptr_align);
895 bx.invoke(func, &[data], normal.llbb(), catchswitch.llbb(), None);
897 normal.ret(bx.cx().const_i32(0));
899 let cs = catchswitch.catch_switch(None, None, 1);
900 catchswitch.add_handler(cs, catchpad.llbb());
902 let tydesc = match bx.tcx().lang_items().msvc_try_filter() {
903 Some(did) => bx.cx().get_static(did),
904 None => bug!("msvc_try_filter not defined"),
906 let funclet = catchpad.catch_pad(cs, &[tydesc, bx.cx().const_i32(0), slot]);
907 let addr = catchpad.load(slot, ptr_align);
909 let i64_align = bx.tcx().data_layout.i64_align;
910 let arg1 = catchpad.load(addr, i64_align);
911 let val1 = bx.cx().const_i32(1);
912 let gep1 = catchpad.inbounds_gep(addr, &[val1]);
913 let arg2 = catchpad.load(gep1, i64_align);
914 let local_ptr = catchpad.bitcast(local_ptr, i64p);
915 let gep2 = catchpad.inbounds_gep(local_ptr, &[val1]);
916 catchpad.store(arg1, local_ptr, i64_align);
917 catchpad.store(arg2, gep2, i64_align);
918 catchpad.catch_ret(&funclet, caught.llbb());
920 caught.ret(bx.cx().const_i32(1));
923 // Note that no invoke is used here because by definition this function
924 // can't panic (that's what it's catching).
925 let ret = bx.call(llfn, &[func, data, local_ptr], None);
926 let i32_align = bx.tcx().data_layout.i32_align;
927 bx.store(ret, dest, i32_align);
930 // Definition of the standard "try" function for Rust using the GNU-like model
931 // of exceptions (e.g. the normal semantics of LLVM's landingpad and invoke
934 // This codegen is a little surprising because we always call a shim
935 // function instead of inlining the call to `invoke` manually here. This is done
936 // because in LLVM we're only allowed to have one personality per function
937 // definition. The call to the `try` intrinsic is being inlined into the
938 // function calling it, and that function may already have other personality
939 // functions in play. By calling a shim we're guaranteed that our shim will have
940 // the right personality function.
942 bx: &mut Builder<'a, 'll, 'tcx>,
945 local_ptr: &'ll Value,
948 let llfn = get_rust_try_fn(bx.cx(), &mut |mut bx| {
949 // Codegens the shims described above:
952 // invoke %func(%args...) normal %normal unwind %catch
958 // (ptr, _) = landingpad
959 // store ptr, %local_ptr
962 // Note that the `local_ptr` data passed into the `try` intrinsic is
963 // expected to be `*mut *mut u8` for this to actually work, but that's
964 // managed by the standard library.
966 let mut then = bx.build_sibling_block("then");
967 let mut catch = bx.build_sibling_block("catch");
969 let func = llvm::get_param(bx.llfn(), 0);
970 let data = llvm::get_param(bx.llfn(), 1);
971 let local_ptr = llvm::get_param(bx.llfn(), 2);
972 bx.invoke(func, &[data], then.llbb(), catch.llbb(), None);
973 then.ret(bx.cx().const_i32(0));
975 // Type indicator for the exception being thrown.
977 // The first value in this tuple is a pointer to the exception object
978 // being thrown. The second value is a "selector" indicating which of
979 // the landing pad clauses the exception's type had been matched to.
980 // rust_try ignores the selector.
981 let lpad_ty = bx.cx().type_struct(&[bx.cx().type_i8p(), bx.cx().type_i32()], false);
982 let vals = catch.landing_pad(lpad_ty, bx.cx().eh_personality(), 1);
983 catch.add_clause(vals, bx.cx().const_null(bx.cx().type_i8p()));
984 let ptr = catch.extract_value(vals, 0);
985 let ptr_align = bx.tcx().data_layout.pointer_align;
986 let bitcast = catch.bitcast(local_ptr, bx.cx().type_ptr_to(bx.cx().type_i8p()));
987 catch.store(ptr, bitcast, ptr_align);
988 catch.ret(bx.cx().const_i32(1));
991 // Note that no invoke is used here because by definition this function
992 // can't panic (that's what it's catching).
993 let ret = bx.call(llfn, &[func, data, local_ptr], None);
994 let i32_align = bx.tcx().data_layout.i32_align;
995 bx.store(ret, dest, i32_align);
998 // Helper function to give a Block to a closure to codegen a shim function.
999 // This is currently primarily used for the `try` intrinsic functions above.
1000 fn gen_fn<'ll, 'tcx>(
1001 cx: &CodegenCx<'ll, 'tcx>,
1003 inputs: Vec<Ty<'tcx>>,
1005 codegen: &mut dyn FnMut(Builder<'_, 'll, 'tcx>),
1007 let rust_fn_sig = ty::Binder::bind(cx.tcx.mk_fn_sig(
1011 hir::Unsafety::Unsafe,
1014 let llfn = cx.define_internal_fn(name, rust_fn_sig);
1015 attributes::from_fn_attrs(cx, llfn, None);
1016 let bx = Builder::new_block(cx, llfn, "entry-block");
1021 // Helper function used to get a handle to the `__rust_try` function used to
1022 // catch exceptions.
1024 // This function is only generated once and is then cached.
1025 fn get_rust_try_fn<'ll, 'tcx>(
1026 cx: &CodegenCx<'ll, 'tcx>,
1027 codegen: &mut dyn FnMut(Builder<'_, 'll, 'tcx>),
1029 if let Some(llfn) = cx.rust_try_fn.get() {
1033 // Define the type up front for the signature of the rust_try function.
1035 let i8p = tcx.mk_mut_ptr(tcx.types.i8);
1036 let fn_ty = tcx.mk_fn_ptr(ty::Binder::bind(tcx.mk_fn_sig(
1040 hir::Unsafety::Unsafe,
1043 let output = tcx.types.i32;
1044 let rust_try = gen_fn(cx, "__rust_try", vec![fn_ty, i8p, i8p], output, codegen);
1045 cx.rust_try_fn.set(Some(rust_try));
1049 fn span_invalid_monomorphization_error(a: &Session, b: Span, c: &str) {
1050 span_err!(a, b, E0511, "{}", c);
1053 fn generic_simd_intrinsic(
1054 bx: &mut Builder<'a, 'll, 'tcx>,
1056 callee_ty: Ty<'tcx>,
1057 args: &[OperandRef<'tcx, &'ll Value>],
1059 llret_ty: &'ll Type,
1061 ) -> Result<&'ll Value, ()> {
1062 // macros for error handling:
1063 macro_rules! emit_error {
1067 ($msg: tt, $($fmt: tt)*) => {
1068 span_invalid_monomorphization_error(
1069 bx.cx().sess(), span,
1070 &format!(concat!("invalid monomorphization of `{}` intrinsic: ", $msg),
1075 macro_rules! return_error {
1078 emit_error!($($fmt)*);
1084 macro_rules! require {
1085 ($cond: expr, $($fmt: tt)*) => {
1087 return_error!($($fmt)*);
1092 macro_rules! require_simd {
1093 ($ty: expr, $position: expr) => {
1094 require!($ty.is_simd(), "expected SIMD {} type, found non-SIMD `{}`", $position, $ty)
1099 let sig = tcx.normalize_erasing_late_bound_regions(
1100 ty::ParamEnv::reveal_all(),
1101 &callee_ty.fn_sig(tcx),
1103 let arg_tys = sig.inputs();
1105 // every intrinsic takes a SIMD vector as its first argument
1106 require_simd!(arg_tys[0], "input");
1107 let in_ty = arg_tys[0];
1108 let in_elem = arg_tys[0].simd_type(tcx);
1109 let in_len = arg_tys[0].simd_size(tcx);
1111 let comparison = match name {
1112 "simd_eq" => Some(hir::BinOpKind::Eq),
1113 "simd_ne" => Some(hir::BinOpKind::Ne),
1114 "simd_lt" => Some(hir::BinOpKind::Lt),
1115 "simd_le" => Some(hir::BinOpKind::Le),
1116 "simd_gt" => Some(hir::BinOpKind::Gt),
1117 "simd_ge" => Some(hir::BinOpKind::Ge),
1121 if let Some(cmp_op) = comparison {
1122 require_simd!(ret_ty, "return");
1124 let out_len = ret_ty.simd_size(tcx);
1125 require!(in_len == out_len,
1126 "expected return type with length {} (same as input type `{}`), \
1127 found `{}` with length {}",
1130 require!(bx.cx().type_kind(bx.cx().element_type(llret_ty)) == TypeKind::Integer,
1131 "expected return type with integer elements, found `{}` with non-integer `{}`",
1133 ret_ty.simd_type(tcx));
1135 return Ok(compare_simd_types(bx,
1136 args[0].immediate(),
1137 args[1].immediate(),
1143 if name.starts_with("simd_shuffle") {
1144 let n: usize = name["simd_shuffle".len()..].parse().unwrap_or_else(|_|
1145 span_bug!(span, "bad `simd_shuffle` instruction only caught in codegen?"));
1147 require_simd!(ret_ty, "return");
1149 let out_len = ret_ty.simd_size(tcx);
1150 require!(out_len == n,
1151 "expected return type of length {}, found `{}` with length {}",
1152 n, ret_ty, out_len);
1153 require!(in_elem == ret_ty.simd_type(tcx),
1154 "expected return element type `{}` (element of input `{}`), \
1155 found `{}` with element type `{}`",
1157 ret_ty, ret_ty.simd_type(tcx));
1159 let total_len = in_len as u128 * 2;
1161 let vector = args[2].immediate();
1163 let indices: Option<Vec<_>> = (0..n)
1166 let val = bx.cx().const_get_elt(vector, i as u64);
1167 match bx.cx().const_to_opt_u128(val, true) {
1169 emit_error!("shuffle index #{} is not a constant", arg_idx);
1172 Some(idx) if idx >= total_len => {
1173 emit_error!("shuffle index #{} is out of bounds (limit {})",
1174 arg_idx, total_len);
1177 Some(idx) => Some(bx.cx().const_i32(idx as i32)),
1181 let indices = match indices {
1183 None => return Ok(bx.cx().const_null(llret_ty))
1186 return Ok(bx.shuffle_vector(args[0].immediate(),
1187 args[1].immediate(),
1188 bx.cx().const_vector(&indices)))
1191 if name == "simd_insert" {
1192 require!(in_elem == arg_tys[2],
1193 "expected inserted type `{}` (element of input `{}`), found `{}`",
1194 in_elem, in_ty, arg_tys[2]);
1195 return Ok(bx.insert_element(args[0].immediate(),
1196 args[2].immediate(),
1197 args[1].immediate()))
1199 if name == "simd_extract" {
1200 require!(ret_ty == in_elem,
1201 "expected return type `{}` (element of input `{}`), found `{}`",
1202 in_elem, in_ty, ret_ty);
1203 return Ok(bx.extract_element(args[0].immediate(), args[1].immediate()))
1206 if name == "simd_select" {
1207 let m_elem_ty = in_elem;
1209 let v_len = arg_tys[1].simd_size(tcx);
1210 require!(m_len == v_len,
1211 "mismatched lengths: mask length `{}` != other vector length `{}`",
1214 match m_elem_ty.sty {
1216 _ => return_error!("mask element type is `{}`, expected `i_`", m_elem_ty)
1218 // truncate the mask to a vector of i1s
1219 let i1 = bx.cx().type_i1();
1220 let i1xn = bx.cx().type_vector(i1, m_len as u64);
1221 let m_i1s = bx.trunc(args[0].immediate(), i1xn);
1222 return Ok(bx.select(m_i1s, args[1].immediate(), args[2].immediate()));
1225 fn simd_simple_float_intrinsic(
1227 in_elem: &::rustc::ty::TyS,
1228 in_ty: &::rustc::ty::TyS,
1230 bx: &mut Builder<'a, 'll, 'tcx>,
1232 args: &[OperandRef<'tcx, &'ll Value>],
1233 ) -> Result<&'ll Value, ()> {
1234 macro_rules! emit_error {
1238 ($msg: tt, $($fmt: tt)*) => {
1239 span_invalid_monomorphization_error(
1240 bx.cx().sess(), span,
1241 &format!(concat!("invalid monomorphization of `{}` intrinsic: ", $msg),
1245 macro_rules! return_error {
1248 emit_error!($($fmt)*);
1253 let ety = match in_elem.sty {
1254 ty::Float(f) if f.bit_width() == 32 => {
1255 if in_len < 2 || in_len > 16 {
1257 "unsupported floating-point vector `{}` with length `{}` \
1258 out-of-range [2, 16]",
1263 ty::Float(f) if f.bit_width() == 64 => {
1264 if in_len < 2 || in_len > 8 {
1265 return_error!("unsupported floating-point vector `{}` with length `{}` \
1266 out-of-range [2, 8]",
1272 return_error!("unsupported element type `{}` of floating-point vector `{}`",
1276 return_error!("`{}` is not a floating-point type", in_ty);
1280 let llvm_name = &format!("llvm.{0}.v{1}{2}", name, in_len, ety);
1281 let intrinsic = bx.cx().get_intrinsic(&llvm_name);
1282 let c = bx.call(intrinsic,
1283 &args.iter().map(|arg| arg.immediate()).collect::<Vec<_>>(),
1285 unsafe { llvm::LLVMRustSetHasUnsafeAlgebra(c) };
1291 return simd_simple_float_intrinsic("sqrt", in_elem, in_ty, in_len, bx, span, args);
1294 return simd_simple_float_intrinsic("sin", in_elem, in_ty, in_len, bx, span, args);
1297 return simd_simple_float_intrinsic("cos", in_elem, in_ty, in_len, bx, span, args);
1300 return simd_simple_float_intrinsic("fabs", in_elem, in_ty, in_len, bx, span, args);
1303 return simd_simple_float_intrinsic("floor", in_elem, in_ty, in_len, bx, span, args);
1306 return simd_simple_float_intrinsic("ceil", in_elem, in_ty, in_len, bx, span, args);
1309 return simd_simple_float_intrinsic("exp", in_elem, in_ty, in_len, bx, span, args);
1312 return simd_simple_float_intrinsic("exp2", in_elem, in_ty, in_len, bx, span, args);
1315 return simd_simple_float_intrinsic("log10", in_elem, in_ty, in_len, bx, span, args);
1318 return simd_simple_float_intrinsic("log2", in_elem, in_ty, in_len, bx, span, args);
1321 return simd_simple_float_intrinsic("log", in_elem, in_ty, in_len, bx, span, args);
1324 return simd_simple_float_intrinsic("powi", in_elem, in_ty, in_len, bx, span, args);
1327 return simd_simple_float_intrinsic("pow", in_elem, in_ty, in_len, bx, span, args);
1330 return simd_simple_float_intrinsic("fma", in_elem, in_ty, in_len, bx, span, args);
1332 _ => { /* fallthrough */ }
1336 // https://github.com/llvm-mirror/llvm/blob/master/include/llvm/IR/Function.h#L182
1337 // https://github.com/llvm-mirror/llvm/blob/master/include/llvm/IR/Intrinsics.h#L81
1338 fn llvm_vector_str(elem_ty: ty::Ty, vec_len: usize, no_pointers: usize) -> String {
1339 let p0s: String = "p0".repeat(no_pointers);
1341 ty::Int(v) => format!("v{}{}i{}", vec_len, p0s, v.bit_width().unwrap()),
1342 ty::Uint(v) => format!("v{}{}i{}", vec_len, p0s, v.bit_width().unwrap()),
1343 ty::Float(v) => format!("v{}{}f{}", vec_len, p0s, v.bit_width()),
1344 _ => unreachable!(),
1348 fn llvm_vector_ty(cx: &CodegenCx<'ll, '_>, elem_ty: ty::Ty, vec_len: usize,
1349 mut no_pointers: usize) -> &'ll Type {
1350 // FIXME: use cx.layout_of(ty).llvm_type() ?
1351 let mut elem_ty = match elem_ty.sty {
1352 ty::Int(v) => cx.type_int_from_ty( v),
1353 ty::Uint(v) => cx.type_uint_from_ty( v),
1354 ty::Float(v) => cx.type_float_from_ty( v),
1355 _ => unreachable!(),
1357 while no_pointers > 0 {
1358 elem_ty = cx.type_ptr_to(elem_ty);
1361 cx.type_vector(elem_ty, vec_len as u64)
1365 if name == "simd_gather" {
1366 // simd_gather(values: <N x T>, pointers: <N x *_ T>,
1367 // mask: <N x i{M}>) -> <N x T>
1368 // * N: number of elements in the input vectors
1369 // * T: type of the element to load
1370 // * M: any integer width is supported, will be truncated to i1
1372 // All types must be simd vector types
1373 require_simd!(in_ty, "first");
1374 require_simd!(arg_tys[1], "second");
1375 require_simd!(arg_tys[2], "third");
1376 require_simd!(ret_ty, "return");
1378 // Of the same length:
1379 require!(in_len == arg_tys[1].simd_size(tcx),
1380 "expected {} argument with length {} (same as input type `{}`), \
1381 found `{}` with length {}", "second", in_len, in_ty, arg_tys[1],
1382 arg_tys[1].simd_size(tcx));
1383 require!(in_len == arg_tys[2].simd_size(tcx),
1384 "expected {} argument with length {} (same as input type `{}`), \
1385 found `{}` with length {}", "third", in_len, in_ty, arg_tys[2],
1386 arg_tys[2].simd_size(tcx));
1388 // The return type must match the first argument type
1389 require!(ret_ty == in_ty,
1390 "expected return type `{}`, found `{}`",
1393 // This counts how many pointers
1394 fn ptr_count(t: ty::Ty) -> usize {
1396 ty::RawPtr(p) => 1 + ptr_count(p.ty),
1402 fn non_ptr(t: ty::Ty) -> ty::Ty {
1404 ty::RawPtr(p) => non_ptr(p.ty),
1409 // The second argument must be a simd vector with an element type that's a pointer
1410 // to the element type of the first argument
1411 let (pointer_count, underlying_ty) = match arg_tys[1].simd_type(tcx).sty {
1412 ty::RawPtr(p) if p.ty == in_elem => (ptr_count(arg_tys[1].simd_type(tcx)),
1413 non_ptr(arg_tys[1].simd_type(tcx))),
1415 require!(false, "expected element type `{}` of second argument `{}` \
1416 to be a pointer to the element type `{}` of the first \
1417 argument `{}`, found `{}` != `*_ {}`",
1418 arg_tys[1].simd_type(tcx).sty, arg_tys[1], in_elem, in_ty,
1419 arg_tys[1].simd_type(tcx).sty, in_elem);
1423 assert!(pointer_count > 0);
1424 assert_eq!(pointer_count - 1, ptr_count(arg_tys[0].simd_type(tcx)));
1425 assert_eq!(underlying_ty, non_ptr(arg_tys[0].simd_type(tcx)));
1427 // The element type of the third argument must be a signed integer type of any width:
1428 match arg_tys[2].simd_type(tcx).sty {
1431 require!(false, "expected element type `{}` of third argument `{}` \
1432 to be a signed integer type",
1433 arg_tys[2].simd_type(tcx).sty, arg_tys[2]);
1437 // Alignment of T, must be a constant integer value:
1438 let alignment_ty = bx.cx().type_i32();
1439 let alignment = bx.cx().const_i32(bx.cx().align_of(in_elem).abi() as i32);
1441 // Truncate the mask vector to a vector of i1s:
1442 let (mask, mask_ty) = {
1443 let i1 = bx.cx().type_i1();
1444 let i1xn = bx.cx().type_vector(i1, in_len as u64);
1445 (bx.trunc(args[2].immediate(), i1xn), i1xn)
1448 // Type of the vector of pointers:
1449 let llvm_pointer_vec_ty = llvm_vector_ty(bx.cx(), underlying_ty, in_len, pointer_count);
1450 let llvm_pointer_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count);
1452 // Type of the vector of elements:
1453 let llvm_elem_vec_ty = llvm_vector_ty(bx.cx(), underlying_ty, in_len, pointer_count - 1);
1454 let llvm_elem_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count - 1);
1456 let llvm_intrinsic = format!("llvm.masked.gather.{}.{}",
1457 llvm_elem_vec_str, llvm_pointer_vec_str);
1458 let f = bx.cx().declare_cfn(&llvm_intrinsic,
1459 bx.cx().type_func(&[
1460 llvm_pointer_vec_ty,
1463 llvm_elem_vec_ty], llvm_elem_vec_ty));
1464 llvm::SetUnnamedAddr(f, false);
1465 let v = bx.call(f, &[args[1].immediate(), alignment, mask, args[0].immediate()],
1470 if name == "simd_scatter" {
1471 // simd_scatter(values: <N x T>, pointers: <N x *mut T>,
1472 // mask: <N x i{M}>) -> ()
1473 // * N: number of elements in the input vectors
1474 // * T: type of the element to load
1475 // * M: any integer width is supported, will be truncated to i1
1477 // All types must be simd vector types
1478 require_simd!(in_ty, "first");
1479 require_simd!(arg_tys[1], "second");
1480 require_simd!(arg_tys[2], "third");
1482 // Of the same length:
1483 require!(in_len == arg_tys[1].simd_size(tcx),
1484 "expected {} argument with length {} (same as input type `{}`), \
1485 found `{}` with length {}", "second", in_len, in_ty, arg_tys[1],
1486 arg_tys[1].simd_size(tcx));
1487 require!(in_len == arg_tys[2].simd_size(tcx),
1488 "expected {} argument with length {} (same as input type `{}`), \
1489 found `{}` with length {}", "third", in_len, in_ty, arg_tys[2],
1490 arg_tys[2].simd_size(tcx));
1492 // This counts how many pointers
1493 fn ptr_count(t: ty::Ty) -> usize {
1495 ty::RawPtr(p) => 1 + ptr_count(p.ty),
1501 fn non_ptr(t: ty::Ty) -> ty::Ty {
1503 ty::RawPtr(p) => non_ptr(p.ty),
1508 // The second argument must be a simd vector with an element type that's a pointer
1509 // to the element type of the first argument
1510 let (pointer_count, underlying_ty) = match arg_tys[1].simd_type(tcx).sty {
1511 ty::RawPtr(p) if p.ty == in_elem && p.mutbl == hir::MutMutable
1512 => (ptr_count(arg_tys[1].simd_type(tcx)),
1513 non_ptr(arg_tys[1].simd_type(tcx))),
1515 require!(false, "expected element type `{}` of second argument `{}` \
1516 to be a pointer to the element type `{}` of the first \
1517 argument `{}`, found `{}` != `*mut {}`",
1518 arg_tys[1].simd_type(tcx).sty, arg_tys[1], in_elem, in_ty,
1519 arg_tys[1].simd_type(tcx).sty, in_elem);
1523 assert!(pointer_count > 0);
1524 assert_eq!(pointer_count - 1, ptr_count(arg_tys[0].simd_type(tcx)));
1525 assert_eq!(underlying_ty, non_ptr(arg_tys[0].simd_type(tcx)));
1527 // The element type of the third argument must be a signed integer type of any width:
1528 match arg_tys[2].simd_type(tcx).sty {
1531 require!(false, "expected element type `{}` of third argument `{}` \
1532 to be a signed integer type",
1533 arg_tys[2].simd_type(tcx).sty, arg_tys[2]);
1537 // Alignment of T, must be a constant integer value:
1538 let alignment_ty = bx.cx().type_i32();
1539 let alignment = bx.cx().const_i32(bx.cx().align_of(in_elem).abi() as i32);
1541 // Truncate the mask vector to a vector of i1s:
1542 let (mask, mask_ty) = {
1543 let i1 = bx.cx().type_i1();
1544 let i1xn = bx.cx().type_vector(i1, in_len as u64);
1545 (bx.trunc(args[2].immediate(), i1xn), i1xn)
1548 let ret_t = bx.cx().type_void();
1550 // Type of the vector of pointers:
1551 let llvm_pointer_vec_ty = llvm_vector_ty(bx.cx(), underlying_ty, in_len, pointer_count);
1552 let llvm_pointer_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count);
1554 // Type of the vector of elements:
1555 let llvm_elem_vec_ty = llvm_vector_ty(bx.cx(), underlying_ty, in_len, pointer_count - 1);
1556 let llvm_elem_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count - 1);
1558 let llvm_intrinsic = format!("llvm.masked.scatter.{}.{}",
1559 llvm_elem_vec_str, llvm_pointer_vec_str);
1560 let f = bx.cx().declare_cfn(&llvm_intrinsic,
1561 bx.cx().type_func(&[llvm_elem_vec_ty,
1562 llvm_pointer_vec_ty,
1565 llvm::SetUnnamedAddr(f, false);
1566 let v = bx.call(f, &[args[0].immediate(), args[1].immediate(), alignment, mask],
1571 macro_rules! arith_red {
1572 ($name:tt : $integer_reduce:ident, $float_reduce:ident, $ordered:expr) => {
1574 require!(ret_ty == in_elem,
1575 "expected return type `{}` (element of input `{}`), found `{}`",
1576 in_elem, in_ty, ret_ty);
1577 return match in_elem.sty {
1578 ty::Int(_) | ty::Uint(_) => {
1579 let r = bx.$integer_reduce(args[0].immediate());
1581 // if overflow occurs, the result is the
1582 // mathematical result modulo 2^n:
1583 if name.contains("mul") {
1584 Ok(bx.mul(args[1].immediate(), r))
1586 Ok(bx.add(args[1].immediate(), r))
1589 Ok(bx.$integer_reduce(args[0].immediate()))
1593 // ordered arithmetic reductions take an accumulator
1594 let acc = if $ordered {
1595 let acc = args[1].immediate();
1596 // FIXME: https://bugs.llvm.org/show_bug.cgi?id=36734
1597 // * if the accumulator of the fadd isn't 0, incorrect
1598 // code is generated
1599 // * if the accumulator of the fmul isn't 1, incorrect
1600 // code is generated
1601 match bx.cx().const_get_real(acc) {
1602 None => return_error!("accumulator of {} is not a constant", $name),
1603 Some((v, loses_info)) => {
1604 if $name.contains("mul") && v != 1.0_f64 {
1605 return_error!("accumulator of {} is not 1.0", $name);
1606 } else if $name.contains("add") && v != 0.0_f64 {
1607 return_error!("accumulator of {} is not 0.0", $name);
1608 } else if loses_info {
1609 return_error!("accumulator of {} loses information", $name);
1615 // unordered arithmetic reductions do not:
1616 match f.bit_width() {
1617 32 => bx.cx().const_undef(bx.cx().type_f32()),
1618 64 => bx.cx().const_undef(bx.cx().type_f64()),
1621 unsupported {} from `{}` with element `{}` of size `{}` to `{}`"#,
1622 $name, in_ty, in_elem, v, ret_ty
1627 Ok(bx.$float_reduce(acc, args[0].immediate()))
1631 "unsupported {} from `{}` with element `{}` to `{}`",
1632 $name, in_ty, in_elem, ret_ty
1640 arith_red!("simd_reduce_add_ordered": vector_reduce_add, vector_reduce_fadd_fast, true);
1641 arith_red!("simd_reduce_mul_ordered": vector_reduce_mul, vector_reduce_fmul_fast, true);
1642 arith_red!("simd_reduce_add_unordered": vector_reduce_add, vector_reduce_fadd_fast, false);
1643 arith_red!("simd_reduce_mul_unordered": vector_reduce_mul, vector_reduce_fmul_fast, false);
1645 macro_rules! minmax_red {
1646 ($name:tt: $int_red:ident, $float_red:ident) => {
1648 require!(ret_ty == in_elem,
1649 "expected return type `{}` (element of input `{}`), found `{}`",
1650 in_elem, in_ty, ret_ty);
1651 return match in_elem.sty {
1653 Ok(bx.$int_red(args[0].immediate(), true))
1656 Ok(bx.$int_red(args[0].immediate(), false))
1659 Ok(bx.$float_red(args[0].immediate()))
1662 return_error!("unsupported {} from `{}` with element `{}` to `{}`",
1663 $name, in_ty, in_elem, ret_ty)
1671 minmax_red!("simd_reduce_min": vector_reduce_min, vector_reduce_fmin);
1672 minmax_red!("simd_reduce_max": vector_reduce_max, vector_reduce_fmax);
1674 minmax_red!("simd_reduce_min_nanless": vector_reduce_min, vector_reduce_fmin_fast);
1675 minmax_red!("simd_reduce_max_nanless": vector_reduce_max, vector_reduce_fmax_fast);
1677 macro_rules! bitwise_red {
1678 ($name:tt : $red:ident, $boolean:expr) => {
1680 let input = if !$boolean {
1681 require!(ret_ty == in_elem,
1682 "expected return type `{}` (element of input `{}`), found `{}`",
1683 in_elem, in_ty, ret_ty);
1687 ty::Int(_) | ty::Uint(_) => {},
1689 return_error!("unsupported {} from `{}` with element `{}` to `{}`",
1690 $name, in_ty, in_elem, ret_ty)
1694 // boolean reductions operate on vectors of i1s:
1695 let i1 = bx.cx().type_i1();
1696 let i1xn = bx.cx().type_vector(i1, in_len as u64);
1697 bx.trunc(args[0].immediate(), i1xn)
1699 return match in_elem.sty {
1700 ty::Int(_) | ty::Uint(_) => {
1701 let r = bx.$red(input);
1706 bx.zext(r, bx.cx().type_bool())
1711 return_error!("unsupported {} from `{}` with element `{}` to `{}`",
1712 $name, in_ty, in_elem, ret_ty)
1719 bitwise_red!("simd_reduce_and": vector_reduce_and, false);
1720 bitwise_red!("simd_reduce_or": vector_reduce_or, false);
1721 bitwise_red!("simd_reduce_xor": vector_reduce_xor, false);
1722 bitwise_red!("simd_reduce_all": vector_reduce_and, true);
1723 bitwise_red!("simd_reduce_any": vector_reduce_or, true);
1725 if name == "simd_cast" {
1726 require_simd!(ret_ty, "return");
1727 let out_len = ret_ty.simd_size(tcx);
1728 require!(in_len == out_len,
1729 "expected return type with length {} (same as input type `{}`), \
1730 found `{}` with length {}",
1733 // casting cares about nominal type, not just structural type
1734 let out_elem = ret_ty.simd_type(tcx);
1736 if in_elem == out_elem { return Ok(args[0].immediate()); }
1738 enum Style { Float, Int(/* is signed? */ bool), Unsupported }
1740 let (in_style, in_width) = match in_elem.sty {
1741 // vectors of pointer-sized integers should've been
1742 // disallowed before here, so this unwrap is safe.
1743 ty::Int(i) => (Style::Int(true), i.bit_width().unwrap()),
1744 ty::Uint(u) => (Style::Int(false), u.bit_width().unwrap()),
1745 ty::Float(f) => (Style::Float, f.bit_width()),
1746 _ => (Style::Unsupported, 0)
1748 let (out_style, out_width) = match out_elem.sty {
1749 ty::Int(i) => (Style::Int(true), i.bit_width().unwrap()),
1750 ty::Uint(u) => (Style::Int(false), u.bit_width().unwrap()),
1751 ty::Float(f) => (Style::Float, f.bit_width()),
1752 _ => (Style::Unsupported, 0)
1755 match (in_style, out_style) {
1756 (Style::Int(in_is_signed), Style::Int(_)) => {
1757 return Ok(match in_width.cmp(&out_width) {
1758 Ordering::Greater => bx.trunc(args[0].immediate(), llret_ty),
1759 Ordering::Equal => args[0].immediate(),
1760 Ordering::Less => if in_is_signed {
1761 bx.sext(args[0].immediate(), llret_ty)
1763 bx.zext(args[0].immediate(), llret_ty)
1767 (Style::Int(in_is_signed), Style::Float) => {
1768 return Ok(if in_is_signed {
1769 bx.sitofp(args[0].immediate(), llret_ty)
1771 bx.uitofp(args[0].immediate(), llret_ty)
1774 (Style::Float, Style::Int(out_is_signed)) => {
1775 return Ok(if out_is_signed {
1776 bx.fptosi(args[0].immediate(), llret_ty)
1778 bx.fptoui(args[0].immediate(), llret_ty)
1781 (Style::Float, Style::Float) => {
1782 return Ok(match in_width.cmp(&out_width) {
1783 Ordering::Greater => bx.fptrunc(args[0].immediate(), llret_ty),
1784 Ordering::Equal => args[0].immediate(),
1785 Ordering::Less => bx.fpext(args[0].immediate(), llret_ty)
1788 _ => {/* Unsupported. Fallthrough. */}
1791 "unsupported cast from `{}` with element `{}` to `{}` with element `{}`",
1795 macro_rules! arith {
1796 ($($name: ident: $($($p: ident),* => $call: ident),*;)*) => {
1797 $(if name == stringify!($name) {
1799 $($(ty::$p(_))|* => {
1800 return Ok(bx.$call(args[0].immediate(), args[1].immediate()))
1805 "unsupported operation on `{}` with element `{}`",
1812 simd_add: Uint, Int => add, Float => fadd;
1813 simd_sub: Uint, Int => sub, Float => fsub;
1814 simd_mul: Uint, Int => mul, Float => fmul;
1815 simd_div: Uint => udiv, Int => sdiv, Float => fdiv;
1816 simd_rem: Uint => urem, Int => srem, Float => frem;
1817 simd_shl: Uint, Int => shl;
1818 simd_shr: Uint => lshr, Int => ashr;
1819 simd_and: Uint, Int => and;
1820 simd_or: Uint, Int => or;
1821 simd_xor: Uint, Int => xor;
1822 simd_fmax: Float => maxnum;
1823 simd_fmin: Float => minnum;
1825 span_bug!(span, "unknown SIMD intrinsic");
1828 // Returns the width of an int Ty, and if it's signed or not
1829 // Returns None if the type is not an integer
1830 // FIXME: there’s multiple of this functions, investigate using some of the already existing
1832 fn int_type_width_signed(ty: Ty, cx: &CodegenCx) -> Option<(u64, bool)> {
1834 ty::Int(t) => Some((match t {
1835 ast::IntTy::Isize => cx.tcx.sess.target.isize_ty.bit_width().unwrap() as u64,
1836 ast::IntTy::I8 => 8,
1837 ast::IntTy::I16 => 16,
1838 ast::IntTy::I32 => 32,
1839 ast::IntTy::I64 => 64,
1840 ast::IntTy::I128 => 128,
1842 ty::Uint(t) => Some((match t {
1843 ast::UintTy::Usize => cx.tcx.sess.target.usize_ty.bit_width().unwrap() as u64,
1844 ast::UintTy::U8 => 8,
1845 ast::UintTy::U16 => 16,
1846 ast::UintTy::U32 => 32,
1847 ast::UintTy::U64 => 64,
1848 ast::UintTy::U128 => 128,
1854 // Returns the width of a float TypeVariant
1855 // Returns None if the type is not a float
1856 fn float_type_width<'tcx>(sty: &ty::TyKind<'tcx>) -> Option<u64> {
1858 ty::Float(t) => Some(t.bit_width() as u64),