1 // Copyright 2013 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(dead_code)] // FFI wrappers
14 use llvm::{AtomicRmwBinOp, AtomicOrdering, SynchronizationScope, AsmDialect};
15 use llvm::{Opcode, IntPredicate, RealPredicate, False, OperandBundleDef};
16 use llvm::{ValueRef, BasicBlockRef, BuilderRef};
20 use libc::{c_uint, c_char};
21 use rustc::ty::TyCtxt;
22 use rustc::ty::layout::{Align, Size};
23 use rustc::session::{config, Session};
26 use std::ffi::CString;
29 use std::ptr::NonNull;
32 // All Builders must have an llfn associated with them
34 pub struct Builder<'a, 'tcx: 'a> {
35 pub llbuilder: BuilderRef,
36 pub cx: &'a CodegenCx<'a, 'tcx>,
39 impl<'a, 'tcx> Drop for Builder<'a, 'tcx> {
42 llvm::LLVMDisposeBuilder(self.llbuilder);
47 // This is a really awful way to get a zero-length c-string, but better (and a
48 // lot more efficient) than doing str::as_c_str("", ...) every time.
49 fn noname() -> *const c_char {
50 static CNULL: c_char = 0;
55 pub struct MemFlags: u8 {
56 const VOLATILE = 1 << 0;
57 const NONTEMPORAL = 1 << 1;
58 const UNALIGNED = 1 << 2;
62 impl<'a, 'tcx> Builder<'a, 'tcx> {
63 pub fn new_block<'b>(cx: &'a CodegenCx<'a, 'tcx>, llfn: ValueRef, name: &'b str) -> Self {
64 let bx = Builder::with_cx(cx);
66 let name = CString::new(name).unwrap();
67 llvm::LLVMAppendBasicBlockInContext(
73 bx.position_at_end(llbb);
77 pub fn with_cx(cx: &'a CodegenCx<'a, 'tcx>) -> Self {
78 // Create a fresh builder from the crate context.
79 let llbuilder = unsafe {
80 llvm::LLVMCreateBuilderInContext(cx.llcx)
88 pub fn build_sibling_block<'b>(&self, name: &'b str) -> Builder<'a, 'tcx> {
89 Builder::new_block(self.cx, self.llfn(), name)
92 pub fn sess(&self) -> &Session {
96 pub fn tcx(&self) -> TyCtxt<'a, 'tcx, 'tcx> {
100 pub fn llfn(&self) -> ValueRef {
102 llvm::LLVMGetBasicBlockParent(self.llbb())
106 pub fn llbb(&self) -> BasicBlockRef {
108 llvm::LLVMGetInsertBlock(self.llbuilder)
112 fn count_insn(&self, category: &str) {
113 if self.cx.sess().codegen_stats() {
114 self.cx.stats.borrow_mut().n_llvm_insns += 1;
116 if self.cx.sess().count_llvm_insns() {
120 .entry(category.to_string())
125 pub fn set_value_name(&self, value: ValueRef, name: &str) {
126 let cname = CString::new(name.as_bytes()).unwrap();
128 llvm::LLVMSetValueName(value, cname.as_ptr());
132 pub fn position_before(&self, insn: ValueRef) {
134 llvm::LLVMPositionBuilderBefore(self.llbuilder, insn);
138 pub fn position_at_end(&self, llbb: BasicBlockRef) {
140 llvm::LLVMPositionBuilderAtEnd(self.llbuilder, llbb);
144 pub fn position_at_start(&self, llbb: BasicBlockRef) {
146 llvm::LLVMRustPositionBuilderAtStart(self.llbuilder, llbb);
150 pub fn ret_void(&self) {
151 self.count_insn("retvoid");
153 llvm::LLVMBuildRetVoid(self.llbuilder);
157 pub fn ret(&self, v: ValueRef) {
158 self.count_insn("ret");
160 llvm::LLVMBuildRet(self.llbuilder, v);
164 pub fn aggregate_ret(&self, ret_vals: &[ValueRef]) {
166 llvm::LLVMBuildAggregateRet(self.llbuilder,
168 ret_vals.len() as c_uint);
172 pub fn br(&self, dest: BasicBlockRef) {
173 self.count_insn("br");
175 llvm::LLVMBuildBr(self.llbuilder, dest);
179 pub fn cond_br(&self, cond: ValueRef, then_llbb: BasicBlockRef, else_llbb: BasicBlockRef) {
180 self.count_insn("condbr");
182 llvm::LLVMBuildCondBr(self.llbuilder, cond, then_llbb, else_llbb);
186 pub fn switch(&self, v: ValueRef, else_llbb: BasicBlockRef, num_cases: usize) -> ValueRef {
188 llvm::LLVMBuildSwitch(self.llbuilder, v, else_llbb, num_cases as c_uint)
192 pub fn indirect_br(&self, addr: ValueRef, num_dests: usize) {
193 self.count_insn("indirectbr");
195 llvm::LLVMBuildIndirectBr(self.llbuilder, addr, num_dests as c_uint);
203 catch: BasicBlockRef,
204 bundle: Option<&OperandBundleDef>) -> ValueRef {
205 self.count_insn("invoke");
207 debug!("Invoke {:?} with args ({})",
210 .map(|&v| format!("{:?}", Value(v)))
211 .collect::<Vec<String>>()
214 let args = self.check_call("invoke", llfn, args);
215 let bundle = bundle.as_ref().and_then(|b| NonNull::new(b.raw()));
218 llvm::LLVMRustBuildInvoke(self.llbuilder,
221 args.len() as c_uint,
229 pub fn unreachable(&self) {
230 self.count_insn("unreachable");
232 llvm::LLVMBuildUnreachable(self.llbuilder);
237 pub fn add(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
238 self.count_insn("add");
240 llvm::LLVMBuildAdd(self.llbuilder, lhs, rhs, noname())
244 pub fn nswadd(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
245 self.count_insn("nswadd");
247 llvm::LLVMBuildNSWAdd(self.llbuilder, lhs, rhs, noname())
251 pub fn nuwadd(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
252 self.count_insn("nuwadd");
254 llvm::LLVMBuildNUWAdd(self.llbuilder, lhs, rhs, noname())
258 pub fn fadd(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
259 self.count_insn("fadd");
261 llvm::LLVMBuildFAdd(self.llbuilder, lhs, rhs, noname())
265 pub fn fadd_fast(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
266 self.count_insn("fadd");
268 let instr = llvm::LLVMBuildFAdd(self.llbuilder, lhs, rhs, noname());
269 llvm::LLVMRustSetHasUnsafeAlgebra(instr);
274 pub fn sub(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
275 self.count_insn("sub");
277 llvm::LLVMBuildSub(self.llbuilder, lhs, rhs, noname())
281 pub fn nswsub(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
282 self.count_insn("nswsub");
284 llvm::LLVMBuildNSWSub(self.llbuilder, lhs, rhs, noname())
288 pub fn nuwsub(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
289 self.count_insn("nuwsub");
291 llvm::LLVMBuildNUWSub(self.llbuilder, lhs, rhs, noname())
295 pub fn fsub(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
296 self.count_insn("fsub");
298 llvm::LLVMBuildFSub(self.llbuilder, lhs, rhs, noname())
302 pub fn fsub_fast(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
303 self.count_insn("fsub");
305 let instr = llvm::LLVMBuildFSub(self.llbuilder, lhs, rhs, noname());
306 llvm::LLVMRustSetHasUnsafeAlgebra(instr);
311 pub fn mul(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
312 self.count_insn("mul");
314 llvm::LLVMBuildMul(self.llbuilder, lhs, rhs, noname())
318 pub fn nswmul(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
319 self.count_insn("nswmul");
321 llvm::LLVMBuildNSWMul(self.llbuilder, lhs, rhs, noname())
325 pub fn nuwmul(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
326 self.count_insn("nuwmul");
328 llvm::LLVMBuildNUWMul(self.llbuilder, lhs, rhs, noname())
332 pub fn fmul(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
333 self.count_insn("fmul");
335 llvm::LLVMBuildFMul(self.llbuilder, lhs, rhs, noname())
339 pub fn fmul_fast(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
340 self.count_insn("fmul");
342 let instr = llvm::LLVMBuildFMul(self.llbuilder, lhs, rhs, noname());
343 llvm::LLVMRustSetHasUnsafeAlgebra(instr);
349 pub fn udiv(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
350 self.count_insn("udiv");
352 llvm::LLVMBuildUDiv(self.llbuilder, lhs, rhs, noname())
356 pub fn exactudiv(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
357 self.count_insn("exactudiv");
359 llvm::LLVMBuildExactUDiv(self.llbuilder, lhs, rhs, noname())
363 pub fn sdiv(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
364 self.count_insn("sdiv");
366 llvm::LLVMBuildSDiv(self.llbuilder, lhs, rhs, noname())
370 pub fn exactsdiv(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
371 self.count_insn("exactsdiv");
373 llvm::LLVMBuildExactSDiv(self.llbuilder, lhs, rhs, noname())
377 pub fn fdiv(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
378 self.count_insn("fdiv");
380 llvm::LLVMBuildFDiv(self.llbuilder, lhs, rhs, noname())
384 pub fn fdiv_fast(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
385 self.count_insn("fdiv");
387 let instr = llvm::LLVMBuildFDiv(self.llbuilder, lhs, rhs, noname());
388 llvm::LLVMRustSetHasUnsafeAlgebra(instr);
393 pub fn urem(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
394 self.count_insn("urem");
396 llvm::LLVMBuildURem(self.llbuilder, lhs, rhs, noname())
400 pub fn srem(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
401 self.count_insn("srem");
403 llvm::LLVMBuildSRem(self.llbuilder, lhs, rhs, noname())
407 pub fn frem(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
408 self.count_insn("frem");
410 llvm::LLVMBuildFRem(self.llbuilder, lhs, rhs, noname())
414 pub fn frem_fast(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
415 self.count_insn("frem");
417 let instr = llvm::LLVMBuildFRem(self.llbuilder, lhs, rhs, noname());
418 llvm::LLVMRustSetHasUnsafeAlgebra(instr);
423 pub fn shl(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
424 self.count_insn("shl");
426 llvm::LLVMBuildShl(self.llbuilder, lhs, rhs, noname())
430 pub fn lshr(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
431 self.count_insn("lshr");
433 llvm::LLVMBuildLShr(self.llbuilder, lhs, rhs, noname())
437 pub fn ashr(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
438 self.count_insn("ashr");
440 llvm::LLVMBuildAShr(self.llbuilder, lhs, rhs, noname())
444 pub fn and(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
445 self.count_insn("and");
447 llvm::LLVMBuildAnd(self.llbuilder, lhs, rhs, noname())
451 pub fn or(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
452 self.count_insn("or");
454 llvm::LLVMBuildOr(self.llbuilder, lhs, rhs, noname())
458 pub fn xor(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
459 self.count_insn("xor");
461 llvm::LLVMBuildXor(self.llbuilder, lhs, rhs, noname())
465 pub fn binop(&self, op: Opcode, lhs: ValueRef, rhs: ValueRef)
467 self.count_insn("binop");
469 llvm::LLVMBuildBinOp(self.llbuilder, op, lhs, rhs, noname())
473 pub fn neg(&self, v: ValueRef) -> ValueRef {
474 self.count_insn("neg");
476 llvm::LLVMBuildNeg(self.llbuilder, v, noname())
480 pub fn nswneg(&self, v: ValueRef) -> ValueRef {
481 self.count_insn("nswneg");
483 llvm::LLVMBuildNSWNeg(self.llbuilder, v, noname())
487 pub fn nuwneg(&self, v: ValueRef) -> ValueRef {
488 self.count_insn("nuwneg");
490 llvm::LLVMBuildNUWNeg(self.llbuilder, v, noname())
493 pub fn fneg(&self, v: ValueRef) -> ValueRef {
494 self.count_insn("fneg");
496 llvm::LLVMBuildFNeg(self.llbuilder, v, noname())
500 pub fn not(&self, v: ValueRef) -> ValueRef {
501 self.count_insn("not");
503 llvm::LLVMBuildNot(self.llbuilder, v, noname())
507 pub fn alloca(&self, ty: Type, name: &str, align: Align) -> ValueRef {
508 let bx = Builder::with_cx(self.cx);
509 bx.position_at_start(unsafe {
510 llvm::LLVMGetFirstBasicBlock(self.llfn())
512 bx.dynamic_alloca(ty, name, align)
515 pub fn dynamic_alloca(&self, ty: Type, name: &str, align: Align) -> ValueRef {
516 self.count_insn("alloca");
518 let alloca = if name.is_empty() {
519 llvm::LLVMBuildAlloca(self.llbuilder, ty.to_ref(), noname())
521 let name = CString::new(name).unwrap();
522 llvm::LLVMBuildAlloca(self.llbuilder, ty.to_ref(),
525 llvm::LLVMSetAlignment(alloca, align.abi() as c_uint);
530 pub fn free(&self, ptr: ValueRef) {
531 self.count_insn("free");
533 llvm::LLVMBuildFree(self.llbuilder, ptr);
537 pub fn load(&self, ptr: ValueRef, align: Align) -> ValueRef {
538 self.count_insn("load");
540 let load = llvm::LLVMBuildLoad(self.llbuilder, ptr, noname());
541 llvm::LLVMSetAlignment(load, align.abi() as c_uint);
546 pub fn volatile_load(&self, ptr: ValueRef) -> ValueRef {
547 self.count_insn("load.volatile");
549 let insn = llvm::LLVMBuildLoad(self.llbuilder, ptr, noname());
550 llvm::LLVMSetVolatile(insn, llvm::True);
555 pub fn atomic_load(&self, ptr: ValueRef, order: AtomicOrdering, align: Align) -> ValueRef {
556 self.count_insn("load.atomic");
558 let load = llvm::LLVMRustBuildAtomicLoad(self.llbuilder, ptr, noname(), order);
559 // FIXME(eddyb) Isn't it UB to use `pref` instead of `abi` here?
560 // However, 64-bit atomic loads on `i686-apple-darwin` appear to
561 // require `___atomic_load` with ABI-alignment, so it's staying.
562 llvm::LLVMSetAlignment(load, align.pref() as c_uint);
568 pub fn range_metadata(&self, load: ValueRef, range: Range<u128>) {
570 let llty = val_ty(load);
572 C_uint_big(llty, range.start),
573 C_uint_big(llty, range.end)
576 llvm::LLVMSetMetadata(load, llvm::MD_range as c_uint,
577 llvm::LLVMMDNodeInContext(self.cx.llcx,
583 pub fn nonnull_metadata(&self, load: ValueRef) {
585 llvm::LLVMSetMetadata(load, llvm::MD_nonnull as c_uint,
586 llvm::LLVMMDNodeInContext(self.cx.llcx, ptr::null(), 0));
590 pub fn store(&self, val: ValueRef, ptr: ValueRef, align: Align) -> ValueRef {
591 self.store_with_flags(val, ptr, align, MemFlags::empty())
594 pub fn store_with_flags(
601 debug!("Store {:?} -> {:?} ({:?})", Value(val), Value(ptr), flags);
602 assert!(!self.llbuilder.is_null());
603 self.count_insn("store");
604 let ptr = self.check_store(val, ptr);
606 let store = llvm::LLVMBuildStore(self.llbuilder, val, ptr);
607 let align = if flags.contains(MemFlags::UNALIGNED) {
610 align.abi() as c_uint
612 llvm::LLVMSetAlignment(store, align);
613 if flags.contains(MemFlags::VOLATILE) {
614 llvm::LLVMSetVolatile(store, llvm::True);
616 if flags.contains(MemFlags::NONTEMPORAL) {
617 // According to LLVM [1] building a nontemporal store must
618 // *always* point to a metadata value of the integer 1.
620 // [1]: http://llvm.org/docs/LangRef.html#store-instruction
621 let one = C_i32(self.cx, 1);
622 let node = llvm::LLVMMDNodeInContext(self.cx.llcx, &one, 1);
623 llvm::LLVMSetMetadata(store, llvm::MD_nontemporal as c_uint, node);
629 pub fn atomic_store(&self, val: ValueRef, ptr: ValueRef,
630 order: AtomicOrdering, align: Align) {
631 debug!("Store {:?} -> {:?}", Value(val), Value(ptr));
632 self.count_insn("store.atomic");
633 let ptr = self.check_store(val, ptr);
635 let store = llvm::LLVMRustBuildAtomicStore(self.llbuilder, val, ptr, order);
636 // FIXME(eddyb) Isn't it UB to use `pref` instead of `abi` here?
637 // Also see `atomic_load` for more context.
638 llvm::LLVMSetAlignment(store, align.pref() as c_uint);
642 pub fn gep(&self, ptr: ValueRef, indices: &[ValueRef]) -> ValueRef {
643 self.count_insn("gep");
645 llvm::LLVMBuildGEP(self.llbuilder, ptr, indices.as_ptr(),
646 indices.len() as c_uint, noname())
650 pub fn inbounds_gep(&self, ptr: ValueRef, indices: &[ValueRef]) -> ValueRef {
651 self.count_insn("inboundsgep");
653 llvm::LLVMBuildInBoundsGEP(
654 self.llbuilder, ptr, indices.as_ptr(), indices.len() as c_uint, noname())
658 pub fn struct_gep(&self, ptr: ValueRef, idx: u64) -> ValueRef {
659 self.count_insn("structgep");
660 assert_eq!(idx as c_uint as u64, idx);
662 llvm::LLVMBuildStructGEP(self.llbuilder, ptr, idx as c_uint, noname())
666 pub fn global_string(&self, _str: *const c_char) -> ValueRef {
667 self.count_insn("globalstring");
669 llvm::LLVMBuildGlobalString(self.llbuilder, _str, noname())
673 pub fn global_string_ptr(&self, _str: *const c_char) -> ValueRef {
674 self.count_insn("globalstringptr");
676 llvm::LLVMBuildGlobalStringPtr(self.llbuilder, _str, noname())
681 pub fn trunc(&self, val: ValueRef, dest_ty: Type) -> ValueRef {
682 self.count_insn("trunc");
684 llvm::LLVMBuildTrunc(self.llbuilder, val, dest_ty.to_ref(), noname())
688 pub fn zext(&self, val: ValueRef, dest_ty: Type) -> ValueRef {
689 self.count_insn("zext");
691 llvm::LLVMBuildZExt(self.llbuilder, val, dest_ty.to_ref(), noname())
695 pub fn sext(&self, val: ValueRef, dest_ty: Type) -> ValueRef {
696 self.count_insn("sext");
698 llvm::LLVMBuildSExt(self.llbuilder, val, dest_ty.to_ref(), noname())
702 pub fn fptoui(&self, val: ValueRef, dest_ty: Type) -> ValueRef {
703 self.count_insn("fptoui");
705 llvm::LLVMBuildFPToUI(self.llbuilder, val, dest_ty.to_ref(), noname())
709 pub fn fptosi(&self, val: ValueRef, dest_ty: Type) -> ValueRef {
710 self.count_insn("fptosi");
712 llvm::LLVMBuildFPToSI(self.llbuilder, val, dest_ty.to_ref(),noname())
716 pub fn uitofp(&self, val: ValueRef, dest_ty: Type) -> ValueRef {
717 self.count_insn("uitofp");
719 llvm::LLVMBuildUIToFP(self.llbuilder, val, dest_ty.to_ref(), noname())
723 pub fn sitofp(&self, val: ValueRef, dest_ty: Type) -> ValueRef {
724 self.count_insn("sitofp");
726 llvm::LLVMBuildSIToFP(self.llbuilder, val, dest_ty.to_ref(), noname())
730 pub fn fptrunc(&self, val: ValueRef, dest_ty: Type) -> ValueRef {
731 self.count_insn("fptrunc");
733 llvm::LLVMBuildFPTrunc(self.llbuilder, val, dest_ty.to_ref(), noname())
737 pub fn fpext(&self, val: ValueRef, dest_ty: Type) -> ValueRef {
738 self.count_insn("fpext");
740 llvm::LLVMBuildFPExt(self.llbuilder, val, dest_ty.to_ref(), noname())
744 pub fn ptrtoint(&self, val: ValueRef, dest_ty: Type) -> ValueRef {
745 self.count_insn("ptrtoint");
747 llvm::LLVMBuildPtrToInt(self.llbuilder, val, dest_ty.to_ref(), noname())
751 pub fn inttoptr(&self, val: ValueRef, dest_ty: Type) -> ValueRef {
752 self.count_insn("inttoptr");
754 llvm::LLVMBuildIntToPtr(self.llbuilder, val, dest_ty.to_ref(), noname())
758 pub fn bitcast(&self, val: ValueRef, dest_ty: Type) -> ValueRef {
759 self.count_insn("bitcast");
761 llvm::LLVMBuildBitCast(self.llbuilder, val, dest_ty.to_ref(), noname())
765 pub fn zext_or_bitcast(&self, val: ValueRef, dest_ty: Type) -> ValueRef {
766 self.count_insn("zextorbitcast");
768 llvm::LLVMBuildZExtOrBitCast(self.llbuilder, val, dest_ty.to_ref(), noname())
772 pub fn sext_or_bitcast(&self, val: ValueRef, dest_ty: Type) -> ValueRef {
773 self.count_insn("sextorbitcast");
775 llvm::LLVMBuildSExtOrBitCast(self.llbuilder, val, dest_ty.to_ref(), noname())
779 pub fn trunc_or_bitcast(&self, val: ValueRef, dest_ty: Type) -> ValueRef {
780 self.count_insn("truncorbitcast");
782 llvm::LLVMBuildTruncOrBitCast(self.llbuilder, val, dest_ty.to_ref(), noname())
786 pub fn cast(&self, op: Opcode, val: ValueRef, dest_ty: Type) -> ValueRef {
787 self.count_insn("cast");
789 llvm::LLVMBuildCast(self.llbuilder, op, val, dest_ty.to_ref(), noname())
793 pub fn pointercast(&self, val: ValueRef, dest_ty: Type) -> ValueRef {
794 self.count_insn("pointercast");
796 llvm::LLVMBuildPointerCast(self.llbuilder, val, dest_ty.to_ref(), noname())
800 pub fn intcast(&self, val: ValueRef, dest_ty: Type, is_signed: bool) -> ValueRef {
801 self.count_insn("intcast");
803 llvm::LLVMRustBuildIntCast(self.llbuilder, val, dest_ty.to_ref(), is_signed)
807 pub fn fpcast(&self, val: ValueRef, dest_ty: Type) -> ValueRef {
808 self.count_insn("fpcast");
810 llvm::LLVMBuildFPCast(self.llbuilder, val, dest_ty.to_ref(), noname())
816 pub fn icmp(&self, op: IntPredicate, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
817 self.count_insn("icmp");
819 llvm::LLVMBuildICmp(self.llbuilder, op as c_uint, lhs, rhs, noname())
823 pub fn fcmp(&self, op: RealPredicate, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
824 self.count_insn("fcmp");
826 llvm::LLVMBuildFCmp(self.llbuilder, op as c_uint, lhs, rhs, noname())
830 /* Miscellaneous instructions */
831 pub fn empty_phi(&self, ty: Type) -> ValueRef {
832 self.count_insn("emptyphi");
834 llvm::LLVMBuildPhi(self.llbuilder, ty.to_ref(), noname())
838 pub fn phi(&self, ty: Type, vals: &[ValueRef], bbs: &[BasicBlockRef]) -> ValueRef {
839 assert_eq!(vals.len(), bbs.len());
840 let phi = self.empty_phi(ty);
841 self.count_insn("addincoming");
843 llvm::LLVMAddIncoming(phi, vals.as_ptr(),
845 vals.len() as c_uint);
850 pub fn add_span_comment(&self, sp: Span, text: &str) {
851 if self.cx.sess().asm_comments() {
852 let s = format!("{} ({})",
854 self.cx.sess().codemap().span_to_string(sp));
856 self.add_comment(&s);
860 pub fn add_comment(&self, text: &str) {
861 if self.cx.sess().asm_comments() {
862 let sanitized = text.replace("$", "");
863 let comment_text = format!("{} {}", "#",
864 sanitized.replace("\n", "\n\t# "));
865 self.count_insn("inlineasm");
866 let comment_text = CString::new(comment_text).unwrap();
868 llvm::LLVMConstInlineAsm(Type::func(&[], &Type::void(self.cx)).to_ref(),
869 comment_text.as_ptr(), noname(), False,
872 self.call(asm, &[], None);
876 pub fn inline_asm_call(&self, asm: *const c_char, cons: *const c_char,
877 inputs: &[ValueRef], output: Type,
878 volatile: bool, alignstack: bool,
879 dia: AsmDialect) -> ValueRef {
880 self.count_insn("inlineasm");
882 let volatile = if volatile { llvm::True }
883 else { llvm::False };
884 let alignstack = if alignstack { llvm::True }
885 else { llvm::False };
887 let argtys = inputs.iter().map(|v| {
888 debug!("Asm Input Type: {:?}", Value(*v));
890 }).collect::<Vec<_>>();
892 debug!("Asm Output Type: {:?}", output);
893 let fty = Type::func(&argtys[..], &output);
895 let v = llvm::LLVMRustInlineAsm(
896 fty.to_ref(), asm, cons, volatile, alignstack, dia);
897 self.call(v, inputs, None)
901 pub fn call(&self, llfn: ValueRef, args: &[ValueRef],
902 bundle: Option<&OperandBundleDef>) -> ValueRef {
903 self.count_insn("call");
905 debug!("Call {:?} with args ({})",
908 .map(|&v| format!("{:?}", Value(v)))
909 .collect::<Vec<String>>()
912 let args = self.check_call("call", llfn, args);
913 let bundle = bundle.as_ref().and_then(|b| NonNull::new(b.raw()));
916 llvm::LLVMRustBuildCall(self.llbuilder, llfn, args.as_ptr(),
917 args.len() as c_uint, bundle, noname())
921 pub fn minnum(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
922 self.count_insn("minnum");
924 let instr = llvm::LLVMRustBuildMinNum(self.llbuilder, lhs, rhs);
926 bug!("LLVMRustBuildMinNum is not available in LLVM version < 6.0");
931 pub fn maxnum(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
932 self.count_insn("maxnum");
934 let instr = llvm::LLVMRustBuildMaxNum(self.llbuilder, lhs, rhs);
936 bug!("LLVMRustBuildMaxNum is not available in LLVM version < 6.0");
942 pub fn select(&self, cond: ValueRef, then_val: ValueRef, else_val: ValueRef) -> ValueRef {
943 self.count_insn("select");
945 llvm::LLVMBuildSelect(self.llbuilder, cond, then_val, else_val, noname())
949 pub fn va_arg(&self, list: ValueRef, ty: Type) -> ValueRef {
950 self.count_insn("vaarg");
952 llvm::LLVMBuildVAArg(self.llbuilder, list, ty.to_ref(), noname())
956 pub fn extract_element(&self, vec: ValueRef, idx: ValueRef) -> ValueRef {
957 self.count_insn("extractelement");
959 llvm::LLVMBuildExtractElement(self.llbuilder, vec, idx, noname())
963 pub fn insert_element(&self, vec: ValueRef, elt: ValueRef, idx: ValueRef) -> ValueRef {
964 self.count_insn("insertelement");
966 llvm::LLVMBuildInsertElement(self.llbuilder, vec, elt, idx, noname())
970 pub fn shuffle_vector(&self, v1: ValueRef, v2: ValueRef, mask: ValueRef) -> ValueRef {
971 self.count_insn("shufflevector");
973 llvm::LLVMBuildShuffleVector(self.llbuilder, v1, v2, mask, noname())
977 pub fn vector_splat(&self, num_elts: usize, elt: ValueRef) -> ValueRef {
979 let elt_ty = val_ty(elt);
980 let undef = llvm::LLVMGetUndef(Type::vector(&elt_ty, num_elts as u64).to_ref());
981 let vec = self.insert_element(undef, elt, C_i32(self.cx, 0));
982 let vec_i32_ty = Type::vector(&Type::i32(self.cx), num_elts as u64);
983 self.shuffle_vector(vec, undef, C_null(vec_i32_ty))
987 pub fn vector_reduce_fadd_fast(&self, acc: ValueRef, src: ValueRef) -> ValueRef {
988 self.count_insn("vector.reduce.fadd_fast");
990 // FIXME: add a non-fast math version once
991 // https://bugs.llvm.org/show_bug.cgi?id=36732
993 let instr = llvm::LLVMRustBuildVectorReduceFAdd(self.llbuilder, acc, src);
995 bug!("LLVMRustBuildVectorReduceFAdd is not available in LLVM version < 5.0");
997 llvm::LLVMRustSetHasUnsafeAlgebra(instr);
1001 pub fn vector_reduce_fmul_fast(&self, acc: ValueRef, src: ValueRef) -> ValueRef {
1002 self.count_insn("vector.reduce.fmul_fast");
1004 // FIXME: add a non-fast math version once
1005 // https://bugs.llvm.org/show_bug.cgi?id=36732
1007 let instr = llvm::LLVMRustBuildVectorReduceFMul(self.llbuilder, acc, src);
1008 if instr.is_null() {
1009 bug!("LLVMRustBuildVectorReduceFMul is not available in LLVM version < 5.0");
1011 llvm::LLVMRustSetHasUnsafeAlgebra(instr);
1015 pub fn vector_reduce_add(&self, src: ValueRef) -> ValueRef {
1016 self.count_insn("vector.reduce.add");
1018 let instr = llvm::LLVMRustBuildVectorReduceAdd(self.llbuilder, src);
1019 if instr.is_null() {
1020 bug!("LLVMRustBuildVectorReduceAdd is not available in LLVM version < 5.0");
1025 pub fn vector_reduce_mul(&self, src: ValueRef) -> ValueRef {
1026 self.count_insn("vector.reduce.mul");
1028 let instr = llvm::LLVMRustBuildVectorReduceMul(self.llbuilder, src);
1029 if instr.is_null() {
1030 bug!("LLVMRustBuildVectorReduceMul is not available in LLVM version < 5.0");
1035 pub fn vector_reduce_and(&self, src: ValueRef) -> ValueRef {
1036 self.count_insn("vector.reduce.and");
1038 let instr = llvm::LLVMRustBuildVectorReduceAnd(self.llbuilder, src);
1039 if instr.is_null() {
1040 bug!("LLVMRustBuildVectorReduceAnd is not available in LLVM version < 5.0");
1045 pub fn vector_reduce_or(&self, src: ValueRef) -> ValueRef {
1046 self.count_insn("vector.reduce.or");
1048 let instr = llvm::LLVMRustBuildVectorReduceOr(self.llbuilder, src);
1049 if instr.is_null() {
1050 bug!("LLVMRustBuildVectorReduceOr is not available in LLVM version < 5.0");
1055 pub fn vector_reduce_xor(&self, src: ValueRef) -> ValueRef {
1056 self.count_insn("vector.reduce.xor");
1058 let instr = llvm::LLVMRustBuildVectorReduceXor(self.llbuilder, src);
1059 if instr.is_null() {
1060 bug!("LLVMRustBuildVectorReduceXor is not available in LLVM version < 5.0");
1065 pub fn vector_reduce_fmin(&self, src: ValueRef) -> ValueRef {
1066 self.count_insn("vector.reduce.fmin");
1068 let instr = llvm::LLVMRustBuildVectorReduceFMin(self.llbuilder, src, /*NoNaNs:*/ false);
1069 if instr.is_null() {
1070 bug!("LLVMRustBuildVectorReduceFMin is not available in LLVM version < 5.0");
1075 pub fn vector_reduce_fmax(&self, src: ValueRef) -> ValueRef {
1076 self.count_insn("vector.reduce.fmax");
1078 let instr = llvm::LLVMRustBuildVectorReduceFMax(self.llbuilder, src, /*NoNaNs:*/ false);
1079 if instr.is_null() {
1080 bug!("LLVMRustBuildVectorReduceFMax is not available in LLVM version < 5.0");
1085 pub fn vector_reduce_fmin_fast(&self, src: ValueRef) -> ValueRef {
1086 self.count_insn("vector.reduce.fmin_fast");
1088 let instr = llvm::LLVMRustBuildVectorReduceFMin(self.llbuilder, src, /*NoNaNs:*/ true);
1089 if instr.is_null() {
1090 bug!("LLVMRustBuildVectorReduceFMin is not available in LLVM version < 5.0");
1092 llvm::LLVMRustSetHasUnsafeAlgebra(instr);
1096 pub fn vector_reduce_fmax_fast(&self, src: ValueRef) -> ValueRef {
1097 self.count_insn("vector.reduce.fmax_fast");
1099 let instr = llvm::LLVMRustBuildVectorReduceFMax(self.llbuilder, src, /*NoNaNs:*/ true);
1100 if instr.is_null() {
1101 bug!("LLVMRustBuildVectorReduceFMax is not available in LLVM version < 5.0");
1103 llvm::LLVMRustSetHasUnsafeAlgebra(instr);
1107 pub fn vector_reduce_min(&self, src: ValueRef, is_signed: bool) -> ValueRef {
1108 self.count_insn("vector.reduce.min");
1110 let instr = llvm::LLVMRustBuildVectorReduceMin(self.llbuilder, src, is_signed);
1111 if instr.is_null() {
1112 bug!("LLVMRustBuildVectorReduceMin is not available in LLVM version < 5.0");
1117 pub fn vector_reduce_max(&self, src: ValueRef, is_signed: bool) -> ValueRef {
1118 self.count_insn("vector.reduce.max");
1120 let instr = llvm::LLVMRustBuildVectorReduceMax(self.llbuilder, src, is_signed);
1121 if instr.is_null() {
1122 bug!("LLVMRustBuildVectorReduceMax is not available in LLVM version < 5.0");
1128 pub fn extract_value(&self, agg_val: ValueRef, idx: u64) -> ValueRef {
1129 self.count_insn("extractvalue");
1130 assert_eq!(idx as c_uint as u64, idx);
1132 llvm::LLVMBuildExtractValue(self.llbuilder, agg_val, idx as c_uint, noname())
1136 pub fn insert_value(&self, agg_val: ValueRef, elt: ValueRef,
1137 idx: u64) -> ValueRef {
1138 self.count_insn("insertvalue");
1139 assert_eq!(idx as c_uint as u64, idx);
1141 llvm::LLVMBuildInsertValue(self.llbuilder, agg_val, elt, idx as c_uint,
1146 pub fn is_null(&self, val: ValueRef) -> ValueRef {
1147 self.count_insn("isnull");
1149 llvm::LLVMBuildIsNull(self.llbuilder, val, noname())
1153 pub fn is_not_null(&self, val: ValueRef) -> ValueRef {
1154 self.count_insn("isnotnull");
1156 llvm::LLVMBuildIsNotNull(self.llbuilder, val, noname())
1160 pub fn ptrdiff(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
1161 self.count_insn("ptrdiff");
1163 llvm::LLVMBuildPtrDiff(self.llbuilder, lhs, rhs, noname())
1167 pub fn landing_pad(&self, ty: Type, pers_fn: ValueRef,
1168 num_clauses: usize) -> ValueRef {
1169 self.count_insn("landingpad");
1171 llvm::LLVMBuildLandingPad(self.llbuilder, ty.to_ref(), pers_fn,
1172 num_clauses as c_uint, noname())
1176 pub fn add_clause(&self, landing_pad: ValueRef, clause: ValueRef) {
1178 llvm::LLVMAddClause(landing_pad, clause);
1182 pub fn set_cleanup(&self, landing_pad: ValueRef) {
1183 self.count_insn("setcleanup");
1185 llvm::LLVMSetCleanup(landing_pad, llvm::True);
1189 pub fn resume(&self, exn: ValueRef) -> ValueRef {
1190 self.count_insn("resume");
1192 llvm::LLVMBuildResume(self.llbuilder, exn)
1196 pub fn cleanup_pad(&self,
1197 parent: Option<ValueRef>,
1198 args: &[ValueRef]) -> ValueRef {
1199 self.count_insn("cleanuppad");
1200 let parent = parent.and_then(NonNull::new);
1201 let name = CString::new("cleanuppad").unwrap();
1203 llvm::LLVMRustBuildCleanupPad(self.llbuilder,
1205 args.len() as c_uint,
1209 assert!(!ret.is_null(), "LLVM does not have support for cleanuppad");
1213 pub fn cleanup_ret(&self, cleanup: ValueRef,
1214 unwind: Option<BasicBlockRef>) -> ValueRef {
1215 self.count_insn("cleanupret");
1216 let unwind = unwind.and_then(NonNull::new);
1218 llvm::LLVMRustBuildCleanupRet(self.llbuilder, cleanup, unwind)
1220 assert!(!ret.is_null(), "LLVM does not have support for cleanupret");
1224 pub fn catch_pad(&self,
1226 args: &[ValueRef]) -> ValueRef {
1227 self.count_insn("catchpad");
1228 let name = CString::new("catchpad").unwrap();
1230 llvm::LLVMRustBuildCatchPad(self.llbuilder, parent,
1231 args.len() as c_uint, args.as_ptr(),
1234 assert!(!ret.is_null(), "LLVM does not have support for catchpad");
1238 pub fn catch_ret(&self, pad: ValueRef, unwind: BasicBlockRef) -> ValueRef {
1239 self.count_insn("catchret");
1241 llvm::LLVMRustBuildCatchRet(self.llbuilder, pad, unwind)
1243 assert!(!ret.is_null(), "LLVM does not have support for catchret");
1247 pub fn catch_switch(&self,
1248 parent: Option<ValueRef>,
1249 unwind: Option<BasicBlockRef>,
1250 num_handlers: usize) -> ValueRef {
1251 self.count_insn("catchswitch");
1252 let parent = parent.and_then(NonNull::new);
1253 let unwind = unwind.and_then(NonNull::new);
1254 let name = CString::new("catchswitch").unwrap();
1256 llvm::LLVMRustBuildCatchSwitch(self.llbuilder, parent, unwind,
1257 num_handlers as c_uint,
1260 assert!(!ret.is_null(), "LLVM does not have support for catchswitch");
1264 pub fn add_handler(&self, catch_switch: ValueRef, handler: BasicBlockRef) {
1266 llvm::LLVMRustAddHandler(catch_switch, handler);
1270 pub fn set_personality_fn(&self, personality: ValueRef) {
1272 llvm::LLVMSetPersonalityFn(self.llfn(), personality);
1276 // Atomic Operations
1277 pub fn atomic_cmpxchg(&self, dst: ValueRef,
1278 cmp: ValueRef, src: ValueRef,
1279 order: AtomicOrdering,
1280 failure_order: AtomicOrdering,
1281 weak: llvm::Bool) -> ValueRef {
1283 llvm::LLVMRustBuildAtomicCmpXchg(self.llbuilder, dst, cmp, src,
1284 order, failure_order, weak)
1287 pub fn atomic_rmw(&self, op: AtomicRmwBinOp,
1288 dst: ValueRef, src: ValueRef,
1289 order: AtomicOrdering) -> ValueRef {
1291 llvm::LLVMBuildAtomicRMW(self.llbuilder, op, dst, src, order, False)
1295 pub fn atomic_fence(&self, order: AtomicOrdering, scope: SynchronizationScope) {
1297 llvm::LLVMRustBuildAtomicFence(self.llbuilder, order, scope);
1301 pub fn add_case(&self, s: ValueRef, on_val: ValueRef, dest: BasicBlockRef) {
1303 llvm::LLVMAddCase(s, on_val, dest)
1307 pub fn add_incoming_to_phi(&self, phi: ValueRef, val: ValueRef, bb: BasicBlockRef) {
1308 self.count_insn("addincoming");
1310 llvm::LLVMAddIncoming(phi, &val, &bb, 1 as c_uint);
1314 pub fn set_invariant_load(&self, load: ValueRef) {
1316 llvm::LLVMSetMetadata(load, llvm::MD_invariant_load as c_uint,
1317 llvm::LLVMMDNodeInContext(self.cx.llcx, ptr::null(), 0));
1321 /// Returns the ptr value that should be used for storing `val`.
1322 fn check_store<'b>(&self,
1324 ptr: ValueRef) -> ValueRef {
1325 let dest_ptr_ty = val_ty(ptr);
1326 let stored_ty = val_ty(val);
1327 let stored_ptr_ty = stored_ty.ptr_to();
1329 assert_eq!(dest_ptr_ty.kind(), llvm::TypeKind::Pointer);
1331 if dest_ptr_ty == stored_ptr_ty {
1334 debug!("Type mismatch in store. \
1335 Expected {:?}, got {:?}; inserting bitcast",
1336 dest_ptr_ty, stored_ptr_ty);
1337 self.bitcast(ptr, stored_ptr_ty)
1341 /// Returns the args that should be used for a call to `llfn`.
1342 fn check_call<'b>(&self,
1345 args: &'b [ValueRef]) -> Cow<'b, [ValueRef]> {
1346 let mut fn_ty = val_ty(llfn);
1347 // Strip off pointers
1348 while fn_ty.kind() == llvm::TypeKind::Pointer {
1349 fn_ty = fn_ty.element_type();
1352 assert!(fn_ty.kind() == llvm::TypeKind::Function,
1353 "builder::{} not passed a function, but {:?}", typ, fn_ty);
1355 let param_tys = fn_ty.func_params();
1357 let all_args_match = param_tys.iter()
1358 .zip(args.iter().map(|&v| val_ty(v)))
1359 .all(|(expected_ty, actual_ty)| *expected_ty == actual_ty);
1362 return Cow::Borrowed(args);
1365 let casted_args: Vec<_> = param_tys.into_iter()
1368 .map(|(i, (expected_ty, &actual_val))| {
1369 let actual_ty = val_ty(actual_val);
1370 if expected_ty != actual_ty {
1371 debug!("Type mismatch in function call of {:?}. \
1372 Expected {:?} for param {}, got {:?}; injecting bitcast",
1374 expected_ty, i, actual_ty);
1375 self.bitcast(actual_val, expected_ty)
1382 return Cow::Owned(casted_args);
1385 pub fn lifetime_start(&self, ptr: ValueRef, size: Size) {
1386 self.call_lifetime_intrinsic("llvm.lifetime.start", ptr, size);
1389 pub fn lifetime_end(&self, ptr: ValueRef, size: Size) {
1390 self.call_lifetime_intrinsic("llvm.lifetime.end", ptr, size);
1393 /// If LLVM lifetime intrinsic support is enabled (i.e. optimizations
1394 /// on), and `ptr` is nonzero-sized, then extracts the size of `ptr`
1395 /// and the intrinsic for `lt` and passes them to `emit`, which is in
1396 /// charge of generating code to call the passed intrinsic on whatever
1397 /// block of generated code is targeted for the intrinsic.
1399 /// If LLVM lifetime intrinsic support is disabled (i.e. optimizations
1400 /// off) or `ptr` is zero-sized, then no-op (does not call `emit`).
1401 fn call_lifetime_intrinsic(&self, intrinsic: &str, ptr: ValueRef, size: Size) {
1402 if self.cx.sess().opts.optimize == config::OptLevel::No {
1406 let size = size.bytes();
1411 let lifetime_intrinsic = self.cx.get_intrinsic(intrinsic);
1413 let ptr = self.pointercast(ptr, Type::i8p(self.cx));
1414 self.call(lifetime_intrinsic, &[C_u64(self.cx, size), ptr], None);