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