1use std::cmp;
2use std::ops::Range;
3
4use rustc_abi::{
5 Align, ArmCall, CanonAbi, ExternAbi, FieldsShape, HasDataLayout, Size, VariantIdx, Variants,
6};
7use rustc_ast as ast;
8use rustc_ast::{InlineAsmOptions, InlineAsmTemplatePiece};
9use rustc_attr_ir::UnrollAttr;
10use rustc_attr_ir::lang_items::LangItem;
11use rustc_data_structures::packed::Pu128;
12use rustc_lint_defs::builtin::TAIL_CALL_TRACK_CALLER;
13use rustc_middle::mir::interpret::{CTFE_ALLOC_SALT, Scalar};
14use rustc_middle::mir::{self, AssertKind, InlineAsmMacro, SwitchTargets, UnwindTerminateReason};
15use rustc_middle::ty::layout::{HasTyCtxt, LayoutOf, TyAndLayout, ValidityRequirement};
16use rustc_middle::ty::print::{with_no_trimmed_paths, with_no_visible_paths};
17use rustc_middle::ty::{self, Instance, Ty, TypeVisitableExt};
18use rustc_session::config::OptLevel;
19use rustc_span::{Span, Spanned, bug, span_bug};
20use rustc_target::callconv::{ArgAbi, ArgAttributes, CastTarget, FnAbi, IndirectMode, PassMode};
21use tracing::{debug, info};
22
23use super::operand::OperandRef;
24use super::operand::OperandValue::{self, Immediate, Pair, Ref, ZeroSized};
25use super::place::{PlaceRef, PlaceValue};
26use super::{CachedLlbb, FunctionCx, LocalRef};
27use crate::base::{self, is_call_from_compiler_builtins_to_upstream_monomorphization};
28use crate::common::{self, IntPredicate};
29use crate::diagnostics::CompilerBuiltinsCannotCall;
30use crate::mir::IntrinsicResult;
31use crate::traits::*;
32use crate::{MemFlags, meth};
33
34#[derive(#[automatically_derived]impl ::core::fmt::Debug for MergingSucc {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
MergingSucc::False => "False",
MergingSucc::True => "True",
})
}
}Debug, #[automatically_derived]impl ::core::marker::StructuralPartialEq for
MergingSucc {
}
#[automatically_derived]impl ::core::cmp::PartialEq for MergingSucc {
#[inline]
fn eq(&self, other: &Self) -> bool {
::core::intrinsics::discriminant_value(self) ==
::core::intrinsics::discriminant_value(other)
}
}PartialEq)]
38enum MergingSucc {
39 False,
40 True,
41}
42
43#[derive(#[automatically_derived]impl ::core::fmt::Debug for CallKind {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
CallKind::Normal => "Normal",
CallKind::Tail => "Tail",
})
}
}Debug, #[automatically_derived]impl ::core::marker::StructuralPartialEq for CallKind
{
}
#[automatically_derived]impl ::core::cmp::PartialEq for CallKind {
#[inline]
fn eq(&self, other: &Self) -> bool {
::core::intrinsics::discriminant_value(self) ==
::core::intrinsics::discriminant_value(other)
}
}PartialEq)]
46enum CallKind {
47 Normal,
48 Tail,
49}
50
51struct TerminatorCodegenHelper<'tcx> {
54 bb: mir::BasicBlock,
55 terminator: &'tcx mir::Terminator<'tcx>,
56}
57
58impl<'a, 'tcx> TerminatorCodegenHelper<'tcx> {
59 fn funclet<'b, Bx: BuilderMethods<'a, 'tcx>>(
62 &self,
63 fx: &'b mut FunctionCx<'a, 'tcx, Bx>,
64 ) -> Option<&'b Bx::Funclet> {
65 let cleanup_kinds = fx.cleanup_kinds.as_ref()?;
66 let funclet_bb = cleanup_kinds[self.bb].funclet_bb(self.bb)?;
67 if fx.funclets[funclet_bb].is_none() {
76 fx.landing_pad_for(funclet_bb);
77 }
78 Some(
79 fx.funclets[funclet_bb]
80 .as_ref()
81 .expect("landing_pad_for didn't also create funclets entry"),
82 )
83 }
84
85 fn llbb_with_cleanup<Bx: BuilderMethods<'a, 'tcx>>(
88 &self,
89 fx: &mut FunctionCx<'a, 'tcx, Bx>,
90 target: mir::BasicBlock,
91 ) -> Bx::BasicBlock {
92 let (needs_landing_pad, is_cleanupret) = self.llbb_characteristics(fx, target);
93 let mut lltarget = fx.llbb(target);
94 if needs_landing_pad {
95 lltarget = fx.landing_pad_for(target);
96 }
97 if is_cleanupret {
98 if !base::wants_new_eh_instructions(&fx.cx.tcx().sess.target) {
::core::panicking::panic("assertion failed: base::wants_new_eh_instructions(&fx.cx.tcx().sess.target)")
};assert!(base::wants_new_eh_instructions(&fx.cx.tcx().sess.target));
100 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/249c1e4e31111b54ad2483cfd4cea06c7020c653/compiler/rustc_codegen_ssa/src/mir/block.rs:100",
"rustc_codegen_ssa::mir::block", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/249c1e4e31111b54ad2483cfd4cea06c7020c653/compiler/rustc_codegen_ssa/src/mir/block.rs"),
::tracing_core::__macro_support::Option::Some(100u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::mir::block"),
::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!("llbb_with_cleanup: creating cleanup trampoline for {0:?}",
target) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("llbb_with_cleanup: creating cleanup trampoline for {:?}", target);
101 let name = &::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0:?}_cleanup_trampoline_{1:?}",
self.bb, target))
})format!("{:?}_cleanup_trampoline_{:?}", self.bb, target);
102 let trampoline_llbb = Bx::append_block(fx.cx, fx.llfn, name);
103 let mut trampoline_bx = Bx::build(fx.cx, trampoline_llbb);
104 trampoline_bx.cleanup_ret(self.funclet(fx).unwrap(), Some(lltarget));
105 trampoline_llbb
106 } else {
107 lltarget
108 }
109 }
110
111 fn llbb_characteristics<Bx: BuilderMethods<'a, 'tcx>>(
112 &self,
113 fx: &mut FunctionCx<'a, 'tcx, Bx>,
114 target: mir::BasicBlock,
115 ) -> (bool, bool) {
116 if let Some(ref cleanup_kinds) = fx.cleanup_kinds {
117 let funclet_bb = cleanup_kinds[self.bb].funclet_bb(self.bb);
118 let target_funclet = cleanup_kinds[target].funclet_bb(target);
119 let (needs_landing_pad, is_cleanupret) = match (funclet_bb, target_funclet) {
120 (None, None) => (false, false),
121 (None, Some(_)) => (true, false),
122 (Some(f), Some(t_f)) => (f != t_f, f != t_f),
123 (Some(_), None) => {
124 let span = self.terminator.source_info.span;
125 ::rustc_span::macros::bug_impl(Some(span),
format_args!("{0:?} - jump out of cleanup?", self.terminator),
Location::caller());span_bug!(span, "{:?} - jump out of cleanup?", self.terminator);
126 }
127 };
128 (needs_landing_pad, is_cleanupret)
129 } else {
130 let needs_landing_pad = !fx.mir[self.bb].is_cleanup && fx.mir[target].is_cleanup;
131 let is_cleanupret = false;
132 (needs_landing_pad, is_cleanupret)
133 }
134 }
135
136 fn funclet_br<Bx: BuilderMethods<'a, 'tcx>>(
137 &self,
138 fx: &mut FunctionCx<'a, 'tcx, Bx>,
139 bx: &mut Bx,
140 target: mir::BasicBlock,
141 mergeable_succ: bool,
142 loop_hint_attrs: &[UnrollAttr],
143 ) -> MergingSucc {
144 let (needs_landing_pad, is_cleanupret) = self.llbb_characteristics(fx, target);
145 if mergeable_succ && !needs_landing_pad && !is_cleanupret {
146 MergingSucc::True
148 } else {
149 let mut lltarget = fx.llbb(target);
150 if needs_landing_pad {
151 lltarget = fx.landing_pad_for(target);
152 }
153 if is_cleanupret {
154 bx.cleanup_ret(self.funclet(fx).unwrap(), Some(lltarget));
157 } else {
158 bx.br_with_attrs(lltarget, loop_hint_attrs);
159 }
160 MergingSucc::False
161 }
162 }
163
164 fn do_call<Bx: BuilderMethods<'a, 'tcx>>(
170 &self,
171 fx: &mut FunctionCx<'a, 'tcx, Bx>,
172 bx: &mut Bx,
173 fn_abi: &'tcx FnAbi<'tcx, Ty<'tcx>>,
174 fn_ptr: Bx::Value,
175 return_slot: ReturnSlot<Bx::Value>,
176 llargs: &[Bx::Value],
177 destination: Option<(ReturnDest<'tcx, Bx::Value>, mir::BasicBlock)>,
178 mut unwind: mir::UnwindAction,
179 lifetime_ends_after_call: &[(Bx::Value, Size)],
180 instance: Option<Instance<'tcx>>,
181 kind: CallKind,
182 mergeable_succ: bool,
183 ) -> MergingSucc {
184 let tcx = bx.tcx();
185 if let Some(instance) = instance
186 && is_call_from_compiler_builtins_to_upstream_monomorphization(tcx, instance)
187 {
188 if destination.is_some() {
189 let caller_def = fx.instance.def_id();
190 let e = CompilerBuiltinsCannotCall {
191 span: tcx.def_span(caller_def),
192 caller: { let _guard = NoTrimmedGuard::new(); tcx.def_path_str(caller_def) }with_no_trimmed_paths!(tcx.def_path_str(caller_def)),
193 callee: { let _guard = NoTrimmedGuard::new(); tcx.def_path_str(instance.def_id()) }with_no_trimmed_paths!(tcx.def_path_str(instance.def_id())),
194 };
195 tcx.dcx().emit_err(e);
196 } else {
197 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/249c1e4e31111b54ad2483cfd4cea06c7020c653/compiler/rustc_codegen_ssa/src/mir/block.rs:197",
"rustc_codegen_ssa::mir::block", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("/rustc-dev/249c1e4e31111b54ad2483cfd4cea06c7020c653/compiler/rustc_codegen_ssa/src/mir/block.rs"),
::tracing_core::__macro_support::Option::Some(197u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::mir::block"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::INFO <=
::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!("compiler_builtins call to diverging function {0:?} replaced with abort",
instance.def_id()) as &dyn ::tracing::field::Value))])
});
} else { ; }
};info!(
198 "compiler_builtins call to diverging function {:?} replaced with abort",
199 instance.def_id()
200 );
201 bx.abort_immediate();
202 bx.unreachable();
203 return MergingSucc::False;
204 }
205 }
206
207 let fn_ty = bx.fn_decl_backend_type(fn_abi);
210
211 let caller_attrs = if bx.tcx().def_kind(fx.instance.def_id()).has_codegen_attrs() {
212 Some(bx.tcx().codegen_instance_attrs(fx.instance.def))
213 } else {
214 None
215 };
216 let caller_attrs = caller_attrs.as_deref();
217
218 if !fn_abi.can_unwind {
219 unwind = mir::UnwindAction::Unreachable;
220 }
221
222 let unwind_block = match unwind {
223 mir::UnwindAction::Cleanup(cleanup) => {
224 if !fx.nop_landing_pads.contains(cleanup) {
225 Some(self.llbb_with_cleanup(fx, cleanup))
226 } else {
227 None
228 }
229 }
230 mir::UnwindAction::Continue => None,
231 mir::UnwindAction::Unreachable => None,
232 mir::UnwindAction::Terminate(reason) => {
233 if fx.mir[self.bb].is_cleanup && base::wants_wasm_eh(&fx.cx.tcx().sess.target) {
234 Some(fx.terminate_block(reason, Some(self.bb)))
237 } else if fx.mir[self.bb].is_cleanup
238 && base::wants_new_eh_instructions(&fx.cx.tcx().sess.target)
239 {
240 None
243 } else {
244 Some(fx.terminate_block(reason, None))
245 }
246 }
247 };
248
249 if true {
{
match (&return_slot.is_indirect(), &fn_abi.ret.is_indirect()) {
(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::Some(format_args!("a return slot must be provided if and only if the return is `PassMode::Indirect`")));
}
}
}
};
};debug_assert_eq!(
250 return_slot.is_indirect(),
251 fn_abi.ret.is_indirect(),
252 "a return slot must be provided if and only if the return is `PassMode::Indirect`",
253 );
254
255 if kind == CallKind::Tail {
256 bx.tail_call(
257 fn_ty,
258 caller_attrs,
259 fn_abi,
260 fn_ptr,
261 return_slot,
262 llargs,
263 self.funclet(fx),
264 instance,
265 );
266 return MergingSucc::False;
267 }
268
269 if let Some(unwind_block) = unwind_block {
270 let ret_llbb = if let Some((_, target)) = destination {
271 self.llbb_with_cleanup(fx, target)
272 } else {
273 fx.unreachable_block()
274 };
275 let invokeret = bx.invoke(
276 fn_ty,
277 caller_attrs,
278 Some(fn_abi),
279 fn_ptr,
280 return_slot,
281 llargs,
282 ret_llbb,
283 unwind_block,
284 self.funclet(fx),
285 instance,
286 );
287 if fx.mir[self.bb].is_cleanup {
288 bx.apply_attrs_to_cleanup_callsite(invokeret);
289 }
290
291 if let Some((ret_dest, target)) = destination {
292 bx.switch_to_block(fx.llbb(target));
293 fx.set_debug_loc(bx, self.terminator.source_info);
294 for &(tmp, size) in lifetime_ends_after_call {
295 bx.lifetime_end(tmp, size);
296 }
297 fx.store_return(bx, ret_dest, &fn_abi.ret, invokeret);
298
299 fx.cached_llbbs[target] = CachedLlbb::Some(bx.llbb());
304 }
305 MergingSucc::False
306 } else {
307 let llret = bx.call(
308 fn_ty,
309 caller_attrs,
310 Some(fn_abi),
311 fn_ptr,
312 return_slot,
313 llargs,
314 self.funclet(fx),
315 instance,
316 );
317 if fx.mir[self.bb].is_cleanup {
318 bx.apply_attrs_to_cleanup_callsite(llret);
319 }
320
321 if let Some((ret_dest, target)) = destination {
322 for &(tmp, size) in lifetime_ends_after_call {
323 bx.lifetime_end(tmp, size);
324 }
325 fx.store_return(bx, ret_dest, &fn_abi.ret, llret);
326 self.funclet_br(fx, bx, target, mergeable_succ, &[])
327 } else {
328 bx.unreachable();
329 MergingSucc::False
330 }
331 }
332 }
333
334 fn do_inlineasm<Bx: BuilderMethods<'a, 'tcx>>(
336 &self,
337 fx: &mut FunctionCx<'a, 'tcx, Bx>,
338 bx: &mut Bx,
339 template: &[InlineAsmTemplatePiece],
340 operands: &[InlineAsmOperandRef<'tcx, Bx>],
341 options: InlineAsmOptions,
342 line_spans: &[Span],
343 destination: Option<mir::BasicBlock>,
344 unwind: mir::UnwindAction,
345 instance: Instance<'_>,
346 mergeable_succ: bool,
347 ) -> MergingSucc {
348 let unwind_target = match unwind {
349 mir::UnwindAction::Cleanup(cleanup) => {
350 if !fx.nop_landing_pads.contains(cleanup) {
351 Some(self.llbb_with_cleanup(fx, cleanup))
352 } else {
353 None
354 }
355 }
356 mir::UnwindAction::Terminate(reason) => Some(fx.terminate_block(reason, None)),
357 mir::UnwindAction::Continue => None,
358 mir::UnwindAction::Unreachable => None,
359 };
360
361 if operands.iter().any(|x| #[allow(non_exhaustive_omitted_patterns)] match x {
InlineAsmOperandRef::Label { .. } => true,
_ => false,
}matches!(x, InlineAsmOperandRef::Label { .. })) {
362 if !unwind_target.is_none() {
::core::panicking::panic("assertion failed: unwind_target.is_none()")
};assert!(unwind_target.is_none());
363 let ret_llbb = if let Some(target) = destination {
364 self.llbb_with_cleanup(fx, target)
365 } else {
366 fx.unreachable_block()
367 };
368
369 bx.codegen_inline_asm(
370 template,
371 operands,
372 options,
373 line_spans,
374 instance,
375 Some(ret_llbb),
376 None,
377 );
378 MergingSucc::False
379 } else if let Some(cleanup) = unwind_target {
380 let ret_llbb = if let Some(target) = destination {
381 self.llbb_with_cleanup(fx, target)
382 } else {
383 fx.unreachable_block()
384 };
385
386 bx.codegen_inline_asm(
387 template,
388 operands,
389 options,
390 line_spans,
391 instance,
392 Some(ret_llbb),
393 Some((cleanup, self.funclet(fx))),
394 );
395 MergingSucc::False
396 } else {
397 bx.codegen_inline_asm(template, operands, options, line_spans, instance, None, None);
398
399 if let Some(target) = destination {
400 self.funclet_br(fx, bx, target, mergeable_succ, &[])
401 } else {
402 bx.unreachable();
403 MergingSucc::False
404 }
405 }
406 }
407}
408
409impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
411 fn codegen_resume_terminator(&mut self, helper: TerminatorCodegenHelper<'tcx>, bx: &mut Bx) {
413 if let Some(funclet) = helper.funclet(self) {
414 bx.cleanup_ret(funclet, None);
415 } else {
416 let slot = self.get_personality_slot(bx);
417 let exn0 = slot.project_field(bx, 0);
418 let exn0 = bx.load_operand(exn0).immediate();
419 let exn1 = slot.project_field(bx, 1);
420 let exn1 = bx.load_operand(exn1).immediate();
421 slot.storage_dead(bx);
422
423 bx.resume(exn0, exn1);
424 }
425 }
426
427 fn codegen_switchint_terminator(
428 &mut self,
429 helper: TerminatorCodegenHelper<'tcx>,
430 bx: &mut Bx,
431 discr: &mir::Operand<'tcx>,
432 targets: &SwitchTargets,
433 ) {
434 let discr = self.codegen_operand(bx, discr);
435 let discr_value = discr.immediate();
436 let switch_ty = discr.layout.ty;
437 if let Some(const_discr) = bx.const_to_opt_u128(discr_value, false) {
439 let target = targets.target_for_value(const_discr);
440 bx.br(helper.llbb_with_cleanup(self, target));
441 return;
442 };
443
444 let mut target_iter = targets.iter();
445 if target_iter.len() == 1 {
446 let (test_value, target) = target_iter.next().unwrap();
449 let otherwise = targets.otherwise();
450 let lltarget = helper.llbb_with_cleanup(self, target);
451 let llotherwise = helper.llbb_with_cleanup(self, otherwise);
452 let target_cold = self.cold_blocks.contains(target);
453 let otherwise_cold = self.cold_blocks.contains(otherwise);
454 let expect = if target_cold == otherwise_cold { None } else { Some(otherwise_cold) };
458 if switch_ty == bx.tcx().types.bool {
459 match test_value {
461 0 => {
462 let expect = expect.map(|e| !e);
463 bx.cond_br_with_expect(discr_value, llotherwise, lltarget, expect);
464 }
465 1 => {
466 bx.cond_br_with_expect(discr_value, lltarget, llotherwise, expect);
467 }
468 _ => ::rustc_span::macros::bug_impl(None, format_args!("impossible case reached"),
Location::caller())bug!(),
469 }
470 } else {
471 let switch_llty = bx.immediate_backend_type(bx.layout_of(switch_ty));
472 let llval = bx.const_uint_big(switch_llty, test_value);
473 let cmp = bx.icmp(IntPredicate::IntEQ, discr_value, llval);
474 bx.cond_br_with_expect(cmp, lltarget, llotherwise, expect);
475 }
476 } else if target_iter.len() == 2
477 && self.mir[targets.otherwise()].is_empty_unreachable()
478 && targets.all_values().contains(&Pu128(0))
479 && targets.all_values().contains(&Pu128(1))
480 {
481 let true_bb = targets.target_for_value(1);
485 let false_bb = targets.target_for_value(0);
486 let true_ll = helper.llbb_with_cleanup(self, true_bb);
487 let false_ll = helper.llbb_with_cleanup(self, false_bb);
488
489 let expected_cond_value = if self.cx.sess().opts.optimize == OptLevel::No {
490 None
491 } else {
492 match (self.cold_blocks.contains(true_bb), self.cold_blocks.contains(false_bb)) {
493 (true, true) | (false, false) => None,
495 (true, false) => Some(false),
497 (false, true) => Some(true),
498 }
499 };
500
501 let bool_ty = bx.tcx().types.bool;
502 let cond = if switch_ty == bool_ty {
503 discr_value
504 } else {
505 let bool_llty = bx.immediate_backend_type(bx.layout_of(bool_ty));
506 bx.unchecked_utrunc(discr_value, bool_llty)
507 };
508 bx.cond_br_with_expect(cond, true_ll, false_ll, expected_cond_value);
509 } else if self.cx.sess().opts.optimize == OptLevel::No
510 && target_iter.len() == 2
511 && self.mir[targets.otherwise()].is_empty_unreachable()
512 {
513 let (test_value1, target1) = target_iter.next().unwrap();
526 let (_test_value2, target2) = target_iter.next().unwrap();
527 let ll1 = helper.llbb_with_cleanup(self, target1);
528 let ll2 = helper.llbb_with_cleanup(self, target2);
529 let switch_llty = bx.immediate_backend_type(bx.layout_of(switch_ty));
530 let llval = bx.const_uint_big(switch_llty, test_value1);
531 let cmp = bx.icmp(IntPredicate::IntEQ, discr_value, llval);
532 bx.cond_br(cmp, ll1, ll2);
533 } else {
534 let otherwise = targets.otherwise();
535 let otherwise_cold = self.cold_blocks.contains(otherwise);
536 let otherwise_unreachable = self.mir[otherwise].is_empty_unreachable();
537 let cold_count =
538 targets.iter().filter(|(_, target)| self.cold_blocks.contains(*target)).count();
539 let none_cold = cold_count == 0;
540 let all_cold = cold_count == targets.iter().len();
541 if (none_cold && (!otherwise_cold || otherwise_unreachable))
542 || (all_cold && (otherwise_cold || otherwise_unreachable))
543 {
544 bx.switch(
547 discr_value,
548 helper.llbb_with_cleanup(self, targets.otherwise()),
549 target_iter
550 .map(|(value, target)| (value, helper.llbb_with_cleanup(self, target))),
551 );
552 } else {
553 bx.switch_with_weights(
555 discr_value,
556 helper.llbb_with_cleanup(self, targets.otherwise()),
557 otherwise_cold,
558 target_iter.map(|(value, target)| {
559 let target_llbb = helper.llbb_with_cleanup(self, target);
560 let is_target_cold = self.cold_blocks.contains(target);
561 (value, target_llbb, is_target_cold)
562 }),
563 );
564 }
565 }
566 }
567
568 fn codegen_return_terminator(&mut self, bx: &mut Bx) {
569 if self.fn_abi.c_variadic {
573 let va_list_arg_idx = self.fn_abi.args.len();
575 match self.locals[mir::Local::arg(va_list_arg_idx)] {
576 LocalRef::Place(va_list) => {
577 bx.lifetime_end(va_list.val.llval, va_list.layout.size);
583 }
584 _ => ::rustc_span::macros::bug_impl(None,
format_args!("C-variadic function must have a `VaList` place"),
Location::caller())bug!("C-variadic function must have a `VaList` place"),
585 }
586 }
587 if self.fn_abi.ret.layout.is_uninhabited() {
588 bx.abort_immediate();
593 bx.unreachable();
596 return;
597 }
598 let llval = match &self.fn_abi.ret.mode {
599 PassMode::Ignore | PassMode::Indirect { .. } => {
600 bx.ret_void();
601 return;
602 }
603
604 PassMode::Direct(_) | PassMode::Pair(..) => {
605 let op = self.codegen_consume(bx, mir::Place::return_place().as_ref());
606 if let Ref(place_val) = op.val {
607 bx.load_from_place(bx.backend_type(op.layout), place_val)
608 } else {
609 op.immediate_or_packed_pair(bx)
610 }
611 }
612
613 PassMode::Cast { cast: cast_ty, pad_i32_count: _ } => {
614 let op = match self.locals[mir::RETURN_PLACE] {
615 LocalRef::Operand(op) => op,
616 LocalRef::PendingOperand => ::rustc_span::macros::bug_impl(None, format_args!("use of return before def"),
Location::caller())bug!("use of return before def"),
617 LocalRef::Place(cg_place) => OperandRef {
618 val: Ref(cg_place.val),
619 layout: cg_place.layout,
620 move_annotation: None,
621 },
622 LocalRef::UnsizedPlace(_) => ::rustc_span::macros::bug_impl(None,
format_args!("return type must be sized"), Location::caller())bug!("return type must be sized"),
623 };
624 let llslot = match op.val {
625 Immediate(_) | Pair(..) => {
626 let scratch = PlaceRef::alloca(bx, self.fn_abi.ret.layout);
627 op.val.store(bx, scratch);
628 scratch.val.llval
629 }
630 Ref(place_val) => {
631 {
match (&place_val.align, &op.layout.align) {
(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::Some(format_args!("return place is unaligned!")));
}
}
}
};assert_eq!(place_val.align, op.layout.align, "return place is unaligned!");
632 place_val.llval
633 }
634 ZeroSized => ::rustc_span::macros::bug_impl(None,
format_args!("ZST return value shouldn\'t be in PassMode::Cast"),
Location::caller())bug!("ZST return value shouldn't be in PassMode::Cast"),
635 };
636
637 if self.fn_abi.conv == CanonAbi::Arm(ArmCall::CCmseNonSecureEntry) {
638 let ret_layout = self.fn_abi.ret.layout;
641 self.clear_padding_cmse(bx, llslot, ret_layout.size, ret_layout);
642 }
643
644 load_cast(bx, cast_ty, llslot, self.fn_abi.ret.layout.align)
645 }
646 PassMode::IndirectUnsized { .. } => ::rustc_span::macros::bug_impl(None,
format_args!("unsized returns are not supported"), Location::caller())bug!("unsized returns are not supported"),
647 };
648 bx.ret(llval);
649 }
650
651 {}
#[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("codegen_drop_terminator",
"rustc_codegen_ssa::mir::block", ::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("/rustc-dev/249c1e4e31111b54ad2483cfd4cea06c7020c653/compiler/rustc_codegen_ssa/src/mir/block.rs"),
::tracing_core::__macro_support::Option::Some(651u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::mir::block"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("source_info")
}> =
::tracing::__macro_support::FieldName::new("source_info");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("location")
}> =
::tracing::__macro_support::FieldName::new("location");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("target")
}> =
::tracing::__macro_support::FieldName::new("target");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("unwind")
}> =
::tracing::__macro_support::FieldName::new("unwind");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("mergeable_succ")
}> =
::tracing::__macro_support::FieldName::new("mergeable_succ");
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(&source_info)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&location)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&target)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&unwind)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&mergeable_succ 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: MergingSucc = loop {};
return __tracing_attr_fake_return;
}
{
let ty = location.ty(self.mir, bx.tcx()).ty;
let ty = self.monomorphize(ty);
let drop_fn = Instance::resolve_drop_glue(bx.tcx(), ty);
if let ty::InstanceKind::Shim(ty::ShimKind::DropGlue(_, None)) =
drop_fn.def {
return helper.funclet_br(self, bx, target, mergeable_succ,
&[]);
}
let place = self.codegen_place(bx, location.as_ref());
let (args1, args2);
let mut args =
if let Some(llextra) = place.val.llextra {
args2 = [place.val.llval, llextra];
&args2[..]
} else { args1 = [place.val.llval]; &args1[..] };
let (maybe_null, drop_fn, fn_abi, drop_instance) =
match ty.kind() {
ty::Dynamic(_, _) => {
let virtual_drop =
Instance {
def: ty::InstanceKind::Virtual(drop_fn.def_id(), 0),
args: drop_fn.args,
};
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/249c1e4e31111b54ad2483cfd4cea06c7020c653/compiler/rustc_codegen_ssa/src/mir/block.rs:700",
"rustc_codegen_ssa::mir::block", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/249c1e4e31111b54ad2483cfd4cea06c7020c653/compiler/rustc_codegen_ssa/src/mir/block.rs"),
::tracing_core::__macro_support::Option::Some(700u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::mir::block"),
::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!("ty = {0:?}",
ty) as &dyn ::tracing::field::Value))])
});
} else { ; }
};
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/249c1e4e31111b54ad2483cfd4cea06c7020c653/compiler/rustc_codegen_ssa/src/mir/block.rs:701",
"rustc_codegen_ssa::mir::block", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/249c1e4e31111b54ad2483cfd4cea06c7020c653/compiler/rustc_codegen_ssa/src/mir/block.rs"),
::tracing_core::__macro_support::Option::Some(701u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::mir::block"),
::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!("drop_fn = {0:?}",
drop_fn) as &dyn ::tracing::field::Value))])
});
} else { ; }
};
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/249c1e4e31111b54ad2483cfd4cea06c7020c653/compiler/rustc_codegen_ssa/src/mir/block.rs:702",
"rustc_codegen_ssa::mir::block", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/249c1e4e31111b54ad2483cfd4cea06c7020c653/compiler/rustc_codegen_ssa/src/mir/block.rs"),
::tracing_core::__macro_support::Option::Some(702u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::mir::block"),
::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!("args = {0:?}",
args) as &dyn ::tracing::field::Value))])
});
} else { ; }
};
let fn_abi =
bx.fn_abi_of_instance(virtual_drop, ty::List::empty());
let vtable = args[1];
args = &args[..1];
(true,
meth::VirtualIndex::from_index(ty::COMMON_VTABLE_ENTRIES_DROPINPLACE).get_optional_fn(bx,
vtable, ty, fn_abi), fn_abi, virtual_drop)
}
_ =>
(false,
bx.get_fn_addr(drop_fn,
bx.sess().pointer_authentication_functions()),
bx.fn_abi_of_instance(drop_fn, ty::List::empty()), drop_fn),
};
if maybe_null {
let is_not_null = bx.append_sibling_block("is_not_null");
let llty = bx.fn_ptr_backend_type(fn_abi);
let null = bx.const_null(llty);
let non_null =
bx.icmp(base::bin_op_to_icmp_predicate(mir::BinOp::Ne,
false), drop_fn, null);
bx.cond_br(non_null, is_not_null,
helper.llbb_with_cleanup(self, target));
bx.switch_to_block(is_not_null);
self.set_debug_loc(bx, *source_info);
}
helper.do_call(self, bx, fn_abi, drop_fn, ReturnSlot::Direct,
args, Some((ReturnDest::Nothing, target)), unwind, &[],
Some(drop_instance), CallKind::Normal,
!maybe_null && mergeable_succ)
}
}
}#[tracing::instrument(level = "trace", skip(self, helper, bx))]
652 fn codegen_drop_terminator(
653 &mut self,
654 helper: TerminatorCodegenHelper<'tcx>,
655 bx: &mut Bx,
656 source_info: &mir::SourceInfo,
657 location: mir::Place<'tcx>,
658 target: mir::BasicBlock,
659 unwind: mir::UnwindAction,
660 mergeable_succ: bool,
661 ) -> MergingSucc {
662 let ty = location.ty(self.mir, bx.tcx()).ty;
663 let ty = self.monomorphize(ty);
664 let drop_fn = Instance::resolve_drop_glue(bx.tcx(), ty);
665
666 if let ty::InstanceKind::Shim(ty::ShimKind::DropGlue(_, None)) = drop_fn.def {
667 return helper.funclet_br(self, bx, target, mergeable_succ, &[]);
669 }
670
671 let place = self.codegen_place(bx, location.as_ref());
672 let (args1, args2);
673 let mut args = if let Some(llextra) = place.val.llextra {
674 args2 = [place.val.llval, llextra];
675 &args2[..]
676 } else {
677 args1 = [place.val.llval];
678 &args1[..]
679 };
680 let (maybe_null, drop_fn, fn_abi, drop_instance) = match ty.kind() {
681 ty::Dynamic(_, _) => {
684 let virtual_drop = Instance {
697 def: ty::InstanceKind::Virtual(drop_fn.def_id(), 0), args: drop_fn.args,
699 };
700 debug!("ty = {:?}", ty);
701 debug!("drop_fn = {:?}", drop_fn);
702 debug!("args = {:?}", args);
703 let fn_abi = bx.fn_abi_of_instance(virtual_drop, ty::List::empty());
704 let vtable = args[1];
705 args = &args[..1];
707 (
708 true,
709 meth::VirtualIndex::from_index(ty::COMMON_VTABLE_ENTRIES_DROPINPLACE)
710 .get_optional_fn(bx, vtable, ty, fn_abi),
711 fn_abi,
712 virtual_drop,
713 )
714 }
715 _ => (
716 false,
717 bx.get_fn_addr(drop_fn, bx.sess().pointer_authentication_functions()),
718 bx.fn_abi_of_instance(drop_fn, ty::List::empty()),
719 drop_fn,
720 ),
721 };
722
723 if maybe_null {
726 let is_not_null = bx.append_sibling_block("is_not_null");
727 let llty = bx.fn_ptr_backend_type(fn_abi);
728 let null = bx.const_null(llty);
729 let non_null =
730 bx.icmp(base::bin_op_to_icmp_predicate(mir::BinOp::Ne, false), drop_fn, null);
731 bx.cond_br(non_null, is_not_null, helper.llbb_with_cleanup(self, target));
732 bx.switch_to_block(is_not_null);
733 self.set_debug_loc(bx, *source_info);
734 }
735
736 helper.do_call(
737 self,
738 bx,
739 fn_abi,
740 drop_fn,
741 ReturnSlot::Direct,
742 args,
743 Some((ReturnDest::Nothing, target)),
744 unwind,
745 &[],
746 Some(drop_instance),
747 CallKind::Normal,
748 !maybe_null && mergeable_succ,
749 )
750 }
751
752 fn codegen_assert_terminator(
753 &mut self,
754 helper: TerminatorCodegenHelper<'tcx>,
755 bx: &mut Bx,
756 terminator: &mir::Terminator<'tcx>,
757 cond: &mir::Operand<'tcx>,
758 expected: bool,
759 msg: &mir::AssertMessage<'tcx>,
760 target: mir::BasicBlock,
761 unwind: mir::UnwindAction,
762 mergeable_succ: bool,
763 ) -> MergingSucc {
764 let span = terminator.source_info.span;
765 let cond = self.codegen_operand(bx, cond).immediate();
766 let mut const_cond = bx.const_to_opt_u128(cond, false).map(|c| c == 1);
767
768 if !bx.sess().overflow_checks() && msg.is_optional_overflow_check() {
773 const_cond = Some(expected);
774 }
775
776 if const_cond == Some(expected) {
778 return helper.funclet_br(self, bx, target, mergeable_succ, &[]);
779 }
780
781 let lltarget = helper.llbb_with_cleanup(self, target);
786 let panic_block = bx.append_sibling_block("panic");
787 if expected {
788 bx.cond_br(cond, lltarget, panic_block);
789 } else {
790 bx.cond_br(cond, panic_block, lltarget);
791 }
792
793 bx.switch_to_block(panic_block);
795 self.set_debug_loc(bx, terminator.source_info);
796
797 let location = self.get_caller_location(bx, terminator.source_info).immediate();
799
800 let (lang_item, args) = match msg {
802 AssertKind::BoundsCheck { len, index } => {
803 let len = self.codegen_operand(bx, len).immediate();
804 let index = self.codegen_operand(bx, index).immediate();
805 (LangItem::PanicBoundsCheck, ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[index, len, location]))vec![index, len, location])
808 }
809 AssertKind::MisalignedPointerDereference { required, found } => {
810 let required = self.codegen_operand(bx, required).immediate();
811 let found = self.codegen_operand(bx, found).immediate();
812 (LangItem::PanicMisalignedPointerDereference, ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[required, found, location]))vec![required, found, location])
815 }
816 AssertKind::NullPointerDereference => {
817 (LangItem::PanicNullPointerDereference, ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[location]))vec![location])
820 }
821 AssertKind::NullReferenceConstructed => {
822 (LangItem::PanicNullReferenceConstructed, ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[location]))vec![location])
825 }
826 AssertKind::InvalidEnumConstruction(source) => {
827 let source = self.codegen_operand(bx, source).immediate();
828 (LangItem::PanicInvalidEnumConstruction, ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[source, location]))vec![source, location])
831 }
832 _ => {
833 (msg.panic_function(), ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[location]))vec![location])
835 }
836 };
837
838 let (fn_abi, llfn, instance) = common::build_langcall(bx, span, lang_item);
839
840 let merging_succ = helper.do_call(
842 self,
843 bx,
844 fn_abi,
845 llfn,
846 ReturnSlot::Direct,
847 &args,
848 None,
849 unwind,
850 &[],
851 Some(instance),
852 CallKind::Normal,
853 false,
854 );
855 {
match (&merging_succ, &MergingSucc::False) {
(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!(merging_succ, MergingSucc::False);
856 MergingSucc::False
857 }
858
859 fn codegen_terminate_terminator(
860 &mut self,
861 helper: TerminatorCodegenHelper<'tcx>,
862 bx: &mut Bx,
863 terminator: &mir::Terminator<'tcx>,
864 reason: UnwindTerminateReason,
865 ) {
866 let span = terminator.source_info.span;
867 self.set_debug_loc(bx, terminator.source_info);
868
869 let (fn_abi, llfn, instance) = common::build_langcall(bx, span, reason.lang_item());
871
872 let merging_succ = helper.do_call(
874 self,
875 bx,
876 fn_abi,
877 llfn,
878 ReturnSlot::Direct,
879 &[],
880 None,
881 mir::UnwindAction::Unreachable,
882 &[],
883 Some(instance),
884 CallKind::Normal,
885 false,
886 );
887 {
match (&merging_succ, &MergingSucc::False) {
(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!(merging_succ, MergingSucc::False);
888 }
889
890 fn codegen_panic_intrinsic(
892 &mut self,
893 helper: &TerminatorCodegenHelper<'tcx>,
894 bx: &mut Bx,
895 intrinsic: ty::IntrinsicDef,
896 instance: Instance<'tcx>,
897 source_info: mir::SourceInfo,
898 target: Option<mir::BasicBlock>,
899 unwind: mir::UnwindAction,
900 mergeable_succ: bool,
901 ) -> Option<MergingSucc> {
902 let Some(requirement) = ValidityRequirement::from_intrinsic(intrinsic.name) else {
906 return None;
907 };
908
909 let ty = instance.args.type_at(0);
910
911 let is_valid = bx
912 .tcx()
913 .check_validity_requirement((requirement, bx.typing_env().as_query_input(ty)))
914 .expect("expect to have layout during codegen");
915
916 if is_valid {
917 let target = target.unwrap();
919 return Some(helper.funclet_br(self, bx, target, mergeable_succ, &[]));
920 }
921
922 let layout = bx.layout_of(ty);
923
924 let msg_str = {
let _guard = NoVisibleGuard::new();
{
{
let _guard = NoTrimmedGuard::new();
{
if layout.is_uninhabited() {
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("attempted to instantiate uninhabited type `{0}`",
ty))
})
} else if requirement == ValidityRequirement::Zero {
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("attempted to zero-initialize type `{0}`, which is invalid",
ty))
})
} else {
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("attempted to leave type `{0}` uninitialized, which is invalid",
ty))
})
}
}
}
}
}with_no_visible_paths!({
925 with_no_trimmed_paths!({
926 if layout.is_uninhabited() {
927 format!("attempted to instantiate uninhabited type `{ty}`")
929 } else if requirement == ValidityRequirement::Zero {
930 format!("attempted to zero-initialize type `{ty}`, which is invalid")
931 } else {
932 format!("attempted to leave type `{ty}` uninitialized, which is invalid")
933 }
934 })
935 });
936 let msg = bx.const_str(&msg_str);
937
938 let (fn_abi, llfn, instance) =
940 common::build_langcall(bx, source_info.span, LangItem::PanicNounwind);
941
942 Some(helper.do_call(
944 self,
945 bx,
946 fn_abi,
947 llfn,
948 ReturnSlot::Direct,
949 &[msg.0, msg.1],
950 target.as_ref().map(|bb| (ReturnDest::Nothing, *bb)),
951 unwind,
952 &[],
953 Some(instance),
954 CallKind::Normal,
955 mergeable_succ,
956 ))
957 }
958
959 fn codegen_call_terminator(
960 &mut self,
961 helper: TerminatorCodegenHelper<'tcx>,
962 bx: &mut Bx,
963 terminator: &mir::Terminator<'tcx>,
964 func: &mir::Operand<'tcx>,
965 args: &[Spanned<mir::Operand<'tcx>>],
966 destination: mir::Place<'tcx>,
967 target: Option<mir::BasicBlock>,
968 unwind: mir::UnwindAction,
969 fn_span: Span,
970 kind: CallKind,
971 mergeable_succ: bool,
972 ) -> MergingSucc {
973 let source_info = mir::SourceInfo { span: fn_span, ..terminator.source_info };
974
975 let callee = self.codegen_operand(bx, func);
977
978 let (instance, mut llfn) = match *callee.layout.ty.kind() {
979 ty::FnDef(def_id, generic_args) => {
980 let instance = ty::Instance::expect_resolve(
981 bx.tcx(),
982 bx.typing_env(),
983 def_id,
984 generic_args.no_bound_vars().unwrap(),
985 fn_span,
986 );
987
988 match instance.def {
989 ty::InstanceKind::Shim(ty::ShimKind::DropGlue(_, None)) => {
992 let target = target.unwrap();
994 return helper.funclet_br(self, bx, target, mergeable_succ, &[]);
995 }
996 ty::InstanceKind::Intrinsic(def_id) => {
997 let intrinsic = bx.tcx().intrinsic(def_id).unwrap();
998 if let Some(merging_succ) = self.codegen_panic_intrinsic(
999 &helper,
1000 bx,
1001 intrinsic,
1002 instance,
1003 source_info,
1004 target,
1005 unwind,
1006 mergeable_succ,
1007 ) {
1008 return merging_succ;
1009 }
1010
1011 let result_layout =
1012 self.cx.layout_of(self.monomorphized_place_ty(destination.as_ref()));
1013
1014 let (result_place, store_in_local) =
1015 if let Some(local) = destination.as_local() {
1016 match self.locals[local] {
1017 LocalRef::Place(dest) => (Some(dest.val), None),
1018 LocalRef::UnsizedPlace(_) => ::rustc_span::macros::bug_impl(None,
format_args!("return type must be sized"), Location::caller())bug!("return type must be sized"),
1019 LocalRef::PendingOperand => (None, Some(local)),
1020 LocalRef::Operand(_) => {
1021 if result_layout.is_zst() {
1022 let place = PlaceRef::new_sized(
1023 bx.const_undef(bx.type_ptr()),
1024 result_layout,
1025 );
1026 (Some(place.val), None)
1027 } else {
1028 ::rustc_span::macros::bug_impl(None,
format_args!("place local already assigned to"), Location::caller());bug!("place local already assigned to");
1029 }
1030 }
1031 }
1032 } else {
1033 (Some(self.codegen_place(bx, destination.as_ref()).val), None)
1034 };
1035
1036 if let Some(place) = result_place
1037 && place.align < result_layout.align
1038 {
1039 ::rustc_span::macros::bug_impl(Some(self.mir.span),
format_args!("can\'t directly store to unaligned value"),
Location::caller());span_bug!(self.mir.span, "can't directly store to unaligned value");
1046 }
1047
1048 let args: Vec<_> =
1049 args.iter().map(|arg| self.codegen_operand(bx, &arg.node)).collect();
1050
1051 let intrinsic_result = self.codegen_intrinsic_call(
1052 bx,
1053 instance,
1054 &args,
1055 result_layout,
1056 result_place,
1057 source_info,
1058 );
1059
1060 if let IntrinsicResult::Operand(op_val) = intrinsic_result {
1061 match (result_place, store_in_local) {
1062 (None, Some(local)) => {
1063 let op = OperandRef {
1064 val: op_val,
1065 layout: result_layout,
1066 move_annotation: None,
1067 };
1068 self.overwrite_local(local, LocalRef::Operand(op));
1069 self.debug_introduce_local(bx, local);
1070 }
1071 (Some(place_val), None) => {
1072 let dest = PlaceRef { val: place_val, layout: result_layout };
1073 op_val.store(bx, dest);
1074 }
1075 _ => ::rustc_span::macros::bug_impl(None, format_args!("impossible case reached"),
Location::caller())bug!(),
1076 }
1077 }
1078
1079 match intrinsic_result {
1080 IntrinsicResult::Operand(_) | IntrinsicResult::WroteIntoPlace => {
1081 return if let Some(target) = target {
1082 helper.funclet_br(self, bx, target, mergeable_succ, &[])
1083 } else {
1084 bx.unreachable();
1085 MergingSucc::False
1086 };
1087 }
1088 IntrinsicResult::Err(_) => {
1089 if let Some(local) = store_in_local {
1093 let op = OperandRef {
1094 val: OperandValue::poison(bx, result_layout),
1095 layout: result_layout,
1096 move_annotation: None,
1097 };
1098 self.overwrite_local(local, LocalRef::Operand(op));
1099 }
1100 bx.abort_immediate();
1103 return MergingSucc::False;
1104 }
1105 IntrinsicResult::Fallback(instance) => {
1106 if intrinsic.must_be_overridden {
1107 ::rustc_span::macros::bug_impl(Some(fn_span),
format_args!("intrinsic {0} must be overridden by codegen backend, but isn\'t",
intrinsic.name), Location::caller());span_bug!(
1108 fn_span,
1109 "intrinsic {} must be overridden by codegen backend, but isn't",
1110 intrinsic.name,
1111 );
1112 }
1113 (Some(instance), None)
1114 }
1115 }
1116 }
1117
1118 _ if kind == CallKind::Tail
1119 && instance.def.requires_caller_location(bx.tcx()) =>
1120 {
1121 if let Some(hir_id) =
1122 terminator.source_info.scope.lint_root(&self.mir.source_scopes)
1123 {
1124 bx.tcx().emit_node_lint(TAIL_CALL_TRACK_CALLER, hir_id, rustc_errors::DiagDecorator(|d| {
1125 _ = d.primary_message("tail calling a function marked with `#[track_caller]` has no special effect").span(fn_span)
1126 }));
1127 }
1128
1129 let instance = ty::Instance::resolve_for_fn_ptr(
1130 bx.tcx(),
1131 bx.typing_env(),
1132 def_id,
1133 generic_args.no_bound_vars().unwrap(),
1134 )
1135 .unwrap();
1136
1137 (
1138 None,
1139 Some(bx.get_fn_addr(
1140 instance,
1141 bx.sess().pointer_authentication_functions(),
1142 )),
1143 )
1144 }
1145 _ => (Some(instance), None),
1146 }
1147 }
1148 ty::FnPtr(..) => (None, Some(callee.immediate())),
1149 _ => ::rustc_span::macros::bug_impl(None,
format_args!("{0} is not callable", callee.layout.ty), Location::caller())bug!("{} is not callable", callee.layout.ty),
1150 };
1151
1152 if let Some(instance) = instance
1153 && let ty::InstanceKind::LlvmIntrinsic(_) = instance.def
1154 && let Some(name) = bx.tcx().codegen_fn_attrs(instance.def_id()).symbol_name
1155 && name.as_str() != "llvm.wasm.throw"
1159 {
1160 if !!instance.args.has_infer() {
::core::panicking::panic("assertion failed: !instance.args.has_infer()")
};assert!(!instance.args.has_infer());
1161 if !!instance.args.has_escaping_bound_vars() {
::core::panicking::panic("assertion failed: !instance.args.has_escaping_bound_vars()")
};assert!(!instance.args.has_escaping_bound_vars());
1162
1163 let result_layout =
1164 self.cx.layout_of(self.monomorphized_place_ty(destination.as_ref()));
1165
1166 let return_dest = if result_layout.is_zst() {
1167 ReturnDest::Nothing
1168 } else if let Some(index) = destination.as_local() {
1169 match self.locals[index] {
1170 LocalRef::Place(dest) => ReturnDest::Store(dest),
1171 LocalRef::UnsizedPlace(_) => ::rustc_span::macros::bug_impl(None,
format_args!("return type must be sized"), Location::caller())bug!("return type must be sized"),
1172 LocalRef::PendingOperand => {
1173 ReturnDest::DirectOperand(index)
1176 }
1177 LocalRef::Operand(_) => ::rustc_span::macros::bug_impl(None,
format_args!("place local already assigned to"), Location::caller())bug!("place local already assigned to"),
1178 }
1179 } else {
1180 ReturnDest::Store(self.codegen_place(bx, destination.as_ref()))
1181 };
1182
1183 let args =
1184 args.into_iter().map(|arg| self.codegen_operand(bx, &arg.node)).collect::<Vec<_>>();
1185
1186 self.set_debug_loc(bx, source_info);
1187
1188 let llret =
1189 bx.codegen_llvm_intrinsic_call(instance, &args, self.mir[helper.bb].is_cleanup);
1190
1191 if let Some(target) = target {
1192 self.store_return(
1193 bx,
1194 return_dest,
1195 &ArgAbi { layout: result_layout, mode: PassMode::Direct(ArgAttributes::new()) },
1196 llret,
1197 );
1198 return helper.funclet_br(self, bx, target, mergeable_succ, &[]);
1199 } else {
1200 bx.unreachable();
1201 return MergingSucc::False;
1202 }
1203 }
1204
1205 let sig = callee.layout.ty.fn_sig(bx.tcx());
1209
1210 let extra_args = &args[sig.inputs().skip_binder().len()..];
1211 let extra_args = bx.tcx().mk_type_list_from_iter(extra_args.iter().map(|op_arg| {
1212 let op_ty = op_arg.node.ty(self.mir, bx.tcx());
1213 self.monomorphize(op_ty)
1214 }));
1215
1216 let fn_abi = match instance {
1217 Some(instance) => bx.fn_abi_of_instance(instance, extra_args),
1218 None => bx.fn_abi_of_fn_ptr(sig, extra_args),
1219 };
1220
1221 let arg_count = fn_abi.args.len() + fn_abi.ret.is_indirect() as usize;
1223
1224 let mut llargs = Vec::with_capacity(arg_count);
1225
1226 let (destination, return_slot) = match kind {
1230 CallKind::Normal => {
1231 let (return_dest, return_slot) =
1232 self.make_return_dest(bx, destination, &fn_abi.ret);
1233 (target.map(|target| (return_dest, target)), return_slot)
1234 }
1235 CallKind::Tail => {
1236 let return_slot = if fn_abi.ret.is_indirect() {
1237 match self.make_return_dest(bx, destination, &fn_abi.ret) {
1238 (ReturnDest::Nothing, return_slot) => return_slot,
1239 _ => ::rustc_span::macros::bug_impl(None,
format_args!("tail calls to functions with indirect returns cannot store into a destination"),
Location::caller())bug!(
1240 "tail calls to functions with indirect returns cannot store into a destination"
1241 ),
1242 }
1243 } else {
1244 ReturnSlot::Direct
1245 };
1246 (None, return_slot)
1247 }
1248 };
1249
1250 let (first_args, untuple) = if sig.abi() == ExternAbi::RustCall
1253 && let Some((tup, args)) = args.split_last()
1254 {
1255 (args, Some(tup))
1256 } else {
1257 (args, None)
1258 };
1259
1260 let mut tail_call_temporaries = ::alloc::vec::Vec::new()vec![];
1283 if kind == CallKind::Tail {
1284 tail_call_temporaries = ::alloc::vec::from_elem_global(None, first_args.len())vec![None; first_args.len()];
1285 for (i, arg) in first_args.iter().enumerate() {
1288 if #[allow(non_exhaustive_omitted_patterns)] match fn_abi.args[i].mode {
PassMode::IndirectUnsized { .. } => true,
_ => false,
}matches!(fn_abi.args[i].mode, PassMode::IndirectUnsized { .. }) {
1289 ::rustc_span::macros::bug_impl(None,
format_args!("extern \"tail\" arguments must not be unsized"),
Location::caller());bug!("extern \"tail\" arguments must not be unsized");
1290 }
1291
1292 if !#[allow(non_exhaustive_omitted_patterns)] match fn_abi.args[i].mode {
PassMode::Indirect { mode: IndirectMode::Pointer, .. } => true,
_ => false,
}matches!(
1293 fn_abi.args[i].mode,
1294 PassMode::Indirect { mode: IndirectMode::Pointer, .. }
1295 ) {
1296 continue;
1297 }
1298
1299 let op = self.codegen_operand(bx, &arg.node);
1300 let tmp = PlaceRef::alloca(bx, op.layout);
1301 bx.lifetime_start(tmp.val.llval, tmp.layout.size);
1302 op.store_with_annotation(bx, tmp);
1303
1304 tail_call_temporaries[i] = Some(tmp);
1305 }
1306 }
1307
1308 let mut lifetime_ends_after_call: Vec<(Bx::Value, Size)> = Vec::new();
1312 'make_args: for (i, arg) in first_args.iter().enumerate() {
1313 let mut op = self.codegen_operand(bx, &arg.node);
1314
1315 if let (0, Some(ty::InstanceKind::Virtual(_, idx))) = (i, instance.map(|i| i.def)) {
1316 match op.val {
1317 Pair(data_ptr, meta) => {
1318 while !op.layout.ty.is_raw_ptr() && !op.layout.ty.is_ref() {
1328 let (idx, _) = op.layout.non_1zst_field(bx).expect(
1329 "not exactly one non-1-ZST field in a `DispatchFromDyn` type",
1330 );
1331 op = op.extract_field(self, bx, idx.as_usize());
1332 }
1333
1334 llfn = Some(meth::VirtualIndex::from_index(idx).get_fn(
1338 bx,
1339 meta,
1340 op.layout.ty,
1341 fn_abi,
1342 ));
1343 llargs.push(data_ptr);
1344 continue 'make_args;
1345 }
1346 Ref(PlaceValue { llval: data_ptr, llextra: Some(meta), .. }) => {
1347 llfn = Some(meth::VirtualIndex::from_index(idx).get_fn(
1349 bx,
1350 meta,
1351 op.layout.ty,
1352 fn_abi,
1353 ));
1354 llargs.push(data_ptr);
1355 continue;
1356 }
1357 _ => {
1358 ::rustc_span::macros::bug_impl(Some(fn_span),
format_args!("can\'t codegen a virtual call on {0:#?}", op),
Location::caller());span_bug!(fn_span, "can't codegen a virtual call on {:#?}", op);
1359 }
1360 }
1361 }
1362
1363 let by_move = if let PassMode::Indirect { mode: IndirectMode::Pointer, .. } =
1364 fn_abi.args[i].mode
1365 && kind == CallKind::Tail
1366 {
1367 let Some(tmp) = tail_call_temporaries[i].take() else {
1380 ::rustc_span::macros::bug_impl(Some(fn_span),
format_args!("missing temporary for indirect tail call argument #{0}", i),
Location::caller())span_bug!(fn_span, "missing temporary for indirect tail call argument #{i}")
1381 };
1382
1383 let local = self.mir.args_iter().nth(i).unwrap();
1384
1385 match &self.locals[local] {
1386 LocalRef::Place(arg) => {
1387 bx.typed_place_copy(arg.val, tmp.val, fn_abi.args[i].layout);
1388 op.val = Ref(arg.val);
1389 }
1390 LocalRef::Operand(arg) => {
1391 let Ref(place_value) = arg.val else {
1392 ::rustc_span::macros::bug_impl(None,
format_args!("only `Ref` should use `PassMode::Indirect`, but got {0:?}",
arg.val), Location::caller());bug!(
1393 "only `Ref` should use `PassMode::Indirect`, but got {:?}",
1394 arg.val
1395 );
1396 };
1397 bx.typed_place_copy(place_value, tmp.val, fn_abi.args[i].layout);
1398 op.val = arg.val;
1399 }
1400 LocalRef::UnsizedPlace(_) => {
1401 ::rustc_span::macros::bug_impl(Some(fn_span),
format_args!("unsized types are not supported"), Location::caller())span_bug!(fn_span, "unsized types are not supported")
1402 }
1403 LocalRef::PendingOperand => {
1404 ::rustc_span::macros::bug_impl(Some(fn_span),
format_args!("argument local should not be pending"), Location::caller())span_bug!(fn_span, "argument local should not be pending")
1405 }
1406 };
1407
1408 bx.lifetime_end(tmp.val.llval, tmp.layout.size);
1409 true
1410 } else {
1411 #[allow(non_exhaustive_omitted_patterns)] match arg.node {
mir::Operand::Move(_) => true,
_ => false,
}matches!(arg.node, mir::Operand::Move(_))
1412 };
1413
1414 self.codegen_argument(
1415 bx,
1416 fn_abi.conv,
1417 op,
1418 by_move,
1419 &mut llargs,
1420 &fn_abi.args[i],
1421 &mut lifetime_ends_after_call,
1422 );
1423 }
1424 let num_untupled = untuple.map(|tup| {
1425 self.codegen_arguments_untupled(
1426 bx,
1427 fn_abi.conv,
1428 &tup.node,
1429 &mut llargs,
1430 &fn_abi.args[first_args.len()..],
1431 &mut lifetime_ends_after_call,
1432 )
1433 });
1434
1435 let needs_location =
1436 instance.is_some_and(|i| i.def.requires_caller_location(self.cx.tcx()));
1437 if needs_location {
1438 let mir_args = if let Some(num_untupled) = num_untupled {
1439 first_args.len() + num_untupled
1440 } else {
1441 args.len()
1442 };
1443 {
match (&fn_abi.args.len(), &(mir_args + 1)) {
(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::Some(format_args!("#[track_caller] fn\'s must have 1 more argument in their ABI than in their MIR: {0:?} {1:?} {2:?}",
instance, fn_span, fn_abi)));
}
}
}
};assert_eq!(
1444 fn_abi.args.len(),
1445 mir_args + 1,
1446 "#[track_caller] fn's must have 1 more argument in their ABI than in their MIR: {instance:?} {fn_span:?} {fn_abi:?}",
1447 );
1448 let location = self.get_caller_location(bx, source_info);
1449 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/249c1e4e31111b54ad2483cfd4cea06c7020c653/compiler/rustc_codegen_ssa/src/mir/block.rs:1449",
"rustc_codegen_ssa::mir::block", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/249c1e4e31111b54ad2483cfd4cea06c7020c653/compiler/rustc_codegen_ssa/src/mir/block.rs"),
::tracing_core::__macro_support::Option::Some(1449u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::mir::block"),
::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!("codegen_call_terminator({0:?}): location={1:?} (fn_span {2:?})",
terminator, location, fn_span) as
&dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(
1450 "codegen_call_terminator({:?}): location={:?} (fn_span {:?})",
1451 terminator, location, fn_span
1452 );
1453
1454 let last_arg = fn_abi.args.last().unwrap();
1455 self.codegen_argument(
1456 bx,
1457 fn_abi.conv,
1458 location,
1459 false,
1460 &mut llargs,
1461 last_arg,
1462 &mut lifetime_ends_after_call,
1463 );
1464 }
1465
1466 let fn_ptr = match (instance, llfn) {
1467 (Some(instance), None) => {
1468 bx.get_fn_addr(instance, bx.sess().pointer_authentication_functions())
1469 }
1470 (_, Some(llfn)) => llfn,
1471 _ => ::rustc_span::macros::bug_impl(Some(fn_span),
format_args!("no instance or llfn for call"), Location::caller())span_bug!(fn_span, "no instance or llfn for call"),
1472 };
1473 self.set_debug_loc(bx, source_info);
1474 helper.do_call(
1475 self,
1476 bx,
1477 fn_abi,
1478 fn_ptr,
1479 return_slot,
1480 &llargs,
1481 destination,
1482 unwind,
1483 &lifetime_ends_after_call,
1484 instance,
1485 kind,
1486 mergeable_succ,
1487 )
1488 }
1489
1490 fn codegen_asm_terminator(
1491 &mut self,
1492 helper: TerminatorCodegenHelper<'tcx>,
1493 bx: &mut Bx,
1494 asm_macro: InlineAsmMacro,
1495 terminator: &mir::Terminator<'tcx>,
1496 template: &[ast::InlineAsmTemplatePiece],
1497 operands: &[mir::InlineAsmOperand<'tcx>],
1498 options: ast::InlineAsmOptions,
1499 line_spans: &[Span],
1500 targets: &[mir::BasicBlock],
1501 unwind: mir::UnwindAction,
1502 instance: Instance<'_>,
1503 mergeable_succ: bool,
1504 ) -> MergingSucc {
1505 let span = terminator.source_info.span;
1506
1507 let mut any_input_uninhabited = false;
1512
1513 let operands: Vec<_> = operands
1514 .iter()
1515 .map(|op| match *op {
1516 mir::InlineAsmOperand::In { reg, ref value } => {
1517 let value = self.codegen_operand(bx, value);
1518 if value.layout.is_uninhabited() {
1519 any_input_uninhabited = true;
1520 }
1521 InlineAsmOperandRef::In { reg, value }
1522 }
1523 mir::InlineAsmOperand::Out { reg, late, ref place } => {
1524 let place = place.map(|place| self.codegen_place(bx, place.as_ref()));
1525 InlineAsmOperandRef::Out { reg, late, place }
1526 }
1527 mir::InlineAsmOperand::InOut { reg, late, ref in_value, ref out_place } => {
1528 let in_value = self.codegen_operand(bx, in_value);
1529 if in_value.layout.is_uninhabited() {
1530 any_input_uninhabited = true;
1531 }
1532 let out_place =
1533 out_place.map(|out_place| self.codegen_place(bx, out_place.as_ref()));
1534 InlineAsmOperandRef::InOut { reg, late, in_value, out_place }
1535 }
1536 mir::InlineAsmOperand::Const { ref value } => {
1537 let const_value = self.eval_mir_constant(value);
1538 let mir::ConstValue::Scalar(scalar) = const_value else {
1539 ::rustc_span::macros::bug_impl(Some(span),
format_args!("expected Scalar for promoted asm const, but got {0:#?}",
const_value), Location::caller())span_bug!(
1540 span,
1541 "expected Scalar for promoted asm const, but got {:#?}",
1542 const_value
1543 )
1544 };
1545 InlineAsmOperandRef::Const {
1546 value: common::asm_const_ptr_clean(bx.tcx(), scalar),
1547 ty: value.ty(),
1548 }
1549 }
1550 mir::InlineAsmOperand::SymFn { ref value } => {
1551 let const_ = self.monomorphize(value.const_);
1552 if let ty::FnDef(def_id, args) = *const_.ty().kind() {
1553 let instance = ty::Instance::resolve_for_fn_ptr(
1554 bx.tcx(),
1555 bx.typing_env(),
1556 def_id,
1557 args.no_bound_vars().unwrap(),
1558 )
1559 .unwrap();
1560
1561 InlineAsmOperandRef::Const {
1562 value: Scalar::from_pointer(
1563 bx.tcx().reserve_and_set_fn_alloc(instance, CTFE_ALLOC_SALT).into(),
1564 bx,
1565 ),
1566 ty: Ty::new_fn_ptr(bx.tcx(), const_.ty().fn_sig(bx.tcx())),
1567 }
1568 } else {
1569 ::rustc_span::macros::bug_impl(Some(span),
format_args!("invalid type for asm sym (fn)"), Location::caller());span_bug!(span, "invalid type for asm sym (fn)");
1570 }
1571 }
1572 mir::InlineAsmOperand::SymStatic { def_id } => {
1573 if bx.tcx().is_thread_local_static(def_id) {
1574 InlineAsmOperandRef::SymThreadLocalStatic { def_id }
1575 } else {
1576 InlineAsmOperandRef::Const {
1577 value: Scalar::from_pointer(
1578 bx.tcx().reserve_and_set_static_alloc(def_id).into(),
1579 bx,
1580 ),
1581 ty: bx.tcx().static_ptr_ty(def_id, bx.typing_env()),
1582 }
1583 }
1584 }
1585 mir::InlineAsmOperand::Label { target_index } => {
1586 InlineAsmOperandRef::Label { label: self.llbb(targets[target_index]) }
1587 }
1588 })
1589 .collect();
1590
1591 if any_input_uninhabited {
1592 bx.unreachable();
1593 MergingSucc::False
1594 } else {
1595 helper.do_inlineasm(
1596 self,
1597 bx,
1598 template,
1599 &operands,
1600 options,
1601 line_spans,
1602 if asm_macro.diverges(options) { None } else { targets.get(0).copied() },
1603 unwind,
1604 instance,
1605 mergeable_succ,
1606 )
1607 }
1608 }
1609
1610 pub(crate) fn codegen_block(&mut self, mut bb: mir::BasicBlock) {
1611 let llbb = match self.try_llbb(bb) {
1612 Some(llbb) => llbb,
1613 None => return,
1614 };
1615 let bx = &mut Bx::build(self.cx, llbb);
1616 let mir = self.mir;
1617
1618 loop {
1622 let data = &mir[bb];
1623
1624 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/249c1e4e31111b54ad2483cfd4cea06c7020c653/compiler/rustc_codegen_ssa/src/mir/block.rs:1624",
"rustc_codegen_ssa::mir::block", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/249c1e4e31111b54ad2483cfd4cea06c7020c653/compiler/rustc_codegen_ssa/src/mir/block.rs"),
::tracing_core::__macro_support::Option::Some(1624u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::mir::block"),
::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!("codegen_block({0:?}={1:?})",
bb, data) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("codegen_block({:?}={:?})", bb, data);
1625
1626 for statement in &data.statements {
1627 self.codegen_statement(bx, statement);
1628 }
1629 self.codegen_stmt_debuginfos(bx, &data.after_last_stmt_debuginfos);
1630
1631 let merging_succ = self.codegen_terminator(bx, bb, data.terminator());
1632 if let MergingSucc::False = merging_succ {
1633 break;
1634 }
1635
1636 let mut successors = data.terminator().successors();
1644 let succ = successors.next().unwrap();
1645 if !#[allow(non_exhaustive_omitted_patterns)] match self.cached_llbbs[succ] {
CachedLlbb::None => true,
_ => false,
} {
::core::panicking::panic("assertion failed: matches!(self.cached_llbbs[succ], CachedLlbb::None)")
};assert!(matches!(self.cached_llbbs[succ], CachedLlbb::None));
1646 self.cached_llbbs[succ] = CachedLlbb::Skip;
1647 bb = succ;
1648 }
1649 }
1650
1651 pub(crate) fn codegen_block_as_unreachable(&mut self, bb: mir::BasicBlock) {
1652 let llbb = match self.try_llbb(bb) {
1653 Some(llbb) => llbb,
1654 None => return,
1655 };
1656 let bx = &mut Bx::build(self.cx, llbb);
1657 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/249c1e4e31111b54ad2483cfd4cea06c7020c653/compiler/rustc_codegen_ssa/src/mir/block.rs:1657",
"rustc_codegen_ssa::mir::block", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/249c1e4e31111b54ad2483cfd4cea06c7020c653/compiler/rustc_codegen_ssa/src/mir/block.rs"),
::tracing_core::__macro_support::Option::Some(1657u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::mir::block"),
::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!("codegen_block_as_unreachable({0:?})",
bb) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("codegen_block_as_unreachable({:?})", bb);
1658 bx.unreachable();
1659 }
1660
1661 fn codegen_terminator(
1662 &mut self,
1663 bx: &mut Bx,
1664 bb: mir::BasicBlock,
1665 terminator: &'tcx mir::Terminator<'tcx>,
1666 ) -> MergingSucc {
1667 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/249c1e4e31111b54ad2483cfd4cea06c7020c653/compiler/rustc_codegen_ssa/src/mir/block.rs:1667",
"rustc_codegen_ssa::mir::block", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/249c1e4e31111b54ad2483cfd4cea06c7020c653/compiler/rustc_codegen_ssa/src/mir/block.rs"),
::tracing_core::__macro_support::Option::Some(1667u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::mir::block"),
::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!("codegen_terminator: {0:?}",
terminator) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("codegen_terminator: {:?}", terminator);
1668
1669 let helper = TerminatorCodegenHelper { bb, terminator };
1670
1671 let mergeable_succ = || {
1672 let mut successors = terminator.successors();
1675 if let Some(succ) = successors.next()
1676 && successors.next().is_none()
1677 && let &[succ_pred] = self.mir.basic_blocks.predecessors()[succ].as_slice()
1678 {
1679 {
match (&succ_pred, &bb) {
(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!(succ_pred, bb);
1682 true
1683 } else {
1684 false
1685 }
1686 };
1687
1688 self.set_debug_loc(bx, terminator.source_info);
1689 match terminator.kind {
1690 mir::TerminatorKind::UnwindResume => {
1691 self.codegen_resume_terminator(helper, bx);
1692 MergingSucc::False
1693 }
1694
1695 mir::TerminatorKind::UnwindTerminate(reason) => {
1696 self.codegen_terminate_terminator(helper, bx, terminator, reason);
1697 MergingSucc::False
1698 }
1699
1700 mir::TerminatorKind::Goto { target, ref loop_hint_attrs } => {
1701 helper.funclet_br(self, bx, target, mergeable_succ(), loop_hint_attrs)
1702 }
1703
1704 mir::TerminatorKind::SwitchInt { ref discr, ref targets } => {
1705 self.codegen_switchint_terminator(helper, bx, discr, targets);
1706 MergingSucc::False
1707 }
1708
1709 mir::TerminatorKind::Return => {
1710 self.codegen_return_terminator(bx);
1711 MergingSucc::False
1712 }
1713
1714 mir::TerminatorKind::Unreachable => {
1715 bx.unreachable();
1716 MergingSucc::False
1717 }
1718
1719 mir::TerminatorKind::Drop { place, target, unwind, replace: _, drop } => {
1720 if !drop.is_none() {
{
::core::panicking::panic_fmt(format_args!("Async Drop must be expanded or reset to sync before codegen"));
}
};assert!(
1721 drop.is_none(),
1722 "Async Drop must be expanded or reset to sync before codegen"
1723 );
1724 self.codegen_drop_terminator(
1725 helper,
1726 bx,
1727 &terminator.source_info,
1728 place,
1729 target,
1730 unwind,
1731 mergeable_succ(),
1732 )
1733 }
1734
1735 mir::TerminatorKind::Assert { ref cond, expected, ref msg, target, unwind } => self
1736 .codegen_assert_terminator(
1737 helper,
1738 bx,
1739 terminator,
1740 cond,
1741 expected,
1742 msg,
1743 target,
1744 unwind,
1745 mergeable_succ(),
1746 ),
1747
1748 mir::TerminatorKind::Call {
1749 ref func,
1750 ref args,
1751 destination,
1752 target,
1753 unwind,
1754 call_source: _,
1755 fn_span,
1756 } => self.codegen_call_terminator(
1757 helper,
1758 bx,
1759 terminator,
1760 func,
1761 args,
1762 destination,
1763 target,
1764 unwind,
1765 fn_span,
1766 CallKind::Normal,
1767 mergeable_succ(),
1768 ),
1769 mir::TerminatorKind::TailCall { ref func, ref args, fn_span } => self
1770 .codegen_call_terminator(
1771 helper,
1772 bx,
1773 terminator,
1774 func,
1775 args,
1776 mir::Place::from(mir::RETURN_PLACE),
1777 None,
1778 mir::UnwindAction::Unreachable,
1779 fn_span,
1780 CallKind::Tail,
1781 mergeable_succ(),
1782 ),
1783 mir::TerminatorKind::CoroutineDrop | mir::TerminatorKind::Yield { .. } => {
1784 ::rustc_span::macros::bug_impl(None, format_args!("coroutine ops in codegen"),
Location::caller())bug!("coroutine ops in codegen")
1785 }
1786 mir::TerminatorKind::FalseEdge { .. } | mir::TerminatorKind::FalseUnwind { .. } => {
1787 ::rustc_span::macros::bug_impl(None,
format_args!("borrowck false edges in codegen"), Location::caller())bug!("borrowck false edges in codegen")
1788 }
1789
1790 mir::TerminatorKind::InlineAsm {
1791 asm_macro,
1792 template,
1793 ref operands,
1794 options,
1795 line_spans,
1796 ref targets,
1797 unwind,
1798 } => self.codegen_asm_terminator(
1799 helper,
1800 bx,
1801 asm_macro,
1802 terminator,
1803 template,
1804 operands,
1805 options,
1806 line_spans,
1807 targets,
1808 unwind,
1809 self.instance,
1810 mergeable_succ(),
1811 ),
1812 }
1813 }
1814
1815 fn clear_padding_cmse(
1830 &mut self,
1831 bx: &mut Bx,
1832 base_ptr: Bx::Value,
1833 limit: Size,
1834 layout: TyAndLayout<'tcx>,
1835 ) {
1836 let variant_independent = layout.variant_independent_padding_ranges(self.cx);
1838 self.zero_byte_ranges(bx, base_ptr, Size::ZERO, limit, &variant_independent);
1839
1840 self.clear_variant_dependent_padding(bx, base_ptr, Size::ZERO, limit, layout);
1842 }
1843
1844 fn clear_variant_dependent_padding(
1845 &mut self,
1846 bx: &mut Bx,
1847 base_ptr: Bx::Value,
1848 base_offset: Size,
1849 limit: Size,
1850 layout: TyAndLayout<'tcx>,
1851 ) {
1852 let cx = self.cx;
1853
1854 if !layout.has_variant_dependent_padding(cx) {
1855 return;
1856 }
1857
1858 match layout.fields {
1860 FieldsShape::Array { stride, count } => {
1861 let elem = layout.field(cx, 0);
1862 if elem.has_variant_dependent_padding(cx) {
1863 for idx in 0..count {
1864 let off = base_offset + idx * stride;
1865 self.clear_variant_dependent_padding(bx, base_ptr, off, limit, elem);
1866 }
1867 }
1868 }
1869 FieldsShape::Arbitrary { .. } => {
1870 for i in 0..layout.fields.count() {
1871 let field = layout.field(cx, i);
1872 if field.has_variant_dependent_padding(cx) {
1873 let off = base_offset + layout.fields.offset(i);
1874 self.clear_variant_dependent_padding(bx, base_ptr, off, limit, field);
1875 }
1876 }
1877 }
1878 FieldsShape::Primitive | FieldsShape::Union(_) => { }
1879 }
1880
1881 let Variants::Multiple { ref variants, .. } = layout.variants else {
1883 return;
1884 };
1885
1886 let mut work = Vec::with_capacity(variants.len());
1888 for i in 0..variants.len() {
1889 let idx = VariantIdx::from_usize(i);
1890 let variant = layout.for_variant(cx, idx);
1891
1892 if variant.is_uninhabited() {
1894 continue;
1895 }
1896
1897 let variant_dependent = layout.variant_dependent_padding_ranges(cx, idx);
1898 let has_nested_variant_dependent = (0..variant.fields.count())
1899 .any(|i| variant.field(cx, i).has_variant_dependent_padding(cx));
1900
1901 if !variant_dependent.is_empty() || has_nested_variant_dependent {
1902 work.push((idx, variant, variant_dependent));
1903 }
1904 }
1905
1906 if work.is_empty() {
1907 return;
1908 }
1909
1910 let root_block = bx.llbb();
1912 let join_block = bx.append_sibling_block("cmse_pad_join");
1913 let mut cases = Vec::with_capacity(work.len());
1914
1915 for (idx, variant, variant_dependent) in work.into_iter() {
1916 let Some(discr) = layout.ty.discriminant_for_variant(bx.tcx(), idx) else {
1917 ::rustc_span::macros::bug_impl(None,
format_args!("multi-variant layout on a type without discriminants"),
Location::caller());bug!("multi-variant layout on a type without discriminants");
1918 };
1919
1920 let variant_block = bx.append_sibling_block("cmse_pad_variant");
1921 bx.switch_to_block(variant_block);
1922
1923 self.zero_byte_ranges(bx, base_ptr, base_offset, limit, &variant_dependent);
1925
1926 for i in 0..variant.fields.count() {
1928 let field = variant.field(cx, i);
1929 let off = base_offset + variant.fields.offset(i);
1930 self.clear_variant_dependent_padding(bx, base_ptr, off, limit, field);
1931 }
1932
1933 bx.br(join_block);
1934 cases.push((discr.val, variant_block));
1935 }
1936
1937 bx.switch_to_block(root_block);
1939
1940 let discr_ty = layout.ty.discriminant_ty(bx.tcx());
1941 let enum_ptr = bx.inbounds_ptradd(base_ptr, bx.const_usize(base_offset.bytes()));
1942 let operand = OperandRef {
1943 val: OperandValue::Ref(PlaceValue::new_sized(enum_ptr, layout.align)),
1944 layout,
1945 move_annotation: None,
1946 };
1947 let discr = operand.codegen_get_discr(self, bx, discr_ty);
1948
1949 bx.switch(discr, join_block, cases.into_iter());
1951
1952 bx.switch_to_block(join_block);
1953 }
1954
1955 fn zero_byte_ranges(
1956 &mut self,
1957 bx: &mut Bx,
1958 ptr: Bx::Value,
1959 offset: Size,
1960 limit: Size,
1961 ranges: &[Range<Size>],
1962 ) {
1963 let zero = bx.const_u8(0);
1964
1965 for range in ranges {
1966 let start = range.start + offset;
1967 let end = range.end + offset;
1968
1969 let end = cmp::min(end, limit);
1970 if range.start >= end {
1971 continue;
1972 }
1973 let offset = bx.const_usize(start.bytes());
1974 let len = bx.const_usize((end - start).bytes());
1975 let ptr = bx.inbounds_ptradd(ptr, offset);
1976 bx.memset(ptr, zero, len, Align::ONE, MemFlags::empty());
1977 }
1978 }
1979
1980 fn codegen_argument(
1981 &mut self,
1982 bx: &mut Bx,
1983 conv: CanonAbi,
1984 op: OperandRef<'tcx, Bx::Value>,
1985 by_move: bool,
1986 llargs: &mut Vec<Bx::Value>,
1987 arg: &ArgAbi<'tcx, Ty<'tcx>>,
1988 lifetime_ends_after_call: &mut Vec<(Bx::Value, Size)>,
1989 ) {
1990 match arg.mode {
1991 PassMode::Ignore => {}
1992 PassMode::Direct(_) => match op.val {
1993 Immediate(v) => llargs.push(v),
1994 _ => ::rustc_span::macros::bug_impl(None,
format_args!("codegen_argument: {0:?} invalid for direct argument", op),
Location::caller())bug!("codegen_argument: {:?} invalid for direct argument", op),
1995 },
1996 PassMode::Pair(..) => match op.val {
1997 Pair(a, b) => {
1998 llargs.push(a);
1999 llargs.push(b);
2000 }
2001 _ => ::rustc_span::macros::bug_impl(None,
format_args!("codegen_argument: {0:?} invalid for pair argument", op),
Location::caller())bug!("codegen_argument: {:?} invalid for pair argument", op),
2002 },
2003 PassMode::Indirect { attrs, address_space: _, mode } => {
2004 let value = match op.val {
2005 Immediate(_) | Pair(..) => {
2006 let required_align = match attrs.pointee_align {
2010 Some(pointee_align) => cmp::max(pointee_align, arg.layout.align),
2011 None => arg.layout.align,
2012 };
2013 let scratch = PlaceValue::alloca(bx, arg.layout.size, required_align);
2014 bx.lifetime_start(scratch.llval, arg.layout.size);
2015 op.store_with_annotation(bx, scratch.with_type(arg.layout));
2016 lifetime_ends_after_call.push((scratch.llval, arg.layout.size));
2017 scratch
2018 }
2019 Ref(op_place_val) => {
2020 if mode == IndirectMode::AmdgpuKernelArg {
2021 ::rustc_span::macros::bug_impl(None,
format_args!("{0:?} passed as amdgpu kernel argument with abi {1:?}", op,
arg), Location::caller());bug!("{op:?} passed as amdgpu kernel argument with abi {arg:?}");
2022 }
2023 let required_align = match attrs.pointee_align {
2027 Some(pointee_align) => cmp::max(pointee_align, arg.layout.align),
2028 None => arg.layout.align,
2029 };
2030 if op_place_val.align < required_align
2032 || (mode == IndirectMode::Pointer && !by_move)
2033 {
2034 let scratch = PlaceValue::alloca(bx, arg.layout.size, required_align);
2035 bx.lifetime_start(scratch.llval, arg.layout.size);
2036 op.store_with_annotation(bx, scratch.with_type(arg.layout));
2037 lifetime_ends_after_call.push((scratch.llval, arg.layout.size));
2038 scratch
2039 } else {
2040 op_place_val
2041 }
2042 }
2043 ZeroSized => {
2044 match mode {
2045 IndirectMode::AmdgpuKernelArg => {
2046 ::rustc_span::macros::bug_impl(None,
format_args!("{0:?} passed as amdgpu kernel argument with abi {1:?}", op,
arg), Location::caller())bug!("{op:?} passed as amdgpu kernel argument with abi {arg:?}")
2047 }
2048 IndirectMode::OnStack => {
2051 ::rustc_span::macros::bug_impl(None,
format_args!("ZST {0:?} passed on stack with abi {1:?}", op, arg),
Location::caller())bug!("ZST {op:?} passed on stack with abi {arg:?}")
2052 }
2053 IndirectMode::Pointer => {}
2054 }
2055 PlaceRef::alloca(bx, arg.layout).val
2059 }
2060 };
2061 llargs.push(value.llval);
2062 }
2063 PassMode::IndirectUnsized { attrs: _, meta_attrs: _ } => match op.val {
2064 Ref(PlaceValue { llval: a, llextra: Some(b), .. }) => {
2065 llargs.push(a);
2066 llargs.push(b);
2067 }
2068 _ => ::rustc_span::macros::bug_impl(None,
format_args!("codegen_argument: {0:?} invalid for unsized indirect argument",
op), Location::caller())bug!("codegen_argument: {:?} invalid for unsized indirect argument", op),
2069 },
2070 PassMode::Cast { pad_i32_count, ref cast } => {
2071 let undef = bx.const_undef(bx.type_i32());
2073 llargs.extend(std::iter::repeat_n(undef, usize::from(pad_i32_count)));
2074 let value = match op.val {
2075 Immediate(_) | Pair(..) => {
2076 let scratch = PlaceRef::alloca(bx, arg.layout);
2077 op.store_with_annotation(bx, scratch);
2078 scratch.val
2079 }
2080 Ref(op_place_val) => op_place_val,
2081 ZeroSized => ::rustc_span::macros::bug_impl(None,
format_args!("ZST {0:?} wasn\'t ignored, but was passed with abi {1:?}",
op, arg), Location::caller())bug!("ZST {op:?} wasn't ignored, but was passed with abi {arg:?}"),
2082 };
2083 let scratch_size = cast.size(bx);
2087 let scratch_align = cast.align(bx);
2088 let copy_bytes = cmp::min(cast.unaligned_size(bx).bytes(), arg.layout.size.bytes());
2095 let scratch = bx.alloca(scratch_size, scratch_align);
2097 bx.lifetime_start(scratch, scratch_size);
2098 bx.memcpy(
2100 scratch,
2101 scratch_align,
2102 value.llval,
2103 value.align,
2104 bx.const_usize(copy_bytes),
2105 MemFlags::empty(),
2106 None,
2107 );
2108
2109 if conv == CanonAbi::Arm(ArmCall::CCmseNonSecureCall) {
2112 self.clear_padding_cmse(bx, scratch, Size::from_bytes(copy_bytes), arg.layout);
2113 }
2114
2115 llargs.push(load_cast(bx, cast, scratch, scratch_align));
2117 bx.lifetime_end(scratch, scratch_size);
2118 }
2119 }
2120 }
2121
2122 fn codegen_arguments_untupled(
2123 &mut self,
2124 bx: &mut Bx,
2125 conv: CanonAbi,
2126 operand: &mir::Operand<'tcx>,
2127 llargs: &mut Vec<Bx::Value>,
2128 args: &[ArgAbi<'tcx, Ty<'tcx>>],
2129 lifetime_ends_after_call: &mut Vec<(Bx::Value, Size)>,
2130 ) -> usize {
2131 let tuple = self.codegen_operand(bx, operand);
2132 let by_move = #[allow(non_exhaustive_omitted_patterns)] match operand {
mir::Operand::Move(_) => true,
_ => false,
}matches!(operand, mir::Operand::Move(_));
2133
2134 if let Ref(place_val) = tuple.val {
2136 if place_val.llextra.is_some() {
2137 ::rustc_span::macros::bug_impl(None,
format_args!("closure arguments must be sized"), Location::caller());bug!("closure arguments must be sized");
2138 }
2139 let tuple_ptr = place_val.with_type(tuple.layout);
2140 for i in 0..tuple.layout.fields.count() {
2141 let field_ptr = tuple_ptr.project_field(bx, i);
2142 let field = bx.load_operand(field_ptr);
2143 self.codegen_argument(
2144 bx,
2145 conv,
2146 field,
2147 by_move,
2148 llargs,
2149 &args[i],
2150 lifetime_ends_after_call,
2151 );
2152 }
2153 } else {
2154 for i in 0..tuple.layout.fields.count() {
2156 let op = tuple.extract_field(self, bx, i);
2157 self.codegen_argument(
2158 bx,
2159 conv,
2160 op,
2161 by_move,
2162 llargs,
2163 &args[i],
2164 lifetime_ends_after_call,
2165 );
2166 }
2167 }
2168 tuple.layout.fields.count()
2169 }
2170
2171 pub(super) fn get_caller_location(
2172 &mut self,
2173 bx: &mut Bx,
2174 source_info: mir::SourceInfo,
2175 ) -> OperandRef<'tcx, Bx::Value> {
2176 self.mir.caller_location_span(source_info, self.caller_location, bx.tcx(), |span: Span| {
2177 let const_loc = bx.tcx().span_as_caller_location(span);
2178 OperandRef::from_const(bx, const_loc, bx.tcx().caller_location_ty())
2179 })
2180 }
2181
2182 fn get_personality_slot(&mut self, bx: &mut Bx) -> PlaceRef<'tcx, Bx::Value> {
2183 let cx = bx.cx();
2184 if let Some(slot) = self.personality_slot {
2185 slot
2186 } else {
2187 let layout = cx.layout_of(Ty::new_tup(
2188 cx.tcx(),
2189 &[Ty::new_mut_ptr(cx.tcx(), cx.tcx().types.u8), cx.tcx().types.i32],
2190 ));
2191 let slot = PlaceRef::alloca(bx, layout);
2192 self.personality_slot = Some(slot);
2193 slot
2194 }
2195 }
2196
2197 fn landing_pad_for(&mut self, bb: mir::BasicBlock) -> Bx::BasicBlock {
2200 if let Some(landing_pad) = self.landing_pads[bb] {
2201 return landing_pad;
2202 }
2203
2204 let landing_pad = self.landing_pad_for_uncached(bb);
2205 self.landing_pads[bb] = Some(landing_pad);
2206 landing_pad
2207 }
2208
2209 fn landing_pad_for_uncached(&mut self, bb: mir::BasicBlock) -> Bx::BasicBlock {
2211 let llbb = self.llbb(bb);
2212 if base::wants_new_eh_instructions(&self.cx.sess().target) {
2213 let cleanup_bb = Bx::append_block(self.cx, self.llfn, &::alloc::__export::must_use({
::alloc::fmt::format(format_args!("funclet_{0:?}", bb))
})format!("funclet_{bb:?}"));
2214 let mut cleanup_bx = Bx::build(self.cx, cleanup_bb);
2215 let funclet = cleanup_bx.cleanup_pad(None, &[]);
2216 cleanup_bx.br(llbb);
2217 self.funclets[bb] = Some(funclet);
2218 cleanup_bb
2219 } else {
2220 let cleanup_llbb = Bx::append_block(self.cx, self.llfn, "cleanup");
2221 let mut cleanup_bx = Bx::build(self.cx, cleanup_llbb);
2222
2223 let llpersonality = self.cx.eh_personality();
2224 let (exn0, exn1) = cleanup_bx.cleanup_landing_pad(llpersonality);
2225
2226 let slot = self.get_personality_slot(&mut cleanup_bx);
2227 slot.storage_live(&mut cleanup_bx);
2228 Pair(exn0, exn1).store(&mut cleanup_bx, slot);
2229
2230 cleanup_bx.br(llbb);
2231 cleanup_llbb
2232 }
2233 }
2234
2235 fn unreachable_block(&mut self) -> Bx::BasicBlock {
2236 self.unreachable_block.unwrap_or_else(|| {
2237 let llbb = Bx::append_block(self.cx, self.llfn, "unreachable");
2238 let mut bx = Bx::build(self.cx, llbb);
2239 bx.unreachable();
2240 self.unreachable_block = Some(llbb);
2241 llbb
2242 })
2243 }
2244
2245 fn terminate_block(
2246 &mut self,
2247 reason: UnwindTerminateReason,
2248 outer_catchpad_bb: Option<mir::BasicBlock>,
2249 ) -> Bx::BasicBlock {
2250 if true {
if !(outer_catchpad_bb.is_some() ==
(base::wants_wasm_eh(&self.cx.tcx().sess.target) &&
reason == UnwindTerminateReason::InCleanup)) {
::core::panicking::panic("assertion failed: outer_catchpad_bb.is_some() ==\n (base::wants_wasm_eh(&self.cx.tcx().sess.target) &&\n reason == UnwindTerminateReason::InCleanup)")
};
};debug_assert!(
2255 outer_catchpad_bb.is_some()
2256 == (base::wants_wasm_eh(&self.cx.tcx().sess.target)
2257 && reason == UnwindTerminateReason::InCleanup)
2258 );
2259
2260 let mut cache_bb = mir::START_BLOCK;
2263 if let Some(outer_bb) = outer_catchpad_bb {
2266 let cleanup_kinds =
2267 self.cleanup_kinds.as_ref().expect("cleanup_kinds required for funclets");
2268 cache_bb = cleanup_kinds[outer_bb]
2269 .funclet_bb(outer_bb)
2270 .expect("funclet_bb should be in a funclet");
2271
2272 if self.funclets[cache_bb].is_none() {
2274 self.landing_pad_for(cache_bb);
2275 }
2276 }
2277 if let Some((cached_bb, cached_reason)) = self.terminate_blocks[cache_bb]
2278 && reason == cached_reason
2279 {
2280 return cached_bb;
2281 }
2282
2283 let funclet;
2284 let llbb;
2285 let mut bx;
2286 if base::wants_new_eh_instructions(&self.cx.sess().target) {
2287 llbb = Bx::append_block(self.cx, self.llfn, "cs_terminate");
2327
2328 let mut cs_bx = Bx::build(self.cx, llbb);
2329
2330 let mut outer_cleanuppad = None;
2334 if outer_catchpad_bb.is_some() {
2335 let outer_funclet = self.funclets[cache_bb]
2337 .as_ref()
2338 .expect("landing_pad_for didn't create funclet");
2339 outer_cleanuppad = Some(cs_bx.get_funclet_cleanuppad(outer_funclet));
2340 }
2341 let cp_llbb = Bx::append_block(self.cx, self.llfn, "cp_terminate");
2342 let cs = cs_bx.catch_switch(outer_cleanuppad, None, &[cp_llbb]);
2343 drop(cs_bx);
2344
2345 bx = Bx::build(self.cx, cp_llbb);
2346 let null =
2347 bx.const_null(bx.type_ptr_ext(bx.cx().data_layout().instruction_address_space));
2348
2349 let args = if base::wants_msvc_seh(&self.cx.sess().target) {
2353 let adjectives = bx.const_i32(0x40);
2360 &[null, adjectives, null] as &[_]
2361 } else {
2362 &[null] as &[_]
2368 };
2369
2370 funclet = Some(bx.catch_pad(cs, args));
2371 } else {
2377 llbb = Bx::append_block(self.cx, self.llfn, "terminate");
2378 bx = Bx::build(self.cx, llbb);
2379
2380 let llpersonality = self.cx.eh_personality();
2381 bx.filter_landing_pad(llpersonality);
2382
2383 funclet = None;
2384 }
2385
2386 self.set_debug_loc(&mut bx, mir::SourceInfo::outermost(self.mir.span));
2387
2388 let (fn_abi, fn_ptr, instance) =
2389 common::build_langcall(&bx, self.mir.span, reason.lang_item());
2390 if is_call_from_compiler_builtins_to_upstream_monomorphization(bx.tcx(), instance) {
2391 bx.abort_immediate();
2392 } else {
2393 let fn_ty = bx.fn_decl_backend_type(fn_abi);
2394
2395 let llret = bx.call(
2396 fn_ty,
2397 None,
2398 Some(fn_abi),
2399 fn_ptr,
2400 ReturnSlot::Direct,
2401 &[],
2402 funclet.as_ref(),
2403 None,
2404 );
2405 bx.apply_attrs_to_cleanup_callsite(llret);
2406 }
2407
2408 bx.unreachable();
2409
2410 self.terminate_blocks[cache_bb] = Some((llbb, reason));
2411 llbb
2412 }
2413
2414 pub fn llbb(&mut self, bb: mir::BasicBlock) -> Bx::BasicBlock {
2419 self.try_llbb(bb).unwrap()
2420 }
2421
2422 pub(crate) fn try_llbb(&mut self, bb: mir::BasicBlock) -> Option<Bx::BasicBlock> {
2424 match self.cached_llbbs[bb] {
2425 CachedLlbb::None => {
2426 let llbb = Bx::append_block(self.cx, self.llfn, &::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0:?}", bb))
})format!("{bb:?}"));
2427 self.cached_llbbs[bb] = CachedLlbb::Some(llbb);
2428 Some(llbb)
2429 }
2430 CachedLlbb::Some(llbb) => Some(llbb),
2431 CachedLlbb::Skip => None,
2432 }
2433 }
2434
2435 fn make_return_dest(
2436 &mut self,
2437 bx: &mut Bx,
2438 dest: mir::Place<'tcx>,
2439 fn_ret: &ArgAbi<'tcx, Ty<'tcx>>,
2440 ) -> (ReturnDest<'tcx, Bx::Value>, ReturnSlot<Bx::Value>) {
2441 if fn_ret.is_ignore() {
2443 return (ReturnDest::Nothing, ReturnSlot::Direct);
2444 }
2445 let dest = if let Some(index) = dest.as_local() {
2446 match self.locals[index] {
2447 LocalRef::Place(dest) => dest,
2448 LocalRef::UnsizedPlace(_) => ::rustc_span::macros::bug_impl(None,
format_args!("return type must be sized"), Location::caller())bug!("return type must be sized"),
2449 LocalRef::PendingOperand => {
2450 return if fn_ret.is_indirect() {
2453 let tmp = PlaceRef::alloca(bx, fn_ret.layout);
2456 tmp.storage_live(bx);
2457 (
2458 ReturnDest::IndirectOperand(tmp, index),
2459 ReturnSlot::Indirect(tmp.val.llval),
2460 )
2461 } else {
2462 (ReturnDest::DirectOperand(index), ReturnSlot::Direct)
2463 };
2464 }
2465 LocalRef::Operand(_) => {
2466 ::rustc_span::macros::bug_impl(None,
format_args!("place local already assigned to"), Location::caller());bug!("place local already assigned to");
2467 }
2468 }
2469 } else {
2470 self.codegen_place(bx, dest.as_ref())
2471 };
2472 if fn_ret.is_indirect() {
2473 if dest.val.align < dest.layout.align {
2474 ::rustc_span::macros::bug_impl(Some(self.mir.span),
format_args!("can\'t directly store to unaligned value"),
Location::caller());span_bug!(self.mir.span, "can't directly store to unaligned value");
2481 }
2482 (ReturnDest::Nothing, ReturnSlot::Indirect(dest.val.llval))
2483 } else {
2484 (ReturnDest::Store(dest), ReturnSlot::Direct)
2485 }
2486 }
2487
2488 fn store_return(
2490 &mut self,
2491 bx: &mut Bx,
2492 dest: ReturnDest<'tcx, Bx::Value>,
2493 ret_abi: &ArgAbi<'tcx, Ty<'tcx>>,
2494 llval: Bx::Value,
2495 ) {
2496 use self::ReturnDest::*;
2497 let retags_enabled = bx.tcx().sess.opts.unstable_opts.codegen_emit_retag.is_some();
2498 match dest {
2499 Nothing => (),
2500 Store(dst) => {
2501 bx.store_arg(ret_abi, llval, dst);
2502 if retags_enabled {
2503 self.codegen_retag_place(bx, dst, false);
2504 }
2505 }
2506 IndirectOperand(tmp, index) => {
2507 let mut op = bx.load_operand(tmp);
2508 tmp.storage_dead(bx);
2509 if retags_enabled {
2510 op = self.codegen_retag_operand(bx, op, false);
2511 }
2512 self.overwrite_local(index, LocalRef::Operand(op));
2513 self.debug_introduce_local(bx, index);
2514 }
2515 DirectOperand(index) => {
2516 let mut op = if let PassMode::Cast { .. } = ret_abi.mode {
2518 let tmp = PlaceRef::alloca(bx, ret_abi.layout);
2519 tmp.storage_live(bx);
2520 bx.store_arg(ret_abi, llval, tmp);
2521 let op = bx.load_operand(tmp);
2522 tmp.storage_dead(bx);
2523 op
2524 } else {
2525 OperandRef::from_immediate_or_packed_pair(bx, llval, ret_abi.layout)
2526 };
2527 if retags_enabled {
2528 op = self.codegen_retag_operand(bx, op, false);
2529 }
2530 self.overwrite_local(index, LocalRef::Operand(op));
2531 self.debug_introduce_local(bx, index);
2532 }
2533 }
2534 }
2535}
2536
2537enum ReturnDest<'tcx, V> {
2538 Nothing,
2540 Store(PlaceRef<'tcx, V>),
2542 IndirectOperand(PlaceRef<'tcx, V>, mir::Local),
2544 DirectOperand(mir::Local),
2546}
2547
2548fn load_cast<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
2549 bx: &mut Bx,
2550 cast: &CastTarget,
2551 ptr: Bx::Value,
2552 align: Align,
2553) -> Bx::Value {
2554 let cast_ty = bx.cast_backend_type(cast);
2555 if let Some(offset_from_start) = cast.rest_offset {
2556 {
match (&cast.prefix.len(), &1) {
(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!(cast.prefix.len(), 1);
2557 {
match (&cast.rest.unit.size, &cast.rest.total) {
(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!(cast.rest.unit.size, cast.rest.total);
2558 let first_ty = bx.reg_backend_type(&cast.prefix[0]);
2559 let second_ty = bx.reg_backend_type(&cast.rest.unit);
2560 let first = bx.load(first_ty, ptr, align);
2561 let second_ptr = bx.inbounds_ptradd(ptr, bx.const_usize(offset_from_start.bytes()));
2562 let second = bx.load(second_ty, second_ptr, align.restrict_for_offset(offset_from_start));
2563 let res = bx.cx().const_poison(cast_ty);
2564 let res = bx.insert_value(res, first, 0);
2565 bx.insert_value(res, second, 1)
2566 } else {
2567 bx.load(cast_ty, ptr, align)
2568 }
2569}
2570
2571pub fn store_cast<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
2572 bx: &mut Bx,
2573 cast: &CastTarget,
2574 value: Bx::Value,
2575 ptr: Bx::Value,
2576 align: Align,
2577) {
2578 if let Some(offset_from_start) = cast.rest_offset {
2579 {
match (&cast.prefix.len(), &1) {
(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!(cast.prefix.len(), 1);
2580 {
match (&cast.rest.unit.size, &cast.rest.total) {
(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!(cast.rest.unit.size, cast.rest.total);
2581 let first = bx.extract_value(value, 0);
2582 let second = bx.extract_value(value, 1);
2583 bx.store(first, ptr, align);
2584 let second_ptr = bx.inbounds_ptradd(ptr, bx.const_usize(offset_from_start.bytes()));
2585 bx.store(second, second_ptr, align.restrict_for_offset(offset_from_start));
2586 } else {
2587 bx.store(value, ptr, align);
2588 };
2589}