1use std::borrow::{Borrow, Cow};
2use std::iter;
3use std::ops::Deref;
4
5use rustc_ast::expand::typetree::FncTree;
6pub(crate) mod autodiff;
7pub(crate) mod gpu_offload;
8
9use libc::{c_char, c_uint};
10use rustc_abi::{self as abi, Align, Size, WrappingRange};
11use rustc_codegen_ssa::MemFlags;
12use rustc_codegen_ssa::common::{IntPredicate, RealPredicate, SynchronizationScope, TypeKind};
13use rustc_codegen_ssa::mir::operand::{OperandRef, OperandValue};
14use rustc_codegen_ssa::mir::place::PlaceRef;
15use rustc_codegen_ssa::traits::*;
16use rustc_data_structures::small_c_str::SmallCStr;
17use rustc_hir::attrs::{AttributeKind, UnrollAttr};
18use rustc_hir::def_id::DefId;
19use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrs;
20use rustc_middle::ty::layout::{
21 FnAbiError, FnAbiOfHelpers, FnAbiRequest, HasTypingEnv, LayoutError, LayoutOfHelpers,
22 TyAndLayout,
23};
24use rustc_middle::ty::{self, Instance, Ty, TyCtxt};
25use rustc_sanitizers::{cfi, kcfi};
26use rustc_session::config::OptLevel;
27use rustc_span::Span;
28use rustc_target::callconv::{FnAbi, PassMode};
29use rustc_target::spec::{Arch, HasTargetSpec, SanitizerSet, Target};
30use smallvec::SmallVec;
31use tracing::{debug, instrument};
32
33use crate::abi::FnAbiLlvmExt;
34use crate::attributes;
35use crate::common::Funclet;
36use crate::context::{CodegenCx, FullCx, GenericCx, SCx};
37use crate::llvm::{
38 self, AtomicOrdering, AtomicRmwBinOp, BasicBlock, FromGeneric, GEPNoWrapFlags, Metadata, TRUE,
39 ToLlvmBool, Type, Value,
40};
41use crate::type_of::LayoutLlvmExt;
42
43#[must_use]
44pub(crate) struct GenericBuilder<'a, 'll, CX: Borrow<SCx<'ll>>> {
45 pub llbuilder: &'ll mut llvm::Builder<'ll>,
46 pub cx: &'a GenericCx<'ll, CX>,
47}
48
49pub(crate) type SBuilder<'a, 'll> = GenericBuilder<'a, 'll, SCx<'ll>>;
50pub(crate) type Builder<'a, 'll, 'tcx> = GenericBuilder<'a, 'll, FullCx<'ll, 'tcx>>;
51
52impl<'a, 'll, CX: Borrow<SCx<'ll>>> Drop for GenericBuilder<'a, 'll, CX> {
53 fn drop(&mut self) {
54 unsafe {
55 llvm::LLVMDisposeBuilder(&mut *(self.llbuilder as *mut _));
56 }
57 }
58}
59
60impl<'a, 'll> SBuilder<'a, 'll> {
61 pub(crate) fn call(
62 &mut self,
63 llty: &'ll Type,
64 llfn: &'ll Value,
65 args: &[&'ll Value],
66 funclet: Option<&Funclet<'ll>>,
67 ) -> &'ll Value {
68 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_llvm/src/builder.rs:68",
"rustc_codegen_llvm::builder", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_llvm/src/builder.rs"),
::tracing_core::__macro_support::Option::Some(68u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::builder"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("call {0:?} with args ({1:?})",
llfn, args) as &dyn Value))])
});
} else { ; }
};debug!("call {:?} with args ({:?})", llfn, args);
69
70 let args = self.check_call("call", llty, llfn, args);
71 let funclet_bundle = funclet.map(|funclet| funclet.bundle());
72 let mut bundles: SmallVec<[_; 2]> = SmallVec::new();
73 if let Some(funclet_bundle) = funclet_bundle {
74 bundles.push(funclet_bundle);
75 }
76
77 let call = unsafe {
78 llvm::LLVMBuildCallWithOperandBundles(
79 self.llbuilder,
80 llty,
81 llfn,
82 args.as_ptr() as *const &llvm::Value,
83 args.len() as c_uint,
84 bundles.as_ptr(),
85 bundles.len() as c_uint,
86 c"".as_ptr(),
87 )
88 };
89 call
90 }
91}
92
93impl<'a, 'll, CX: Borrow<SCx<'ll>>> GenericBuilder<'a, 'll, CX> {
94 fn with_cx(scx: &'a GenericCx<'ll, CX>) -> Self {
95 let llbuilder = unsafe { llvm::LLVMCreateBuilderInContext(scx.deref().borrow().llcx) };
97 GenericBuilder { llbuilder, cx: scx }
98 }
99
100 pub(crate) fn append_block(
101 cx: &'a GenericCx<'ll, CX>,
102 llfn: &'ll Value,
103 name: &str,
104 ) -> &'ll BasicBlock {
105 unsafe {
106 let name = SmallCStr::new(name);
107 llvm::LLVMAppendBasicBlockInContext(cx.llcx(), llfn, name.as_ptr())
108 }
109 }
110
111 pub(crate) fn trunc(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
112 unsafe { llvm::LLVMBuildTrunc(self.llbuilder, val, dest_ty, UNNAMED) }
113 }
114
115 pub(crate) fn bitcast(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
116 unsafe { llvm::LLVMBuildBitCast(self.llbuilder, val, dest_ty, UNNAMED) }
117 }
118
119 pub(crate) fn ret_void(&mut self) {
120 llvm::LLVMBuildRetVoid(self.llbuilder);
121 }
122
123 pub(crate) fn ret(&mut self, v: &'ll Value) {
124 unsafe {
125 llvm::LLVMBuildRet(self.llbuilder, v);
126 }
127 }
128
129 pub(crate) fn build(cx: &'a GenericCx<'ll, CX>, llbb: &'ll BasicBlock) -> Self {
130 let bx = Self::with_cx(cx);
131 unsafe {
132 llvm::LLVMPositionBuilderAtEnd(bx.llbuilder, llbb);
133 }
134 bx
135 }
136
137 pub(crate) fn direct_alloca(&mut self, ty: &'ll Type, align: Align, name: &str) -> &'ll Value {
142 let val = unsafe {
143 let alloca = llvm::LLVMBuildAlloca(self.llbuilder, ty, UNNAMED);
144 llvm::LLVMSetAlignment(alloca, align.bytes() as c_uint);
145 llvm::LLVMBuildPointerCast(self.llbuilder, alloca, self.cx.type_ptr(), UNNAMED)
147 };
148 if name != "" {
149 let name = std::ffi::CString::new(name).unwrap();
150 llvm::set_value_name(val, &name.as_bytes());
151 }
152 val
153 }
154
155 pub(crate) fn inbounds_gep(
156 &mut self,
157 ty: &'ll Type,
158 ptr: &'ll Value,
159 indices: &[&'ll Value],
160 ) -> &'ll Value {
161 unsafe {
162 llvm::LLVMBuildGEPWithNoWrapFlags(
163 self.llbuilder,
164 ty,
165 ptr,
166 indices.as_ptr(),
167 indices.len() as c_uint,
168 UNNAMED,
169 GEPNoWrapFlags::InBounds,
170 )
171 }
172 }
173
174 pub(crate) fn store(&mut self, val: &'ll Value, ptr: &'ll Value, align: Align) -> &'ll Value {
175 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_llvm/src/builder.rs:175",
"rustc_codegen_llvm::builder", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_llvm/src/builder.rs"),
::tracing_core::__macro_support::Option::Some(175u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::builder"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("Store {0:?} -> {1:?}",
val, ptr) as &dyn Value))])
});
} else { ; }
};debug!("Store {:?} -> {:?}", val, ptr);
176 match (&self.cx.type_kind(self.cx.val_ty(ptr)), &TypeKind::Pointer) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val, &*right_val,
::core::option::Option::None);
}
}
};assert_eq!(self.cx.type_kind(self.cx.val_ty(ptr)), TypeKind::Pointer);
177 unsafe {
178 let store = llvm::LLVMBuildStore(self.llbuilder, val, ptr);
179 llvm::LLVMSetAlignment(store, align.bytes() as c_uint);
180 store
181 }
182 }
183
184 pub(crate) fn load(&mut self, ty: &'ll Type, ptr: &'ll Value, align: Align) -> &'ll Value {
185 unsafe {
186 let load = llvm::LLVMBuildLoad2(self.llbuilder, ty, ptr, UNNAMED);
187 llvm::LLVMSetAlignment(load, align.bytes() as c_uint);
188 load
189 }
190 }
191}
192
193pub(crate) const UNNAMED: *const c_char = c"".as_ptr();
197
198impl<'ll, CX: Borrow<SCx<'ll>>> BackendTypes for GenericBuilder<'_, 'll, CX> {
199 type Function = <GenericCx<'ll, CX> as BackendTypes>::Function;
200 type BasicBlock = <GenericCx<'ll, CX> as BackendTypes>::BasicBlock;
201 type Funclet = <GenericCx<'ll, CX> as BackendTypes>::Funclet;
202
203 type Value = <GenericCx<'ll, CX> as BackendTypes>::Value;
204 type Type = <GenericCx<'ll, CX> as BackendTypes>::Type;
205 type FunctionSignature = <GenericCx<'ll, CX> as BackendTypes>::FunctionSignature;
206
207 type DIScope = <GenericCx<'ll, CX> as BackendTypes>::DIScope;
208 type DILocation = <GenericCx<'ll, CX> as BackendTypes>::DILocation;
209 type DIVariable = <GenericCx<'ll, CX> as BackendTypes>::DIVariable;
210}
211
212impl abi::HasDataLayout for Builder<'_, '_, '_> {
213 fn data_layout(&self) -> &abi::TargetDataLayout {
214 self.cx.data_layout()
215 }
216}
217
218impl<'tcx> ty::layout::HasTyCtxt<'tcx> for Builder<'_, '_, 'tcx> {
219 #[inline]
220 fn tcx(&self) -> TyCtxt<'tcx> {
221 self.cx.tcx
222 }
223}
224
225impl<'tcx> ty::layout::HasTypingEnv<'tcx> for Builder<'_, '_, 'tcx> {
226 fn typing_env(&self) -> ty::TypingEnv<'tcx> {
227 self.cx.typing_env()
228 }
229}
230
231impl HasTargetSpec for Builder<'_, '_, '_> {
232 #[inline]
233 fn target_spec(&self) -> &Target {
234 self.cx.target_spec()
235 }
236}
237
238impl<'tcx> LayoutOfHelpers<'tcx> for Builder<'_, '_, 'tcx> {
239 #[inline]
240 fn handle_layout_err(&self, err: LayoutError<'tcx>, span: Span, ty: Ty<'tcx>) -> ! {
241 self.cx.handle_layout_err(err, span, ty)
242 }
243}
244
245impl<'tcx> FnAbiOfHelpers<'tcx> for Builder<'_, '_, 'tcx> {
246 #[inline]
247 fn handle_fn_abi_err(
248 &self,
249 err: FnAbiError<'tcx>,
250 span: Span,
251 fn_abi_request: FnAbiRequest<'tcx>,
252 ) -> ! {
253 self.cx.handle_fn_abi_err(err, span, fn_abi_request)
254 }
255}
256
257impl<'ll, 'tcx> Deref for Builder<'_, 'll, 'tcx> {
258 type Target = CodegenCx<'ll, 'tcx>;
259
260 #[inline]
261 fn deref(&self) -> &Self::Target {
262 self.cx
263 }
264}
265
266macro_rules! math_builder_methods {
267 ($($name:ident($($arg:ident),*) => $llvm_capi:ident),+ $(,)?) => {
268 $(fn $name(&mut self, $($arg: &'ll Value),*) -> &'ll Value {
269 unsafe {
270 llvm::$llvm_capi(self.llbuilder, $($arg,)* UNNAMED)
271 }
272 })+
273 }
274}
275
276macro_rules! set_math_builder_methods {
277 ($($name:ident($($arg:ident),*) => ($llvm_capi:ident, $llvm_set_math:ident)),+ $(,)?) => {
278 $(fn $name(&mut self, $($arg: &'ll Value),*) -> &'ll Value {
279 unsafe {
280 let instr = llvm::$llvm_capi(self.llbuilder, $($arg,)* UNNAMED);
281 llvm::$llvm_set_math(instr);
282 instr
283 }
284 })+
285 }
286}
287
288impl<'a, 'll, 'tcx> BuilderMethods<'a, 'tcx> for Builder<'a, 'll, 'tcx> {
289 type CodegenCx = CodegenCx<'ll, 'tcx>;
290
291 fn build(cx: &'a CodegenCx<'ll, 'tcx>, llbb: &'ll BasicBlock) -> Self {
292 let bx = Builder::with_cx(cx);
293 unsafe {
294 llvm::LLVMPositionBuilderAtEnd(bx.llbuilder, llbb);
295 }
296 bx
297 }
298
299 fn cx(&self) -> &CodegenCx<'ll, 'tcx> {
300 self.cx
301 }
302
303 fn llbb(&self) -> &'ll BasicBlock {
304 unsafe { llvm::LLVMGetInsertBlock(self.llbuilder) }
305 }
306
307 fn set_span(&mut self, _span: Span) {}
308
309 fn append_block(cx: &'a CodegenCx<'ll, 'tcx>, llfn: &'ll Value, name: &str) -> &'ll BasicBlock {
310 unsafe {
311 let name = SmallCStr::new(name);
312 llvm::LLVMAppendBasicBlockInContext(cx.llcx, llfn, name.as_ptr())
313 }
314 }
315
316 fn append_sibling_block(&mut self, name: &str) -> &'ll BasicBlock {
317 Self::append_block(self.cx, self.llfn(), name)
318 }
319
320 fn switch_to_block(&mut self, llbb: Self::BasicBlock) {
321 *self = Self::build(self.cx, llbb)
322 }
323
324 fn ret_void(&mut self) {
325 llvm::LLVMBuildRetVoid(self.llbuilder);
326 }
327
328 fn ret(&mut self, v: &'ll Value) {
329 unsafe {
330 llvm::LLVMBuildRet(self.llbuilder, v);
331 }
332 }
333
334 fn br(&mut self, dest: &'ll BasicBlock) {
335 unsafe {
336 llvm::LLVMBuildBr(self.llbuilder, dest);
337 }
338 }
339
340 fn br_with_attrs(&mut self, dest: &'ll BasicBlock, attributes: &[AttributeKind]) {
341 unsafe {
342 let val = llvm::LLVMBuildBr(self.llbuilder, dest);
343
344 let mut nodes = Vec::new();
345
346 for attribute in attributes {
347 let AttributeKind::Unroll(unroll) = attribute else {
348 continue;
349 };
350 let md_node = if let UnrollAttr::Count(count) = unroll {
353 let unroll_meta = self.create_metadata("llvm.loop.unroll.count".as_bytes());
354 let count = llvm::LLVMValueAsMetadata(self.get_const_i32(u64::from(*count)));
355 self.md_node_in_context(&[unroll_meta, count])
356 } else {
357 let metadata_str = match unroll {
358 UnrollAttr::Hint => "llvm.loop.unroll.enable",
359 UnrollAttr::Full => "llvm.loop.unroll.full",
360 UnrollAttr::Never => "llvm.loop.unroll.disable",
361 UnrollAttr::Count(_) => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
362 };
363 let unroll_meta = self.create_metadata(metadata_str.as_bytes());
364 self.md_node_in_context(&[unroll_meta])
365 };
366 nodes.push(md_node);
367 }
368
369 if let [first, ..] = nodes[..] {
370 nodes.insert(0, first);
371
372 let loop_meta_mdnode = self.set_metadata_node(val, llvm::MD_loop, &nodes);
374
375 let loop_meta_val = llvm::LLVMGetMetadata(val, llvm::MD_loop).unwrap();
377
378 llvm::LLVMReplaceMDNodeOperandWith(loop_meta_val, 0, loop_meta_mdnode);
381 }
382 }
383 }
384
385 fn cond_br(
386 &mut self,
387 cond: &'ll Value,
388 then_llbb: &'ll BasicBlock,
389 else_llbb: &'ll BasicBlock,
390 ) {
391 unsafe {
392 llvm::LLVMBuildCondBr(self.llbuilder, cond, then_llbb, else_llbb);
393 }
394 }
395
396 fn switch(
397 &mut self,
398 v: &'ll Value,
399 else_llbb: &'ll BasicBlock,
400 cases: impl ExactSizeIterator<Item = (u128, &'ll BasicBlock)>,
401 ) {
402 let switch =
403 unsafe { llvm::LLVMBuildSwitch(self.llbuilder, v, else_llbb, cases.len() as c_uint) };
404 for (on_val, dest) in cases {
405 let on_val = self.const_uint_big(self.val_ty(v), on_val);
406 unsafe { llvm::LLVMAddCase(switch, on_val, dest) }
407 }
408 }
409
410 fn switch_with_weights(
411 &mut self,
412 v: Self::Value,
413 else_llbb: Self::BasicBlock,
414 else_is_cold: bool,
415 cases: impl ExactSizeIterator<Item = (u128, Self::BasicBlock, bool)>,
416 ) {
417 if self.cx.sess().opts.optimize == rustc_session::config::OptLevel::No {
418 self.switch(v, else_llbb, cases.map(|(val, dest, _)| (val, dest)));
419 return;
420 }
421
422 let id = self.cx.create_metadata(b"branch_weights");
423
424 let cold_weight = llvm::LLVMValueAsMetadata(self.cx.const_u32(1));
429 let hot_weight = llvm::LLVMValueAsMetadata(self.cx.const_u32(2000));
430 let weight =
431 |is_cold: bool| -> &Metadata { if is_cold { cold_weight } else { hot_weight } };
432
433 let mut md: SmallVec<[&Metadata; 16]> = SmallVec::with_capacity(cases.len() + 2);
434 md.push(id);
435 md.push(weight(else_is_cold));
436
437 let switch =
438 unsafe { llvm::LLVMBuildSwitch(self.llbuilder, v, else_llbb, cases.len() as c_uint) };
439 for (on_val, dest, is_cold) in cases {
440 let on_val = self.const_uint_big(self.val_ty(v), on_val);
441 unsafe { llvm::LLVMAddCase(switch, on_val, dest) }
442 md.push(weight(is_cold));
443 }
444
445 self.cx.set_metadata_node(switch, llvm::MD_prof, &md);
446 }
447
448 fn invoke(
449 &mut self,
450 llty: &'ll Type,
451 fn_attrs: Option<&CodegenFnAttrs>,
452 fn_abi: Option<&FnAbi<'tcx, Ty<'tcx>>>,
453 llfn: &'ll Value,
454 args: &[&'ll Value],
455 then: &'ll BasicBlock,
456 catch: &'ll BasicBlock,
457 funclet: Option<&Funclet<'ll>>,
458 instance: Option<Instance<'tcx>>,
459 ) -> &'ll Value {
460 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_llvm/src/builder.rs:460",
"rustc_codegen_llvm::builder", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_llvm/src/builder.rs"),
::tracing_core::__macro_support::Option::Some(460u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::builder"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("invoke {0:?} with args ({1:?})",
llfn, args) as &dyn Value))])
});
} else { ; }
};debug!("invoke {:?} with args ({:?})", llfn, args);
461
462 let args = self.check_call("invoke", llty, llfn, args);
463 let funclet_bundle = funclet.map(|funclet| funclet.bundle());
464 let mut bundles: SmallVec<[_; 2]> = SmallVec::new();
465 if let Some(funclet_bundle) = funclet_bundle {
466 bundles.push(funclet_bundle);
467 }
468
469 self.cfi_type_test(fn_attrs, fn_abi, instance, llfn);
471
472 let kcfi_bundle = self.kcfi_operand_bundle(fn_attrs, fn_abi, instance, llfn);
474 if let Some(kcfi_bundle) = kcfi_bundle.as_ref().map(|b| b.as_ref()) {
475 bundles.push(kcfi_bundle);
476 }
477
478 let invoke = unsafe {
479 llvm::LLVMBuildInvokeWithOperandBundles(
480 self.llbuilder,
481 llty,
482 llfn,
483 args.as_ptr(),
484 args.len() as c_uint,
485 then,
486 catch,
487 bundles.as_ptr(),
488 bundles.len() as c_uint,
489 UNNAMED,
490 )
491 };
492 if let Some(fn_abi) = fn_abi {
493 fn_abi.apply_attrs_callsite(self, invoke);
494 }
495 invoke
496 }
497
498 fn unreachable(&mut self) {
499 unsafe {
500 llvm::LLVMBuildUnreachable(self.llbuilder);
501 }
502 }
503
504 fn unchecked_umul(&mut self, x: &'ll Value, y: &'ll Value) -> &'ll Value {
unsafe { llvm::LLVMBuildNUWMul(self.llbuilder, x, y, UNNAMED) }
}math_builder_methods! {
505 add(a, b) => LLVMBuildAdd,
506 fadd(a, b) => LLVMBuildFAdd,
507 sub(a, b) => LLVMBuildSub,
508 fsub(a, b) => LLVMBuildFSub,
509 mul(a, b) => LLVMBuildMul,
510 fmul(a, b) => LLVMBuildFMul,
511 udiv(a, b) => LLVMBuildUDiv,
512 exactudiv(a, b) => LLVMBuildExactUDiv,
513 sdiv(a, b) => LLVMBuildSDiv,
514 exactsdiv(a, b) => LLVMBuildExactSDiv,
515 fdiv(a, b) => LLVMBuildFDiv,
516 urem(a, b) => LLVMBuildURem,
517 srem(a, b) => LLVMBuildSRem,
518 frem(a, b) => LLVMBuildFRem,
519 shl(a, b) => LLVMBuildShl,
520 lshr(a, b) => LLVMBuildLShr,
521 ashr(a, b) => LLVMBuildAShr,
522 and(a, b) => LLVMBuildAnd,
523 or(a, b) => LLVMBuildOr,
524 xor(a, b) => LLVMBuildXor,
525 neg(x) => LLVMBuildNeg,
526 fneg(x) => LLVMBuildFNeg,
527 not(x) => LLVMBuildNot,
528 unchecked_sadd(x, y) => LLVMBuildNSWAdd,
529 unchecked_uadd(x, y) => LLVMBuildNUWAdd,
530 unchecked_ssub(x, y) => LLVMBuildNSWSub,
531 unchecked_usub(x, y) => LLVMBuildNUWSub,
532 unchecked_smul(x, y) => LLVMBuildNSWMul,
533 unchecked_umul(x, y) => LLVMBuildNUWMul,
534 }
535
536 fn unchecked_suadd(&mut self, a: &'ll Value, b: &'ll Value) -> &'ll Value {
537 unsafe {
538 let add = llvm::LLVMBuildAdd(self.llbuilder, a, b, UNNAMED);
539 if llvm::LLVMIsAInstruction(add).is_some() {
540 llvm::LLVMSetNUW(add, TRUE);
541 llvm::LLVMSetNSW(add, TRUE);
542 }
543 add
544 }
545 }
546 fn unchecked_susub(&mut self, a: &'ll Value, b: &'ll Value) -> &'ll Value {
547 unsafe {
548 let sub = llvm::LLVMBuildSub(self.llbuilder, a, b, UNNAMED);
549 if llvm::LLVMIsAInstruction(sub).is_some() {
550 llvm::LLVMSetNUW(sub, TRUE);
551 llvm::LLVMSetNSW(sub, TRUE);
552 }
553 sub
554 }
555 }
556 fn unchecked_sumul(&mut self, a: &'ll Value, b: &'ll Value) -> &'ll Value {
557 unsafe {
558 let mul = llvm::LLVMBuildMul(self.llbuilder, a, b, UNNAMED);
559 if llvm::LLVMIsAInstruction(mul).is_some() {
560 llvm::LLVMSetNUW(mul, TRUE);
561 llvm::LLVMSetNSW(mul, TRUE);
562 }
563 mul
564 }
565 }
566
567 fn or_disjoint(&mut self, a: &'ll Value, b: &'ll Value) -> &'ll Value {
568 unsafe {
569 let or = llvm::LLVMBuildOr(self.llbuilder, a, b, UNNAMED);
570
571 if llvm::LLVMIsAInstruction(or).is_some() {
575 llvm::LLVMSetIsDisjoint(or, TRUE);
576 }
577 or
578 }
579 }
580
581 fn frem_algebraic(&mut self, x: &'ll Value, y: &'ll Value) -> &'ll Value {
unsafe {
let instr = llvm::LLVMBuildFRem(self.llbuilder, x, y, UNNAMED);
llvm::LLVMRustSetAlgebraicMath(instr);
instr
}
}set_math_builder_methods! {
582 fadd_fast(x, y) => (LLVMBuildFAdd, LLVMRustSetFastMath),
583 fsub_fast(x, y) => (LLVMBuildFSub, LLVMRustSetFastMath),
584 fmul_fast(x, y) => (LLVMBuildFMul, LLVMRustSetFastMath),
585 fdiv_fast(x, y) => (LLVMBuildFDiv, LLVMRustSetFastMath),
586 frem_fast(x, y) => (LLVMBuildFRem, LLVMRustSetFastMath),
587 fadd_algebraic(x, y) => (LLVMBuildFAdd, LLVMRustSetAlgebraicMath),
588 fsub_algebraic(x, y) => (LLVMBuildFSub, LLVMRustSetAlgebraicMath),
589 fmul_algebraic(x, y) => (LLVMBuildFMul, LLVMRustSetAlgebraicMath),
590 fdiv_algebraic(x, y) => (LLVMBuildFDiv, LLVMRustSetAlgebraicMath),
591 frem_algebraic(x, y) => (LLVMBuildFRem, LLVMRustSetAlgebraicMath),
592 }
593
594 fn checked_binop(
595 &mut self,
596 oop: OverflowOp,
597 ty: Ty<'tcx>,
598 lhs: Self::Value,
599 rhs: Self::Value,
600 ) -> (Self::Value, Self::Value) {
601 let (size, signed) = ty.int_size_and_signed(self.tcx);
602 let width = size.bits();
603
604 if !signed {
605 match oop {
606 OverflowOp::Sub => {
607 let sub = self.sub(lhs, rhs);
611 let cmp = self.icmp(IntPredicate::IntULT, lhs, rhs);
612 return (sub, cmp);
613 }
614 OverflowOp::Add => {
615 let add = self.add(lhs, rhs);
618 let cmp = self.icmp(IntPredicate::IntULT, add, lhs);
619 return (add, cmp);
620 }
621 OverflowOp::Mul => {}
622 }
623 }
624
625 let oop_str = match oop {
626 OverflowOp::Add => "add",
627 OverflowOp::Sub => "sub",
628 OverflowOp::Mul => "mul",
629 };
630
631 let name = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("llvm.{0}{1}.with.overflow",
if signed { 's' } else { 'u' }, oop_str))
})format!("llvm.{}{oop_str}.with.overflow", if signed { 's' } else { 'u' });
632
633 let res = self.call_intrinsic(name, &[self.type_ix(width)], &[lhs, rhs]);
634 (self.extract_value(res, 0), self.extract_value(res, 1))
635 }
636
637 fn from_immediate(&mut self, val: Self::Value) -> Self::Value {
638 if self.cx().val_ty(val) == self.cx().type_i1() {
639 self.zext(val, self.cx().type_i8())
640 } else {
641 val
642 }
643 }
644
645 fn to_immediate_scalar(&mut self, val: Self::Value, scalar: abi::Scalar) -> Self::Value {
646 if scalar.is_bool() {
647 return self.unchecked_utrunc(val, self.cx().type_i1());
648 }
649 val
650 }
651
652 fn alloca(&mut self, size: Size, align: Align) -> &'ll Value {
653 let mut bx = Builder::with_cx(self.cx);
654 bx.position_at_start(unsafe { llvm::LLVMGetFirstBasicBlock(self.llfn()) });
655 let ty = self.cx().type_array(self.cx().type_i8(), size.bytes());
656 unsafe {
657 let alloca = llvm::LLVMBuildAlloca(bx.llbuilder, ty, UNNAMED);
658 llvm::LLVMSetAlignment(alloca, align.bytes() as c_uint);
659 llvm::LLVMBuildPointerCast(bx.llbuilder, alloca, self.cx().type_ptr(), UNNAMED)
661 }
662 }
663
664 fn alloca_with_ty(&mut self, layout: TyAndLayout<'tcx>) -> Self::Value {
665 let mut bx = Builder::with_cx(self.cx);
666 bx.position_at_start(unsafe { llvm::LLVMGetFirstBasicBlock(self.llfn()) });
667 let scalable_vector_ty = layout.llvm_type(self.cx);
668
669 unsafe {
670 let alloca = llvm::LLVMBuildAlloca(&bx.llbuilder, scalable_vector_ty, UNNAMED);
671 llvm::LLVMSetAlignment(alloca, layout.align.abi.bytes() as c_uint);
672 alloca
673 }
674 }
675
676 fn load(&mut self, ty: &'ll Type, ptr: &'ll Value, align: Align) -> &'ll Value {
677 unsafe {
678 let load = llvm::LLVMBuildLoad2(self.llbuilder, ty, ptr, UNNAMED);
679 let align = align.min(self.cx().tcx.sess.target.max_reliable_alignment());
680 llvm::LLVMSetAlignment(load, align.bytes() as c_uint);
681 load
682 }
683 }
684
685 fn volatile_load(&mut self, ty: &'ll Type, ptr: &'ll Value) -> &'ll Value {
686 unsafe {
687 let load = llvm::LLVMBuildLoad2(self.llbuilder, ty, ptr, UNNAMED);
688 llvm::LLVMSetVolatile(load, llvm::TRUE);
689 load
690 }
691 }
692
693 fn atomic_load(
694 &mut self,
695 ty: &'ll Type,
696 ptr: &'ll Value,
697 order: rustc_middle::ty::AtomicOrdering,
698 size: Size,
699 ) -> &'ll Value {
700 unsafe {
701 let load = llvm::LLVMBuildLoad2(self.llbuilder, ty, ptr, UNNAMED);
702 llvm::LLVMSetOrdering(load, AtomicOrdering::from_generic(order));
704 llvm::LLVMSetAlignment(load, size.bytes() as c_uint);
706 load
707 }
708 }
709
710 #[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("load_operand",
"rustc_codegen_llvm::builder", ::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_llvm/src/builder.rs"),
::tracing_core::__macro_support::Option::Some(710u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::builder"),
::tracing_core::field::FieldSet::new(&["place"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::TRACE <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&place)
as &dyn Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: OperandRef<'tcx, &'ll Value> =
loop {};
return __tracing_attr_fake_return;
}
{
if place.layout.is_unsized() {
let tail =
self.tcx.struct_tail_for_codegen(place.layout.ty,
self.typing_env());
if #[allow(non_exhaustive_omitted_patterns)] match tail.kind()
{
ty::Foreign(..) => true,
_ => false,
} {
{
::core::panicking::panic_fmt(format_args!("unsized locals must not be `extern` types"));
};
}
}
match (&place.val.llextra.is_some(), &place.layout.is_unsized()) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
};
if place.layout.is_zst() {
return OperandRef::zero_sized(place.layout);
}
fn scalar_load_metadata<'a, 'll,
'tcx>(bx: &mut Builder<'a, 'll, 'tcx>, load: &'ll Value,
scalar: abi::Scalar, layout: TyAndLayout<'tcx>,
offset: Size) {
{}
#[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::TRACE <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("scalar_load_metadata",
"rustc_codegen_llvm::builder", ::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_llvm/src/builder.rs"),
::tracing_core::__macro_support::Option::Some(727u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::builder"),
::tracing_core::field::FieldSet::new(&["load", "scalar",
"layout", "offset"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::TRACE <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&load)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&scalar)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&layout)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&offset)
as &dyn Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy
:: needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: () = loop {};
return __tracing_attr_fake_return;
}
{
if bx.cx.sess().opts.optimize == OptLevel::No { return; }
if !scalar.is_uninit_valid() { bx.noundef_metadata(load); }
match scalar.primitive() {
abi::Primitive::Int(..) => {
if !scalar.is_always_valid(bx) {
bx.range_metadata(load, scalar.valid_range(bx));
}
}
abi::Primitive::Pointer(_) => {
if !scalar.valid_range(bx).contains(0) {
bx.nonnull_metadata(load);
}
if let Some(pointee) = layout.pointee_info_at(bx, offset) &&
pointee.align > Align::ONE {
bx.align_metadata(load, pointee.align);
}
}
abi::Primitive::Float(_) => {}
}
}
}
}
}
let val =
if let Some(_) = place.val.llextra {
OperandValue::Ref(place.val)
} else if place.layout.is_llvm_immediate() {
let mut const_llval = None;
let llty = place.layout.llvm_type(self);
if let Some(global) =
llvm::LLVMIsAGlobalVariable(place.val.llval) {
if llvm::LLVMIsGlobalConstant(global).is_true() {
if let Some(init) = llvm::LLVMGetInitializer(global) {
if self.val_ty(init) == llty { const_llval = Some(init); }
}
}
}
let llval =
const_llval.unwrap_or_else(||
{
let load =
self.load(llty, place.val.llval, place.val.align);
if let abi::BackendRepr::Scalar(scalar) =
place.layout.backend_repr {
scalar_load_metadata(self, load, scalar, place.layout,
Size::ZERO);
self.to_immediate_scalar(load, scalar)
} else { load }
});
OperandValue::Immediate(llval)
} else if let abi::BackendRepr::ScalarPair(a, b) =
place.layout.backend_repr {
let b_offset = a.size(self).align_to(b.align(self).abi);
let mut load =
|i, scalar: abi::Scalar, layout, align, offset|
{
let llptr =
if i == 0 {
place.val.llval
} else {
self.inbounds_ptradd(place.val.llval,
self.const_usize(b_offset.bytes()))
};
let llty =
place.layout.scalar_pair_element_llvm_type(self, i, false);
let load = self.load(llty, llptr, align);
scalar_load_metadata(self, load, scalar, layout, offset);
self.to_immediate_scalar(load, scalar)
};
OperandValue::Pair(load(0, a, place.layout, place.val.align,
Size::ZERO),
load(1, b, place.layout,
place.val.align.restrict_for_offset(b_offset), b_offset))
} else { OperandValue::Ref(place.val) };
OperandRef { val, layout: place.layout, move_annotation: None }
}
}
}#[instrument(level = "trace", skip(self))]
711 fn load_operand(&mut self, place: PlaceRef<'tcx, &'ll Value>) -> OperandRef<'tcx, &'ll Value> {
712 if place.layout.is_unsized() {
713 let tail = self.tcx.struct_tail_for_codegen(place.layout.ty, self.typing_env());
714 if matches!(tail.kind(), ty::Foreign(..)) {
715 panic!("unsized locals must not be `extern` types");
719 }
720 }
721 assert_eq!(place.val.llextra.is_some(), place.layout.is_unsized());
722
723 if place.layout.is_zst() {
724 return OperandRef::zero_sized(place.layout);
725 }
726
727 #[instrument(level = "trace", skip(bx))]
728 fn scalar_load_metadata<'a, 'll, 'tcx>(
729 bx: &mut Builder<'a, 'll, 'tcx>,
730 load: &'ll Value,
731 scalar: abi::Scalar,
732 layout: TyAndLayout<'tcx>,
733 offset: Size,
734 ) {
735 if bx.cx.sess().opts.optimize == OptLevel::No {
736 return;
738 }
739
740 if !scalar.is_uninit_valid() {
741 bx.noundef_metadata(load);
742 }
743
744 match scalar.primitive() {
745 abi::Primitive::Int(..) => {
746 if !scalar.is_always_valid(bx) {
747 bx.range_metadata(load, scalar.valid_range(bx));
748 }
749 }
750 abi::Primitive::Pointer(_) => {
751 if !scalar.valid_range(bx).contains(0) {
752 bx.nonnull_metadata(load);
753 }
754
755 if let Some(pointee) = layout.pointee_info_at(bx, offset)
756 && pointee.align > Align::ONE
757 {
758 bx.align_metadata(load, pointee.align);
759 }
760 }
761 abi::Primitive::Float(_) => {}
762 }
763 }
764
765 let val = if let Some(_) = place.val.llextra {
766 OperandValue::Ref(place.val)
768 } else if place.layout.is_llvm_immediate() {
769 let mut const_llval = None;
770 let llty = place.layout.llvm_type(self);
771 if let Some(global) = llvm::LLVMIsAGlobalVariable(place.val.llval) {
772 if llvm::LLVMIsGlobalConstant(global).is_true() {
773 if let Some(init) = llvm::LLVMGetInitializer(global) {
774 if self.val_ty(init) == llty {
775 const_llval = Some(init);
776 }
777 }
778 }
779 }
780
781 let llval = const_llval.unwrap_or_else(|| {
782 let load = self.load(llty, place.val.llval, place.val.align);
783 if let abi::BackendRepr::Scalar(scalar) = place.layout.backend_repr {
784 scalar_load_metadata(self, load, scalar, place.layout, Size::ZERO);
785 self.to_immediate_scalar(load, scalar)
786 } else {
787 load
788 }
789 });
790 OperandValue::Immediate(llval)
791 } else if let abi::BackendRepr::ScalarPair(a, b) = place.layout.backend_repr {
792 let b_offset = a.size(self).align_to(b.align(self).abi);
793
794 let mut load = |i, scalar: abi::Scalar, layout, align, offset| {
795 let llptr = if i == 0 {
796 place.val.llval
797 } else {
798 self.inbounds_ptradd(place.val.llval, self.const_usize(b_offset.bytes()))
799 };
800 let llty = place.layout.scalar_pair_element_llvm_type(self, i, false);
801 let load = self.load(llty, llptr, align);
802 scalar_load_metadata(self, load, scalar, layout, offset);
803 self.to_immediate_scalar(load, scalar)
804 };
805
806 OperandValue::Pair(
807 load(0, a, place.layout, place.val.align, Size::ZERO),
808 load(1, b, place.layout, place.val.align.restrict_for_offset(b_offset), b_offset),
809 )
810 } else {
811 OperandValue::Ref(place.val)
812 };
813
814 OperandRef { val, layout: place.layout, move_annotation: None }
815 }
816
817 fn write_operand_repeatedly(
818 &mut self,
819 cg_elem: OperandRef<'tcx, &'ll Value>,
820 count: u64,
821 dest: PlaceRef<'tcx, &'ll Value>,
822 ) {
823 if self.cx.sess().opts.optimize == OptLevel::No {
824 self.write_operand_repeatedly_unoptimized(cg_elem, count, dest);
832 } else {
833 self.write_operand_repeatedly_optimized(cg_elem, count, dest);
834 }
835 }
836
837 fn range_metadata(&mut self, load: &'ll Value, range: WrappingRange) {
838 if self.cx.sess().opts.optimize == OptLevel::No {
839 return;
841 }
842
843 let llty = self.cx.val_ty(load);
844 let md = [
845 llvm::LLVMValueAsMetadata(self.cx.const_uint_big(llty, range.start)),
846 llvm::LLVMValueAsMetadata(self.cx.const_uint_big(llty, range.end.wrapping_add(1))),
847 ];
848 self.set_metadata_node(load, llvm::MD_range, &md);
849 }
850
851 fn nonnull_metadata(&mut self, load: &'ll Value) {
852 self.set_metadata_node(load, llvm::MD_nonnull, &[]);
853 }
854
855 fn store(&mut self, val: &'ll Value, ptr: &'ll Value, align: Align) -> &'ll Value {
856 self.store_with_flags(val, ptr, align, MemFlags::empty())
857 }
858
859 fn store_with_flags(
860 &mut self,
861 val: &'ll Value,
862 ptr: &'ll Value,
863 align: Align,
864 flags: MemFlags,
865 ) -> &'ll Value {
866 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_llvm/src/builder.rs:866",
"rustc_codegen_llvm::builder", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_llvm/src/builder.rs"),
::tracing_core::__macro_support::Option::Some(866u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::builder"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("Store {0:?} -> {1:?} ({2:?})",
val, ptr, flags) as &dyn Value))])
});
} else { ; }
};debug!("Store {:?} -> {:?} ({:?})", val, ptr, flags);
867 match (&self.cx.type_kind(self.cx.val_ty(ptr)), &TypeKind::Pointer) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val, &*right_val,
::core::option::Option::None);
}
}
};assert_eq!(self.cx.type_kind(self.cx.val_ty(ptr)), TypeKind::Pointer);
868 unsafe {
869 let store = llvm::LLVMBuildStore(self.llbuilder, val, ptr);
870 let align = align.min(self.cx().tcx.sess.target.max_reliable_alignment());
871 let align =
872 if flags.contains(MemFlags::UNALIGNED) { 1 } else { align.bytes() as c_uint };
873 llvm::LLVMSetAlignment(store, align);
874 if flags.contains(MemFlags::VOLATILE) {
875 llvm::LLVMSetVolatile(store, llvm::TRUE);
876 }
877 if flags.contains(MemFlags::NONTEMPORAL) {
878 let use_nontemporal = #[allow(non_exhaustive_omitted_patterns)] match self.cx.tcx.sess.target.arch {
Arch::AArch64 | Arch::Arm | Arch::RiscV32 | Arch::RiscV64 => true,
_ => false,
}matches!(
891 self.cx.tcx.sess.target.arch,
892 Arch::AArch64 | Arch::Arm | Arch::RiscV32 | Arch::RiscV64
893 );
894 if use_nontemporal {
895 let one = llvm::LLVMValueAsMetadata(self.cx.const_i32(1));
900 self.set_metadata_node(store, llvm::MD_nontemporal, &[one]);
901 }
902 }
903 if flags.contains(MemFlags::CAPTURES_READ_ONLY)
904 && crate::llvm_util::get_version() >= (22, 0, 0)
905 {
906 if !(self.type_kind(self.val_ty(val)) == TypeKind::Pointer) {
{
::core::panicking::panic_fmt(format_args!("CAPTURED_READ_ONLY is only supported on pointer stores"));
}
};assert!(
907 self.type_kind(self.val_ty(val)) == TypeKind::Pointer,
908 "CAPTURED_READ_ONLY is only supported on pointer stores"
909 );
910 let args = [
911 self.cx.create_metadata(b"address"),
912 self.cx.create_metadata(b"read_provenance"),
913 ];
914 let id = self.get_md_kind_id("captures");
916 let md = llvm::LLVMMDNodeInContext2(self.cx.llcx, args.as_ptr(), args.len());
917 self.set_metadata(store, id, md);
918 }
919 store
920 }
921 }
922
923 fn atomic_store(
924 &mut self,
925 val: &'ll Value,
926 ptr: &'ll Value,
927 order: rustc_middle::ty::AtomicOrdering,
928 size: Size,
929 ) {
930 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_llvm/src/builder.rs:930",
"rustc_codegen_llvm::builder", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_llvm/src/builder.rs"),
::tracing_core::__macro_support::Option::Some(930u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::builder"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("Store {0:?} -> {1:?}",
val, ptr) as &dyn Value))])
});
} else { ; }
};debug!("Store {:?} -> {:?}", val, ptr);
931 match (&self.cx.type_kind(self.cx.val_ty(ptr)), &TypeKind::Pointer) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val, &*right_val,
::core::option::Option::None);
}
}
};assert_eq!(self.cx.type_kind(self.cx.val_ty(ptr)), TypeKind::Pointer);
932 unsafe {
933 let store = llvm::LLVMBuildStore(self.llbuilder, val, ptr);
934 llvm::LLVMSetOrdering(store, AtomicOrdering::from_generic(order));
936 llvm::LLVMSetAlignment(store, size.bytes() as c_uint);
938 }
939 }
940
941 fn gep(&mut self, ty: &'ll Type, ptr: &'ll Value, indices: &[&'ll Value]) -> &'ll Value {
942 unsafe {
943 llvm::LLVMBuildGEPWithNoWrapFlags(
944 self.llbuilder,
945 ty,
946 ptr,
947 indices.as_ptr(),
948 indices.len() as c_uint,
949 UNNAMED,
950 GEPNoWrapFlags::default(),
951 )
952 }
953 }
954
955 fn inbounds_gep(
956 &mut self,
957 ty: &'ll Type,
958 ptr: &'ll Value,
959 indices: &[&'ll Value],
960 ) -> &'ll Value {
961 unsafe {
962 llvm::LLVMBuildGEPWithNoWrapFlags(
963 self.llbuilder,
964 ty,
965 ptr,
966 indices.as_ptr(),
967 indices.len() as c_uint,
968 UNNAMED,
969 GEPNoWrapFlags::InBounds,
970 )
971 }
972 }
973
974 fn inbounds_nuw_gep(
975 &mut self,
976 ty: &'ll Type,
977 ptr: &'ll Value,
978 indices: &[&'ll Value],
979 ) -> &'ll Value {
980 unsafe {
981 llvm::LLVMBuildGEPWithNoWrapFlags(
982 self.llbuilder,
983 ty,
984 ptr,
985 indices.as_ptr(),
986 indices.len() as c_uint,
987 UNNAMED,
988 GEPNoWrapFlags::InBounds | GEPNoWrapFlags::NUW,
989 )
990 }
991 }
992
993 fn trunc(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
995 unsafe { llvm::LLVMBuildTrunc(self.llbuilder, val, dest_ty, UNNAMED) }
996 }
997
998 fn unchecked_utrunc(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
999 if true {
match (&self.val_ty(val), &dest_ty) {
(left_val, right_val) => {
if *left_val == *right_val {
let kind = ::core::panicking::AssertKind::Ne;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
};
};debug_assert_ne!(self.val_ty(val), dest_ty);
1000
1001 let trunc = self.trunc(val, dest_ty);
1002 unsafe {
1003 if llvm::LLVMIsAInstruction(trunc).is_some() {
1004 llvm::LLVMSetNUW(trunc, TRUE);
1005 }
1006 }
1007 trunc
1008 }
1009
1010 fn unchecked_strunc(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1011 if true {
match (&self.val_ty(val), &dest_ty) {
(left_val, right_val) => {
if *left_val == *right_val {
let kind = ::core::panicking::AssertKind::Ne;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
};
};debug_assert_ne!(self.val_ty(val), dest_ty);
1012
1013 let trunc = self.trunc(val, dest_ty);
1014 unsafe {
1015 if llvm::LLVMIsAInstruction(trunc).is_some() {
1016 llvm::LLVMSetNSW(trunc, TRUE);
1017 }
1018 }
1019 trunc
1020 }
1021
1022 fn sext(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1023 unsafe { llvm::LLVMBuildSExt(self.llbuilder, val, dest_ty, UNNAMED) }
1024 }
1025
1026 fn fptoui_sat(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1027 self.call_intrinsic("llvm.fptoui.sat", &[dest_ty, self.val_ty(val)], &[val])
1028 }
1029
1030 fn fptosi_sat(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1031 self.call_intrinsic("llvm.fptosi.sat", &[dest_ty, self.val_ty(val)], &[val])
1032 }
1033
1034 fn fptoui(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1035 if self.sess().target.is_like_wasm {
1050 let src_ty = self.cx.val_ty(val);
1051 if self.cx.type_kind(src_ty) != TypeKind::Vector {
1052 let float_width = self.cx.float_width(src_ty);
1053 let int_width = self.cx.int_width(dest_ty);
1054 if #[allow(non_exhaustive_omitted_patterns)] match (int_width, float_width) {
(32 | 64, 32 | 64) => true,
_ => false,
}matches!((int_width, float_width), (32 | 64, 32 | 64)) {
1055 return self.call_intrinsic(
1056 "llvm.wasm.trunc.unsigned",
1057 &[dest_ty, src_ty],
1058 &[val],
1059 );
1060 }
1061 }
1062 }
1063 unsafe { llvm::LLVMBuildFPToUI(self.llbuilder, val, dest_ty, UNNAMED) }
1064 }
1065
1066 fn fptosi(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1067 if self.sess().target.is_like_wasm {
1069 let src_ty = self.cx.val_ty(val);
1070 if self.cx.type_kind(src_ty) != TypeKind::Vector {
1071 let float_width = self.cx.float_width(src_ty);
1072 let int_width = self.cx.int_width(dest_ty);
1073 if #[allow(non_exhaustive_omitted_patterns)] match (int_width, float_width) {
(32 | 64, 32 | 64) => true,
_ => false,
}matches!((int_width, float_width), (32 | 64, 32 | 64)) {
1074 return self.call_intrinsic(
1075 "llvm.wasm.trunc.signed",
1076 &[dest_ty, src_ty],
1077 &[val],
1078 );
1079 }
1080 }
1081 }
1082 unsafe { llvm::LLVMBuildFPToSI(self.llbuilder, val, dest_ty, UNNAMED) }
1083 }
1084
1085 fn uitofp(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1086 unsafe { llvm::LLVMBuildUIToFP(self.llbuilder, val, dest_ty, UNNAMED) }
1087 }
1088
1089 fn sitofp(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1090 unsafe { llvm::LLVMBuildSIToFP(self.llbuilder, val, dest_ty, UNNAMED) }
1091 }
1092
1093 fn fptrunc(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1094 unsafe { llvm::LLVMBuildFPTrunc(self.llbuilder, val, dest_ty, UNNAMED) }
1095 }
1096
1097 fn fpext(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1098 unsafe { llvm::LLVMBuildFPExt(self.llbuilder, val, dest_ty, UNNAMED) }
1099 }
1100
1101 fn ptrtoint(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1102 unsafe { llvm::LLVMBuildPtrToInt(self.llbuilder, val, dest_ty, UNNAMED) }
1103 }
1104
1105 fn inttoptr(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1106 unsafe { llvm::LLVMBuildIntToPtr(self.llbuilder, val, dest_ty, UNNAMED) }
1107 }
1108
1109 fn bitcast(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1110 unsafe { llvm::LLVMBuildBitCast(self.llbuilder, val, dest_ty, UNNAMED) }
1111 }
1112
1113 fn intcast(&mut self, val: &'ll Value, dest_ty: &'ll Type, is_signed: bool) -> &'ll Value {
1114 unsafe {
1115 llvm::LLVMBuildIntCast2(self.llbuilder, val, dest_ty, is_signed.to_llvm_bool(), UNNAMED)
1116 }
1117 }
1118
1119 fn pointercast(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1120 unsafe { llvm::LLVMBuildPointerCast(self.llbuilder, val, dest_ty, UNNAMED) }
1121 }
1122
1123 fn icmp(&mut self, op: IntPredicate, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
1125 let op = llvm::IntPredicate::from_generic(op);
1126 unsafe { llvm::LLVMBuildICmp(self.llbuilder, op as c_uint, lhs, rhs, UNNAMED) }
1127 }
1128
1129 fn fcmp(&mut self, op: RealPredicate, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
1130 let op = llvm::RealPredicate::from_generic(op);
1131 unsafe { llvm::LLVMBuildFCmp(self.llbuilder, op as c_uint, lhs, rhs, UNNAMED) }
1132 }
1133
1134 fn three_way_compare(
1135 &mut self,
1136 ty: Ty<'tcx>,
1137 lhs: Self::Value,
1138 rhs: Self::Value,
1139 ) -> Self::Value {
1140 let size = ty.primitive_size(self.tcx);
1141 let name = if ty.is_signed() { "llvm.scmp" } else { "llvm.ucmp" };
1142
1143 self.call_intrinsic(name, &[self.type_i8(), self.type_ix(size.bits())], &[lhs, rhs])
1144 }
1145
1146 fn memcpy(
1148 &mut self,
1149 dst: &'ll Value,
1150 dst_align: Align,
1151 src: &'ll Value,
1152 src_align: Align,
1153 size: &'ll Value,
1154 flags: MemFlags,
1155 tt: Option<FncTree>,
1156 ) {
1157 if !!flags.contains(MemFlags::NONTEMPORAL) {
{
::core::panicking::panic_fmt(format_args!("non-temporal memcpy not supported"));
}
};assert!(!flags.contains(MemFlags::NONTEMPORAL), "non-temporal memcpy not supported");
1158 let size = self.intcast(size, self.type_isize(), false);
1159 let is_volatile = flags.contains(MemFlags::VOLATILE);
1160 let memcpy = unsafe {
1161 llvm::LLVMRustBuildMemCpy(
1162 self.llbuilder,
1163 dst,
1164 dst_align.bytes() as c_uint,
1165 src,
1166 src_align.bytes() as c_uint,
1167 size,
1168 is_volatile,
1169 )
1170 };
1171
1172 if let Some(tt) = tt {
1178 crate::typetree::add_tt(self.cx().llmod, self.cx().llcx, memcpy, tt);
1179 }
1180 }
1181
1182 fn memmove(
1183 &mut self,
1184 dst: &'ll Value,
1185 dst_align: Align,
1186 src: &'ll Value,
1187 src_align: Align,
1188 size: &'ll Value,
1189 flags: MemFlags,
1190 ) {
1191 if !!flags.contains(MemFlags::NONTEMPORAL) {
{
::core::panicking::panic_fmt(format_args!("non-temporal memmove not supported"));
}
};assert!(!flags.contains(MemFlags::NONTEMPORAL), "non-temporal memmove not supported");
1192 let size = self.intcast(size, self.type_isize(), false);
1193 let is_volatile = flags.contains(MemFlags::VOLATILE);
1194 unsafe {
1195 llvm::LLVMRustBuildMemMove(
1196 self.llbuilder,
1197 dst,
1198 dst_align.bytes() as c_uint,
1199 src,
1200 src_align.bytes() as c_uint,
1201 size,
1202 is_volatile,
1203 );
1204 }
1205 }
1206
1207 fn memset(
1208 &mut self,
1209 ptr: &'ll Value,
1210 fill_byte: &'ll Value,
1211 size: &'ll Value,
1212 align: Align,
1213 flags: MemFlags,
1214 ) {
1215 if !!flags.contains(MemFlags::NONTEMPORAL) {
{
::core::panicking::panic_fmt(format_args!("non-temporal memset not supported"));
}
};assert!(!flags.contains(MemFlags::NONTEMPORAL), "non-temporal memset not supported");
1216 let is_volatile = flags.contains(MemFlags::VOLATILE);
1217 unsafe {
1218 llvm::LLVMRustBuildMemSet(
1219 self.llbuilder,
1220 ptr,
1221 align.bytes() as c_uint,
1222 fill_byte,
1223 size,
1224 is_volatile,
1225 );
1226 }
1227 }
1228
1229 fn select(
1230 &mut self,
1231 cond: &'ll Value,
1232 then_val: &'ll Value,
1233 else_val: &'ll Value,
1234 ) -> &'ll Value {
1235 unsafe { llvm::LLVMBuildSelect(self.llbuilder, cond, then_val, else_val, UNNAMED) }
1236 }
1237
1238 fn va_arg(&mut self, list: &'ll Value, ty: &'ll Type) -> &'ll Value {
1239 unsafe { llvm::LLVMBuildVAArg(self.llbuilder, list, ty, UNNAMED) }
1240 }
1241
1242 fn extract_element(&mut self, vec: &'ll Value, idx: &'ll Value) -> &'ll Value {
1243 unsafe { llvm::LLVMBuildExtractElement(self.llbuilder, vec, idx, UNNAMED) }
1244 }
1245
1246 fn vector_splat(&mut self, num_elts: usize, elt: &'ll Value) -> &'ll Value {
1247 unsafe {
1248 let elt_ty = self.cx.val_ty(elt);
1249 let undef = llvm::LLVMGetUndef(self.type_vector(elt_ty, num_elts as u64));
1250 let vec = self.insert_element(undef, elt, self.cx.const_i32(0));
1251 let vec_i32_ty = self.type_vector(self.type_i32(), num_elts as u64);
1252 self.shuffle_vector(vec, undef, self.const_null(vec_i32_ty))
1253 }
1254 }
1255
1256 fn extract_value(&mut self, agg_val: &'ll Value, idx: u64) -> &'ll Value {
1257 match (&(idx as c_uint as u64), &idx) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val, &*right_val,
::core::option::Option::None);
}
}
};assert_eq!(idx as c_uint as u64, idx);
1258 unsafe { llvm::LLVMBuildExtractValue(self.llbuilder, agg_val, idx as c_uint, UNNAMED) }
1259 }
1260
1261 fn insert_value(&mut self, agg_val: &'ll Value, elt: &'ll Value, idx: u64) -> &'ll Value {
1262 match (&(idx as c_uint as u64), &idx) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val, &*right_val,
::core::option::Option::None);
}
}
};assert_eq!(idx as c_uint as u64, idx);
1263 unsafe { llvm::LLVMBuildInsertValue(self.llbuilder, agg_val, elt, idx as c_uint, UNNAMED) }
1264 }
1265
1266 fn set_personality_fn(&mut self, personality: &'ll Value) {
1267 unsafe {
1268 llvm::LLVMSetPersonalityFn(self.llfn(), personality);
1269 }
1270 }
1271
1272 fn cleanup_landing_pad(&mut self, pers_fn: &'ll Value) -> (&'ll Value, &'ll Value) {
1273 let ty = self.type_struct(&[self.type_ptr(), self.type_i32()], false);
1274 let landing_pad = self.landing_pad(ty, pers_fn, 0);
1275 unsafe {
1276 llvm::LLVMSetCleanup(landing_pad, llvm::TRUE);
1277 }
1278 (self.extract_value(landing_pad, 0), self.extract_value(landing_pad, 1))
1279 }
1280
1281 fn filter_landing_pad(&mut self, pers_fn: &'ll Value) {
1282 let ty = self.type_struct(&[self.type_ptr(), self.type_i32()], false);
1283 let landing_pad = self.landing_pad(ty, pers_fn, 1);
1284 self.add_clause(landing_pad, self.const_array(self.type_ptr(), &[]));
1285 }
1286
1287 fn resume(&mut self, exn0: &'ll Value, exn1: &'ll Value) {
1288 let ty = self.type_struct(&[self.type_ptr(), self.type_i32()], false);
1289 let mut exn = self.const_poison(ty);
1290 exn = self.insert_value(exn, exn0, 0);
1291 exn = self.insert_value(exn, exn1, 1);
1292 unsafe {
1293 llvm::LLVMBuildResume(self.llbuilder, exn);
1294 }
1295 }
1296
1297 fn cleanup_pad(&mut self, parent: Option<&'ll Value>, args: &[&'ll Value]) -> Funclet<'ll> {
1298 let ret = unsafe {
1299 llvm::LLVMBuildCleanupPad(
1300 self.llbuilder,
1301 parent,
1302 args.as_ptr(),
1303 args.len() as c_uint,
1304 c"cleanuppad".as_ptr(),
1305 )
1306 };
1307 Funclet::new(ret.expect("LLVM does not have support for cleanuppad"))
1308 }
1309
1310 fn cleanup_ret(&mut self, funclet: &Funclet<'ll>, unwind: Option<&'ll BasicBlock>) {
1311 unsafe {
1312 llvm::LLVMBuildCleanupRet(self.llbuilder, funclet.cleanuppad(), unwind)
1313 .expect("LLVM does not have support for cleanupret");
1314 }
1315 }
1316
1317 fn catch_pad(&mut self, parent: &'ll Value, args: &[&'ll Value]) -> Funclet<'ll> {
1318 let ret = unsafe {
1319 llvm::LLVMBuildCatchPad(
1320 self.llbuilder,
1321 parent,
1322 args.as_ptr(),
1323 args.len() as c_uint,
1324 c"catchpad".as_ptr(),
1325 )
1326 };
1327 Funclet::new(ret.expect("LLVM does not have support for catchpad"))
1328 }
1329
1330 fn catch_switch(
1331 &mut self,
1332 parent: Option<&'ll Value>,
1333 unwind: Option<&'ll BasicBlock>,
1334 handlers: &[&'ll BasicBlock],
1335 ) -> &'ll Value {
1336 let ret = unsafe {
1337 llvm::LLVMBuildCatchSwitch(
1338 self.llbuilder,
1339 parent,
1340 unwind,
1341 handlers.len() as c_uint,
1342 c"catchswitch".as_ptr(),
1343 )
1344 };
1345 let ret = ret.expect("LLVM does not have support for catchswitch");
1346 for handler in handlers {
1347 unsafe {
1348 llvm::LLVMAddHandler(ret, handler);
1349 }
1350 }
1351 ret
1352 }
1353
1354 fn get_funclet_cleanuppad(&self, funclet: &Funclet<'ll>) -> &'ll Value {
1355 funclet.cleanuppad()
1356 }
1357
1358 fn atomic_cmpxchg(
1360 &mut self,
1361 dst: &'ll Value,
1362 cmp: &'ll Value,
1363 src: &'ll Value,
1364 order: rustc_middle::ty::AtomicOrdering,
1365 failure_order: rustc_middle::ty::AtomicOrdering,
1366 weak: bool,
1367 ) -> (&'ll Value, &'ll Value) {
1368 unsafe {
1369 let value = llvm::LLVMBuildAtomicCmpXchg(
1370 self.llbuilder,
1371 dst,
1372 cmp,
1373 src,
1374 AtomicOrdering::from_generic(order),
1375 AtomicOrdering::from_generic(failure_order),
1376 llvm::FALSE, );
1378 llvm::LLVMSetWeak(value, weak.to_llvm_bool());
1379 let val = self.extract_value(value, 0);
1380 let success = self.extract_value(value, 1);
1381 (val, success)
1382 }
1383 }
1384
1385 fn atomic_rmw(
1386 &mut self,
1387 op: rustc_codegen_ssa::common::AtomicRmwBinOp,
1388 dst: &'ll Value,
1389 src: &'ll Value,
1390 order: rustc_middle::ty::AtomicOrdering,
1391 ret_ptr: bool,
1392 ) -> &'ll Value {
1393 let mut res = unsafe {
1397 llvm::LLVMBuildAtomicRMW(
1398 self.llbuilder,
1399 AtomicRmwBinOp::from_generic(op),
1400 dst,
1401 src,
1402 AtomicOrdering::from_generic(order),
1403 llvm::FALSE, )
1405 };
1406 if ret_ptr && self.val_ty(res) != self.type_ptr() {
1407 res = self.inttoptr(res, self.type_ptr());
1408 }
1409 res
1410 }
1411
1412 fn atomic_fence(
1413 &mut self,
1414 order: rustc_middle::ty::AtomicOrdering,
1415 scope: SynchronizationScope,
1416 ) {
1417 let single_threaded = match scope {
1418 SynchronizationScope::SingleThread => true,
1419 SynchronizationScope::CrossThread => false,
1420 };
1421 unsafe {
1422 llvm::LLVMBuildFence(
1423 self.llbuilder,
1424 AtomicOrdering::from_generic(order),
1425 single_threaded.to_llvm_bool(),
1426 UNNAMED,
1427 );
1428 }
1429 }
1430
1431 fn set_invariant_load(&mut self, load: &'ll Value) {
1432 self.set_metadata_node(load, llvm::MD_invariant_load, &[]);
1433 }
1434
1435 fn lifetime_start(&mut self, ptr: &'ll Value, size: Size) {
1436 self.call_lifetime_intrinsic("llvm.lifetime.start", ptr, size);
1437 }
1438
1439 fn lifetime_end(&mut self, ptr: &'ll Value, size: Size) {
1440 self.call_lifetime_intrinsic("llvm.lifetime.end", ptr, size);
1441 }
1442
1443 fn call(
1444 &mut self,
1445 llty: &'ll Type,
1446 caller_attrs: Option<&CodegenFnAttrs>,
1447 fn_abi: Option<&FnAbi<'tcx, Ty<'tcx>>>,
1448 llfn: &'ll Value,
1449 args: &[&'ll Value],
1450 funclet: Option<&Funclet<'ll>>,
1451 callee_instance: Option<Instance<'tcx>>,
1452 ) -> &'ll Value {
1453 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_llvm/src/builder.rs:1453",
"rustc_codegen_llvm::builder", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_llvm/src/builder.rs"),
::tracing_core::__macro_support::Option::Some(1453u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::builder"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("call {0:?} with args ({1:?})",
llfn, args) as &dyn Value))])
});
} else { ; }
};debug!("call {:?} with args ({:?})", llfn, args);
1454
1455 let args = self.check_call("call", llty, llfn, args);
1456 let funclet_bundle = funclet.map(|funclet| funclet.bundle());
1457 let mut bundles: SmallVec<[_; 2]> = SmallVec::new();
1458 if let Some(funclet_bundle) = funclet_bundle {
1459 bundles.push(funclet_bundle);
1460 }
1461
1462 self.cfi_type_test(caller_attrs, fn_abi, callee_instance, llfn);
1464
1465 let kcfi_bundle = self.kcfi_operand_bundle(caller_attrs, fn_abi, callee_instance, llfn);
1467 if let Some(kcfi_bundle) = kcfi_bundle.as_ref().map(|b| b.as_ref()) {
1468 bundles.push(kcfi_bundle);
1469 }
1470
1471 let call = unsafe {
1472 llvm::LLVMBuildCallWithOperandBundles(
1473 self.llbuilder,
1474 llty,
1475 llfn,
1476 args.as_ptr() as *const &llvm::Value,
1477 args.len() as c_uint,
1478 bundles.as_ptr(),
1479 bundles.len() as c_uint,
1480 c"".as_ptr(),
1481 )
1482 };
1483
1484 if let Some(callee_instance) = callee_instance {
1485 let callee_attrs = self.cx.tcx.codegen_fn_attrs(callee_instance.def_id());
1487
1488 if let Some(inlining_rule) =
1489 attributes::inline_attr(&self.cx, self.cx.tcx, callee_instance, callee_attrs)
1490 {
1491 attributes::apply_to_callsite(
1492 call,
1493 llvm::AttributePlace::Function,
1494 &[inlining_rule],
1495 );
1496 }
1497 }
1498
1499 if let Some(fn_abi) = fn_abi {
1500 fn_abi.apply_attrs_callsite(self, call);
1501 }
1502 call
1503 }
1504
1505 fn tail_call(
1506 &mut self,
1507 llty: Self::Type,
1508 caller_attrs: Option<&CodegenFnAttrs>,
1509 fn_abi: &FnAbi<'tcx, Ty<'tcx>>,
1510 llfn: Self::Value,
1511 args: &[Self::Value],
1512 funclet: Option<&Self::Funclet>,
1513 callee_instance: Option<Instance<'tcx>>,
1514 ) {
1515 let call =
1516 self.call(llty, caller_attrs, Some(fn_abi), llfn, args, funclet, callee_instance);
1517 llvm::LLVMSetTailCallKind(call, llvm::TailCallKind::MustTail);
1518
1519 match &fn_abi.ret.mode {
1520 PassMode::Ignore | PassMode::Indirect { .. } => self.ret_void(),
1521 PassMode::Direct(_) | PassMode::Pair { .. } | PassMode::Cast { .. } => self.ret(call),
1522 }
1523 }
1524
1525 fn zext(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {
1526 unsafe { llvm::LLVMBuildZExt(self.llbuilder, val, dest_ty, UNNAMED) }
1527 }
1528
1529 fn apply_attrs_to_cleanup_callsite(&mut self, llret: &'ll Value) {
1530 let cold_inline = llvm::AttributeKind::Cold.create_attr(self.llcx);
1532 attributes::apply_to_callsite(llret, llvm::AttributePlace::Function, &[cold_inline]);
1533 }
1534}
1535
1536impl<'ll> StaticBuilderMethods for Builder<'_, 'll, '_> {
1537 fn get_static(&mut self, def_id: DefId) -> &'ll Value {
1538 let global = self.cx().get_static(def_id);
1540 if self.cx().tcx.is_thread_local_static(def_id) {
1541 let pointer =
1542 self.call_intrinsic("llvm.threadlocal.address", &[self.val_ty(global)], &[global]);
1543 self.pointercast(pointer, self.type_ptr())
1545 } else {
1546 self.cx().const_pointercast(global, self.type_ptr())
1548 }
1549 }
1550}
1551
1552impl<'a, 'll, 'tcx> Builder<'a, 'll, 'tcx> {
1553 pub(crate) fn llfn(&self) -> &'ll Value {
1554 unsafe { llvm::LLVMGetBasicBlockParent(self.llbb()) }
1555 }
1556}
1557
1558impl<'a, 'll, CX: Borrow<SCx<'ll>>> GenericBuilder<'a, 'll, CX> {
1559 fn position_at_start(&mut self, llbb: &'ll BasicBlock) {
1560 unsafe {
1561 llvm::LLVMRustPositionBuilderAtStart(self.llbuilder, llbb);
1562 }
1563 }
1564}
1565impl<'a, 'll, 'tcx> Builder<'a, 'll, 'tcx> {
1566 fn align_metadata(&mut self, load: &'ll Value, align: Align) {
1567 let md = [llvm::LLVMValueAsMetadata(self.cx.const_u64(align.bytes()))];
1568 self.set_metadata_node(load, llvm::MD_align, &md);
1569 }
1570
1571 fn noundef_metadata(&mut self, load: &'ll Value) {
1572 self.set_metadata_node(load, llvm::MD_noundef, &[]);
1573 }
1574
1575 pub(crate) fn set_unpredictable(&mut self, inst: &'ll Value) {
1576 self.set_metadata_node(inst, llvm::MD_unpredictable, &[]);
1577 }
1578
1579 fn write_operand_repeatedly_optimized(
1580 &mut self,
1581 cg_elem: OperandRef<'tcx, &'ll Value>,
1582 count: u64,
1583 dest: PlaceRef<'tcx, &'ll Value>,
1584 ) {
1585 let zero = self.const_usize(0);
1586 let count = self.const_usize(count);
1587
1588 let header_bb = self.append_sibling_block("repeat_loop_header");
1589 let body_bb = self.append_sibling_block("repeat_loop_body");
1590 let next_bb = self.append_sibling_block("repeat_loop_next");
1591
1592 self.br(header_bb);
1593
1594 let mut header_bx = Self::build(self.cx, header_bb);
1595 let i = header_bx.phi(self.val_ty(zero), &[zero], &[self.llbb()]);
1596
1597 let keep_going = header_bx.icmp(IntPredicate::IntULT, i, count);
1598 header_bx.cond_br(keep_going, body_bb, next_bb);
1599
1600 let mut body_bx = Self::build(self.cx, body_bb);
1601 let dest_elem = dest.project_index(&mut body_bx, i);
1602 cg_elem.val.store(&mut body_bx, dest_elem);
1603
1604 let next = body_bx.unchecked_uadd(i, self.const_usize(1));
1605 body_bx.br(header_bb);
1606 header_bx.add_incoming_to_phi(i, next, body_bb);
1607
1608 *self = Self::build(self.cx, next_bb);
1609 }
1610
1611 fn write_operand_repeatedly_unoptimized(
1612 &mut self,
1613 cg_elem: OperandRef<'tcx, &'ll Value>,
1614 count: u64,
1615 dest: PlaceRef<'tcx, &'ll Value>,
1616 ) {
1617 let zero = self.const_usize(0);
1618 let count = self.const_usize(count);
1619 let start = dest.project_index(self, zero).val.llval;
1620 let end = dest.project_index(self, count).val.llval;
1621
1622 let header_bb = self.append_sibling_block("repeat_loop_header");
1623 let body_bb = self.append_sibling_block("repeat_loop_body");
1624 let next_bb = self.append_sibling_block("repeat_loop_next");
1625
1626 self.br(header_bb);
1627
1628 let mut header_bx = Self::build(self.cx, header_bb);
1629 let current = header_bx.phi(self.val_ty(start), &[start], &[self.llbb()]);
1630
1631 let keep_going = header_bx.icmp(IntPredicate::IntNE, current, end);
1632 header_bx.cond_br(keep_going, body_bb, next_bb);
1633
1634 let mut body_bx = Self::build(self.cx, body_bb);
1635 let align = dest.val.align.restrict_for_offset(dest.layout.field(self.cx(), 0).size);
1636 cg_elem
1637 .val
1638 .store(&mut body_bx, PlaceRef::new_sized_aligned(current, cg_elem.layout, align));
1639
1640 let next = body_bx.inbounds_gep(
1641 self.backend_type(cg_elem.layout),
1642 current,
1643 &[self.const_usize(1)],
1644 );
1645 body_bx.br(header_bb);
1646 header_bx.add_incoming_to_phi(current, next, body_bb);
1647
1648 *self = Self::build(self.cx, next_bb);
1649 }
1650
1651 pub(crate) fn minimum_number_nsz(&mut self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
1652 let call = self.call_intrinsic("llvm.minimumnum", &[self.val_ty(lhs)], &[lhs, rhs]);
1653 unsafe { llvm::LLVMRustSetNoSignedZeros(call) };
1654 call
1655 }
1656
1657 pub(crate) fn maximum_number_nsz(&mut self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
1658 let call = self.call_intrinsic("llvm.maximumnum", &[self.val_ty(lhs)], &[lhs, rhs]);
1659 unsafe { llvm::LLVMRustSetNoSignedZeros(call) };
1660 call
1661 }
1662
1663 pub(crate) fn insert_element(
1664 &mut self,
1665 vec: &'ll Value,
1666 elt: &'ll Value,
1667 idx: &'ll Value,
1668 ) -> &'ll Value {
1669 unsafe { llvm::LLVMBuildInsertElement(self.llbuilder, vec, elt, idx, UNNAMED) }
1670 }
1671
1672 pub(crate) fn shuffle_vector(
1673 &mut self,
1674 v1: &'ll Value,
1675 v2: &'ll Value,
1676 mask: &'ll Value,
1677 ) -> &'ll Value {
1678 unsafe { llvm::LLVMBuildShuffleVector(self.llbuilder, v1, v2, mask, UNNAMED) }
1679 }
1680
1681 pub(crate) fn vector_reduce_fadd(&mut self, acc: &'ll Value, src: &'ll Value) -> &'ll Value {
1682 self.call_intrinsic("llvm.vector.reduce.fadd", &[self.val_ty(src)], &[acc, src])
1683 }
1684 pub(crate) fn vector_reduce_fmul(&mut self, acc: &'ll Value, src: &'ll Value) -> &'ll Value {
1685 self.call_intrinsic("llvm.vector.reduce.fmul", &[self.val_ty(src)], &[acc, src])
1686 }
1687 pub(crate) fn vector_reduce_fadd_reassoc(
1688 &mut self,
1689 acc: &'ll Value,
1690 src: &'ll Value,
1691 ) -> &'ll Value {
1692 unsafe {
1693 let instr =
1694 self.call_intrinsic("llvm.vector.reduce.fadd", &[self.val_ty(src)], &[acc, src]);
1695 llvm::LLVMRustSetAllowReassoc(instr);
1696 instr
1697 }
1698 }
1699 pub(crate) fn vector_reduce_fmul_reassoc(
1700 &mut self,
1701 acc: &'ll Value,
1702 src: &'ll Value,
1703 ) -> &'ll Value {
1704 unsafe {
1705 let instr =
1706 self.call_intrinsic("llvm.vector.reduce.fmul", &[self.val_ty(src)], &[acc, src]);
1707 llvm::LLVMRustSetAllowReassoc(instr);
1708 instr
1709 }
1710 }
1711 pub(crate) fn vector_reduce_add(&mut self, src: &'ll Value) -> &'ll Value {
1712 self.call_intrinsic("llvm.vector.reduce.add", &[self.val_ty(src)], &[src])
1713 }
1714 pub(crate) fn vector_reduce_mul(&mut self, src: &'ll Value) -> &'ll Value {
1715 self.call_intrinsic("llvm.vector.reduce.mul", &[self.val_ty(src)], &[src])
1716 }
1717 pub(crate) fn vector_reduce_and(&mut self, src: &'ll Value) -> &'ll Value {
1718 self.call_intrinsic("llvm.vector.reduce.and", &[self.val_ty(src)], &[src])
1719 }
1720 pub(crate) fn vector_reduce_or(&mut self, src: &'ll Value) -> &'ll Value {
1721 self.call_intrinsic("llvm.vector.reduce.or", &[self.val_ty(src)], &[src])
1722 }
1723 pub(crate) fn vector_reduce_xor(&mut self, src: &'ll Value) -> &'ll Value {
1724 self.call_intrinsic("llvm.vector.reduce.xor", &[self.val_ty(src)], &[src])
1725 }
1726 pub(crate) fn vector_reduce_min(&mut self, src: &'ll Value, is_signed: bool) -> &'ll Value {
1727 self.call_intrinsic(
1728 if is_signed { "llvm.vector.reduce.smin" } else { "llvm.vector.reduce.umin" },
1729 &[self.val_ty(src)],
1730 &[src],
1731 )
1732 }
1733 pub(crate) fn vector_reduce_max(&mut self, src: &'ll Value, is_signed: bool) -> &'ll Value {
1734 self.call_intrinsic(
1735 if is_signed { "llvm.vector.reduce.smax" } else { "llvm.vector.reduce.umax" },
1736 &[self.val_ty(src)],
1737 &[src],
1738 )
1739 }
1740}
1741impl<'a, 'll, CX: Borrow<SCx<'ll>>> GenericBuilder<'a, 'll, CX> {
1742 pub(crate) fn add_clause(&mut self, landing_pad: &'ll Value, clause: &'ll Value) {
1743 unsafe {
1744 llvm::LLVMAddClause(landing_pad, clause);
1745 }
1746 }
1747
1748 pub(crate) fn catch_ret(
1749 &mut self,
1750 funclet: &Funclet<'ll>,
1751 unwind: &'ll BasicBlock,
1752 ) -> &'ll Value {
1753 let ret = unsafe { llvm::LLVMBuildCatchRet(self.llbuilder, funclet.cleanuppad(), unwind) };
1754 ret.expect("LLVM does not have support for catchret")
1755 }
1756
1757 pub(crate) fn check_call<'b>(
1758 &mut self,
1759 typ: &str,
1760 fn_ty: &'ll Type,
1761 llfn: &'ll Value,
1762 args: &'b [&'ll Value],
1763 ) -> Cow<'b, [&'ll Value]> {
1764 if !(self.cx.type_kind(fn_ty) == TypeKind::Function) {
{
::core::panicking::panic_fmt(format_args!("builder::{0} not passed a function, but {1:?}",
typ, fn_ty));
}
};assert!(
1765 self.cx.type_kind(fn_ty) == TypeKind::Function,
1766 "builder::{typ} not passed a function, but {fn_ty:?}"
1767 );
1768
1769 let param_tys = self.cx.func_params_types(fn_ty);
1770
1771 let all_args_match = iter::zip(¶m_tys, args.iter().map(|&v| self.cx.val_ty(v)))
1772 .all(|(expected_ty, actual_ty)| *expected_ty == actual_ty);
1773
1774 if all_args_match {
1775 return Cow::Borrowed(args);
1776 }
1777
1778 let casted_args: Vec<_> = iter::zip(param_tys, args)
1779 .enumerate()
1780 .map(|(i, (expected_ty, &actual_val))| {
1781 let actual_ty = self.cx.val_ty(actual_val);
1782 if expected_ty != actual_ty {
1783 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_llvm/src/builder.rs:1783",
"rustc_codegen_llvm::builder", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_llvm/src/builder.rs"),
::tracing_core::__macro_support::Option::Some(1783u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::builder"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("type mismatch in function call of {0:?}. Expected {1:?} for param {2}, got {3:?}; injecting bitcast",
llfn, expected_ty, i, actual_ty) as &dyn Value))])
});
} else { ; }
};debug!(
1784 "type mismatch in function call of {:?}. \
1785 Expected {:?} for param {}, got {:?}; injecting bitcast",
1786 llfn, expected_ty, i, actual_ty
1787 );
1788 self.bitcast(actual_val, expected_ty)
1789 } else {
1790 actual_val
1791 }
1792 })
1793 .collect();
1794
1795 Cow::Owned(casted_args)
1796 }
1797
1798 pub(crate) fn va_arg(&mut self, list: &'ll Value, ty: &'ll Type) -> &'ll Value {
1799 unsafe { llvm::LLVMBuildVAArg(self.llbuilder, list, ty, UNNAMED) }
1800 }
1801}
1802
1803impl<'a, 'll, 'tcx> Builder<'a, 'll, 'tcx> {
1804 pub(crate) fn call_intrinsic(
1805 &mut self,
1806 base_name: impl Into<Cow<'static, str>>,
1807 type_params: &[&'ll Type],
1808 args: &[&'ll Value],
1809 ) -> &'ll Value {
1810 let (ty, f) = self.cx.get_intrinsic(base_name.into(), type_params);
1811 self.call(ty, None, None, f, args, None, None)
1812 }
1813
1814 fn call_lifetime_intrinsic(&mut self, intrinsic: &'static str, ptr: &'ll Value, size: Size) {
1815 let size = size.bytes();
1816 if size == 0 {
1817 return;
1818 }
1819
1820 if !self.cx().sess().emit_lifetime_markers() {
1821 return;
1822 }
1823
1824 if crate::llvm_util::get_version() >= (22, 0, 0) {
1825 let ptr = unsafe { llvm::LLVMRustStripPointerCasts(ptr) };
1828 self.call_intrinsic(intrinsic, &[self.val_ty(ptr)], &[ptr]);
1829 } else {
1830 self.call_intrinsic(intrinsic, &[self.val_ty(ptr)], &[self.cx.const_u64(size), ptr]);
1831 }
1832 }
1833}
1834impl<'a, 'll, CX: Borrow<SCx<'ll>>> GenericBuilder<'a, 'll, CX> {
1835 pub(crate) fn phi(
1836 &mut self,
1837 ty: &'ll Type,
1838 vals: &[&'ll Value],
1839 bbs: &[&'ll BasicBlock],
1840 ) -> &'ll Value {
1841 match (&vals.len(), &bbs.len()) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val, &*right_val,
::core::option::Option::None);
}
}
};assert_eq!(vals.len(), bbs.len());
1842 let phi = unsafe { llvm::LLVMBuildPhi(self.llbuilder, ty, UNNAMED) };
1843 unsafe {
1844 llvm::LLVMAddIncoming(phi, vals.as_ptr(), bbs.as_ptr(), vals.len() as c_uint);
1845 phi
1846 }
1847 }
1848
1849 fn add_incoming_to_phi(&mut self, phi: &'ll Value, val: &'ll Value, bb: &'ll BasicBlock) {
1850 unsafe {
1851 llvm::LLVMAddIncoming(phi, &val, &bb, 1 as c_uint);
1852 }
1853 }
1854}
1855impl<'a, 'll, 'tcx> Builder<'a, 'll, 'tcx> {
1856 pub(crate) fn landing_pad(
1857 &mut self,
1858 ty: &'ll Type,
1859 pers_fn: &'ll Value,
1860 num_clauses: usize,
1861 ) -> &'ll Value {
1862 self.set_personality_fn(pers_fn);
1866 unsafe {
1867 llvm::LLVMBuildLandingPad(self.llbuilder, ty, None, num_clauses as c_uint, UNNAMED)
1868 }
1869 }
1870
1871 pub(crate) fn callbr(
1872 &mut self,
1873 llty: &'ll Type,
1874 fn_attrs: Option<&CodegenFnAttrs>,
1875 fn_abi: Option<&FnAbi<'tcx, Ty<'tcx>>>,
1876 llfn: &'ll Value,
1877 args: &[&'ll Value],
1878 default_dest: &'ll BasicBlock,
1879 indirect_dest: &[&'ll BasicBlock],
1880 funclet: Option<&Funclet<'ll>>,
1881 instance: Option<Instance<'tcx>>,
1882 ) -> &'ll Value {
1883 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_llvm/src/builder.rs:1883",
"rustc_codegen_llvm::builder", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_llvm/src/builder.rs"),
::tracing_core::__macro_support::Option::Some(1883u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::builder"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("invoke {0:?} with args ({1:?})",
llfn, args) as &dyn Value))])
});
} else { ; }
};debug!("invoke {:?} with args ({:?})", llfn, args);
1884
1885 let args = self.check_call("callbr", llty, llfn, args);
1886 let funclet_bundle = funclet.map(|funclet| funclet.bundle());
1887 let mut bundles: SmallVec<[_; 2]> = SmallVec::new();
1888 if let Some(funclet_bundle) = funclet_bundle {
1889 bundles.push(funclet_bundle);
1890 }
1891
1892 self.cfi_type_test(fn_attrs, fn_abi, instance, llfn);
1894
1895 let kcfi_bundle = self.kcfi_operand_bundle(fn_attrs, fn_abi, instance, llfn);
1897 if let Some(kcfi_bundle) = kcfi_bundle.as_ref().map(|b| b.as_ref()) {
1898 bundles.push(kcfi_bundle);
1899 }
1900
1901 let callbr = unsafe {
1902 llvm::LLVMBuildCallBr(
1903 self.llbuilder,
1904 llty,
1905 llfn,
1906 default_dest,
1907 indirect_dest.as_ptr(),
1908 indirect_dest.len() as c_uint,
1909 args.as_ptr(),
1910 args.len() as c_uint,
1911 bundles.as_ptr(),
1912 bundles.len() as c_uint,
1913 UNNAMED,
1914 )
1915 };
1916 if let Some(fn_abi) = fn_abi {
1917 fn_abi.apply_attrs_callsite(self, callbr);
1918 }
1919 callbr
1920 }
1921
1922 fn cfi_type_test(
1924 &mut self,
1925 fn_attrs: Option<&CodegenFnAttrs>,
1926 fn_abi: Option<&FnAbi<'tcx, Ty<'tcx>>>,
1927 instance: Option<Instance<'tcx>>,
1928 llfn: &'ll Value,
1929 ) {
1930 let is_indirect_call = unsafe { llvm::LLVMRustIsNonGVFunctionPointerTy(llfn) };
1931 if self.tcx.sess.is_sanitizer_cfi_enabled()
1932 && let Some(fn_abi) = fn_abi
1933 && is_indirect_call
1934 {
1935 if let Some(fn_attrs) = fn_attrs
1936 && fn_attrs.sanitizers.disabled.contains(SanitizerSet::CFI)
1937 {
1938 return;
1939 }
1940
1941 let mut options = cfi::TypeIdOptions::empty();
1942 if self.tcx.sess.is_sanitizer_cfi_generalize_pointers_enabled() {
1943 options.insert(cfi::TypeIdOptions::GENERALIZE_POINTERS);
1944 }
1945 if self.tcx.sess.is_sanitizer_cfi_normalize_integers_enabled() {
1946 options.insert(cfi::TypeIdOptions::NORMALIZE_INTEGERS);
1947 }
1948
1949 let typeid = if let Some(instance) = instance {
1950 cfi::typeid_for_instance(self.tcx, instance, options)
1951 } else {
1952 cfi::typeid_for_fnabi(self.tcx, fn_abi, options)
1953 };
1954 let typeid_metadata = self.cx.create_metadata(typeid.as_bytes());
1955 let dbg_loc = self.get_dbg_loc();
1956
1957 let typeid = self.get_metadata_value(typeid_metadata);
1961 let cond = self.call_intrinsic("llvm.type.test", &[], &[llfn, typeid]);
1962 let bb_pass = self.append_sibling_block("type_test.pass");
1963 let bb_fail = self.append_sibling_block("type_test.fail");
1964 self.cond_br(cond, bb_pass, bb_fail);
1965
1966 self.switch_to_block(bb_fail);
1967 if let Some(dbg_loc) = dbg_loc {
1968 self.set_dbg_loc(dbg_loc);
1969 }
1970 self.abort();
1971 self.unreachable();
1972
1973 self.switch_to_block(bb_pass);
1974 if let Some(dbg_loc) = dbg_loc {
1975 self.set_dbg_loc(dbg_loc);
1976 }
1977 }
1978 }
1979
1980 fn kcfi_operand_bundle(
1982 &mut self,
1983 fn_attrs: Option<&CodegenFnAttrs>,
1984 fn_abi: Option<&FnAbi<'tcx, Ty<'tcx>>>,
1985 instance: Option<Instance<'tcx>>,
1986 llfn: &'ll Value,
1987 ) -> Option<llvm::OperandBundleBox<'ll>> {
1988 let is_indirect_call = unsafe { llvm::LLVMRustIsNonGVFunctionPointerTy(llfn) };
1989 let kcfi_bundle = if self.tcx.sess.is_sanitizer_kcfi_enabled()
1990 && let Some(fn_abi) = fn_abi
1991 && is_indirect_call
1992 {
1993 if let Some(fn_attrs) = fn_attrs
1994 && fn_attrs.sanitizers.disabled.contains(SanitizerSet::KCFI)
1995 {
1996 return None;
1997 }
1998
1999 let mut options = kcfi::TypeIdOptions::empty();
2000 if self.tcx.sess.is_sanitizer_cfi_generalize_pointers_enabled() {
2001 options.insert(kcfi::TypeIdOptions::GENERALIZE_POINTERS);
2002 }
2003 if self.tcx.sess.is_sanitizer_cfi_normalize_integers_enabled() {
2004 options.insert(kcfi::TypeIdOptions::NORMALIZE_INTEGERS);
2005 }
2006
2007 let kcfi_typeid = if let Some(instance) = instance {
2008 kcfi::typeid_for_instance(self.tcx, instance, options)
2009 } else {
2010 kcfi::typeid_for_fnabi(self.tcx, fn_abi, options)
2011 };
2012
2013 Some(llvm::OperandBundleBox::new("kcfi", &[self.const_u32(kcfi_typeid)]))
2014 } else {
2015 None
2016 };
2017 kcfi_bundle
2018 }
2019
2020 #[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("instrprof_increment",
"rustc_codegen_llvm::builder", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_llvm/src/builder.rs"),
::tracing_core::__macro_support::Option::Some(2021u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::builder"),
::tracing_core::field::FieldSet::new(&["fn_name", "hash",
"num_counters", "index"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&fn_name)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&hash)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&num_counters)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&index)
as &dyn Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: () = loop {};
return __tracing_attr_fake_return;
}
{
self.call_intrinsic("llvm.instrprof.increment", &[],
&[fn_name, hash, num_counters, index]);
}
}
}#[instrument(level = "debug", skip(self))]
2022 pub(crate) fn instrprof_increment(
2023 &mut self,
2024 fn_name: &'ll Value,
2025 hash: &'ll Value,
2026 num_counters: &'ll Value,
2027 index: &'ll Value,
2028 ) {
2029 self.call_intrinsic("llvm.instrprof.increment", &[], &[fn_name, hash, num_counters, index]);
2030 }
2031}