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