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