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
13 use llvm::{AtomicRmwBinOp, AtomicOrdering, SynchronizationScope, AsmDialect};
14 use llvm::{Opcode, IntPredicate, RealPredicate, False, OperandBundleDef};
15 use llvm::{self, BasicBlock};
19 use libc::{c_uint, c_char};
20 use rustc::ty::TyCtxt;
21 use rustc::ty::layout::{Align, Size};
22 use rustc::session::{config, Session};
25 use std::ffi::CString;
28 use std::ptr::NonNull;
31 // All Builders must have an llfn associated with them
33 pub struct Builder<'a, 'll: 'a, 'tcx: 'll> {
34 pub llbuilder: &'ll llvm::Builder,
35 pub cx: &'a CodegenCx<'ll, 'tcx>,
38 impl Drop for Builder<'a, 'll, 'tcx> {
41 llvm::LLVMDisposeBuilder(self.llbuilder);
46 // This is a really awful way to get a zero-length c-string, but better (and a
47 // lot more efficient) than doing str::as_c_str("", ...) every time.
48 fn noname() -> *const c_char {
49 static CNULL: c_char = 0;
54 pub struct MemFlags: u8 {
55 const VOLATILE = 1 << 0;
56 const NONTEMPORAL = 1 << 1;
57 const UNALIGNED = 1 << 2;
61 impl Builder<'a, 'll, 'tcx> {
62 pub fn new_block<'b>(cx: &'a CodegenCx<'ll, 'tcx>, llfn: &'ll Value, name: &'b str) -> Self {
63 let bx = Builder::with_cx(cx);
65 let name = CString::new(name).unwrap();
66 llvm::LLVMAppendBasicBlockInContext(
72 bx.position_at_end(llbb);
76 pub fn with_cx(cx: &'a CodegenCx<'ll, 'tcx>) -> Self {
77 // Create a fresh builder from the crate context.
78 let llbuilder = unsafe {
79 llvm::LLVMCreateBuilderInContext(cx.llcx)
87 pub fn build_sibling_block<'b>(&self, name: &'b str) -> Builder<'a, 'll, 'tcx> {
88 Builder::new_block(self.cx, self.llfn(), name)
91 pub fn sess(&self) -> &Session {
95 pub fn tcx(&self) -> TyCtxt<'a, 'tcx, 'tcx> {
99 pub fn llfn(&self) -> &'ll Value {
101 llvm::LLVMGetBasicBlockParent(self.llbb())
105 pub fn llbb(&self) -> &'ll BasicBlock {
107 llvm::LLVMGetInsertBlock(self.llbuilder)
111 fn count_insn(&self, category: &str) {
112 if self.cx.sess().codegen_stats() {
113 self.cx.stats.borrow_mut().n_llvm_insns += 1;
115 if self.cx.sess().count_llvm_insns() {
119 .entry(category.to_string())
124 pub fn set_value_name(&self, value: &'ll Value, name: &str) {
125 let cname = CString::new(name.as_bytes()).unwrap();
127 llvm::LLVMSetValueName(value, cname.as_ptr());
131 pub fn position_before(&self, insn: &'ll Value) {
133 llvm::LLVMPositionBuilderBefore(self.llbuilder, insn);
137 pub fn position_at_end(&self, llbb: &'ll BasicBlock) {
139 llvm::LLVMPositionBuilderAtEnd(self.llbuilder, llbb);
143 pub fn position_at_start(&self, llbb: &'ll BasicBlock) {
145 llvm::LLVMRustPositionBuilderAtStart(self.llbuilder, llbb);
149 pub fn ret_void(&self) {
150 self.count_insn("retvoid");
152 llvm::LLVMBuildRetVoid(self.llbuilder);
156 pub fn ret(&self, v: &'ll Value) {
157 self.count_insn("ret");
159 llvm::LLVMBuildRet(self.llbuilder, v);
163 pub fn aggregate_ret(&self, ret_vals: &[&'ll Value]) {
165 llvm::LLVMBuildAggregateRet(self.llbuilder,
167 ret_vals.len() as c_uint);
171 pub fn br(&self, dest: &'ll BasicBlock) {
172 self.count_insn("br");
174 llvm::LLVMBuildBr(self.llbuilder, dest);
178 pub fn cond_br(&self, cond: &'ll Value, then_llbb: &'ll BasicBlock, else_llbb: &'ll BasicBlock) {
179 self.count_insn("condbr");
181 llvm::LLVMBuildCondBr(self.llbuilder, cond, then_llbb, else_llbb);
185 pub fn switch(&self, v: &'ll Value, else_llbb: &'ll BasicBlock, num_cases: usize) -> &'ll Value {
187 llvm::LLVMBuildSwitch(self.llbuilder, v, else_llbb, num_cases as c_uint)
191 pub fn indirect_br(&self, addr: &'ll Value, num_dests: usize) {
192 self.count_insn("indirectbr");
194 llvm::LLVMBuildIndirectBr(self.llbuilder, addr, num_dests as c_uint);
201 then: &'ll BasicBlock,
202 catch: &'ll BasicBlock,
203 bundle: Option<&OperandBundleDef>) -> &'ll Value {
204 self.count_insn("invoke");
206 debug!("Invoke {:?} with args ({:?})",
210 let args = self.check_call("invoke", llfn, args);
211 let bundle = bundle.as_ref().and_then(|b| NonNull::new(b.raw()));
214 llvm::LLVMRustBuildInvoke(self.llbuilder,
217 args.len() as c_uint,
225 pub fn unreachable(&self) {
226 self.count_insn("unreachable");
228 llvm::LLVMBuildUnreachable(self.llbuilder);
233 pub fn add(&self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
234 self.count_insn("add");
236 llvm::LLVMBuildAdd(self.llbuilder, lhs, rhs, noname())
240 pub fn nswadd(&self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
241 self.count_insn("nswadd");
243 llvm::LLVMBuildNSWAdd(self.llbuilder, lhs, rhs, noname())
247 pub fn nuwadd(&self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
248 self.count_insn("nuwadd");
250 llvm::LLVMBuildNUWAdd(self.llbuilder, lhs, rhs, noname())
254 pub fn fadd(&self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
255 self.count_insn("fadd");
257 llvm::LLVMBuildFAdd(self.llbuilder, lhs, rhs, noname())
261 pub fn fadd_fast(&self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
262 self.count_insn("fadd");
264 let instr = llvm::LLVMBuildFAdd(self.llbuilder, lhs, rhs, noname());
265 llvm::LLVMRustSetHasUnsafeAlgebra(instr);
270 pub fn sub(&self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
271 self.count_insn("sub");
273 llvm::LLVMBuildSub(self.llbuilder, lhs, rhs, noname())
277 pub fn nswsub(&self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
278 self.count_insn("nswsub");
280 llvm::LLVMBuildNSWSub(self.llbuilder, lhs, rhs, noname())
284 pub fn nuwsub(&self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
285 self.count_insn("nuwsub");
287 llvm::LLVMBuildNUWSub(self.llbuilder, lhs, rhs, noname())
291 pub fn fsub(&self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
292 self.count_insn("fsub");
294 llvm::LLVMBuildFSub(self.llbuilder, lhs, rhs, noname())
298 pub fn fsub_fast(&self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
299 self.count_insn("fsub");
301 let instr = llvm::LLVMBuildFSub(self.llbuilder, lhs, rhs, noname());
302 llvm::LLVMRustSetHasUnsafeAlgebra(instr);
307 pub fn mul(&self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
308 self.count_insn("mul");
310 llvm::LLVMBuildMul(self.llbuilder, lhs, rhs, noname())
314 pub fn nswmul(&self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
315 self.count_insn("nswmul");
317 llvm::LLVMBuildNSWMul(self.llbuilder, lhs, rhs, noname())
321 pub fn nuwmul(&self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
322 self.count_insn("nuwmul");
324 llvm::LLVMBuildNUWMul(self.llbuilder, lhs, rhs, noname())
328 pub fn fmul(&self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
329 self.count_insn("fmul");
331 llvm::LLVMBuildFMul(self.llbuilder, lhs, rhs, noname())
335 pub fn fmul_fast(&self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
336 self.count_insn("fmul");
338 let instr = llvm::LLVMBuildFMul(self.llbuilder, lhs, rhs, noname());
339 llvm::LLVMRustSetHasUnsafeAlgebra(instr);
345 pub fn udiv(&self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
346 self.count_insn("udiv");
348 llvm::LLVMBuildUDiv(self.llbuilder, lhs, rhs, noname())
352 pub fn exactudiv(&self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
353 self.count_insn("exactudiv");
355 llvm::LLVMBuildExactUDiv(self.llbuilder, lhs, rhs, noname())
359 pub fn sdiv(&self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
360 self.count_insn("sdiv");
362 llvm::LLVMBuildSDiv(self.llbuilder, lhs, rhs, noname())
366 pub fn exactsdiv(&self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
367 self.count_insn("exactsdiv");
369 llvm::LLVMBuildExactSDiv(self.llbuilder, lhs, rhs, noname())
373 pub fn fdiv(&self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
374 self.count_insn("fdiv");
376 llvm::LLVMBuildFDiv(self.llbuilder, lhs, rhs, noname())
380 pub fn fdiv_fast(&self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
381 self.count_insn("fdiv");
383 let instr = llvm::LLVMBuildFDiv(self.llbuilder, lhs, rhs, noname());
384 llvm::LLVMRustSetHasUnsafeAlgebra(instr);
389 pub fn urem(&self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
390 self.count_insn("urem");
392 llvm::LLVMBuildURem(self.llbuilder, lhs, rhs, noname())
396 pub fn srem(&self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
397 self.count_insn("srem");
399 llvm::LLVMBuildSRem(self.llbuilder, lhs, rhs, noname())
403 pub fn frem(&self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
404 self.count_insn("frem");
406 llvm::LLVMBuildFRem(self.llbuilder, lhs, rhs, noname())
410 pub fn frem_fast(&self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
411 self.count_insn("frem");
413 let instr = llvm::LLVMBuildFRem(self.llbuilder, lhs, rhs, noname());
414 llvm::LLVMRustSetHasUnsafeAlgebra(instr);
419 pub fn shl(&self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
420 self.count_insn("shl");
422 llvm::LLVMBuildShl(self.llbuilder, lhs, rhs, noname())
426 pub fn lshr(&self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
427 self.count_insn("lshr");
429 llvm::LLVMBuildLShr(self.llbuilder, lhs, rhs, noname())
433 pub fn ashr(&self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
434 self.count_insn("ashr");
436 llvm::LLVMBuildAShr(self.llbuilder, lhs, rhs, noname())
440 pub fn and(&self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
441 self.count_insn("and");
443 llvm::LLVMBuildAnd(self.llbuilder, lhs, rhs, noname())
447 pub fn or(&self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
448 self.count_insn("or");
450 llvm::LLVMBuildOr(self.llbuilder, lhs, rhs, noname())
454 pub fn xor(&self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
455 self.count_insn("xor");
457 llvm::LLVMBuildXor(self.llbuilder, lhs, rhs, noname())
461 pub fn binop(&self, op: Opcode, lhs: &'ll Value, rhs: &'ll Value)
463 self.count_insn("binop");
465 llvm::LLVMBuildBinOp(self.llbuilder, op, lhs, rhs, noname())
469 pub fn neg(&self, v: &'ll Value) -> &'ll Value {
470 self.count_insn("neg");
472 llvm::LLVMBuildNeg(self.llbuilder, v, noname())
476 pub fn nswneg(&self, v: &'ll Value) -> &'ll Value {
477 self.count_insn("nswneg");
479 llvm::LLVMBuildNSWNeg(self.llbuilder, v, noname())
483 pub fn nuwneg(&self, v: &'ll Value) -> &'ll Value {
484 self.count_insn("nuwneg");
486 llvm::LLVMBuildNUWNeg(self.llbuilder, v, noname())
489 pub fn fneg(&self, v: &'ll Value) -> &'ll Value {
490 self.count_insn("fneg");
492 llvm::LLVMBuildFNeg(self.llbuilder, v, noname())
496 pub fn not(&self, v: &'ll Value) -> &'ll Value {
497 self.count_insn("not");
499 llvm::LLVMBuildNot(self.llbuilder, v, noname())
503 pub fn alloca(&self, ty: &'ll Type, name: &str, align: Align) -> &'ll Value {
504 let bx = Builder::with_cx(self.cx);
505 bx.position_at_start(unsafe {
506 llvm::LLVMGetFirstBasicBlock(self.llfn())
508 bx.dynamic_alloca(ty, name, align)
511 pub fn dynamic_alloca(&self, ty: &'ll Type, name: &str, align: Align) -> &'ll Value {
512 self.count_insn("alloca");
514 let alloca = if name.is_empty() {
515 llvm::LLVMBuildAlloca(self.llbuilder, ty, noname())
517 let name = CString::new(name).unwrap();
518 llvm::LLVMBuildAlloca(self.llbuilder, ty,
521 llvm::LLVMSetAlignment(alloca, align.abi() as c_uint);
526 pub fn free(&self, ptr: &'ll Value) {
527 self.count_insn("free");
529 llvm::LLVMBuildFree(self.llbuilder, ptr);
533 pub fn load(&self, ptr: &'ll Value, align: Align) -> &'ll Value {
534 self.count_insn("load");
536 let load = llvm::LLVMBuildLoad(self.llbuilder, ptr, noname());
537 llvm::LLVMSetAlignment(load, align.abi() as c_uint);
542 pub fn volatile_load(&self, ptr: &'ll Value) -> &'ll Value {
543 self.count_insn("load.volatile");
545 let insn = llvm::LLVMBuildLoad(self.llbuilder, ptr, noname());
546 llvm::LLVMSetVolatile(insn, llvm::True);
551 pub fn atomic_load(&self, ptr: &'ll Value, order: AtomicOrdering, align: Align) -> &'ll Value {
552 self.count_insn("load.atomic");
554 let load = llvm::LLVMRustBuildAtomicLoad(self.llbuilder, ptr, noname(), order);
555 // FIXME(eddyb) Isn't it UB to use `pref` instead of `abi` here?
556 // However, 64-bit atomic loads on `i686-apple-darwin` appear to
557 // require `___atomic_load` with ABI-alignment, so it's staying.
558 llvm::LLVMSetAlignment(load, align.pref() as c_uint);
564 pub fn range_metadata(&self, load: &'ll Value, range: Range<u128>) {
566 let llty = val_ty(load);
568 C_uint_big(llty, range.start),
569 C_uint_big(llty, range.end)
572 llvm::LLVMSetMetadata(load, llvm::MD_range as c_uint,
573 llvm::LLVMMDNodeInContext(self.cx.llcx,
579 pub fn nonnull_metadata(&self, load: &'ll Value) {
581 llvm::LLVMSetMetadata(load, llvm::MD_nonnull as c_uint,
582 llvm::LLVMMDNodeInContext(self.cx.llcx, ptr::null(), 0));
586 pub fn store(&self, val: &'ll Value, ptr: &'ll Value, align: Align) -> &'ll Value {
587 self.store_with_flags(val, ptr, align, MemFlags::empty())
590 pub fn store_with_flags(
597 debug!("Store {:?} -> {:?} ({:?})", val, ptr, flags);
598 self.count_insn("store");
599 let ptr = self.check_store(val, ptr);
601 let store = llvm::LLVMBuildStore(self.llbuilder, val, ptr);
602 let align = if flags.contains(MemFlags::UNALIGNED) {
605 align.abi() as c_uint
607 llvm::LLVMSetAlignment(store, align);
608 if flags.contains(MemFlags::VOLATILE) {
609 llvm::LLVMSetVolatile(store, llvm::True);
611 if flags.contains(MemFlags::NONTEMPORAL) {
612 // According to LLVM [1] building a nontemporal store must
613 // *always* point to a metadata value of the integer 1.
615 // [1]: http://llvm.org/docs/LangRef.html#store-instruction
616 let one = C_i32(self.cx, 1);
617 let node = llvm::LLVMMDNodeInContext(self.cx.llcx, &one, 1);
618 llvm::LLVMSetMetadata(store, llvm::MD_nontemporal as c_uint, node);
624 pub fn atomic_store(&self, val: &'ll Value, ptr: &'ll Value,
625 order: AtomicOrdering, align: Align) {
626 debug!("Store {:?} -> {:?}", val, ptr);
627 self.count_insn("store.atomic");
628 let ptr = self.check_store(val, ptr);
630 let store = llvm::LLVMRustBuildAtomicStore(self.llbuilder, val, ptr, order);
631 // FIXME(eddyb) Isn't it UB to use `pref` instead of `abi` here?
632 // Also see `atomic_load` for more context.
633 llvm::LLVMSetAlignment(store, align.pref() as c_uint);
637 pub fn gep(&self, ptr: &'ll Value, indices: &[&'ll Value]) -> &'ll Value {
638 self.count_insn("gep");
640 llvm::LLVMBuildGEP(self.llbuilder, ptr, indices.as_ptr(),
641 indices.len() as c_uint, noname())
645 pub fn inbounds_gep(&self, ptr: &'ll Value, indices: &[&'ll Value]) -> &'ll Value {
646 self.count_insn("inboundsgep");
648 llvm::LLVMBuildInBoundsGEP(
649 self.llbuilder, ptr, indices.as_ptr(), indices.len() as c_uint, noname())
653 pub fn struct_gep(&self, ptr: &'ll Value, idx: u64) -> &'ll Value {
654 self.count_insn("structgep");
655 assert_eq!(idx as c_uint as u64, idx);
657 llvm::LLVMBuildStructGEP(self.llbuilder, ptr, idx as c_uint, noname())
661 pub fn global_string(&self, _str: *const c_char) -> &'ll Value {
662 self.count_insn("globalstring");
664 llvm::LLVMBuildGlobalString(self.llbuilder, _str, noname())
668 pub fn global_string_ptr(&self, _str: *const c_char) -> &'ll Value {
669 self.count_insn("globalstringptr");
671 llvm::LLVMBuildGlobalStringPtr(self.llbuilder, _str, noname())
676 pub fn trunc(&self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
677 self.count_insn("trunc");
679 llvm::LLVMBuildTrunc(self.llbuilder, val, dest_ty, noname())
683 pub fn zext(&self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
684 self.count_insn("zext");
686 llvm::LLVMBuildZExt(self.llbuilder, val, dest_ty, noname())
690 pub fn sext(&self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
691 self.count_insn("sext");
693 llvm::LLVMBuildSExt(self.llbuilder, val, dest_ty, noname())
697 pub fn fptoui(&self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
698 self.count_insn("fptoui");
700 llvm::LLVMBuildFPToUI(self.llbuilder, val, dest_ty, noname())
704 pub fn fptosi(&self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
705 self.count_insn("fptosi");
707 llvm::LLVMBuildFPToSI(self.llbuilder, val, dest_ty,noname())
711 pub fn uitofp(&self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
712 self.count_insn("uitofp");
714 llvm::LLVMBuildUIToFP(self.llbuilder, val, dest_ty, noname())
718 pub fn sitofp(&self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
719 self.count_insn("sitofp");
721 llvm::LLVMBuildSIToFP(self.llbuilder, val, dest_ty, noname())
725 pub fn fptrunc(&self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
726 self.count_insn("fptrunc");
728 llvm::LLVMBuildFPTrunc(self.llbuilder, val, dest_ty, noname())
732 pub fn fpext(&self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
733 self.count_insn("fpext");
735 llvm::LLVMBuildFPExt(self.llbuilder, val, dest_ty, noname())
739 pub fn ptrtoint(&self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
740 self.count_insn("ptrtoint");
742 llvm::LLVMBuildPtrToInt(self.llbuilder, val, dest_ty, noname())
746 pub fn inttoptr(&self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
747 self.count_insn("inttoptr");
749 llvm::LLVMBuildIntToPtr(self.llbuilder, val, dest_ty, noname())
753 pub fn bitcast(&self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
754 self.count_insn("bitcast");
756 llvm::LLVMBuildBitCast(self.llbuilder, val, dest_ty, noname())
760 pub fn zext_or_bitcast(&self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
761 self.count_insn("zextorbitcast");
763 llvm::LLVMBuildZExtOrBitCast(self.llbuilder, val, dest_ty, noname())
767 pub fn sext_or_bitcast(&self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
768 self.count_insn("sextorbitcast");
770 llvm::LLVMBuildSExtOrBitCast(self.llbuilder, val, dest_ty, noname())
774 pub fn trunc_or_bitcast(&self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
775 self.count_insn("truncorbitcast");
777 llvm::LLVMBuildTruncOrBitCast(self.llbuilder, val, dest_ty, noname())
781 pub fn cast(&self, op: Opcode, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
782 self.count_insn("cast");
784 llvm::LLVMBuildCast(self.llbuilder, op, val, dest_ty, noname())
788 pub fn pointercast(&self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
789 self.count_insn("pointercast");
791 llvm::LLVMBuildPointerCast(self.llbuilder, val, dest_ty, noname())
795 pub fn intcast(&self, val: &'ll Value, dest_ty: &'ll Type, is_signed: bool) -> &'ll Value {
796 self.count_insn("intcast");
798 llvm::LLVMRustBuildIntCast(self.llbuilder, val, dest_ty, is_signed)
802 pub fn fpcast(&self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
803 self.count_insn("fpcast");
805 llvm::LLVMBuildFPCast(self.llbuilder, val, dest_ty, noname())
811 pub fn icmp(&self, op: IntPredicate, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
812 self.count_insn("icmp");
814 llvm::LLVMBuildICmp(self.llbuilder, op as c_uint, lhs, rhs, noname())
818 pub fn fcmp(&self, op: RealPredicate, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
819 self.count_insn("fcmp");
821 llvm::LLVMBuildFCmp(self.llbuilder, op as c_uint, lhs, rhs, noname())
825 /* Miscellaneous instructions */
826 pub fn empty_phi(&self, ty: &'ll Type) -> &'ll Value {
827 self.count_insn("emptyphi");
829 llvm::LLVMBuildPhi(self.llbuilder, ty, noname())
833 pub fn phi(&self, ty: &'ll Type, vals: &[&'ll Value], bbs: &[&'ll BasicBlock]) -> &'ll Value {
834 assert_eq!(vals.len(), bbs.len());
835 let phi = self.empty_phi(ty);
836 self.count_insn("addincoming");
838 llvm::LLVMAddIncoming(phi, vals.as_ptr(),
840 vals.len() as c_uint);
845 pub fn add_span_comment(&self, sp: Span, text: &str) {
846 if self.cx.sess().asm_comments() {
847 let s = format!("{} ({})",
849 self.cx.sess().codemap().span_to_string(sp));
851 self.add_comment(&s);
855 pub fn add_comment(&self, text: &str) {
856 if self.cx.sess().asm_comments() {
857 let sanitized = text.replace("$", "");
858 let comment_text = format!("{} {}", "#",
859 sanitized.replace("\n", "\n\t# "));
860 self.count_insn("inlineasm");
861 let comment_text = CString::new(comment_text).unwrap();
863 llvm::LLVMConstInlineAsm(Type::func(&[], Type::void(self.cx)),
864 comment_text.as_ptr(), noname(), False,
867 self.call(asm, &[], None);
871 pub fn inline_asm_call(&self, asm: *const c_char, cons: *const c_char,
872 inputs: &[&'ll Value], output: &'ll Type,
873 volatile: bool, alignstack: bool,
874 dia: AsmDialect) -> &'ll Value {
875 self.count_insn("inlineasm");
877 let volatile = if volatile { llvm::True }
878 else { llvm::False };
879 let alignstack = if alignstack { llvm::True }
880 else { llvm::False };
882 let argtys = inputs.iter().map(|v| {
883 debug!("Asm Input Type: {:?}", *v);
885 }).collect::<Vec<_>>();
887 debug!("Asm Output Type: {:?}", output);
888 let fty = Type::func(&argtys[..], output);
890 let v = llvm::LLVMRustInlineAsm(
891 fty, asm, cons, volatile, alignstack, dia);
892 self.call(v, inputs, None)
896 pub fn call(&self, llfn: &'ll Value, args: &[&'ll Value],
897 bundle: Option<&OperandBundleDef>) -> &'ll Value {
898 self.count_insn("call");
900 debug!("Call {:?} with args ({:?})",
904 let args = self.check_call("call", llfn, args);
905 let bundle = bundle.as_ref().and_then(|b| NonNull::new(b.raw()));
908 llvm::LLVMRustBuildCall(self.llbuilder, llfn, args.as_ptr(),
909 args.len() as c_uint, bundle, noname())
913 pub fn minnum(&self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
914 self.count_insn("minnum");
916 let instr = llvm::LLVMRustBuildMinNum(self.llbuilder, lhs, rhs);
917 instr.expect("LLVMRustBuildMinNum is not available in LLVM version < 6.0")
920 pub fn maxnum(&self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
921 self.count_insn("maxnum");
923 let instr = llvm::LLVMRustBuildMaxNum(self.llbuilder, lhs, rhs);
924 instr.expect("LLVMRustBuildMaxNum is not available in LLVM version < 6.0")
929 &self, cond: &'ll Value,
930 then_val: &'ll Value,
931 else_val: &'ll Value,
933 self.count_insn("select");
935 llvm::LLVMBuildSelect(self.llbuilder, cond, then_val, else_val, noname())
939 pub fn va_arg(&self, list: &'ll Value, ty: &'ll Type) -> &'ll Value {
940 self.count_insn("vaarg");
942 llvm::LLVMBuildVAArg(self.llbuilder, list, ty, noname())
946 pub fn extract_element(&self, vec: &'ll Value, idx: &'ll Value) -> &'ll Value {
947 self.count_insn("extractelement");
949 llvm::LLVMBuildExtractElement(self.llbuilder, vec, idx, noname())
953 pub fn insert_element(
954 &self, vec: &'ll Value,
958 self.count_insn("insertelement");
960 llvm::LLVMBuildInsertElement(self.llbuilder, vec, elt, idx, noname())
964 pub fn shuffle_vector(&self, v1: &'ll Value, v2: &'ll Value, mask: &'ll Value) -> &'ll Value {
965 self.count_insn("shufflevector");
967 llvm::LLVMBuildShuffleVector(self.llbuilder, v1, v2, mask, noname())
971 pub fn vector_splat(&self, num_elts: usize, elt: &'ll Value) -> &'ll Value {
973 let elt_ty = val_ty(elt);
974 let undef = llvm::LLVMGetUndef(Type::vector(elt_ty, num_elts as u64));
975 let vec = self.insert_element(undef, elt, C_i32(self.cx, 0));
976 let vec_i32_ty = Type::vector(Type::i32(self.cx), num_elts as u64);
977 self.shuffle_vector(vec, undef, C_null(vec_i32_ty))
981 pub fn vector_reduce_fadd_fast(&self, acc: &'ll Value, src: &'ll Value) -> &'ll Value {
982 self.count_insn("vector.reduce.fadd_fast");
984 // FIXME: add a non-fast math version once
985 // https://bugs.llvm.org/show_bug.cgi?id=36732
987 let instr = llvm::LLVMRustBuildVectorReduceFAdd(self.llbuilder, acc, src);
988 let instr = instr.expect("LLVMRustBuildVectorReduceFAdd is not available in LLVM version < 5.0");
989 llvm::LLVMRustSetHasUnsafeAlgebra(instr);
993 pub fn vector_reduce_fmul_fast(&self, acc: &'ll Value, src: &'ll Value) -> &'ll Value {
994 self.count_insn("vector.reduce.fmul_fast");
996 // FIXME: add a non-fast math version once
997 // https://bugs.llvm.org/show_bug.cgi?id=36732
999 let instr = llvm::LLVMRustBuildVectorReduceFMul(self.llbuilder, acc, src);
1000 let instr = instr.expect("LLVMRustBuildVectorReduceFMul is not available in LLVM version < 5.0");
1001 llvm::LLVMRustSetHasUnsafeAlgebra(instr);
1005 pub fn vector_reduce_add(&self, src: &'ll Value) -> &'ll Value {
1006 self.count_insn("vector.reduce.add");
1008 let instr = llvm::LLVMRustBuildVectorReduceAdd(self.llbuilder, src);
1009 instr.expect("LLVMRustBuildVectorReduceAdd is not available in LLVM version < 5.0")
1012 pub fn vector_reduce_mul(&self, src: &'ll Value) -> &'ll Value {
1013 self.count_insn("vector.reduce.mul");
1015 let instr = llvm::LLVMRustBuildVectorReduceMul(self.llbuilder, src);
1016 instr.expect("LLVMRustBuildVectorReduceMul is not available in LLVM version < 5.0")
1019 pub fn vector_reduce_and(&self, src: &'ll Value) -> &'ll Value {
1020 self.count_insn("vector.reduce.and");
1022 let instr = llvm::LLVMRustBuildVectorReduceAnd(self.llbuilder, src);
1023 instr.expect("LLVMRustBuildVectorReduceAnd is not available in LLVM version < 5.0")
1026 pub fn vector_reduce_or(&self, src: &'ll Value) -> &'ll Value {
1027 self.count_insn("vector.reduce.or");
1029 let instr = llvm::LLVMRustBuildVectorReduceOr(self.llbuilder, src);
1030 instr.expect("LLVMRustBuildVectorReduceOr is not available in LLVM version < 5.0")
1033 pub fn vector_reduce_xor(&self, src: &'ll Value) -> &'ll Value {
1034 self.count_insn("vector.reduce.xor");
1036 let instr = llvm::LLVMRustBuildVectorReduceXor(self.llbuilder, src);
1037 instr.expect("LLVMRustBuildVectorReduceXor is not available in LLVM version < 5.0")
1040 pub fn vector_reduce_fmin(&self, src: &'ll Value) -> &'ll Value {
1041 self.count_insn("vector.reduce.fmin");
1043 let instr = llvm::LLVMRustBuildVectorReduceFMin(self.llbuilder, src, /*NoNaNs:*/ false);
1044 instr.expect("LLVMRustBuildVectorReduceFMin is not available in LLVM version < 5.0")
1047 pub fn vector_reduce_fmax(&self, src: &'ll Value) -> &'ll Value {
1048 self.count_insn("vector.reduce.fmax");
1050 let instr = llvm::LLVMRustBuildVectorReduceFMax(self.llbuilder, src, /*NoNaNs:*/ false);
1051 instr.expect("LLVMRustBuildVectorReduceFMax is not available in LLVM version < 5.0")
1054 pub fn vector_reduce_fmin_fast(&self, src: &'ll Value) -> &'ll Value {
1055 self.count_insn("vector.reduce.fmin_fast");
1057 let instr = llvm::LLVMRustBuildVectorReduceFMin(self.llbuilder, src, /*NoNaNs:*/ true);
1058 let instr = instr.expect("LLVMRustBuildVectorReduceFMin is not available in LLVM version < 5.0");
1059 llvm::LLVMRustSetHasUnsafeAlgebra(instr);
1063 pub fn vector_reduce_fmax_fast(&self, src: &'ll Value) -> &'ll Value {
1064 self.count_insn("vector.reduce.fmax_fast");
1066 let instr = llvm::LLVMRustBuildVectorReduceFMax(self.llbuilder, src, /*NoNaNs:*/ true);
1067 let instr = instr.expect("LLVMRustBuildVectorReduceFMax is not available in LLVM version < 5.0");
1068 llvm::LLVMRustSetHasUnsafeAlgebra(instr);
1072 pub fn vector_reduce_min(&self, src: &'ll Value, is_signed: bool) -> &'ll Value {
1073 self.count_insn("vector.reduce.min");
1075 let instr = llvm::LLVMRustBuildVectorReduceMin(self.llbuilder, src, is_signed);
1076 instr.expect("LLVMRustBuildVectorReduceMin is not available in LLVM version < 5.0")
1079 pub fn vector_reduce_max(&self, src: &'ll Value, is_signed: bool) -> &'ll Value {
1080 self.count_insn("vector.reduce.max");
1082 let instr = llvm::LLVMRustBuildVectorReduceMax(self.llbuilder, src, is_signed);
1083 instr.expect("LLVMRustBuildVectorReduceMax is not available in LLVM version < 5.0")
1087 pub fn extract_value(&self, agg_val: &'ll Value, idx: u64) -> &'ll Value {
1088 self.count_insn("extractvalue");
1089 assert_eq!(idx as c_uint as u64, idx);
1091 llvm::LLVMBuildExtractValue(self.llbuilder, agg_val, idx as c_uint, noname())
1095 pub fn insert_value(&self, agg_val: &'ll Value, elt: &'ll Value,
1096 idx: u64) -> &'ll Value {
1097 self.count_insn("insertvalue");
1098 assert_eq!(idx as c_uint as u64, idx);
1100 llvm::LLVMBuildInsertValue(self.llbuilder, agg_val, elt, idx as c_uint,
1105 pub fn is_null(&self, val: &'ll Value) -> &'ll Value {
1106 self.count_insn("isnull");
1108 llvm::LLVMBuildIsNull(self.llbuilder, val, noname())
1112 pub fn is_not_null(&self, val: &'ll Value) -> &'ll Value {
1113 self.count_insn("isnotnull");
1115 llvm::LLVMBuildIsNotNull(self.llbuilder, val, noname())
1119 pub fn ptrdiff(&self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
1120 self.count_insn("ptrdiff");
1122 llvm::LLVMBuildPtrDiff(self.llbuilder, lhs, rhs, noname())
1126 pub fn landing_pad(&self, ty: &'ll Type, pers_fn: &'ll Value,
1127 num_clauses: usize) -> &'ll Value {
1128 self.count_insn("landingpad");
1130 llvm::LLVMBuildLandingPad(self.llbuilder, ty, pers_fn,
1131 num_clauses as c_uint, noname())
1135 pub fn add_clause(&self, landing_pad: &'ll Value, clause: &'ll Value) {
1137 llvm::LLVMAddClause(landing_pad, clause);
1141 pub fn set_cleanup(&self, landing_pad: &'ll Value) {
1142 self.count_insn("setcleanup");
1144 llvm::LLVMSetCleanup(landing_pad, llvm::True);
1148 pub fn resume(&self, exn: &'ll Value) -> &'ll Value {
1149 self.count_insn("resume");
1151 llvm::LLVMBuildResume(self.llbuilder, exn)
1155 pub fn cleanup_pad(&self,
1156 parent: Option<&'ll Value>,
1157 args: &[&'ll Value]) -> &'ll Value {
1158 self.count_insn("cleanuppad");
1159 let name = CString::new("cleanuppad").unwrap();
1161 llvm::LLVMRustBuildCleanupPad(self.llbuilder,
1163 args.len() as c_uint,
1167 ret.expect("LLVM does not have support for cleanuppad")
1171 &self, cleanup: &'ll Value,
1172 unwind: Option<&'ll BasicBlock>,
1174 self.count_insn("cleanupret");
1176 llvm::LLVMRustBuildCleanupRet(self.llbuilder, cleanup, unwind)
1178 ret.expect("LLVM does not have support for cleanupret")
1181 pub fn catch_pad(&self,
1183 args: &[&'ll Value]) -> &'ll Value {
1184 self.count_insn("catchpad");
1185 let name = CString::new("catchpad").unwrap();
1187 llvm::LLVMRustBuildCatchPad(self.llbuilder, parent,
1188 args.len() as c_uint, args.as_ptr(),
1191 ret.expect("LLVM does not have support for catchpad")
1194 pub fn catch_ret(&self, pad: &'ll Value, unwind: &'ll BasicBlock) -> &'ll Value {
1195 self.count_insn("catchret");
1197 llvm::LLVMRustBuildCatchRet(self.llbuilder, pad, unwind)
1199 ret.expect("LLVM does not have support for catchret")
1202 pub fn catch_switch(
1204 parent: Option<&'ll Value>,
1205 unwind: Option<&'ll BasicBlock>,
1206 num_handlers: usize,
1208 self.count_insn("catchswitch");
1209 let name = CString::new("catchswitch").unwrap();
1211 llvm::LLVMRustBuildCatchSwitch(self.llbuilder, parent, unwind,
1212 num_handlers as c_uint,
1215 ret.expect("LLVM does not have support for catchswitch")
1218 pub fn add_handler(&self, catch_switch: &'ll Value, handler: &'ll BasicBlock) {
1220 llvm::LLVMRustAddHandler(catch_switch, handler);
1224 pub fn set_personality_fn(&self, personality: &'ll Value) {
1226 llvm::LLVMSetPersonalityFn(self.llfn(), personality);
1230 // Atomic Operations
1231 pub fn atomic_cmpxchg(
1236 order: AtomicOrdering,
1237 failure_order: AtomicOrdering,
1241 llvm::LLVMRustBuildAtomicCmpXchg(self.llbuilder, dst, cmp, src,
1242 order, failure_order, weak)
1250 order: AtomicOrdering,
1253 llvm::LLVMBuildAtomicRMW(self.llbuilder, op, dst, src, order, False)
1257 pub fn atomic_fence(&self, order: AtomicOrdering, scope: SynchronizationScope) {
1259 llvm::LLVMRustBuildAtomicFence(self.llbuilder, order, scope);
1263 pub fn add_case(&self, s: &'ll Value, on_val: &'ll Value, dest: &'ll BasicBlock) {
1265 llvm::LLVMAddCase(s, on_val, dest)
1269 pub fn add_incoming_to_phi(&self, phi: &'ll Value, val: &'ll Value, bb: &'ll BasicBlock) {
1270 self.count_insn("addincoming");
1272 llvm::LLVMAddIncoming(phi, &val, &bb, 1 as c_uint);
1276 pub fn set_invariant_load(&self, load: &'ll Value) {
1278 llvm::LLVMSetMetadata(load, llvm::MD_invariant_load as c_uint,
1279 llvm::LLVMMDNodeInContext(self.cx.llcx, ptr::null(), 0));
1283 /// Returns the ptr value that should be used for storing `val`.
1284 fn check_store<'b>(&self,
1286 ptr: &'ll Value) -> &'ll Value {
1287 let dest_ptr_ty = val_ty(ptr);
1288 let stored_ty = val_ty(val);
1289 let stored_ptr_ty = stored_ty.ptr_to();
1291 assert_eq!(dest_ptr_ty.kind(), llvm::TypeKind::Pointer);
1293 if dest_ptr_ty == stored_ptr_ty {
1296 debug!("Type mismatch in store. \
1297 Expected {:?}, got {:?}; inserting bitcast",
1298 dest_ptr_ty, stored_ptr_ty);
1299 self.bitcast(ptr, stored_ptr_ty)
1303 /// Returns the args that should be used for a call to `llfn`.
1304 fn check_call<'b>(&self,
1307 args: &'b [&'ll Value]) -> Cow<'b, [&'ll Value]> {
1308 let mut fn_ty = val_ty(llfn);
1309 // Strip off pointers
1310 while fn_ty.kind() == llvm::TypeKind::Pointer {
1311 fn_ty = fn_ty.element_type();
1314 assert!(fn_ty.kind() == llvm::TypeKind::Function,
1315 "builder::{} not passed a function, but {:?}", typ, fn_ty);
1317 let param_tys = fn_ty.func_params();
1319 let all_args_match = param_tys.iter()
1320 .zip(args.iter().map(|&v| val_ty(v)))
1321 .all(|(expected_ty, actual_ty)| *expected_ty == actual_ty);
1324 return Cow::Borrowed(args);
1327 let casted_args: Vec<_> = param_tys.into_iter()
1330 .map(|(i, (expected_ty, &actual_val))| {
1331 let actual_ty = val_ty(actual_val);
1332 if expected_ty != actual_ty {
1333 debug!("Type mismatch in function call of {:?}. \
1334 Expected {:?} for param {}, got {:?}; injecting bitcast",
1335 llfn, expected_ty, i, actual_ty);
1336 self.bitcast(actual_val, expected_ty)
1343 return Cow::Owned(casted_args);
1346 pub fn lifetime_start(&self, ptr: &'ll Value, size: Size) {
1347 self.call_lifetime_intrinsic("llvm.lifetime.start", ptr, size);
1350 pub fn lifetime_end(&self, ptr: &'ll Value, size: Size) {
1351 self.call_lifetime_intrinsic("llvm.lifetime.end", ptr, size);
1354 /// If LLVM lifetime intrinsic support is enabled (i.e. optimizations
1355 /// on), and `ptr` is nonzero-sized, then extracts the size of `ptr`
1356 /// and the intrinsic for `lt` and passes them to `emit`, which is in
1357 /// charge of generating code to call the passed intrinsic on whatever
1358 /// block of generated code is targeted for the intrinsic.
1360 /// If LLVM lifetime intrinsic support is disabled (i.e. optimizations
1361 /// off) or `ptr` is zero-sized, then no-op (does not call `emit`).
1362 fn call_lifetime_intrinsic(&self, intrinsic: &str, ptr: &'ll Value, size: Size) {
1363 if self.cx.sess().opts.optimize == config::OptLevel::No {
1367 let size = size.bytes();
1372 let lifetime_intrinsic = self.cx.get_intrinsic(intrinsic);
1374 let ptr = self.pointercast(ptr, Type::i8p(self.cx));
1375 self.call(lifetime_intrinsic, &[C_u64(self.cx, size), ptr], None);