]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_codegen_llvm/src/builder.rs
Move decision aboute noalias into codegen_llvm
[rust.git] / compiler / rustc_codegen_llvm / src / builder.rs
1 use crate::common::Funclet;
2 use crate::context::CodegenCx;
3 use crate::llvm::{self, BasicBlock, False};
4 use crate::llvm::{AtomicOrdering, AtomicRmwBinOp, SynchronizationScope};
5 use crate::type_::Type;
6 use crate::type_of::LayoutLlvmExt;
7 use crate::value::Value;
8 use cstr::cstr;
9 use libc::{c_char, c_uint};
10 use rustc_codegen_ssa::common::{IntPredicate, RealPredicate, TypeKind};
11 use rustc_codegen_ssa::mir::operand::{OperandRef, OperandValue};
12 use rustc_codegen_ssa::mir::place::PlaceRef;
13 use rustc_codegen_ssa::traits::*;
14 use rustc_codegen_ssa::MemFlags;
15 use rustc_data_structures::small_c_str::SmallCStr;
16 use rustc_hir::def_id::DefId;
17 use rustc_middle::ty::layout::TyAndLayout;
18 use rustc_middle::ty::{self, Ty, TyCtxt};
19 use rustc_span::{sym, Span};
20 use rustc_target::abi::{self, Align, Size};
21 use rustc_target::spec::{HasTargetSpec, Target};
22 use std::borrow::Cow;
23 use std::ffi::CStr;
24 use std::ops::{Deref, Range};
25 use std::ptr;
26 use tracing::debug;
27
28 // All Builders must have an llfn associated with them
29 #[must_use]
30 pub struct Builder<'a, 'll, 'tcx> {
31     pub llbuilder: &'ll mut llvm::Builder<'ll>,
32     pub cx: &'a CodegenCx<'ll, 'tcx>,
33 }
34
35 impl Drop for Builder<'a, 'll, 'tcx> {
36     fn drop(&mut self) {
37         unsafe {
38             llvm::LLVMDisposeBuilder(&mut *(self.llbuilder as *mut _));
39         }
40     }
41 }
42
43 // FIXME(eddyb) use a checked constructor when they become `const fn`.
44 const EMPTY_C_STR: &CStr = unsafe { CStr::from_bytes_with_nul_unchecked(b"\0") };
45
46 /// Empty string, to be used where LLVM expects an instruction name, indicating
47 /// that the instruction is to be left unnamed (i.e. numbered, in textual IR).
48 // FIXME(eddyb) pass `&CStr` directly to FFI once it's a thin pointer.
49 const UNNAMED: *const c_char = EMPTY_C_STR.as_ptr();
50
51 impl BackendTypes for Builder<'_, 'll, 'tcx> {
52     type Value = <CodegenCx<'ll, 'tcx> as BackendTypes>::Value;
53     type Function = <CodegenCx<'ll, 'tcx> as BackendTypes>::Function;
54     type BasicBlock = <CodegenCx<'ll, 'tcx> as BackendTypes>::BasicBlock;
55     type Type = <CodegenCx<'ll, 'tcx> as BackendTypes>::Type;
56     type Funclet = <CodegenCx<'ll, 'tcx> as BackendTypes>::Funclet;
57
58     type DIScope = <CodegenCx<'ll, 'tcx> as BackendTypes>::DIScope;
59     type DILocation = <CodegenCx<'ll, 'tcx> as BackendTypes>::DILocation;
60     type DIVariable = <CodegenCx<'ll, 'tcx> as BackendTypes>::DIVariable;
61 }
62
63 impl abi::HasDataLayout for Builder<'_, '_, '_> {
64     fn data_layout(&self) -> &abi::TargetDataLayout {
65         self.cx.data_layout()
66     }
67 }
68
69 impl ty::layout::HasTyCtxt<'tcx> for Builder<'_, '_, 'tcx> {
70     fn tcx(&self) -> TyCtxt<'tcx> {
71         self.cx.tcx
72     }
73 }
74
75 impl ty::layout::HasParamEnv<'tcx> for Builder<'_, '_, 'tcx> {
76     fn param_env(&self) -> ty::ParamEnv<'tcx> {
77         self.cx.param_env()
78     }
79 }
80
81 impl HasTargetSpec for Builder<'_, '_, 'tcx> {
82     fn target_spec(&self) -> &Target {
83         &self.cx.target_spec()
84     }
85 }
86
87 impl abi::LayoutOf for Builder<'_, '_, 'tcx> {
88     type Ty = Ty<'tcx>;
89     type TyAndLayout = TyAndLayout<'tcx>;
90
91     fn layout_of(&self, ty: Ty<'tcx>) -> Self::TyAndLayout {
92         self.cx.layout_of(ty)
93     }
94 }
95
96 impl Deref for Builder<'_, 'll, 'tcx> {
97     type Target = CodegenCx<'ll, 'tcx>;
98
99     fn deref(&self) -> &Self::Target {
100         self.cx
101     }
102 }
103
104 impl HasCodegen<'tcx> for Builder<'_, 'll, 'tcx> {
105     type CodegenCx = CodegenCx<'ll, 'tcx>;
106 }
107
108 macro_rules! builder_methods_for_value_instructions {
109     ($($name:ident($($arg:ident),*) => $llvm_capi:ident),+ $(,)?) => {
110         $(fn $name(&mut self, $($arg: &'ll Value),*) -> &'ll Value {
111             unsafe {
112                 llvm::$llvm_capi(self.llbuilder, $($arg,)* UNNAMED)
113             }
114         })+
115     }
116 }
117
118 impl BuilderMethods<'a, 'tcx> for Builder<'a, 'll, 'tcx> {
119     fn new_block<'b>(cx: &'a CodegenCx<'ll, 'tcx>, llfn: &'ll Value, name: &'b str) -> Self {
120         let mut bx = Builder::with_cx(cx);
121         let llbb = unsafe {
122             let name = SmallCStr::new(name);
123             llvm::LLVMAppendBasicBlockInContext(cx.llcx, llfn, name.as_ptr())
124         };
125         bx.position_at_end(llbb);
126         bx
127     }
128
129     fn with_cx(cx: &'a CodegenCx<'ll, 'tcx>) -> Self {
130         // Create a fresh builder from the crate context.
131         let llbuilder = unsafe { llvm::LLVMCreateBuilderInContext(cx.llcx) };
132         Builder { llbuilder, cx }
133     }
134
135     fn build_sibling_block(&self, name: &str) -> Self {
136         Builder::new_block(self.cx, self.llfn(), name)
137     }
138
139     fn llbb(&self) -> &'ll BasicBlock {
140         unsafe { llvm::LLVMGetInsertBlock(self.llbuilder) }
141     }
142
143     fn set_span(&mut self, _span: Span) {}
144
145     fn position_at_end(&mut self, llbb: &'ll BasicBlock) {
146         unsafe {
147             llvm::LLVMPositionBuilderAtEnd(self.llbuilder, llbb);
148         }
149     }
150
151     fn ret_void(&mut self) {
152         unsafe {
153             llvm::LLVMBuildRetVoid(self.llbuilder);
154         }
155     }
156
157     fn ret(&mut self, v: &'ll Value) {
158         unsafe {
159             llvm::LLVMBuildRet(self.llbuilder, v);
160         }
161     }
162
163     fn br(&mut self, dest: &'ll BasicBlock) {
164         unsafe {
165             llvm::LLVMBuildBr(self.llbuilder, dest);
166         }
167     }
168
169     fn cond_br(
170         &mut self,
171         cond: &'ll Value,
172         then_llbb: &'ll BasicBlock,
173         else_llbb: &'ll BasicBlock,
174     ) {
175         unsafe {
176             llvm::LLVMBuildCondBr(self.llbuilder, cond, then_llbb, else_llbb);
177         }
178     }
179
180     fn switch(
181         &mut self,
182         v: &'ll Value,
183         else_llbb: &'ll BasicBlock,
184         cases: impl ExactSizeIterator<Item = (u128, &'ll BasicBlock)>,
185     ) {
186         let switch =
187             unsafe { llvm::LLVMBuildSwitch(self.llbuilder, v, else_llbb, cases.len() as c_uint) };
188         for (on_val, dest) in cases {
189             let on_val = self.const_uint_big(self.val_ty(v), on_val);
190             unsafe { llvm::LLVMAddCase(switch, on_val, dest) }
191         }
192     }
193
194     fn invoke(
195         &mut self,
196         llfn: &'ll Value,
197         args: &[&'ll Value],
198         then: &'ll BasicBlock,
199         catch: &'ll BasicBlock,
200         funclet: Option<&Funclet<'ll>>,
201     ) -> &'ll Value {
202         debug!("invoke {:?} with args ({:?})", llfn, args);
203
204         let args = self.check_call("invoke", llfn, args);
205         let bundle = funclet.map(|funclet| funclet.bundle());
206         let bundle = bundle.as_ref().map(|b| &*b.raw);
207
208         unsafe {
209             llvm::LLVMRustBuildInvoke(
210                 self.llbuilder,
211                 llfn,
212                 args.as_ptr(),
213                 args.len() as c_uint,
214                 then,
215                 catch,
216                 bundle,
217                 UNNAMED,
218             )
219         }
220     }
221
222     fn unreachable(&mut self) {
223         unsafe {
224             llvm::LLVMBuildUnreachable(self.llbuilder);
225         }
226     }
227
228     builder_methods_for_value_instructions! {
229         add(a, b) => LLVMBuildAdd,
230         fadd(a, b) => LLVMBuildFAdd,
231         sub(a, b) => LLVMBuildSub,
232         fsub(a, b) => LLVMBuildFSub,
233         mul(a, b) => LLVMBuildMul,
234         fmul(a, b) => LLVMBuildFMul,
235         udiv(a, b) => LLVMBuildUDiv,
236         exactudiv(a, b) => LLVMBuildExactUDiv,
237         sdiv(a, b) => LLVMBuildSDiv,
238         exactsdiv(a, b) => LLVMBuildExactSDiv,
239         fdiv(a, b) => LLVMBuildFDiv,
240         urem(a, b) => LLVMBuildURem,
241         srem(a, b) => LLVMBuildSRem,
242         frem(a, b) => LLVMBuildFRem,
243         shl(a, b) => LLVMBuildShl,
244         lshr(a, b) => LLVMBuildLShr,
245         ashr(a, b) => LLVMBuildAShr,
246         and(a, b) => LLVMBuildAnd,
247         or(a, b) => LLVMBuildOr,
248         xor(a, b) => LLVMBuildXor,
249         neg(x) => LLVMBuildNeg,
250         fneg(x) => LLVMBuildFNeg,
251         not(x) => LLVMBuildNot,
252         unchecked_sadd(x, y) => LLVMBuildNSWAdd,
253         unchecked_uadd(x, y) => LLVMBuildNUWAdd,
254         unchecked_ssub(x, y) => LLVMBuildNSWSub,
255         unchecked_usub(x, y) => LLVMBuildNUWSub,
256         unchecked_smul(x, y) => LLVMBuildNSWMul,
257         unchecked_umul(x, y) => LLVMBuildNUWMul,
258     }
259
260     fn fadd_fast(&mut self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
261         unsafe {
262             let instr = llvm::LLVMBuildFAdd(self.llbuilder, lhs, rhs, UNNAMED);
263             llvm::LLVMRustSetHasUnsafeAlgebra(instr);
264             instr
265         }
266     }
267
268     fn fsub_fast(&mut self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
269         unsafe {
270             let instr = llvm::LLVMBuildFSub(self.llbuilder, lhs, rhs, UNNAMED);
271             llvm::LLVMRustSetHasUnsafeAlgebra(instr);
272             instr
273         }
274     }
275
276     fn fmul_fast(&mut self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
277         unsafe {
278             let instr = llvm::LLVMBuildFMul(self.llbuilder, lhs, rhs, UNNAMED);
279             llvm::LLVMRustSetHasUnsafeAlgebra(instr);
280             instr
281         }
282     }
283
284     fn fdiv_fast(&mut self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
285         unsafe {
286             let instr = llvm::LLVMBuildFDiv(self.llbuilder, lhs, rhs, UNNAMED);
287             llvm::LLVMRustSetHasUnsafeAlgebra(instr);
288             instr
289         }
290     }
291
292     fn frem_fast(&mut self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
293         unsafe {
294             let instr = llvm::LLVMBuildFRem(self.llbuilder, lhs, rhs, UNNAMED);
295             llvm::LLVMRustSetHasUnsafeAlgebra(instr);
296             instr
297         }
298     }
299
300     fn checked_binop(
301         &mut self,
302         oop: OverflowOp,
303         ty: Ty<'_>,
304         lhs: Self::Value,
305         rhs: Self::Value,
306     ) -> (Self::Value, Self::Value) {
307         use rustc_middle::ty::{Int, Uint};
308         use rustc_middle::ty::{IntTy::*, UintTy::*};
309
310         let new_kind = match ty.kind() {
311             Int(t @ Isize) => Int(t.normalize(self.tcx.sess.target.pointer_width)),
312             Uint(t @ Usize) => Uint(t.normalize(self.tcx.sess.target.pointer_width)),
313             t @ (Uint(_) | Int(_)) => t.clone(),
314             _ => panic!("tried to get overflow intrinsic for op applied to non-int type"),
315         };
316
317         let name = match oop {
318             OverflowOp::Add => match new_kind {
319                 Int(I8) => "llvm.sadd.with.overflow.i8",
320                 Int(I16) => "llvm.sadd.with.overflow.i16",
321                 Int(I32) => "llvm.sadd.with.overflow.i32",
322                 Int(I64) => "llvm.sadd.with.overflow.i64",
323                 Int(I128) => "llvm.sadd.with.overflow.i128",
324
325                 Uint(U8) => "llvm.uadd.with.overflow.i8",
326                 Uint(U16) => "llvm.uadd.with.overflow.i16",
327                 Uint(U32) => "llvm.uadd.with.overflow.i32",
328                 Uint(U64) => "llvm.uadd.with.overflow.i64",
329                 Uint(U128) => "llvm.uadd.with.overflow.i128",
330
331                 _ => unreachable!(),
332             },
333             OverflowOp::Sub => match new_kind {
334                 Int(I8) => "llvm.ssub.with.overflow.i8",
335                 Int(I16) => "llvm.ssub.with.overflow.i16",
336                 Int(I32) => "llvm.ssub.with.overflow.i32",
337                 Int(I64) => "llvm.ssub.with.overflow.i64",
338                 Int(I128) => "llvm.ssub.with.overflow.i128",
339
340                 Uint(U8) => "llvm.usub.with.overflow.i8",
341                 Uint(U16) => "llvm.usub.with.overflow.i16",
342                 Uint(U32) => "llvm.usub.with.overflow.i32",
343                 Uint(U64) => "llvm.usub.with.overflow.i64",
344                 Uint(U128) => "llvm.usub.with.overflow.i128",
345
346                 _ => unreachable!(),
347             },
348             OverflowOp::Mul => match new_kind {
349                 Int(I8) => "llvm.smul.with.overflow.i8",
350                 Int(I16) => "llvm.smul.with.overflow.i16",
351                 Int(I32) => "llvm.smul.with.overflow.i32",
352                 Int(I64) => "llvm.smul.with.overflow.i64",
353                 Int(I128) => "llvm.smul.with.overflow.i128",
354
355                 Uint(U8) => "llvm.umul.with.overflow.i8",
356                 Uint(U16) => "llvm.umul.with.overflow.i16",
357                 Uint(U32) => "llvm.umul.with.overflow.i32",
358                 Uint(U64) => "llvm.umul.with.overflow.i64",
359                 Uint(U128) => "llvm.umul.with.overflow.i128",
360
361                 _ => unreachable!(),
362             },
363         };
364
365         let intrinsic = self.get_intrinsic(&name);
366         let res = self.call(intrinsic, &[lhs, rhs], None);
367         (self.extract_value(res, 0), self.extract_value(res, 1))
368     }
369
370     fn from_immediate(&mut self, val: Self::Value) -> Self::Value {
371         if self.cx().val_ty(val) == self.cx().type_i1() {
372             self.zext(val, self.cx().type_i8())
373         } else {
374             val
375         }
376     }
377     fn to_immediate_scalar(&mut self, val: Self::Value, scalar: &abi::Scalar) -> Self::Value {
378         if scalar.is_bool() {
379             return self.trunc(val, self.cx().type_i1());
380         }
381         val
382     }
383
384     fn alloca(&mut self, ty: &'ll Type, align: Align) -> &'ll Value {
385         let mut bx = Builder::with_cx(self.cx);
386         bx.position_at_start(unsafe { llvm::LLVMGetFirstBasicBlock(self.llfn()) });
387         bx.dynamic_alloca(ty, align)
388     }
389
390     fn dynamic_alloca(&mut self, ty: &'ll Type, align: Align) -> &'ll Value {
391         unsafe {
392             let alloca = llvm::LLVMBuildAlloca(self.llbuilder, ty, UNNAMED);
393             llvm::LLVMSetAlignment(alloca, align.bytes() as c_uint);
394             alloca
395         }
396     }
397
398     fn array_alloca(&mut self, ty: &'ll Type, len: &'ll Value, align: Align) -> &'ll Value {
399         unsafe {
400             let alloca = llvm::LLVMBuildArrayAlloca(self.llbuilder, ty, len, UNNAMED);
401             llvm::LLVMSetAlignment(alloca, align.bytes() as c_uint);
402             alloca
403         }
404     }
405
406     fn load(&mut self, ptr: &'ll Value, align: Align) -> &'ll Value {
407         unsafe {
408             let load = llvm::LLVMBuildLoad(self.llbuilder, ptr, UNNAMED);
409             llvm::LLVMSetAlignment(load, align.bytes() as c_uint);
410             load
411         }
412     }
413
414     fn volatile_load(&mut self, ptr: &'ll Value) -> &'ll Value {
415         unsafe {
416             let load = llvm::LLVMBuildLoad(self.llbuilder, ptr, UNNAMED);
417             llvm::LLVMSetVolatile(load, llvm::True);
418             load
419         }
420     }
421
422     fn atomic_load(
423         &mut self,
424         ptr: &'ll Value,
425         order: rustc_codegen_ssa::common::AtomicOrdering,
426         size: Size,
427     ) -> &'ll Value {
428         unsafe {
429             let load = llvm::LLVMRustBuildAtomicLoad(
430                 self.llbuilder,
431                 ptr,
432                 UNNAMED,
433                 AtomicOrdering::from_generic(order),
434             );
435             // LLVM requires the alignment of atomic loads to be at least the size of the type.
436             llvm::LLVMSetAlignment(load, size.bytes() as c_uint);
437             load
438         }
439     }
440
441     fn load_operand(&mut self, place: PlaceRef<'tcx, &'ll Value>) -> OperandRef<'tcx, &'ll Value> {
442         debug!("PlaceRef::load: {:?}", place);
443
444         assert_eq!(place.llextra.is_some(), place.layout.is_unsized());
445
446         if place.layout.is_zst() {
447             return OperandRef::new_zst(self, place.layout);
448         }
449
450         fn scalar_load_metadata<'a, 'll, 'tcx>(
451             bx: &mut Builder<'a, 'll, 'tcx>,
452             load: &'ll Value,
453             scalar: &abi::Scalar,
454         ) {
455             let vr = scalar.valid_range.clone();
456             match scalar.value {
457                 abi::Int(..) => {
458                     let range = scalar.valid_range_exclusive(bx);
459                     if range.start != range.end {
460                         bx.range_metadata(load, range);
461                     }
462                 }
463                 abi::Pointer if vr.start() < vr.end() && !vr.contains(&0) => {
464                     bx.nonnull_metadata(load);
465                 }
466                 _ => {}
467             }
468         }
469
470         let val = if let Some(llextra) = place.llextra {
471             OperandValue::Ref(place.llval, Some(llextra), place.align)
472         } else if place.layout.is_llvm_immediate() {
473             let mut const_llval = None;
474             unsafe {
475                 if let Some(global) = llvm::LLVMIsAGlobalVariable(place.llval) {
476                     if llvm::LLVMIsGlobalConstant(global) == llvm::True {
477                         const_llval = llvm::LLVMGetInitializer(global);
478                     }
479                 }
480             }
481             let llval = const_llval.unwrap_or_else(|| {
482                 let load = self.load(place.llval, place.align);
483                 if let abi::Abi::Scalar(ref scalar) = place.layout.abi {
484                     scalar_load_metadata(self, load, scalar);
485                 }
486                 load
487             });
488             OperandValue::Immediate(self.to_immediate(llval, place.layout))
489         } else if let abi::Abi::ScalarPair(ref a, ref b) = place.layout.abi {
490             let b_offset = a.value.size(self).align_to(b.value.align(self).abi);
491
492             let mut load = |i, scalar: &abi::Scalar, align| {
493                 let llptr = self.struct_gep(place.llval, i as u64);
494                 let load = self.load(llptr, align);
495                 scalar_load_metadata(self, load, scalar);
496                 self.to_immediate_scalar(load, scalar)
497             };
498
499             OperandValue::Pair(
500                 load(0, a, place.align),
501                 load(1, b, place.align.restrict_for_offset(b_offset)),
502             )
503         } else {
504             OperandValue::Ref(place.llval, None, place.align)
505         };
506
507         OperandRef { val, layout: place.layout }
508     }
509
510     fn write_operand_repeatedly(
511         mut self,
512         cg_elem: OperandRef<'tcx, &'ll Value>,
513         count: u64,
514         dest: PlaceRef<'tcx, &'ll Value>,
515     ) -> Self {
516         let zero = self.const_usize(0);
517         let count = self.const_usize(count);
518         let start = dest.project_index(&mut self, zero).llval;
519         let end = dest.project_index(&mut self, count).llval;
520
521         let mut header_bx = self.build_sibling_block("repeat_loop_header");
522         let mut body_bx = self.build_sibling_block("repeat_loop_body");
523         let next_bx = self.build_sibling_block("repeat_loop_next");
524
525         self.br(header_bx.llbb());
526         let current = header_bx.phi(self.val_ty(start), &[start], &[self.llbb()]);
527
528         let keep_going = header_bx.icmp(IntPredicate::IntNE, current, end);
529         header_bx.cond_br(keep_going, body_bx.llbb(), next_bx.llbb());
530
531         let align = dest.align.restrict_for_offset(dest.layout.field(self.cx(), 0).size);
532         cg_elem
533             .val
534             .store(&mut body_bx, PlaceRef::new_sized_aligned(current, cg_elem.layout, align));
535
536         let next = body_bx.inbounds_gep(current, &[self.const_usize(1)]);
537         body_bx.br(header_bx.llbb());
538         header_bx.add_incoming_to_phi(current, next, body_bx.llbb());
539
540         next_bx
541     }
542
543     fn range_metadata(&mut self, load: &'ll Value, range: Range<u128>) {
544         if self.sess().target.arch == "amdgpu" {
545             // amdgpu/LLVM does something weird and thinks a i64 value is
546             // split into a v2i32, halving the bitwidth LLVM expects,
547             // tripping an assertion. So, for now, just disable this
548             // optimization.
549             return;
550         }
551
552         unsafe {
553             let llty = self.cx.val_ty(load);
554             let v = [
555                 self.cx.const_uint_big(llty, range.start),
556                 self.cx.const_uint_big(llty, range.end),
557             ];
558
559             llvm::LLVMSetMetadata(
560                 load,
561                 llvm::MD_range as c_uint,
562                 llvm::LLVMMDNodeInContext(self.cx.llcx, v.as_ptr(), v.len() as c_uint),
563             );
564         }
565     }
566
567     fn nonnull_metadata(&mut self, load: &'ll Value) {
568         unsafe {
569             llvm::LLVMSetMetadata(
570                 load,
571                 llvm::MD_nonnull as c_uint,
572                 llvm::LLVMMDNodeInContext(self.cx.llcx, ptr::null(), 0),
573             );
574         }
575     }
576
577     fn store(&mut self, val: &'ll Value, ptr: &'ll Value, align: Align) -> &'ll Value {
578         self.store_with_flags(val, ptr, align, MemFlags::empty())
579     }
580
581     fn store_with_flags(
582         &mut self,
583         val: &'ll Value,
584         ptr: &'ll Value,
585         align: Align,
586         flags: MemFlags,
587     ) -> &'ll Value {
588         debug!("Store {:?} -> {:?} ({:?})", val, ptr, flags);
589         let ptr = self.check_store(val, ptr);
590         unsafe {
591             let store = llvm::LLVMBuildStore(self.llbuilder, val, ptr);
592             let align =
593                 if flags.contains(MemFlags::UNALIGNED) { 1 } else { align.bytes() as c_uint };
594             llvm::LLVMSetAlignment(store, align);
595             if flags.contains(MemFlags::VOLATILE) {
596                 llvm::LLVMSetVolatile(store, llvm::True);
597             }
598             if flags.contains(MemFlags::NONTEMPORAL) {
599                 // According to LLVM [1] building a nontemporal store must
600                 // *always* point to a metadata value of the integer 1.
601                 //
602                 // [1]: http://llvm.org/docs/LangRef.html#store-instruction
603                 let one = self.cx.const_i32(1);
604                 let node = llvm::LLVMMDNodeInContext(self.cx.llcx, &one, 1);
605                 llvm::LLVMSetMetadata(store, llvm::MD_nontemporal as c_uint, node);
606             }
607             store
608         }
609     }
610
611     fn atomic_store(
612         &mut self,
613         val: &'ll Value,
614         ptr: &'ll Value,
615         order: rustc_codegen_ssa::common::AtomicOrdering,
616         size: Size,
617     ) {
618         debug!("Store {:?} -> {:?}", val, ptr);
619         let ptr = self.check_store(val, ptr);
620         unsafe {
621             let store = llvm::LLVMRustBuildAtomicStore(
622                 self.llbuilder,
623                 val,
624                 ptr,
625                 AtomicOrdering::from_generic(order),
626             );
627             // LLVM requires the alignment of atomic stores to be at least the size of the type.
628             llvm::LLVMSetAlignment(store, size.bytes() as c_uint);
629         }
630     }
631
632     fn gep(&mut self, ptr: &'ll Value, indices: &[&'ll Value]) -> &'ll Value {
633         unsafe {
634             llvm::LLVMBuildGEP(
635                 self.llbuilder,
636                 ptr,
637                 indices.as_ptr(),
638                 indices.len() as c_uint,
639                 UNNAMED,
640             )
641         }
642     }
643
644     fn inbounds_gep(&mut self, ptr: &'ll Value, indices: &[&'ll Value]) -> &'ll Value {
645         unsafe {
646             llvm::LLVMBuildInBoundsGEP(
647                 self.llbuilder,
648                 ptr,
649                 indices.as_ptr(),
650                 indices.len() as c_uint,
651                 UNNAMED,
652             )
653         }
654     }
655
656     fn struct_gep(&mut self, ptr: &'ll Value, idx: u64) -> &'ll Value {
657         assert_eq!(idx as c_uint as u64, idx);
658         unsafe { llvm::LLVMBuildStructGEP(self.llbuilder, ptr, idx as c_uint, UNNAMED) }
659     }
660
661     /* Casts */
662     fn trunc(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
663         unsafe { llvm::LLVMBuildTrunc(self.llbuilder, val, dest_ty, UNNAMED) }
664     }
665
666     fn sext(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
667         unsafe { llvm::LLVMBuildSExt(self.llbuilder, val, dest_ty, UNNAMED) }
668     }
669
670     fn fptoui_sat(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> Option<&'ll Value> {
671         // WebAssembly has saturating floating point to integer casts if the
672         // `nontrapping-fptoint` target feature is activated. We'll use those if
673         // they are available.
674         if self.sess().target.arch == "wasm32"
675             && self.sess().target_features.contains(&sym::nontrapping_dash_fptoint)
676         {
677             let src_ty = self.cx.val_ty(val);
678             let float_width = self.cx.float_width(src_ty);
679             let int_width = self.cx.int_width(dest_ty);
680             let name = match (int_width, float_width) {
681                 (32, 32) => Some("llvm.wasm.trunc.saturate.unsigned.i32.f32"),
682                 (32, 64) => Some("llvm.wasm.trunc.saturate.unsigned.i32.f64"),
683                 (64, 32) => Some("llvm.wasm.trunc.saturate.unsigned.i64.f32"),
684                 (64, 64) => Some("llvm.wasm.trunc.saturate.unsigned.i64.f64"),
685                 _ => None,
686             };
687             if let Some(name) = name {
688                 let intrinsic = self.get_intrinsic(name);
689                 return Some(self.call(intrinsic, &[val], None));
690             }
691         }
692         None
693     }
694
695     fn fptosi_sat(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> Option<&'ll Value> {
696         // WebAssembly has saturating floating point to integer casts if the
697         // `nontrapping-fptoint` target feature is activated. We'll use those if
698         // they are available.
699         if self.sess().target.arch == "wasm32"
700             && self.sess().target_features.contains(&sym::nontrapping_dash_fptoint)
701         {
702             let src_ty = self.cx.val_ty(val);
703             let float_width = self.cx.float_width(src_ty);
704             let int_width = self.cx.int_width(dest_ty);
705             let name = match (int_width, float_width) {
706                 (32, 32) => Some("llvm.wasm.trunc.saturate.signed.i32.f32"),
707                 (32, 64) => Some("llvm.wasm.trunc.saturate.signed.i32.f64"),
708                 (64, 32) => Some("llvm.wasm.trunc.saturate.signed.i64.f32"),
709                 (64, 64) => Some("llvm.wasm.trunc.saturate.signed.i64.f64"),
710                 _ => None,
711             };
712             if let Some(name) = name {
713                 let intrinsic = self.get_intrinsic(name);
714                 return Some(self.call(intrinsic, &[val], None));
715             }
716         }
717         None
718     }
719
720     fn fptosui_may_trap(&self, val: &'ll Value, dest_ty: &'ll Type) -> bool {
721         // Most of the time we'll be generating the `fptosi` or `fptoui`
722         // instruction for floating-point-to-integer conversions. These
723         // instructions by definition in LLVM do not trap. For the WebAssembly
724         // target, however, we'll lower in some cases to intrinsic calls instead
725         // which may trap. If we detect that this is a situation where we'll be
726         // using the intrinsics then we report that the call map trap, which
727         // callers might need to handle.
728         if !self.wasm_and_missing_nontrapping_fptoint() {
729             return false;
730         }
731         let src_ty = self.cx.val_ty(val);
732         let float_width = self.cx.float_width(src_ty);
733         let int_width = self.cx.int_width(dest_ty);
734         matches!((int_width, float_width), (32, 32) | (32, 64) | (64, 32) | (64, 64))
735     }
736
737     fn fptoui(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
738         // When we can, use the native wasm intrinsics which have tighter
739         // codegen. Note that this has a semantic difference in that the
740         // intrinsic can trap whereas `fptoui` never traps. That difference,
741         // however, is handled by `fptosui_may_trap` above.
742         //
743         // Note that we skip the wasm intrinsics for vector types where `fptoui`
744         // must be used instead.
745         if self.wasm_and_missing_nontrapping_fptoint() {
746             let src_ty = self.cx.val_ty(val);
747             if self.cx.type_kind(src_ty) != TypeKind::Vector {
748                 let float_width = self.cx.float_width(src_ty);
749                 let int_width = self.cx.int_width(dest_ty);
750                 let name = match (int_width, float_width) {
751                     (32, 32) => Some("llvm.wasm.trunc.unsigned.i32.f32"),
752                     (32, 64) => Some("llvm.wasm.trunc.unsigned.i32.f64"),
753                     (64, 32) => Some("llvm.wasm.trunc.unsigned.i64.f32"),
754                     (64, 64) => Some("llvm.wasm.trunc.unsigned.i64.f64"),
755                     _ => None,
756                 };
757                 if let Some(name) = name {
758                     let intrinsic = self.get_intrinsic(name);
759                     return self.call(intrinsic, &[val], None);
760                 }
761             }
762         }
763         unsafe { llvm::LLVMBuildFPToUI(self.llbuilder, val, dest_ty, UNNAMED) }
764     }
765
766     fn fptosi(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
767         if self.wasm_and_missing_nontrapping_fptoint() {
768             let src_ty = self.cx.val_ty(val);
769             if self.cx.type_kind(src_ty) != TypeKind::Vector {
770                 let float_width = self.cx.float_width(src_ty);
771                 let int_width = self.cx.int_width(dest_ty);
772                 let name = match (int_width, float_width) {
773                     (32, 32) => Some("llvm.wasm.trunc.signed.i32.f32"),
774                     (32, 64) => Some("llvm.wasm.trunc.signed.i32.f64"),
775                     (64, 32) => Some("llvm.wasm.trunc.signed.i64.f32"),
776                     (64, 64) => Some("llvm.wasm.trunc.signed.i64.f64"),
777                     _ => None,
778                 };
779                 if let Some(name) = name {
780                     let intrinsic = self.get_intrinsic(name);
781                     return self.call(intrinsic, &[val], None);
782                 }
783             }
784         }
785         unsafe { llvm::LLVMBuildFPToSI(self.llbuilder, val, dest_ty, UNNAMED) }
786     }
787
788     fn uitofp(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
789         unsafe { llvm::LLVMBuildUIToFP(self.llbuilder, val, dest_ty, UNNAMED) }
790     }
791
792     fn sitofp(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
793         unsafe { llvm::LLVMBuildSIToFP(self.llbuilder, val, dest_ty, UNNAMED) }
794     }
795
796     fn fptrunc(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
797         unsafe { llvm::LLVMBuildFPTrunc(self.llbuilder, val, dest_ty, UNNAMED) }
798     }
799
800     fn fpext(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
801         unsafe { llvm::LLVMBuildFPExt(self.llbuilder, val, dest_ty, UNNAMED) }
802     }
803
804     fn ptrtoint(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
805         unsafe { llvm::LLVMBuildPtrToInt(self.llbuilder, val, dest_ty, UNNAMED) }
806     }
807
808     fn inttoptr(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
809         unsafe { llvm::LLVMBuildIntToPtr(self.llbuilder, val, dest_ty, UNNAMED) }
810     }
811
812     fn bitcast(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
813         unsafe { llvm::LLVMBuildBitCast(self.llbuilder, val, dest_ty, UNNAMED) }
814     }
815
816     fn intcast(&mut self, val: &'ll Value, dest_ty: &'ll Type, is_signed: bool) -> &'ll Value {
817         unsafe { llvm::LLVMRustBuildIntCast(self.llbuilder, val, dest_ty, is_signed) }
818     }
819
820     fn pointercast(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
821         unsafe { llvm::LLVMBuildPointerCast(self.llbuilder, val, dest_ty, UNNAMED) }
822     }
823
824     /* Comparisons */
825     fn icmp(&mut self, op: IntPredicate, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
826         let op = llvm::IntPredicate::from_generic(op);
827         unsafe { llvm::LLVMBuildICmp(self.llbuilder, op as c_uint, lhs, rhs, UNNAMED) }
828     }
829
830     fn fcmp(&mut self, op: RealPredicate, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
831         unsafe { llvm::LLVMBuildFCmp(self.llbuilder, op as c_uint, lhs, rhs, UNNAMED) }
832     }
833
834     /* Miscellaneous instructions */
835     fn memcpy(
836         &mut self,
837         dst: &'ll Value,
838         dst_align: Align,
839         src: &'ll Value,
840         src_align: Align,
841         size: &'ll Value,
842         flags: MemFlags,
843     ) {
844         if flags.contains(MemFlags::NONTEMPORAL) {
845             // HACK(nox): This is inefficient but there is no nontemporal memcpy.
846             let val = self.load(src, src_align);
847             let ptr = self.pointercast(dst, self.type_ptr_to(self.val_ty(val)));
848             self.store_with_flags(val, ptr, dst_align, flags);
849             return;
850         }
851         let size = self.intcast(size, self.type_isize(), false);
852         let is_volatile = flags.contains(MemFlags::VOLATILE);
853         let dst = self.pointercast(dst, self.type_i8p());
854         let src = self.pointercast(src, self.type_i8p());
855         unsafe {
856             llvm::LLVMRustBuildMemCpy(
857                 self.llbuilder,
858                 dst,
859                 dst_align.bytes() as c_uint,
860                 src,
861                 src_align.bytes() as c_uint,
862                 size,
863                 is_volatile,
864             );
865         }
866     }
867
868     fn memmove(
869         &mut self,
870         dst: &'ll Value,
871         dst_align: Align,
872         src: &'ll Value,
873         src_align: Align,
874         size: &'ll Value,
875         flags: MemFlags,
876     ) {
877         if flags.contains(MemFlags::NONTEMPORAL) {
878             // HACK(nox): This is inefficient but there is no nontemporal memmove.
879             let val = self.load(src, src_align);
880             let ptr = self.pointercast(dst, self.type_ptr_to(self.val_ty(val)));
881             self.store_with_flags(val, ptr, dst_align, flags);
882             return;
883         }
884         let size = self.intcast(size, self.type_isize(), false);
885         let is_volatile = flags.contains(MemFlags::VOLATILE);
886         let dst = self.pointercast(dst, self.type_i8p());
887         let src = self.pointercast(src, self.type_i8p());
888         unsafe {
889             llvm::LLVMRustBuildMemMove(
890                 self.llbuilder,
891                 dst,
892                 dst_align.bytes() as c_uint,
893                 src,
894                 src_align.bytes() as c_uint,
895                 size,
896                 is_volatile,
897             );
898         }
899     }
900
901     fn memset(
902         &mut self,
903         ptr: &'ll Value,
904         fill_byte: &'ll Value,
905         size: &'ll Value,
906         align: Align,
907         flags: MemFlags,
908     ) {
909         let is_volatile = flags.contains(MemFlags::VOLATILE);
910         let ptr = self.pointercast(ptr, self.type_i8p());
911         unsafe {
912             llvm::LLVMRustBuildMemSet(
913                 self.llbuilder,
914                 ptr,
915                 align.bytes() as c_uint,
916                 fill_byte,
917                 size,
918                 is_volatile,
919             );
920         }
921     }
922
923     fn select(
924         &mut self,
925         cond: &'ll Value,
926         then_val: &'ll Value,
927         else_val: &'ll Value,
928     ) -> &'ll Value {
929         unsafe { llvm::LLVMBuildSelect(self.llbuilder, cond, then_val, else_val, UNNAMED) }
930     }
931
932     fn va_arg(&mut self, list: &'ll Value, ty: &'ll Type) -> &'ll Value {
933         unsafe { llvm::LLVMBuildVAArg(self.llbuilder, list, ty, UNNAMED) }
934     }
935
936     fn extract_element(&mut self, vec: &'ll Value, idx: &'ll Value) -> &'ll Value {
937         unsafe { llvm::LLVMBuildExtractElement(self.llbuilder, vec, idx, UNNAMED) }
938     }
939
940     fn vector_splat(&mut self, num_elts: usize, elt: &'ll Value) -> &'ll Value {
941         unsafe {
942             let elt_ty = self.cx.val_ty(elt);
943             let undef = llvm::LLVMGetUndef(self.type_vector(elt_ty, num_elts as u64));
944             let vec = self.insert_element(undef, elt, self.cx.const_i32(0));
945             let vec_i32_ty = self.type_vector(self.type_i32(), num_elts as u64);
946             self.shuffle_vector(vec, undef, self.const_null(vec_i32_ty))
947         }
948     }
949
950     fn extract_value(&mut self, agg_val: &'ll Value, idx: u64) -> &'ll Value {
951         assert_eq!(idx as c_uint as u64, idx);
952         unsafe { llvm::LLVMBuildExtractValue(self.llbuilder, agg_val, idx as c_uint, UNNAMED) }
953     }
954
955     fn insert_value(&mut self, agg_val: &'ll Value, elt: &'ll Value, idx: u64) -> &'ll Value {
956         assert_eq!(idx as c_uint as u64, idx);
957         unsafe { llvm::LLVMBuildInsertValue(self.llbuilder, agg_val, elt, idx as c_uint, UNNAMED) }
958     }
959
960     fn landing_pad(
961         &mut self,
962         ty: &'ll Type,
963         pers_fn: &'ll Value,
964         num_clauses: usize,
965     ) -> &'ll Value {
966         unsafe {
967             llvm::LLVMBuildLandingPad(self.llbuilder, ty, pers_fn, num_clauses as c_uint, UNNAMED)
968         }
969     }
970
971     fn set_cleanup(&mut self, landing_pad: &'ll Value) {
972         unsafe {
973             llvm::LLVMSetCleanup(landing_pad, llvm::True);
974         }
975     }
976
977     fn resume(&mut self, exn: &'ll Value) -> &'ll Value {
978         unsafe { llvm::LLVMBuildResume(self.llbuilder, exn) }
979     }
980
981     fn cleanup_pad(&mut self, parent: Option<&'ll Value>, args: &[&'ll Value]) -> Funclet<'ll> {
982         let name = cstr!("cleanuppad");
983         let ret = unsafe {
984             llvm::LLVMRustBuildCleanupPad(
985                 self.llbuilder,
986                 parent,
987                 args.len() as c_uint,
988                 args.as_ptr(),
989                 name.as_ptr(),
990             )
991         };
992         Funclet::new(ret.expect("LLVM does not have support for cleanuppad"))
993     }
994
995     fn cleanup_ret(
996         &mut self,
997         funclet: &Funclet<'ll>,
998         unwind: Option<&'ll BasicBlock>,
999     ) -> &'ll Value {
1000         let ret =
1001             unsafe { llvm::LLVMRustBuildCleanupRet(self.llbuilder, funclet.cleanuppad(), unwind) };
1002         ret.expect("LLVM does not have support for cleanupret")
1003     }
1004
1005     fn catch_pad(&mut self, parent: &'ll Value, args: &[&'ll Value]) -> Funclet<'ll> {
1006         let name = cstr!("catchpad");
1007         let ret = unsafe {
1008             llvm::LLVMRustBuildCatchPad(
1009                 self.llbuilder,
1010                 parent,
1011                 args.len() as c_uint,
1012                 args.as_ptr(),
1013                 name.as_ptr(),
1014             )
1015         };
1016         Funclet::new(ret.expect("LLVM does not have support for catchpad"))
1017     }
1018
1019     fn catch_switch(
1020         &mut self,
1021         parent: Option<&'ll Value>,
1022         unwind: Option<&'ll BasicBlock>,
1023         num_handlers: usize,
1024     ) -> &'ll Value {
1025         let name = cstr!("catchswitch");
1026         let ret = unsafe {
1027             llvm::LLVMRustBuildCatchSwitch(
1028                 self.llbuilder,
1029                 parent,
1030                 unwind,
1031                 num_handlers as c_uint,
1032                 name.as_ptr(),
1033             )
1034         };
1035         ret.expect("LLVM does not have support for catchswitch")
1036     }
1037
1038     fn add_handler(&mut self, catch_switch: &'ll Value, handler: &'ll BasicBlock) {
1039         unsafe {
1040             llvm::LLVMRustAddHandler(catch_switch, handler);
1041         }
1042     }
1043
1044     fn set_personality_fn(&mut self, personality: &'ll Value) {
1045         unsafe {
1046             llvm::LLVMSetPersonalityFn(self.llfn(), personality);
1047         }
1048     }
1049
1050     // Atomic Operations
1051     fn atomic_cmpxchg(
1052         &mut self,
1053         dst: &'ll Value,
1054         cmp: &'ll Value,
1055         src: &'ll Value,
1056         order: rustc_codegen_ssa::common::AtomicOrdering,
1057         failure_order: rustc_codegen_ssa::common::AtomicOrdering,
1058         weak: bool,
1059     ) -> &'ll Value {
1060         let weak = if weak { llvm::True } else { llvm::False };
1061         unsafe {
1062             llvm::LLVMRustBuildAtomicCmpXchg(
1063                 self.llbuilder,
1064                 dst,
1065                 cmp,
1066                 src,
1067                 AtomicOrdering::from_generic(order),
1068                 AtomicOrdering::from_generic(failure_order),
1069                 weak,
1070             )
1071         }
1072     }
1073     fn atomic_rmw(
1074         &mut self,
1075         op: rustc_codegen_ssa::common::AtomicRmwBinOp,
1076         dst: &'ll Value,
1077         src: &'ll Value,
1078         order: rustc_codegen_ssa::common::AtomicOrdering,
1079     ) -> &'ll Value {
1080         unsafe {
1081             llvm::LLVMBuildAtomicRMW(
1082                 self.llbuilder,
1083                 AtomicRmwBinOp::from_generic(op),
1084                 dst,
1085                 src,
1086                 AtomicOrdering::from_generic(order),
1087                 False,
1088             )
1089         }
1090     }
1091
1092     fn atomic_fence(
1093         &mut self,
1094         order: rustc_codegen_ssa::common::AtomicOrdering,
1095         scope: rustc_codegen_ssa::common::SynchronizationScope,
1096     ) {
1097         unsafe {
1098             llvm::LLVMRustBuildAtomicFence(
1099                 self.llbuilder,
1100                 AtomicOrdering::from_generic(order),
1101                 SynchronizationScope::from_generic(scope),
1102             );
1103         }
1104     }
1105
1106     fn set_invariant_load(&mut self, load: &'ll Value) {
1107         unsafe {
1108             llvm::LLVMSetMetadata(
1109                 load,
1110                 llvm::MD_invariant_load as c_uint,
1111                 llvm::LLVMMDNodeInContext(self.cx.llcx, ptr::null(), 0),
1112             );
1113         }
1114     }
1115
1116     fn lifetime_start(&mut self, ptr: &'ll Value, size: Size) {
1117         self.call_lifetime_intrinsic("llvm.lifetime.start.p0i8", ptr, size);
1118     }
1119
1120     fn lifetime_end(&mut self, ptr: &'ll Value, size: Size) {
1121         self.call_lifetime_intrinsic("llvm.lifetime.end.p0i8", ptr, size);
1122     }
1123
1124     fn instrprof_increment(
1125         &mut self,
1126         fn_name: &'ll Value,
1127         hash: &'ll Value,
1128         num_counters: &'ll Value,
1129         index: &'ll Value,
1130     ) {
1131         debug!(
1132             "instrprof_increment() with args ({:?}, {:?}, {:?}, {:?})",
1133             fn_name, hash, num_counters, index
1134         );
1135
1136         let llfn = unsafe { llvm::LLVMRustGetInstrProfIncrementIntrinsic(self.cx().llmod) };
1137         let args = &[fn_name, hash, num_counters, index];
1138         let args = self.check_call("call", llfn, args);
1139
1140         unsafe {
1141             let _ = llvm::LLVMRustBuildCall(
1142                 self.llbuilder,
1143                 llfn,
1144                 args.as_ptr() as *const &llvm::Value,
1145                 args.len() as c_uint,
1146                 None,
1147             );
1148         }
1149     }
1150
1151     fn call(
1152         &mut self,
1153         llfn: &'ll Value,
1154         args: &[&'ll Value],
1155         funclet: Option<&Funclet<'ll>>,
1156     ) -> &'ll Value {
1157         debug!("call {:?} with args ({:?})", llfn, args);
1158
1159         let args = self.check_call("call", llfn, args);
1160         let bundle = funclet.map(|funclet| funclet.bundle());
1161         let bundle = bundle.as_ref().map(|b| &*b.raw);
1162
1163         unsafe {
1164             llvm::LLVMRustBuildCall(
1165                 self.llbuilder,
1166                 llfn,
1167                 args.as_ptr() as *const &llvm::Value,
1168                 args.len() as c_uint,
1169                 bundle,
1170             )
1171         }
1172     }
1173
1174     fn zext(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1175         unsafe { llvm::LLVMBuildZExt(self.llbuilder, val, dest_ty, UNNAMED) }
1176     }
1177
1178     fn cx(&self) -> &CodegenCx<'ll, 'tcx> {
1179         self.cx
1180     }
1181
1182     unsafe fn delete_basic_block(&mut self, bb: &'ll BasicBlock) {
1183         llvm::LLVMDeleteBasicBlock(bb);
1184     }
1185
1186     fn do_not_inline(&mut self, llret: &'ll Value) {
1187         llvm::Attribute::NoInline.apply_callsite(llvm::AttributePlace::Function, llret);
1188     }
1189 }
1190
1191 impl StaticBuilderMethods for Builder<'a, 'll, 'tcx> {
1192     fn get_static(&mut self, def_id: DefId) -> &'ll Value {
1193         // Forward to the `get_static` method of `CodegenCx`
1194         self.cx().get_static(def_id)
1195     }
1196 }
1197
1198 impl Builder<'a, 'll, 'tcx> {
1199     pub fn llfn(&self) -> &'ll Value {
1200         unsafe { llvm::LLVMGetBasicBlockParent(self.llbb()) }
1201     }
1202
1203     fn position_at_start(&mut self, llbb: &'ll BasicBlock) {
1204         unsafe {
1205             llvm::LLVMRustPositionBuilderAtStart(self.llbuilder, llbb);
1206         }
1207     }
1208
1209     pub fn minnum(&mut self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
1210         unsafe { llvm::LLVMRustBuildMinNum(self.llbuilder, lhs, rhs) }
1211     }
1212
1213     pub fn maxnum(&mut self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
1214         unsafe { llvm::LLVMRustBuildMaxNum(self.llbuilder, lhs, rhs) }
1215     }
1216
1217     pub fn insert_element(
1218         &mut self,
1219         vec: &'ll Value,
1220         elt: &'ll Value,
1221         idx: &'ll Value,
1222     ) -> &'ll Value {
1223         unsafe { llvm::LLVMBuildInsertElement(self.llbuilder, vec, elt, idx, UNNAMED) }
1224     }
1225
1226     pub fn shuffle_vector(
1227         &mut self,
1228         v1: &'ll Value,
1229         v2: &'ll Value,
1230         mask: &'ll Value,
1231     ) -> &'ll Value {
1232         unsafe { llvm::LLVMBuildShuffleVector(self.llbuilder, v1, v2, mask, UNNAMED) }
1233     }
1234
1235     pub fn vector_reduce_fadd(&mut self, acc: &'ll Value, src: &'ll Value) -> &'ll Value {
1236         unsafe { llvm::LLVMRustBuildVectorReduceFAdd(self.llbuilder, acc, src) }
1237     }
1238     pub fn vector_reduce_fmul(&mut self, acc: &'ll Value, src: &'ll Value) -> &'ll Value {
1239         unsafe { llvm::LLVMRustBuildVectorReduceFMul(self.llbuilder, acc, src) }
1240     }
1241     pub fn vector_reduce_fadd_fast(&mut self, acc: &'ll Value, src: &'ll Value) -> &'ll Value {
1242         unsafe {
1243             let instr = llvm::LLVMRustBuildVectorReduceFAdd(self.llbuilder, acc, src);
1244             llvm::LLVMRustSetHasUnsafeAlgebra(instr);
1245             instr
1246         }
1247     }
1248     pub fn vector_reduce_fmul_fast(&mut self, acc: &'ll Value, src: &'ll Value) -> &'ll Value {
1249         unsafe {
1250             let instr = llvm::LLVMRustBuildVectorReduceFMul(self.llbuilder, acc, src);
1251             llvm::LLVMRustSetHasUnsafeAlgebra(instr);
1252             instr
1253         }
1254     }
1255     pub fn vector_reduce_add(&mut self, src: &'ll Value) -> &'ll Value {
1256         unsafe { llvm::LLVMRustBuildVectorReduceAdd(self.llbuilder, src) }
1257     }
1258     pub fn vector_reduce_mul(&mut self, src: &'ll Value) -> &'ll Value {
1259         unsafe { llvm::LLVMRustBuildVectorReduceMul(self.llbuilder, src) }
1260     }
1261     pub fn vector_reduce_and(&mut self, src: &'ll Value) -> &'ll Value {
1262         unsafe { llvm::LLVMRustBuildVectorReduceAnd(self.llbuilder, src) }
1263     }
1264     pub fn vector_reduce_or(&mut self, src: &'ll Value) -> &'ll Value {
1265         unsafe { llvm::LLVMRustBuildVectorReduceOr(self.llbuilder, src) }
1266     }
1267     pub fn vector_reduce_xor(&mut self, src: &'ll Value) -> &'ll Value {
1268         unsafe { llvm::LLVMRustBuildVectorReduceXor(self.llbuilder, src) }
1269     }
1270     pub fn vector_reduce_fmin(&mut self, src: &'ll Value) -> &'ll Value {
1271         unsafe {
1272             llvm::LLVMRustBuildVectorReduceFMin(self.llbuilder, src, /*NoNaNs:*/ false)
1273         }
1274     }
1275     pub fn vector_reduce_fmax(&mut self, src: &'ll Value) -> &'ll Value {
1276         unsafe {
1277             llvm::LLVMRustBuildVectorReduceFMax(self.llbuilder, src, /*NoNaNs:*/ false)
1278         }
1279     }
1280     pub fn vector_reduce_fmin_fast(&mut self, src: &'ll Value) -> &'ll Value {
1281         unsafe {
1282             let instr =
1283                 llvm::LLVMRustBuildVectorReduceFMin(self.llbuilder, src, /*NoNaNs:*/ true);
1284             llvm::LLVMRustSetHasUnsafeAlgebra(instr);
1285             instr
1286         }
1287     }
1288     pub fn vector_reduce_fmax_fast(&mut self, src: &'ll Value) -> &'ll Value {
1289         unsafe {
1290             let instr =
1291                 llvm::LLVMRustBuildVectorReduceFMax(self.llbuilder, src, /*NoNaNs:*/ true);
1292             llvm::LLVMRustSetHasUnsafeAlgebra(instr);
1293             instr
1294         }
1295     }
1296     pub fn vector_reduce_min(&mut self, src: &'ll Value, is_signed: bool) -> &'ll Value {
1297         unsafe { llvm::LLVMRustBuildVectorReduceMin(self.llbuilder, src, is_signed) }
1298     }
1299     pub fn vector_reduce_max(&mut self, src: &'ll Value, is_signed: bool) -> &'ll Value {
1300         unsafe { llvm::LLVMRustBuildVectorReduceMax(self.llbuilder, src, is_signed) }
1301     }
1302
1303     pub fn add_clause(&mut self, landing_pad: &'ll Value, clause: &'ll Value) {
1304         unsafe {
1305             llvm::LLVMAddClause(landing_pad, clause);
1306         }
1307     }
1308
1309     pub fn catch_ret(&mut self, funclet: &Funclet<'ll>, unwind: &'ll BasicBlock) -> &'ll Value {
1310         let ret =
1311             unsafe { llvm::LLVMRustBuildCatchRet(self.llbuilder, funclet.cleanuppad(), unwind) };
1312         ret.expect("LLVM does not have support for catchret")
1313     }
1314
1315     fn check_store(&mut self, val: &'ll Value, ptr: &'ll Value) -> &'ll Value {
1316         let dest_ptr_ty = self.cx.val_ty(ptr);
1317         let stored_ty = self.cx.val_ty(val);
1318         let stored_ptr_ty = self.cx.type_ptr_to(stored_ty);
1319
1320         assert_eq!(self.cx.type_kind(dest_ptr_ty), TypeKind::Pointer);
1321
1322         if dest_ptr_ty == stored_ptr_ty {
1323             ptr
1324         } else {
1325             debug!(
1326                 "type mismatch in store. \
1327                     Expected {:?}, got {:?}; inserting bitcast",
1328                 dest_ptr_ty, stored_ptr_ty
1329             );
1330             self.bitcast(ptr, stored_ptr_ty)
1331         }
1332     }
1333
1334     fn check_call<'b>(
1335         &mut self,
1336         typ: &str,
1337         llfn: &'ll Value,
1338         args: &'b [&'ll Value],
1339     ) -> Cow<'b, [&'ll Value]> {
1340         let mut fn_ty = self.cx.val_ty(llfn);
1341         // Strip off pointers
1342         while self.cx.type_kind(fn_ty) == TypeKind::Pointer {
1343             fn_ty = self.cx.element_type(fn_ty);
1344         }
1345
1346         assert!(
1347             self.cx.type_kind(fn_ty) == TypeKind::Function,
1348             "builder::{} not passed a function, but {:?}",
1349             typ,
1350             fn_ty
1351         );
1352
1353         let param_tys = self.cx.func_params_types(fn_ty);
1354
1355         let all_args_match = param_tys
1356             .iter()
1357             .zip(args.iter().map(|&v| self.val_ty(v)))
1358             .all(|(expected_ty, actual_ty)| *expected_ty == actual_ty);
1359
1360         if all_args_match {
1361             return Cow::Borrowed(args);
1362         }
1363
1364         let casted_args: Vec<_> = param_tys
1365             .into_iter()
1366             .zip(args.iter())
1367             .enumerate()
1368             .map(|(i, (expected_ty, &actual_val))| {
1369                 let actual_ty = self.val_ty(actual_val);
1370                 if expected_ty != actual_ty {
1371                     debug!(
1372                         "type mismatch in function call of {:?}. \
1373                             Expected {:?} for param {}, got {:?}; injecting bitcast",
1374                         llfn, expected_ty, i, actual_ty
1375                     );
1376                     self.bitcast(actual_val, expected_ty)
1377                 } else {
1378                     actual_val
1379                 }
1380             })
1381             .collect();
1382
1383         Cow::Owned(casted_args)
1384     }
1385
1386     pub fn va_arg(&mut self, list: &'ll Value, ty: &'ll Type) -> &'ll Value {
1387         unsafe { llvm::LLVMBuildVAArg(self.llbuilder, list, ty, UNNAMED) }
1388     }
1389
1390     fn call_lifetime_intrinsic(&mut self, intrinsic: &str, ptr: &'ll Value, size: Size) {
1391         let size = size.bytes();
1392         if size == 0 {
1393             return;
1394         }
1395
1396         if !self.cx().sess().emit_lifetime_markers() {
1397             return;
1398         }
1399
1400         let lifetime_intrinsic = self.cx.get_intrinsic(intrinsic);
1401
1402         let ptr = self.pointercast(ptr, self.cx.type_i8p());
1403         self.call(lifetime_intrinsic, &[self.cx.const_u64(size), ptr], None);
1404     }
1405
1406     pub(crate) fn phi(
1407         &mut self,
1408         ty: &'ll Type,
1409         vals: &[&'ll Value],
1410         bbs: &[&'ll BasicBlock],
1411     ) -> &'ll Value {
1412         assert_eq!(vals.len(), bbs.len());
1413         let phi = unsafe { llvm::LLVMBuildPhi(self.llbuilder, ty, UNNAMED) };
1414         unsafe {
1415             llvm::LLVMAddIncoming(phi, vals.as_ptr(), bbs.as_ptr(), vals.len() as c_uint);
1416             phi
1417         }
1418     }
1419
1420     fn add_incoming_to_phi(&mut self, phi: &'ll Value, val: &'ll Value, bb: &'ll BasicBlock) {
1421         unsafe {
1422             llvm::LLVMAddIncoming(phi, &val, &bb, 1 as c_uint);
1423         }
1424     }
1425
1426     fn wasm_and_missing_nontrapping_fptoint(&self) -> bool {
1427         self.sess().target.arch == "wasm32"
1428             && !self.sess().target_features.contains(&sym::nontrapping_dash_fptoint)
1429     }
1430 }