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 /// Remember to add all intrinsics here, in librustc_typeck/check/mod.rs,
91 /// and in libcore/intrinsics.rs; if you need access to any llvm intrinsics,
92 /// add them to librustc_codegen_llvm/context.rs
93 fn codegen_intrinsic_call(
96 fn_ty: &FnType<'tcx, Ty<'tcx>>,
97 args: &[OperandRef<'tcx, &'ll Value>],
104 let (def_id, substs) = match callee_ty.sty {
105 ty::FnDef(def_id, substs) => (def_id, substs),
106 _ => bug!("expected fn item type, found {}", callee_ty)
109 let sig = callee_ty.fn_sig(tcx);
110 let sig = tcx.normalize_erasing_late_bound_regions(ty::ParamEnv::reveal_all(), &sig);
111 let arg_tys = sig.inputs();
112 let ret_ty = sig.output();
113 let name = &*tcx.item_name(def_id).as_str();
115 let llret_ty = cx.layout_of(ret_ty).llvm_type(cx);
116 let result = PlaceRef::new_sized(llresult, fn_ty.ret.layout, fn_ty.ret.layout.align);
118 let simple = get_simple_intrinsic(cx, name);
119 let llval = match name {
120 _ if simple.is_some() => {
121 self.call(simple.unwrap(),
122 &args.iter().map(|arg| arg.immediate()).collect::<Vec<_>>(),
129 let expect = cx.get_intrinsic(&("llvm.expect.i1"));
130 self.call(expect, &[args[0].immediate(), cx.const_bool(true)], None)
133 let expect = cx.get_intrinsic(&("llvm.expect.i1"));
134 self.call(expect, &[args[0].immediate(), cx.const_bool(false)], None)
137 try_intrinsic(self, cx,
145 let llfn = cx.get_intrinsic(&("llvm.debugtrap"));
146 self.call(llfn, &[], None)
149 let tp_ty = substs.type_at(0);
150 cx.const_usize(cx.size_of(tp_ty).bytes())
153 let tp_ty = substs.type_at(0);
154 if let OperandValue::Pair(_, meta) = args[0].val {
156 glue::size_and_align_of_dst(self, tp_ty, Some(meta));
159 cx.const_usize(cx.size_of(tp_ty).bytes())
163 let tp_ty = substs.type_at(0);
164 cx.const_usize(cx.align_of(tp_ty).abi())
166 "min_align_of_val" => {
167 let tp_ty = substs.type_at(0);
168 if let OperandValue::Pair(_, meta) = args[0].val {
170 glue::size_and_align_of_dst(self, tp_ty, Some(meta));
173 cx.const_usize(cx.align_of(tp_ty).abi())
177 let tp_ty = substs.type_at(0);
178 cx.const_usize(cx.align_of(tp_ty).pref())
181 let tp_ty = substs.type_at(0);
182 let ty_name = Symbol::intern(&tp_ty.to_string()).as_str();
183 cx.const_str_slice(ty_name)
186 cx.const_u64(cx.tcx.type_id_hash(substs.type_at(0)))
189 let ty = substs.type_at(0);
190 if !cx.layout_of(ty).is_zst() {
191 // Just zero out the stack slot.
192 // If we store a zero constant, LLVM will drown in vreg allocation for large
193 // data structures, and the generated code will be awful. (A telltale sign of
194 // this is large quantities of `mov [byte ptr foo],0` in the generated code.)
206 // Effectively no-ops
207 "uninit" | "forget" => {
211 let tp_ty = substs.type_at(0);
213 cx.const_bool(cx.type_needs_drop(tp_ty))
216 let ptr = args[0].immediate();
217 let offset = args[1].immediate();
218 self.inbounds_gep(ptr, &[offset])
221 let ptr = args[0].immediate();
222 let offset = args[1].immediate();
223 self.gep(ptr, &[offset])
226 "copy_nonoverlapping" => {
227 copy_intrinsic(&self, false, false, substs.type_at(0),
228 args[1].immediate(), args[0].immediate(), args[2].immediate());
232 copy_intrinsic(&self, true, false, substs.type_at(0),
233 args[1].immediate(), args[0].immediate(), args[2].immediate());
237 memset_intrinsic(&self, false, substs.type_at(0),
238 args[0].immediate(), args[1].immediate(), args[2].immediate());
242 "volatile_copy_nonoverlapping_memory" => {
243 copy_intrinsic(&self, false, true, substs.type_at(0),
244 args[0].immediate(), args[1].immediate(), args[2].immediate());
247 "volatile_copy_memory" => {
248 copy_intrinsic(&self, true, true, substs.type_at(0),
249 args[0].immediate(), args[1].immediate(), args[2].immediate());
252 "volatile_set_memory" => {
253 memset_intrinsic(&self, true, substs.type_at(0),
254 args[0].immediate(), args[1].immediate(), args[2].immediate());
257 "volatile_load" | "unaligned_volatile_load" => {
258 let tp_ty = substs.type_at(0);
259 let mut ptr = args[0].immediate();
260 if let PassMode::Cast(ty) = fn_ty.ret.mode {
261 ptr = self.pointercast(ptr, cx.type_ptr_to(ty.llvm_type(cx)));
263 let load = self.volatile_load(ptr);
264 let align = if name == "unaligned_volatile_load" {
267 cx.align_of(tp_ty).abi() as u32
270 llvm::LLVMSetAlignment(load, align);
272 to_immediate(self, load, cx.layout_of(tp_ty))
274 "volatile_store" => {
275 let dst = args[0].deref(cx);
276 args[1].val.volatile_store(self, dst);
279 "unaligned_volatile_store" => {
280 let dst = args[0].deref(cx);
281 args[1].val.unaligned_volatile_store(self, dst);
284 "prefetch_read_data" | "prefetch_write_data" |
285 "prefetch_read_instruction" | "prefetch_write_instruction" => {
286 let expect = cx.get_intrinsic(&("llvm.prefetch"));
287 let (rw, cache_type) = match name {
288 "prefetch_read_data" => (0, 1),
289 "prefetch_write_data" => (1, 1),
290 "prefetch_read_instruction" => (0, 0),
291 "prefetch_write_instruction" => (1, 0),
298 cx.const_i32(cache_type)
301 "ctlz" | "ctlz_nonzero" | "cttz" | "cttz_nonzero" | "ctpop" | "bswap" |
302 "bitreverse" | "add_with_overflow" | "sub_with_overflow" |
303 "mul_with_overflow" | "overflowing_add" | "overflowing_sub" | "overflowing_mul" |
304 "unchecked_div" | "unchecked_rem" | "unchecked_shl" | "unchecked_shr" | "exact_div" |
305 "rotate_left" | "rotate_right" => {
307 match int_type_width_signed(ty, cx) {
308 Some((width, signed)) =>
311 let y = cx.const_bool(false);
312 let llfn = cx.get_intrinsic(&format!("llvm.{}.i{}", name, width));
313 self.call(llfn, &[args[0].immediate(), y], None)
315 "ctlz_nonzero" | "cttz_nonzero" => {
316 let y = cx.const_bool(true);
317 let llvm_name = &format!("llvm.{}.i{}", &name[..4], width);
318 let llfn = cx.get_intrinsic(llvm_name);
319 self.call(llfn, &[args[0].immediate(), y], None)
321 "ctpop" => self.call(
322 cx.get_intrinsic(&format!("llvm.ctpop.i{}", width)),
323 &[args[0].immediate()],
328 args[0].immediate() // byte swap a u8/i8 is just a no-op
330 self.call(cx.get_intrinsic(&format!("llvm.bswap.i{}", width)),
331 &[args[0].immediate()], None)
335 self.call(cx.get_intrinsic(&format!("llvm.bitreverse.i{}", width)),
336 &[args[0].immediate()], None)
338 "add_with_overflow" | "sub_with_overflow" | "mul_with_overflow" => {
339 let intrinsic = format!("llvm.{}{}.with.overflow.i{}",
340 if signed { 's' } else { 'u' },
342 let llfn = cx.get_intrinsic(&intrinsic);
344 // Convert `i1` to a `bool`, and write it to the out parameter
345 let pair = self.call(llfn, &[
349 let val = self.extract_value(pair, 0);
350 let overflow = self.zext(
351 self.extract_value(pair, 1),
355 let dest = result.project_field(self, 0);
356 self.store(val, dest.llval, dest.align);
357 let dest = result.project_field(self, 1);
358 self.store(overflow, dest.llval, dest.align);
362 "overflowing_add" => self.add(args[0].immediate(), args[1].immediate()),
363 "overflowing_sub" => self.sub(args[0].immediate(), args[1].immediate()),
364 "overflowing_mul" => self.mul(args[0].immediate(), args[1].immediate()),
367 self.exactsdiv(args[0].immediate(), args[1].immediate())
369 self.exactudiv(args[0].immediate(), args[1].immediate())
373 self.sdiv(args[0].immediate(), args[1].immediate())
375 self.udiv(args[0].immediate(), args[1].immediate())
379 self.srem(args[0].immediate(), args[1].immediate())
381 self.urem(args[0].immediate(), args[1].immediate())
383 "unchecked_shl" => self.shl(args[0].immediate(), args[1].immediate()),
386 self.ashr(args[0].immediate(), args[1].immediate())
388 self.lshr(args[0].immediate(), args[1].immediate())
390 "rotate_left" | "rotate_right" => {
391 let is_left = name == "rotate_left";
392 let val = args[0].immediate();
393 let raw_shift = args[1].immediate();
394 if llvm_util::get_major_version() >= 7 {
395 // rotate = funnel shift with first two args the same
396 let llvm_name = &format!("llvm.fsh{}.i{}",
397 if is_left { 'l' } else { 'r' }, width);
398 let llfn = cx.get_intrinsic(llvm_name);
399 self.call(llfn, &[val, val, raw_shift], None)
401 // rotate_left: (X << (S % BW)) | (X >> ((BW - S) % BW))
402 // rotate_right: (X << ((BW - S) % BW)) | (X >> (S % BW))
403 let width = cx.const_uint(cx.type_ix(width), width);
404 let shift = self.urem(raw_shift, width);
405 let inv_shift = self.urem(self.sub(width, raw_shift), width);
406 let shift1 = self.shl(
408 if is_left { shift } else { inv_shift },
410 let shift2 = self.lshr(
412 if !is_left { shift } else { inv_shift },
414 self.or(shift1, shift2)
420 span_invalid_monomorphization_error(
422 &format!("invalid monomorphization of `{}` intrinsic: \
423 expected basic integer type, found `{}`", name, ty));
429 "fadd_fast" | "fsub_fast" | "fmul_fast" | "fdiv_fast" | "frem_fast" => {
430 let sty = &arg_tys[0].sty;
431 match float_type_width(sty) {
434 "fadd_fast" => self.fadd_fast(args[0].immediate(), args[1].immediate()),
435 "fsub_fast" => self.fsub_fast(args[0].immediate(), args[1].immediate()),
436 "fmul_fast" => self.fmul_fast(args[0].immediate(), args[1].immediate()),
437 "fdiv_fast" => self.fdiv_fast(args[0].immediate(), args[1].immediate()),
438 "frem_fast" => self.frem_fast(args[0].immediate(), args[1].immediate()),
442 span_invalid_monomorphization_error(
444 &format!("invalid monomorphization of `{}` intrinsic: \
445 expected basic float type, found `{}`", name, sty));
452 "discriminant_value" => {
453 args[0].deref(cx).codegen_get_discr(self, ret_ty)
456 name if name.starts_with("simd_") => {
457 match generic_simd_intrinsic(&self, name,
466 // This requires that atomic intrinsics follow a specific naming pattern:
467 // "atomic_<operation>[_<ordering>]", and no ordering means SeqCst
468 name if name.starts_with("atomic_") => {
469 use self::AtomicOrdering::*;
471 let split: Vec<&str> = name.split('_').collect();
473 let is_cxchg = split[1] == "cxchg" || split[1] == "cxchgweak";
474 let (order, failorder) = match split.len() {
475 2 => (SequentiallyConsistent, SequentiallyConsistent),
476 3 => match split[2] {
477 "unordered" => (Unordered, Unordered),
478 "relaxed" => (Monotonic, Monotonic),
479 "acq" => (Acquire, Acquire),
480 "rel" => (Release, Monotonic),
481 "acqrel" => (AcquireRelease, Acquire),
482 "failrelaxed" if is_cxchg =>
483 (SequentiallyConsistent, Monotonic),
484 "failacq" if is_cxchg =>
485 (SequentiallyConsistent, Acquire),
486 _ => cx.sess().fatal("unknown ordering in atomic intrinsic")
488 4 => match (split[2], split[3]) {
489 ("acq", "failrelaxed") if is_cxchg =>
490 (Acquire, Monotonic),
491 ("acqrel", "failrelaxed") if is_cxchg =>
492 (AcquireRelease, Monotonic),
493 _ => cx.sess().fatal("unknown ordering in atomic intrinsic")
495 _ => cx.sess().fatal("Atomic intrinsic not in correct format"),
498 let invalid_monomorphization = |ty| {
499 span_invalid_monomorphization_error(tcx.sess, span,
500 &format!("invalid monomorphization of `{}` intrinsic: \
501 expected basic integer type, found `{}`", name, ty));
505 "cxchg" | "cxchgweak" => {
506 let ty = substs.type_at(0);
507 if int_type_width_signed(ty, cx).is_some() {
508 let weak = split[1] == "cxchgweak";
509 let pair = self.atomic_cmpxchg(
516 let val = self.extract_value(pair, 0);
517 let success = self.zext(
518 self.extract_value(pair, 1),
522 let dest = result.project_field(self, 0);
523 self.store(val, dest.llval, dest.align);
524 let dest = result.project_field(self, 1);
525 self.store(success, dest.llval, dest.align);
528 return invalid_monomorphization(ty);
533 let ty = substs.type_at(0);
534 if int_type_width_signed(ty, cx).is_some() {
535 let size = cx.size_of(ty);
536 self.atomic_load(args[0].immediate(), order, size)
538 return invalid_monomorphization(ty);
543 let ty = substs.type_at(0);
544 if int_type_width_signed(ty, cx).is_some() {
545 let size = cx.size_of(ty);
554 return invalid_monomorphization(ty);
559 self.atomic_fence(order, SynchronizationScope::CrossThread);
563 "singlethreadfence" => {
564 self.atomic_fence(order, SynchronizationScope::SingleThread);
568 // These are all AtomicRMW ops
570 let atom_op = match op {
571 "xchg" => AtomicRmwBinOp::AtomicXchg,
572 "xadd" => AtomicRmwBinOp::AtomicAdd,
573 "xsub" => AtomicRmwBinOp::AtomicSub,
574 "and" => AtomicRmwBinOp::AtomicAnd,
575 "nand" => AtomicRmwBinOp::AtomicNand,
576 "or" => AtomicRmwBinOp::AtomicOr,
577 "xor" => AtomicRmwBinOp::AtomicXor,
578 "max" => AtomicRmwBinOp::AtomicMax,
579 "min" => AtomicRmwBinOp::AtomicMin,
580 "umax" => AtomicRmwBinOp::AtomicUMax,
581 "umin" => AtomicRmwBinOp::AtomicUMin,
582 _ => cx.sess().fatal("unknown atomic operation")
585 let ty = substs.type_at(0);
586 if int_type_width_signed(ty, cx).is_some() {
594 return invalid_monomorphization(ty);
600 "nontemporal_store" => {
601 let dst = args[0].deref(cx);
602 args[1].val.nontemporal_store(self, dst);
607 let intr = match Intrinsic::find(&name) {
609 None => bug!("unknown intrinsic '{}'", name),
611 fn one<T>(x: Vec<T>) -> T {
612 assert_eq!(x.len(), 1);
613 x.into_iter().next().unwrap()
616 cx: &CodegenCx<'ll, '_>,
618 ) -> Vec<&'ll Type> {
619 use intrinsics::Type::*;
621 Void => vec![cx.type_void()],
622 Integer(_signed, _width, llvm_width) => {
623 vec![cx.type_ix( llvm_width as u64)]
627 32 => vec![cx.type_f32()],
628 64 => vec![cx.type_f64()],
632 Pointer(ref t, ref llvm_elem, _const) => {
633 let t = llvm_elem.as_ref().unwrap_or(t);
634 let elem = one(ty_to_type(cx, t));
635 vec![cx.type_ptr_to(elem)]
637 Vector(ref t, ref llvm_elem, length) => {
638 let t = llvm_elem.as_ref().unwrap_or(t);
639 let elem = one(ty_to_type(cx, t));
640 vec![cx.type_vector(elem, length as u64)]
642 Aggregate(false, ref contents) => {
643 let elems = contents.iter()
644 .map(|t| one(ty_to_type(cx, t)))
645 .collect::<Vec<_>>();
646 vec![cx.type_struct( &elems, false)]
648 Aggregate(true, ref contents) => {
650 .flat_map(|t| ty_to_type(cx, t))
656 // This allows an argument list like `foo, (bar, baz),
657 // qux` to be converted into `foo, bar, baz, qux`, integer
658 // arguments to be truncated as needed and pointers to be
660 fn modify_as_needed<'ll, 'tcx>(
661 bx: &Builder<'_, 'll, 'tcx>,
662 t: &intrinsics::Type,
663 arg: &OperandRef<'tcx, &'ll Value>,
664 ) -> Vec<&'ll Value> {
666 intrinsics::Type::Aggregate(true, ref contents) => {
667 // We found a tuple that needs squishing! So
668 // run over the tuple and load each field.
670 // This assumes the type is "simple", i.e. no
671 // destructors, and the contents are SIMD
673 assert!(!bx.cx().type_needs_drop(arg.layout.ty));
674 let (ptr, align) = match arg.val {
675 OperandValue::Ref(ptr, None, align) => (ptr, align),
678 let arg = PlaceRef::new_sized(ptr, arg.layout, align);
679 (0..contents.len()).map(|i| {
680 bx.load_operand(arg.project_field(bx, i)).immediate()
683 intrinsics::Type::Pointer(_, Some(ref llvm_elem), _) => {
684 let llvm_elem = one(ty_to_type(bx.cx(), llvm_elem));
685 vec![bx.pointercast(arg.immediate(), bx.cx().type_ptr_to(llvm_elem))]
687 intrinsics::Type::Vector(_, Some(ref llvm_elem), length) => {
688 let llvm_elem = one(ty_to_type(bx.cx(), llvm_elem));
690 bx.bitcast(arg.immediate(),
691 bx.cx().type_vector(llvm_elem, length as u64))
694 intrinsics::Type::Integer(_, width, llvm_width) if width != llvm_width => {
695 // the LLVM intrinsic uses a smaller integer
696 // size than the C intrinsic's signature, so
697 // we have to trim it down here.
698 vec![bx.trunc(arg.immediate(), bx.cx().type_ix(llvm_width as u64))]
700 _ => vec![arg.immediate()],
705 let inputs = intr.inputs.iter()
706 .flat_map(|t| ty_to_type(cx, t))
707 .collect::<Vec<_>>();
709 let outputs = one(ty_to_type(cx, &intr.output));
711 let llargs: Vec<_> = intr.inputs.iter().zip(args).flat_map(|(t, arg)| {
712 modify_as_needed(&self, t, arg)
714 assert_eq!(inputs.len(), llargs.len());
716 let val = match intr.definition {
717 intrinsics::IntrinsicDef::Named(name) => {
718 let f = cx.declare_cfn(
720 cx.type_func(&inputs, outputs),
722 self.call(f, &llargs, None)
727 intrinsics::Type::Aggregate(flatten, ref elems) => {
728 // the output is a tuple so we need to munge it properly
731 for i in 0..elems.len() {
732 let dest = result.project_field(self, i);
733 let val = self.extract_value(val, i as u64);
734 self.store(val, dest.llval, dest.align);
743 if !fn_ty.ret.is_ignore() {
744 if let PassMode::Cast(ty) = fn_ty.ret.mode {
745 let ptr = self.pointercast(result.llval, cx.type_ptr_to(ty.llvm_type(cx)));
746 self.store(llval, ptr, result.align);
748 OperandRef::from_immediate_or_packed_pair(self, llval, result.layout)
749 .val.store(self, result);
756 bx: &Builder<'a, 'll, 'tcx>,
764 let (size, align) = bx.cx().size_and_align_of(ty);
765 let size = bx.mul(bx.cx().const_usize(size.bytes()), count);
766 let flags = if volatile {
772 bx.memmove(dst, align, src, align, size, flags);
774 bx.memcpy(dst, align, src, align, size, flags);
779 bx: &Builder<'a, 'll, 'tcx>,
786 let (size, align) = bx.cx().size_and_align_of(ty);
787 let size = bx.cx().const_usize(size.bytes());
788 let flags = if volatile {
793 bx.memset(dst, val, bx.mul(size, count), align, flags);
797 bx: &Builder<'a, 'll, 'tcx>,
798 cx: &CodegenCx<'ll, 'tcx>,
801 local_ptr: &'ll Value,
804 if bx.cx().sess().no_landing_pads() {
805 bx.call(func, &[data], None);
806 let ptr_align = bx.tcx().data_layout.pointer_align;
807 bx.store(cx.const_null(cx.type_i8p()), dest, ptr_align);
808 } else if wants_msvc_seh(bx.cx().sess()) {
809 codegen_msvc_try(bx, cx, func, data, local_ptr, dest);
811 codegen_gnu_try(bx, cx, func, data, local_ptr, dest);
815 // MSVC's definition of the `rust_try` function.
817 // This implementation uses the new exception handling instructions in LLVM
818 // which have support in LLVM for SEH on MSVC targets. Although these
819 // instructions are meant to work for all targets, as of the time of this
820 // writing, however, LLVM does not recommend the usage of these new instructions
821 // as the old ones are still more optimized.
823 bx: &Builder<'a, 'll, 'tcx>,
824 cx: &CodegenCx<'ll, 'tcx>,
827 local_ptr: &'ll Value,
830 let llfn = get_rust_try_fn(cx, &mut |bx| {
833 bx.set_personality_fn(bx.cx().eh_personality());
835 let normal = bx.build_sibling_block("normal");
836 let catchswitch = bx.build_sibling_block("catchswitch");
837 let catchpad = bx.build_sibling_block("catchpad");
838 let caught = bx.build_sibling_block("caught");
840 let func = llvm::get_param(bx.llfn(), 0);
841 let data = llvm::get_param(bx.llfn(), 1);
842 let local_ptr = llvm::get_param(bx.llfn(), 2);
844 // We're generating an IR snippet that looks like:
846 // declare i32 @rust_try(%func, %data, %ptr) {
847 // %slot = alloca i64*
848 // invoke %func(%data) to label %normal unwind label %catchswitch
854 // %cs = catchswitch within none [%catchpad] unwind to caller
857 // %tok = catchpad within %cs [%type_descriptor, 0, %slot]
858 // %ptr[0] = %slot[0]
859 // %ptr[1] = %slot[1]
860 // catchret from %tok to label %caught
866 // This structure follows the basic usage of throw/try/catch in LLVM.
867 // For example, compile this C++ snippet to see what LLVM generates:
869 // #include <stdint.h>
871 // int bar(void (*foo)(void), uint64_t *ret) {
875 // } catch(uint64_t a[2]) {
882 // More information can be found in libstd's seh.rs implementation.
883 let i64p = cx.type_ptr_to(cx.type_i64());
884 let ptr_align = bx.tcx().data_layout.pointer_align;
885 let slot = bx.alloca(i64p, "slot", ptr_align);
886 bx.invoke(func, &[data], normal.llbb(), catchswitch.llbb(), None);
888 normal.ret(cx.const_i32(0));
890 let cs = catchswitch.catch_switch(None, None, 1);
891 catchswitch.add_handler(cs, catchpad.llbb());
894 let tydesc = match tcx.lang_items().msvc_try_filter() {
895 Some(did) => cx.get_static(did),
896 None => bug!("msvc_try_filter not defined"),
898 let tok = catchpad.catch_pad(cs, &[tydesc, cx.const_i32(0), slot]);
899 let addr = catchpad.load(slot, ptr_align);
901 let i64_align = bx.tcx().data_layout.i64_align;
902 let arg1 = catchpad.load(addr, i64_align);
903 let val1 = cx.const_i32(1);
904 let arg2 = catchpad.load(catchpad.inbounds_gep(addr, &[val1]), i64_align);
905 let local_ptr = catchpad.bitcast(local_ptr, i64p);
906 catchpad.store(arg1, local_ptr, i64_align);
907 catchpad.store(arg2, catchpad.inbounds_gep(local_ptr, &[val1]), i64_align);
908 catchpad.catch_ret(tok, caught.llbb());
910 caught.ret(cx.const_i32(1));
913 // Note that no invoke is used here because by definition this function
914 // can't panic (that's what it's catching).
915 let ret = bx.call(llfn, &[func, data, local_ptr], None);
916 let i32_align = bx.tcx().data_layout.i32_align;
917 bx.store(ret, dest, i32_align);
920 // Definition of the standard "try" function for Rust using the GNU-like model
921 // of exceptions (e.g. the normal semantics of LLVM's landingpad and invoke
924 // This codegen is a little surprising because we always call a shim
925 // function instead of inlining the call to `invoke` manually here. This is done
926 // because in LLVM we're only allowed to have one personality per function
927 // definition. The call to the `try` intrinsic is being inlined into the
928 // function calling it, and that function may already have other personality
929 // functions in play. By calling a shim we're guaranteed that our shim will have
930 // the right personality function.
932 bx: &Builder<'a, 'll, 'tcx>,
933 cx: &CodegenCx<'ll, 'tcx>,
936 local_ptr: &'ll Value,
939 let llfn = get_rust_try_fn(cx, &mut |bx| {
942 // Codegens the shims described above:
945 // invoke %func(%args...) normal %normal unwind %catch
951 // (ptr, _) = landingpad
952 // store ptr, %local_ptr
955 // Note that the `local_ptr` data passed into the `try` intrinsic is
956 // expected to be `*mut *mut u8` for this to actually work, but that's
957 // managed by the standard library.
959 let then = bx.build_sibling_block("then");
960 let catch = bx.build_sibling_block("catch");
962 let func = llvm::get_param(bx.llfn(), 0);
963 let data = llvm::get_param(bx.llfn(), 1);
964 let local_ptr = llvm::get_param(bx.llfn(), 2);
965 bx.invoke(func, &[data], then.llbb(), catch.llbb(), None);
966 then.ret(cx.const_i32(0));
968 // Type indicator for the exception being thrown.
970 // The first value in this tuple is a pointer to the exception object
971 // being thrown. The second value is a "selector" indicating which of
972 // the landing pad clauses the exception's type had been matched to.
973 // rust_try ignores the selector.
974 let lpad_ty = cx.type_struct(&[cx.type_i8p(), cx.type_i32()], false);
975 let vals = catch.landing_pad(lpad_ty, bx.cx().eh_personality(), 1);
976 catch.add_clause(vals, bx.cx().const_null(cx.type_i8p()));
977 let ptr = catch.extract_value(vals, 0);
978 let ptr_align = bx.tcx().data_layout.pointer_align;
979 catch.store(ptr, catch.bitcast(local_ptr, cx.type_ptr_to(cx.type_i8p())), ptr_align);
980 catch.ret(cx.const_i32(1));
983 // Note that no invoke is used here because by definition this function
984 // can't panic (that's what it's catching).
985 let ret = bx.call(llfn, &[func, data, local_ptr], None);
986 let i32_align = bx.tcx().data_layout.i32_align;
987 bx.store(ret, dest, i32_align);
990 // Helper function to give a Block to a closure to codegen a shim function.
991 // This is currently primarily used for the `try` intrinsic functions above.
992 fn gen_fn<'ll, 'tcx>(
993 cx: &CodegenCx<'ll, 'tcx>,
995 inputs: Vec<Ty<'tcx>>,
997 codegen: &mut dyn FnMut(Builder<'_, 'll, 'tcx>),
999 let rust_fn_sig = ty::Binder::bind(cx.tcx.mk_fn_sig(
1003 hir::Unsafety::Unsafe,
1006 let llfn = cx.define_internal_fn(name, rust_fn_sig);
1007 attributes::from_fn_attrs(cx, llfn, None);
1008 let bx = Builder::new_block(cx, llfn, "entry-block");
1013 // Helper function used to get a handle to the `__rust_try` function used to
1014 // catch exceptions.
1016 // This function is only generated once and is then cached.
1017 fn get_rust_try_fn<'ll, 'tcx>(
1018 cx: &CodegenCx<'ll, 'tcx>,
1019 codegen: &mut dyn FnMut(Builder<'_, 'll, 'tcx>),
1021 if let Some(llfn) = cx.rust_try_fn.get() {
1025 // Define the type up front for the signature of the rust_try function.
1027 let i8p = tcx.mk_mut_ptr(tcx.types.i8);
1028 let fn_ty = tcx.mk_fn_ptr(ty::Binder::bind(tcx.mk_fn_sig(
1032 hir::Unsafety::Unsafe,
1035 let output = tcx.types.i32;
1036 let rust_try = gen_fn(cx, "__rust_try", vec![fn_ty, i8p, i8p], output, codegen);
1037 cx.rust_try_fn.set(Some(rust_try));
1041 fn span_invalid_monomorphization_error(a: &Session, b: Span, c: &str) {
1042 span_err!(a, b, E0511, "{}", c);
1045 fn generic_simd_intrinsic(
1046 bx: &Builder<'a, 'll, 'tcx>,
1048 callee_ty: Ty<'tcx>,
1049 args: &[OperandRef<'tcx, &'ll Value>],
1051 llret_ty: &'ll Type,
1053 ) -> Result<&'ll Value, ()> {
1054 // macros for error handling:
1055 macro_rules! emit_error {
1059 ($msg: tt, $($fmt: tt)*) => {
1060 span_invalid_monomorphization_error(
1061 bx.cx().sess(), span,
1062 &format!(concat!("invalid monomorphization of `{}` intrinsic: ", $msg),
1067 macro_rules! return_error {
1070 emit_error!($($fmt)*);
1076 macro_rules! require {
1077 ($cond: expr, $($fmt: tt)*) => {
1079 return_error!($($fmt)*);
1084 macro_rules! require_simd {
1085 ($ty: expr, $position: expr) => {
1086 require!($ty.is_simd(), "expected SIMD {} type, found non-SIMD `{}`", $position, $ty)
1091 let sig = tcx.normalize_erasing_late_bound_regions(
1092 ty::ParamEnv::reveal_all(),
1093 &callee_ty.fn_sig(tcx),
1095 let arg_tys = sig.inputs();
1097 // every intrinsic takes a SIMD vector as its first argument
1098 require_simd!(arg_tys[0], "input");
1099 let in_ty = arg_tys[0];
1100 let in_elem = arg_tys[0].simd_type(tcx);
1101 let in_len = arg_tys[0].simd_size(tcx);
1103 let comparison = match name {
1104 "simd_eq" => Some(hir::BinOpKind::Eq),
1105 "simd_ne" => Some(hir::BinOpKind::Ne),
1106 "simd_lt" => Some(hir::BinOpKind::Lt),
1107 "simd_le" => Some(hir::BinOpKind::Le),
1108 "simd_gt" => Some(hir::BinOpKind::Gt),
1109 "simd_ge" => Some(hir::BinOpKind::Ge),
1113 if let Some(cmp_op) = comparison {
1114 require_simd!(ret_ty, "return");
1116 let out_len = ret_ty.simd_size(tcx);
1117 require!(in_len == out_len,
1118 "expected return type with length {} (same as input type `{}`), \
1119 found `{}` with length {}",
1122 require!(bx.cx().type_kind(bx.cx().element_type(llret_ty)) == TypeKind::Integer,
1123 "expected return type with integer elements, found `{}` with non-integer `{}`",
1125 ret_ty.simd_type(tcx));
1127 return Ok(compare_simd_types(bx,
1128 args[0].immediate(),
1129 args[1].immediate(),
1135 if name.starts_with("simd_shuffle") {
1136 let n: usize = name["simd_shuffle".len()..].parse().unwrap_or_else(|_|
1137 span_bug!(span, "bad `simd_shuffle` instruction only caught in codegen?"));
1139 require_simd!(ret_ty, "return");
1141 let out_len = ret_ty.simd_size(tcx);
1142 require!(out_len == n,
1143 "expected return type of length {}, found `{}` with length {}",
1144 n, ret_ty, out_len);
1145 require!(in_elem == ret_ty.simd_type(tcx),
1146 "expected return element type `{}` (element of input `{}`), \
1147 found `{}` with element type `{}`",
1149 ret_ty, ret_ty.simd_type(tcx));
1151 let total_len = in_len as u128 * 2;
1153 let vector = args[2].immediate();
1155 let indices: Option<Vec<_>> = (0..n)
1158 let val = bx.cx().const_get_elt(vector, i as u64);
1159 match bx.cx().const_to_opt_u128(val, true) {
1161 emit_error!("shuffle index #{} is not a constant", arg_idx);
1164 Some(idx) if idx >= total_len => {
1165 emit_error!("shuffle index #{} is out of bounds (limit {})",
1166 arg_idx, total_len);
1169 Some(idx) => Some(bx.cx().const_i32(idx as i32)),
1173 let indices = match indices {
1175 None => return Ok(bx.cx().const_null(llret_ty))
1178 return Ok(bx.shuffle_vector(args[0].immediate(),
1179 args[1].immediate(),
1180 bx.cx().const_vector(&indices)))
1183 if name == "simd_insert" {
1184 require!(in_elem == arg_tys[2],
1185 "expected inserted type `{}` (element of input `{}`), found `{}`",
1186 in_elem, in_ty, arg_tys[2]);
1187 return Ok(bx.insert_element(args[0].immediate(),
1188 args[2].immediate(),
1189 args[1].immediate()))
1191 if name == "simd_extract" {
1192 require!(ret_ty == in_elem,
1193 "expected return type `{}` (element of input `{}`), found `{}`",
1194 in_elem, in_ty, ret_ty);
1195 return Ok(bx.extract_element(args[0].immediate(), args[1].immediate()))
1198 if name == "simd_select" {
1199 let m_elem_ty = in_elem;
1201 let v_len = arg_tys[1].simd_size(tcx);
1202 require!(m_len == v_len,
1203 "mismatched lengths: mask length `{}` != other vector length `{}`",
1206 match m_elem_ty.sty {
1208 _ => return_error!("mask element type is `{}`, expected `i_`", m_elem_ty)
1210 // truncate the mask to a vector of i1s
1211 let i1 = bx.cx().type_i1();
1212 let i1xn = bx.cx().type_vector(i1, m_len as u64);
1213 let m_i1s = bx.trunc(args[0].immediate(), i1xn);
1214 return Ok(bx.select(m_i1s, args[1].immediate(), args[2].immediate()));
1217 fn simd_simple_float_intrinsic(
1219 in_elem: &::rustc::ty::TyS,
1220 in_ty: &::rustc::ty::TyS,
1222 bx: &Builder<'a, 'll, 'tcx>,
1224 args: &[OperandRef<'tcx, &'ll Value>],
1225 ) -> Result<&'ll Value, ()> {
1226 macro_rules! emit_error {
1230 ($msg: tt, $($fmt: tt)*) => {
1231 span_invalid_monomorphization_error(
1232 bx.cx().sess(), span,
1233 &format!(concat!("invalid monomorphization of `{}` intrinsic: ", $msg),
1237 macro_rules! return_error {
1240 emit_error!($($fmt)*);
1245 let ety = match in_elem.sty {
1246 ty::Float(f) if f.bit_width() == 32 => {
1247 if in_len < 2 || in_len > 16 {
1249 "unsupported floating-point vector `{}` with length `{}` \
1250 out-of-range [2, 16]",
1255 ty::Float(f) if f.bit_width() == 64 => {
1256 if in_len < 2 || in_len > 8 {
1257 return_error!("unsupported floating-point vector `{}` with length `{}` \
1258 out-of-range [2, 8]",
1264 return_error!("unsupported element type `{}` of floating-point vector `{}`",
1268 return_error!("`{}` is not a floating-point type", in_ty);
1272 let llvm_name = &format!("llvm.{0}.v{1}{2}", name, in_len, ety);
1273 let intrinsic = bx.cx().get_intrinsic(&llvm_name);
1274 let c = bx.call(intrinsic,
1275 &args.iter().map(|arg| arg.immediate()).collect::<Vec<_>>(),
1277 unsafe { llvm::LLVMRustSetHasUnsafeAlgebra(c) };
1283 return simd_simple_float_intrinsic("sqrt", in_elem, in_ty, in_len, bx, span, args);
1286 return simd_simple_float_intrinsic("sin", in_elem, in_ty, in_len, bx, span, args);
1289 return simd_simple_float_intrinsic("cos", in_elem, in_ty, in_len, bx, span, args);
1292 return simd_simple_float_intrinsic("fabs", in_elem, in_ty, in_len, bx, span, args);
1295 return simd_simple_float_intrinsic("floor", in_elem, in_ty, in_len, bx, span, args);
1298 return simd_simple_float_intrinsic("ceil", in_elem, in_ty, in_len, bx, span, args);
1301 return simd_simple_float_intrinsic("exp", in_elem, in_ty, in_len, bx, span, args);
1304 return simd_simple_float_intrinsic("exp2", in_elem, in_ty, in_len, bx, span, args);
1307 return simd_simple_float_intrinsic("log10", in_elem, in_ty, in_len, bx, span, args);
1310 return simd_simple_float_intrinsic("log2", in_elem, in_ty, in_len, bx, span, args);
1313 return simd_simple_float_intrinsic("log", in_elem, in_ty, in_len, bx, span, args);
1316 return simd_simple_float_intrinsic("powi", in_elem, in_ty, in_len, bx, span, args);
1319 return simd_simple_float_intrinsic("pow", in_elem, in_ty, in_len, bx, span, args);
1322 return simd_simple_float_intrinsic("fma", in_elem, in_ty, in_len, bx, span, args);
1324 _ => { /* fallthrough */ }
1328 // https://github.com/llvm-mirror/llvm/blob/master/include/llvm/IR/Function.h#L182
1329 // https://github.com/llvm-mirror/llvm/blob/master/include/llvm/IR/Intrinsics.h#L81
1330 fn llvm_vector_str(elem_ty: ty::Ty, vec_len: usize, no_pointers: usize) -> String {
1331 let p0s: String = "p0".repeat(no_pointers);
1333 ty::Int(v) => format!("v{}{}i{}", vec_len, p0s, v.bit_width().unwrap()),
1334 ty::Uint(v) => format!("v{}{}i{}", vec_len, p0s, v.bit_width().unwrap()),
1335 ty::Float(v) => format!("v{}{}f{}", vec_len, p0s, v.bit_width()),
1336 _ => unreachable!(),
1340 fn llvm_vector_ty(cx: &CodegenCx<'ll, '_>, elem_ty: ty::Ty, vec_len: usize,
1341 mut no_pointers: usize) -> &'ll Type {
1342 // FIXME: use cx.layout_of(ty).llvm_type() ?
1343 let mut elem_ty = match elem_ty.sty {
1344 ty::Int(v) => cx.type_int_from_ty( v),
1345 ty::Uint(v) => cx.type_uint_from_ty( v),
1346 ty::Float(v) => cx.type_float_from_ty( v),
1347 _ => unreachable!(),
1349 while no_pointers > 0 {
1350 elem_ty = cx.type_ptr_to(elem_ty);
1353 cx.type_vector(elem_ty, vec_len as u64)
1357 if name == "simd_gather" {
1358 // simd_gather(values: <N x T>, pointers: <N x *_ T>,
1359 // mask: <N x i{M}>) -> <N x T>
1360 // * N: number of elements in the input vectors
1361 // * T: type of the element to load
1362 // * M: any integer width is supported, will be truncated to i1
1364 // All types must be simd vector types
1365 require_simd!(in_ty, "first");
1366 require_simd!(arg_tys[1], "second");
1367 require_simd!(arg_tys[2], "third");
1368 require_simd!(ret_ty, "return");
1370 // Of the same length:
1371 require!(in_len == arg_tys[1].simd_size(tcx),
1372 "expected {} argument with length {} (same as input type `{}`), \
1373 found `{}` with length {}", "second", in_len, in_ty, arg_tys[1],
1374 arg_tys[1].simd_size(tcx));
1375 require!(in_len == arg_tys[2].simd_size(tcx),
1376 "expected {} argument with length {} (same as input type `{}`), \
1377 found `{}` with length {}", "third", in_len, in_ty, arg_tys[2],
1378 arg_tys[2].simd_size(tcx));
1380 // The return type must match the first argument type
1381 require!(ret_ty == in_ty,
1382 "expected return type `{}`, found `{}`",
1385 // This counts how many pointers
1386 fn ptr_count(t: ty::Ty) -> usize {
1388 ty::RawPtr(p) => 1 + ptr_count(p.ty),
1394 fn non_ptr(t: ty::Ty) -> ty::Ty {
1396 ty::RawPtr(p) => non_ptr(p.ty),
1401 // The second argument must be a simd vector with an element type that's a pointer
1402 // to the element type of the first argument
1403 let (pointer_count, underlying_ty) = match arg_tys[1].simd_type(tcx).sty {
1404 ty::RawPtr(p) if p.ty == in_elem => (ptr_count(arg_tys[1].simd_type(tcx)),
1405 non_ptr(arg_tys[1].simd_type(tcx))),
1407 require!(false, "expected element type `{}` of second argument `{}` \
1408 to be a pointer to the element type `{}` of the first \
1409 argument `{}`, found `{}` != `*_ {}`",
1410 arg_tys[1].simd_type(tcx).sty, arg_tys[1], in_elem, in_ty,
1411 arg_tys[1].simd_type(tcx).sty, in_elem);
1415 assert!(pointer_count > 0);
1416 assert_eq!(pointer_count - 1, ptr_count(arg_tys[0].simd_type(tcx)));
1417 assert_eq!(underlying_ty, non_ptr(arg_tys[0].simd_type(tcx)));
1419 // The element type of the third argument must be a signed integer type of any width:
1420 match arg_tys[2].simd_type(tcx).sty {
1423 require!(false, "expected element type `{}` of third argument `{}` \
1424 to be a signed integer type",
1425 arg_tys[2].simd_type(tcx).sty, arg_tys[2]);
1429 // Alignment of T, must be a constant integer value:
1430 let alignment_ty = bx.cx().type_i32();
1431 let alignment = bx.cx().const_i32(bx.cx().align_of(in_elem).abi() as i32);
1433 // Truncate the mask vector to a vector of i1s:
1434 let (mask, mask_ty) = {
1435 let i1 = bx.cx().type_i1();
1436 let i1xn = bx.cx().type_vector(i1, in_len as u64);
1437 (bx.trunc(args[2].immediate(), i1xn), i1xn)
1440 // Type of the vector of pointers:
1441 let llvm_pointer_vec_ty = llvm_vector_ty(bx.cx(), underlying_ty, in_len, pointer_count);
1442 let llvm_pointer_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count);
1444 // Type of the vector of elements:
1445 let llvm_elem_vec_ty = llvm_vector_ty(bx.cx(), underlying_ty, in_len, pointer_count - 1);
1446 let llvm_elem_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count - 1);
1448 let llvm_intrinsic = format!("llvm.masked.gather.{}.{}",
1449 llvm_elem_vec_str, llvm_pointer_vec_str);
1450 let f = bx.cx().declare_cfn(&llvm_intrinsic,
1451 bx.cx().type_func(&[
1452 llvm_pointer_vec_ty,
1455 llvm_elem_vec_ty], llvm_elem_vec_ty));
1456 llvm::SetUnnamedAddr(f, false);
1457 let v = bx.call(f, &[args[1].immediate(), alignment, mask, args[0].immediate()],
1462 if name == "simd_scatter" {
1463 // simd_scatter(values: <N x T>, pointers: <N x *mut T>,
1464 // mask: <N x i{M}>) -> ()
1465 // * N: number of elements in the input vectors
1466 // * T: type of the element to load
1467 // * M: any integer width is supported, will be truncated to i1
1469 // All types must be simd vector types
1470 require_simd!(in_ty, "first");
1471 require_simd!(arg_tys[1], "second");
1472 require_simd!(arg_tys[2], "third");
1474 // Of the same length:
1475 require!(in_len == arg_tys[1].simd_size(tcx),
1476 "expected {} argument with length {} (same as input type `{}`), \
1477 found `{}` with length {}", "second", in_len, in_ty, arg_tys[1],
1478 arg_tys[1].simd_size(tcx));
1479 require!(in_len == arg_tys[2].simd_size(tcx),
1480 "expected {} argument with length {} (same as input type `{}`), \
1481 found `{}` with length {}", "third", in_len, in_ty, arg_tys[2],
1482 arg_tys[2].simd_size(tcx));
1484 // This counts how many pointers
1485 fn ptr_count(t: ty::Ty) -> usize {
1487 ty::RawPtr(p) => 1 + ptr_count(p.ty),
1493 fn non_ptr(t: ty::Ty) -> ty::Ty {
1495 ty::RawPtr(p) => non_ptr(p.ty),
1500 // The second argument must be a simd vector with an element type that's a pointer
1501 // to the element type of the first argument
1502 let (pointer_count, underlying_ty) = match arg_tys[1].simd_type(tcx).sty {
1503 ty::RawPtr(p) if p.ty == in_elem && p.mutbl == hir::MutMutable
1504 => (ptr_count(arg_tys[1].simd_type(tcx)),
1505 non_ptr(arg_tys[1].simd_type(tcx))),
1507 require!(false, "expected element type `{}` of second argument `{}` \
1508 to be a pointer to the element type `{}` of the first \
1509 argument `{}`, found `{}` != `*mut {}`",
1510 arg_tys[1].simd_type(tcx).sty, arg_tys[1], in_elem, in_ty,
1511 arg_tys[1].simd_type(tcx).sty, in_elem);
1515 assert!(pointer_count > 0);
1516 assert_eq!(pointer_count - 1, ptr_count(arg_tys[0].simd_type(tcx)));
1517 assert_eq!(underlying_ty, non_ptr(arg_tys[0].simd_type(tcx)));
1519 // The element type of the third argument must be a signed integer type of any width:
1520 match arg_tys[2].simd_type(tcx).sty {
1523 require!(false, "expected element type `{}` of third argument `{}` \
1524 to be a signed integer type",
1525 arg_tys[2].simd_type(tcx).sty, arg_tys[2]);
1529 // Alignment of T, must be a constant integer value:
1530 let alignment_ty = bx.cx().type_i32();
1531 let alignment = bx.cx().const_i32(bx.cx().align_of(in_elem).abi() as i32);
1533 // Truncate the mask vector to a vector of i1s:
1534 let (mask, mask_ty) = {
1535 let i1 = bx.cx().type_i1();
1536 let i1xn = bx.cx().type_vector(i1, in_len as u64);
1537 (bx.trunc(args[2].immediate(), i1xn), i1xn)
1540 let ret_t = bx.cx().type_void();
1542 // Type of the vector of pointers:
1543 let llvm_pointer_vec_ty = llvm_vector_ty(bx.cx(), underlying_ty, in_len, pointer_count);
1544 let llvm_pointer_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count);
1546 // Type of the vector of elements:
1547 let llvm_elem_vec_ty = llvm_vector_ty(bx.cx(), underlying_ty, in_len, pointer_count - 1);
1548 let llvm_elem_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count - 1);
1550 let llvm_intrinsic = format!("llvm.masked.scatter.{}.{}",
1551 llvm_elem_vec_str, llvm_pointer_vec_str);
1552 let f = bx.cx().declare_cfn(&llvm_intrinsic,
1553 bx.cx().type_func(&[llvm_elem_vec_ty,
1554 llvm_pointer_vec_ty,
1557 llvm::SetUnnamedAddr(f, false);
1558 let v = bx.call(f, &[args[0].immediate(), args[1].immediate(), alignment, mask],
1563 macro_rules! arith_red {
1564 ($name:tt : $integer_reduce:ident, $float_reduce:ident, $ordered:expr) => {
1566 require!(ret_ty == in_elem,
1567 "expected return type `{}` (element of input `{}`), found `{}`",
1568 in_elem, in_ty, ret_ty);
1569 return match in_elem.sty {
1570 ty::Int(_) | ty::Uint(_) => {
1571 let r = bx.$integer_reduce(args[0].immediate());
1573 // if overflow occurs, the result is the
1574 // mathematical result modulo 2^n:
1575 if name.contains("mul") {
1576 Ok(bx.mul(args[1].immediate(), r))
1578 Ok(bx.add(args[1].immediate(), r))
1581 Ok(bx.$integer_reduce(args[0].immediate()))
1585 // ordered arithmetic reductions take an accumulator
1586 let acc = if $ordered {
1587 let acc = args[1].immediate();
1588 // FIXME: https://bugs.llvm.org/show_bug.cgi?id=36734
1589 // * if the accumulator of the fadd isn't 0, incorrect
1590 // code is generated
1591 // * if the accumulator of the fmul isn't 1, incorrect
1592 // code is generated
1593 match bx.cx().const_get_real(acc) {
1594 None => return_error!("accumulator of {} is not a constant", $name),
1595 Some((v, loses_info)) => {
1596 if $name.contains("mul") && v != 1.0_f64 {
1597 return_error!("accumulator of {} is not 1.0", $name);
1598 } else if $name.contains("add") && v != 0.0_f64 {
1599 return_error!("accumulator of {} is not 0.0", $name);
1600 } else if loses_info {
1601 return_error!("accumulator of {} loses information", $name);
1607 // unordered arithmetic reductions do not:
1608 match f.bit_width() {
1609 32 => bx.cx().const_undef(bx.cx().type_f32()),
1610 64 => bx.cx().const_undef(bx.cx().type_f64()),
1613 unsupported {} from `{}` with element `{}` of size `{}` to `{}`"#,
1614 $name, in_ty, in_elem, v, ret_ty
1619 Ok(bx.$float_reduce(acc, args[0].immediate()))
1623 "unsupported {} from `{}` with element `{}` to `{}`",
1624 $name, in_ty, in_elem, ret_ty
1632 arith_red!("simd_reduce_add_ordered": vector_reduce_add, vector_reduce_fadd_fast, true);
1633 arith_red!("simd_reduce_mul_ordered": vector_reduce_mul, vector_reduce_fmul_fast, true);
1634 arith_red!("simd_reduce_add_unordered": vector_reduce_add, vector_reduce_fadd_fast, false);
1635 arith_red!("simd_reduce_mul_unordered": vector_reduce_mul, vector_reduce_fmul_fast, false);
1637 macro_rules! minmax_red {
1638 ($name:tt: $int_red:ident, $float_red:ident) => {
1640 require!(ret_ty == in_elem,
1641 "expected return type `{}` (element of input `{}`), found `{}`",
1642 in_elem, in_ty, ret_ty);
1643 return match in_elem.sty {
1645 Ok(bx.$int_red(args[0].immediate(), true))
1648 Ok(bx.$int_red(args[0].immediate(), false))
1651 Ok(bx.$float_red(args[0].immediate()))
1654 return_error!("unsupported {} from `{}` with element `{}` to `{}`",
1655 $name, in_ty, in_elem, ret_ty)
1663 minmax_red!("simd_reduce_min": vector_reduce_min, vector_reduce_fmin);
1664 minmax_red!("simd_reduce_max": vector_reduce_max, vector_reduce_fmax);
1666 minmax_red!("simd_reduce_min_nanless": vector_reduce_min, vector_reduce_fmin_fast);
1667 minmax_red!("simd_reduce_max_nanless": vector_reduce_max, vector_reduce_fmax_fast);
1669 macro_rules! bitwise_red {
1670 ($name:tt : $red:ident, $boolean:expr) => {
1672 let input = if !$boolean {
1673 require!(ret_ty == in_elem,
1674 "expected return type `{}` (element of input `{}`), found `{}`",
1675 in_elem, in_ty, ret_ty);
1679 ty::Int(_) | ty::Uint(_) => {},
1681 return_error!("unsupported {} from `{}` with element `{}` to `{}`",
1682 $name, in_ty, in_elem, ret_ty)
1686 // boolean reductions operate on vectors of i1s:
1687 let i1 = bx.cx().type_i1();
1688 let i1xn = bx.cx().type_vector(i1, in_len as u64);
1689 bx.trunc(args[0].immediate(), i1xn)
1691 return match in_elem.sty {
1692 ty::Int(_) | ty::Uint(_) => {
1693 let r = bx.$red(input);
1698 bx.zext(r, bx.cx().type_bool())
1703 return_error!("unsupported {} from `{}` with element `{}` to `{}`",
1704 $name, in_ty, in_elem, ret_ty)
1711 bitwise_red!("simd_reduce_and": vector_reduce_and, false);
1712 bitwise_red!("simd_reduce_or": vector_reduce_or, false);
1713 bitwise_red!("simd_reduce_xor": vector_reduce_xor, false);
1714 bitwise_red!("simd_reduce_all": vector_reduce_and, true);
1715 bitwise_red!("simd_reduce_any": vector_reduce_or, true);
1717 if name == "simd_cast" {
1718 require_simd!(ret_ty, "return");
1719 let out_len = ret_ty.simd_size(tcx);
1720 require!(in_len == out_len,
1721 "expected return type with length {} (same as input type `{}`), \
1722 found `{}` with length {}",
1725 // casting cares about nominal type, not just structural type
1726 let out_elem = ret_ty.simd_type(tcx);
1728 if in_elem == out_elem { return Ok(args[0].immediate()); }
1730 enum Style { Float, Int(/* is signed? */ bool), Unsupported }
1732 let (in_style, in_width) = match in_elem.sty {
1733 // vectors of pointer-sized integers should've been
1734 // disallowed before here, so this unwrap is safe.
1735 ty::Int(i) => (Style::Int(true), i.bit_width().unwrap()),
1736 ty::Uint(u) => (Style::Int(false), u.bit_width().unwrap()),
1737 ty::Float(f) => (Style::Float, f.bit_width()),
1738 _ => (Style::Unsupported, 0)
1740 let (out_style, out_width) = match out_elem.sty {
1741 ty::Int(i) => (Style::Int(true), i.bit_width().unwrap()),
1742 ty::Uint(u) => (Style::Int(false), u.bit_width().unwrap()),
1743 ty::Float(f) => (Style::Float, f.bit_width()),
1744 _ => (Style::Unsupported, 0)
1747 match (in_style, out_style) {
1748 (Style::Int(in_is_signed), Style::Int(_)) => {
1749 return Ok(match in_width.cmp(&out_width) {
1750 Ordering::Greater => bx.trunc(args[0].immediate(), llret_ty),
1751 Ordering::Equal => args[0].immediate(),
1752 Ordering::Less => if in_is_signed {
1753 bx.sext(args[0].immediate(), llret_ty)
1755 bx.zext(args[0].immediate(), llret_ty)
1759 (Style::Int(in_is_signed), Style::Float) => {
1760 return Ok(if in_is_signed {
1761 bx.sitofp(args[0].immediate(), llret_ty)
1763 bx.uitofp(args[0].immediate(), llret_ty)
1766 (Style::Float, Style::Int(out_is_signed)) => {
1767 return Ok(if out_is_signed {
1768 bx.fptosi(args[0].immediate(), llret_ty)
1770 bx.fptoui(args[0].immediate(), llret_ty)
1773 (Style::Float, Style::Float) => {
1774 return Ok(match in_width.cmp(&out_width) {
1775 Ordering::Greater => bx.fptrunc(args[0].immediate(), llret_ty),
1776 Ordering::Equal => args[0].immediate(),
1777 Ordering::Less => bx.fpext(args[0].immediate(), llret_ty)
1780 _ => {/* Unsupported. Fallthrough. */}
1783 "unsupported cast from `{}` with element `{}` to `{}` with element `{}`",
1787 macro_rules! arith {
1788 ($($name: ident: $($($p: ident),* => $call: ident),*;)*) => {
1789 $(if name == stringify!($name) {
1791 $($(ty::$p(_))|* => {
1792 return Ok(bx.$call(args[0].immediate(), args[1].immediate()))
1797 "unsupported operation on `{}` with element `{}`",
1804 simd_add: Uint, Int => add, Float => fadd;
1805 simd_sub: Uint, Int => sub, Float => fsub;
1806 simd_mul: Uint, Int => mul, Float => fmul;
1807 simd_div: Uint => udiv, Int => sdiv, Float => fdiv;
1808 simd_rem: Uint => urem, Int => srem, Float => frem;
1809 simd_shl: Uint, Int => shl;
1810 simd_shr: Uint => lshr, Int => ashr;
1811 simd_and: Uint, Int => and;
1812 simd_or: Uint, Int => or;
1813 simd_xor: Uint, Int => xor;
1814 simd_fmax: Float => maxnum;
1815 simd_fmin: Float => minnum;
1817 span_bug!(span, "unknown SIMD intrinsic");
1820 // Returns the width of an int Ty, and if it's signed or not
1821 // Returns None if the type is not an integer
1822 // FIXME: there’s multiple of this functions, investigate using some of the already existing
1824 fn int_type_width_signed(ty: Ty, cx: &CodegenCx) -> Option<(u64, bool)> {
1826 ty::Int(t) => Some((match t {
1827 ast::IntTy::Isize => cx.tcx.sess.target.isize_ty.bit_width().unwrap() as u64,
1828 ast::IntTy::I8 => 8,
1829 ast::IntTy::I16 => 16,
1830 ast::IntTy::I32 => 32,
1831 ast::IntTy::I64 => 64,
1832 ast::IntTy::I128 => 128,
1834 ty::Uint(t) => Some((match t {
1835 ast::UintTy::Usize => cx.tcx.sess.target.usize_ty.bit_width().unwrap() as u64,
1836 ast::UintTy::U8 => 8,
1837 ast::UintTy::U16 => 16,
1838 ast::UintTy::U32 => 32,
1839 ast::UintTy::U64 => 64,
1840 ast::UintTy::U128 => 128,
1846 // Returns the width of a float TypeVariant
1847 // Returns None if the type is not a float
1848 fn float_type_width<'tcx>(sty: &ty::TyKind<'tcx>) -> Option<u64> {
1850 ty::Float(t) => Some(t.bit_width() as u64),