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 use llvm::{AtomicRmwBinOp, AtomicOrdering, SynchronizationScope, AsmDialect};
12 use llvm::{False, OperandBundleDef};
13 use llvm::{self, BasicBlock};
17 use libc::{c_uint, c_char};
18 use rustc::ty::TyCtxt;
19 use rustc::ty::layout::{Align, Size};
20 use rustc::session::{config, Session};
21 use rustc_data_structures::small_c_str::SmallCStr;
22 use traits::{self, BuilderMethods};
28 // All Builders must have an llfn associated with them
30 pub struct Builder<'a, 'll: 'a, 'tcx: 'll, V: 'll = &'ll Value> {
31 pub llbuilder: &'ll mut llvm::Builder<'ll>,
32 pub cx: &'a CodegenCx<'ll, 'tcx, V>,
35 impl<V> Drop for Builder<'_, '_, '_, V> {
38 llvm::LLVMDisposeBuilder(&mut *(self.llbuilder as *mut _));
43 // This is a really awful way to get a zero-length c-string, but better (and a
44 // lot more efficient) than doing str::as_c_str("", ...) every time.
45 fn noname() -> *const c_char {
46 static CNULL: c_char = 0;
51 pub struct MemFlags: u8 {
52 const VOLATILE = 1 << 0;
53 const NONTEMPORAL = 1 << 1;
54 const UNALIGNED = 1 << 2;
58 impl BuilderMethods<'a, 'll, 'tcx, Value, BasicBlock>
59 for Builder<'a, 'll, 'tcx> {
61 cx: &'a CodegenCx<'ll, 'tcx>,
65 let bx = Builder::with_cx(cx);
67 let name = SmallCStr::new(name);
68 llvm::LLVMAppendBasicBlockInContext(
74 bx.position_at_end(llbb);
78 fn with_cx(cx: &'a CodegenCx<'ll, 'tcx>) -> Self {
79 // Create a fresh builder from the crate context.
80 let llbuilder = unsafe {
81 llvm::LLVMCreateBuilderInContext(cx.llcx)
89 fn build_sibling_block<'b>(&self, name: &'b str) -> Self {
90 Builder::new_block(self.cx, self.llfn(), name)
93 fn sess(&self) -> &Session {
97 fn tcx(&self) -> TyCtxt<'a, 'tcx, 'tcx> {
101 fn llfn(&self) -> &'ll Value {
103 llvm::LLVMGetBasicBlockParent(self.llbb())
107 fn llbb(&self) -> &'ll BasicBlock {
109 llvm::LLVMGetInsertBlock(self.llbuilder)
113 fn count_insn(&self, category: &str) {
114 if self.cx().sess().codegen_stats() {
115 self.cx().stats.borrow_mut().n_llvm_insns += 1;
117 if self.cx().sess().count_llvm_insns() {
121 .entry(category.to_string())
126 fn set_value_name(&self, value: &'ll Value, name: &str) {
127 let cname = SmallCStr::new(name);
129 llvm::LLVMSetValueName(value, cname.as_ptr());
133 fn position_at_end(&self, llbb: &'ll BasicBlock) {
135 llvm::LLVMPositionBuilderAtEnd(self.llbuilder, llbb);
139 fn position_at_start(&self, llbb: &'ll BasicBlock) {
141 llvm::LLVMRustPositionBuilderAtStart(self.llbuilder, llbb);
146 self.count_insn("retvoid");
148 llvm::LLVMBuildRetVoid(self.llbuilder);
152 fn ret(&self, v: &'ll Value) {
153 self.count_insn("ret");
155 llvm::LLVMBuildRet(self.llbuilder, v);
159 fn br(&self, dest: &'ll BasicBlock) {
160 self.count_insn("br");
162 llvm::LLVMBuildBr(self.llbuilder, dest);
169 then_llbb: &'ll BasicBlock,
170 else_llbb: &'ll BasicBlock,
172 self.count_insn("condbr");
174 llvm::LLVMBuildCondBr(self.llbuilder, cond, then_llbb, else_llbb);
181 else_llbb: &'ll BasicBlock,
185 llvm::LLVMBuildSwitch(self.llbuilder, v, else_llbb, num_cases as c_uint)
192 then: &'ll BasicBlock,
193 catch: &'ll BasicBlock,
194 bundle: Option<&traits::OperandBundleDef<'ll, &'ll Value>>) -> &'ll Value {
195 self.count_insn("invoke");
197 debug!("Invoke {:?} with args ({:?})",
201 let args = self.check_call("invoke", llfn, args);
202 let bundle = bundle.map(|b| &*(OperandBundleDef::from_generic(b)).raw);
205 llvm::LLVMRustBuildInvoke(self.llbuilder,
208 args.len() as c_uint,
216 fn unreachable(&self) {
217 self.count_insn("unreachable");
219 llvm::LLVMBuildUnreachable(self.llbuilder);
224 fn add(&self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
225 self.count_insn("add");
227 llvm::LLVMBuildAdd(self.llbuilder, lhs, rhs, noname())
231 fn fadd(&self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
232 self.count_insn("fadd");
234 llvm::LLVMBuildFAdd(self.llbuilder, lhs, rhs, noname())
238 fn fadd_fast(&self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
239 self.count_insn("fadd");
241 let instr = llvm::LLVMBuildFAdd(self.llbuilder, lhs, rhs, noname());
242 llvm::LLVMRustSetHasUnsafeAlgebra(instr);
247 fn sub(&self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
248 self.count_insn("sub");
250 llvm::LLVMBuildSub(self.llbuilder, lhs, rhs, noname())
254 fn fsub(&self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
255 self.count_insn("fsub");
257 llvm::LLVMBuildFSub(self.llbuilder, lhs, rhs, noname())
261 fn fsub_fast(&self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
262 self.count_insn("fsub");
264 let instr = llvm::LLVMBuildFSub(self.llbuilder, lhs, rhs, noname());
265 llvm::LLVMRustSetHasUnsafeAlgebra(instr);
270 fn mul(&self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
271 self.count_insn("mul");
273 llvm::LLVMBuildMul(self.llbuilder, lhs, rhs, noname())
277 fn fmul(&self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
278 self.count_insn("fmul");
280 llvm::LLVMBuildFMul(self.llbuilder, lhs, rhs, noname())
284 fn fmul_fast(&self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
285 self.count_insn("fmul");
287 let instr = llvm::LLVMBuildFMul(self.llbuilder, lhs, rhs, noname());
288 llvm::LLVMRustSetHasUnsafeAlgebra(instr);
294 fn udiv(&self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
295 self.count_insn("udiv");
297 llvm::LLVMBuildUDiv(self.llbuilder, lhs, rhs, noname())
301 fn exactudiv(&self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
302 self.count_insn("exactudiv");
304 llvm::LLVMBuildExactUDiv(self.llbuilder, lhs, rhs, noname())
308 fn sdiv(&self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
309 self.count_insn("sdiv");
311 llvm::LLVMBuildSDiv(self.llbuilder, lhs, rhs, noname())
315 fn exactsdiv(&self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
316 self.count_insn("exactsdiv");
318 llvm::LLVMBuildExactSDiv(self.llbuilder, lhs, rhs, noname())
322 fn fdiv(&self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
323 self.count_insn("fdiv");
325 llvm::LLVMBuildFDiv(self.llbuilder, lhs, rhs, noname())
329 fn fdiv_fast(&self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
330 self.count_insn("fdiv");
332 let instr = llvm::LLVMBuildFDiv(self.llbuilder, lhs, rhs, noname());
333 llvm::LLVMRustSetHasUnsafeAlgebra(instr);
338 fn urem(&self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
339 self.count_insn("urem");
341 llvm::LLVMBuildURem(self.llbuilder, lhs, rhs, noname())
345 fn srem(&self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
346 self.count_insn("srem");
348 llvm::LLVMBuildSRem(self.llbuilder, lhs, rhs, noname())
352 fn frem(&self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
353 self.count_insn("frem");
355 llvm::LLVMBuildFRem(self.llbuilder, lhs, rhs, noname())
359 fn frem_fast(&self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
360 self.count_insn("frem");
362 let instr = llvm::LLVMBuildFRem(self.llbuilder, lhs, rhs, noname());
363 llvm::LLVMRustSetHasUnsafeAlgebra(instr);
368 fn shl(&self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
369 self.count_insn("shl");
371 llvm::LLVMBuildShl(self.llbuilder, lhs, rhs, noname())
375 fn lshr(&self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
376 self.count_insn("lshr");
378 llvm::LLVMBuildLShr(self.llbuilder, lhs, rhs, noname())
382 fn ashr(&self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
383 self.count_insn("ashr");
385 llvm::LLVMBuildAShr(self.llbuilder, lhs, rhs, noname())
389 fn and(&self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
390 self.count_insn("and");
392 llvm::LLVMBuildAnd(self.llbuilder, lhs, rhs, noname())
396 fn or(&self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
397 self.count_insn("or");
399 llvm::LLVMBuildOr(self.llbuilder, lhs, rhs, noname())
403 fn xor(&self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
404 self.count_insn("xor");
406 llvm::LLVMBuildXor(self.llbuilder, lhs, rhs, noname())
410 fn neg(&self, v: &'ll Value) -> &'ll Value {
411 self.count_insn("neg");
413 llvm::LLVMBuildNeg(self.llbuilder, v, noname())
417 fn fneg(&self, v: &'ll Value) -> &'ll Value {
418 self.count_insn("fneg");
420 llvm::LLVMBuildFNeg(self.llbuilder, v, noname())
424 fn not(&self, v: &'ll Value) -> &'ll Value {
425 self.count_insn("not");
427 llvm::LLVMBuildNot(self.llbuilder, v, noname())
431 fn alloca(&self, ty: &'ll Type, name: &str, align: Align) -> &'ll Value {
432 let bx = Builder::with_cx(self.cx);
433 bx.position_at_start(unsafe {
434 llvm::LLVMGetFirstBasicBlock(self.llfn())
436 bx.dynamic_alloca(ty, name, align)
439 fn dynamic_alloca(&self, ty: &'ll Type, name: &str, align: Align) -> &'ll Value {
440 self.count_insn("alloca");
442 let alloca = if name.is_empty() {
443 llvm::LLVMBuildAlloca(self.llbuilder, ty, noname())
445 let name = SmallCStr::new(name);
446 llvm::LLVMBuildAlloca(self.llbuilder, ty,
449 llvm::LLVMSetAlignment(alloca, align.abi() as c_uint);
454 fn array_alloca(&self,
458 align: Align) -> &'ll Value {
459 self.count_insn("alloca");
461 let alloca = if name.is_empty() {
462 llvm::LLVMBuildArrayAlloca(self.llbuilder, ty, len, noname())
464 let name = SmallCStr::new(name);
465 llvm::LLVMBuildArrayAlloca(self.llbuilder, ty, len,
468 llvm::LLVMSetAlignment(alloca, align.abi() as c_uint);
473 fn load(&self, ptr: &'ll Value, align: Align) -> &'ll Value {
474 self.count_insn("load");
476 let load = llvm::LLVMBuildLoad(self.llbuilder, ptr, noname());
477 llvm::LLVMSetAlignment(load, align.abi() as c_uint);
482 fn volatile_load(&self, ptr: &'ll Value) -> &'ll Value {
483 self.count_insn("load.volatile");
485 let insn = llvm::LLVMBuildLoad(self.llbuilder, ptr, noname());
486 llvm::LLVMSetVolatile(insn, llvm::True);
494 order: traits::AtomicOrdering,
497 self.count_insn("load.atomic");
499 let load = llvm::LLVMRustBuildAtomicLoad(
503 AtomicOrdering::from_generic(order),
505 // LLVM requires the alignment of atomic loads to be at least the size of the type.
506 llvm::LLVMSetAlignment(load, size.bytes() as c_uint);
512 fn range_metadata(&self, load: &'ll Value, range: Range<u128>) {
513 if self.sess().target.target.arch == "amdgpu" {
514 // amdgpu/LLVM does something weird and thinks a i64 value is
515 // split into a v2i32, halving the bitwidth LLVM expects,
516 // tripping an assertion. So, for now, just disable this
522 let llty = val_ty(load);
524 C_uint_big(llty, range.start),
525 C_uint_big(llty, range.end)
528 llvm::LLVMSetMetadata(load, llvm::MD_range as c_uint,
529 llvm::LLVMMDNodeInContext(self.cx.llcx,
535 fn nonnull_metadata(&self, load: &'ll Value) {
537 llvm::LLVMSetMetadata(load, llvm::MD_nonnull as c_uint,
538 llvm::LLVMMDNodeInContext(self.cx.llcx, ptr::null(), 0));
542 fn store(&self, val: &'ll Value, ptr: &'ll Value, align: Align) -> &'ll Value {
543 self.store_with_flags(val, ptr, align, MemFlags::empty())
553 debug!("Store {:?} -> {:?} ({:?})", val, ptr, flags);
554 self.count_insn("store");
555 let ptr = self.check_store(val, ptr);
557 let store = llvm::LLVMBuildStore(self.llbuilder, val, ptr);
558 let align = if flags.contains(MemFlags::UNALIGNED) {
561 align.abi() as c_uint
563 llvm::LLVMSetAlignment(store, align);
564 if flags.contains(MemFlags::VOLATILE) {
565 llvm::LLVMSetVolatile(store, llvm::True);
567 if flags.contains(MemFlags::NONTEMPORAL) {
568 // According to LLVM [1] building a nontemporal store must
569 // *always* point to a metadata value of the integer 1.
571 // [1]: http://llvm.org/docs/LangRef.html#store-instruction
572 let one = C_i32(self.cx, 1);
573 let node = llvm::LLVMMDNodeInContext(self.cx.llcx, &one, 1);
574 llvm::LLVMSetMetadata(store, llvm::MD_nontemporal as c_uint, node);
580 fn atomic_store(&self, val: &'ll Value, ptr: &'ll Value,
581 order: traits::AtomicOrdering, size: Size) {
582 debug!("Store {:?} -> {:?}", val, ptr);
583 self.count_insn("store.atomic");
584 let ptr = self.check_store(val, ptr);
586 let store = llvm::LLVMRustBuildAtomicStore(
590 AtomicOrdering::from_generic(order),
592 // LLVM requires the alignment of atomic stores to be at least the size of the type.
593 llvm::LLVMSetAlignment(store, size.bytes() as c_uint);
597 fn gep(&self, ptr: &'ll Value, indices: &[&'ll Value]) -> &'ll Value {
598 self.count_insn("gep");
600 llvm::LLVMBuildGEP(self.llbuilder, ptr, indices.as_ptr(),
601 indices.len() as c_uint, noname())
605 fn inbounds_gep(&self, ptr: &'ll Value, indices: &[&'ll Value]) -> &'ll Value {
606 self.count_insn("inboundsgep");
608 llvm::LLVMBuildInBoundsGEP(
609 self.llbuilder, ptr, indices.as_ptr(), indices.len() as c_uint, noname())
614 fn trunc(&self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
615 self.count_insn("trunc");
617 llvm::LLVMBuildTrunc(self.llbuilder, val, dest_ty, noname())
621 fn sext(&self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
622 self.count_insn("sext");
624 llvm::LLVMBuildSExt(self.llbuilder, val, dest_ty, noname())
628 fn fptoui(&self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
629 self.count_insn("fptoui");
631 llvm::LLVMBuildFPToUI(self.llbuilder, val, dest_ty, noname())
635 fn fptosi(&self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
636 self.count_insn("fptosi");
638 llvm::LLVMBuildFPToSI(self.llbuilder, val, dest_ty,noname())
642 fn uitofp(&self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
643 self.count_insn("uitofp");
645 llvm::LLVMBuildUIToFP(self.llbuilder, val, dest_ty, noname())
649 fn sitofp(&self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
650 self.count_insn("sitofp");
652 llvm::LLVMBuildSIToFP(self.llbuilder, val, dest_ty, noname())
656 fn fptrunc(&self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
657 self.count_insn("fptrunc");
659 llvm::LLVMBuildFPTrunc(self.llbuilder, val, dest_ty, noname())
663 fn fpext(&self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
664 self.count_insn("fpext");
666 llvm::LLVMBuildFPExt(self.llbuilder, val, dest_ty, noname())
670 fn ptrtoint(&self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
671 self.count_insn("ptrtoint");
673 llvm::LLVMBuildPtrToInt(self.llbuilder, val, dest_ty, noname())
677 fn inttoptr(&self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
678 self.count_insn("inttoptr");
680 llvm::LLVMBuildIntToPtr(self.llbuilder, val, dest_ty, noname())
684 fn bitcast(&self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
685 self.count_insn("bitcast");
687 llvm::LLVMBuildBitCast(self.llbuilder, val, dest_ty, noname())
692 fn intcast(&self, val: &'ll Value, dest_ty: &'ll Type, is_signed: bool) -> &'ll Value {
693 self.count_insn("intcast");
695 llvm::LLVMRustBuildIntCast(self.llbuilder, val, dest_ty, is_signed)
699 fn pointercast(&self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
700 self.count_insn("pointercast");
702 llvm::LLVMBuildPointerCast(self.llbuilder, val, dest_ty, noname())
707 fn icmp(&self, op: traits::IntPredicate, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
708 self.count_insn("icmp");
709 let op = llvm::IntPredicate::from_generic(op);
711 llvm::LLVMBuildICmp(self.llbuilder, op as c_uint, lhs, rhs, noname())
715 fn fcmp(&self, op: traits::RealPredicate, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
716 self.count_insn("fcmp");
718 llvm::LLVMBuildFCmp(self.llbuilder, op as c_uint, lhs, rhs, noname())
722 /* Miscellaneous instructions */
723 fn empty_phi(&self, ty: &'ll Type) -> &'ll Value {
724 self.count_insn("emptyphi");
726 llvm::LLVMBuildPhi(self.llbuilder, ty, noname())
730 fn phi(&self, ty: &'ll Type, vals: &[&'ll Value], bbs: &[&'ll BasicBlock]) -> &'ll Value {
731 assert_eq!(vals.len(), bbs.len());
732 let phi = self.empty_phi(ty);
733 self.count_insn("addincoming");
735 llvm::LLVMAddIncoming(phi, vals.as_ptr(),
737 vals.len() as c_uint);
742 fn inline_asm_call(&self, asm: *const c_char, cons: *const c_char,
743 inputs: &[&'ll Value], output: &'ll Type,
744 volatile: bool, alignstack: bool,
745 dia: AsmDialect) -> Option<&'ll Value> {
746 self.count_insn("inlineasm");
748 let volatile = if volatile { llvm::True }
749 else { llvm::False };
750 let alignstack = if alignstack { llvm::True }
751 else { llvm::False };
753 let argtys = inputs.iter().map(|v| {
754 debug!("Asm Input Type: {:?}", *v);
756 }).collect::<Vec<_>>();
758 debug!("Asm Output Type: {:?}", output);
759 let fty = Type::func::<Value>(&argtys[..], output);
761 // Ask LLVM to verify that the constraints are well-formed.
762 let constraints_ok = llvm::LLVMRustInlineAsmVerify(fty, cons);
763 debug!("Constraint verification result: {:?}", constraints_ok);
765 let v = llvm::LLVMRustInlineAsm(
766 fty, asm, cons, volatile, alignstack, dia);
767 Some(self.call(v, inputs, None))
769 // LLVM has detected an issue with our constraints, bail out
775 fn memcpy(&self, dst: &'ll Value, dst_align: u64,
776 src: &'ll Value, src_align: u64,
777 size: &'ll Value, is_volatile: bool) -> &'ll Value {
779 llvm::LLVMRustBuildMemCpy(self.llbuilder, dst, dst_align as c_uint,
780 src, src_align as c_uint, size, is_volatile)
784 fn memmove(&self, dst: &'ll Value, dst_align: u64,
785 src: &'ll Value, src_align: u64,
786 size: &'ll Value, is_volatile: bool) -> &'ll Value {
788 llvm::LLVMRustBuildMemMove(self.llbuilder, dst, dst_align as c_uint,
789 src, src_align as c_uint, size, is_volatile)
793 fn minnum(&self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
794 self.count_insn("minnum");
796 let instr = llvm::LLVMRustBuildMinNum(self.llbuilder, lhs, rhs);
797 instr.expect("LLVMRustBuildMinNum is not available in LLVM version < 6.0")
800 fn maxnum(&self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
801 self.count_insn("maxnum");
803 let instr = llvm::LLVMRustBuildMaxNum(self.llbuilder, lhs, rhs);
804 instr.expect("LLVMRustBuildMaxNum is not available in LLVM version < 6.0")
809 &self, cond: &'ll Value,
810 then_val: &'ll Value,
811 else_val: &'ll Value,
813 self.count_insn("select");
815 llvm::LLVMBuildSelect(self.llbuilder, cond, then_val, else_val, noname())
820 fn va_arg(&self, list: &'ll Value, ty: &'ll Type) -> &'ll Value {
821 self.count_insn("vaarg");
823 llvm::LLVMBuildVAArg(self.llbuilder, list, ty, noname())
827 fn extract_element(&self, vec: &'ll Value, idx: &'ll Value) -> &'ll Value {
828 self.count_insn("extractelement");
830 llvm::LLVMBuildExtractElement(self.llbuilder, vec, idx, noname())
835 &self, vec: &'ll Value,
839 self.count_insn("insertelement");
841 llvm::LLVMBuildInsertElement(self.llbuilder, vec, elt, idx, noname())
845 fn shuffle_vector(&self, v1: &'ll Value, v2: &'ll Value, mask: &'ll Value) -> &'ll Value {
846 self.count_insn("shufflevector");
848 llvm::LLVMBuildShuffleVector(self.llbuilder, v1, v2, mask, noname())
852 fn vector_splat(&self, num_elts: usize, elt: &'ll Value) -> &'ll Value {
854 let elt_ty = val_ty(elt);
855 let undef = llvm::LLVMGetUndef(Type::vector::<Value>(elt_ty, num_elts as u64));
856 let vec = self.insert_element(undef, elt, C_i32(self.cx, 0));
857 let vec_i32_ty = Type::vector::<Value>(Type::i32(self.cx), num_elts as u64);
858 self.shuffle_vector(vec, undef, C_null(vec_i32_ty))
862 fn vector_reduce_fadd_fast(&self, acc: &'ll Value, src: &'ll Value) -> &'ll Value {
863 self.count_insn("vector.reduce.fadd_fast");
865 // FIXME: add a non-fast math version once
866 // https://bugs.llvm.org/show_bug.cgi?id=36732
868 let instr = llvm::LLVMRustBuildVectorReduceFAdd(self.llbuilder, acc, src);
869 llvm::LLVMRustSetHasUnsafeAlgebra(instr);
873 fn vector_reduce_fmul_fast(&self, acc: &'ll Value, src: &'ll Value) -> &'ll Value {
874 self.count_insn("vector.reduce.fmul_fast");
876 // FIXME: add a non-fast math version once
877 // https://bugs.llvm.org/show_bug.cgi?id=36732
879 let instr = llvm::LLVMRustBuildVectorReduceFMul(self.llbuilder, acc, src);
880 llvm::LLVMRustSetHasUnsafeAlgebra(instr);
884 fn vector_reduce_add(&self, src: &'ll Value) -> &'ll Value {
885 self.count_insn("vector.reduce.add");
886 unsafe { llvm::LLVMRustBuildVectorReduceAdd(self.llbuilder, src) }
888 fn vector_reduce_mul(&self, src: &'ll Value) -> &'ll Value {
889 self.count_insn("vector.reduce.mul");
890 unsafe { llvm::LLVMRustBuildVectorReduceMul(self.llbuilder, src) }
892 fn vector_reduce_and(&self, src: &'ll Value) -> &'ll Value {
893 self.count_insn("vector.reduce.and");
894 unsafe { llvm::LLVMRustBuildVectorReduceAnd(self.llbuilder, src) }
896 fn vector_reduce_or(&self, src: &'ll Value) -> &'ll Value {
897 self.count_insn("vector.reduce.or");
898 unsafe { llvm::LLVMRustBuildVectorReduceOr(self.llbuilder, src) }
900 fn vector_reduce_xor(&self, src: &'ll Value) -> &'ll Value {
901 self.count_insn("vector.reduce.xor");
902 unsafe { llvm::LLVMRustBuildVectorReduceXor(self.llbuilder, src) }
904 fn vector_reduce_fmin(&self, src: &'ll Value) -> &'ll Value {
905 self.count_insn("vector.reduce.fmin");
906 unsafe { llvm::LLVMRustBuildVectorReduceFMin(self.llbuilder, src, /*NoNaNs:*/ false) }
908 fn vector_reduce_fmax(&self, src: &'ll Value) -> &'ll Value {
909 self.count_insn("vector.reduce.fmax");
910 unsafe { llvm::LLVMRustBuildVectorReduceFMax(self.llbuilder, src, /*NoNaNs:*/ false) }
912 fn vector_reduce_fmin_fast(&self, src: &'ll Value) -> &'ll Value {
913 self.count_insn("vector.reduce.fmin_fast");
915 let instr = llvm::LLVMRustBuildVectorReduceFMin(self.llbuilder, src, /*NoNaNs:*/ true);
916 llvm::LLVMRustSetHasUnsafeAlgebra(instr);
920 fn vector_reduce_fmax_fast(&self, src: &'ll Value) -> &'ll Value {
921 self.count_insn("vector.reduce.fmax_fast");
923 let instr = llvm::LLVMRustBuildVectorReduceFMax(self.llbuilder, src, /*NoNaNs:*/ true);
924 llvm::LLVMRustSetHasUnsafeAlgebra(instr);
928 fn vector_reduce_min(&self, src: &'ll Value, is_signed: bool) -> &'ll Value {
929 self.count_insn("vector.reduce.min");
930 unsafe { llvm::LLVMRustBuildVectorReduceMin(self.llbuilder, src, is_signed) }
932 fn vector_reduce_max(&self, src: &'ll Value, is_signed: bool) -> &'ll Value {
933 self.count_insn("vector.reduce.max");
934 unsafe { llvm::LLVMRustBuildVectorReduceMax(self.llbuilder, src, is_signed) }
937 fn extract_value(&self, agg_val: &'ll Value, idx: u64) -> &'ll Value {
938 self.count_insn("extractvalue");
939 assert_eq!(idx as c_uint as u64, idx);
941 llvm::LLVMBuildExtractValue(self.llbuilder, agg_val, idx as c_uint, noname())
945 fn insert_value(&self, agg_val: &'ll Value, elt: &'ll Value,
946 idx: u64) -> &'ll Value {
947 self.count_insn("insertvalue");
948 assert_eq!(idx as c_uint as u64, idx);
950 llvm::LLVMBuildInsertValue(self.llbuilder, agg_val, elt, idx as c_uint,
955 fn landing_pad(&self, ty: &'ll Type, pers_fn: &'ll Value,
956 num_clauses: usize) -> &'ll Value {
957 self.count_insn("landingpad");
959 llvm::LLVMBuildLandingPad(self.llbuilder, ty, pers_fn,
960 num_clauses as c_uint, noname())
964 fn add_clause(&self, landing_pad: &'ll Value, clause: &'ll Value) {
966 llvm::LLVMAddClause(landing_pad, clause);
970 fn set_cleanup(&self, landing_pad: &'ll Value) {
971 self.count_insn("setcleanup");
973 llvm::LLVMSetCleanup(landing_pad, llvm::True);
977 fn resume(&self, exn: &'ll Value) -> &'ll Value {
978 self.count_insn("resume");
980 llvm::LLVMBuildResume(self.llbuilder, exn)
984 fn cleanup_pad(&self,
985 parent: Option<&'ll Value>,
986 args: &[&'ll Value]) -> &'ll Value {
987 self.count_insn("cleanuppad");
988 let name = const_cstr!("cleanuppad");
990 llvm::LLVMRustBuildCleanupPad(self.llbuilder,
992 args.len() as c_uint,
996 ret.expect("LLVM does not have support for cleanuppad")
1000 &self, cleanup: &'ll Value,
1001 unwind: Option<&'ll BasicBlock>,
1003 self.count_insn("cleanupret");
1005 llvm::LLVMRustBuildCleanupRet(self.llbuilder, cleanup, unwind)
1007 ret.expect("LLVM does not have support for cleanupret")
1012 args: &[&'ll Value]) -> &'ll Value {
1013 self.count_insn("catchpad");
1014 let name = const_cstr!("catchpad");
1016 llvm::LLVMRustBuildCatchPad(self.llbuilder, parent,
1017 args.len() as c_uint, args.as_ptr(),
1020 ret.expect("LLVM does not have support for catchpad")
1023 fn catch_ret(&self, pad: &'ll Value, unwind: &'ll BasicBlock) -> &'ll Value {
1024 self.count_insn("catchret");
1026 llvm::LLVMRustBuildCatchRet(self.llbuilder, pad, unwind)
1028 ret.expect("LLVM does not have support for catchret")
1033 parent: Option<&'ll Value>,
1034 unwind: Option<&'ll BasicBlock>,
1035 num_handlers: usize,
1037 self.count_insn("catchswitch");
1038 let name = const_cstr!("catchswitch");
1040 llvm::LLVMRustBuildCatchSwitch(self.llbuilder, parent, unwind,
1041 num_handlers as c_uint,
1044 ret.expect("LLVM does not have support for catchswitch")
1047 fn add_handler(&self, catch_switch: &'ll Value, handler: &'ll BasicBlock) {
1049 llvm::LLVMRustAddHandler(catch_switch, handler);
1053 fn set_personality_fn(&self, personality: &'ll Value) {
1055 llvm::LLVMSetPersonalityFn(self.llfn(), personality);
1059 // Atomic Operations
1065 order: traits::AtomicOrdering,
1066 failure_order: traits::AtomicOrdering,
1069 let weak = if weak { llvm::True } else { llvm::False };
1071 llvm::LLVMRustBuildAtomicCmpXchg(
1076 AtomicOrdering::from_generic(order),
1077 AtomicOrdering::from_generic(failure_order),
1084 op: traits::AtomicRmwBinOp,
1087 order: traits::AtomicOrdering,
1090 llvm::LLVMBuildAtomicRMW(
1092 AtomicRmwBinOp::from_generic(op),
1095 AtomicOrdering::from_generic(order),
1100 fn atomic_fence(&self, order: traits::AtomicOrdering, scope: SynchronizationScope) {
1102 llvm::LLVMRustBuildAtomicFence(
1104 AtomicOrdering::from_generic(order),
1110 fn add_case(&self, s: &'ll Value, on_val: &'ll Value, dest: &'ll BasicBlock) {
1112 llvm::LLVMAddCase(s, on_val, dest)
1116 fn add_incoming_to_phi(&self, phi: &'ll Value, val: &'ll Value, bb: &'ll BasicBlock) {
1117 self.count_insn("addincoming");
1119 llvm::LLVMAddIncoming(phi, &val, &bb, 1 as c_uint);
1123 fn set_invariant_load(&self, load: &'ll Value) {
1125 llvm::LLVMSetMetadata(load, llvm::MD_invariant_load as c_uint,
1126 llvm::LLVMMDNodeInContext(self.cx.llcx, ptr::null(), 0));
1130 /// Returns the ptr value that should be used for storing `val`.
1131 fn check_store<'b>(&self,
1133 ptr: &'ll Value) -> &'ll Value {
1134 let dest_ptr_ty = val_ty(ptr);
1135 let stored_ty = val_ty(val);
1136 let stored_ptr_ty = stored_ty.ptr_to();
1138 assert_eq!(dest_ptr_ty.kind(), llvm::TypeKind::Pointer);
1140 if dest_ptr_ty == stored_ptr_ty {
1143 debug!("Type mismatch in store. \
1144 Expected {:?}, got {:?}; inserting bitcast",
1145 dest_ptr_ty, stored_ptr_ty);
1146 self.bitcast(ptr, stored_ptr_ty)
1150 /// Returns the args that should be used for a call to `llfn`.
1151 fn check_call<'b>(&self,
1154 args: &'b [&'ll Value]) -> Cow<'b, [&'ll Value]> {
1155 let mut fn_ty = val_ty(llfn);
1156 // Strip off pointers
1157 while fn_ty.kind() == llvm::TypeKind::Pointer {
1158 fn_ty = fn_ty.element_type();
1161 assert!(fn_ty.kind() == llvm::TypeKind::Function,
1162 "builder::{} not passed a function, but {:?}", typ, fn_ty);
1164 let param_tys = fn_ty.func_params();
1166 let all_args_match = param_tys.iter()
1167 .zip(args.iter().map(|&v| val_ty(v)))
1168 .all(|(expected_ty, actual_ty)| *expected_ty == actual_ty);
1171 return Cow::Borrowed(args);
1174 let casted_args: Vec<_> = param_tys.into_iter()
1177 .map(|(i, (expected_ty, &actual_val))| {
1178 let actual_ty = val_ty(actual_val);
1179 if expected_ty != actual_ty {
1180 debug!("Type mismatch in function call of {:?}. \
1181 Expected {:?} for param {}, got {:?}; injecting bitcast",
1182 llfn, expected_ty, i, actual_ty);
1183 self.bitcast(actual_val, expected_ty)
1190 Cow::Owned(casted_args)
1193 fn lifetime_start(&self, ptr: &'ll Value, size: Size) {
1194 self.call_lifetime_intrinsic("llvm.lifetime.start", ptr, size);
1197 fn lifetime_end(&self, ptr: &'ll Value, size: Size) {
1198 self.call_lifetime_intrinsic("llvm.lifetime.end", ptr, size);
1201 /// If LLVM lifetime intrinsic support is enabled (i.e. optimizations
1202 /// on), and `ptr` is nonzero-sized, then extracts the size of `ptr`
1203 /// and the intrinsic for `lt` and passes them to `emit`, which is in
1204 /// charge of generating code to call the passed intrinsic on whatever
1205 /// block of generated code is targeted for the intrinsic.
1207 /// If LLVM lifetime intrinsic support is disabled (i.e. optimizations
1208 /// off) or `ptr` is zero-sized, then no-op (does not call `emit`).
1209 fn call_lifetime_intrinsic(&self, intrinsic: &str, ptr: &'ll Value, size: Size) {
1210 if self.cx.sess().opts.optimize == config::OptLevel::No {
1214 let size = size.bytes();
1219 let lifetime_intrinsic = self.cx.get_intrinsic(intrinsic);
1221 let ptr = self.pointercast(ptr, Type::i8p(self.cx));
1222 self.call(lifetime_intrinsic, &[C_u64(self.cx, size), ptr], None);
1225 fn call(&self, llfn: &'ll Value, args: &[&'ll Value],
1226 bundle: Option<&traits::OperandBundleDef<'ll, &'ll Value>>) -> &'ll Value {
1227 self.count_insn("call");
1229 debug!("Call {:?} with args ({:?})",
1233 let args = self.check_call("call", llfn, args);
1234 let bundle = bundle.map(|b| &*(OperandBundleDef::from_generic(b)).raw);
1237 llvm::LLVMRustBuildCall(
1240 args.as_ptr() as *const &llvm::Value,
1241 args.len() as c_uint,
1247 fn zext(&self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1248 self.count_insn("zext");
1250 llvm::LLVMBuildZExt(self.llbuilder, val, dest_ty, noname())
1254 fn struct_gep(&self, ptr: &'ll Value, idx: u64) -> &'ll Value {
1255 self.count_insn("structgep");
1256 assert_eq!(idx as c_uint as u64, idx);
1258 llvm::LLVMBuildStructGEP(self.llbuilder, ptr, idx as c_uint, noname())
1262 fn cx(&self) -> &'a CodegenCx<'ll, 'tcx, &'ll Value> {