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)]
13 use intrinsics::{self, Intrinsic};
17 use abi::{Abi, FnType};
19 use mir::lvalue::{LvalueRef, Alignment};
27 use rustc::ty::{self, Ty};
30 use syntax::symbol::Symbol;
33 use rustc::session::Session;
36 use std::cmp::Ordering;
39 fn get_simple_intrinsic(ccx: &CrateContext, name: &str) -> Option<ValueRef> {
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(ccx.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_trans/trans/context.rs
89 pub fn trans_intrinsic_call<'a, 'tcx>(bcx: &Builder<'a, 'tcx>,
98 let (def_id, substs) = match callee_ty.sty {
99 ty::TyFnDef(def_id, substs) => (def_id, substs),
100 _ => bug!("expected fn item type, found {}", callee_ty)
103 let sig = callee_ty.fn_sig(tcx);
104 let sig = tcx.erase_late_bound_regions_and_normalize(&sig);
105 let arg_tys = sig.inputs();
106 let ret_ty = sig.output();
107 let name = &*tcx.item_name(def_id).as_str();
109 let llret_ty = type_of::type_of(ccx, ret_ty);
111 let simple = get_simple_intrinsic(ccx, name);
112 let llval = match name {
113 _ if simple.is_some() => {
114 bcx.call(simple.unwrap(), &llargs, None)
120 let expect = ccx.get_intrinsic(&("llvm.expect.i1"));
121 bcx.call(expect, &[llargs[0], C_bool(ccx, true)], None)
124 let expect = ccx.get_intrinsic(&("llvm.expect.i1"));
125 bcx.call(expect, &[llargs[0], C_bool(ccx, false)], None)
128 try_intrinsic(bcx, ccx, llargs[0], llargs[1], llargs[2], llresult);
132 let llfn = ccx.get_intrinsic(&("llvm.debugtrap"));
133 bcx.call(llfn, &[], None)
136 let tp_ty = substs.type_at(0);
137 let lltp_ty = type_of::type_of(ccx, tp_ty);
138 C_uint(ccx, machine::llsize_of_alloc(ccx, lltp_ty))
141 let tp_ty = substs.type_at(0);
142 if !bcx.ccx.shared().type_is_sized(tp_ty) {
144 glue::size_and_align_of_dst(bcx, tp_ty, llargs[1]);
147 let lltp_ty = type_of::type_of(ccx, tp_ty);
148 C_uint(ccx, machine::llsize_of_alloc(ccx, lltp_ty))
152 let tp_ty = substs.type_at(0);
153 C_uint(ccx, ccx.align_of(tp_ty))
155 "min_align_of_val" => {
156 let tp_ty = substs.type_at(0);
157 if !bcx.ccx.shared().type_is_sized(tp_ty) {
159 glue::size_and_align_of_dst(bcx, tp_ty, llargs[1]);
162 C_uint(ccx, ccx.align_of(tp_ty))
166 let tp_ty = substs.type_at(0);
167 let lltp_ty = type_of::type_of(ccx, tp_ty);
168 C_uint(ccx, machine::llalign_of_pref(ccx, lltp_ty))
171 let tp_ty = substs.type_at(0);
172 let ty_name = Symbol::intern(&tp_ty.to_string()).as_str();
173 C_str_slice(ccx, ty_name)
176 C_u64(ccx, ccx.tcx().type_id_hash(substs.type_at(0)))
179 let ty = substs.type_at(0);
180 if !type_is_zero_size(ccx, ty) {
181 // Just zero out the stack slot.
182 // If we store a zero constant, LLVM will drown in vreg allocation for large data
183 // structures, and the generated code will be awful. (A telltale sign of this is
184 // large quantities of `mov [byte ptr foo],0` in the generated code.)
185 memset_intrinsic(bcx, false, ty, llresult, C_u8(ccx, 0), C_uint(ccx, 1usize));
189 // Effectively no-ops
194 let tp_ty = substs.type_at(0);
196 C_bool(ccx, bcx.ccx.shared().type_needs_drop(tp_ty))
200 let offset = llargs[1];
201 bcx.inbounds_gep(ptr, &[offset])
205 let offset = llargs[1];
206 bcx.gep(ptr, &[offset])
209 "copy_nonoverlapping" => {
210 copy_intrinsic(bcx, false, false, substs.type_at(0), llargs[1], llargs[0], llargs[2])
213 copy_intrinsic(bcx, true, false, substs.type_at(0), llargs[1], llargs[0], llargs[2])
216 memset_intrinsic(bcx, false, substs.type_at(0), llargs[0], llargs[1], llargs[2])
219 "volatile_copy_nonoverlapping_memory" => {
220 copy_intrinsic(bcx, false, true, substs.type_at(0), llargs[0], llargs[1], llargs[2])
222 "volatile_copy_memory" => {
223 copy_intrinsic(bcx, true, true, substs.type_at(0), llargs[0], llargs[1], llargs[2])
225 "volatile_set_memory" => {
226 memset_intrinsic(bcx, true, substs.type_at(0), llargs[0], llargs[1], llargs[2])
229 let tp_ty = substs.type_at(0);
230 let mut ptr = llargs[0];
231 if let Some(ty) = fn_ty.ret.cast {
232 ptr = bcx.pointercast(ptr, ty.ptr_to());
234 let load = bcx.volatile_load(ptr);
236 llvm::LLVMSetAlignment(load, ccx.align_of(tp_ty));
238 to_immediate(bcx, load, tp_ty)
240 "volatile_store" => {
241 let tp_ty = substs.type_at(0);
242 if type_is_fat_ptr(bcx.ccx, tp_ty) {
243 bcx.volatile_store(llargs[1], get_dataptr(bcx, llargs[0]));
244 bcx.volatile_store(llargs[2], get_meta(bcx, llargs[0]));
246 let val = if fn_ty.args[1].is_indirect() {
247 bcx.load(llargs[1], None)
249 from_immediate(bcx, llargs[1])
251 let ptr = bcx.pointercast(llargs[0], val_ty(val).ptr_to());
252 let store = bcx.volatile_store(val, ptr);
254 llvm::LLVMSetAlignment(store, ccx.align_of(tp_ty));
259 "prefetch_read_data" | "prefetch_write_data" |
260 "prefetch_read_instruction" | "prefetch_write_instruction" => {
261 let expect = ccx.get_intrinsic(&("llvm.prefetch"));
262 let (rw, cache_type) = match name {
263 "prefetch_read_data" => (0, 1),
264 "prefetch_write_data" => (1, 1),
265 "prefetch_read_instruction" => (0, 0),
266 "prefetch_write_instruction" => (1, 0),
269 bcx.call(expect, &[llargs[0], C_i32(ccx, rw), llargs[1], C_i32(ccx, cache_type)], None)
271 "ctlz" | "ctlz_nonzero" | "cttz" | "cttz_nonzero" | "ctpop" | "bswap" |
272 "add_with_overflow" | "sub_with_overflow" | "mul_with_overflow" |
273 "overflowing_add" | "overflowing_sub" | "overflowing_mul" |
274 "unchecked_div" | "unchecked_rem" | "unchecked_shl" | "unchecked_shr" => {
275 let sty = &arg_tys[0].sty;
276 match int_type_width_signed(sty, ccx) {
277 Some((width, signed)) =>
280 let y = C_bool(bcx.ccx, false);
281 let llfn = ccx.get_intrinsic(&format!("llvm.{}.i{}", name, width));
282 bcx.call(llfn, &[llargs[0], y], None)
284 "ctlz_nonzero" | "cttz_nonzero" => {
285 let y = C_bool(bcx.ccx, true);
286 let llvm_name = &format!("llvm.{}.i{}", &name[..4], width);
287 let llfn = ccx.get_intrinsic(llvm_name);
288 bcx.call(llfn, &[llargs[0], y], None)
290 "ctpop" => bcx.call(ccx.get_intrinsic(&format!("llvm.ctpop.i{}", width)),
294 llargs[0] // byte swap a u8/i8 is just a no-op
296 bcx.call(ccx.get_intrinsic(&format!("llvm.bswap.i{}", width)),
300 "add_with_overflow" | "sub_with_overflow" | "mul_with_overflow" => {
301 let intrinsic = format!("llvm.{}{}.with.overflow.i{}",
302 if signed { 's' } else { 'u' },
304 let llfn = bcx.ccx.get_intrinsic(&intrinsic);
306 // Convert `i1` to a `bool`, and write it to the out parameter
307 let val = bcx.call(llfn, &[llargs[0], llargs[1]], None);
308 let result = bcx.extract_value(val, 0);
309 let overflow = bcx.zext(bcx.extract_value(val, 1), Type::bool(ccx));
310 bcx.store(result, bcx.struct_gep(llresult, 0), None);
311 bcx.store(overflow, bcx.struct_gep(llresult, 1), None);
315 "overflowing_add" => bcx.add(llargs[0], llargs[1]),
316 "overflowing_sub" => bcx.sub(llargs[0], llargs[1]),
317 "overflowing_mul" => bcx.mul(llargs[0], llargs[1]),
320 bcx.sdiv(llargs[0], llargs[1])
322 bcx.udiv(llargs[0], llargs[1])
326 bcx.srem(llargs[0], llargs[1])
328 bcx.urem(llargs[0], llargs[1])
330 "unchecked_shl" => bcx.shl(llargs[0], llargs[1]),
333 bcx.ashr(llargs[0], llargs[1])
335 bcx.lshr(llargs[0], llargs[1])
340 span_invalid_monomorphization_error(
342 &format!("invalid monomorphization of `{}` intrinsic: \
343 expected basic integer type, found `{}`", name, sty));
349 "fadd_fast" | "fsub_fast" | "fmul_fast" | "fdiv_fast" | "frem_fast" => {
350 let sty = &arg_tys[0].sty;
351 match float_type_width(sty) {
354 "fadd_fast" => bcx.fadd_fast(llargs[0], llargs[1]),
355 "fsub_fast" => bcx.fsub_fast(llargs[0], llargs[1]),
356 "fmul_fast" => bcx.fmul_fast(llargs[0], llargs[1]),
357 "fdiv_fast" => bcx.fdiv_fast(llargs[0], llargs[1]),
358 "frem_fast" => bcx.frem_fast(llargs[0], llargs[1]),
362 span_invalid_monomorphization_error(
364 &format!("invalid monomorphization of `{}` intrinsic: \
365 expected basic float type, found `{}`", name, sty));
372 "discriminant_value" => {
373 let val_ty = substs.type_at(0);
375 ty::TyAdt(adt, ..) if adt.is_enum() => {
376 adt::trans_get_discr(bcx, val_ty, llargs[0], Alignment::AbiAligned,
377 Some(llret_ty), true)
379 _ => C_null(llret_ty)
382 name if name.starts_with("simd_") => {
383 generic_simd_intrinsic(bcx, name,
389 // This requires that atomic intrinsics follow a specific naming pattern:
390 // "atomic_<operation>[_<ordering>]", and no ordering means SeqCst
391 name if name.starts_with("atomic_") => {
392 use llvm::AtomicOrdering::*;
394 let split: Vec<&str> = name.split('_').collect();
396 let is_cxchg = split[1] == "cxchg" || split[1] == "cxchgweak";
397 let (order, failorder) = match split.len() {
398 2 => (SequentiallyConsistent, SequentiallyConsistent),
399 3 => match split[2] {
400 "unordered" => (Unordered, Unordered),
401 "relaxed" => (Monotonic, Monotonic),
402 "acq" => (Acquire, Acquire),
403 "rel" => (Release, Monotonic),
404 "acqrel" => (AcquireRelease, Acquire),
405 "failrelaxed" if is_cxchg =>
406 (SequentiallyConsistent, Monotonic),
407 "failacq" if is_cxchg =>
408 (SequentiallyConsistent, Acquire),
409 _ => ccx.sess().fatal("unknown ordering in atomic intrinsic")
411 4 => match (split[2], split[3]) {
412 ("acq", "failrelaxed") if is_cxchg =>
413 (Acquire, Monotonic),
414 ("acqrel", "failrelaxed") if is_cxchg =>
415 (AcquireRelease, Monotonic),
416 _ => ccx.sess().fatal("unknown ordering in atomic intrinsic")
418 _ => ccx.sess().fatal("Atomic intrinsic not in correct format"),
421 let invalid_monomorphization = |sty| {
422 span_invalid_monomorphization_error(tcx.sess, span,
423 &format!("invalid monomorphization of `{}` intrinsic: \
424 expected basic integer type, found `{}`", name, sty));
428 "cxchg" | "cxchgweak" => {
429 let sty = &substs.type_at(0).sty;
430 if int_type_width_signed(sty, ccx).is_some() {
431 let weak = if split[1] == "cxchgweak" { llvm::True } else { llvm::False };
432 let val = bcx.atomic_cmpxchg(llargs[0], llargs[1], llargs[2], order,
434 let result = bcx.extract_value(val, 0);
435 let success = bcx.zext(bcx.extract_value(val, 1), Type::bool(bcx.ccx));
436 bcx.store(result, bcx.struct_gep(llresult, 0), None);
437 bcx.store(success, bcx.struct_gep(llresult, 1), None);
439 invalid_monomorphization(sty);
445 let sty = &substs.type_at(0).sty;
446 if int_type_width_signed(sty, ccx).is_some() {
447 bcx.atomic_load(llargs[0], order)
449 invalid_monomorphization(sty);
455 let sty = &substs.type_at(0).sty;
456 if int_type_width_signed(sty, ccx).is_some() {
457 bcx.atomic_store(llargs[1], llargs[0], order);
459 invalid_monomorphization(sty);
465 bcx.atomic_fence(order, llvm::SynchronizationScope::CrossThread);
469 "singlethreadfence" => {
470 bcx.atomic_fence(order, llvm::SynchronizationScope::SingleThread);
474 // These are all AtomicRMW ops
476 let atom_op = match op {
477 "xchg" => llvm::AtomicXchg,
478 "xadd" => llvm::AtomicAdd,
479 "xsub" => llvm::AtomicSub,
480 "and" => llvm::AtomicAnd,
481 "nand" => llvm::AtomicNand,
482 "or" => llvm::AtomicOr,
483 "xor" => llvm::AtomicXor,
484 "max" => llvm::AtomicMax,
485 "min" => llvm::AtomicMin,
486 "umax" => llvm::AtomicUMax,
487 "umin" => llvm::AtomicUMin,
488 _ => ccx.sess().fatal("unknown atomic operation")
491 let sty = &substs.type_at(0).sty;
492 if int_type_width_signed(sty, ccx).is_some() {
493 bcx.atomic_rmw(atom_op, llargs[0], llargs[1], order)
495 invalid_monomorphization(sty);
503 let intr = match Intrinsic::find(&name) {
505 None => bug!("unknown intrinsic '{}'", name),
507 fn one<T>(x: Vec<T>) -> T {
508 assert_eq!(x.len(), 1);
509 x.into_iter().next().unwrap()
511 fn ty_to_type(ccx: &CrateContext, t: &intrinsics::Type,
512 any_changes_needed: &mut bool) -> Vec<Type> {
513 use intrinsics::Type::*;
515 Void => vec![Type::void(ccx)],
516 Integer(_signed, width, llvm_width) => {
517 *any_changes_needed |= width != llvm_width;
518 vec![Type::ix(ccx, llvm_width as u64)]
522 32 => vec![Type::f32(ccx)],
523 64 => vec![Type::f64(ccx)],
527 Pointer(ref t, ref llvm_elem, _const) => {
528 *any_changes_needed |= llvm_elem.is_some();
530 let t = llvm_elem.as_ref().unwrap_or(t);
531 let elem = one(ty_to_type(ccx, t, any_changes_needed));
534 Vector(ref t, ref llvm_elem, length) => {
535 *any_changes_needed |= llvm_elem.is_some();
537 let t = llvm_elem.as_ref().unwrap_or(t);
538 let elem = one(ty_to_type(ccx, t, any_changes_needed));
539 vec![Type::vector(&elem, length as u64)]
541 Aggregate(false, ref contents) => {
542 let elems = contents.iter()
543 .map(|t| one(ty_to_type(ccx, t, any_changes_needed)))
544 .collect::<Vec<_>>();
545 vec![Type::struct_(ccx, &elems, false)]
547 Aggregate(true, ref contents) => {
548 *any_changes_needed = true;
550 .flat_map(|t| ty_to_type(ccx, t, any_changes_needed))
556 // This allows an argument list like `foo, (bar, baz),
557 // qux` to be converted into `foo, bar, baz, qux`, integer
558 // arguments to be truncated as needed and pointers to be
560 fn modify_as_needed<'a, 'tcx>(bcx: &Builder<'a, 'tcx>,
561 t: &intrinsics::Type,
567 intrinsics::Type::Aggregate(true, ref contents) => {
568 // We found a tuple that needs squishing! So
569 // run over the tuple and load each field.
571 // This assumes the type is "simple", i.e. no
572 // destructors, and the contents are SIMD
574 assert!(!bcx.ccx.shared().type_needs_drop(arg_type));
575 let arg = LvalueRef::new_sized_ty(llarg, arg_type, Alignment::AbiAligned);
576 (0..contents.len()).map(|i| {
577 let (ptr, align) = arg.trans_field_ptr(bcx, i);
578 bcx.load(ptr, align.to_align())
581 intrinsics::Type::Pointer(_, Some(ref llvm_elem), _) => {
582 let llvm_elem = one(ty_to_type(bcx.ccx, llvm_elem, &mut false));
583 vec![bcx.pointercast(llarg, llvm_elem.ptr_to())]
585 intrinsics::Type::Vector(_, Some(ref llvm_elem), length) => {
586 let llvm_elem = one(ty_to_type(bcx.ccx, llvm_elem, &mut false));
587 vec![bcx.bitcast(llarg, Type::vector(&llvm_elem, length as u64))]
589 intrinsics::Type::Integer(_, width, llvm_width) if width != llvm_width => {
590 // the LLVM intrinsic uses a smaller integer
591 // size than the C intrinsic's signature, so
592 // we have to trim it down here.
593 vec![bcx.trunc(llarg, Type::ix(bcx.ccx, llvm_width as u64))]
600 let mut any_changes_needed = false;
601 let inputs = intr.inputs.iter()
602 .flat_map(|t| ty_to_type(ccx, t, &mut any_changes_needed))
603 .collect::<Vec<_>>();
605 let mut out_changes = false;
606 let outputs = one(ty_to_type(ccx, &intr.output, &mut out_changes));
607 // outputting a flattened aggregate is nonsense
608 assert!(!out_changes);
610 let llargs = if !any_changes_needed {
611 // no aggregates to flatten, so no change needed
614 // there are some aggregates that need to be flattened
615 // in the LLVM call, so we need to run over the types
616 // again to find them and extract the arguments
620 .flat_map(|((t, llarg), ty)| modify_as_needed(bcx, t, ty, *llarg))
623 assert_eq!(inputs.len(), llargs.len());
625 let val = match intr.definition {
626 intrinsics::IntrinsicDef::Named(name) => {
627 let f = declare::declare_cfn(ccx,
629 Type::func(&inputs, &outputs));
630 bcx.call(f, &llargs, None)
635 intrinsics::Type::Aggregate(flatten, ref elems) => {
636 // the output is a tuple so we need to munge it properly
639 for i in 0..elems.len() {
640 let val = bcx.extract_value(val, i);
641 let lval = LvalueRef::new_sized_ty(llresult, ret_ty,
642 Alignment::AbiAligned);
643 let (dest, align) = lval.trans_field_ptr(bcx, i);
644 bcx.store(val, dest, align.to_align());
653 if val_ty(llval) != Type::void(ccx) && machine::llsize_of_alloc(ccx, val_ty(llval)) != 0 {
654 if let Some(ty) = fn_ty.ret.cast {
655 let ptr = bcx.pointercast(llresult, ty.ptr_to());
656 bcx.store(llval, ptr, Some(ccx.align_of(ret_ty)));
658 store_ty(bcx, llval, llresult, Alignment::AbiAligned, ret_ty);
663 fn copy_intrinsic<'a, 'tcx>(bcx: &Builder<'a, 'tcx>,
672 let lltp_ty = type_of::type_of(ccx, tp_ty);
673 let align = C_i32(ccx, ccx.align_of(tp_ty) as i32);
674 let size = machine::llsize_of(ccx, lltp_ty);
675 let int_size = machine::llbitsize_of_real(ccx, ccx.int_type());
677 let operation = if allow_overlap {
683 let name = format!("llvm.{}.p0i8.p0i8.i{}", operation, int_size);
685 let dst_ptr = bcx.pointercast(dst, Type::i8p(ccx));
686 let src_ptr = bcx.pointercast(src, Type::i8p(ccx));
687 let llfn = ccx.get_intrinsic(&name);
692 bcx.mul(size, count),
694 C_bool(ccx, volatile)],
698 fn memset_intrinsic<'a, 'tcx>(
699 bcx: &Builder<'a, 'tcx>,
707 let align = C_i32(ccx, ccx.align_of(ty) as i32);
708 let lltp_ty = type_of::type_of(ccx, ty);
709 let size = machine::llsize_of(ccx, lltp_ty);
710 let dst = bcx.pointercast(dst, Type::i8p(ccx));
711 call_memset(bcx, dst, val, bcx.mul(size, count), align, volatile)
714 fn try_intrinsic<'a, 'tcx>(
715 bcx: &Builder<'a, 'tcx>,
722 if bcx.sess().no_landing_pads() {
723 bcx.call(func, &[data], None);
724 bcx.store(C_null(Type::i8p(&bcx.ccx)), dest, None);
725 } else if wants_msvc_seh(bcx.sess()) {
726 trans_msvc_try(bcx, ccx, func, data, local_ptr, dest);
728 trans_gnu_try(bcx, ccx, func, data, local_ptr, dest);
732 // MSVC's definition of the `rust_try` function.
734 // This implementation uses the new exception handling instructions in LLVM
735 // which have support in LLVM for SEH on MSVC targets. Although these
736 // instructions are meant to work for all targets, as of the time of this
737 // writing, however, LLVM does not recommend the usage of these new instructions
738 // as the old ones are still more optimized.
739 fn trans_msvc_try<'a, 'tcx>(bcx: &Builder<'a, 'tcx>,
745 let llfn = get_rust_try_fn(ccx, &mut |bcx| {
748 bcx.set_personality_fn(bcx.ccx.eh_personality());
750 let normal = bcx.build_sibling_block("normal");
751 let catchswitch = bcx.build_sibling_block("catchswitch");
752 let catchpad = bcx.build_sibling_block("catchpad");
753 let caught = bcx.build_sibling_block("caught");
755 let func = llvm::get_param(bcx.llfn(), 0);
756 let data = llvm::get_param(bcx.llfn(), 1);
757 let local_ptr = llvm::get_param(bcx.llfn(), 2);
759 // We're generating an IR snippet that looks like:
761 // declare i32 @rust_try(%func, %data, %ptr) {
762 // %slot = alloca i64*
763 // invoke %func(%data) to label %normal unwind label %catchswitch
769 // %cs = catchswitch within none [%catchpad] unwind to caller
772 // %tok = catchpad within %cs [%type_descriptor, 0, %slot]
773 // %ptr[0] = %slot[0]
774 // %ptr[1] = %slot[1]
775 // catchret from %tok to label %caught
781 // This structure follows the basic usage of throw/try/catch in LLVM.
782 // For example, compile this C++ snippet to see what LLVM generates:
784 // #include <stdint.h>
786 // int bar(void (*foo)(void), uint64_t *ret) {
790 // } catch(uint64_t a[2]) {
797 // More information can be found in libstd's seh.rs implementation.
798 let i64p = Type::i64(ccx).ptr_to();
799 let slot = bcx.alloca(i64p, "slot", None);
800 bcx.invoke(func, &[data], normal.llbb(), catchswitch.llbb(),
803 normal.ret(C_i32(ccx, 0));
805 let cs = catchswitch.catch_switch(None, None, 1);
806 catchswitch.add_handler(cs, catchpad.llbb());
809 let tydesc = match tcx.lang_items.msvc_try_filter() {
810 Some(did) => ::consts::get_static(ccx, did),
811 None => bug!("msvc_try_filter not defined"),
813 let tok = catchpad.catch_pad(cs, &[tydesc, C_i32(ccx, 0), slot]);
814 let addr = catchpad.load(slot, None);
815 let arg1 = catchpad.load(addr, None);
816 let val1 = C_i32(ccx, 1);
817 let arg2 = catchpad.load(catchpad.inbounds_gep(addr, &[val1]), None);
818 let local_ptr = catchpad.bitcast(local_ptr, i64p);
819 catchpad.store(arg1, local_ptr, None);
820 catchpad.store(arg2, catchpad.inbounds_gep(local_ptr, &[val1]), None);
821 catchpad.catch_ret(tok, caught.llbb());
823 caught.ret(C_i32(ccx, 1));
826 // Note that no invoke is used here because by definition this function
827 // can't panic (that's what it's catching).
828 let ret = bcx.call(llfn, &[func, data, local_ptr], None);
829 bcx.store(ret, dest, None);
832 // Definition of the standard "try" function for Rust using the GNU-like model
833 // of exceptions (e.g. the normal semantics of LLVM's landingpad and invoke
836 // This translation is a little surprising because we always call a shim
837 // function instead of inlining the call to `invoke` manually here. This is done
838 // because in LLVM we're only allowed to have one personality per function
839 // definition. The call to the `try` intrinsic is being inlined into the
840 // function calling it, and that function may already have other personality
841 // functions in play. By calling a shim we're guaranteed that our shim will have
842 // the right personality function.
843 fn trans_gnu_try<'a, 'tcx>(bcx: &Builder<'a, 'tcx>,
849 let llfn = get_rust_try_fn(ccx, &mut |bcx| {
852 // Translates the shims described above:
855 // invoke %func(%args...) normal %normal unwind %catch
861 // (ptr, _) = landingpad
862 // store ptr, %local_ptr
865 // Note that the `local_ptr` data passed into the `try` intrinsic is
866 // expected to be `*mut *mut u8` for this to actually work, but that's
867 // managed by the standard library.
869 let then = bcx.build_sibling_block("then");
870 let catch = bcx.build_sibling_block("catch");
872 let func = llvm::get_param(bcx.llfn(), 0);
873 let data = llvm::get_param(bcx.llfn(), 1);
874 let local_ptr = llvm::get_param(bcx.llfn(), 2);
875 bcx.invoke(func, &[data], then.llbb(), catch.llbb(), None);
876 then.ret(C_i32(ccx, 0));
878 // Type indicator for the exception being thrown.
880 // The first value in this tuple is a pointer to the exception object
881 // being thrown. The second value is a "selector" indicating which of
882 // the landing pad clauses the exception's type had been matched to.
883 // rust_try ignores the selector.
884 let lpad_ty = Type::struct_(ccx, &[Type::i8p(ccx), Type::i32(ccx)],
886 let vals = catch.landing_pad(lpad_ty, bcx.ccx.eh_personality(), 1, catch.llfn());
887 catch.add_clause(vals, C_null(Type::i8p(ccx)));
888 let ptr = catch.extract_value(vals, 0);
889 catch.store(ptr, catch.bitcast(local_ptr, Type::i8p(ccx).ptr_to()), None);
890 catch.ret(C_i32(ccx, 1));
893 // Note that no invoke is used here because by definition this function
894 // can't panic (that's what it's catching).
895 let ret = bcx.call(llfn, &[func, data, local_ptr], None);
896 bcx.store(ret, dest, None);
899 // Helper function to give a Block to a closure to translate a shim function.
900 // This is currently primarily used for the `try` intrinsic functions above.
901 fn gen_fn<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
903 inputs: Vec<Ty<'tcx>>,
905 trans: &mut for<'b> FnMut(Builder<'b, 'tcx>))
907 let rust_fn_ty = ccx.tcx().mk_fn_ptr(ty::Binder(ccx.tcx().mk_fn_sig(
911 hir::Unsafety::Unsafe,
914 let llfn = declare::define_internal_fn(ccx, name, rust_fn_ty);
915 let bcx = Builder::new_block(ccx, llfn, "entry-block");
920 // Helper function used to get a handle to the `__rust_try` function used to
923 // This function is only generated once and is then cached.
924 fn get_rust_try_fn<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
925 trans: &mut for<'b> FnMut(Builder<'b, 'tcx>))
927 if let Some(llfn) = ccx.rust_try_fn().get() {
931 // Define the type up front for the signature of the rust_try function.
933 let i8p = tcx.mk_mut_ptr(tcx.types.i8);
934 let fn_ty = tcx.mk_fn_ptr(ty::Binder(tcx.mk_fn_sig(
938 hir::Unsafety::Unsafe,
941 let output = tcx.types.i32;
942 let rust_try = gen_fn(ccx, "__rust_try", vec![fn_ty, i8p, i8p], output, trans);
943 ccx.rust_try_fn().set(Some(rust_try));
947 fn span_invalid_monomorphization_error(a: &Session, b: Span, c: &str) {
948 span_err!(a, b, E0511, "{}", c);
951 fn generic_simd_intrinsic<'a, 'tcx>(
952 bcx: &Builder<'a, 'tcx>,
960 // macros for error handling:
961 macro_rules! emit_error {
965 ($msg: tt, $($fmt: tt)*) => {
966 span_invalid_monomorphization_error(
968 &format!(concat!("invalid monomorphization of `{}` intrinsic: ",
973 macro_rules! require {
974 ($cond: expr, $($fmt: tt)*) => {
976 emit_error!($($fmt)*);
977 return C_nil(bcx.ccx)
981 macro_rules! require_simd {
982 ($ty: expr, $position: expr) => {
983 require!($ty.is_simd(), "expected SIMD {} type, found non-SIMD `{}`", $position, $ty)
990 let sig = tcx.erase_late_bound_regions_and_normalize(&callee_ty.fn_sig(tcx));
991 let arg_tys = sig.inputs();
993 // every intrinsic takes a SIMD vector as its first argument
994 require_simd!(arg_tys[0], "input");
995 let in_ty = arg_tys[0];
996 let in_elem = arg_tys[0].simd_type(tcx);
997 let in_len = arg_tys[0].simd_size(tcx);
999 let comparison = match name {
1000 "simd_eq" => Some(hir::BiEq),
1001 "simd_ne" => Some(hir::BiNe),
1002 "simd_lt" => Some(hir::BiLt),
1003 "simd_le" => Some(hir::BiLe),
1004 "simd_gt" => Some(hir::BiGt),
1005 "simd_ge" => Some(hir::BiGe),
1009 if let Some(cmp_op) = comparison {
1010 require_simd!(ret_ty, "return");
1012 let out_len = ret_ty.simd_size(tcx);
1013 require!(in_len == out_len,
1014 "expected return type with length {} (same as input type `{}`), \
1015 found `{}` with length {}",
1018 require!(llret_ty.element_type().kind() == llvm::Integer,
1019 "expected return type with integer elements, found `{}` with non-integer `{}`",
1021 ret_ty.simd_type(tcx));
1023 return compare_simd_types(bcx,
1031 if name.starts_with("simd_shuffle") {
1032 let n: usize = match name["simd_shuffle".len()..].parse() {
1034 Err(_) => span_bug!(span,
1035 "bad `simd_shuffle` instruction only caught in trans?")
1038 require_simd!(ret_ty, "return");
1040 let out_len = ret_ty.simd_size(tcx);
1041 require!(out_len == n,
1042 "expected return type of length {}, found `{}` with length {}",
1043 n, ret_ty, out_len);
1044 require!(in_elem == ret_ty.simd_type(tcx),
1045 "expected return element type `{}` (element of input `{}`), \
1046 found `{}` with element type `{}`",
1048 ret_ty, ret_ty.simd_type(tcx));
1050 let total_len = in_len as u128 * 2;
1052 let vector = llargs[2];
1054 let indices: Option<Vec<_>> = (0..n)
1057 let val = const_get_elt(vector, &[i as libc::c_uint]);
1058 match const_to_opt_u128(val, true) {
1060 emit_error!("shuffle index #{} is not a constant", arg_idx);
1063 Some(idx) if idx >= total_len => {
1064 emit_error!("shuffle index #{} is out of bounds (limit {})",
1065 arg_idx, total_len);
1068 Some(idx) => Some(C_i32(bcx.ccx, idx as i32)),
1072 let indices = match indices {
1074 None => return C_null(llret_ty)
1077 return bcx.shuffle_vector(llargs[0], llargs[1], C_vector(&indices))
1080 if name == "simd_insert" {
1081 require!(in_elem == arg_tys[2],
1082 "expected inserted type `{}` (element of input `{}`), found `{}`",
1083 in_elem, in_ty, arg_tys[2]);
1084 return bcx.insert_element(llargs[0], llargs[2], llargs[1])
1086 if name == "simd_extract" {
1087 require!(ret_ty == in_elem,
1088 "expected return type `{}` (element of input `{}`), found `{}`",
1089 in_elem, in_ty, ret_ty);
1090 return bcx.extract_element(llargs[0], llargs[1])
1093 if name == "simd_cast" {
1094 require_simd!(ret_ty, "return");
1095 let out_len = ret_ty.simd_size(tcx);
1096 require!(in_len == out_len,
1097 "expected return type with length {} (same as input type `{}`), \
1098 found `{}` with length {}",
1101 // casting cares about nominal type, not just structural type
1102 let out_elem = ret_ty.simd_type(tcx);
1104 if in_elem == out_elem { return llargs[0]; }
1106 enum Style { Float, Int(/* is signed? */ bool), Unsupported }
1108 let (in_style, in_width) = match in_elem.sty {
1109 // vectors of pointer-sized integers should've been
1110 // disallowed before here, so this unwrap is safe.
1111 ty::TyInt(i) => (Style::Int(true), i.bit_width().unwrap()),
1112 ty::TyUint(u) => (Style::Int(false), u.bit_width().unwrap()),
1113 ty::TyFloat(f) => (Style::Float, f.bit_width()),
1114 _ => (Style::Unsupported, 0)
1116 let (out_style, out_width) = match out_elem.sty {
1117 ty::TyInt(i) => (Style::Int(true), i.bit_width().unwrap()),
1118 ty::TyUint(u) => (Style::Int(false), u.bit_width().unwrap()),
1119 ty::TyFloat(f) => (Style::Float, f.bit_width()),
1120 _ => (Style::Unsupported, 0)
1123 match (in_style, out_style) {
1124 (Style::Int(in_is_signed), Style::Int(_)) => {
1125 return match in_width.cmp(&out_width) {
1126 Ordering::Greater => bcx.trunc(llargs[0], llret_ty),
1127 Ordering::Equal => llargs[0],
1128 Ordering::Less => if in_is_signed {
1129 bcx.sext(llargs[0], llret_ty)
1131 bcx.zext(llargs[0], llret_ty)
1135 (Style::Int(in_is_signed), Style::Float) => {
1136 return if in_is_signed {
1137 bcx.sitofp(llargs[0], llret_ty)
1139 bcx.uitofp(llargs[0], llret_ty)
1142 (Style::Float, Style::Int(out_is_signed)) => {
1143 return if out_is_signed {
1144 bcx.fptosi(llargs[0], llret_ty)
1146 bcx.fptoui(llargs[0], llret_ty)
1149 (Style::Float, Style::Float) => {
1150 return match in_width.cmp(&out_width) {
1151 Ordering::Greater => bcx.fptrunc(llargs[0], llret_ty),
1152 Ordering::Equal => llargs[0],
1153 Ordering::Less => bcx.fpext(llargs[0], llret_ty)
1156 _ => {/* Unsupported. Fallthrough. */}
1159 "unsupported cast from `{}` with element `{}` to `{}` with element `{}`",
1163 macro_rules! arith {
1164 ($($name: ident: $($($p: ident),* => $call: ident),*;)*) => {
1166 if name == stringify!($name) {
1170 return bcx.$call(llargs[0], llargs[1])
1176 "unsupported operation on `{}` with element `{}`",
1183 simd_add: TyUint, TyInt => add, TyFloat => fadd;
1184 simd_sub: TyUint, TyInt => sub, TyFloat => fsub;
1185 simd_mul: TyUint, TyInt => mul, TyFloat => fmul;
1186 simd_div: TyFloat => fdiv;
1187 simd_shl: TyUint, TyInt => shl;
1188 simd_shr: TyUint => lshr, TyInt => ashr;
1189 simd_and: TyUint, TyInt => and;
1190 simd_or: TyUint, TyInt => or;
1191 simd_xor: TyUint, TyInt => xor;
1193 span_bug!(span, "unknown SIMD intrinsic");
1196 // Returns the width of an int TypeVariant, and if it's signed or not
1197 // Returns None if the type is not an integer
1198 // FIXME: there’s multiple of this functions, investigate using some of the already existing
1200 fn int_type_width_signed<'tcx>(sty: &ty::TypeVariants<'tcx>, ccx: &CrateContext)
1201 -> Option<(u64, bool)> {
1202 use rustc::ty::{TyInt, TyUint};
1204 TyInt(t) => Some((match t {
1206 match &ccx.tcx().sess.target.target.target_pointer_width[..] {
1210 tws => bug!("Unsupported target word size for isize: {}", tws),
1213 ast::IntTy::I8 => 8,
1214 ast::IntTy::I16 => 16,
1215 ast::IntTy::I32 => 32,
1216 ast::IntTy::I64 => 64,
1217 ast::IntTy::I128 => 128,
1219 TyUint(t) => Some((match t {
1220 ast::UintTy::Us => {
1221 match &ccx.tcx().sess.target.target.target_pointer_width[..] {
1225 tws => bug!("Unsupported target word size for usize: {}", tws),
1228 ast::UintTy::U8 => 8,
1229 ast::UintTy::U16 => 16,
1230 ast::UintTy::U32 => 32,
1231 ast::UintTy::U64 => 64,
1232 ast::UintTy::U128 => 128,
1238 // Returns the width of a float TypeVariant
1239 // Returns None if the type is not a float
1240 fn float_type_width<'tcx>(sty: &ty::TypeVariants<'tcx>)
1242 use rustc::ty::TyFloat;
1244 TyFloat(t) => Some(match t {
1245 ast::FloatTy::F32 => 32,
1246 ast::FloatTy::F64 => 64,