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;
26 use type_of::LayoutLlvmExt;
27 use rustc::ty::{self, Ty};
28 use rustc::ty::layout::LayoutOf;
31 use syntax::symbol::Symbol;
32 use builder::{Builder, MemFlags};
36 BuilderMethods, ConstMethods, BaseTypeMethods, DerivedTypeMethods, DerivedIntrinsicMethods,
40 use rustc::session::Session;
43 use std::cmp::Ordering;
46 fn get_simple_intrinsic(cx: &CodegenCx<'ll, '_>, name: &str) -> Option<&'ll Value> {
47 let llvm_name = match name {
48 "sqrtf32" => "llvm.sqrt.f32",
49 "sqrtf64" => "llvm.sqrt.f64",
50 "powif32" => "llvm.powi.f32",
51 "powif64" => "llvm.powi.f64",
52 "sinf32" => "llvm.sin.f32",
53 "sinf64" => "llvm.sin.f64",
54 "cosf32" => "llvm.cos.f32",
55 "cosf64" => "llvm.cos.f64",
56 "powf32" => "llvm.pow.f32",
57 "powf64" => "llvm.pow.f64",
58 "expf32" => "llvm.exp.f32",
59 "expf64" => "llvm.exp.f64",
60 "exp2f32" => "llvm.exp2.f32",
61 "exp2f64" => "llvm.exp2.f64",
62 "logf32" => "llvm.log.f32",
63 "logf64" => "llvm.log.f64",
64 "log10f32" => "llvm.log10.f32",
65 "log10f64" => "llvm.log10.f64",
66 "log2f32" => "llvm.log2.f32",
67 "log2f64" => "llvm.log2.f64",
68 "fmaf32" => "llvm.fma.f32",
69 "fmaf64" => "llvm.fma.f64",
70 "fabsf32" => "llvm.fabs.f32",
71 "fabsf64" => "llvm.fabs.f64",
72 "copysignf32" => "llvm.copysign.f32",
73 "copysignf64" => "llvm.copysign.f64",
74 "floorf32" => "llvm.floor.f32",
75 "floorf64" => "llvm.floor.f64",
76 "ceilf32" => "llvm.ceil.f32",
77 "ceilf64" => "llvm.ceil.f64",
78 "truncf32" => "llvm.trunc.f32",
79 "truncf64" => "llvm.trunc.f64",
80 "rintf32" => "llvm.rint.f32",
81 "rintf64" => "llvm.rint.f64",
82 "nearbyintf32" => "llvm.nearbyint.f32",
83 "nearbyintf64" => "llvm.nearbyint.f64",
84 "roundf32" => "llvm.round.f32",
85 "roundf64" => "llvm.round.f64",
86 "assume" => "llvm.assume",
87 "abort" => "llvm.trap",
90 Some(cx.get_intrinsic(&llvm_name))
93 /// Remember to add all intrinsics here, in librustc_typeck/check/mod.rs,
94 /// and in libcore/intrinsics.rs; if you need access to any llvm intrinsics,
95 /// add them to librustc_codegen_llvm/context.rs
96 pub fn codegen_intrinsic_call(
97 bx: &Builder<'a, 'll, 'tcx>,
99 fn_ty: &FnType<'tcx, Ty<'tcx>>,
100 args: &[OperandRef<'tcx, &'ll Value>],
101 llresult: &'ll Value,
107 let (def_id, substs) = match callee_ty.sty {
108 ty::FnDef(def_id, substs) => (def_id, substs),
109 _ => bug!("expected fn item type, found {}", callee_ty)
112 let sig = callee_ty.fn_sig(tcx);
113 let sig = tcx.normalize_erasing_late_bound_regions(ty::ParamEnv::reveal_all(), &sig);
114 let arg_tys = sig.inputs();
115 let ret_ty = sig.output();
116 let name = &*tcx.item_name(def_id).as_str();
118 let llret_ty = cx.layout_of(ret_ty).llvm_type(cx);
119 let result = PlaceRef::new_sized(llresult, fn_ty.ret.layout, fn_ty.ret.layout.align);
121 let simple = get_simple_intrinsic(cx, name);
122 let llval = match name {
123 _ if simple.is_some() => {
124 bx.call(simple.unwrap(),
125 &args.iter().map(|arg| arg.immediate()).collect::<Vec<_>>(),
132 let expect = cx.get_intrinsic(&("llvm.expect.i1"));
133 bx.call(expect, &[args[0].immediate(), bx.cx().const_bool(true)], None)
136 let expect = cx.get_intrinsic(&("llvm.expect.i1"));
137 bx.call(expect, &[args[0].immediate(), bx.cx().const_bool(false)], None)
140 try_intrinsic(bx, cx,
148 let llfn = cx.get_intrinsic(&("llvm.debugtrap"));
149 bx.call(llfn, &[], None)
152 let tp_ty = substs.type_at(0);
153 cx.const_usize(cx.size_of(tp_ty).bytes())
156 let tp_ty = substs.type_at(0);
157 if let OperandValue::Pair(_, meta) = args[0].val {
159 glue::size_and_align_of_dst(bx, tp_ty, Some(meta));
162 cx.const_usize(cx.size_of(tp_ty).bytes())
166 let tp_ty = substs.type_at(0);
167 cx.const_usize(cx.align_of(tp_ty).abi())
169 "min_align_of_val" => {
170 let tp_ty = substs.type_at(0);
171 if let OperandValue::Pair(_, meta) = args[0].val {
173 glue::size_and_align_of_dst(bx, tp_ty, Some(meta));
176 cx.const_usize(cx.align_of(tp_ty).abi())
180 let tp_ty = substs.type_at(0);
181 cx.const_usize(cx.align_of(tp_ty).pref())
184 let tp_ty = substs.type_at(0);
185 let ty_name = Symbol::intern(&tp_ty.to_string()).as_str();
186 cx.const_str_slice(ty_name)
189 cx.const_u64(cx.tcx.type_id_hash(substs.type_at(0)))
192 let ty = substs.type_at(0);
193 if !cx.layout_of(ty).is_zst() {
194 // Just zero out the stack slot.
195 // If we store a zero constant, LLVM will drown in vreg allocation for large data
196 // structures, and the generated code will be awful. (A telltale sign of this is
197 // large quantities of `mov [byte ptr foo],0` in the generated code.)
209 // Effectively no-ops
210 "uninit" | "forget" => {
214 let tp_ty = substs.type_at(0);
216 cx.const_bool(bx.cx().type_needs_drop(tp_ty))
219 let ptr = args[0].immediate();
220 let offset = args[1].immediate();
221 bx.inbounds_gep(ptr, &[offset])
224 let ptr = args[0].immediate();
225 let offset = args[1].immediate();
226 bx.gep(ptr, &[offset])
229 "copy_nonoverlapping" => {
230 copy_intrinsic(bx, false, false, substs.type_at(0),
231 args[1].immediate(), args[0].immediate(), args[2].immediate());
235 copy_intrinsic(bx, true, false, substs.type_at(0),
236 args[1].immediate(), args[0].immediate(), args[2].immediate());
240 memset_intrinsic(bx, false, substs.type_at(0),
241 args[0].immediate(), args[1].immediate(), args[2].immediate());
245 "volatile_copy_nonoverlapping_memory" => {
246 copy_intrinsic(bx, false, true, substs.type_at(0),
247 args[0].immediate(), args[1].immediate(), args[2].immediate());
250 "volatile_copy_memory" => {
251 copy_intrinsic(bx, true, true, substs.type_at(0),
252 args[0].immediate(), args[1].immediate(), args[2].immediate());
255 "volatile_set_memory" => {
256 memset_intrinsic(bx, true, substs.type_at(0),
257 args[0].immediate(), args[1].immediate(), args[2].immediate());
260 "volatile_load" | "unaligned_volatile_load" => {
261 let tp_ty = substs.type_at(0);
262 let mut ptr = args[0].immediate();
263 if let PassMode::Cast(ty) = fn_ty.ret.mode {
264 ptr = bx.pointercast(ptr, bx.cx().type_ptr_to(ty.llvm_type(cx)));
266 let load = bx.volatile_load(ptr);
267 let align = if name == "unaligned_volatile_load" {
270 cx.align_of(tp_ty).abi() as u32
273 llvm::LLVMSetAlignment(load, align);
275 to_immediate(bx, load, cx.layout_of(tp_ty))
277 "volatile_store" => {
278 let dst = args[0].deref(bx.cx());
279 args[1].val.volatile_store(bx, dst);
282 "unaligned_volatile_store" => {
283 let dst = args[0].deref(bx.cx());
284 args[1].val.unaligned_volatile_store(bx, dst);
287 "prefetch_read_data" | "prefetch_write_data" |
288 "prefetch_read_instruction" | "prefetch_write_instruction" => {
289 let expect = cx.get_intrinsic(&("llvm.prefetch"));
290 let (rw, cache_type) = match name {
291 "prefetch_read_data" => (0, 1),
292 "prefetch_write_data" => (1, 1),
293 "prefetch_read_instruction" => (0, 0),
294 "prefetch_write_instruction" => (1, 0),
301 cx.const_i32(cache_type)
304 "ctlz" | "ctlz_nonzero" | "cttz" | "cttz_nonzero" | "ctpop" | "bswap" |
305 "bitreverse" | "add_with_overflow" | "sub_with_overflow" |
306 "mul_with_overflow" | "overflowing_add" | "overflowing_sub" | "overflowing_mul" |
307 "unchecked_div" | "unchecked_rem" | "unchecked_shl" | "unchecked_shr" | "exact_div" |
308 "rotate_left" | "rotate_right" => {
310 match int_type_width_signed(ty, cx) {
311 Some((width, signed)) =>
314 let y = cx.const_bool(false);
315 let llfn = cx.get_intrinsic(&format!("llvm.{}.i{}", name, width));
316 bx.call(llfn, &[args[0].immediate(), y], None)
318 "ctlz_nonzero" | "cttz_nonzero" => {
319 let y = cx.const_bool(true);
320 let llvm_name = &format!("llvm.{}.i{}", &name[..4], width);
321 let llfn = cx.get_intrinsic(llvm_name);
322 bx.call(llfn, &[args[0].immediate(), y], None)
324 "ctpop" => bx.call(cx.get_intrinsic(&format!("llvm.ctpop.i{}", width)),
325 &[args[0].immediate()], None),
328 args[0].immediate() // byte swap a u8/i8 is just a no-op
330 bx.call(cx.get_intrinsic(&format!("llvm.bswap.i{}", width)),
331 &[args[0].immediate()], None)
335 bx.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 = bx.cx().get_intrinsic(&intrinsic);
344 // Convert `i1` to a `bool`, and write it to the out parameter
345 let pair = bx.call(llfn, &[
349 let val = bx.extract_value(pair, 0);
350 let overflow = bx.zext(bx.extract_value(pair, 1), cx.type_bool());
352 let dest = result.project_field(bx, 0);
353 bx.store(val, dest.llval, dest.align);
354 let dest = result.project_field(bx, 1);
355 bx.store(overflow, dest.llval, dest.align);
359 "overflowing_add" => bx.add(args[0].immediate(), args[1].immediate()),
360 "overflowing_sub" => bx.sub(args[0].immediate(), args[1].immediate()),
361 "overflowing_mul" => bx.mul(args[0].immediate(), args[1].immediate()),
364 bx.exactsdiv(args[0].immediate(), args[1].immediate())
366 bx.exactudiv(args[0].immediate(), args[1].immediate())
370 bx.sdiv(args[0].immediate(), args[1].immediate())
372 bx.udiv(args[0].immediate(), args[1].immediate())
376 bx.srem(args[0].immediate(), args[1].immediate())
378 bx.urem(args[0].immediate(), args[1].immediate())
380 "unchecked_shl" => bx.shl(args[0].immediate(), args[1].immediate()),
383 bx.ashr(args[0].immediate(), args[1].immediate())
385 bx.lshr(args[0].immediate(), args[1].immediate())
387 "rotate_left" | "rotate_right" => {
388 let is_left = name == "rotate_left";
389 let val = args[0].immediate();
390 let raw_shift = args[1].immediate();
391 if llvm_util::get_major_version() >= 7 {
392 // rotate = funnel shift with first two args the same
393 let llvm_name = &format!("llvm.fsh{}.i{}",
394 if is_left { 'l' } else { 'r' }, width);
395 let llfn = cx.get_intrinsic(llvm_name);
396 bx.call(llfn, &[val, val, raw_shift], None)
398 // rotate_left: (X << (S % BW)) | (X >> ((BW - S) % BW))
399 // rotate_right: (X << ((BW - S) % BW)) | (X >> (S % BW))
400 let width = cx.const_uint(cx.type_ix(width), width);
401 let shift = bx.urem(raw_shift, width);
402 let inv_shift = bx.urem(bx.sub(width, raw_shift), width);
403 let shift1 = bx.shl(val, if is_left { shift } else { inv_shift });
404 let shift2 = bx.lshr(val, if !is_left { shift } else { inv_shift });
405 bx.or(shift1, shift2)
411 span_invalid_monomorphization_error(
413 &format!("invalid monomorphization of `{}` intrinsic: \
414 expected basic integer type, found `{}`", name, ty));
419 "fadd_fast" | "fsub_fast" | "fmul_fast" | "fdiv_fast" | "frem_fast" => {
420 let sty = &arg_tys[0].sty;
421 match float_type_width(sty) {
424 "fadd_fast" => bx.fadd_fast(args[0].immediate(), args[1].immediate()),
425 "fsub_fast" => bx.fsub_fast(args[0].immediate(), args[1].immediate()),
426 "fmul_fast" => bx.fmul_fast(args[0].immediate(), args[1].immediate()),
427 "fdiv_fast" => bx.fdiv_fast(args[0].immediate(), args[1].immediate()),
428 "frem_fast" => bx.frem_fast(args[0].immediate(), args[1].immediate()),
432 span_invalid_monomorphization_error(
434 &format!("invalid monomorphization of `{}` intrinsic: \
435 expected basic float type, found `{}`", name, sty));
442 "discriminant_value" => {
443 args[0].deref(bx.cx()).codegen_get_discr(bx, ret_ty)
446 name if name.starts_with("simd_") => {
447 match generic_simd_intrinsic(bx, name,
456 // This requires that atomic intrinsics follow a specific naming pattern:
457 // "atomic_<operation>[_<ordering>]", and no ordering means SeqCst
458 name if name.starts_with("atomic_") => {
459 use self::AtomicOrdering::*;
461 let split: Vec<&str> = name.split('_').collect();
463 let is_cxchg = split[1] == "cxchg" || split[1] == "cxchgweak";
464 let (order, failorder) = match split.len() {
465 2 => (SequentiallyConsistent, SequentiallyConsistent),
466 3 => match split[2] {
467 "unordered" => (Unordered, Unordered),
468 "relaxed" => (Monotonic, Monotonic),
469 "acq" => (Acquire, Acquire),
470 "rel" => (Release, Monotonic),
471 "acqrel" => (AcquireRelease, Acquire),
472 "failrelaxed" if is_cxchg =>
473 (SequentiallyConsistent, Monotonic),
474 "failacq" if is_cxchg =>
475 (SequentiallyConsistent, Acquire),
476 _ => cx.sess().fatal("unknown ordering in atomic intrinsic")
478 4 => match (split[2], split[3]) {
479 ("acq", "failrelaxed") if is_cxchg =>
480 (Acquire, Monotonic),
481 ("acqrel", "failrelaxed") if is_cxchg =>
482 (AcquireRelease, Monotonic),
483 _ => cx.sess().fatal("unknown ordering in atomic intrinsic")
485 _ => cx.sess().fatal("Atomic intrinsic not in correct format"),
488 let invalid_monomorphization = |ty| {
489 span_invalid_monomorphization_error(tcx.sess, span,
490 &format!("invalid monomorphization of `{}` intrinsic: \
491 expected basic integer type, found `{}`", name, ty));
495 "cxchg" | "cxchgweak" => {
496 let ty = substs.type_at(0);
497 if int_type_width_signed(ty, cx).is_some() {
498 let weak = split[1] == "cxchgweak";
499 let pair = bx.atomic_cmpxchg(
506 let val = bx.extract_value(pair, 0);
507 let success = bx.zext(bx.extract_value(pair, 1), bx.cx().type_bool());
509 let dest = result.project_field(bx, 0);
510 bx.store(val, dest.llval, dest.align);
511 let dest = result.project_field(bx, 1);
512 bx.store(success, dest.llval, dest.align);
515 return invalid_monomorphization(ty);
520 let ty = substs.type_at(0);
521 if int_type_width_signed(ty, cx).is_some() {
522 let size = cx.size_of(ty);
523 bx.atomic_load(args[0].immediate(), order, size)
525 return invalid_monomorphization(ty);
530 let ty = substs.type_at(0);
531 if int_type_width_signed(ty, cx).is_some() {
532 let size = cx.size_of(ty);
533 bx.atomic_store(args[1].immediate(), args[0].immediate(), order, size);
536 return invalid_monomorphization(ty);
541 bx.atomic_fence(order, SynchronizationScope::CrossThread);
545 "singlethreadfence" => {
546 bx.atomic_fence(order, SynchronizationScope::SingleThread);
550 // These are all AtomicRMW ops
552 let atom_op = match op {
553 "xchg" => AtomicRmwBinOp::AtomicXchg,
554 "xadd" => AtomicRmwBinOp::AtomicAdd,
555 "xsub" => AtomicRmwBinOp::AtomicSub,
556 "and" => AtomicRmwBinOp::AtomicAnd,
557 "nand" => AtomicRmwBinOp::AtomicNand,
558 "or" => AtomicRmwBinOp::AtomicOr,
559 "xor" => AtomicRmwBinOp::AtomicXor,
560 "max" => AtomicRmwBinOp::AtomicMax,
561 "min" => AtomicRmwBinOp::AtomicMin,
562 "umax" => AtomicRmwBinOp::AtomicUMax,
563 "umin" => AtomicRmwBinOp::AtomicUMin,
564 _ => cx.sess().fatal("unknown atomic operation")
567 let ty = substs.type_at(0);
568 if int_type_width_signed(ty, cx).is_some() {
569 bx.atomic_rmw(atom_op, args[0].immediate(), args[1].immediate(), order)
571 return invalid_monomorphization(ty);
577 "nontemporal_store" => {
578 let dst = args[0].deref(bx.cx());
579 args[1].val.nontemporal_store(bx, dst);
584 let intr = Intrinsic::find(&name).unwrap_or_else(||
585 bug!("unknown intrinsic '{}'", name));
587 fn one<T>(x: Vec<T>) -> T {
588 assert_eq!(x.len(), 1);
589 x.into_iter().next().unwrap()
591 fn ty_to_type(cx: &CodegenCx<'ll, '_>, t: &intrinsics::Type) -> Vec<&'ll Type> {
592 use intrinsics::Type::*;
594 Void => vec![cx.type_void()],
595 Integer(_signed, _width, llvm_width) => {
596 vec![cx.type_ix( llvm_width as u64)]
600 32 => vec![cx.type_f32()],
601 64 => vec![cx.type_f64()],
605 Pointer(ref t, ref llvm_elem, _const) => {
606 let t = llvm_elem.as_ref().unwrap_or(t);
607 let elem = one(ty_to_type(cx, t));
608 vec![cx.type_ptr_to(elem)]
610 Vector(ref t, ref llvm_elem, length) => {
611 let t = llvm_elem.as_ref().unwrap_or(t);
612 let elem = one(ty_to_type(cx, t));
613 vec![cx.type_vector(elem, length as u64)]
615 Aggregate(false, ref contents) => {
616 let elems = contents.iter()
617 .map(|t| one(ty_to_type(cx, t)))
618 .collect::<Vec<_>>();
619 vec![cx.type_struct( &elems, false)]
621 Aggregate(true, ref contents) => {
623 .flat_map(|t| ty_to_type(cx, t))
629 // This allows an argument list like `foo, (bar, baz),
630 // qux` to be converted into `foo, bar, baz, qux`, integer
631 // arguments to be truncated as needed and pointers to be
634 bx: &Builder<'a, 'll, 'tcx>,
635 t: &intrinsics::Type,
636 arg: &OperandRef<'tcx, &'ll Value>,
637 ) -> Vec<&'ll Value> {
639 intrinsics::Type::Aggregate(true, ref contents) => {
640 // We found a tuple that needs squishing! So
641 // run over the tuple and load each field.
643 // This assumes the type is "simple", i.e. no
644 // destructors, and the contents are SIMD
646 assert!(!bx.cx().type_needs_drop(arg.layout.ty));
647 let (ptr, align) = match arg.val {
648 OperandValue::Ref(ptr, None, align) => (ptr, align),
651 let arg = PlaceRef::new_sized(ptr, arg.layout, align);
652 (0..contents.len()).map(|i| {
653 arg.project_field(bx, i).load(bx).immediate()
656 intrinsics::Type::Pointer(_, Some(ref llvm_elem), _) => {
657 let llvm_elem = one(ty_to_type(bx.cx(), llvm_elem));
658 vec![bx.pointercast(arg.immediate(), bx.cx().type_ptr_to(llvm_elem))]
660 intrinsics::Type::Vector(_, Some(ref llvm_elem), length) => {
661 let llvm_elem = one(ty_to_type(bx.cx(), llvm_elem));
663 bx.bitcast(arg.immediate(),
664 bx.cx().type_vector(llvm_elem, length as u64))
667 intrinsics::Type::Integer(_, width, llvm_width) if width != llvm_width => {
668 // the LLVM intrinsic uses a smaller integer
669 // size than the C intrinsic's signature, so
670 // we have to trim it down here.
671 vec![bx.trunc(arg.immediate(), bx.cx().type_ix(llvm_width as u64))]
673 _ => vec![arg.immediate()],
678 let inputs = intr.inputs.iter()
679 .flat_map(|t| ty_to_type(cx, t))
680 .collect::<Vec<_>>();
682 let outputs = one(ty_to_type(cx, &intr.output));
684 let llargs: Vec<_> = intr.inputs.iter().zip(args).flat_map(|(t, arg)| {
685 modify_as_needed(bx, t, arg)
687 assert_eq!(inputs.len(), llargs.len());
689 let val = match intr.definition {
690 intrinsics::IntrinsicDef::Named(name) => {
691 let f = declare::declare_cfn(cx,
693 cx.type_func(&inputs, outputs));
694 bx.call(f, &llargs, None)
699 intrinsics::Type::Aggregate(flatten, ref elems) => {
700 // the output is a tuple so we need to munge it properly
703 for i in 0..elems.len() {
704 let dest = result.project_field(bx, i);
705 let val = bx.extract_value(val, i as u64);
706 bx.store(val, dest.llval, dest.align);
715 if !fn_ty.ret.is_ignore() {
716 if let PassMode::Cast(ty) = fn_ty.ret.mode {
717 let ptr = bx.pointercast(result.llval, cx.type_ptr_to(ty.llvm_type(cx)));
718 bx.store(llval, ptr, result.align);
720 OperandRef::from_immediate_or_packed_pair(bx, llval, result.layout)
721 .val.store(bx, result);
727 bx: &Builder<'a, 'll, 'tcx>,
735 let (size, align) = bx.cx().size_and_align_of(ty);
736 let size = bx.mul(bx.cx().const_usize(size.bytes()), count);
737 let flags = if volatile {
743 bx.memmove(dst, align, src, align, size, flags);
745 bx.memcpy(dst, align, src, align, size, flags);
750 bx: &Builder<'a, 'll, 'tcx>,
757 let (size, align) = bx.cx().size_and_align_of(ty);
758 let size = bx.cx().const_usize(size.bytes());
759 let flags = if volatile {
764 bx.memset(dst, val, bx.mul(size, count), align, flags);
768 bx: &Builder<'a, 'll, 'tcx>,
769 cx: &CodegenCx<'ll, 'tcx>,
772 local_ptr: &'ll Value,
775 if bx.sess().no_landing_pads() {
776 bx.call(func, &[data], None);
777 let ptr_align = bx.tcx().data_layout.pointer_align;
778 bx.store(cx.const_null(cx.type_i8p()), dest, ptr_align);
779 } else if wants_msvc_seh(bx.sess()) {
780 codegen_msvc_try(bx, cx, func, data, local_ptr, dest);
782 codegen_gnu_try(bx, cx, func, data, local_ptr, dest);
786 // MSVC's definition of the `rust_try` function.
788 // This implementation uses the new exception handling instructions in LLVM
789 // which have support in LLVM for SEH on MSVC targets. Although these
790 // instructions are meant to work for all targets, as of the time of this
791 // writing, however, LLVM does not recommend the usage of these new instructions
792 // as the old ones are still more optimized.
794 bx: &Builder<'a, 'll, 'tcx>,
795 cx: &CodegenCx<'ll, 'tcx>,
798 local_ptr: &'ll Value,
801 let llfn = get_rust_try_fn(cx, &mut |bx| {
804 bx.set_personality_fn(bx.cx().eh_personality());
806 let normal = bx.build_sibling_block("normal");
807 let catchswitch = bx.build_sibling_block("catchswitch");
808 let catchpad = bx.build_sibling_block("catchpad");
809 let caught = bx.build_sibling_block("caught");
811 let func = llvm::get_param(bx.llfn(), 0);
812 let data = llvm::get_param(bx.llfn(), 1);
813 let local_ptr = llvm::get_param(bx.llfn(), 2);
815 // We're generating an IR snippet that looks like:
817 // declare i32 @rust_try(%func, %data, %ptr) {
818 // %slot = alloca i64*
819 // invoke %func(%data) to label %normal unwind label %catchswitch
825 // %cs = catchswitch within none [%catchpad] unwind to caller
828 // %tok = catchpad within %cs [%type_descriptor, 0, %slot]
829 // %ptr[0] = %slot[0]
830 // %ptr[1] = %slot[1]
831 // catchret from %tok to label %caught
837 // This structure follows the basic usage of throw/try/catch in LLVM.
838 // For example, compile this C++ snippet to see what LLVM generates:
840 // #include <stdint.h>
842 // int bar(void (*foo)(void), uint64_t *ret) {
846 // } catch(uint64_t a[2]) {
853 // More information can be found in libstd's seh.rs implementation.
854 let i64p = cx.type_ptr_to(cx.type_i64());
855 let ptr_align = bx.tcx().data_layout.pointer_align;
856 let slot = bx.alloca(i64p, "slot", ptr_align);
857 bx.invoke(func, &[data], normal.llbb(), catchswitch.llbb(), None);
859 normal.ret(cx.const_i32(0));
861 let cs = catchswitch.catch_switch(None, None, 1);
862 catchswitch.add_handler(cs, catchpad.llbb());
865 let tydesc = match tcx.lang_items().msvc_try_filter() {
866 Some(did) => cx.get_static(did),
867 None => bug!("msvc_try_filter not defined"),
869 let tok = catchpad.catch_pad(cs, &[tydesc, cx.const_i32(0), slot]);
870 let addr = catchpad.load(slot, ptr_align);
872 let i64_align = bx.tcx().data_layout.i64_align;
873 let arg1 = catchpad.load(addr, i64_align);
874 let val1 = cx.const_i32(1);
875 let arg2 = catchpad.load(catchpad.inbounds_gep(addr, &[val1]), i64_align);
876 let local_ptr = catchpad.bitcast(local_ptr, i64p);
877 catchpad.store(arg1, local_ptr, i64_align);
878 catchpad.store(arg2, catchpad.inbounds_gep(local_ptr, &[val1]), i64_align);
879 catchpad.catch_ret(tok, caught.llbb());
881 caught.ret(cx.const_i32(1));
884 // Note that no invoke is used here because by definition this function
885 // can't panic (that's what it's catching).
886 let ret = bx.call(llfn, &[func, data, local_ptr], None);
887 let i32_align = bx.tcx().data_layout.i32_align;
888 bx.store(ret, dest, i32_align);
891 // Definition of the standard "try" function for Rust using the GNU-like model
892 // of exceptions (e.g. the normal semantics of LLVM's landingpad and invoke
895 // This codegen is a little surprising because we always call a shim
896 // function instead of inlining the call to `invoke` manually here. This is done
897 // because in LLVM we're only allowed to have one personality per function
898 // definition. The call to the `try` intrinsic is being inlined into the
899 // function calling it, and that function may already have other personality
900 // functions in play. By calling a shim we're guaranteed that our shim will have
901 // the right personality function.
903 bx: &Builder<'a, 'll, 'tcx>,
904 cx: &CodegenCx<'ll, 'tcx>,
907 local_ptr: &'ll Value,
910 let llfn = get_rust_try_fn(cx, &mut |bx| {
913 // Codegens the shims described above:
916 // invoke %func(%args...) normal %normal unwind %catch
922 // (ptr, _) = landingpad
923 // store ptr, %local_ptr
926 // Note that the `local_ptr` data passed into the `try` intrinsic is
927 // expected to be `*mut *mut u8` for this to actually work, but that's
928 // managed by the standard library.
930 let then = bx.build_sibling_block("then");
931 let catch = bx.build_sibling_block("catch");
933 let func = llvm::get_param(bx.llfn(), 0);
934 let data = llvm::get_param(bx.llfn(), 1);
935 let local_ptr = llvm::get_param(bx.llfn(), 2);
936 bx.invoke(func, &[data], then.llbb(), catch.llbb(), None);
937 then.ret(cx.const_i32(0));
939 // Type indicator for the exception being thrown.
941 // The first value in this tuple is a pointer to the exception object
942 // being thrown. The second value is a "selector" indicating which of
943 // the landing pad clauses the exception's type had been matched to.
944 // rust_try ignores the selector.
945 let lpad_ty = cx.type_struct(&[cx.type_i8p(), cx.type_i32()], false);
946 let vals = catch.landing_pad(lpad_ty, bx.cx().eh_personality(), 1);
947 catch.add_clause(vals, bx.cx().const_null(cx.type_i8p()));
948 let ptr = catch.extract_value(vals, 0);
949 let ptr_align = bx.tcx().data_layout.pointer_align;
950 catch.store(ptr, catch.bitcast(local_ptr, cx.type_ptr_to(cx.type_i8p())), ptr_align);
951 catch.ret(cx.const_i32(1));
954 // Note that no invoke is used here because by definition this function
955 // can't panic (that's what it's catching).
956 let ret = bx.call(llfn, &[func, data, local_ptr], None);
957 let i32_align = bx.tcx().data_layout.i32_align;
958 bx.store(ret, dest, i32_align);
961 // Helper function to give a Block to a closure to codegen a shim function.
962 // This is currently primarily used for the `try` intrinsic functions above.
963 fn gen_fn<'ll, 'tcx>(
964 cx: &CodegenCx<'ll, 'tcx>,
966 inputs: Vec<Ty<'tcx>>,
968 codegen: &mut dyn FnMut(Builder<'_, 'll, 'tcx>),
970 let rust_fn_sig = ty::Binder::bind(cx.tcx.mk_fn_sig(
974 hir::Unsafety::Unsafe,
977 let llfn = declare::define_internal_fn(cx, name, rust_fn_sig);
978 attributes::from_fn_attrs(cx, llfn, None);
979 let bx = Builder::new_block(cx, llfn, "entry-block");
984 // Helper function used to get a handle to the `__rust_try` function used to
987 // This function is only generated once and is then cached.
988 fn get_rust_try_fn<'ll, 'tcx>(
989 cx: &CodegenCx<'ll, 'tcx>,
990 codegen: &mut dyn FnMut(Builder<'_, 'll, 'tcx>),
992 if let Some(llfn) = cx.rust_try_fn.get() {
996 // Define the type up front for the signature of the rust_try function.
998 let i8p = tcx.mk_mut_ptr(tcx.types.i8);
999 let fn_ty = tcx.mk_fn_ptr(ty::Binder::bind(tcx.mk_fn_sig(
1003 hir::Unsafety::Unsafe,
1006 let output = tcx.types.i32;
1007 let rust_try = gen_fn(cx, "__rust_try", vec![fn_ty, i8p, i8p], output, codegen);
1008 cx.rust_try_fn.set(Some(rust_try));
1012 fn span_invalid_monomorphization_error(a: &Session, b: Span, c: &str) {
1013 span_err!(a, b, E0511, "{}", c);
1016 fn generic_simd_intrinsic(
1017 bx: &Builder<'a, 'll, 'tcx>,
1019 callee_ty: Ty<'tcx>,
1020 args: &[OperandRef<'tcx, &'ll Value>],
1022 llret_ty: &'ll Type,
1024 ) -> Result<&'ll Value, ()> {
1025 // macros for error handling:
1026 macro_rules! emit_error {
1030 ($msg: tt, $($fmt: tt)*) => {
1031 span_invalid_monomorphization_error(
1033 &format!(concat!("invalid monomorphization of `{}` intrinsic: ", $msg),
1038 macro_rules! return_error {
1041 emit_error!($($fmt)*);
1047 macro_rules! require {
1048 ($cond: expr, $($fmt: tt)*) => {
1050 return_error!($($fmt)*);
1055 macro_rules! require_simd {
1056 ($ty: expr, $position: expr) => {
1057 require!($ty.is_simd(), "expected SIMD {} type, found non-SIMD `{}`", $position, $ty)
1062 let sig = tcx.normalize_erasing_late_bound_regions(
1063 ty::ParamEnv::reveal_all(),
1064 &callee_ty.fn_sig(tcx),
1066 let arg_tys = sig.inputs();
1068 // every intrinsic takes a SIMD vector as its first argument
1069 require_simd!(arg_tys[0], "input");
1070 let in_ty = arg_tys[0];
1071 let in_elem = arg_tys[0].simd_type(tcx);
1072 let in_len = arg_tys[0].simd_size(tcx);
1074 let comparison = match name {
1075 "simd_eq" => Some(hir::BinOpKind::Eq),
1076 "simd_ne" => Some(hir::BinOpKind::Ne),
1077 "simd_lt" => Some(hir::BinOpKind::Lt),
1078 "simd_le" => Some(hir::BinOpKind::Le),
1079 "simd_gt" => Some(hir::BinOpKind::Gt),
1080 "simd_ge" => Some(hir::BinOpKind::Ge),
1084 if let Some(cmp_op) = comparison {
1085 require_simd!(ret_ty, "return");
1087 let out_len = ret_ty.simd_size(tcx);
1088 require!(in_len == out_len,
1089 "expected return type with length {} (same as input type `{}`), \
1090 found `{}` with length {}",
1093 require!(bx.cx().type_kind(bx.cx().element_type(llret_ty)) == TypeKind::Integer,
1094 "expected return type with integer elements, found `{}` with non-integer `{}`",
1096 ret_ty.simd_type(tcx));
1098 return Ok(compare_simd_types(bx,
1099 args[0].immediate(),
1100 args[1].immediate(),
1106 if name.starts_with("simd_shuffle") {
1107 let n: usize = name["simd_shuffle".len()..].parse().unwrap_or_else(|_|
1108 span_bug!(span, "bad `simd_shuffle` instruction only caught in codegen?"));
1110 require_simd!(ret_ty, "return");
1112 let out_len = ret_ty.simd_size(tcx);
1113 require!(out_len == n,
1114 "expected return type of length {}, found `{}` with length {}",
1115 n, ret_ty, out_len);
1116 require!(in_elem == ret_ty.simd_type(tcx),
1117 "expected return element type `{}` (element of input `{}`), \
1118 found `{}` with element type `{}`",
1120 ret_ty, ret_ty.simd_type(tcx));
1122 let total_len = in_len as u128 * 2;
1124 let vector = args[2].immediate();
1126 let indices: Option<Vec<_>> = (0..n)
1129 let val = bx.cx().const_get_elt(vector, i as u64);
1130 match bx.cx().const_to_opt_u128(val, true) {
1132 emit_error!("shuffle index #{} is not a constant", arg_idx);
1135 Some(idx) if idx >= total_len => {
1136 emit_error!("shuffle index #{} is out of bounds (limit {})",
1137 arg_idx, total_len);
1140 Some(idx) => Some(bx.cx().const_i32(idx as i32)),
1144 let indices = match indices {
1146 None => return Ok(bx.cx().const_null(llret_ty))
1149 return Ok(bx.shuffle_vector(args[0].immediate(),
1150 args[1].immediate(),
1151 bx.cx().const_vector(&indices)))
1154 if name == "simd_insert" {
1155 require!(in_elem == arg_tys[2],
1156 "expected inserted type `{}` (element of input `{}`), found `{}`",
1157 in_elem, in_ty, arg_tys[2]);
1158 return Ok(bx.insert_element(args[0].immediate(),
1159 args[2].immediate(),
1160 args[1].immediate()))
1162 if name == "simd_extract" {
1163 require!(ret_ty == in_elem,
1164 "expected return type `{}` (element of input `{}`), found `{}`",
1165 in_elem, in_ty, ret_ty);
1166 return Ok(bx.extract_element(args[0].immediate(), args[1].immediate()))
1169 if name == "simd_select" {
1170 let m_elem_ty = in_elem;
1172 let v_len = arg_tys[1].simd_size(tcx);
1173 require!(m_len == v_len,
1174 "mismatched lengths: mask length `{}` != other vector length `{}`",
1177 match m_elem_ty.sty {
1179 _ => return_error!("mask element type is `{}`, expected `i_`", m_elem_ty)
1181 // truncate the mask to a vector of i1s
1182 let i1 = bx.cx().type_i1();
1183 let i1xn = bx.cx().type_vector(i1, m_len as u64);
1184 let m_i1s = bx.trunc(args[0].immediate(), i1xn);
1185 return Ok(bx.select(m_i1s, args[1].immediate(), args[2].immediate()));
1188 fn simd_simple_float_intrinsic(
1190 in_elem: &::rustc::ty::TyS,
1191 in_ty: &::rustc::ty::TyS,
1193 bx: &Builder<'a, 'll, 'tcx>,
1195 args: &[OperandRef<'tcx, &'ll Value>],
1196 ) -> Result<&'ll Value, ()> {
1197 macro_rules! emit_error {
1201 ($msg: tt, $($fmt: tt)*) => {
1202 span_invalid_monomorphization_error(
1204 &format!(concat!("invalid monomorphization of `{}` intrinsic: ", $msg),
1208 macro_rules! return_error {
1211 emit_error!($($fmt)*);
1216 let ety = match in_elem.sty {
1217 ty::Float(f) if f.bit_width() == 32 => {
1218 if in_len < 2 || in_len > 16 {
1220 "unsupported floating-point vector `{}` with length `{}` \
1221 out-of-range [2, 16]",
1226 ty::Float(f) if f.bit_width() == 64 => {
1227 if in_len < 2 || in_len > 8 {
1228 return_error!("unsupported floating-point vector `{}` with length `{}` \
1229 out-of-range [2, 8]",
1235 return_error!("unsupported element type `{}` of floating-point vector `{}`",
1239 return_error!("`{}` is not a floating-point type", in_ty);
1243 let llvm_name = &format!("llvm.{0}.v{1}{2}", name, in_len, ety);
1244 let intrinsic = bx.cx().get_intrinsic(&llvm_name);
1245 let c = bx.call(intrinsic,
1246 &args.iter().map(|arg| arg.immediate()).collect::<Vec<_>>(),
1248 unsafe { llvm::LLVMRustSetHasUnsafeAlgebra(c) };
1254 return simd_simple_float_intrinsic("sqrt", in_elem, in_ty, in_len, bx, span, args);
1257 return simd_simple_float_intrinsic("sin", in_elem, in_ty, in_len, bx, span, args);
1260 return simd_simple_float_intrinsic("cos", in_elem, in_ty, in_len, bx, span, args);
1263 return simd_simple_float_intrinsic("fabs", in_elem, in_ty, in_len, bx, span, args);
1266 return simd_simple_float_intrinsic("floor", in_elem, in_ty, in_len, bx, span, args);
1269 return simd_simple_float_intrinsic("ceil", in_elem, in_ty, in_len, bx, span, args);
1272 return simd_simple_float_intrinsic("exp", in_elem, in_ty, in_len, bx, span, args);
1275 return simd_simple_float_intrinsic("exp2", in_elem, in_ty, in_len, bx, span, args);
1278 return simd_simple_float_intrinsic("log10", in_elem, in_ty, in_len, bx, span, args);
1281 return simd_simple_float_intrinsic("log2", in_elem, in_ty, in_len, bx, span, args);
1284 return simd_simple_float_intrinsic("log", in_elem, in_ty, in_len, bx, span, args);
1287 return simd_simple_float_intrinsic("powi", in_elem, in_ty, in_len, bx, span, args);
1290 return simd_simple_float_intrinsic("pow", in_elem, in_ty, in_len, bx, span, args);
1293 return simd_simple_float_intrinsic("fma", in_elem, in_ty, in_len, bx, span, args);
1295 _ => { /* fallthrough */ }
1299 // https://github.com/llvm-mirror/llvm/blob/master/include/llvm/IR/Function.h#L182
1300 // https://github.com/llvm-mirror/llvm/blob/master/include/llvm/IR/Intrinsics.h#L81
1301 fn llvm_vector_str(elem_ty: ty::Ty, vec_len: usize, no_pointers: usize) -> String {
1302 let p0s: String = "p0".repeat(no_pointers);
1304 ty::Int(v) => format!("v{}{}i{}", vec_len, p0s, v.bit_width().unwrap()),
1305 ty::Uint(v) => format!("v{}{}i{}", vec_len, p0s, v.bit_width().unwrap()),
1306 ty::Float(v) => format!("v{}{}f{}", vec_len, p0s, v.bit_width()),
1307 _ => unreachable!(),
1311 fn llvm_vector_ty(cx: &CodegenCx<'ll, '_>, elem_ty: ty::Ty, vec_len: usize,
1312 mut no_pointers: usize) -> &'ll Type {
1313 // FIXME: use cx.layout_of(ty).llvm_type() ?
1314 let mut elem_ty = match elem_ty.sty {
1315 ty::Int(v) => cx.type_int_from_ty( v),
1316 ty::Uint(v) => cx.type_uint_from_ty( v),
1317 ty::Float(v) => cx.type_float_from_ty( v),
1318 _ => unreachable!(),
1320 while no_pointers > 0 {
1321 elem_ty = cx.type_ptr_to(elem_ty);
1324 cx.type_vector(elem_ty, vec_len as u64)
1328 if name == "simd_gather" {
1329 // simd_gather(values: <N x T>, pointers: <N x *_ T>,
1330 // mask: <N x i{M}>) -> <N x T>
1331 // * N: number of elements in the input vectors
1332 // * T: type of the element to load
1333 // * M: any integer width is supported, will be truncated to i1
1335 // All types must be simd vector types
1336 require_simd!(in_ty, "first");
1337 require_simd!(arg_tys[1], "second");
1338 require_simd!(arg_tys[2], "third");
1339 require_simd!(ret_ty, "return");
1341 // Of the same length:
1342 require!(in_len == arg_tys[1].simd_size(tcx),
1343 "expected {} argument with length {} (same as input type `{}`), \
1344 found `{}` with length {}", "second", in_len, in_ty, arg_tys[1],
1345 arg_tys[1].simd_size(tcx));
1346 require!(in_len == arg_tys[2].simd_size(tcx),
1347 "expected {} argument with length {} (same as input type `{}`), \
1348 found `{}` with length {}", "third", in_len, in_ty, arg_tys[2],
1349 arg_tys[2].simd_size(tcx));
1351 // The return type must match the first argument type
1352 require!(ret_ty == in_ty,
1353 "expected return type `{}`, found `{}`",
1356 // This counts how many pointers
1357 fn ptr_count(t: ty::Ty) -> usize {
1359 ty::RawPtr(p) => 1 + ptr_count(p.ty),
1365 fn non_ptr(t: ty::Ty) -> ty::Ty {
1367 ty::RawPtr(p) => non_ptr(p.ty),
1372 // The second argument must be a simd vector with an element type that's a pointer
1373 // to the element type of the first argument
1374 let (pointer_count, underlying_ty) = match arg_tys[1].simd_type(tcx).sty {
1375 ty::RawPtr(p) if p.ty == in_elem => (ptr_count(arg_tys[1].simd_type(tcx)),
1376 non_ptr(arg_tys[1].simd_type(tcx))),
1378 require!(false, "expected element type `{}` of second argument `{}` \
1379 to be a pointer to the element type `{}` of the first \
1380 argument `{}`, found `{}` != `*_ {}`",
1381 arg_tys[1].simd_type(tcx).sty, arg_tys[1], in_elem, in_ty,
1382 arg_tys[1].simd_type(tcx).sty, in_elem);
1386 assert!(pointer_count > 0);
1387 assert_eq!(pointer_count - 1, ptr_count(arg_tys[0].simd_type(tcx)));
1388 assert_eq!(underlying_ty, non_ptr(arg_tys[0].simd_type(tcx)));
1390 // The element type of the third argument must be a signed integer type of any width:
1391 match arg_tys[2].simd_type(tcx).sty {
1394 require!(false, "expected element type `{}` of third argument `{}` \
1395 to be a signed integer type",
1396 arg_tys[2].simd_type(tcx).sty, arg_tys[2]);
1400 // Alignment of T, must be a constant integer value:
1401 let alignment_ty = bx.cx().type_i32();
1402 let alignment = bx.cx().const_i32(bx.cx().align_of(in_elem).abi() as i32);
1404 // Truncate the mask vector to a vector of i1s:
1405 let (mask, mask_ty) = {
1406 let i1 = bx.cx().type_i1();
1407 let i1xn = bx.cx().type_vector(i1, in_len as u64);
1408 (bx.trunc(args[2].immediate(), i1xn), i1xn)
1411 // Type of the vector of pointers:
1412 let llvm_pointer_vec_ty = llvm_vector_ty(bx.cx(), underlying_ty, in_len, pointer_count);
1413 let llvm_pointer_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count);
1415 // Type of the vector of elements:
1416 let llvm_elem_vec_ty = llvm_vector_ty(bx.cx(), underlying_ty, in_len, pointer_count - 1);
1417 let llvm_elem_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count - 1);
1419 let llvm_intrinsic = format!("llvm.masked.gather.{}.{}",
1420 llvm_elem_vec_str, llvm_pointer_vec_str);
1421 let f = declare::declare_cfn(bx.cx(), &llvm_intrinsic,
1422 bx.cx().type_func(&[
1423 llvm_pointer_vec_ty,
1426 llvm_elem_vec_ty], llvm_elem_vec_ty));
1427 llvm::SetUnnamedAddr(f, false);
1428 let v = bx.call(f, &[args[1].immediate(), alignment, mask, args[0].immediate()],
1433 if name == "simd_scatter" {
1434 // simd_scatter(values: <N x T>, pointers: <N x *mut T>,
1435 // mask: <N x i{M}>) -> ()
1436 // * N: number of elements in the input vectors
1437 // * T: type of the element to load
1438 // * M: any integer width is supported, will be truncated to i1
1440 // All types must be simd vector types
1441 require_simd!(in_ty, "first");
1442 require_simd!(arg_tys[1], "second");
1443 require_simd!(arg_tys[2], "third");
1445 // Of the same length:
1446 require!(in_len == arg_tys[1].simd_size(tcx),
1447 "expected {} argument with length {} (same as input type `{}`), \
1448 found `{}` with length {}", "second", in_len, in_ty, arg_tys[1],
1449 arg_tys[1].simd_size(tcx));
1450 require!(in_len == arg_tys[2].simd_size(tcx),
1451 "expected {} argument with length {} (same as input type `{}`), \
1452 found `{}` with length {}", "third", in_len, in_ty, arg_tys[2],
1453 arg_tys[2].simd_size(tcx));
1455 // This counts how many pointers
1456 fn ptr_count(t: ty::Ty) -> usize {
1458 ty::RawPtr(p) => 1 + ptr_count(p.ty),
1464 fn non_ptr(t: ty::Ty) -> ty::Ty {
1466 ty::RawPtr(p) => non_ptr(p.ty),
1471 // The second argument must be a simd vector with an element type that's a pointer
1472 // to the element type of the first argument
1473 let (pointer_count, underlying_ty) = match arg_tys[1].simd_type(tcx).sty {
1474 ty::RawPtr(p) if p.ty == in_elem && p.mutbl == hir::MutMutable
1475 => (ptr_count(arg_tys[1].simd_type(tcx)),
1476 non_ptr(arg_tys[1].simd_type(tcx))),
1478 require!(false, "expected element type `{}` of second argument `{}` \
1479 to be a pointer to the element type `{}` of the first \
1480 argument `{}`, found `{}` != `*mut {}`",
1481 arg_tys[1].simd_type(tcx).sty, arg_tys[1], in_elem, in_ty,
1482 arg_tys[1].simd_type(tcx).sty, in_elem);
1486 assert!(pointer_count > 0);
1487 assert_eq!(pointer_count - 1, ptr_count(arg_tys[0].simd_type(tcx)));
1488 assert_eq!(underlying_ty, non_ptr(arg_tys[0].simd_type(tcx)));
1490 // The element type of the third argument must be a signed integer type of any width:
1491 match arg_tys[2].simd_type(tcx).sty {
1494 require!(false, "expected element type `{}` of third argument `{}` \
1495 to be a signed integer type",
1496 arg_tys[2].simd_type(tcx).sty, arg_tys[2]);
1500 // Alignment of T, must be a constant integer value:
1501 let alignment_ty = bx.cx().type_i32();
1502 let alignment = bx.cx().const_i32(bx.cx().align_of(in_elem).abi() as i32);
1504 // Truncate the mask vector to a vector of i1s:
1505 let (mask, mask_ty) = {
1506 let i1 = bx.cx().type_i1();
1507 let i1xn = bx.cx().type_vector(i1, in_len as u64);
1508 (bx.trunc(args[2].immediate(), i1xn), i1xn)
1511 let ret_t = bx.cx().type_void();
1513 // Type of the vector of pointers:
1514 let llvm_pointer_vec_ty = llvm_vector_ty(bx.cx(), underlying_ty, in_len, pointer_count);
1515 let llvm_pointer_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count);
1517 // Type of the vector of elements:
1518 let llvm_elem_vec_ty = llvm_vector_ty(bx.cx(), underlying_ty, in_len, pointer_count - 1);
1519 let llvm_elem_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count - 1);
1521 let llvm_intrinsic = format!("llvm.masked.scatter.{}.{}",
1522 llvm_elem_vec_str, llvm_pointer_vec_str);
1523 let f = declare::declare_cfn(bx.cx(), &llvm_intrinsic,
1524 bx.cx().type_func(&[llvm_elem_vec_ty,
1525 llvm_pointer_vec_ty,
1528 llvm::SetUnnamedAddr(f, false);
1529 let v = bx.call(f, &[args[0].immediate(), args[1].immediate(), alignment, mask],
1534 macro_rules! arith_red {
1535 ($name:tt : $integer_reduce:ident, $float_reduce:ident, $ordered:expr) => {
1537 require!(ret_ty == in_elem,
1538 "expected return type `{}` (element of input `{}`), found `{}`",
1539 in_elem, in_ty, ret_ty);
1540 return match in_elem.sty {
1541 ty::Int(_) | ty::Uint(_) => {
1542 let r = bx.$integer_reduce(args[0].immediate());
1544 // if overflow occurs, the result is the
1545 // mathematical result modulo 2^n:
1546 if name.contains("mul") {
1547 Ok(bx.mul(args[1].immediate(), r))
1549 Ok(bx.add(args[1].immediate(), r))
1552 Ok(bx.$integer_reduce(args[0].immediate()))
1556 // ordered arithmetic reductions take an accumulator
1557 let acc = if $ordered {
1558 let acc = args[1].immediate();
1559 // FIXME: https://bugs.llvm.org/show_bug.cgi?id=36734
1560 // * if the accumulator of the fadd isn't 0, incorrect
1561 // code is generated
1562 // * if the accumulator of the fmul isn't 1, incorrect
1563 // code is generated
1564 match bx.cx().const_get_real(acc) {
1565 None => return_error!("accumulator of {} is not a constant", $name),
1566 Some((v, loses_info)) => {
1567 if $name.contains("mul") && v != 1.0_f64 {
1568 return_error!("accumulator of {} is not 1.0", $name);
1569 } else if $name.contains("add") && v != 0.0_f64 {
1570 return_error!("accumulator of {} is not 0.0", $name);
1571 } else if loses_info {
1572 return_error!("accumulator of {} loses information", $name);
1578 // unordered arithmetic reductions do not:
1579 match f.bit_width() {
1580 32 => bx.cx().const_undef(bx.cx().type_f32()),
1581 64 => bx.cx().const_undef(bx.cx().type_f64()),
1584 unsupported {} from `{}` with element `{}` of size `{}` to `{}`"#,
1585 $name, in_ty, in_elem, v, ret_ty
1590 Ok(bx.$float_reduce(acc, args[0].immediate()))
1594 "unsupported {} from `{}` with element `{}` to `{}`",
1595 $name, in_ty, in_elem, ret_ty
1603 arith_red!("simd_reduce_add_ordered": vector_reduce_add, vector_reduce_fadd_fast, true);
1604 arith_red!("simd_reduce_mul_ordered": vector_reduce_mul, vector_reduce_fmul_fast, true);
1605 arith_red!("simd_reduce_add_unordered": vector_reduce_add, vector_reduce_fadd_fast, false);
1606 arith_red!("simd_reduce_mul_unordered": vector_reduce_mul, vector_reduce_fmul_fast, false);
1608 macro_rules! minmax_red {
1609 ($name:tt: $int_red:ident, $float_red:ident) => {
1611 require!(ret_ty == in_elem,
1612 "expected return type `{}` (element of input `{}`), found `{}`",
1613 in_elem, in_ty, ret_ty);
1614 return match in_elem.sty {
1616 Ok(bx.$int_red(args[0].immediate(), true))
1619 Ok(bx.$int_red(args[0].immediate(), false))
1622 Ok(bx.$float_red(args[0].immediate()))
1625 return_error!("unsupported {} from `{}` with element `{}` to `{}`",
1626 $name, in_ty, in_elem, ret_ty)
1634 minmax_red!("simd_reduce_min": vector_reduce_min, vector_reduce_fmin);
1635 minmax_red!("simd_reduce_max": vector_reduce_max, vector_reduce_fmax);
1637 minmax_red!("simd_reduce_min_nanless": vector_reduce_min, vector_reduce_fmin_fast);
1638 minmax_red!("simd_reduce_max_nanless": vector_reduce_max, vector_reduce_fmax_fast);
1640 macro_rules! bitwise_red {
1641 ($name:tt : $red:ident, $boolean:expr) => {
1643 let input = if !$boolean {
1644 require!(ret_ty == in_elem,
1645 "expected return type `{}` (element of input `{}`), found `{}`",
1646 in_elem, in_ty, ret_ty);
1650 ty::Int(_) | ty::Uint(_) => {},
1652 return_error!("unsupported {} from `{}` with element `{}` to `{}`",
1653 $name, in_ty, in_elem, ret_ty)
1657 // boolean reductions operate on vectors of i1s:
1658 let i1 = bx.cx().type_i1();
1659 let i1xn = bx.cx().type_vector(i1, in_len as u64);
1660 bx.trunc(args[0].immediate(), i1xn)
1662 return match in_elem.sty {
1663 ty::Int(_) | ty::Uint(_) => {
1664 let r = bx.$red(input);
1669 bx.zext(r, bx.cx().type_bool())
1674 return_error!("unsupported {} from `{}` with element `{}` to `{}`",
1675 $name, in_ty, in_elem, ret_ty)
1682 bitwise_red!("simd_reduce_and": vector_reduce_and, false);
1683 bitwise_red!("simd_reduce_or": vector_reduce_or, false);
1684 bitwise_red!("simd_reduce_xor": vector_reduce_xor, false);
1685 bitwise_red!("simd_reduce_all": vector_reduce_and, true);
1686 bitwise_red!("simd_reduce_any": vector_reduce_or, true);
1688 if name == "simd_cast" {
1689 require_simd!(ret_ty, "return");
1690 let out_len = ret_ty.simd_size(tcx);
1691 require!(in_len == out_len,
1692 "expected return type with length {} (same as input type `{}`), \
1693 found `{}` with length {}",
1696 // casting cares about nominal type, not just structural type
1697 let out_elem = ret_ty.simd_type(tcx);
1699 if in_elem == out_elem { return Ok(args[0].immediate()); }
1701 enum Style { Float, Int(/* is signed? */ bool), Unsupported }
1703 let (in_style, in_width) = match in_elem.sty {
1704 // vectors of pointer-sized integers should've been
1705 // disallowed before here, so this unwrap is safe.
1706 ty::Int(i) => (Style::Int(true), i.bit_width().unwrap()),
1707 ty::Uint(u) => (Style::Int(false), u.bit_width().unwrap()),
1708 ty::Float(f) => (Style::Float, f.bit_width()),
1709 _ => (Style::Unsupported, 0)
1711 let (out_style, out_width) = match out_elem.sty {
1712 ty::Int(i) => (Style::Int(true), i.bit_width().unwrap()),
1713 ty::Uint(u) => (Style::Int(false), u.bit_width().unwrap()),
1714 ty::Float(f) => (Style::Float, f.bit_width()),
1715 _ => (Style::Unsupported, 0)
1718 match (in_style, out_style) {
1719 (Style::Int(in_is_signed), Style::Int(_)) => {
1720 return Ok(match in_width.cmp(&out_width) {
1721 Ordering::Greater => bx.trunc(args[0].immediate(), llret_ty),
1722 Ordering::Equal => args[0].immediate(),
1723 Ordering::Less => if in_is_signed {
1724 bx.sext(args[0].immediate(), llret_ty)
1726 bx.zext(args[0].immediate(), llret_ty)
1730 (Style::Int(in_is_signed), Style::Float) => {
1731 return Ok(if in_is_signed {
1732 bx.sitofp(args[0].immediate(), llret_ty)
1734 bx.uitofp(args[0].immediate(), llret_ty)
1737 (Style::Float, Style::Int(out_is_signed)) => {
1738 return Ok(if out_is_signed {
1739 bx.fptosi(args[0].immediate(), llret_ty)
1741 bx.fptoui(args[0].immediate(), llret_ty)
1744 (Style::Float, Style::Float) => {
1745 return Ok(match in_width.cmp(&out_width) {
1746 Ordering::Greater => bx.fptrunc(args[0].immediate(), llret_ty),
1747 Ordering::Equal => args[0].immediate(),
1748 Ordering::Less => bx.fpext(args[0].immediate(), llret_ty)
1751 _ => {/* Unsupported. Fallthrough. */}
1754 "unsupported cast from `{}` with element `{}` to `{}` with element `{}`",
1758 macro_rules! arith {
1759 ($($name: ident: $($($p: ident),* => $call: ident),*;)*) => {
1760 $(if name == stringify!($name) {
1762 $($(ty::$p(_))|* => {
1763 return Ok(bx.$call(args[0].immediate(), args[1].immediate()))
1768 "unsupported operation on `{}` with element `{}`",
1775 simd_add: Uint, Int => add, Float => fadd;
1776 simd_sub: Uint, Int => sub, Float => fsub;
1777 simd_mul: Uint, Int => mul, Float => fmul;
1778 simd_div: Uint => udiv, Int => sdiv, Float => fdiv;
1779 simd_rem: Uint => urem, Int => srem, Float => frem;
1780 simd_shl: Uint, Int => shl;
1781 simd_shr: Uint => lshr, Int => ashr;
1782 simd_and: Uint, Int => and;
1783 simd_or: Uint, Int => or;
1784 simd_xor: Uint, Int => xor;
1785 simd_fmax: Float => maxnum;
1786 simd_fmin: Float => minnum;
1788 span_bug!(span, "unknown SIMD intrinsic");
1791 // Returns the width of an int Ty, and if it's signed or not
1792 // Returns None if the type is not an integer
1793 // FIXME: there’s multiple of this functions, investigate using some of the already existing
1795 fn int_type_width_signed(ty: Ty, cx: &CodegenCx) -> Option<(u64, bool)> {
1797 ty::Int(t) => Some((match t {
1798 ast::IntTy::Isize => cx.tcx.sess.target.isize_ty.bit_width().unwrap() as u64,
1799 ast::IntTy::I8 => 8,
1800 ast::IntTy::I16 => 16,
1801 ast::IntTy::I32 => 32,
1802 ast::IntTy::I64 => 64,
1803 ast::IntTy::I128 => 128,
1805 ty::Uint(t) => Some((match t {
1806 ast::UintTy::Usize => cx.tcx.sess.target.usize_ty.bit_width().unwrap() as u64,
1807 ast::UintTy::U8 => 8,
1808 ast::UintTy::U16 => 16,
1809 ast::UintTy::U32 => 32,
1810 ast::UintTy::U64 => 64,
1811 ast::UintTy::U128 => 128,
1817 // Returns the width of a float TypeVariant
1818 // Returns None if the type is not a float
1819 fn float_type_width<'tcx>(sty: &ty::TyKind<'tcx>) -> Option<u64> {
1821 ty::Float(t) => Some(t.bit_width() as u64),