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