1use std::cmp;
2
3use rustc_abi::{Align, BackendRepr, ExternAbi, HasDataLayout, Reg, Size, WrappingRange};
4use rustc_ast as ast;
5use rustc_ast::{InlineAsmOptions, InlineAsmTemplatePiece};
6use rustc_data_structures::packed::Pu128;
7use rustc_hir::lang_items::LangItem;
8use rustc_lint_defs::builtin::TAIL_CALL_TRACK_CALLER;
9use rustc_middle::mir::{self, AssertKind, InlineAsmMacro, SwitchTargets, UnwindTerminateReason};
10use rustc_middle::ty::layout::{HasTyCtxt, LayoutOf, ValidityRequirement};
11use rustc_middle::ty::print::{with_no_trimmed_paths, with_no_visible_paths};
12use rustc_middle::ty::{self, Instance, Ty};
13use rustc_middle::{bug, span_bug};
14use rustc_session::config::OptLevel;
15use rustc_span::Span;
16use rustc_span::source_map::Spanned;
17use rustc_target::callconv::{ArgAbi, CastTarget, FnAbi, PassMode};
18use tracing::{debug, info};
19
20use super::operand::OperandRef;
21use super::operand::OperandValue::{Immediate, Pair, Ref, ZeroSized};
22use super::place::{PlaceRef, PlaceValue};
23use super::{CachedLlbb, FunctionCx, LocalRef};
24use crate::base::{self, is_call_from_compiler_builtins_to_upstream_monomorphization};
25use crate::common::{self, IntPredicate};
26use crate::errors::CompilerBuiltinsCannotCall;
27use crate::traits::*;
28use crate::{MemFlags, meth};
29
30#[derive(Debug, PartialEq)]
34enum MergingSucc {
35 False,
36 True,
37}
38
39#[derive(Debug, PartialEq)]
42enum CallKind {
43 Normal,
44 Tail,
45}
46
47struct TerminatorCodegenHelper<'tcx> {
50 bb: mir::BasicBlock,
51 terminator: &'tcx mir::Terminator<'tcx>,
52}
53
54impl<'a, 'tcx> TerminatorCodegenHelper<'tcx> {
55 fn funclet<'b, Bx: BuilderMethods<'a, 'tcx>>(
58 &self,
59 fx: &'b mut FunctionCx<'a, 'tcx, Bx>,
60 ) -> Option<&'b Bx::Funclet> {
61 let cleanup_kinds = fx.cleanup_kinds.as_ref()?;
62 let funclet_bb = cleanup_kinds[self.bb].funclet_bb(self.bb)?;
63 if fx.funclets[funclet_bb].is_none() {
72 fx.landing_pad_for(funclet_bb);
73 }
74 Some(
75 fx.funclets[funclet_bb]
76 .as_ref()
77 .expect("landing_pad_for didn't also create funclets entry"),
78 )
79 }
80
81 fn llbb_with_cleanup<Bx: BuilderMethods<'a, 'tcx>>(
84 &self,
85 fx: &mut FunctionCx<'a, 'tcx, Bx>,
86 target: mir::BasicBlock,
87 ) -> Bx::BasicBlock {
88 let (needs_landing_pad, is_cleanupret) = self.llbb_characteristics(fx, target);
89 let mut lltarget = fx.llbb(target);
90 if needs_landing_pad {
91 lltarget = fx.landing_pad_for(target);
92 }
93 if is_cleanupret {
94 assert!(base::wants_new_eh_instructions(fx.cx.tcx().sess));
96 debug!("llbb_with_cleanup: creating cleanup trampoline for {:?}", target);
97 let name = &format!("{:?}_cleanup_trampoline_{:?}", self.bb, target);
98 let trampoline_llbb = Bx::append_block(fx.cx, fx.llfn, name);
99 let mut trampoline_bx = Bx::build(fx.cx, trampoline_llbb);
100 trampoline_bx.cleanup_ret(self.funclet(fx).unwrap(), Some(lltarget));
101 trampoline_llbb
102 } else {
103 lltarget
104 }
105 }
106
107 fn llbb_characteristics<Bx: BuilderMethods<'a, 'tcx>>(
108 &self,
109 fx: &mut FunctionCx<'a, 'tcx, Bx>,
110 target: mir::BasicBlock,
111 ) -> (bool, bool) {
112 if let Some(ref cleanup_kinds) = fx.cleanup_kinds {
113 let funclet_bb = cleanup_kinds[self.bb].funclet_bb(self.bb);
114 let target_funclet = cleanup_kinds[target].funclet_bb(target);
115 let (needs_landing_pad, is_cleanupret) = match (funclet_bb, target_funclet) {
116 (None, None) => (false, false),
117 (None, Some(_)) => (true, false),
118 (Some(f), Some(t_f)) => (f != t_f, f != t_f),
119 (Some(_), None) => {
120 let span = self.terminator.source_info.span;
121 span_bug!(span, "{:?} - jump out of cleanup?", self.terminator);
122 }
123 };
124 (needs_landing_pad, is_cleanupret)
125 } else {
126 let needs_landing_pad = !fx.mir[self.bb].is_cleanup && fx.mir[target].is_cleanup;
127 let is_cleanupret = false;
128 (needs_landing_pad, is_cleanupret)
129 }
130 }
131
132 fn funclet_br<Bx: BuilderMethods<'a, 'tcx>>(
133 &self,
134 fx: &mut FunctionCx<'a, 'tcx, Bx>,
135 bx: &mut Bx,
136 target: mir::BasicBlock,
137 mergeable_succ: bool,
138 ) -> MergingSucc {
139 let (needs_landing_pad, is_cleanupret) = self.llbb_characteristics(fx, target);
140 if mergeable_succ && !needs_landing_pad && !is_cleanupret {
141 MergingSucc::True
143 } else {
144 let mut lltarget = fx.llbb(target);
145 if needs_landing_pad {
146 lltarget = fx.landing_pad_for(target);
147 }
148 if is_cleanupret {
149 bx.cleanup_ret(self.funclet(fx).unwrap(), Some(lltarget));
152 } else {
153 bx.br(lltarget);
154 }
155 MergingSucc::False
156 }
157 }
158
159 fn do_call<Bx: BuilderMethods<'a, 'tcx>>(
162 &self,
163 fx: &mut FunctionCx<'a, 'tcx, Bx>,
164 bx: &mut Bx,
165 fn_abi: &'tcx FnAbi<'tcx, Ty<'tcx>>,
166 fn_ptr: Bx::Value,
167 llargs: &[Bx::Value],
168 destination: Option<(ReturnDest<'tcx, Bx::Value>, mir::BasicBlock)>,
169 mut unwind: mir::UnwindAction,
170 lifetime_ends_after_call: &[(Bx::Value, Size)],
171 instance: Option<Instance<'tcx>>,
172 kind: CallKind,
173 mergeable_succ: bool,
174 ) -> MergingSucc {
175 let tcx = bx.tcx();
176 if let Some(instance) = instance
177 && is_call_from_compiler_builtins_to_upstream_monomorphization(tcx, instance)
178 {
179 if destination.is_some() {
180 let caller_def = fx.instance.def_id();
181 let e = CompilerBuiltinsCannotCall {
182 span: tcx.def_span(caller_def),
183 caller: with_no_trimmed_paths!(tcx.def_path_str(caller_def)),
184 callee: with_no_trimmed_paths!(tcx.def_path_str(instance.def_id())),
185 };
186 tcx.dcx().emit_err(e);
187 } else {
188 info!(
189 "compiler_builtins call to diverging function {:?} replaced with abort",
190 instance.def_id()
191 );
192 bx.abort();
193 bx.unreachable();
194 return MergingSucc::False;
195 }
196 }
197
198 let fn_ty = bx.fn_decl_backend_type(fn_abi);
201
202 let fn_attrs = if bx.tcx().def_kind(fx.instance.def_id()).has_codegen_attrs() {
203 Some(bx.tcx().codegen_instance_attrs(fx.instance.def))
204 } else {
205 None
206 };
207 let fn_attrs = fn_attrs.as_deref();
208
209 if !fn_abi.can_unwind {
210 unwind = mir::UnwindAction::Unreachable;
211 }
212
213 let unwind_block = match unwind {
214 mir::UnwindAction::Cleanup(cleanup) => Some(self.llbb_with_cleanup(fx, cleanup)),
215 mir::UnwindAction::Continue => None,
216 mir::UnwindAction::Unreachable => None,
217 mir::UnwindAction::Terminate(reason) => {
218 if fx.mir[self.bb].is_cleanup && base::wants_new_eh_instructions(fx.cx.tcx().sess) {
219 None
229 } else {
230 Some(fx.terminate_block(reason))
231 }
232 }
233 };
234
235 if kind == CallKind::Tail {
236 bx.tail_call(fn_ty, fn_attrs, fn_abi, fn_ptr, llargs, self.funclet(fx), instance);
237 return MergingSucc::False;
238 }
239
240 if let Some(unwind_block) = unwind_block {
241 let ret_llbb = if let Some((_, target)) = destination {
242 fx.llbb(target)
243 } else {
244 fx.unreachable_block()
245 };
246 let invokeret = bx.invoke(
247 fn_ty,
248 fn_attrs,
249 Some(fn_abi),
250 fn_ptr,
251 llargs,
252 ret_llbb,
253 unwind_block,
254 self.funclet(fx),
255 instance,
256 );
257 if fx.mir[self.bb].is_cleanup {
258 bx.apply_attrs_to_cleanup_callsite(invokeret);
259 }
260
261 if let Some((ret_dest, target)) = destination {
262 bx.switch_to_block(fx.llbb(target));
263 fx.set_debug_loc(bx, self.terminator.source_info);
264 for &(tmp, size) in lifetime_ends_after_call {
265 bx.lifetime_end(tmp, size);
266 }
267 fx.store_return(bx, ret_dest, &fn_abi.ret, invokeret);
268 }
269 MergingSucc::False
270 } else {
271 let llret =
272 bx.call(fn_ty, fn_attrs, Some(fn_abi), fn_ptr, llargs, self.funclet(fx), instance);
273 if fx.mir[self.bb].is_cleanup {
274 bx.apply_attrs_to_cleanup_callsite(llret);
275 }
276
277 if let Some((ret_dest, target)) = destination {
278 for &(tmp, size) in lifetime_ends_after_call {
279 bx.lifetime_end(tmp, size);
280 }
281 fx.store_return(bx, ret_dest, &fn_abi.ret, llret);
282 self.funclet_br(fx, bx, target, mergeable_succ)
283 } else {
284 bx.unreachable();
285 MergingSucc::False
286 }
287 }
288 }
289
290 fn do_inlineasm<Bx: BuilderMethods<'a, 'tcx>>(
292 &self,
293 fx: &mut FunctionCx<'a, 'tcx, Bx>,
294 bx: &mut Bx,
295 template: &[InlineAsmTemplatePiece],
296 operands: &[InlineAsmOperandRef<'tcx, Bx>],
297 options: InlineAsmOptions,
298 line_spans: &[Span],
299 destination: Option<mir::BasicBlock>,
300 unwind: mir::UnwindAction,
301 instance: Instance<'_>,
302 mergeable_succ: bool,
303 ) -> MergingSucc {
304 let unwind_target = match unwind {
305 mir::UnwindAction::Cleanup(cleanup) => Some(self.llbb_with_cleanup(fx, cleanup)),
306 mir::UnwindAction::Terminate(reason) => Some(fx.terminate_block(reason)),
307 mir::UnwindAction::Continue => None,
308 mir::UnwindAction::Unreachable => None,
309 };
310
311 if operands.iter().any(|x| matches!(x, InlineAsmOperandRef::Label { .. })) {
312 assert!(unwind_target.is_none());
313 let ret_llbb = if let Some(target) = destination {
314 fx.llbb(target)
315 } else {
316 fx.unreachable_block()
317 };
318
319 bx.codegen_inline_asm(
320 template,
321 operands,
322 options,
323 line_spans,
324 instance,
325 Some(ret_llbb),
326 None,
327 );
328 MergingSucc::False
329 } else if let Some(cleanup) = unwind_target {
330 let ret_llbb = if let Some(target) = destination {
331 fx.llbb(target)
332 } else {
333 fx.unreachable_block()
334 };
335
336 bx.codegen_inline_asm(
337 template,
338 operands,
339 options,
340 line_spans,
341 instance,
342 Some(ret_llbb),
343 Some((cleanup, self.funclet(fx))),
344 );
345 MergingSucc::False
346 } else {
347 bx.codegen_inline_asm(template, operands, options, line_spans, instance, None, None);
348
349 if let Some(target) = destination {
350 self.funclet_br(fx, bx, target, mergeable_succ)
351 } else {
352 bx.unreachable();
353 MergingSucc::False
354 }
355 }
356 }
357}
358
359impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
361 fn codegen_resume_terminator(&mut self, helper: TerminatorCodegenHelper<'tcx>, bx: &mut Bx) {
363 if let Some(funclet) = helper.funclet(self) {
364 bx.cleanup_ret(funclet, None);
365 } else {
366 let slot = self.get_personality_slot(bx);
367 let exn0 = slot.project_field(bx, 0);
368 let exn0 = bx.load_operand(exn0).immediate();
369 let exn1 = slot.project_field(bx, 1);
370 let exn1 = bx.load_operand(exn1).immediate();
371 slot.storage_dead(bx);
372
373 bx.resume(exn0, exn1);
374 }
375 }
376
377 fn codegen_switchint_terminator(
378 &mut self,
379 helper: TerminatorCodegenHelper<'tcx>,
380 bx: &mut Bx,
381 discr: &mir::Operand<'tcx>,
382 targets: &SwitchTargets,
383 ) {
384 let discr = self.codegen_operand(bx, discr);
385 let discr_value = discr.immediate();
386 let switch_ty = discr.layout.ty;
387 if let Some(const_discr) = bx.const_to_opt_u128(discr_value, false) {
389 let target = targets.target_for_value(const_discr);
390 bx.br(helper.llbb_with_cleanup(self, target));
391 return;
392 };
393
394 let mut target_iter = targets.iter();
395 if target_iter.len() == 1 {
396 let (test_value, target) = target_iter.next().unwrap();
399 let otherwise = targets.otherwise();
400 let lltarget = helper.llbb_with_cleanup(self, target);
401 let llotherwise = helper.llbb_with_cleanup(self, otherwise);
402 let target_cold = self.cold_blocks[target];
403 let otherwise_cold = self.cold_blocks[otherwise];
404 let expect = if target_cold == otherwise_cold { None } else { Some(otherwise_cold) };
408 if switch_ty == bx.tcx().types.bool {
409 match test_value {
411 0 => {
412 let expect = expect.map(|e| !e);
413 bx.cond_br_with_expect(discr_value, llotherwise, lltarget, expect);
414 }
415 1 => {
416 bx.cond_br_with_expect(discr_value, lltarget, llotherwise, expect);
417 }
418 _ => bug!(),
419 }
420 } else {
421 let switch_llty = bx.immediate_backend_type(bx.layout_of(switch_ty));
422 let llval = bx.const_uint_big(switch_llty, test_value);
423 let cmp = bx.icmp(IntPredicate::IntEQ, discr_value, llval);
424 bx.cond_br_with_expect(cmp, lltarget, llotherwise, expect);
425 }
426 } else if target_iter.len() == 2
427 && self.mir[targets.otherwise()].is_empty_unreachable()
428 && targets.all_values().contains(&Pu128(0))
429 && targets.all_values().contains(&Pu128(1))
430 {
431 let true_bb = targets.target_for_value(1);
435 let false_bb = targets.target_for_value(0);
436 let true_ll = helper.llbb_with_cleanup(self, true_bb);
437 let false_ll = helper.llbb_with_cleanup(self, false_bb);
438
439 let expected_cond_value = if self.cx.sess().opts.optimize == OptLevel::No {
440 None
441 } else {
442 match (self.cold_blocks[true_bb], self.cold_blocks[false_bb]) {
443 (true, true) | (false, false) => None,
445 (true, false) => Some(false),
447 (false, true) => Some(true),
448 }
449 };
450
451 let bool_ty = bx.tcx().types.bool;
452 let cond = if switch_ty == bool_ty {
453 discr_value
454 } else {
455 let bool_llty = bx.immediate_backend_type(bx.layout_of(bool_ty));
456 bx.unchecked_utrunc(discr_value, bool_llty)
457 };
458 bx.cond_br_with_expect(cond, true_ll, false_ll, expected_cond_value);
459 } else if self.cx.sess().opts.optimize == OptLevel::No
460 && target_iter.len() == 2
461 && self.mir[targets.otherwise()].is_empty_unreachable()
462 {
463 let (test_value1, target1) = target_iter.next().unwrap();
476 let (_test_value2, target2) = target_iter.next().unwrap();
477 let ll1 = helper.llbb_with_cleanup(self, target1);
478 let ll2 = helper.llbb_with_cleanup(self, target2);
479 let switch_llty = bx.immediate_backend_type(bx.layout_of(switch_ty));
480 let llval = bx.const_uint_big(switch_llty, test_value1);
481 let cmp = bx.icmp(IntPredicate::IntEQ, discr_value, llval);
482 bx.cond_br(cmp, ll1, ll2);
483 } else {
484 let otherwise = targets.otherwise();
485 let otherwise_cold = self.cold_blocks[otherwise];
486 let otherwise_unreachable = self.mir[otherwise].is_empty_unreachable();
487 let cold_count = targets.iter().filter(|(_, target)| self.cold_blocks[*target]).count();
488 let none_cold = cold_count == 0;
489 let all_cold = cold_count == targets.iter().len();
490 if (none_cold && (!otherwise_cold || otherwise_unreachable))
491 || (all_cold && (otherwise_cold || otherwise_unreachable))
492 {
493 bx.switch(
496 discr_value,
497 helper.llbb_with_cleanup(self, targets.otherwise()),
498 target_iter
499 .map(|(value, target)| (value, helper.llbb_with_cleanup(self, target))),
500 );
501 } else {
502 bx.switch_with_weights(
504 discr_value,
505 helper.llbb_with_cleanup(self, targets.otherwise()),
506 otherwise_cold,
507 target_iter.map(|(value, target)| {
508 (value, helper.llbb_with_cleanup(self, target), self.cold_blocks[target])
509 }),
510 );
511 }
512 }
513 }
514
515 fn codegen_return_terminator(&mut self, bx: &mut Bx) {
516 if self.fn_abi.c_variadic {
518 let va_list_arg_idx = self.fn_abi.args.len();
520 match self.locals[mir::Local::from_usize(1 + va_list_arg_idx)] {
521 LocalRef::Place(va_list) => {
522 bx.va_end(va_list.val.llval);
523
524 bx.lifetime_end(va_list.val.llval, va_list.layout.size);
526 }
527 _ => bug!("C-variadic function must have a `VaList` place"),
528 }
529 }
530 if self.fn_abi.ret.layout.is_uninhabited() {
531 bx.abort();
536 bx.unreachable();
539 return;
540 }
541 let llval = match &self.fn_abi.ret.mode {
542 PassMode::Ignore | PassMode::Indirect { .. } => {
543 bx.ret_void();
544 return;
545 }
546
547 PassMode::Direct(_) | PassMode::Pair(..) => {
548 let op = self.codegen_consume(bx, mir::Place::return_place().as_ref());
549 if let Ref(place_val) = op.val {
550 bx.load_from_place(bx.backend_type(op.layout), place_val)
551 } else {
552 op.immediate_or_packed_pair(bx)
553 }
554 }
555
556 PassMode::Cast { cast: cast_ty, pad_i32: _ } => {
557 let op = match self.locals[mir::RETURN_PLACE] {
558 LocalRef::Operand(op) => op,
559 LocalRef::PendingOperand => bug!("use of return before def"),
560 LocalRef::Place(cg_place) => {
561 OperandRef { val: Ref(cg_place.val), layout: cg_place.layout }
562 }
563 LocalRef::UnsizedPlace(_) => bug!("return type must be sized"),
564 };
565 let llslot = match op.val {
566 Immediate(_) | Pair(..) => {
567 let scratch = PlaceRef::alloca(bx, self.fn_abi.ret.layout);
568 op.val.store(bx, scratch);
569 scratch.val.llval
570 }
571 Ref(place_val) => {
572 assert_eq!(
573 place_val.align, op.layout.align.abi,
574 "return place is unaligned!"
575 );
576 place_val.llval
577 }
578 ZeroSized => bug!("ZST return value shouldn't be in PassMode::Cast"),
579 };
580 load_cast(bx, cast_ty, llslot, self.fn_abi.ret.layout.align.abi)
581 }
582 };
583 bx.ret(llval);
584 }
585
586 #[tracing::instrument(level = "trace", skip(self, helper, bx))]
587 fn codegen_drop_terminator(
588 &mut self,
589 helper: TerminatorCodegenHelper<'tcx>,
590 bx: &mut Bx,
591 source_info: &mir::SourceInfo,
592 location: mir::Place<'tcx>,
593 target: mir::BasicBlock,
594 unwind: mir::UnwindAction,
595 mergeable_succ: bool,
596 ) -> MergingSucc {
597 let ty = location.ty(self.mir, bx.tcx()).ty;
598 let ty = self.monomorphize(ty);
599 let drop_fn = Instance::resolve_drop_in_place(bx.tcx(), ty);
600
601 if let ty::InstanceKind::DropGlue(_, None) = drop_fn.def {
602 return helper.funclet_br(self, bx, target, mergeable_succ);
604 }
605
606 let place = self.codegen_place(bx, location.as_ref());
607 let (args1, args2);
608 let mut args = if let Some(llextra) = place.val.llextra {
609 args2 = [place.val.llval, llextra];
610 &args2[..]
611 } else {
612 args1 = [place.val.llval];
613 &args1[..]
614 };
615 let (maybe_null, drop_fn, fn_abi, drop_instance) = match ty.kind() {
616 ty::Dynamic(_, _) => {
619 let virtual_drop = Instance {
632 def: ty::InstanceKind::Virtual(drop_fn.def_id(), 0), args: drop_fn.args,
634 };
635 debug!("ty = {:?}", ty);
636 debug!("drop_fn = {:?}", drop_fn);
637 debug!("args = {:?}", args);
638 let fn_abi = bx.fn_abi_of_instance(virtual_drop, ty::List::empty());
639 let vtable = args[1];
640 args = &args[..1];
642 (
643 true,
644 meth::VirtualIndex::from_index(ty::COMMON_VTABLE_ENTRIES_DROPINPLACE)
645 .get_optional_fn(bx, vtable, ty, fn_abi),
646 fn_abi,
647 virtual_drop,
648 )
649 }
650 _ => (
651 false,
652 bx.get_fn_addr(drop_fn),
653 bx.fn_abi_of_instance(drop_fn, ty::List::empty()),
654 drop_fn,
655 ),
656 };
657
658 if maybe_null {
661 let is_not_null = bx.append_sibling_block("is_not_null");
662 let llty = bx.fn_ptr_backend_type(fn_abi);
663 let null = bx.const_null(llty);
664 let non_null =
665 bx.icmp(base::bin_op_to_icmp_predicate(mir::BinOp::Ne, false), drop_fn, null);
666 bx.cond_br(non_null, is_not_null, helper.llbb_with_cleanup(self, target));
667 bx.switch_to_block(is_not_null);
668 self.set_debug_loc(bx, *source_info);
669 }
670
671 helper.do_call(
672 self,
673 bx,
674 fn_abi,
675 drop_fn,
676 args,
677 Some((ReturnDest::Nothing, target)),
678 unwind,
679 &[],
680 Some(drop_instance),
681 CallKind::Normal,
682 !maybe_null && mergeable_succ,
683 )
684 }
685
686 fn codegen_assert_terminator(
687 &mut self,
688 helper: TerminatorCodegenHelper<'tcx>,
689 bx: &mut Bx,
690 terminator: &mir::Terminator<'tcx>,
691 cond: &mir::Operand<'tcx>,
692 expected: bool,
693 msg: &mir::AssertMessage<'tcx>,
694 target: mir::BasicBlock,
695 unwind: mir::UnwindAction,
696 mergeable_succ: bool,
697 ) -> MergingSucc {
698 let span = terminator.source_info.span;
699 let cond = self.codegen_operand(bx, cond).immediate();
700 let mut const_cond = bx.const_to_opt_u128(cond, false).map(|c| c == 1);
701
702 if !bx.sess().overflow_checks() && msg.is_optional_overflow_check() {
707 const_cond = Some(expected);
708 }
709
710 if const_cond == Some(expected) {
712 return helper.funclet_br(self, bx, target, mergeable_succ);
713 }
714
715 let lltarget = helper.llbb_with_cleanup(self, target);
720 let panic_block = bx.append_sibling_block("panic");
721 if expected {
722 bx.cond_br(cond, lltarget, panic_block);
723 } else {
724 bx.cond_br(cond, panic_block, lltarget);
725 }
726
727 bx.switch_to_block(panic_block);
729 self.set_debug_loc(bx, terminator.source_info);
730
731 let location = self.get_caller_location(bx, terminator.source_info).immediate();
733
734 let (lang_item, args) = match msg {
736 AssertKind::BoundsCheck { len, index } => {
737 let len = self.codegen_operand(bx, len).immediate();
738 let index = self.codegen_operand(bx, index).immediate();
739 (LangItem::PanicBoundsCheck, vec![index, len, location])
742 }
743 AssertKind::MisalignedPointerDereference { required, found } => {
744 let required = self.codegen_operand(bx, required).immediate();
745 let found = self.codegen_operand(bx, found).immediate();
746 (LangItem::PanicMisalignedPointerDereference, vec![required, found, location])
749 }
750 AssertKind::NullPointerDereference => {
751 (LangItem::PanicNullPointerDereference, vec![location])
754 }
755 AssertKind::InvalidEnumConstruction(source) => {
756 let source = self.codegen_operand(bx, source).immediate();
757 (LangItem::PanicInvalidEnumConstruction, vec![source, location])
760 }
761 _ => {
762 (msg.panic_function(), vec![location])
764 }
765 };
766
767 let (fn_abi, llfn, instance) = common::build_langcall(bx, span, lang_item);
768
769 let merging_succ = helper.do_call(
771 self,
772 bx,
773 fn_abi,
774 llfn,
775 &args,
776 None,
777 unwind,
778 &[],
779 Some(instance),
780 CallKind::Normal,
781 false,
782 );
783 assert_eq!(merging_succ, MergingSucc::False);
784 MergingSucc::False
785 }
786
787 fn codegen_terminate_terminator(
788 &mut self,
789 helper: TerminatorCodegenHelper<'tcx>,
790 bx: &mut Bx,
791 terminator: &mir::Terminator<'tcx>,
792 reason: UnwindTerminateReason,
793 ) {
794 let span = terminator.source_info.span;
795 self.set_debug_loc(bx, terminator.source_info);
796
797 let (fn_abi, llfn, instance) = common::build_langcall(bx, span, reason.lang_item());
799
800 let merging_succ = helper.do_call(
802 self,
803 bx,
804 fn_abi,
805 llfn,
806 &[],
807 None,
808 mir::UnwindAction::Unreachable,
809 &[],
810 Some(instance),
811 CallKind::Normal,
812 false,
813 );
814 assert_eq!(merging_succ, MergingSucc::False);
815 }
816
817 fn codegen_panic_intrinsic(
819 &mut self,
820 helper: &TerminatorCodegenHelper<'tcx>,
821 bx: &mut Bx,
822 intrinsic: ty::IntrinsicDef,
823 instance: Instance<'tcx>,
824 source_info: mir::SourceInfo,
825 target: Option<mir::BasicBlock>,
826 unwind: mir::UnwindAction,
827 mergeable_succ: bool,
828 ) -> Option<MergingSucc> {
829 let Some(requirement) = ValidityRequirement::from_intrinsic(intrinsic.name) else {
833 return None;
834 };
835
836 let ty = instance.args.type_at(0);
837
838 let is_valid = bx
839 .tcx()
840 .check_validity_requirement((requirement, bx.typing_env().as_query_input(ty)))
841 .expect("expect to have layout during codegen");
842
843 if is_valid {
844 let target = target.unwrap();
846 return Some(helper.funclet_br(self, bx, target, mergeable_succ));
847 }
848
849 let layout = bx.layout_of(ty);
850
851 let msg_str = with_no_visible_paths!({
852 with_no_trimmed_paths!({
853 if layout.is_uninhabited() {
854 format!("attempted to instantiate uninhabited type `{ty}`")
856 } else if requirement == ValidityRequirement::Zero {
857 format!("attempted to zero-initialize type `{ty}`, which is invalid")
858 } else {
859 format!("attempted to leave type `{ty}` uninitialized, which is invalid")
860 }
861 })
862 });
863 let msg = bx.const_str(&msg_str);
864
865 let (fn_abi, llfn, instance) =
867 common::build_langcall(bx, source_info.span, LangItem::PanicNounwind);
868
869 Some(helper.do_call(
871 self,
872 bx,
873 fn_abi,
874 llfn,
875 &[msg.0, msg.1],
876 target.as_ref().map(|bb| (ReturnDest::Nothing, *bb)),
877 unwind,
878 &[],
879 Some(instance),
880 CallKind::Normal,
881 mergeable_succ,
882 ))
883 }
884
885 fn codegen_call_terminator(
886 &mut self,
887 helper: TerminatorCodegenHelper<'tcx>,
888 bx: &mut Bx,
889 terminator: &mir::Terminator<'tcx>,
890 func: &mir::Operand<'tcx>,
891 args: &[Spanned<mir::Operand<'tcx>>],
892 destination: mir::Place<'tcx>,
893 target: Option<mir::BasicBlock>,
894 unwind: mir::UnwindAction,
895 fn_span: Span,
896 kind: CallKind,
897 mergeable_succ: bool,
898 ) -> MergingSucc {
899 let source_info = mir::SourceInfo { span: fn_span, ..terminator.source_info };
900
901 let callee = self.codegen_operand(bx, func);
903
904 let (instance, mut llfn) = match *callee.layout.ty.kind() {
905 ty::FnDef(def_id, generic_args) => {
906 let instance = ty::Instance::expect_resolve(
907 bx.tcx(),
908 bx.typing_env(),
909 def_id,
910 generic_args,
911 fn_span,
912 );
913
914 match instance.def {
915 ty::InstanceKind::DropGlue(_, None) => {
918 let target = target.unwrap();
920 return helper.funclet_br(self, bx, target, mergeable_succ);
921 }
922 ty::InstanceKind::Intrinsic(def_id) => {
923 let intrinsic = bx.tcx().intrinsic(def_id).unwrap();
924 if let Some(merging_succ) = self.codegen_panic_intrinsic(
925 &helper,
926 bx,
927 intrinsic,
928 instance,
929 source_info,
930 target,
931 unwind,
932 mergeable_succ,
933 ) {
934 return merging_succ;
935 }
936
937 let result_layout =
938 self.cx.layout_of(self.monomorphized_place_ty(destination.as_ref()));
939
940 let (result, store_in_local) = if result_layout.is_zst() {
941 (
942 PlaceRef::new_sized(bx.const_undef(bx.type_ptr()), result_layout),
943 None,
944 )
945 } else if let Some(local) = destination.as_local() {
946 match self.locals[local] {
947 LocalRef::Place(dest) => (dest, None),
948 LocalRef::UnsizedPlace(_) => bug!("return type must be sized"),
949 LocalRef::PendingOperand => {
950 let tmp = PlaceRef::alloca(bx, result_layout);
954 tmp.storage_live(bx);
955 (tmp, Some(local))
956 }
957 LocalRef::Operand(_) => {
958 bug!("place local already assigned to");
959 }
960 }
961 } else {
962 (self.codegen_place(bx, destination.as_ref()), None)
963 };
964
965 if result.val.align < result.layout.align.abi {
966 span_bug!(self.mir.span, "can't directly store to unaligned value");
973 }
974
975 let args: Vec<_> =
976 args.iter().map(|arg| self.codegen_operand(bx, &arg.node)).collect();
977
978 match self.codegen_intrinsic_call(bx, instance, &args, result, source_info)
979 {
980 Ok(()) => {
981 if let Some(local) = store_in_local {
982 let op = bx.load_operand(result);
983 result.storage_dead(bx);
984 self.overwrite_local(local, LocalRef::Operand(op));
985 self.debug_introduce_local(bx, local);
986 }
987
988 return if let Some(target) = target {
989 helper.funclet_br(self, bx, target, mergeable_succ)
990 } else {
991 bx.unreachable();
992 MergingSucc::False
993 };
994 }
995 Err(instance) => {
996 if intrinsic.must_be_overridden {
997 span_bug!(
998 fn_span,
999 "intrinsic {} must be overridden by codegen backend, but isn't",
1000 intrinsic.name,
1001 );
1002 }
1003 (Some(instance), None)
1004 }
1005 }
1006 }
1007
1008 _ if kind == CallKind::Tail
1009 && instance.def.requires_caller_location(bx.tcx()) =>
1010 {
1011 if let Some(hir_id) =
1012 terminator.source_info.scope.lint_root(&self.mir.source_scopes)
1013 {
1014 let msg = "tail calling a function marked with `#[track_caller]` has no special effect";
1015 bx.tcx().node_lint(TAIL_CALL_TRACK_CALLER, hir_id, |d| {
1016 _ = d.primary_message(msg).span(fn_span)
1017 });
1018 }
1019
1020 let instance = ty::Instance::resolve_for_fn_ptr(
1021 bx.tcx(),
1022 bx.typing_env(),
1023 def_id,
1024 generic_args,
1025 )
1026 .unwrap();
1027
1028 (None, Some(bx.get_fn_addr(instance)))
1029 }
1030 _ => (Some(instance), None),
1031 }
1032 }
1033 ty::FnPtr(..) => (None, Some(callee.immediate())),
1034 _ => bug!("{} is not callable", callee.layout.ty),
1035 };
1036
1037 let sig = callee.layout.ty.fn_sig(bx.tcx());
1041
1042 let extra_args = &args[sig.inputs().skip_binder().len()..];
1043 let extra_args = bx.tcx().mk_type_list_from_iter(extra_args.iter().map(|op_arg| {
1044 let op_ty = op_arg.node.ty(self.mir, bx.tcx());
1045 self.monomorphize(op_ty)
1046 }));
1047
1048 let fn_abi = match instance {
1049 Some(instance) => bx.fn_abi_of_instance(instance, extra_args),
1050 None => bx.fn_abi_of_fn_ptr(sig, extra_args),
1051 };
1052
1053 let arg_count = fn_abi.args.len() + fn_abi.ret.is_indirect() as usize;
1055
1056 let mut llargs = Vec::with_capacity(arg_count);
1057
1058 let destination = match kind {
1062 CallKind::Normal => {
1063 let return_dest = self.make_return_dest(bx, destination, &fn_abi.ret, &mut llargs);
1064 target.map(|target| (return_dest, target))
1065 }
1066 CallKind::Tail => None,
1067 };
1068
1069 let (first_args, untuple) = if sig.abi() == ExternAbi::RustCall
1071 && let Some((tup, args)) = args.split_last()
1072 {
1073 (args, Some(tup))
1074 } else {
1075 (args, None)
1076 };
1077
1078 let mut lifetime_ends_after_call: Vec<(Bx::Value, Size)> = Vec::new();
1082 'make_args: for (i, arg) in first_args.iter().enumerate() {
1083 if kind == CallKind::Tail && matches!(fn_abi.args[i].mode, PassMode::Indirect { .. }) {
1084 span_bug!(
1086 fn_span,
1087 "arguments using PassMode::Indirect are currently not supported for tail calls"
1088 );
1089 }
1090
1091 let mut op = self.codegen_operand(bx, &arg.node);
1092
1093 if let (0, Some(ty::InstanceKind::Virtual(_, idx))) = (i, instance.map(|i| i.def)) {
1094 match op.val {
1095 Pair(data_ptr, meta) => {
1096 while !op.layout.ty.is_raw_ptr() && !op.layout.ty.is_ref() {
1106 let (idx, _) = op.layout.non_1zst_field(bx).expect(
1107 "not exactly one non-1-ZST field in a `DispatchFromDyn` type",
1108 );
1109 op = op.extract_field(self, bx, idx.as_usize());
1110 }
1111
1112 llfn = Some(meth::VirtualIndex::from_index(idx).get_fn(
1116 bx,
1117 meta,
1118 op.layout.ty,
1119 fn_abi,
1120 ));
1121 llargs.push(data_ptr);
1122 continue 'make_args;
1123 }
1124 Ref(PlaceValue { llval: data_ptr, llextra: Some(meta), .. }) => {
1125 llfn = Some(meth::VirtualIndex::from_index(idx).get_fn(
1127 bx,
1128 meta,
1129 op.layout.ty,
1130 fn_abi,
1131 ));
1132 llargs.push(data_ptr);
1133 continue;
1134 }
1135 _ => {
1136 span_bug!(fn_span, "can't codegen a virtual call on {:#?}", op);
1137 }
1138 }
1139 }
1140
1141 match (&arg.node, op.val) {
1144 (&mir::Operand::Copy(_), Ref(PlaceValue { llextra: None, .. }))
1145 | (&mir::Operand::Constant(_), Ref(PlaceValue { llextra: None, .. })) => {
1146 let tmp = PlaceRef::alloca(bx, op.layout);
1147 bx.lifetime_start(tmp.val.llval, tmp.layout.size);
1148 op.val.store(bx, tmp);
1149 op.val = Ref(tmp.val);
1150 lifetime_ends_after_call.push((tmp.val.llval, tmp.layout.size));
1151 }
1152 _ => {}
1153 }
1154
1155 self.codegen_argument(
1156 bx,
1157 op,
1158 &mut llargs,
1159 &fn_abi.args[i],
1160 &mut lifetime_ends_after_call,
1161 );
1162 }
1163 let num_untupled = untuple.map(|tup| {
1164 self.codegen_arguments_untupled(
1165 bx,
1166 &tup.node,
1167 &mut llargs,
1168 &fn_abi.args[first_args.len()..],
1169 &mut lifetime_ends_after_call,
1170 )
1171 });
1172
1173 let needs_location =
1174 instance.is_some_and(|i| i.def.requires_caller_location(self.cx.tcx()));
1175 if needs_location {
1176 let mir_args = if let Some(num_untupled) = num_untupled {
1177 first_args.len() + num_untupled
1178 } else {
1179 args.len()
1180 };
1181 assert_eq!(
1182 fn_abi.args.len(),
1183 mir_args + 1,
1184 "#[track_caller] fn's must have 1 more argument in their ABI than in their MIR: {instance:?} {fn_span:?} {fn_abi:?}",
1185 );
1186 let location = self.get_caller_location(bx, source_info);
1187 debug!(
1188 "codegen_call_terminator({:?}): location={:?} (fn_span {:?})",
1189 terminator, location, fn_span
1190 );
1191
1192 let last_arg = fn_abi.args.last().unwrap();
1193 self.codegen_argument(
1194 bx,
1195 location,
1196 &mut llargs,
1197 last_arg,
1198 &mut lifetime_ends_after_call,
1199 );
1200 }
1201
1202 let fn_ptr = match (instance, llfn) {
1203 (Some(instance), None) => bx.get_fn_addr(instance),
1204 (_, Some(llfn)) => llfn,
1205 _ => span_bug!(fn_span, "no instance or llfn for call"),
1206 };
1207 self.set_debug_loc(bx, source_info);
1208 helper.do_call(
1209 self,
1210 bx,
1211 fn_abi,
1212 fn_ptr,
1213 &llargs,
1214 destination,
1215 unwind,
1216 &lifetime_ends_after_call,
1217 instance,
1218 kind,
1219 mergeable_succ,
1220 )
1221 }
1222
1223 fn codegen_asm_terminator(
1224 &mut self,
1225 helper: TerminatorCodegenHelper<'tcx>,
1226 bx: &mut Bx,
1227 asm_macro: InlineAsmMacro,
1228 terminator: &mir::Terminator<'tcx>,
1229 template: &[ast::InlineAsmTemplatePiece],
1230 operands: &[mir::InlineAsmOperand<'tcx>],
1231 options: ast::InlineAsmOptions,
1232 line_spans: &[Span],
1233 targets: &[mir::BasicBlock],
1234 unwind: mir::UnwindAction,
1235 instance: Instance<'_>,
1236 mergeable_succ: bool,
1237 ) -> MergingSucc {
1238 let span = terminator.source_info.span;
1239
1240 let operands: Vec<_> = operands
1241 .iter()
1242 .map(|op| match *op {
1243 mir::InlineAsmOperand::In { reg, ref value } => {
1244 let value = self.codegen_operand(bx, value);
1245 InlineAsmOperandRef::In { reg, value }
1246 }
1247 mir::InlineAsmOperand::Out { reg, late, ref place } => {
1248 let place = place.map(|place| self.codegen_place(bx, place.as_ref()));
1249 InlineAsmOperandRef::Out { reg, late, place }
1250 }
1251 mir::InlineAsmOperand::InOut { reg, late, ref in_value, ref out_place } => {
1252 let in_value = self.codegen_operand(bx, in_value);
1253 let out_place =
1254 out_place.map(|out_place| self.codegen_place(bx, out_place.as_ref()));
1255 InlineAsmOperandRef::InOut { reg, late, in_value, out_place }
1256 }
1257 mir::InlineAsmOperand::Const { ref value } => {
1258 let const_value = self.eval_mir_constant(value);
1259 let string = common::asm_const_to_str(
1260 bx.tcx(),
1261 span,
1262 const_value,
1263 bx.layout_of(value.ty()),
1264 );
1265 InlineAsmOperandRef::Const { string }
1266 }
1267 mir::InlineAsmOperand::SymFn { ref value } => {
1268 let const_ = self.monomorphize(value.const_);
1269 if let ty::FnDef(def_id, args) = *const_.ty().kind() {
1270 let instance = ty::Instance::resolve_for_fn_ptr(
1271 bx.tcx(),
1272 bx.typing_env(),
1273 def_id,
1274 args,
1275 )
1276 .unwrap();
1277 InlineAsmOperandRef::SymFn { instance }
1278 } else {
1279 span_bug!(span, "invalid type for asm sym (fn)");
1280 }
1281 }
1282 mir::InlineAsmOperand::SymStatic { def_id } => {
1283 InlineAsmOperandRef::SymStatic { def_id }
1284 }
1285 mir::InlineAsmOperand::Label { target_index } => {
1286 InlineAsmOperandRef::Label { label: self.llbb(targets[target_index]) }
1287 }
1288 })
1289 .collect();
1290
1291 helper.do_inlineasm(
1292 self,
1293 bx,
1294 template,
1295 &operands,
1296 options,
1297 line_spans,
1298 if asm_macro.diverges(options) { None } else { targets.get(0).copied() },
1299 unwind,
1300 instance,
1301 mergeable_succ,
1302 )
1303 }
1304
1305 pub(crate) fn codegen_block(&mut self, mut bb: mir::BasicBlock) {
1306 let llbb = match self.try_llbb(bb) {
1307 Some(llbb) => llbb,
1308 None => return,
1309 };
1310 let bx = &mut Bx::build(self.cx, llbb);
1311 let mir = self.mir;
1312
1313 loop {
1317 let data = &mir[bb];
1318
1319 debug!("codegen_block({:?}={:?})", bb, data);
1320
1321 for statement in &data.statements {
1322 self.codegen_statement(bx, statement);
1323 }
1324 self.codegen_stmt_debuginfos(bx, &data.after_last_stmt_debuginfos);
1325
1326 let merging_succ = self.codegen_terminator(bx, bb, data.terminator());
1327 if let MergingSucc::False = merging_succ {
1328 break;
1329 }
1330
1331 let mut successors = data.terminator().successors();
1339 let succ = successors.next().unwrap();
1340 assert!(matches!(self.cached_llbbs[succ], CachedLlbb::None));
1341 self.cached_llbbs[succ] = CachedLlbb::Skip;
1342 bb = succ;
1343 }
1344 }
1345
1346 pub(crate) fn codegen_block_as_unreachable(&mut self, bb: mir::BasicBlock) {
1347 let llbb = match self.try_llbb(bb) {
1348 Some(llbb) => llbb,
1349 None => return,
1350 };
1351 let bx = &mut Bx::build(self.cx, llbb);
1352 debug!("codegen_block_as_unreachable({:?})", bb);
1353 bx.unreachable();
1354 }
1355
1356 fn codegen_terminator(
1357 &mut self,
1358 bx: &mut Bx,
1359 bb: mir::BasicBlock,
1360 terminator: &'tcx mir::Terminator<'tcx>,
1361 ) -> MergingSucc {
1362 debug!("codegen_terminator: {:?}", terminator);
1363
1364 let helper = TerminatorCodegenHelper { bb, terminator };
1365
1366 let mergeable_succ = || {
1367 let mut successors = terminator.successors();
1370 if let Some(succ) = successors.next()
1371 && successors.next().is_none()
1372 && let &[succ_pred] = self.mir.basic_blocks.predecessors()[succ].as_slice()
1373 {
1374 assert_eq!(succ_pred, bb);
1377 true
1378 } else {
1379 false
1380 }
1381 };
1382
1383 self.set_debug_loc(bx, terminator.source_info);
1384 match terminator.kind {
1385 mir::TerminatorKind::UnwindResume => {
1386 self.codegen_resume_terminator(helper, bx);
1387 MergingSucc::False
1388 }
1389
1390 mir::TerminatorKind::UnwindTerminate(reason) => {
1391 self.codegen_terminate_terminator(helper, bx, terminator, reason);
1392 MergingSucc::False
1393 }
1394
1395 mir::TerminatorKind::Goto { target } => {
1396 helper.funclet_br(self, bx, target, mergeable_succ())
1397 }
1398
1399 mir::TerminatorKind::SwitchInt { ref discr, ref targets } => {
1400 self.codegen_switchint_terminator(helper, bx, discr, targets);
1401 MergingSucc::False
1402 }
1403
1404 mir::TerminatorKind::Return => {
1405 self.codegen_return_terminator(bx);
1406 MergingSucc::False
1407 }
1408
1409 mir::TerminatorKind::Unreachable => {
1410 bx.unreachable();
1411 MergingSucc::False
1412 }
1413
1414 mir::TerminatorKind::Drop { place, target, unwind, replace: _, drop, async_fut } => {
1415 assert!(
1416 async_fut.is_none() && drop.is_none(),
1417 "Async Drop must be expanded or reset to sync before codegen"
1418 );
1419 self.codegen_drop_terminator(
1420 helper,
1421 bx,
1422 &terminator.source_info,
1423 place,
1424 target,
1425 unwind,
1426 mergeable_succ(),
1427 )
1428 }
1429
1430 mir::TerminatorKind::Assert { ref cond, expected, ref msg, target, unwind } => self
1431 .codegen_assert_terminator(
1432 helper,
1433 bx,
1434 terminator,
1435 cond,
1436 expected,
1437 msg,
1438 target,
1439 unwind,
1440 mergeable_succ(),
1441 ),
1442
1443 mir::TerminatorKind::Call {
1444 ref func,
1445 ref args,
1446 destination,
1447 target,
1448 unwind,
1449 call_source: _,
1450 fn_span,
1451 } => self.codegen_call_terminator(
1452 helper,
1453 bx,
1454 terminator,
1455 func,
1456 args,
1457 destination,
1458 target,
1459 unwind,
1460 fn_span,
1461 CallKind::Normal,
1462 mergeable_succ(),
1463 ),
1464 mir::TerminatorKind::TailCall { ref func, ref args, fn_span } => self
1465 .codegen_call_terminator(
1466 helper,
1467 bx,
1468 terminator,
1469 func,
1470 args,
1471 mir::Place::from(mir::RETURN_PLACE),
1472 None,
1473 mir::UnwindAction::Unreachable,
1474 fn_span,
1475 CallKind::Tail,
1476 mergeable_succ(),
1477 ),
1478 mir::TerminatorKind::CoroutineDrop | mir::TerminatorKind::Yield { .. } => {
1479 bug!("coroutine ops in codegen")
1480 }
1481 mir::TerminatorKind::FalseEdge { .. } | mir::TerminatorKind::FalseUnwind { .. } => {
1482 bug!("borrowck false edges in codegen")
1483 }
1484
1485 mir::TerminatorKind::InlineAsm {
1486 asm_macro,
1487 template,
1488 ref operands,
1489 options,
1490 line_spans,
1491 ref targets,
1492 unwind,
1493 } => self.codegen_asm_terminator(
1494 helper,
1495 bx,
1496 asm_macro,
1497 terminator,
1498 template,
1499 operands,
1500 options,
1501 line_spans,
1502 targets,
1503 unwind,
1504 self.instance,
1505 mergeable_succ(),
1506 ),
1507 }
1508 }
1509
1510 fn codegen_argument(
1511 &mut self,
1512 bx: &mut Bx,
1513 op: OperandRef<'tcx, Bx::Value>,
1514 llargs: &mut Vec<Bx::Value>,
1515 arg: &ArgAbi<'tcx, Ty<'tcx>>,
1516 lifetime_ends_after_call: &mut Vec<(Bx::Value, Size)>,
1517 ) {
1518 match arg.mode {
1519 PassMode::Ignore => return,
1520 PassMode::Cast { pad_i32: true, .. } => {
1521 llargs.push(bx.const_undef(bx.reg_backend_type(&Reg::i32())));
1523 }
1524 PassMode::Pair(..) => match op.val {
1525 Pair(a, b) => {
1526 llargs.push(a);
1527 llargs.push(b);
1528 return;
1529 }
1530 _ => bug!("codegen_argument: {:?} invalid for pair argument", op),
1531 },
1532 PassMode::Indirect { attrs: _, meta_attrs: Some(_), on_stack: _ } => match op.val {
1533 Ref(PlaceValue { llval: a, llextra: Some(b), .. }) => {
1534 llargs.push(a);
1535 llargs.push(b);
1536 return;
1537 }
1538 _ => bug!("codegen_argument: {:?} invalid for unsized indirect argument", op),
1539 },
1540 _ => {}
1541 }
1542
1543 let (mut llval, align, by_ref) = match op.val {
1545 Immediate(_) | Pair(..) => match arg.mode {
1546 PassMode::Indirect { attrs, .. } => {
1547 let required_align = match attrs.pointee_align {
1551 Some(pointee_align) => cmp::max(pointee_align, arg.layout.align.abi),
1552 None => arg.layout.align.abi,
1553 };
1554 let scratch = PlaceValue::alloca(bx, arg.layout.size, required_align);
1555 bx.lifetime_start(scratch.llval, arg.layout.size);
1556 op.val.store(bx, scratch.with_type(arg.layout));
1557 lifetime_ends_after_call.push((scratch.llval, arg.layout.size));
1558 (scratch.llval, scratch.align, true)
1559 }
1560 PassMode::Cast { .. } => {
1561 let scratch = PlaceRef::alloca(bx, arg.layout);
1562 op.val.store(bx, scratch);
1563 (scratch.val.llval, scratch.val.align, true)
1564 }
1565 _ => (op.immediate_or_packed_pair(bx), arg.layout.align.abi, false),
1566 },
1567 Ref(op_place_val) => match arg.mode {
1568 PassMode::Indirect { attrs, .. } => {
1569 let required_align = match attrs.pointee_align {
1570 Some(pointee_align) => cmp::max(pointee_align, arg.layout.align.abi),
1571 None => arg.layout.align.abi,
1572 };
1573 if op_place_val.align < required_align {
1574 let scratch = PlaceValue::alloca(bx, arg.layout.size, required_align);
1578 bx.lifetime_start(scratch.llval, arg.layout.size);
1579 bx.typed_place_copy(scratch, op_place_val, op.layout);
1580 lifetime_ends_after_call.push((scratch.llval, arg.layout.size));
1581 (scratch.llval, scratch.align, true)
1582 } else {
1583 (op_place_val.llval, op_place_val.align, true)
1584 }
1585 }
1586 _ => (op_place_val.llval, op_place_val.align, true),
1587 },
1588 ZeroSized => match arg.mode {
1589 PassMode::Indirect { on_stack, .. } => {
1590 if on_stack {
1591 bug!("ZST {op:?} passed on stack with abi {arg:?}");
1594 }
1595 let scratch = PlaceRef::alloca(bx, arg.layout);
1599 (scratch.val.llval, scratch.val.align, true)
1600 }
1601 _ => bug!("ZST {op:?} wasn't ignored, but was passed with abi {arg:?}"),
1602 },
1603 };
1604
1605 if by_ref && !arg.is_indirect() {
1606 if let PassMode::Cast { cast, pad_i32: _ } = &arg.mode {
1608 let scratch_size = cast.size(bx);
1612 let scratch_align = cast.align(bx);
1613 let copy_bytes = cmp::min(cast.unaligned_size(bx).bytes(), arg.layout.size.bytes());
1620 let llscratch = bx.alloca(scratch_size, scratch_align);
1622 bx.lifetime_start(llscratch, scratch_size);
1623 bx.memcpy(
1625 llscratch,
1626 scratch_align,
1627 llval,
1628 align,
1629 bx.const_usize(copy_bytes),
1630 MemFlags::empty(),
1631 None,
1632 );
1633 llval = load_cast(bx, cast, llscratch, scratch_align);
1635 bx.lifetime_end(llscratch, scratch_size);
1636 } else {
1637 llval = bx.load(bx.backend_type(arg.layout), llval, align);
1643 if let BackendRepr::Scalar(scalar) = arg.layout.backend_repr {
1644 if scalar.is_bool() {
1645 bx.range_metadata(llval, WrappingRange { start: 0, end: 1 });
1646 }
1647 llval = bx.to_immediate_scalar(llval, scalar);
1649 }
1650 }
1651 }
1652
1653 llargs.push(llval);
1654 }
1655
1656 fn codegen_arguments_untupled(
1657 &mut self,
1658 bx: &mut Bx,
1659 operand: &mir::Operand<'tcx>,
1660 llargs: &mut Vec<Bx::Value>,
1661 args: &[ArgAbi<'tcx, Ty<'tcx>>],
1662 lifetime_ends_after_call: &mut Vec<(Bx::Value, Size)>,
1663 ) -> usize {
1664 let tuple = self.codegen_operand(bx, operand);
1665
1666 if let Ref(place_val) = tuple.val {
1668 if place_val.llextra.is_some() {
1669 bug!("closure arguments must be sized");
1670 }
1671 let tuple_ptr = place_val.with_type(tuple.layout);
1672 for i in 0..tuple.layout.fields.count() {
1673 let field_ptr = tuple_ptr.project_field(bx, i);
1674 let field = bx.load_operand(field_ptr);
1675 self.codegen_argument(bx, field, llargs, &args[i], lifetime_ends_after_call);
1676 }
1677 } else {
1678 for i in 0..tuple.layout.fields.count() {
1680 let op = tuple.extract_field(self, bx, i);
1681 self.codegen_argument(bx, op, llargs, &args[i], lifetime_ends_after_call);
1682 }
1683 }
1684 tuple.layout.fields.count()
1685 }
1686
1687 pub(super) fn get_caller_location(
1688 &mut self,
1689 bx: &mut Bx,
1690 source_info: mir::SourceInfo,
1691 ) -> OperandRef<'tcx, Bx::Value> {
1692 self.mir.caller_location_span(source_info, self.caller_location, bx.tcx(), |span: Span| {
1693 let const_loc = bx.tcx().span_as_caller_location(span);
1694 OperandRef::from_const(bx, const_loc, bx.tcx().caller_location_ty())
1695 })
1696 }
1697
1698 fn get_personality_slot(&mut self, bx: &mut Bx) -> PlaceRef<'tcx, Bx::Value> {
1699 let cx = bx.cx();
1700 if let Some(slot) = self.personality_slot {
1701 slot
1702 } else {
1703 let layout = cx.layout_of(Ty::new_tup(
1704 cx.tcx(),
1705 &[Ty::new_mut_ptr(cx.tcx(), cx.tcx().types.u8), cx.tcx().types.i32],
1706 ));
1707 let slot = PlaceRef::alloca(bx, layout);
1708 self.personality_slot = Some(slot);
1709 slot
1710 }
1711 }
1712
1713 fn landing_pad_for(&mut self, bb: mir::BasicBlock) -> Bx::BasicBlock {
1716 if let Some(landing_pad) = self.landing_pads[bb] {
1717 return landing_pad;
1718 }
1719
1720 let landing_pad = self.landing_pad_for_uncached(bb);
1721 self.landing_pads[bb] = Some(landing_pad);
1722 landing_pad
1723 }
1724
1725 fn landing_pad_for_uncached(&mut self, bb: mir::BasicBlock) -> Bx::BasicBlock {
1727 let llbb = self.llbb(bb);
1728 if base::wants_new_eh_instructions(self.cx.sess()) {
1729 let cleanup_bb = Bx::append_block(self.cx, self.llfn, &format!("funclet_{bb:?}"));
1730 let mut cleanup_bx = Bx::build(self.cx, cleanup_bb);
1731 let funclet = cleanup_bx.cleanup_pad(None, &[]);
1732 cleanup_bx.br(llbb);
1733 self.funclets[bb] = Some(funclet);
1734 cleanup_bb
1735 } else {
1736 let cleanup_llbb = Bx::append_block(self.cx, self.llfn, "cleanup");
1737 let mut cleanup_bx = Bx::build(self.cx, cleanup_llbb);
1738
1739 let llpersonality = self.cx.eh_personality();
1740 let (exn0, exn1) = cleanup_bx.cleanup_landing_pad(llpersonality);
1741
1742 let slot = self.get_personality_slot(&mut cleanup_bx);
1743 slot.storage_live(&mut cleanup_bx);
1744 Pair(exn0, exn1).store(&mut cleanup_bx, slot);
1745
1746 cleanup_bx.br(llbb);
1747 cleanup_llbb
1748 }
1749 }
1750
1751 fn unreachable_block(&mut self) -> Bx::BasicBlock {
1752 self.unreachable_block.unwrap_or_else(|| {
1753 let llbb = Bx::append_block(self.cx, self.llfn, "unreachable");
1754 let mut bx = Bx::build(self.cx, llbb);
1755 bx.unreachable();
1756 self.unreachable_block = Some(llbb);
1757 llbb
1758 })
1759 }
1760
1761 fn terminate_block(&mut self, reason: UnwindTerminateReason) -> Bx::BasicBlock {
1762 if let Some((cached_bb, cached_reason)) = self.terminate_block
1763 && reason == cached_reason
1764 {
1765 return cached_bb;
1766 }
1767
1768 let funclet;
1769 let llbb;
1770 let mut bx;
1771 if base::wants_new_eh_instructions(self.cx.sess()) {
1772 llbb = Bx::append_block(self.cx, self.llfn, "cs_terminate");
1802 let cp_llbb = Bx::append_block(self.cx, self.llfn, "cp_terminate");
1803
1804 let mut cs_bx = Bx::build(self.cx, llbb);
1805 let cs = cs_bx.catch_switch(None, None, &[cp_llbb]);
1806
1807 bx = Bx::build(self.cx, cp_llbb);
1808 let null =
1809 bx.const_null(bx.type_ptr_ext(bx.cx().data_layout().instruction_address_space));
1810
1811 let args = if base::wants_msvc_seh(self.cx.sess()) {
1815 let adjectives = bx.const_i32(0x40);
1822 &[null, adjectives, null] as &[_]
1823 } else {
1824 &[null] as &[_]
1830 };
1831
1832 funclet = Some(bx.catch_pad(cs, args));
1833 } else {
1834 llbb = Bx::append_block(self.cx, self.llfn, "terminate");
1835 bx = Bx::build(self.cx, llbb);
1836
1837 let llpersonality = self.cx.eh_personality();
1838 bx.filter_landing_pad(llpersonality);
1839
1840 funclet = None;
1841 }
1842
1843 self.set_debug_loc(&mut bx, mir::SourceInfo::outermost(self.mir.span));
1844
1845 let (fn_abi, fn_ptr, instance) =
1846 common::build_langcall(&bx, self.mir.span, reason.lang_item());
1847 if is_call_from_compiler_builtins_to_upstream_monomorphization(bx.tcx(), instance) {
1848 bx.abort();
1849 } else {
1850 let fn_ty = bx.fn_decl_backend_type(fn_abi);
1851
1852 let llret = bx.call(fn_ty, None, Some(fn_abi), fn_ptr, &[], funclet.as_ref(), None);
1853 bx.apply_attrs_to_cleanup_callsite(llret);
1854 }
1855
1856 bx.unreachable();
1857
1858 self.terminate_block = Some((llbb, reason));
1859 llbb
1860 }
1861
1862 pub fn llbb(&mut self, bb: mir::BasicBlock) -> Bx::BasicBlock {
1867 self.try_llbb(bb).unwrap()
1868 }
1869
1870 pub(crate) fn try_llbb(&mut self, bb: mir::BasicBlock) -> Option<Bx::BasicBlock> {
1872 match self.cached_llbbs[bb] {
1873 CachedLlbb::None => {
1874 let llbb = Bx::append_block(self.cx, self.llfn, &format!("{bb:?}"));
1875 self.cached_llbbs[bb] = CachedLlbb::Some(llbb);
1876 Some(llbb)
1877 }
1878 CachedLlbb::Some(llbb) => Some(llbb),
1879 CachedLlbb::Skip => None,
1880 }
1881 }
1882
1883 fn make_return_dest(
1884 &mut self,
1885 bx: &mut Bx,
1886 dest: mir::Place<'tcx>,
1887 fn_ret: &ArgAbi<'tcx, Ty<'tcx>>,
1888 llargs: &mut Vec<Bx::Value>,
1889 ) -> ReturnDest<'tcx, Bx::Value> {
1890 if fn_ret.is_ignore() {
1892 return ReturnDest::Nothing;
1893 }
1894 let dest = if let Some(index) = dest.as_local() {
1895 match self.locals[index] {
1896 LocalRef::Place(dest) => dest,
1897 LocalRef::UnsizedPlace(_) => bug!("return type must be sized"),
1898 LocalRef::PendingOperand => {
1899 return if fn_ret.is_indirect() {
1902 let tmp = PlaceRef::alloca(bx, fn_ret.layout);
1905 tmp.storage_live(bx);
1906 llargs.push(tmp.val.llval);
1907 ReturnDest::IndirectOperand(tmp, index)
1908 } else {
1909 ReturnDest::DirectOperand(index)
1910 };
1911 }
1912 LocalRef::Operand(_) => {
1913 bug!("place local already assigned to");
1914 }
1915 }
1916 } else {
1917 self.codegen_place(bx, dest.as_ref())
1918 };
1919 if fn_ret.is_indirect() {
1920 if dest.val.align < dest.layout.align.abi {
1921 span_bug!(self.mir.span, "can't directly store to unaligned value");
1928 }
1929 llargs.push(dest.val.llval);
1930 ReturnDest::Nothing
1931 } else {
1932 ReturnDest::Store(dest)
1933 }
1934 }
1935
1936 fn store_return(
1938 &mut self,
1939 bx: &mut Bx,
1940 dest: ReturnDest<'tcx, Bx::Value>,
1941 ret_abi: &ArgAbi<'tcx, Ty<'tcx>>,
1942 llval: Bx::Value,
1943 ) {
1944 use self::ReturnDest::*;
1945
1946 match dest {
1947 Nothing => (),
1948 Store(dst) => bx.store_arg(ret_abi, llval, dst),
1949 IndirectOperand(tmp, index) => {
1950 let op = bx.load_operand(tmp);
1951 tmp.storage_dead(bx);
1952 self.overwrite_local(index, LocalRef::Operand(op));
1953 self.debug_introduce_local(bx, index);
1954 }
1955 DirectOperand(index) => {
1956 let op = if let PassMode::Cast { .. } = ret_abi.mode {
1958 let tmp = PlaceRef::alloca(bx, ret_abi.layout);
1959 tmp.storage_live(bx);
1960 bx.store_arg(ret_abi, llval, tmp);
1961 let op = bx.load_operand(tmp);
1962 tmp.storage_dead(bx);
1963 op
1964 } else {
1965 OperandRef::from_immediate_or_packed_pair(bx, llval, ret_abi.layout)
1966 };
1967 self.overwrite_local(index, LocalRef::Operand(op));
1968 self.debug_introduce_local(bx, index);
1969 }
1970 }
1971 }
1972}
1973
1974enum ReturnDest<'tcx, V> {
1975 Nothing,
1977 Store(PlaceRef<'tcx, V>),
1979 IndirectOperand(PlaceRef<'tcx, V>, mir::Local),
1981 DirectOperand(mir::Local),
1983}
1984
1985fn load_cast<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
1986 bx: &mut Bx,
1987 cast: &CastTarget,
1988 ptr: Bx::Value,
1989 align: Align,
1990) -> Bx::Value {
1991 let cast_ty = bx.cast_backend_type(cast);
1992 if let Some(offset_from_start) = cast.rest_offset {
1993 assert!(cast.prefix[1..].iter().all(|p| p.is_none()));
1994 assert_eq!(cast.rest.unit.size, cast.rest.total);
1995 let first_ty = bx.reg_backend_type(&cast.prefix[0].unwrap());
1996 let second_ty = bx.reg_backend_type(&cast.rest.unit);
1997 let first = bx.load(first_ty, ptr, align);
1998 let second_ptr = bx.inbounds_ptradd(ptr, bx.const_usize(offset_from_start.bytes()));
1999 let second = bx.load(second_ty, second_ptr, align.restrict_for_offset(offset_from_start));
2000 let res = bx.cx().const_poison(cast_ty);
2001 let res = bx.insert_value(res, first, 0);
2002 bx.insert_value(res, second, 1)
2003 } else {
2004 bx.load(cast_ty, ptr, align)
2005 }
2006}
2007
2008pub fn store_cast<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
2009 bx: &mut Bx,
2010 cast: &CastTarget,
2011 value: Bx::Value,
2012 ptr: Bx::Value,
2013 align: Align,
2014) {
2015 if let Some(offset_from_start) = cast.rest_offset {
2016 assert!(cast.prefix[1..].iter().all(|p| p.is_none()));
2017 assert_eq!(cast.rest.unit.size, cast.rest.total);
2018 assert!(cast.prefix[0].is_some());
2019 let first = bx.extract_value(value, 0);
2020 let second = bx.extract_value(value, 1);
2021 bx.store(first, ptr, align);
2022 let second_ptr = bx.inbounds_ptradd(ptr, bx.const_usize(offset_from_start.bytes()));
2023 bx.store(second, second_ptr, align.restrict_for_offset(offset_from_start));
2024 } else {
2025 bx.store(value, ptr, align);
2026 };
2027}