]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/trans/builder.rs
auto merge of #16836 : P1start/rust/closure_ret_bang, r=alexcrichton
[rust.git] / src / librustc / middle / trans / builder.rs
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.
4 //
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.
10
11 #![allow(dead_code)] // FFI wrappers
12
13 use llvm;
14 use llvm::{CallConv, AtomicBinOp, AtomicOrdering, AsmDialect, AttrBuilder};
15 use llvm::{Opcode, IntPredicate, RealPredicate, False};
16 use llvm::{ValueRef, BasicBlockRef, BuilderRef, ModuleRef};
17 use middle::trans::base;
18 use middle::trans::common::*;
19 use middle::trans::machine::llalign_of_pref;
20 use middle::trans::type_::Type;
21 use std::collections::HashMap;
22 use libc::{c_uint, c_ulonglong, c_char};
23 use std::string::String;
24 use syntax::codemap::Span;
25
26 pub struct Builder<'a, 'tcx: 'a> {
27     pub llbuilder: BuilderRef,
28     pub ccx: &'a CrateContext<'a, 'tcx>,
29 }
30
31 // This is a really awful way to get a zero-length c-string, but better (and a
32 // lot more efficient) than doing str::as_c_str("", ...) every time.
33 pub fn noname() -> *const c_char {
34     static cnull: c_char = 0;
35     &cnull as *const c_char
36 }
37
38 impl<'a, 'tcx> Builder<'a, 'tcx> {
39     pub fn new(ccx: &'a CrateContext<'a, 'tcx>) -> Builder<'a, 'tcx> {
40         Builder {
41             llbuilder: ccx.raw_builder(),
42             ccx: ccx,
43         }
44     }
45
46     pub fn count_insn(&self, category: &str) {
47         if self.ccx.sess().trans_stats() {
48             self.ccx.stats().n_llvm_insns.set(self.ccx
49                                                 .stats()
50                                                 .n_llvm_insns
51                                                 .get() + 1);
52         }
53         self.ccx.count_llvm_insn();
54         if self.ccx.sess().count_llvm_insns() {
55             base::with_insn_ctxt(|v| {
56                 let mut h = self.ccx.stats().llvm_insns.borrow_mut();
57
58                 // Build version of path with cycles removed.
59
60                 // Pass 1: scan table mapping str -> rightmost pos.
61                 let mut mm = HashMap::new();
62                 let len = v.len();
63                 let mut i = 0u;
64                 while i < len {
65                     mm.insert(v[i], i);
66                     i += 1u;
67                 }
68
69                 // Pass 2: concat strings for each elt, skipping
70                 // forwards over any cycles by advancing to rightmost
71                 // occurrence of each element in path.
72                 let mut s = String::from_str(".");
73                 i = 0u;
74                 while i < len {
75                     i = *mm.get(&v[i]);
76                     s.push_char('/');
77                     s.push_str(v[i]);
78                     i += 1u;
79                 }
80
81                 s.push_char('/');
82                 s.push_str(category);
83
84                 let n = match h.find(&s) {
85                     Some(&n) => n,
86                     _ => 0u
87                 };
88                 h.insert(s, n+1u);
89             })
90         }
91     }
92
93     pub fn position_before(&self, insn: ValueRef) {
94         unsafe {
95             llvm::LLVMPositionBuilderBefore(self.llbuilder, insn);
96         }
97     }
98
99     pub fn position_at_end(&self, llbb: BasicBlockRef) {
100         unsafe {
101             llvm::LLVMPositionBuilderAtEnd(self.llbuilder, llbb);
102         }
103     }
104
105     pub fn ret_void(&self) {
106         self.count_insn("retvoid");
107         unsafe {
108             llvm::LLVMBuildRetVoid(self.llbuilder);
109         }
110     }
111
112     pub fn ret(&self, v: ValueRef) {
113         self.count_insn("ret");
114         unsafe {
115             llvm::LLVMBuildRet(self.llbuilder, v);
116         }
117     }
118
119     pub fn aggregate_ret(&self, ret_vals: &[ValueRef]) {
120         unsafe {
121             llvm::LLVMBuildAggregateRet(self.llbuilder,
122                                         ret_vals.as_ptr(),
123                                         ret_vals.len() as c_uint);
124         }
125     }
126
127     pub fn br(&self, dest: BasicBlockRef) {
128         self.count_insn("br");
129         unsafe {
130             llvm::LLVMBuildBr(self.llbuilder, dest);
131         }
132     }
133
134     pub fn cond_br(&self, cond: ValueRef, then_llbb: BasicBlockRef, else_llbb: BasicBlockRef) {
135         self.count_insn("condbr");
136         unsafe {
137             llvm::LLVMBuildCondBr(self.llbuilder, cond, then_llbb, else_llbb);
138         }
139     }
140
141     pub fn switch(&self, v: ValueRef, else_llbb: BasicBlockRef, num_cases: uint) -> ValueRef {
142         unsafe {
143             llvm::LLVMBuildSwitch(self.llbuilder, v, else_llbb, num_cases as c_uint)
144         }
145     }
146
147     pub fn indirect_br(&self, addr: ValueRef, num_dests: uint) {
148         self.count_insn("indirectbr");
149         unsafe {
150             llvm::LLVMBuildIndirectBr(self.llbuilder, addr, num_dests as c_uint);
151         }
152     }
153
154     pub fn invoke(&self,
155                   llfn: ValueRef,
156                   args: &[ValueRef],
157                   then: BasicBlockRef,
158                   catch: BasicBlockRef,
159                   attributes: Option<AttrBuilder>)
160                   -> ValueRef {
161         self.count_insn("invoke");
162
163         debug!("Invoke {} with args ({})",
164                self.ccx.tn().val_to_string(llfn),
165                args.iter()
166                    .map(|&v| self.ccx.tn().val_to_string(v))
167                    .collect::<Vec<String>>()
168                    .connect(", "));
169
170         unsafe {
171             let v = llvm::LLVMBuildInvoke(self.llbuilder,
172                                           llfn,
173                                           args.as_ptr(),
174                                           args.len() as c_uint,
175                                           then,
176                                           catch,
177                                           noname());
178             match attributes {
179                 Some(a) => a.apply_callsite(v),
180                 None => {}
181             }
182             v
183         }
184     }
185
186     pub fn unreachable(&self) {
187         self.count_insn("unreachable");
188         unsafe {
189             llvm::LLVMBuildUnreachable(self.llbuilder);
190         }
191     }
192
193     /* Arithmetic */
194     pub fn add(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
195         self.count_insn("add");
196         unsafe {
197             llvm::LLVMBuildAdd(self.llbuilder, lhs, rhs, noname())
198         }
199     }
200
201     pub fn nswadd(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
202         self.count_insn("nswadd");
203         unsafe {
204             llvm::LLVMBuildNSWAdd(self.llbuilder, lhs, rhs, noname())
205         }
206     }
207
208     pub fn nuwadd(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
209         self.count_insn("nuwadd");
210         unsafe {
211             llvm::LLVMBuildNUWAdd(self.llbuilder, lhs, rhs, noname())
212         }
213     }
214
215     pub fn fadd(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
216         self.count_insn("fadd");
217         unsafe {
218             llvm::LLVMBuildFAdd(self.llbuilder, lhs, rhs, noname())
219         }
220     }
221
222     pub fn sub(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
223         self.count_insn("sub");
224         unsafe {
225             llvm::LLVMBuildSub(self.llbuilder, lhs, rhs, noname())
226         }
227     }
228
229     pub fn nswsub(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
230         self.count_insn("nwsub");
231         unsafe {
232             llvm::LLVMBuildNSWSub(self.llbuilder, lhs, rhs, noname())
233         }
234     }
235
236     pub fn nuwsub(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
237         self.count_insn("nuwsub");
238         unsafe {
239             llvm::LLVMBuildNUWSub(self.llbuilder, lhs, rhs, noname())
240         }
241     }
242
243     pub fn fsub(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
244         self.count_insn("sub");
245         unsafe {
246             llvm::LLVMBuildFSub(self.llbuilder, lhs, rhs, noname())
247         }
248     }
249
250     pub fn mul(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
251         self.count_insn("mul");
252         unsafe {
253             llvm::LLVMBuildMul(self.llbuilder, lhs, rhs, noname())
254         }
255     }
256
257     pub fn nswmul(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
258         self.count_insn("nswmul");
259         unsafe {
260             llvm::LLVMBuildNSWMul(self.llbuilder, lhs, rhs, noname())
261         }
262     }
263
264     pub fn nuwmul(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
265         self.count_insn("nuwmul");
266         unsafe {
267             llvm::LLVMBuildNUWMul(self.llbuilder, lhs, rhs, noname())
268         }
269     }
270
271     pub fn fmul(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
272         self.count_insn("fmul");
273         unsafe {
274             llvm::LLVMBuildFMul(self.llbuilder, lhs, rhs, noname())
275         }
276     }
277
278     pub fn udiv(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
279         self.count_insn("udiv");
280         unsafe {
281             llvm::LLVMBuildUDiv(self.llbuilder, lhs, rhs, noname())
282         }
283     }
284
285     pub fn sdiv(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
286         self.count_insn("sdiv");
287         unsafe {
288             llvm::LLVMBuildSDiv(self.llbuilder, lhs, rhs, noname())
289         }
290     }
291
292     pub fn exactsdiv(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
293         self.count_insn("exactsdiv");
294         unsafe {
295             llvm::LLVMBuildExactSDiv(self.llbuilder, lhs, rhs, noname())
296         }
297     }
298
299     pub fn fdiv(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
300         self.count_insn("fdiv");
301         unsafe {
302             llvm::LLVMBuildFDiv(self.llbuilder, lhs, rhs, noname())
303         }
304     }
305
306     pub fn urem(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
307         self.count_insn("urem");
308         unsafe {
309             llvm::LLVMBuildURem(self.llbuilder, lhs, rhs, noname())
310         }
311     }
312
313     pub fn srem(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
314         self.count_insn("srem");
315         unsafe {
316             llvm::LLVMBuildSRem(self.llbuilder, lhs, rhs, noname())
317         }
318     }
319
320     pub fn frem(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
321         self.count_insn("frem");
322         unsafe {
323             llvm::LLVMBuildFRem(self.llbuilder, lhs, rhs, noname())
324         }
325     }
326
327     pub fn shl(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
328         self.count_insn("shl");
329         unsafe {
330             llvm::LLVMBuildShl(self.llbuilder, lhs, rhs, noname())
331         }
332     }
333
334     pub fn lshr(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
335         self.count_insn("lshr");
336         unsafe {
337             llvm::LLVMBuildLShr(self.llbuilder, lhs, rhs, noname())
338         }
339     }
340
341     pub fn ashr(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
342         self.count_insn("ashr");
343         unsafe {
344             llvm::LLVMBuildAShr(self.llbuilder, lhs, rhs, noname())
345         }
346     }
347
348     pub fn and(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
349         self.count_insn("and");
350         unsafe {
351             llvm::LLVMBuildAnd(self.llbuilder, lhs, rhs, noname())
352         }
353     }
354
355     pub fn or(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
356         self.count_insn("or");
357         unsafe {
358             llvm::LLVMBuildOr(self.llbuilder, lhs, rhs, noname())
359         }
360     }
361
362     pub fn xor(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
363         self.count_insn("xor");
364         unsafe {
365             llvm::LLVMBuildXor(self.llbuilder, lhs, rhs, noname())
366         }
367     }
368
369     pub fn binop(&self, op: Opcode, lhs: ValueRef, rhs: ValueRef)
370               -> ValueRef {
371         self.count_insn("binop");
372         unsafe {
373             llvm::LLVMBuildBinOp(self.llbuilder, op, lhs, rhs, noname())
374         }
375     }
376
377     pub fn neg(&self, v: ValueRef) -> ValueRef {
378         self.count_insn("neg");
379         unsafe {
380             llvm::LLVMBuildNeg(self.llbuilder, v, noname())
381         }
382     }
383
384     pub fn nswneg(&self, v: ValueRef) -> ValueRef {
385         self.count_insn("nswneg");
386         unsafe {
387             llvm::LLVMBuildNSWNeg(self.llbuilder, v, noname())
388         }
389     }
390
391     pub fn nuwneg(&self, v: ValueRef) -> ValueRef {
392         self.count_insn("nuwneg");
393         unsafe {
394             llvm::LLVMBuildNUWNeg(self.llbuilder, v, noname())
395         }
396     }
397     pub fn fneg(&self, v: ValueRef) -> ValueRef {
398         self.count_insn("fneg");
399         unsafe {
400             llvm::LLVMBuildFNeg(self.llbuilder, v, noname())
401         }
402     }
403
404     pub fn not(&self, v: ValueRef) -> ValueRef {
405         self.count_insn("not");
406         unsafe {
407             llvm::LLVMBuildNot(self.llbuilder, v, noname())
408         }
409     }
410
411     /* Memory */
412     pub fn malloc(&self, ty: Type) -> ValueRef {
413         self.count_insn("malloc");
414         unsafe {
415             llvm::LLVMBuildMalloc(self.llbuilder, ty.to_ref(), noname())
416         }
417     }
418
419     pub fn array_malloc(&self, ty: Type, val: ValueRef) -> ValueRef {
420         self.count_insn("arraymalloc");
421         unsafe {
422             llvm::LLVMBuildArrayMalloc(self.llbuilder, ty.to_ref(), val, noname())
423         }
424     }
425
426     pub fn alloca(&self, ty: Type, name: &str) -> ValueRef {
427         self.count_insn("alloca");
428         unsafe {
429             if name.is_empty() {
430                 llvm::LLVMBuildAlloca(self.llbuilder, ty.to_ref(), noname())
431             } else {
432                 name.with_c_str(|c| {
433                     llvm::LLVMBuildAlloca(self.llbuilder, ty.to_ref(), c)
434                 })
435             }
436         }
437     }
438
439     pub fn array_alloca(&self, ty: Type, val: ValueRef) -> ValueRef {
440         self.count_insn("arrayalloca");
441         unsafe {
442             llvm::LLVMBuildArrayAlloca(self.llbuilder, ty.to_ref(), val, noname())
443         }
444     }
445
446     pub fn free(&self, ptr: ValueRef) {
447         self.count_insn("free");
448         unsafe {
449             llvm::LLVMBuildFree(self.llbuilder, ptr);
450         }
451     }
452
453     pub fn load(&self, ptr: ValueRef) -> ValueRef {
454         self.count_insn("load");
455         unsafe {
456             llvm::LLVMBuildLoad(self.llbuilder, ptr, noname())
457         }
458     }
459
460     pub fn volatile_load(&self, ptr: ValueRef) -> ValueRef {
461         self.count_insn("load.volatile");
462         unsafe {
463             let insn = llvm::LLVMBuildLoad(self.llbuilder, ptr, noname());
464             llvm::LLVMSetVolatile(insn, llvm::True);
465             insn
466         }
467     }
468
469     pub fn atomic_load(&self, ptr: ValueRef, order: AtomicOrdering) -> ValueRef {
470         self.count_insn("load.atomic");
471         unsafe {
472             let ty = Type::from_ref(llvm::LLVMTypeOf(ptr));
473             let align = llalign_of_pref(self.ccx, ty.element_type());
474             llvm::LLVMBuildAtomicLoad(self.llbuilder, ptr, noname(), order,
475                                       align as c_uint)
476         }
477     }
478
479
480     pub fn load_range_assert(&self, ptr: ValueRef, lo: c_ulonglong,
481                            hi: c_ulonglong, signed: llvm::Bool) -> ValueRef {
482         let value = self.load(ptr);
483
484         unsafe {
485             let t = llvm::LLVMGetElementType(llvm::LLVMTypeOf(ptr));
486             let min = llvm::LLVMConstInt(t, lo, signed);
487             let max = llvm::LLVMConstInt(t, hi, signed);
488
489             let v = [min, max];
490
491             llvm::LLVMSetMetadata(value, llvm::MD_range as c_uint,
492                                   llvm::LLVMMDNodeInContext(self.ccx.llcx(),
493                                                             v.as_ptr(), v.len() as c_uint));
494         }
495
496         value
497     }
498
499     pub fn store(&self, val: ValueRef, ptr: ValueRef) {
500         debug!("Store {} -> {}",
501                self.ccx.tn().val_to_string(val),
502                self.ccx.tn().val_to_string(ptr));
503         assert!(self.llbuilder.is_not_null());
504         self.count_insn("store");
505         unsafe {
506             llvm::LLVMBuildStore(self.llbuilder, val, ptr);
507         }
508     }
509
510     pub fn volatile_store(&self, val: ValueRef, ptr: ValueRef) {
511         debug!("Store {} -> {}",
512                self.ccx.tn().val_to_string(val),
513                self.ccx.tn().val_to_string(ptr));
514         assert!(self.llbuilder.is_not_null());
515         self.count_insn("store.volatile");
516         unsafe {
517             let insn = llvm::LLVMBuildStore(self.llbuilder, val, ptr);
518             llvm::LLVMSetVolatile(insn, llvm::True);
519         }
520     }
521
522     pub fn atomic_store(&self, val: ValueRef, ptr: ValueRef, order: AtomicOrdering) {
523         debug!("Store {} -> {}",
524                self.ccx.tn().val_to_string(val),
525                self.ccx.tn().val_to_string(ptr));
526         self.count_insn("store.atomic");
527         unsafe {
528             let ty = Type::from_ref(llvm::LLVMTypeOf(ptr));
529             let align = llalign_of_pref(self.ccx, ty.element_type());
530             llvm::LLVMBuildAtomicStore(self.llbuilder, val, ptr, order, align as c_uint);
531         }
532     }
533
534     pub fn gep(&self, ptr: ValueRef, indices: &[ValueRef]) -> ValueRef {
535         self.count_insn("gep");
536         unsafe {
537             llvm::LLVMBuildGEP(self.llbuilder, ptr, indices.as_ptr(),
538                                indices.len() as c_uint, noname())
539         }
540     }
541
542     // Simple wrapper around GEP that takes an array of ints and wraps them
543     // in C_i32()
544     #[inline]
545     pub fn gepi(&self, base: ValueRef, ixs: &[uint]) -> ValueRef {
546         // Small vector optimization. This should catch 100% of the cases that
547         // we care about.
548         if ixs.len() < 16 {
549             let mut small_vec = [ C_i32(self.ccx, 0), ..16 ];
550             for (small_vec_e, &ix) in small_vec.iter_mut().zip(ixs.iter()) {
551                 *small_vec_e = C_i32(self.ccx, ix as i32);
552             }
553             self.inbounds_gep(base, small_vec.slice(0, ixs.len()))
554         } else {
555             let v = ixs.iter().map(|i| C_i32(self.ccx, *i as i32)).collect::<Vec<ValueRef>>();
556             self.count_insn("gepi");
557             self.inbounds_gep(base, v.as_slice())
558         }
559     }
560
561     pub fn inbounds_gep(&self, ptr: ValueRef, indices: &[ValueRef]) -> ValueRef {
562         self.count_insn("inboundsgep");
563         unsafe {
564             llvm::LLVMBuildInBoundsGEP(
565                 self.llbuilder, ptr, indices.as_ptr(), indices.len() as c_uint, noname())
566         }
567     }
568
569     pub fn struct_gep(&self, ptr: ValueRef, idx: uint) -> ValueRef {
570         self.count_insn("structgep");
571         unsafe {
572             llvm::LLVMBuildStructGEP(self.llbuilder, ptr, idx as c_uint, noname())
573         }
574     }
575
576     pub fn global_string(&self, _str: *const c_char) -> ValueRef {
577         self.count_insn("globalstring");
578         unsafe {
579             llvm::LLVMBuildGlobalString(self.llbuilder, _str, noname())
580         }
581     }
582
583     pub fn global_string_ptr(&self, _str: *const c_char) -> ValueRef {
584         self.count_insn("globalstringptr");
585         unsafe {
586             llvm::LLVMBuildGlobalStringPtr(self.llbuilder, _str, noname())
587         }
588     }
589
590     /* Casts */
591     pub fn trunc(&self, val: ValueRef, dest_ty: Type) -> ValueRef {
592         self.count_insn("trunc");
593         unsafe {
594             llvm::LLVMBuildTrunc(self.llbuilder, val, dest_ty.to_ref(), noname())
595         }
596     }
597
598     pub fn zext(&self, val: ValueRef, dest_ty: Type) -> ValueRef {
599         self.count_insn("zext");
600         unsafe {
601             llvm::LLVMBuildZExt(self.llbuilder, val, dest_ty.to_ref(), noname())
602         }
603     }
604
605     pub fn sext(&self, val: ValueRef, dest_ty: Type) -> ValueRef {
606         self.count_insn("sext");
607         unsafe {
608             llvm::LLVMBuildSExt(self.llbuilder, val, dest_ty.to_ref(), noname())
609         }
610     }
611
612     pub fn fptoui(&self, val: ValueRef, dest_ty: Type) -> ValueRef {
613         self.count_insn("fptoui");
614         unsafe {
615             llvm::LLVMBuildFPToUI(self.llbuilder, val, dest_ty.to_ref(), noname())
616         }
617     }
618
619     pub fn fptosi(&self, val: ValueRef, dest_ty: Type) -> ValueRef {
620         self.count_insn("fptosi");
621         unsafe {
622             llvm::LLVMBuildFPToSI(self.llbuilder, val, dest_ty.to_ref(),noname())
623         }
624     }
625
626     pub fn uitofp(&self, val: ValueRef, dest_ty: Type) -> ValueRef {
627         self.count_insn("uitofp");
628         unsafe {
629             llvm::LLVMBuildUIToFP(self.llbuilder, val, dest_ty.to_ref(), noname())
630         }
631     }
632
633     pub fn sitofp(&self, val: ValueRef, dest_ty: Type) -> ValueRef {
634         self.count_insn("sitofp");
635         unsafe {
636             llvm::LLVMBuildSIToFP(self.llbuilder, val, dest_ty.to_ref(), noname())
637         }
638     }
639
640     pub fn fptrunc(&self, val: ValueRef, dest_ty: Type) -> ValueRef {
641         self.count_insn("fptrunc");
642         unsafe {
643             llvm::LLVMBuildFPTrunc(self.llbuilder, val, dest_ty.to_ref(), noname())
644         }
645     }
646
647     pub fn fpext(&self, val: ValueRef, dest_ty: Type) -> ValueRef {
648         self.count_insn("fpext");
649         unsafe {
650             llvm::LLVMBuildFPExt(self.llbuilder, val, dest_ty.to_ref(), noname())
651         }
652     }
653
654     pub fn ptrtoint(&self, val: ValueRef, dest_ty: Type) -> ValueRef {
655         self.count_insn("ptrtoint");
656         unsafe {
657             llvm::LLVMBuildPtrToInt(self.llbuilder, val, dest_ty.to_ref(), noname())
658         }
659     }
660
661     pub fn inttoptr(&self, val: ValueRef, dest_ty: Type) -> ValueRef {
662         self.count_insn("inttoptr");
663         unsafe {
664             llvm::LLVMBuildIntToPtr(self.llbuilder, val, dest_ty.to_ref(), noname())
665         }
666     }
667
668     pub fn bitcast(&self, val: ValueRef, dest_ty: Type) -> ValueRef {
669         self.count_insn("bitcast");
670         unsafe {
671             llvm::LLVMBuildBitCast(self.llbuilder, val, dest_ty.to_ref(), noname())
672         }
673     }
674
675     pub fn zext_or_bitcast(&self, val: ValueRef, dest_ty: Type) -> ValueRef {
676         self.count_insn("zextorbitcast");
677         unsafe {
678             llvm::LLVMBuildZExtOrBitCast(self.llbuilder, val, dest_ty.to_ref(), noname())
679         }
680     }
681
682     pub fn sext_or_bitcast(&self, val: ValueRef, dest_ty: Type) -> ValueRef {
683         self.count_insn("sextorbitcast");
684         unsafe {
685             llvm::LLVMBuildSExtOrBitCast(self.llbuilder, val, dest_ty.to_ref(), noname())
686         }
687     }
688
689     pub fn trunc_or_bitcast(&self, val: ValueRef, dest_ty: Type) -> ValueRef {
690         self.count_insn("truncorbitcast");
691         unsafe {
692             llvm::LLVMBuildTruncOrBitCast(self.llbuilder, val, dest_ty.to_ref(), noname())
693         }
694     }
695
696     pub fn cast(&self, op: Opcode, val: ValueRef, dest_ty: Type) -> ValueRef {
697         self.count_insn("cast");
698         unsafe {
699             llvm::LLVMBuildCast(self.llbuilder, op, val, dest_ty.to_ref(), noname())
700         }
701     }
702
703     pub fn pointercast(&self, val: ValueRef, dest_ty: Type) -> ValueRef {
704         self.count_insn("pointercast");
705         unsafe {
706             llvm::LLVMBuildPointerCast(self.llbuilder, val, dest_ty.to_ref(), noname())
707         }
708     }
709
710     pub fn intcast(&self, val: ValueRef, dest_ty: Type) -> ValueRef {
711         self.count_insn("intcast");
712         unsafe {
713             llvm::LLVMBuildIntCast(self.llbuilder, val, dest_ty.to_ref(), noname())
714         }
715     }
716
717     pub fn fpcast(&self, val: ValueRef, dest_ty: Type) -> ValueRef {
718         self.count_insn("fpcast");
719         unsafe {
720             llvm::LLVMBuildFPCast(self.llbuilder, val, dest_ty.to_ref(), noname())
721         }
722     }
723
724
725     /* Comparisons */
726     pub fn icmp(&self, op: IntPredicate, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
727         self.count_insn("icmp");
728         unsafe {
729             llvm::LLVMBuildICmp(self.llbuilder, op as c_uint, lhs, rhs, noname())
730         }
731     }
732
733     pub fn fcmp(&self, op: RealPredicate, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
734         self.count_insn("fcmp");
735         unsafe {
736             llvm::LLVMBuildFCmp(self.llbuilder, op as c_uint, lhs, rhs, noname())
737         }
738     }
739
740     /* Miscellaneous instructions */
741     pub fn empty_phi(&self, ty: Type) -> ValueRef {
742         self.count_insn("emptyphi");
743         unsafe {
744             llvm::LLVMBuildPhi(self.llbuilder, ty.to_ref(), noname())
745         }
746     }
747
748     pub fn phi(&self, ty: Type, vals: &[ValueRef], bbs: &[BasicBlockRef]) -> ValueRef {
749         assert_eq!(vals.len(), bbs.len());
750         let phi = self.empty_phi(ty);
751         self.count_insn("addincoming");
752         unsafe {
753             llvm::LLVMAddIncoming(phi, vals.as_ptr(),
754                                   bbs.as_ptr(),
755                                   vals.len() as c_uint);
756             phi
757         }
758     }
759
760     pub fn add_span_comment(&self, sp: Span, text: &str) {
761         if self.ccx.sess().asm_comments() {
762             let s = format!("{} ({})",
763                             text,
764                             self.ccx.sess().codemap().span_to_string(sp));
765             debug!("{}", s.as_slice());
766             self.add_comment(s.as_slice());
767         }
768     }
769
770     pub fn add_comment(&self, text: &str) {
771         if self.ccx.sess().asm_comments() {
772             let sanitized = text.replace("$", "");
773             let comment_text = format!("{} {}", "#",
774                                        sanitized.replace("\n", "\n\t# "));
775             self.count_insn("inlineasm");
776             let asm = comment_text.as_slice().with_c_str(|c| {
777                 unsafe {
778                     llvm::LLVMConstInlineAsm(Type::func([], &Type::void(self.ccx)).to_ref(),
779                                              c, noname(), False, False)
780                 }
781             });
782             self.call(asm, [], None);
783         }
784     }
785
786     pub fn inline_asm_call(&self, asm: *const c_char, cons: *const c_char,
787                          inputs: &[ValueRef], output: Type,
788                          volatile: bool, alignstack: bool,
789                          dia: AsmDialect) -> ValueRef {
790         self.count_insn("inlineasm");
791
792         let volatile = if volatile { llvm::True }
793                        else        { llvm::False };
794         let alignstack = if alignstack { llvm::True }
795                          else          { llvm::False };
796
797         let argtys = inputs.iter().map(|v| {
798             debug!("Asm Input Type: {:?}", self.ccx.tn().val_to_string(*v));
799             val_ty(*v)
800         }).collect::<Vec<_>>();
801
802         debug!("Asm Output Type: {:?}", self.ccx.tn().type_to_string(output));
803         let fty = Type::func(argtys.as_slice(), &output);
804         unsafe {
805             let v = llvm::LLVMInlineAsm(
806                 fty.to_ref(), asm, cons, volatile, alignstack, dia as c_uint);
807             self.call(v, inputs, None)
808         }
809     }
810
811     pub fn call(&self, llfn: ValueRef, args: &[ValueRef],
812                 attributes: Option<AttrBuilder>) -> ValueRef {
813         self.count_insn("call");
814
815         debug!("Call {} with args ({})",
816                self.ccx.tn().val_to_string(llfn),
817                args.iter()
818                    .map(|&v| self.ccx.tn().val_to_string(v))
819                    .collect::<Vec<String>>()
820                    .connect(", "));
821
822         unsafe {
823             let v = llvm::LLVMBuildCall(self.llbuilder, llfn, args.as_ptr(),
824                                         args.len() as c_uint, noname());
825             match attributes {
826                 Some(a) => a.apply_callsite(v),
827                 None => {}
828             }
829             v
830         }
831     }
832
833     pub fn call_with_conv(&self, llfn: ValueRef, args: &[ValueRef],
834                           conv: CallConv, attributes: Option<AttrBuilder>) -> ValueRef {
835         self.count_insn("callwithconv");
836         let v = self.call(llfn, args, attributes);
837         llvm::SetInstructionCallConv(v, conv);
838         v
839     }
840
841     pub fn select(&self, cond: ValueRef, then_val: ValueRef, else_val: ValueRef) -> ValueRef {
842         self.count_insn("select");
843         unsafe {
844             llvm::LLVMBuildSelect(self.llbuilder, cond, then_val, else_val, noname())
845         }
846     }
847
848     pub fn va_arg(&self, list: ValueRef, ty: Type) -> ValueRef {
849         self.count_insn("vaarg");
850         unsafe {
851             llvm::LLVMBuildVAArg(self.llbuilder, list, ty.to_ref(), noname())
852         }
853     }
854
855     pub fn extract_element(&self, vec: ValueRef, idx: ValueRef) -> ValueRef {
856         self.count_insn("extractelement");
857         unsafe {
858             llvm::LLVMBuildExtractElement(self.llbuilder, vec, idx, noname())
859         }
860     }
861
862     pub fn insert_element(&self, vec: ValueRef, elt: ValueRef, idx: ValueRef) -> ValueRef {
863         self.count_insn("insertelement");
864         unsafe {
865             llvm::LLVMBuildInsertElement(self.llbuilder, vec, elt, idx, noname())
866         }
867     }
868
869     pub fn shuffle_vector(&self, v1: ValueRef, v2: ValueRef, mask: ValueRef) -> ValueRef {
870         self.count_insn("shufflevector");
871         unsafe {
872             llvm::LLVMBuildShuffleVector(self.llbuilder, v1, v2, mask, noname())
873         }
874     }
875
876     pub fn vector_splat(&self, num_elts: uint, elt: ValueRef) -> ValueRef {
877         unsafe {
878             let elt_ty = val_ty(elt);
879             let undef = llvm::LLVMGetUndef(Type::vector(&elt_ty, num_elts as u64).to_ref());
880             let vec = self.insert_element(undef, elt, C_i32(self.ccx, 0));
881             let vec_i32_ty = Type::vector(&Type::i32(self.ccx), num_elts as u64);
882             self.shuffle_vector(vec, undef, C_null(vec_i32_ty))
883         }
884     }
885
886     pub fn extract_value(&self, agg_val: ValueRef, idx: uint) -> ValueRef {
887         self.count_insn("extractvalue");
888         unsafe {
889             llvm::LLVMBuildExtractValue(self.llbuilder, agg_val, idx as c_uint, noname())
890         }
891     }
892
893     pub fn insert_value(&self, agg_val: ValueRef, elt: ValueRef,
894                        idx: uint) -> ValueRef {
895         self.count_insn("insertvalue");
896         unsafe {
897             llvm::LLVMBuildInsertValue(self.llbuilder, agg_val, elt, idx as c_uint,
898                                        noname())
899         }
900     }
901
902     pub fn is_null(&self, val: ValueRef) -> ValueRef {
903         self.count_insn("isnull");
904         unsafe {
905             llvm::LLVMBuildIsNull(self.llbuilder, val, noname())
906         }
907     }
908
909     pub fn is_not_null(&self, val: ValueRef) -> ValueRef {
910         self.count_insn("isnotnull");
911         unsafe {
912             llvm::LLVMBuildIsNotNull(self.llbuilder, val, noname())
913         }
914     }
915
916     pub fn ptrdiff(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
917         self.count_insn("ptrdiff");
918         unsafe {
919             llvm::LLVMBuildPtrDiff(self.llbuilder, lhs, rhs, noname())
920         }
921     }
922
923     pub fn trap(&self) {
924         unsafe {
925             let bb: BasicBlockRef = llvm::LLVMGetInsertBlock(self.llbuilder);
926             let fn_: ValueRef = llvm::LLVMGetBasicBlockParent(bb);
927             let m: ModuleRef = llvm::LLVMGetGlobalParent(fn_);
928             let t: ValueRef = "llvm.trap".with_c_str(|buf| {
929                 llvm::LLVMGetNamedFunction(m, buf)
930             });
931             assert!((t as int != 0));
932             let args: &[ValueRef] = [];
933             self.count_insn("trap");
934             llvm::LLVMBuildCall(
935                 self.llbuilder, t, args.as_ptr(), args.len() as c_uint, noname());
936         }
937     }
938
939     pub fn landing_pad(&self, ty: Type, pers_fn: ValueRef, num_clauses: uint) -> ValueRef {
940         self.count_insn("landingpad");
941         unsafe {
942             llvm::LLVMBuildLandingPad(
943                 self.llbuilder, ty.to_ref(), pers_fn, num_clauses as c_uint, noname())
944         }
945     }
946
947     pub fn set_cleanup(&self, landing_pad: ValueRef) {
948         self.count_insn("setcleanup");
949         unsafe {
950             llvm::LLVMSetCleanup(landing_pad, llvm::True);
951         }
952     }
953
954     pub fn resume(&self, exn: ValueRef) -> ValueRef {
955         self.count_insn("resume");
956         unsafe {
957             llvm::LLVMBuildResume(self.llbuilder, exn)
958         }
959     }
960
961     // Atomic Operations
962     pub fn atomic_cmpxchg(&self, dst: ValueRef,
963                          cmp: ValueRef, src: ValueRef,
964                          order: AtomicOrdering,
965                          failure_order: AtomicOrdering) -> ValueRef {
966         unsafe {
967             llvm::LLVMBuildAtomicCmpXchg(self.llbuilder, dst, cmp, src,
968                                          order, failure_order)
969         }
970     }
971     pub fn atomic_rmw(&self, op: AtomicBinOp,
972                      dst: ValueRef, src: ValueRef,
973                      order: AtomicOrdering) -> ValueRef {
974         unsafe {
975             llvm::LLVMBuildAtomicRMW(self.llbuilder, op, dst, src, order, False)
976         }
977     }
978
979     pub fn atomic_fence(&self, order: AtomicOrdering) {
980         unsafe {
981             llvm::LLVMBuildAtomicFence(self.llbuilder, order);
982         }
983     }
984 }