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