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};
15 use llvm::{self, TypeKind};
16 use abi::{Abi, FnType, LlvmType, PassMode};
17 use mir::place::PlaceRef;
18 use mir::operand::{OperandRef, OperandValue};
24 use type_of::LayoutLlvmExt;
25 use rustc::ty::{self, Ty};
26 use rustc::ty::layout::{HasDataLayout, LayoutOf};
29 use syntax::symbol::Symbol;
33 use rustc::session::Session;
36 use std::cmp::Ordering;
39 fn get_simple_intrinsic(cx: &CodegenCx<'ll, '_>, name: &str) -> Option<&'ll Value> {
40 let llvm_name = match name {
41 "sqrtf32" => "llvm.sqrt.f32",
42 "sqrtf64" => "llvm.sqrt.f64",
43 "powif32" => "llvm.powi.f32",
44 "powif64" => "llvm.powi.f64",
45 "sinf32" => "llvm.sin.f32",
46 "sinf64" => "llvm.sin.f64",
47 "cosf32" => "llvm.cos.f32",
48 "cosf64" => "llvm.cos.f64",
49 "powf32" => "llvm.pow.f32",
50 "powf64" => "llvm.pow.f64",
51 "expf32" => "llvm.exp.f32",
52 "expf64" => "llvm.exp.f64",
53 "exp2f32" => "llvm.exp2.f32",
54 "exp2f64" => "llvm.exp2.f64",
55 "logf32" => "llvm.log.f32",
56 "logf64" => "llvm.log.f64",
57 "log10f32" => "llvm.log10.f32",
58 "log10f64" => "llvm.log10.f64",
59 "log2f32" => "llvm.log2.f32",
60 "log2f64" => "llvm.log2.f64",
61 "fmaf32" => "llvm.fma.f32",
62 "fmaf64" => "llvm.fma.f64",
63 "fabsf32" => "llvm.fabs.f32",
64 "fabsf64" => "llvm.fabs.f64",
65 "copysignf32" => "llvm.copysign.f32",
66 "copysignf64" => "llvm.copysign.f64",
67 "floorf32" => "llvm.floor.f32",
68 "floorf64" => "llvm.floor.f64",
69 "ceilf32" => "llvm.ceil.f32",
70 "ceilf64" => "llvm.ceil.f64",
71 "truncf32" => "llvm.trunc.f32",
72 "truncf64" => "llvm.trunc.f64",
73 "rintf32" => "llvm.rint.f32",
74 "rintf64" => "llvm.rint.f64",
75 "nearbyintf32" => "llvm.nearbyint.f32",
76 "nearbyintf64" => "llvm.nearbyint.f64",
77 "roundf32" => "llvm.round.f32",
78 "roundf64" => "llvm.round.f64",
79 "assume" => "llvm.assume",
80 "abort" => "llvm.trap",
83 Some(cx.get_intrinsic(&llvm_name))
86 /// Remember to add all intrinsics here, in librustc_typeck/check/mod.rs,
87 /// and in libcore/intrinsics.rs; if you need access to any llvm intrinsics,
88 /// add them to librustc_codegen_llvm/context.rs
89 pub fn codegen_intrinsic_call(
90 bx: &Builder<'a, 'll, 'tcx>,
92 fn_ty: &FnType<'tcx, Ty<'tcx>>,
93 args: &[OperandRef<'ll, 'tcx>],
100 let (def_id, substs) = match callee_ty.sty {
101 ty::FnDef(def_id, substs) => (def_id, substs),
102 _ => bug!("expected fn item type, found {}", callee_ty)
105 let sig = callee_ty.fn_sig(tcx);
106 let sig = tcx.normalize_erasing_late_bound_regions(ty::ParamEnv::reveal_all(), &sig);
107 let arg_tys = sig.inputs();
108 let ret_ty = sig.output();
109 let name = &*tcx.item_name(def_id).as_str();
111 let llret_ty = cx.layout_of(ret_ty).llvm_type(cx);
112 let result = PlaceRef::new_sized(llresult, fn_ty.ret.layout, fn_ty.ret.layout.align);
114 let simple = get_simple_intrinsic(cx, name);
115 let llval = match name {
116 _ if simple.is_some() => {
117 bx.call(simple.unwrap(),
118 &args.iter().map(|arg| arg.immediate()).collect::<Vec<_>>(),
125 let expect = cx.get_intrinsic(&("llvm.expect.i1"));
126 bx.call(expect, &[args[0].immediate(), C_bool(cx, true)], None)
129 let expect = cx.get_intrinsic(&("llvm.expect.i1"));
130 bx.call(expect, &[args[0].immediate(), C_bool(cx, false)], None)
133 try_intrinsic(bx, cx,
141 let llfn = cx.get_intrinsic(&("llvm.debugtrap"));
142 bx.call(llfn, &[], None)
145 let tp_ty = substs.type_at(0);
146 C_usize(cx, cx.size_of(tp_ty).bytes())
149 let tp_ty = substs.type_at(0);
150 if let OperandValue::Pair(_, meta) = args[0].val {
152 glue::size_and_align_of_dst(bx, tp_ty, Some(meta));
155 C_usize(cx, cx.size_of(tp_ty).bytes())
159 let tp_ty = substs.type_at(0);
160 C_usize(cx, cx.align_of(tp_ty).abi())
162 "min_align_of_val" => {
163 let tp_ty = substs.type_at(0);
164 if let OperandValue::Pair(_, meta) = args[0].val {
166 glue::size_and_align_of_dst(bx, tp_ty, Some(meta));
169 C_usize(cx, cx.align_of(tp_ty).abi())
173 let tp_ty = substs.type_at(0);
174 C_usize(cx, cx.align_of(tp_ty).pref())
177 let tp_ty = substs.type_at(0);
178 let ty_name = Symbol::intern(&tp_ty.to_string()).as_str();
179 C_str_slice(cx, ty_name)
182 C_u64(cx, cx.tcx.type_id_hash(substs.type_at(0)))
185 let ty = substs.type_at(0);
186 if !cx.layout_of(ty).is_zst() {
187 // Just zero out the stack slot.
188 // If we store a zero constant, LLVM will drown in vreg allocation for large data
189 // structures, and the generated code will be awful. (A telltale sign of this is
190 // large quantities of `mov [byte ptr foo],0` in the generated code.)
191 memset_intrinsic(bx, false, ty, llresult, C_u8(cx, 0), C_usize(cx, 1));
195 // Effectively no-ops
200 let tp_ty = substs.type_at(0);
202 C_bool(cx, bx.cx.type_needs_drop(tp_ty))
205 let ptr = args[0].immediate();
206 let offset = args[1].immediate();
207 bx.inbounds_gep(ptr, &[offset])
210 let ptr = args[0].immediate();
211 let offset = args[1].immediate();
212 bx.gep(ptr, &[offset])
215 "copy_nonoverlapping" => {
216 copy_intrinsic(bx, false, false, substs.type_at(0),
217 args[1].immediate(), args[0].immediate(), args[2].immediate())
220 copy_intrinsic(bx, true, false, substs.type_at(0),
221 args[1].immediate(), args[0].immediate(), args[2].immediate())
224 memset_intrinsic(bx, false, substs.type_at(0),
225 args[0].immediate(), args[1].immediate(), args[2].immediate())
228 "volatile_copy_nonoverlapping_memory" => {
229 copy_intrinsic(bx, false, true, substs.type_at(0),
230 args[0].immediate(), args[1].immediate(), args[2].immediate())
232 "volatile_copy_memory" => {
233 copy_intrinsic(bx, true, true, substs.type_at(0),
234 args[0].immediate(), args[1].immediate(), args[2].immediate())
236 "volatile_set_memory" => {
237 memset_intrinsic(bx, true, substs.type_at(0),
238 args[0].immediate(), args[1].immediate(), args[2].immediate())
240 "volatile_load" | "unaligned_volatile_load" => {
241 let tp_ty = substs.type_at(0);
242 let mut ptr = args[0].immediate();
243 if let PassMode::Cast(ty) = fn_ty.ret.mode {
244 ptr = bx.pointercast(ptr, ty.llvm_type(cx).ptr_to());
246 let load = bx.volatile_load(ptr);
247 let align = if name == "unaligned_volatile_load" {
250 cx.align_of(tp_ty).abi() as u32
253 llvm::LLVMSetAlignment(load, align);
255 to_immediate(bx, load, cx.layout_of(tp_ty))
257 "volatile_store" => {
258 let dst = args[0].deref(bx.cx);
259 args[1].val.volatile_store(bx, dst);
262 "unaligned_volatile_store" => {
263 let dst = args[0].deref(bx.cx);
264 args[1].val.unaligned_volatile_store(bx, dst);
267 "prefetch_read_data" | "prefetch_write_data" |
268 "prefetch_read_instruction" | "prefetch_write_instruction" => {
269 let expect = cx.get_intrinsic(&("llvm.prefetch"));
270 let (rw, cache_type) = match name {
271 "prefetch_read_data" => (0, 1),
272 "prefetch_write_data" => (1, 1),
273 "prefetch_read_instruction" => (0, 0),
274 "prefetch_write_instruction" => (1, 0),
281 C_i32(cx, cache_type)
284 "ctlz" | "ctlz_nonzero" | "cttz" | "cttz_nonzero" | "ctpop" | "bswap" |
285 "bitreverse" | "add_with_overflow" | "sub_with_overflow" |
286 "mul_with_overflow" | "overflowing_add" | "overflowing_sub" | "overflowing_mul" |
287 "unchecked_div" | "unchecked_rem" | "unchecked_shl" | "unchecked_shr" | "exact_div" => {
289 match int_type_width_signed(ty, cx) {
290 Some((width, signed)) =>
293 let y = C_bool(bx.cx, false);
294 let llfn = cx.get_intrinsic(&format!("llvm.{}.i{}", name, width));
295 bx.call(llfn, &[args[0].immediate(), y], None)
297 "ctlz_nonzero" | "cttz_nonzero" => {
298 let y = C_bool(bx.cx, true);
299 let llvm_name = &format!("llvm.{}.i{}", &name[..4], width);
300 let llfn = cx.get_intrinsic(llvm_name);
301 bx.call(llfn, &[args[0].immediate(), y], None)
303 "ctpop" => bx.call(cx.get_intrinsic(&format!("llvm.ctpop.i{}", width)),
304 &[args[0].immediate()], None),
307 args[0].immediate() // byte swap a u8/i8 is just a no-op
309 bx.call(cx.get_intrinsic(&format!("llvm.bswap.i{}", width)),
310 &[args[0].immediate()], None)
314 bx.call(cx.get_intrinsic(&format!("llvm.bitreverse.i{}", width)),
315 &[args[0].immediate()], None)
317 "add_with_overflow" | "sub_with_overflow" | "mul_with_overflow" => {
318 let intrinsic = format!("llvm.{}{}.with.overflow.i{}",
319 if signed { 's' } else { 'u' },
321 let llfn = bx.cx.get_intrinsic(&intrinsic);
323 // Convert `i1` to a `bool`, and write it to the out parameter
324 let pair = bx.call(llfn, &[
328 let val = bx.extract_value(pair, 0);
329 let overflow = bx.zext(bx.extract_value(pair, 1), Type::bool(cx));
331 let dest = result.project_field(bx, 0);
332 bx.store(val, dest.llval, dest.align);
333 let dest = result.project_field(bx, 1);
334 bx.store(overflow, dest.llval, dest.align);
338 "overflowing_add" => bx.add(args[0].immediate(), args[1].immediate()),
339 "overflowing_sub" => bx.sub(args[0].immediate(), args[1].immediate()),
340 "overflowing_mul" => bx.mul(args[0].immediate(), args[1].immediate()),
343 bx.exactsdiv(args[0].immediate(), args[1].immediate())
345 bx.exactudiv(args[0].immediate(), args[1].immediate())
349 bx.sdiv(args[0].immediate(), args[1].immediate())
351 bx.udiv(args[0].immediate(), args[1].immediate())
355 bx.srem(args[0].immediate(), args[1].immediate())
357 bx.urem(args[0].immediate(), args[1].immediate())
359 "unchecked_shl" => bx.shl(args[0].immediate(), args[1].immediate()),
362 bx.ashr(args[0].immediate(), args[1].immediate())
364 bx.lshr(args[0].immediate(), args[1].immediate())
369 span_invalid_monomorphization_error(
371 &format!("invalid monomorphization of `{}` intrinsic: \
372 expected basic integer type, found `{}`", name, ty));
378 "fadd_fast" | "fsub_fast" | "fmul_fast" | "fdiv_fast" | "frem_fast" => {
379 let sty = &arg_tys[0].sty;
380 match float_type_width(sty) {
383 "fadd_fast" => bx.fadd_fast(args[0].immediate(), args[1].immediate()),
384 "fsub_fast" => bx.fsub_fast(args[0].immediate(), args[1].immediate()),
385 "fmul_fast" => bx.fmul_fast(args[0].immediate(), args[1].immediate()),
386 "fdiv_fast" => bx.fdiv_fast(args[0].immediate(), args[1].immediate()),
387 "frem_fast" => bx.frem_fast(args[0].immediate(), args[1].immediate()),
391 span_invalid_monomorphization_error(
393 &format!("invalid monomorphization of `{}` intrinsic: \
394 expected basic float type, found `{}`", name, sty));
401 "discriminant_value" => {
402 args[0].deref(bx.cx).codegen_get_discr(bx, ret_ty)
405 name if name.starts_with("simd_") => {
406 match generic_simd_intrinsic(bx, name,
415 // This requires that atomic intrinsics follow a specific naming pattern:
416 // "atomic_<operation>[_<ordering>]", and no ordering means SeqCst
417 name if name.starts_with("atomic_") => {
418 use llvm::AtomicOrdering::*;
420 let split: Vec<&str> = name.split('_').collect();
422 let is_cxchg = split[1] == "cxchg" || split[1] == "cxchgweak";
423 let (order, failorder) = match split.len() {
424 2 => (SequentiallyConsistent, SequentiallyConsistent),
425 3 => match split[2] {
426 "unordered" => (Unordered, Unordered),
427 "relaxed" => (Monotonic, Monotonic),
428 "acq" => (Acquire, Acquire),
429 "rel" => (Release, Monotonic),
430 "acqrel" => (AcquireRelease, Acquire),
431 "failrelaxed" if is_cxchg =>
432 (SequentiallyConsistent, Monotonic),
433 "failacq" if is_cxchg =>
434 (SequentiallyConsistent, Acquire),
435 _ => cx.sess().fatal("unknown ordering in atomic intrinsic")
437 4 => match (split[2], split[3]) {
438 ("acq", "failrelaxed") if is_cxchg =>
439 (Acquire, Monotonic),
440 ("acqrel", "failrelaxed") if is_cxchg =>
441 (AcquireRelease, Monotonic),
442 _ => cx.sess().fatal("unknown ordering in atomic intrinsic")
444 _ => cx.sess().fatal("Atomic intrinsic not in correct format"),
447 let invalid_monomorphization = |ty| {
448 span_invalid_monomorphization_error(tcx.sess, span,
449 &format!("invalid monomorphization of `{}` intrinsic: \
450 expected basic integer type, found `{}`", name, ty));
454 "cxchg" | "cxchgweak" => {
455 let ty = substs.type_at(0);
456 if int_type_width_signed(ty, cx).is_some() {
457 let weak = if split[1] == "cxchgweak" { llvm::True } else { llvm::False };
458 let pair = bx.atomic_cmpxchg(
465 let val = bx.extract_value(pair, 0);
466 let success = bx.zext(bx.extract_value(pair, 1), Type::bool(bx.cx));
468 let dest = result.project_field(bx, 0);
469 bx.store(val, dest.llval, dest.align);
470 let dest = result.project_field(bx, 1);
471 bx.store(success, dest.llval, dest.align);
474 return invalid_monomorphization(ty);
479 let ty = substs.type_at(0);
480 if int_type_width_signed(ty, cx).is_some() {
481 let align = cx.align_of(ty);
482 bx.atomic_load(args[0].immediate(), order, align)
484 return invalid_monomorphization(ty);
489 let ty = substs.type_at(0);
490 if int_type_width_signed(ty, cx).is_some() {
491 let align = cx.align_of(ty);
492 bx.atomic_store(args[1].immediate(), args[0].immediate(), order, align);
495 return invalid_monomorphization(ty);
500 bx.atomic_fence(order, llvm::SynchronizationScope::CrossThread);
504 "singlethreadfence" => {
505 bx.atomic_fence(order, llvm::SynchronizationScope::SingleThread);
509 // These are all AtomicRMW ops
511 let atom_op = match op {
512 "xchg" => llvm::AtomicXchg,
513 "xadd" => llvm::AtomicAdd,
514 "xsub" => llvm::AtomicSub,
515 "and" => llvm::AtomicAnd,
516 "nand" => llvm::AtomicNand,
517 "or" => llvm::AtomicOr,
518 "xor" => llvm::AtomicXor,
519 "max" => llvm::AtomicMax,
520 "min" => llvm::AtomicMin,
521 "umax" => llvm::AtomicUMax,
522 "umin" => llvm::AtomicUMin,
523 _ => cx.sess().fatal("unknown atomic operation")
526 let ty = substs.type_at(0);
527 if int_type_width_signed(ty, cx).is_some() {
528 bx.atomic_rmw(atom_op, args[0].immediate(), args[1].immediate(), order)
530 return invalid_monomorphization(ty);
536 "nontemporal_store" => {
537 let dst = args[0].deref(bx.cx);
538 args[1].val.nontemporal_store(bx, dst);
543 let intr = match Intrinsic::find(&name) {
545 None => bug!("unknown intrinsic '{}'", name),
547 fn one<T>(x: Vec<T>) -> T {
548 assert_eq!(x.len(), 1);
549 x.into_iter().next().unwrap()
551 fn ty_to_type(cx: &CodegenCx<'ll, '_>, t: &intrinsics::Type) -> Vec<&'ll Type> {
552 use intrinsics::Type::*;
554 Void => vec![Type::void(cx)],
555 Integer(_signed, _width, llvm_width) => {
556 vec![Type::ix(cx, llvm_width as u64)]
560 32 => vec![Type::f32(cx)],
561 64 => vec![Type::f64(cx)],
565 Pointer(ref t, ref llvm_elem, _const) => {
566 let t = llvm_elem.as_ref().unwrap_or(t);
567 let elem = one(ty_to_type(cx, t));
570 Vector(ref t, ref llvm_elem, length) => {
571 let t = llvm_elem.as_ref().unwrap_or(t);
572 let elem = one(ty_to_type(cx, t));
573 vec![Type::vector(elem, length as u64)]
575 Aggregate(false, ref contents) => {
576 let elems = contents.iter()
577 .map(|t| one(ty_to_type(cx, t)))
578 .collect::<Vec<_>>();
579 vec![Type::struct_(cx, &elems, false)]
581 Aggregate(true, ref contents) => {
583 .flat_map(|t| ty_to_type(cx, t))
589 // This allows an argument list like `foo, (bar, baz),
590 // qux` to be converted into `foo, bar, baz, qux`, integer
591 // arguments to be truncated as needed and pointers to be
594 bx: &Builder<'a, 'll, 'tcx>,
595 t: &intrinsics::Type,
596 arg: &OperandRef<'ll, 'tcx>,
597 ) -> Vec<&'ll Value> {
599 intrinsics::Type::Aggregate(true, ref contents) => {
600 // We found a tuple that needs squishing! So
601 // run over the tuple and load each field.
603 // This assumes the type is "simple", i.e. no
604 // destructors, and the contents are SIMD
606 assert!(!bx.cx.type_needs_drop(arg.layout.ty));
607 let (ptr, align) = match arg.val {
608 OperandValue::Ref(ptr, None, align) => (ptr, align),
611 let arg = PlaceRef::new_sized(ptr, arg.layout, align);
612 (0..contents.len()).map(|i| {
613 arg.project_field(bx, i).load(bx).immediate()
616 intrinsics::Type::Pointer(_, Some(ref llvm_elem), _) => {
617 let llvm_elem = one(ty_to_type(bx.cx, llvm_elem));
618 vec![bx.pointercast(arg.immediate(), llvm_elem.ptr_to())]
620 intrinsics::Type::Vector(_, Some(ref llvm_elem), length) => {
621 let llvm_elem = one(ty_to_type(bx.cx, llvm_elem));
622 vec![bx.bitcast(arg.immediate(), Type::vector(llvm_elem, length as u64))]
624 intrinsics::Type::Integer(_, width, llvm_width) if width != llvm_width => {
625 // the LLVM intrinsic uses a smaller integer
626 // size than the C intrinsic's signature, so
627 // we have to trim it down here.
628 vec![bx.trunc(arg.immediate(), Type::ix(bx.cx, llvm_width as u64))]
630 _ => vec![arg.immediate()],
635 let inputs = intr.inputs.iter()
636 .flat_map(|t| ty_to_type(cx, t))
637 .collect::<Vec<_>>();
639 let outputs = one(ty_to_type(cx, &intr.output));
641 let llargs: Vec<_> = intr.inputs.iter().zip(args).flat_map(|(t, arg)| {
642 modify_as_needed(bx, t, arg)
644 assert_eq!(inputs.len(), llargs.len());
646 let val = match intr.definition {
647 intrinsics::IntrinsicDef::Named(name) => {
648 let f = declare::declare_cfn(cx,
650 Type::func(&inputs, outputs));
651 bx.call(f, &llargs, None)
656 intrinsics::Type::Aggregate(flatten, ref elems) => {
657 // the output is a tuple so we need to munge it properly
660 for i in 0..elems.len() {
661 let dest = result.project_field(bx, i);
662 let val = bx.extract_value(val, i as u64);
663 bx.store(val, dest.llval, dest.align);
672 if !fn_ty.ret.is_ignore() {
673 if let PassMode::Cast(ty) = fn_ty.ret.mode {
674 let ptr = bx.pointercast(result.llval, ty.llvm_type(cx).ptr_to());
675 bx.store(llval, ptr, result.align);
677 OperandRef::from_immediate_or_packed_pair(bx, llval, result.layout)
678 .val.store(bx, result);
684 bx: &Builder<'a, 'll, 'tcx>,
693 let (size, align) = cx.size_and_align_of(ty);
694 let size = C_usize(cx, size.bytes());
695 let align = C_i32(cx, align.abi() as i32);
697 let operation = if allow_overlap {
703 let name = format!("llvm.{}.p0i8.p0i8.i{}", operation,
704 cx.data_layout().pointer_size.bits());
706 let dst_ptr = bx.pointercast(dst, Type::i8p(cx));
707 let src_ptr = bx.pointercast(src, Type::i8p(cx));
708 let llfn = cx.get_intrinsic(&name);
715 C_bool(cx, volatile)],
720 bx: &Builder<'a, 'll, 'tcx>,
728 let (size, align) = cx.size_and_align_of(ty);
729 let size = C_usize(cx, size.bytes());
730 let align = C_i32(cx, align.abi() as i32);
731 let dst = bx.pointercast(dst, Type::i8p(cx));
732 call_memset(bx, dst, val, bx.mul(size, count), align, volatile)
736 bx: &Builder<'a, 'll, 'tcx>,
737 cx: &CodegenCx<'ll, 'tcx>,
740 local_ptr: &'ll Value,
743 if bx.sess().no_landing_pads() {
744 bx.call(func, &[data], None);
745 let ptr_align = bx.tcx().data_layout.pointer_align;
746 bx.store(C_null(Type::i8p(&bx.cx)), dest, ptr_align);
747 } else if wants_msvc_seh(bx.sess()) {
748 codegen_msvc_try(bx, cx, func, data, local_ptr, dest);
750 codegen_gnu_try(bx, cx, func, data, local_ptr, dest);
754 // MSVC's definition of the `rust_try` function.
756 // This implementation uses the new exception handling instructions in LLVM
757 // which have support in LLVM for SEH on MSVC targets. Although these
758 // instructions are meant to work for all targets, as of the time of this
759 // writing, however, LLVM does not recommend the usage of these new instructions
760 // as the old ones are still more optimized.
762 bx: &Builder<'a, 'll, 'tcx>,
763 cx: &CodegenCx<'ll, 'tcx>,
766 local_ptr: &'ll Value,
769 let llfn = get_rust_try_fn(cx, &mut |bx| {
772 bx.set_personality_fn(bx.cx.eh_personality());
774 let normal = bx.build_sibling_block("normal");
775 let catchswitch = bx.build_sibling_block("catchswitch");
776 let catchpad = bx.build_sibling_block("catchpad");
777 let caught = bx.build_sibling_block("caught");
779 let func = llvm::get_param(bx.llfn(), 0);
780 let data = llvm::get_param(bx.llfn(), 1);
781 let local_ptr = llvm::get_param(bx.llfn(), 2);
783 // We're generating an IR snippet that looks like:
785 // declare i32 @rust_try(%func, %data, %ptr) {
786 // %slot = alloca i64*
787 // invoke %func(%data) to label %normal unwind label %catchswitch
793 // %cs = catchswitch within none [%catchpad] unwind to caller
796 // %tok = catchpad within %cs [%type_descriptor, 0, %slot]
797 // %ptr[0] = %slot[0]
798 // %ptr[1] = %slot[1]
799 // catchret from %tok to label %caught
805 // This structure follows the basic usage of throw/try/catch in LLVM.
806 // For example, compile this C++ snippet to see what LLVM generates:
808 // #include <stdint.h>
810 // int bar(void (*foo)(void), uint64_t *ret) {
814 // } catch(uint64_t a[2]) {
821 // More information can be found in libstd's seh.rs implementation.
822 let i64p = Type::i64(cx).ptr_to();
823 let ptr_align = bx.tcx().data_layout.pointer_align;
824 let slot = bx.alloca(i64p, "slot", ptr_align);
825 bx.invoke(func, &[data], normal.llbb(), catchswitch.llbb(),
828 normal.ret(C_i32(cx, 0));
830 let cs = catchswitch.catch_switch(None, None, 1);
831 catchswitch.add_handler(cs, catchpad.llbb());
834 let tydesc = match tcx.lang_items().msvc_try_filter() {
835 Some(did) => ::consts::get_static(cx, did),
836 None => bug!("msvc_try_filter not defined"),
838 let tok = catchpad.catch_pad(cs, &[tydesc, C_i32(cx, 0), slot]);
839 let addr = catchpad.load(slot, ptr_align);
841 let i64_align = bx.tcx().data_layout.i64_align;
842 let arg1 = catchpad.load(addr, i64_align);
843 let val1 = C_i32(cx, 1);
844 let arg2 = catchpad.load(catchpad.inbounds_gep(addr, &[val1]), i64_align);
845 let local_ptr = catchpad.bitcast(local_ptr, i64p);
846 catchpad.store(arg1, local_ptr, i64_align);
847 catchpad.store(arg2, catchpad.inbounds_gep(local_ptr, &[val1]), i64_align);
848 catchpad.catch_ret(tok, caught.llbb());
850 caught.ret(C_i32(cx, 1));
853 // Note that no invoke is used here because by definition this function
854 // can't panic (that's what it's catching).
855 let ret = bx.call(llfn, &[func, data, local_ptr], None);
856 let i32_align = bx.tcx().data_layout.i32_align;
857 bx.store(ret, dest, i32_align);
860 // Definition of the standard "try" function for Rust using the GNU-like model
861 // of exceptions (e.g. the normal semantics of LLVM's landingpad and invoke
864 // This codegen is a little surprising because we always call a shim
865 // function instead of inlining the call to `invoke` manually here. This is done
866 // because in LLVM we're only allowed to have one personality per function
867 // definition. The call to the `try` intrinsic is being inlined into the
868 // function calling it, and that function may already have other personality
869 // functions in play. By calling a shim we're guaranteed that our shim will have
870 // the right personality function.
872 bx: &Builder<'a, 'll, 'tcx>,
873 cx: &CodegenCx<'ll, 'tcx>,
876 local_ptr: &'ll Value,
879 let llfn = get_rust_try_fn(cx, &mut |bx| {
882 // Codegens the shims described above:
885 // invoke %func(%args...) normal %normal unwind %catch
891 // (ptr, _) = landingpad
892 // store ptr, %local_ptr
895 // Note that the `local_ptr` data passed into the `try` intrinsic is
896 // expected to be `*mut *mut u8` for this to actually work, but that's
897 // managed by the standard library.
899 let then = bx.build_sibling_block("then");
900 let catch = bx.build_sibling_block("catch");
902 let func = llvm::get_param(bx.llfn(), 0);
903 let data = llvm::get_param(bx.llfn(), 1);
904 let local_ptr = llvm::get_param(bx.llfn(), 2);
905 bx.invoke(func, &[data], then.llbb(), catch.llbb(), None);
906 then.ret(C_i32(cx, 0));
908 // Type indicator for the exception being thrown.
910 // The first value in this tuple is a pointer to the exception object
911 // being thrown. The second value is a "selector" indicating which of
912 // the landing pad clauses the exception's type had been matched to.
913 // rust_try ignores the selector.
914 let lpad_ty = Type::struct_(cx, &[Type::i8p(cx), Type::i32(cx)],
916 let vals = catch.landing_pad(lpad_ty, bx.cx.eh_personality(), 1);
917 catch.add_clause(vals, C_null(Type::i8p(cx)));
918 let ptr = catch.extract_value(vals, 0);
919 let ptr_align = bx.tcx().data_layout.pointer_align;
920 catch.store(ptr, catch.bitcast(local_ptr, Type::i8p(cx).ptr_to()), ptr_align);
921 catch.ret(C_i32(cx, 1));
924 // Note that no invoke is used here because by definition this function
925 // can't panic (that's what it's catching).
926 let ret = bx.call(llfn, &[func, data, local_ptr], None);
927 let i32_align = bx.tcx().data_layout.i32_align;
928 bx.store(ret, dest, i32_align);
931 // Helper function to give a Block to a closure to codegen a shim function.
932 // This is currently primarily used for the `try` intrinsic functions above.
933 fn gen_fn<'ll, 'tcx>(
934 cx: &CodegenCx<'ll, 'tcx>,
936 inputs: Vec<Ty<'tcx>>,
938 codegen: &mut dyn FnMut(Builder<'_, 'll, 'tcx>),
940 let rust_fn_ty = cx.tcx.mk_fn_ptr(ty::Binder::bind(cx.tcx.mk_fn_sig(
944 hir::Unsafety::Unsafe,
947 let llfn = declare::define_internal_fn(cx, name, rust_fn_ty);
948 attributes::from_fn_attrs(cx, llfn, None);
949 let bx = Builder::new_block(cx, llfn, "entry-block");
954 // Helper function used to get a handle to the `__rust_try` function used to
957 // This function is only generated once and is then cached.
958 fn get_rust_try_fn<'ll, 'tcx>(
959 cx: &CodegenCx<'ll, 'tcx>,
960 codegen: &mut dyn FnMut(Builder<'_, 'll, 'tcx>),
962 if let Some(llfn) = cx.rust_try_fn.get() {
966 // Define the type up front for the signature of the rust_try function.
968 let i8p = tcx.mk_mut_ptr(tcx.types.i8);
969 let fn_ty = tcx.mk_fn_ptr(ty::Binder::bind(tcx.mk_fn_sig(
973 hir::Unsafety::Unsafe,
976 let output = tcx.types.i32;
977 let rust_try = gen_fn(cx, "__rust_try", vec![fn_ty, i8p, i8p], output, codegen);
978 cx.rust_try_fn.set(Some(rust_try));
982 fn span_invalid_monomorphization_error(a: &Session, b: Span, c: &str) {
983 span_err!(a, b, E0511, "{}", c);
986 fn generic_simd_intrinsic(
987 bx: &Builder<'a, 'll, 'tcx>,
990 args: &[OperandRef<'ll, 'tcx>],
994 ) -> Result<&'ll Value, ()> {
995 // macros for error handling:
996 macro_rules! emit_error {
1000 ($msg: tt, $($fmt: tt)*) => {
1001 span_invalid_monomorphization_error(
1003 &format!(concat!("invalid monomorphization of `{}` intrinsic: ",
1008 macro_rules! return_error {
1011 emit_error!($($fmt)*);
1017 macro_rules! require {
1018 ($cond: expr, $($fmt: tt)*) => {
1020 return_error!($($fmt)*);
1024 macro_rules! require_simd {
1025 ($ty: expr, $position: expr) => {
1026 require!($ty.is_simd(), "expected SIMD {} type, found non-SIMD `{}`", $position, $ty)
1033 let sig = tcx.normalize_erasing_late_bound_regions(
1034 ty::ParamEnv::reveal_all(),
1035 &callee_ty.fn_sig(tcx),
1037 let arg_tys = sig.inputs();
1039 // every intrinsic takes a SIMD vector as its first argument
1040 require_simd!(arg_tys[0], "input");
1041 let in_ty = arg_tys[0];
1042 let in_elem = arg_tys[0].simd_type(tcx);
1043 let in_len = arg_tys[0].simd_size(tcx);
1045 let comparison = match name {
1046 "simd_eq" => Some(hir::BinOpKind::Eq),
1047 "simd_ne" => Some(hir::BinOpKind::Ne),
1048 "simd_lt" => Some(hir::BinOpKind::Lt),
1049 "simd_le" => Some(hir::BinOpKind::Le),
1050 "simd_gt" => Some(hir::BinOpKind::Gt),
1051 "simd_ge" => Some(hir::BinOpKind::Ge),
1055 if let Some(cmp_op) = comparison {
1056 require_simd!(ret_ty, "return");
1058 let out_len = ret_ty.simd_size(tcx);
1059 require!(in_len == out_len,
1060 "expected return type with length {} (same as input type `{}`), \
1061 found `{}` with length {}",
1064 require!(llret_ty.element_type().kind() == TypeKind::Integer,
1065 "expected return type with integer elements, found `{}` with non-integer `{}`",
1067 ret_ty.simd_type(tcx));
1069 return Ok(compare_simd_types(bx,
1070 args[0].immediate(),
1071 args[1].immediate(),
1077 if name.starts_with("simd_shuffle") {
1078 let n: usize = match name["simd_shuffle".len()..].parse() {
1080 Err(_) => span_bug!(span,
1081 "bad `simd_shuffle` instruction only caught in codegen?")
1084 require_simd!(ret_ty, "return");
1086 let out_len = ret_ty.simd_size(tcx);
1087 require!(out_len == n,
1088 "expected return type of length {}, found `{}` with length {}",
1089 n, ret_ty, out_len);
1090 require!(in_elem == ret_ty.simd_type(tcx),
1091 "expected return element type `{}` (element of input `{}`), \
1092 found `{}` with element type `{}`",
1094 ret_ty, ret_ty.simd_type(tcx));
1096 let total_len = in_len as u128 * 2;
1098 let vector = args[2].immediate();
1100 let indices: Option<Vec<_>> = (0..n)
1103 let val = const_get_elt(vector, i as u64);
1104 match const_to_opt_u128(val, true) {
1106 emit_error!("shuffle index #{} is not a constant", arg_idx);
1109 Some(idx) if idx >= total_len => {
1110 emit_error!("shuffle index #{} is out of bounds (limit {})",
1111 arg_idx, total_len);
1114 Some(idx) => Some(C_i32(bx.cx, idx as i32)),
1118 let indices = match indices {
1120 None => return Ok(C_null(llret_ty))
1123 return Ok(bx.shuffle_vector(args[0].immediate(),
1124 args[1].immediate(),
1125 C_vector(&indices)))
1128 if name == "simd_insert" {
1129 require!(in_elem == arg_tys[2],
1130 "expected inserted type `{}` (element of input `{}`), found `{}`",
1131 in_elem, in_ty, arg_tys[2]);
1132 return Ok(bx.insert_element(args[0].immediate(),
1133 args[2].immediate(),
1134 args[1].immediate()))
1136 if name == "simd_extract" {
1137 require!(ret_ty == in_elem,
1138 "expected return type `{}` (element of input `{}`), found `{}`",
1139 in_elem, in_ty, ret_ty);
1140 return Ok(bx.extract_element(args[0].immediate(), args[1].immediate()))
1143 if name == "simd_select" {
1144 let m_elem_ty = in_elem;
1146 let v_len = arg_tys[1].simd_size(tcx);
1147 require!(m_len == v_len,
1148 "mismatched lengths: mask length `{}` != other vector length `{}`",
1151 match m_elem_ty.sty {
1154 return_error!("mask element type is `{}`, expected `i_`", m_elem_ty);
1157 // truncate the mask to a vector of i1s
1158 let i1 = Type::i1(bx.cx);
1159 let i1xn = Type::vector(i1, m_len as u64);
1160 let m_i1s = bx.trunc(args[0].immediate(), i1xn);
1161 return Ok(bx.select(m_i1s, args[1].immediate(), args[2].immediate()));
1164 fn simd_simple_float_intrinsic(
1166 in_elem: &::rustc::ty::TyS,
1167 in_ty: &::rustc::ty::TyS,
1169 bx: &Builder<'a, 'll, 'tcx>,
1171 args: &[OperandRef<'ll, 'tcx>],
1172 ) -> Result<&'ll Value, ()> {
1173 macro_rules! emit_error {
1177 ($msg: tt, $($fmt: tt)*) => {
1178 span_invalid_monomorphization_error(
1180 &format!(concat!("invalid monomorphization of `{}` intrinsic: ",
1185 macro_rules! return_error {
1188 emit_error!($($fmt)*);
1193 let ety = match in_elem.sty {
1194 ty::Float(f) if f.bit_width() == 32 => {
1195 if in_len < 2 || in_len > 16 {
1197 "unsupported floating-point vector `{}` with length `{}` \
1198 out-of-range [2, 16]",
1203 ty::Float(f) if f.bit_width() == 64 => {
1204 if in_len < 2 || in_len > 8 {
1205 return_error!("unsupported floating-point vector `{}` with length `{}` \
1206 out-of-range [2, 8]",
1212 return_error!("unsupported element type `{}` of floating-point vector `{}`",
1216 return_error!("`{}` is not a floating-point type", in_ty);
1220 let llvm_name = &format!("llvm.{0}.v{1}{2}", name, in_len, ety);
1221 let intrinsic = bx.cx.get_intrinsic(&llvm_name);
1222 let c = bx.call(intrinsic,
1223 &args.iter().map(|arg| arg.immediate()).collect::<Vec<_>>(),
1225 unsafe { llvm::LLVMRustSetHasUnsafeAlgebra(c) };
1229 if name == "simd_fsqrt" {
1230 return simd_simple_float_intrinsic("sqrt", in_elem, in_ty, in_len, bx, span, args);
1233 if name == "simd_fsin" {
1234 return simd_simple_float_intrinsic("sin", in_elem, in_ty, in_len, bx, span, args);
1237 if name == "simd_fcos" {
1238 return simd_simple_float_intrinsic("cos", in_elem, in_ty, in_len, bx, span, args);
1241 if name == "simd_fabs" {
1242 return simd_simple_float_intrinsic("fabs", in_elem, in_ty, in_len, bx, span, args);
1245 if name == "simd_floor" {
1246 return simd_simple_float_intrinsic("floor", in_elem, in_ty, in_len, bx, span, args);
1249 if name == "simd_ceil" {
1250 return simd_simple_float_intrinsic("ceil", in_elem, in_ty, in_len, bx, span, args);
1253 if name == "simd_fexp" {
1254 return simd_simple_float_intrinsic("exp", in_elem, in_ty, in_len, bx, span, args);
1257 if name == "simd_fexp2" {
1258 return simd_simple_float_intrinsic("exp2", in_elem, in_ty, in_len, bx, span, args);
1261 if name == "simd_flog10" {
1262 return simd_simple_float_intrinsic("log10", in_elem, in_ty, in_len, bx, span, args);
1265 if name == "simd_flog2" {
1266 return simd_simple_float_intrinsic("log2", in_elem, in_ty, in_len, bx, span, args);
1269 if name == "simd_flog" {
1270 return simd_simple_float_intrinsic("log", in_elem, in_ty, in_len, bx, span, args);
1273 if name == "simd_fpowi" {
1274 return simd_simple_float_intrinsic("powi", in_elem, in_ty, in_len, bx, span, args);
1277 if name == "simd_fpow" {
1278 return simd_simple_float_intrinsic("pow", in_elem, in_ty, in_len, bx, span, args);
1281 if name == "simd_fma" {
1282 return simd_simple_float_intrinsic("fma", in_elem, in_ty, in_len, bx, span, args);
1286 // https://github.com/llvm-mirror/llvm/blob/master/include/llvm/IR/Function.h#L182
1287 // https://github.com/llvm-mirror/llvm/blob/master/include/llvm/IR/Intrinsics.h#L81
1288 fn llvm_vector_str(elem_ty: ty::Ty, vec_len: usize, no_pointers: usize) -> String {
1289 let p0s: String = "p0".repeat(no_pointers);
1291 ty::Int(v) => format!("v{}{}i{}", vec_len, p0s, v.bit_width().unwrap()),
1292 ty::Uint(v) => format!("v{}{}i{}", vec_len, p0s, v.bit_width().unwrap()),
1293 ty::Float(v) => format!("v{}{}f{}", vec_len, p0s, v.bit_width()),
1294 _ => unreachable!(),
1298 fn llvm_vector_ty(cx: &CodegenCx<'ll, '_>, elem_ty: ty::Ty, vec_len: usize,
1299 mut no_pointers: usize) -> &'ll Type {
1300 // FIXME: use cx.layout_of(ty).llvm_type() ?
1301 let mut elem_ty = match elem_ty.sty {
1302 ty::Int(v) => Type::int_from_ty(cx, v),
1303 ty::Uint(v) => Type::uint_from_ty(cx, v),
1304 ty::Float(v) => Type::float_from_ty(cx, v),
1305 _ => unreachable!(),
1307 while no_pointers > 0 {
1308 elem_ty = elem_ty.ptr_to();
1311 Type::vector(elem_ty, vec_len as u64)
1315 if name == "simd_gather" {
1316 // simd_gather(values: <N x T>, pointers: <N x *_ T>,
1317 // mask: <N x i{M}>) -> <N x T>
1318 // * N: number of elements in the input vectors
1319 // * T: type of the element to load
1320 // * M: any integer width is supported, will be truncated to i1
1322 // All types must be simd vector types
1323 require_simd!(in_ty, "first");
1324 require_simd!(arg_tys[1], "second");
1325 require_simd!(arg_tys[2], "third");
1326 require_simd!(ret_ty, "return");
1328 // Of the same length:
1329 require!(in_len == arg_tys[1].simd_size(tcx),
1330 "expected {} argument with length {} (same as input type `{}`), \
1331 found `{}` with length {}", "second", in_len, in_ty, arg_tys[1],
1332 arg_tys[1].simd_size(tcx));
1333 require!(in_len == arg_tys[2].simd_size(tcx),
1334 "expected {} argument with length {} (same as input type `{}`), \
1335 found `{}` with length {}", "third", in_len, in_ty, arg_tys[2],
1336 arg_tys[2].simd_size(tcx));
1338 // The return type must match the first argument type
1339 require!(ret_ty == in_ty,
1340 "expected return type `{}`, found `{}`",
1343 // This counts how many pointers
1344 fn ptr_count(t: ty::Ty) -> usize {
1346 ty::RawPtr(p) => 1 + ptr_count(p.ty),
1352 fn non_ptr(t: ty::Ty) -> ty::Ty {
1354 ty::RawPtr(p) => non_ptr(p.ty),
1359 // The second argument must be a simd vector with an element type that's a pointer
1360 // to the element type of the first argument
1361 let (pointer_count, underlying_ty) = match arg_tys[1].simd_type(tcx).sty {
1362 ty::RawPtr(p) if p.ty == in_elem => (ptr_count(arg_tys[1].simd_type(tcx)),
1363 non_ptr(arg_tys[1].simd_type(tcx))),
1365 require!(false, "expected element type `{}` of second argument `{}` \
1366 to be a pointer to the element type `{}` of the first \
1367 argument `{}`, found `{}` != `*_ {}`",
1368 arg_tys[1].simd_type(tcx).sty, arg_tys[1], in_elem, in_ty,
1369 arg_tys[1].simd_type(tcx).sty, in_elem);
1373 assert!(pointer_count > 0);
1374 assert!(pointer_count - 1 == ptr_count(arg_tys[0].simd_type(tcx)));
1375 assert_eq!(underlying_ty, non_ptr(arg_tys[0].simd_type(tcx)));
1377 // The element type of the third argument must be a signed integer type of any width:
1378 match arg_tys[2].simd_type(tcx).sty {
1381 require!(false, "expected element type `{}` of third argument `{}` \
1382 to be a signed integer type",
1383 arg_tys[2].simd_type(tcx).sty, arg_tys[2]);
1387 // Alignment of T, must be a constant integer value:
1388 let alignment_ty = Type::i32(bx.cx);
1389 let alignment = C_i32(bx.cx, bx.cx.align_of(in_elem).abi() as i32);
1391 // Truncate the mask vector to a vector of i1s:
1392 let (mask, mask_ty) = {
1393 let i1 = Type::i1(bx.cx);
1394 let i1xn = Type::vector(i1, in_len as u64);
1395 (bx.trunc(args[2].immediate(), i1xn), i1xn)
1398 // Type of the vector of pointers:
1399 let llvm_pointer_vec_ty = llvm_vector_ty(bx.cx, underlying_ty, in_len, pointer_count);
1400 let llvm_pointer_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count);
1402 // Type of the vector of elements:
1403 let llvm_elem_vec_ty = llvm_vector_ty(bx.cx, underlying_ty, in_len, pointer_count - 1);
1404 let llvm_elem_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count - 1);
1406 let llvm_intrinsic = format!("llvm.masked.gather.{}.{}",
1407 llvm_elem_vec_str, llvm_pointer_vec_str);
1408 let f = declare::declare_cfn(bx.cx, &llvm_intrinsic,
1409 Type::func(&[llvm_pointer_vec_ty, alignment_ty, mask_ty,
1410 llvm_elem_vec_ty], llvm_elem_vec_ty));
1411 llvm::SetUnnamedAddr(f, false);
1412 let v = bx.call(f, &[args[1].immediate(), alignment, mask, args[0].immediate()],
1417 if name == "simd_scatter" {
1418 // simd_scatter(values: <N x T>, pointers: <N x *mut T>,
1419 // mask: <N x i{M}>) -> ()
1420 // * N: number of elements in the input vectors
1421 // * T: type of the element to load
1422 // * M: any integer width is supported, will be truncated to i1
1424 // All types must be simd vector types
1425 require_simd!(in_ty, "first");
1426 require_simd!(arg_tys[1], "second");
1427 require_simd!(arg_tys[2], "third");
1429 // Of the same length:
1430 require!(in_len == arg_tys[1].simd_size(tcx),
1431 "expected {} argument with length {} (same as input type `{}`), \
1432 found `{}` with length {}", "second", in_len, in_ty, arg_tys[1],
1433 arg_tys[1].simd_size(tcx));
1434 require!(in_len == arg_tys[2].simd_size(tcx),
1435 "expected {} argument with length {} (same as input type `{}`), \
1436 found `{}` with length {}", "third", in_len, in_ty, arg_tys[2],
1437 arg_tys[2].simd_size(tcx));
1439 // This counts how many pointers
1440 fn ptr_count(t: ty::Ty) -> usize {
1442 ty::RawPtr(p) => 1 + ptr_count(p.ty),
1448 fn non_ptr(t: ty::Ty) -> ty::Ty {
1450 ty::RawPtr(p) => non_ptr(p.ty),
1455 // The second argument must be a simd vector with an element type that's a pointer
1456 // to the element type of the first argument
1457 let (pointer_count, underlying_ty) = match arg_tys[1].simd_type(tcx).sty {
1458 ty::RawPtr(p) if p.ty == in_elem && p.mutbl == hir::MutMutable
1459 => (ptr_count(arg_tys[1].simd_type(tcx)),
1460 non_ptr(arg_tys[1].simd_type(tcx))),
1462 require!(false, "expected element type `{}` of second argument `{}` \
1463 to be a pointer to the element type `{}` of the first \
1464 argument `{}`, found `{}` != `*mut {}`",
1465 arg_tys[1].simd_type(tcx).sty, arg_tys[1], in_elem, in_ty,
1466 arg_tys[1].simd_type(tcx).sty, in_elem);
1470 assert!(pointer_count > 0);
1471 assert!(pointer_count - 1 == ptr_count(arg_tys[0].simd_type(tcx)));
1472 assert_eq!(underlying_ty, non_ptr(arg_tys[0].simd_type(tcx)));
1474 // The element type of the third argument must be a signed integer type of any width:
1475 match arg_tys[2].simd_type(tcx).sty {
1478 require!(false, "expected element type `{}` of third argument `{}` \
1479 to be a signed integer type",
1480 arg_tys[2].simd_type(tcx).sty, arg_tys[2]);
1484 // Alignment of T, must be a constant integer value:
1485 let alignment_ty = Type::i32(bx.cx);
1486 let alignment = C_i32(bx.cx, bx.cx.align_of(in_elem).abi() as i32);
1488 // Truncate the mask vector to a vector of i1s:
1489 let (mask, mask_ty) = {
1490 let i1 = Type::i1(bx.cx);
1491 let i1xn = Type::vector(i1, in_len as u64);
1492 (bx.trunc(args[2].immediate(), i1xn), i1xn)
1495 let ret_t = Type::void(bx.cx);
1497 // Type of the vector of pointers:
1498 let llvm_pointer_vec_ty = llvm_vector_ty(bx.cx, underlying_ty, in_len, pointer_count);
1499 let llvm_pointer_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count);
1501 // Type of the vector of elements:
1502 let llvm_elem_vec_ty = llvm_vector_ty(bx.cx, underlying_ty, in_len, pointer_count - 1);
1503 let llvm_elem_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count - 1);
1505 let llvm_intrinsic = format!("llvm.masked.scatter.{}.{}",
1506 llvm_elem_vec_str, llvm_pointer_vec_str);
1507 let f = declare::declare_cfn(bx.cx, &llvm_intrinsic,
1508 Type::func(&[llvm_elem_vec_ty,
1509 llvm_pointer_vec_ty,
1512 llvm::SetUnnamedAddr(f, false);
1513 let v = bx.call(f, &[args[0].immediate(), args[1].immediate(), alignment, mask],
1518 macro_rules! arith_red {
1519 ($name:tt : $integer_reduce:ident, $float_reduce:ident, $ordered:expr) => {
1521 require!(ret_ty == in_elem,
1522 "expected return type `{}` (element of input `{}`), found `{}`",
1523 in_elem, in_ty, ret_ty);
1524 return match in_elem.sty {
1525 ty::Int(_) | ty::Uint(_) => {
1526 let r = bx.$integer_reduce(args[0].immediate());
1528 // if overflow occurs, the result is the
1529 // mathematical result modulo 2^n:
1530 if name.contains("mul") {
1531 Ok(bx.mul(args[1].immediate(), r))
1533 Ok(bx.add(args[1].immediate(), r))
1536 Ok(bx.$integer_reduce(args[0].immediate()))
1540 // ordered arithmetic reductions take an accumulator
1541 let acc = if $ordered {
1542 let acc = args[1].immediate();
1543 // FIXME: https://bugs.llvm.org/show_bug.cgi?id=36734
1544 // * if the accumulator of the fadd isn't 0, incorrect
1545 // code is generated
1546 // * if the accumulator of the fmul isn't 1, incorrect
1547 // code is generated
1548 match const_get_real(acc) {
1549 None => return_error!("accumulator of {} is not a constant", $name),
1550 Some((v, loses_info)) => {
1551 if $name.contains("mul") && v != 1.0_f64 {
1552 return_error!("accumulator of {} is not 1.0", $name);
1553 } else if $name.contains("add") && v != 0.0_f64 {
1554 return_error!("accumulator of {} is not 0.0", $name);
1555 } else if loses_info {
1556 return_error!("accumulator of {} loses information", $name);
1562 // unordered arithmetic reductions do not:
1563 match f.bit_width() {
1564 32 => C_undef(Type::f32(bx.cx)),
1565 64 => C_undef(Type::f64(bx.cx)),
1568 unsupported {} from `{}` with element `{}` of size `{}` to `{}`"#,
1569 $name, in_ty, in_elem, v, ret_ty
1575 Ok(bx.$float_reduce(acc, args[0].immediate()))
1579 "unsupported {} from `{}` with element `{}` to `{}`",
1580 $name, in_ty, in_elem, ret_ty
1588 arith_red!("simd_reduce_add_ordered": vector_reduce_add, vector_reduce_fadd_fast, true);
1589 arith_red!("simd_reduce_mul_ordered": vector_reduce_mul, vector_reduce_fmul_fast, true);
1590 arith_red!("simd_reduce_add_unordered": vector_reduce_add, vector_reduce_fadd_fast, false);
1591 arith_red!("simd_reduce_mul_unordered": vector_reduce_mul, vector_reduce_fmul_fast, false);
1593 macro_rules! minmax_red {
1594 ($name:tt: $int_red:ident, $float_red:ident) => {
1596 require!(ret_ty == in_elem,
1597 "expected return type `{}` (element of input `{}`), found `{}`",
1598 in_elem, in_ty, ret_ty);
1599 return match in_elem.sty {
1601 Ok(bx.$int_red(args[0].immediate(), true))
1604 Ok(bx.$int_red(args[0].immediate(), false))
1607 Ok(bx.$float_red(args[0].immediate()))
1610 return_error!("unsupported {} from `{}` with element `{}` to `{}`",
1611 $name, in_ty, in_elem, ret_ty)
1619 minmax_red!("simd_reduce_min": vector_reduce_min, vector_reduce_fmin);
1620 minmax_red!("simd_reduce_max": vector_reduce_max, vector_reduce_fmax);
1622 minmax_red!("simd_reduce_min_nanless": vector_reduce_min, vector_reduce_fmin_fast);
1623 minmax_red!("simd_reduce_max_nanless": vector_reduce_max, vector_reduce_fmax_fast);
1625 macro_rules! bitwise_red {
1626 ($name:tt : $red:ident, $boolean:expr) => {
1628 let input = if !$boolean {
1629 require!(ret_ty == in_elem,
1630 "expected return type `{}` (element of input `{}`), found `{}`",
1631 in_elem, in_ty, ret_ty);
1635 ty::Int(_) | ty::Uint(_) => {},
1637 return_error!("unsupported {} from `{}` with element `{}` to `{}`",
1638 $name, in_ty, in_elem, ret_ty)
1642 // boolean reductions operate on vectors of i1s:
1643 let i1 = Type::i1(bx.cx);
1644 let i1xn = Type::vector(i1, in_len as u64);
1645 bx.trunc(args[0].immediate(), i1xn)
1647 return match in_elem.sty {
1648 ty::Int(_) | ty::Uint(_) => {
1649 let r = bx.$red(input);
1654 bx.zext(r, Type::bool(bx.cx))
1659 return_error!("unsupported {} from `{}` with element `{}` to `{}`",
1660 $name, in_ty, in_elem, ret_ty)
1667 bitwise_red!("simd_reduce_and": vector_reduce_and, false);
1668 bitwise_red!("simd_reduce_or": vector_reduce_or, false);
1669 bitwise_red!("simd_reduce_xor": vector_reduce_xor, false);
1670 bitwise_red!("simd_reduce_all": vector_reduce_and, true);
1671 bitwise_red!("simd_reduce_any": vector_reduce_or, true);
1673 if name == "simd_cast" {
1674 require_simd!(ret_ty, "return");
1675 let out_len = ret_ty.simd_size(tcx);
1676 require!(in_len == out_len,
1677 "expected return type with length {} (same as input type `{}`), \
1678 found `{}` with length {}",
1681 // casting cares about nominal type, not just structural type
1682 let out_elem = ret_ty.simd_type(tcx);
1684 if in_elem == out_elem { return Ok(args[0].immediate()); }
1686 enum Style { Float, Int(/* is signed? */ bool), Unsupported }
1688 let (in_style, in_width) = match in_elem.sty {
1689 // vectors of pointer-sized integers should've been
1690 // disallowed before here, so this unwrap is safe.
1691 ty::Int(i) => (Style::Int(true), i.bit_width().unwrap()),
1692 ty::Uint(u) => (Style::Int(false), u.bit_width().unwrap()),
1693 ty::Float(f) => (Style::Float, f.bit_width()),
1694 _ => (Style::Unsupported, 0)
1696 let (out_style, out_width) = match out_elem.sty {
1697 ty::Int(i) => (Style::Int(true), i.bit_width().unwrap()),
1698 ty::Uint(u) => (Style::Int(false), u.bit_width().unwrap()),
1699 ty::Float(f) => (Style::Float, f.bit_width()),
1700 _ => (Style::Unsupported, 0)
1703 match (in_style, out_style) {
1704 (Style::Int(in_is_signed), Style::Int(_)) => {
1705 return Ok(match in_width.cmp(&out_width) {
1706 Ordering::Greater => bx.trunc(args[0].immediate(), llret_ty),
1707 Ordering::Equal => args[0].immediate(),
1708 Ordering::Less => if in_is_signed {
1709 bx.sext(args[0].immediate(), llret_ty)
1711 bx.zext(args[0].immediate(), llret_ty)
1715 (Style::Int(in_is_signed), Style::Float) => {
1716 return Ok(if in_is_signed {
1717 bx.sitofp(args[0].immediate(), llret_ty)
1719 bx.uitofp(args[0].immediate(), llret_ty)
1722 (Style::Float, Style::Int(out_is_signed)) => {
1723 return Ok(if out_is_signed {
1724 bx.fptosi(args[0].immediate(), llret_ty)
1726 bx.fptoui(args[0].immediate(), llret_ty)
1729 (Style::Float, Style::Float) => {
1730 return Ok(match in_width.cmp(&out_width) {
1731 Ordering::Greater => bx.fptrunc(args[0].immediate(), llret_ty),
1732 Ordering::Equal => args[0].immediate(),
1733 Ordering::Less => bx.fpext(args[0].immediate(), llret_ty)
1736 _ => {/* Unsupported. Fallthrough. */}
1739 "unsupported cast from `{}` with element `{}` to `{}` with element `{}`",
1743 macro_rules! arith {
1744 ($($name: ident: $($($p: ident),* => $call: ident),*;)*) => {
1745 $(if name == stringify!($name) {
1747 $($(ty::$p(_))|* => {
1748 return Ok(bx.$call(args[0].immediate(), args[1].immediate()))
1753 "unsupported operation on `{}` with element `{}`",
1760 simd_add: Uint, Int => add, Float => fadd;
1761 simd_sub: Uint, Int => sub, Float => fsub;
1762 simd_mul: Uint, Int => mul, Float => fmul;
1763 simd_div: Uint => udiv, Int => sdiv, Float => fdiv;
1764 simd_rem: Uint => urem, Int => srem, Float => frem;
1765 simd_shl: Uint, Int => shl;
1766 simd_shr: Uint => lshr, Int => ashr;
1767 simd_and: Uint, Int => and;
1768 simd_or: Uint, Int => or;
1769 simd_xor: Uint, Int => xor;
1770 simd_fmax: Float => maxnum;
1771 simd_fmin: Float => minnum;
1773 span_bug!(span, "unknown SIMD intrinsic");
1776 // Returns the width of an int Ty, and if it's signed or not
1777 // Returns None if the type is not an integer
1778 // FIXME: there’s multiple of this functions, investigate using some of the already existing
1780 fn int_type_width_signed(ty: Ty, cx: &CodegenCx) -> Option<(u64, bool)> {
1782 ty::Int(t) => Some((match t {
1783 ast::IntTy::Isize => cx.tcx.sess.target.isize_ty.bit_width().unwrap() as u64,
1784 ast::IntTy::I8 => 8,
1785 ast::IntTy::I16 => 16,
1786 ast::IntTy::I32 => 32,
1787 ast::IntTy::I64 => 64,
1788 ast::IntTy::I128 => 128,
1790 ty::Uint(t) => Some((match t {
1791 ast::UintTy::Usize => cx.tcx.sess.target.usize_ty.bit_width().unwrap() as u64,
1792 ast::UintTy::U8 => 8,
1793 ast::UintTy::U16 => 16,
1794 ast::UintTy::U32 => 32,
1795 ast::UintTy::U64 => 64,
1796 ast::UintTy::U128 => 128,
1802 // Returns the width of a float TypeVariant
1803 // Returns None if the type is not a float
1804 fn float_type_width<'tcx>(sty: &ty::TyKind<'tcx>) -> Option<u64> {
1806 ty::Float(t) => Some(t.bit_width() as u64),