1use std::cmp;
2
3use rustc_abi::{BackendRepr, ExternAbi, HasDataLayout, Reg, 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::source_map::Spanned;
15use rustc_span::{Span, sym};
16use rustc_target::callconv::{ArgAbi, 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 copied_constant_arguments: &[PlaceRef<'tcx, <Bx as BackendTypes>::Value>],
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 in copied_constant_arguments {
249 bx.lifetime_end(tmp.val.llval, tmp.layout.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 in copied_constant_arguments {
263 bx.lifetime_end(tmp.val.llval, tmp.layout.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 let ty = bx.cast_backend_type(cast_ty);
562 bx.load(ty, llslot, self.fn_abi.ret.layout.align.abi)
563 }
564 };
565 bx.ret(llval);
566 }
567
568 #[tracing::instrument(level = "trace", skip(self, helper, bx))]
569 fn codegen_drop_terminator(
570 &mut self,
571 helper: TerminatorCodegenHelper<'tcx>,
572 bx: &mut Bx,
573 source_info: &mir::SourceInfo,
574 location: mir::Place<'tcx>,
575 target: mir::BasicBlock,
576 unwind: mir::UnwindAction,
577 mergeable_succ: bool,
578 ) -> MergingSucc {
579 let ty = location.ty(self.mir, bx.tcx()).ty;
580 let ty = self.monomorphize(ty);
581 let drop_fn = Instance::resolve_drop_in_place(bx.tcx(), ty);
582
583 if let ty::InstanceKind::DropGlue(_, None) = drop_fn.def {
584 return helper.funclet_br(self, bx, target, mergeable_succ);
586 }
587
588 let place = self.codegen_place(bx, location.as_ref());
589 let (args1, args2);
590 let mut args = if let Some(llextra) = place.val.llextra {
591 args2 = [place.val.llval, llextra];
592 &args2[..]
593 } else {
594 args1 = [place.val.llval];
595 &args1[..]
596 };
597 let (maybe_null, drop_fn, fn_abi, drop_instance) = match ty.kind() {
598 ty::Dynamic(_, _, ty::Dyn) => {
601 let virtual_drop = Instance {
614 def: ty::InstanceKind::Virtual(drop_fn.def_id(), 0), args: drop_fn.args,
616 };
617 debug!("ty = {:?}", ty);
618 debug!("drop_fn = {:?}", drop_fn);
619 debug!("args = {:?}", args);
620 let fn_abi = bx.fn_abi_of_instance(virtual_drop, ty::List::empty());
621 let vtable = args[1];
622 args = &args[..1];
624 (
625 true,
626 meth::VirtualIndex::from_index(ty::COMMON_VTABLE_ENTRIES_DROPINPLACE)
627 .get_optional_fn(bx, vtable, ty, fn_abi),
628 fn_abi,
629 virtual_drop,
630 )
631 }
632 ty::Dynamic(_, _, ty::DynStar) => {
633 let virtual_drop = Instance {
656 def: ty::InstanceKind::Virtual(drop_fn.def_id(), 0), args: drop_fn.args,
658 };
659 debug!("ty = {:?}", ty);
660 debug!("drop_fn = {:?}", drop_fn);
661 debug!("args = {:?}", args);
662 let fn_abi = bx.fn_abi_of_instance(virtual_drop, ty::List::empty());
663 let meta_ptr = place.project_field(bx, 1);
664 let meta = bx.load_operand(meta_ptr);
665 args = &args[..1];
667 debug!("args' = {:?}", args);
668 (
669 true,
670 meth::VirtualIndex::from_index(ty::COMMON_VTABLE_ENTRIES_DROPINPLACE)
671 .get_optional_fn(bx, meta.immediate(), ty, fn_abi),
672 fn_abi,
673 virtual_drop,
674 )
675 }
676 _ => (
677 false,
678 bx.get_fn_addr(drop_fn),
679 bx.fn_abi_of_instance(drop_fn, ty::List::empty()),
680 drop_fn,
681 ),
682 };
683
684 if maybe_null {
687 let is_not_null = bx.append_sibling_block("is_not_null");
688 let llty = bx.fn_ptr_backend_type(fn_abi);
689 let null = bx.const_null(llty);
690 let non_null =
691 bx.icmp(base::bin_op_to_icmp_predicate(mir::BinOp::Ne, false), drop_fn, null);
692 bx.cond_br(non_null, is_not_null, helper.llbb_with_cleanup(self, target));
693 bx.switch_to_block(is_not_null);
694 self.set_debug_loc(bx, *source_info);
695 }
696
697 helper.do_call(
698 self,
699 bx,
700 fn_abi,
701 drop_fn,
702 args,
703 Some((ReturnDest::Nothing, target)),
704 unwind,
705 &[],
706 Some(drop_instance),
707 !maybe_null && mergeable_succ,
708 )
709 }
710
711 fn codegen_assert_terminator(
712 &mut self,
713 helper: TerminatorCodegenHelper<'tcx>,
714 bx: &mut Bx,
715 terminator: &mir::Terminator<'tcx>,
716 cond: &mir::Operand<'tcx>,
717 expected: bool,
718 msg: &mir::AssertMessage<'tcx>,
719 target: mir::BasicBlock,
720 unwind: mir::UnwindAction,
721 mergeable_succ: bool,
722 ) -> MergingSucc {
723 let span = terminator.source_info.span;
724 let cond = self.codegen_operand(bx, cond).immediate();
725 let mut const_cond = bx.const_to_opt_u128(cond, false).map(|c| c == 1);
726
727 if !bx.sess().overflow_checks() && msg.is_optional_overflow_check() {
732 const_cond = Some(expected);
733 }
734
735 if const_cond == Some(expected) {
737 return helper.funclet_br(self, bx, target, mergeable_succ);
738 }
739
740 let lltarget = helper.llbb_with_cleanup(self, target);
745 let panic_block = bx.append_sibling_block("panic");
746 if expected {
747 bx.cond_br(cond, lltarget, panic_block);
748 } else {
749 bx.cond_br(cond, panic_block, lltarget);
750 }
751
752 bx.switch_to_block(panic_block);
754 self.set_debug_loc(bx, terminator.source_info);
755
756 let location = self.get_caller_location(bx, terminator.source_info).immediate();
758
759 let (lang_item, args) = match msg {
761 AssertKind::BoundsCheck { len, index } => {
762 let len = self.codegen_operand(bx, len).immediate();
763 let index = self.codegen_operand(bx, index).immediate();
764 (LangItem::PanicBoundsCheck, vec![index, len, location])
767 }
768 AssertKind::MisalignedPointerDereference { required, found } => {
769 let required = self.codegen_operand(bx, required).immediate();
770 let found = self.codegen_operand(bx, found).immediate();
771 (LangItem::PanicMisalignedPointerDereference, vec![required, found, location])
774 }
775 AssertKind::NullPointerDereference => {
776 (LangItem::PanicNullPointerDereference, vec![location])
779 }
780 _ => {
781 (msg.panic_function(), vec![location])
783 }
784 };
785
786 let (fn_abi, llfn, instance) = common::build_langcall(bx, Some(span), lang_item);
787
788 let merging_succ =
790 helper.do_call(self, bx, fn_abi, llfn, &args, None, unwind, &[], Some(instance), false);
791 assert_eq!(merging_succ, MergingSucc::False);
792 MergingSucc::False
793 }
794
795 fn codegen_terminate_terminator(
796 &mut self,
797 helper: TerminatorCodegenHelper<'tcx>,
798 bx: &mut Bx,
799 terminator: &mir::Terminator<'tcx>,
800 reason: UnwindTerminateReason,
801 ) {
802 let span = terminator.source_info.span;
803 self.set_debug_loc(bx, terminator.source_info);
804
805 let (fn_abi, llfn, instance) = common::build_langcall(bx, Some(span), reason.lang_item());
807
808 let merging_succ = helper.do_call(
810 self,
811 bx,
812 fn_abi,
813 llfn,
814 &[],
815 None,
816 mir::UnwindAction::Unreachable,
817 &[],
818 Some(instance),
819 false,
820 );
821 assert_eq!(merging_succ, MergingSucc::False);
822 }
823
824 fn codegen_panic_intrinsic(
826 &mut self,
827 helper: &TerminatorCodegenHelper<'tcx>,
828 bx: &mut Bx,
829 intrinsic: ty::IntrinsicDef,
830 instance: Option<Instance<'tcx>>,
831 source_info: mir::SourceInfo,
832 target: Option<mir::BasicBlock>,
833 unwind: mir::UnwindAction,
834 mergeable_succ: bool,
835 ) -> Option<MergingSucc> {
836 if let Some(requirement) = ValidityRequirement::from_intrinsic(intrinsic.name) {
840 let ty = instance.unwrap().args.type_at(0);
841
842 let do_panic = !bx
843 .tcx()
844 .check_validity_requirement((requirement, bx.typing_env().as_query_input(ty)))
845 .expect("expect to have layout during codegen");
846
847 let layout = bx.layout_of(ty);
848
849 Some(if do_panic {
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!(
859 "attempted to leave type `{ty}` uninitialized, which is invalid"
860 )
861 }
862 })
863 });
864 let msg = bx.const_str(&msg_str);
865
866 let (fn_abi, llfn, instance) =
868 common::build_langcall(bx, Some(source_info.span), LangItem::PanicNounwind);
869
870 helper.do_call(
872 self,
873 bx,
874 fn_abi,
875 llfn,
876 &[msg.0, msg.1],
877 target.as_ref().map(|bb| (ReturnDest::Nothing, *bb)),
878 unwind,
879 &[],
880 Some(instance),
881 mergeable_succ,
882 )
883 } else {
884 let target = target.unwrap();
886 helper.funclet_br(self, bx, target, mergeable_succ)
887 })
888 } else {
889 None
890 }
891 }
892
893 fn codegen_call_terminator(
894 &mut self,
895 helper: TerminatorCodegenHelper<'tcx>,
896 bx: &mut Bx,
897 terminator: &mir::Terminator<'tcx>,
898 func: &mir::Operand<'tcx>,
899 args: &[Spanned<mir::Operand<'tcx>>],
900 destination: mir::Place<'tcx>,
901 target: Option<mir::BasicBlock>,
902 unwind: mir::UnwindAction,
903 fn_span: Span,
904 mergeable_succ: bool,
905 ) -> MergingSucc {
906 let source_info = terminator.source_info;
907 let span = source_info.span;
908
909 let callee = self.codegen_operand(bx, func);
911
912 let (instance, mut llfn) = match *callee.layout.ty.kind() {
913 ty::FnDef(def_id, args) => (
914 Some(ty::Instance::expect_resolve(
915 bx.tcx(),
916 bx.typing_env(),
917 def_id,
918 args,
919 fn_span,
920 )),
921 None,
922 ),
923 ty::FnPtr(..) => (None, Some(callee.immediate())),
924 _ => bug!("{} is not callable", callee.layout.ty),
925 };
926
927 let def = instance.map(|i| i.def);
928
929 if let Some(ty::InstanceKind::DropGlue(_, None)) = def {
932 let target = target.unwrap();
934 return helper.funclet_br(self, bx, target, mergeable_succ);
935 }
936
937 let sig = callee.layout.ty.fn_sig(bx.tcx());
941 let abi = sig.abi();
942
943 let extra_args = &args[sig.inputs().skip_binder().len()..];
944 let extra_args = bx.tcx().mk_type_list_from_iter(extra_args.iter().map(|op_arg| {
945 let op_ty = op_arg.node.ty(self.mir, bx.tcx());
946 self.monomorphize(op_ty)
947 }));
948
949 let fn_abi = match instance {
950 Some(instance) => bx.fn_abi_of_instance(instance, extra_args),
951 None => bx.fn_abi_of_fn_ptr(sig, extra_args),
952 };
953
954 let arg_count = fn_abi.args.len() + fn_abi.ret.is_indirect() as usize;
956
957 let instance = match def {
958 Some(ty::InstanceKind::Intrinsic(def_id)) => {
959 let intrinsic = bx.tcx().intrinsic(def_id).unwrap();
960 if let Some(merging_succ) = self.codegen_panic_intrinsic(
961 &helper,
962 bx,
963 intrinsic,
964 instance,
965 source_info,
966 target,
967 unwind,
968 mergeable_succ,
969 ) {
970 return merging_succ;
971 }
972
973 let mut llargs = Vec::with_capacity(1);
974 let ret_dest = self.make_return_dest(
975 bx,
976 destination,
977 &fn_abi.ret,
978 &mut llargs,
979 Some(intrinsic),
980 );
981 let dest = match ret_dest {
982 _ if fn_abi.ret.is_indirect() => llargs[0],
983 ReturnDest::Nothing => bx.const_undef(bx.type_ptr()),
984 ReturnDest::IndirectOperand(dst, _) | ReturnDest::Store(dst) => dst.val.llval,
985 ReturnDest::DirectOperand(_) => {
986 bug!("Cannot use direct operand with an intrinsic call")
987 }
988 };
989
990 let args: Vec<_> =
991 args.iter().map(|arg| self.codegen_operand(bx, &arg.node)).collect();
992
993 if matches!(intrinsic, ty::IntrinsicDef { name: sym::caller_location, .. }) {
994 let location = self
995 .get_caller_location(bx, mir::SourceInfo { span: fn_span, ..source_info });
996
997 assert_eq!(llargs, []);
998 if let ReturnDest::IndirectOperand(tmp, _) = ret_dest {
999 location.val.store(bx, tmp);
1000 }
1001 self.store_return(bx, ret_dest, &fn_abi.ret, location.immediate());
1002 return helper.funclet_br(self, bx, target.unwrap(), mergeable_succ);
1003 }
1004
1005 let instance = *instance.as_ref().unwrap();
1006 match Self::codegen_intrinsic_call(bx, instance, fn_abi, &args, dest, span) {
1007 Ok(()) => {
1008 if let ReturnDest::IndirectOperand(dst, _) = ret_dest {
1009 self.store_return(bx, ret_dest, &fn_abi.ret, dst.val.llval);
1010 }
1011
1012 return if let Some(target) = target {
1013 helper.funclet_br(self, bx, target, mergeable_succ)
1014 } else {
1015 bx.unreachable();
1016 MergingSucc::False
1017 };
1018 }
1019 Err(instance) => {
1020 if intrinsic.must_be_overridden {
1021 span_bug!(
1022 span,
1023 "intrinsic {} must be overridden by codegen backend, but isn't",
1024 intrinsic.name,
1025 );
1026 }
1027 Some(instance)
1028 }
1029 }
1030 }
1031 _ => instance,
1032 };
1033
1034 let mut llargs = Vec::with_capacity(arg_count);
1035
1036 let return_dest = self.make_return_dest(bx, destination, &fn_abi.ret, &mut llargs, None);
1040 let destination = target.map(|target| (return_dest, target));
1041
1042 let (first_args, untuple) = if abi == ExternAbi::RustCall
1044 && let Some((tup, args)) = args.split_last()
1045 {
1046 (args, Some(tup))
1047 } else {
1048 (args, None)
1049 };
1050
1051 let mut copied_constant_arguments = vec![];
1052 'make_args: for (i, arg) in first_args.iter().enumerate() {
1053 let mut op = self.codegen_operand(bx, &arg.node);
1054
1055 if let (0, Some(ty::InstanceKind::Virtual(_, idx))) = (i, def) {
1056 match op.val {
1057 Pair(data_ptr, meta) => {
1058 while !op.layout.ty.is_raw_ptr() && !op.layout.ty.is_ref() {
1068 let (idx, _) = op.layout.non_1zst_field(bx).expect(
1069 "not exactly one non-1-ZST field in a `DispatchFromDyn` type",
1070 );
1071 op = op.extract_field(self, bx, idx);
1072 }
1073
1074 llfn = Some(meth::VirtualIndex::from_index(idx).get_fn(
1078 bx,
1079 meta,
1080 op.layout.ty,
1081 fn_abi,
1082 ));
1083 llargs.push(data_ptr);
1084 continue 'make_args;
1085 }
1086 Ref(PlaceValue { llval: data_ptr, llextra: Some(meta), .. }) => {
1087 llfn = Some(meth::VirtualIndex::from_index(idx).get_fn(
1089 bx,
1090 meta,
1091 op.layout.ty,
1092 fn_abi,
1093 ));
1094 llargs.push(data_ptr);
1095 continue;
1096 }
1097 Immediate(_) => {
1098 while !op.layout.ty.is_raw_ptr() && !op.layout.ty.is_ref() {
1100 let (idx, _) = op.layout.non_1zst_field(bx).expect(
1101 "not exactly one non-1-ZST field in a `DispatchFromDyn` type",
1102 );
1103 op = op.extract_field(self, bx, idx);
1104 }
1105
1106 if !op.layout.ty.builtin_deref(true).unwrap().is_dyn_star() {
1109 span_bug!(span, "can't codegen a virtual call on {:#?}", op);
1110 }
1111 let place = op.deref(bx.cx());
1112 let data_place = place.project_field(bx, 0);
1113 let meta_place = place.project_field(bx, 1);
1114 let meta = bx.load_operand(meta_place);
1115 llfn = Some(meth::VirtualIndex::from_index(idx).get_fn(
1116 bx,
1117 meta.immediate(),
1118 op.layout.ty,
1119 fn_abi,
1120 ));
1121 llargs.push(data_place.val.llval);
1122 continue;
1123 }
1124 _ => {
1125 span_bug!(span, "can't codegen a virtual call on {:#?}", op);
1126 }
1127 }
1128 }
1129
1130 match (&arg.node, op.val) {
1133 (&mir::Operand::Copy(_), Ref(PlaceValue { llextra: None, .. }))
1134 | (&mir::Operand::Constant(_), Ref(PlaceValue { llextra: None, .. })) => {
1135 let tmp = PlaceRef::alloca(bx, op.layout);
1136 bx.lifetime_start(tmp.val.llval, tmp.layout.size);
1137 op.val.store(bx, tmp);
1138 op.val = Ref(tmp.val);
1139 copied_constant_arguments.push(tmp);
1140 }
1141 _ => {}
1142 }
1143
1144 self.codegen_argument(bx, op, &mut llargs, &fn_abi.args[i]);
1145 }
1146 let num_untupled = untuple.map(|tup| {
1147 self.codegen_arguments_untupled(
1148 bx,
1149 &tup.node,
1150 &mut llargs,
1151 &fn_abi.args[first_args.len()..],
1152 )
1153 });
1154
1155 let needs_location =
1156 instance.is_some_and(|i| i.def.requires_caller_location(self.cx.tcx()));
1157 if needs_location {
1158 let mir_args = if let Some(num_untupled) = num_untupled {
1159 first_args.len() + num_untupled
1160 } else {
1161 args.len()
1162 };
1163 assert_eq!(
1164 fn_abi.args.len(),
1165 mir_args + 1,
1166 "#[track_caller] fn's must have 1 more argument in their ABI than in their MIR: {instance:?} {fn_span:?} {fn_abi:?}",
1167 );
1168 let location =
1169 self.get_caller_location(bx, mir::SourceInfo { span: fn_span, ..source_info });
1170 debug!(
1171 "codegen_call_terminator({:?}): location={:?} (fn_span {:?})",
1172 terminator, location, fn_span
1173 );
1174
1175 let last_arg = fn_abi.args.last().unwrap();
1176 self.codegen_argument(bx, location, &mut llargs, last_arg);
1177 }
1178
1179 let fn_ptr = match (instance, llfn) {
1180 (Some(instance), None) => bx.get_fn_addr(instance),
1181 (_, Some(llfn)) => llfn,
1182 _ => span_bug!(span, "no instance or llfn for call"),
1183 };
1184 helper.do_call(
1185 self,
1186 bx,
1187 fn_abi,
1188 fn_ptr,
1189 &llargs,
1190 destination,
1191 unwind,
1192 &copied_constant_arguments,
1193 instance,
1194 mergeable_succ,
1195 )
1196 }
1197
1198 fn codegen_asm_terminator(
1199 &mut self,
1200 helper: TerminatorCodegenHelper<'tcx>,
1201 bx: &mut Bx,
1202 asm_macro: InlineAsmMacro,
1203 terminator: &mir::Terminator<'tcx>,
1204 template: &[ast::InlineAsmTemplatePiece],
1205 operands: &[mir::InlineAsmOperand<'tcx>],
1206 options: ast::InlineAsmOptions,
1207 line_spans: &[Span],
1208 targets: &[mir::BasicBlock],
1209 unwind: mir::UnwindAction,
1210 instance: Instance<'_>,
1211 mergeable_succ: bool,
1212 ) -> MergingSucc {
1213 let span = terminator.source_info.span;
1214
1215 let operands: Vec<_> = operands
1216 .iter()
1217 .map(|op| match *op {
1218 mir::InlineAsmOperand::In { reg, ref value } => {
1219 let value = self.codegen_operand(bx, value);
1220 InlineAsmOperandRef::In { reg, value }
1221 }
1222 mir::InlineAsmOperand::Out { reg, late, ref place } => {
1223 let place = place.map(|place| self.codegen_place(bx, place.as_ref()));
1224 InlineAsmOperandRef::Out { reg, late, place }
1225 }
1226 mir::InlineAsmOperand::InOut { reg, late, ref in_value, ref out_place } => {
1227 let in_value = self.codegen_operand(bx, in_value);
1228 let out_place =
1229 out_place.map(|out_place| self.codegen_place(bx, out_place.as_ref()));
1230 InlineAsmOperandRef::InOut { reg, late, in_value, out_place }
1231 }
1232 mir::InlineAsmOperand::Const { ref value } => {
1233 let const_value = self.eval_mir_constant(value);
1234 let string = common::asm_const_to_str(
1235 bx.tcx(),
1236 span,
1237 const_value,
1238 bx.layout_of(value.ty()),
1239 );
1240 InlineAsmOperandRef::Const { string }
1241 }
1242 mir::InlineAsmOperand::SymFn { ref value } => {
1243 let const_ = self.monomorphize(value.const_);
1244 if let ty::FnDef(def_id, args) = *const_.ty().kind() {
1245 let instance = ty::Instance::resolve_for_fn_ptr(
1246 bx.tcx(),
1247 bx.typing_env(),
1248 def_id,
1249 args,
1250 )
1251 .unwrap();
1252 InlineAsmOperandRef::SymFn { instance }
1253 } else {
1254 span_bug!(span, "invalid type for asm sym (fn)");
1255 }
1256 }
1257 mir::InlineAsmOperand::SymStatic { def_id } => {
1258 InlineAsmOperandRef::SymStatic { def_id }
1259 }
1260 mir::InlineAsmOperand::Label { target_index } => {
1261 InlineAsmOperandRef::Label { label: self.llbb(targets[target_index]) }
1262 }
1263 })
1264 .collect();
1265
1266 helper.do_inlineasm(
1267 self,
1268 bx,
1269 template,
1270 &operands,
1271 options,
1272 line_spans,
1273 if asm_macro.diverges(options) { None } else { targets.get(0).copied() },
1274 unwind,
1275 instance,
1276 mergeable_succ,
1277 )
1278 }
1279
1280 pub(crate) fn codegen_block(&mut self, mut bb: mir::BasicBlock) {
1281 let llbb = match self.try_llbb(bb) {
1282 Some(llbb) => llbb,
1283 None => return,
1284 };
1285 let bx = &mut Bx::build(self.cx, llbb);
1286 let mir = self.mir;
1287
1288 loop {
1292 let data = &mir[bb];
1293
1294 debug!("codegen_block({:?}={:?})", bb, data);
1295
1296 for statement in &data.statements {
1297 self.codegen_statement(bx, statement);
1298 }
1299
1300 let merging_succ = self.codegen_terminator(bx, bb, data.terminator());
1301 if let MergingSucc::False = merging_succ {
1302 break;
1303 }
1304
1305 let mut successors = data.terminator().successors();
1313 let succ = successors.next().unwrap();
1314 assert!(matches!(self.cached_llbbs[succ], CachedLlbb::None));
1315 self.cached_llbbs[succ] = CachedLlbb::Skip;
1316 bb = succ;
1317 }
1318 }
1319
1320 pub(crate) fn codegen_block_as_unreachable(&mut self, bb: mir::BasicBlock) {
1321 let llbb = match self.try_llbb(bb) {
1322 Some(llbb) => llbb,
1323 None => return,
1324 };
1325 let bx = &mut Bx::build(self.cx, llbb);
1326 debug!("codegen_block_as_unreachable({:?})", bb);
1327 bx.unreachable();
1328 }
1329
1330 fn codegen_terminator(
1331 &mut self,
1332 bx: &mut Bx,
1333 bb: mir::BasicBlock,
1334 terminator: &'tcx mir::Terminator<'tcx>,
1335 ) -> MergingSucc {
1336 debug!("codegen_terminator: {:?}", terminator);
1337
1338 let helper = TerminatorCodegenHelper { bb, terminator };
1339
1340 let mergeable_succ = || {
1341 let mut successors = terminator.successors();
1344 if let Some(succ) = successors.next()
1345 && successors.next().is_none()
1346 && let &[succ_pred] = self.mir.basic_blocks.predecessors()[succ].as_slice()
1347 {
1348 assert_eq!(succ_pred, bb);
1351 true
1352 } else {
1353 false
1354 }
1355 };
1356
1357 self.set_debug_loc(bx, terminator.source_info);
1358 match terminator.kind {
1359 mir::TerminatorKind::UnwindResume => {
1360 self.codegen_resume_terminator(helper, bx);
1361 MergingSucc::False
1362 }
1363
1364 mir::TerminatorKind::UnwindTerminate(reason) => {
1365 self.codegen_terminate_terminator(helper, bx, terminator, reason);
1366 MergingSucc::False
1367 }
1368
1369 mir::TerminatorKind::Goto { target } => {
1370 helper.funclet_br(self, bx, target, mergeable_succ())
1371 }
1372
1373 mir::TerminatorKind::SwitchInt { ref discr, ref targets } => {
1374 self.codegen_switchint_terminator(helper, bx, discr, targets);
1375 MergingSucc::False
1376 }
1377
1378 mir::TerminatorKind::Return => {
1379 self.codegen_return_terminator(bx);
1380 MergingSucc::False
1381 }
1382
1383 mir::TerminatorKind::Unreachable => {
1384 bx.unreachable();
1385 MergingSucc::False
1386 }
1387
1388 mir::TerminatorKind::Drop { place, target, unwind, replace: _, drop, async_fut } => {
1389 assert!(
1390 async_fut.is_none() && drop.is_none(),
1391 "Async Drop must be expanded or reset to sync before codegen"
1392 );
1393 self.codegen_drop_terminator(
1394 helper,
1395 bx,
1396 &terminator.source_info,
1397 place,
1398 target,
1399 unwind,
1400 mergeable_succ(),
1401 )
1402 }
1403
1404 mir::TerminatorKind::Assert { ref cond, expected, ref msg, target, unwind } => self
1405 .codegen_assert_terminator(
1406 helper,
1407 bx,
1408 terminator,
1409 cond,
1410 expected,
1411 msg,
1412 target,
1413 unwind,
1414 mergeable_succ(),
1415 ),
1416
1417 mir::TerminatorKind::Call {
1418 ref func,
1419 ref args,
1420 destination,
1421 target,
1422 unwind,
1423 call_source: _,
1424 fn_span,
1425 } => self.codegen_call_terminator(
1426 helper,
1427 bx,
1428 terminator,
1429 func,
1430 args,
1431 destination,
1432 target,
1433 unwind,
1434 fn_span,
1435 mergeable_succ(),
1436 ),
1437 mir::TerminatorKind::TailCall { .. } => {
1438 span_bug!(
1440 terminator.source_info.span,
1441 "`TailCall` terminator is not yet supported by `rustc_codegen_ssa`"
1442 )
1443 }
1444 mir::TerminatorKind::CoroutineDrop | mir::TerminatorKind::Yield { .. } => {
1445 bug!("coroutine ops in codegen")
1446 }
1447 mir::TerminatorKind::FalseEdge { .. } | mir::TerminatorKind::FalseUnwind { .. } => {
1448 bug!("borrowck false edges in codegen")
1449 }
1450
1451 mir::TerminatorKind::InlineAsm {
1452 asm_macro,
1453 template,
1454 ref operands,
1455 options,
1456 line_spans,
1457 ref targets,
1458 unwind,
1459 } => self.codegen_asm_terminator(
1460 helper,
1461 bx,
1462 asm_macro,
1463 terminator,
1464 template,
1465 operands,
1466 options,
1467 line_spans,
1468 targets,
1469 unwind,
1470 self.instance,
1471 mergeable_succ(),
1472 ),
1473 }
1474 }
1475
1476 fn codegen_argument(
1477 &mut self,
1478 bx: &mut Bx,
1479 op: OperandRef<'tcx, Bx::Value>,
1480 llargs: &mut Vec<Bx::Value>,
1481 arg: &ArgAbi<'tcx, Ty<'tcx>>,
1482 ) {
1483 match arg.mode {
1484 PassMode::Ignore => return,
1485 PassMode::Cast { pad_i32: true, .. } => {
1486 llargs.push(bx.const_undef(bx.reg_backend_type(&Reg::i32())));
1488 }
1489 PassMode::Pair(..) => match op.val {
1490 Pair(a, b) => {
1491 llargs.push(a);
1492 llargs.push(b);
1493 return;
1494 }
1495 _ => bug!("codegen_argument: {:?} invalid for pair argument", op),
1496 },
1497 PassMode::Indirect { attrs: _, meta_attrs: Some(_), on_stack: _ } => match op.val {
1498 Ref(PlaceValue { llval: a, llextra: Some(b), .. }) => {
1499 llargs.push(a);
1500 llargs.push(b);
1501 return;
1502 }
1503 _ => bug!("codegen_argument: {:?} invalid for unsized indirect argument", op),
1504 },
1505 _ => {}
1506 }
1507
1508 let (mut llval, align, by_ref) = match op.val {
1510 Immediate(_) | Pair(..) => match arg.mode {
1511 PassMode::Indirect { attrs, .. } => {
1512 let required_align = match attrs.pointee_align {
1516 Some(pointee_align) => cmp::max(pointee_align, arg.layout.align.abi),
1517 None => arg.layout.align.abi,
1518 };
1519 let scratch = PlaceValue::alloca(bx, arg.layout.size, required_align);
1520 op.val.store(bx, scratch.with_type(arg.layout));
1521 (scratch.llval, scratch.align, true)
1522 }
1523 PassMode::Cast { .. } => {
1524 let scratch = PlaceRef::alloca(bx, arg.layout);
1525 op.val.store(bx, scratch);
1526 (scratch.val.llval, scratch.val.align, true)
1527 }
1528 _ => (op.immediate_or_packed_pair(bx), arg.layout.align.abi, false),
1529 },
1530 Ref(op_place_val) => match arg.mode {
1531 PassMode::Indirect { attrs, .. } => {
1532 let required_align = match attrs.pointee_align {
1533 Some(pointee_align) => cmp::max(pointee_align, arg.layout.align.abi),
1534 None => arg.layout.align.abi,
1535 };
1536 if op_place_val.align < required_align {
1537 let scratch = PlaceValue::alloca(bx, arg.layout.size, required_align);
1541 bx.typed_place_copy(scratch, op_place_val, op.layout);
1542 (scratch.llval, scratch.align, true)
1543 } else {
1544 (op_place_val.llval, op_place_val.align, true)
1545 }
1546 }
1547 _ => (op_place_val.llval, op_place_val.align, true),
1548 },
1549 ZeroSized => match arg.mode {
1550 PassMode::Indirect { on_stack, .. } => {
1551 if on_stack {
1552 bug!("ZST {op:?} passed on stack with abi {arg:?}");
1555 }
1556 let scratch = PlaceRef::alloca(bx, arg.layout);
1560 (scratch.val.llval, scratch.val.align, true)
1561 }
1562 _ => bug!("ZST {op:?} wasn't ignored, but was passed with abi {arg:?}"),
1563 },
1564 };
1565
1566 if by_ref && !arg.is_indirect() {
1567 if let PassMode::Cast { cast, pad_i32: _ } = &arg.mode {
1569 let scratch_size = cast.size(bx);
1573 let scratch_align = cast.align(bx);
1574 let copy_bytes = cmp::min(cast.unaligned_size(bx).bytes(), arg.layout.size.bytes());
1581 let llscratch = bx.alloca(scratch_size, scratch_align);
1583 bx.lifetime_start(llscratch, scratch_size);
1584 bx.memcpy(
1586 llscratch,
1587 scratch_align,
1588 llval,
1589 align,
1590 bx.const_usize(copy_bytes),
1591 MemFlags::empty(),
1592 );
1593 let cast_ty = bx.cast_backend_type(cast);
1595 llval = bx.load(cast_ty, llscratch, scratch_align);
1596 bx.lifetime_end(llscratch, scratch_size);
1597 } else {
1598 llval = bx.load(bx.backend_type(arg.layout), llval, align);
1604 if let BackendRepr::Scalar(scalar) = arg.layout.backend_repr {
1605 if scalar.is_bool() {
1606 bx.range_metadata(llval, WrappingRange { start: 0, end: 1 });
1607 }
1608 llval = bx.to_immediate_scalar(llval, scalar);
1610 }
1611 }
1612 }
1613
1614 llargs.push(llval);
1615 }
1616
1617 fn codegen_arguments_untupled(
1618 &mut self,
1619 bx: &mut Bx,
1620 operand: &mir::Operand<'tcx>,
1621 llargs: &mut Vec<Bx::Value>,
1622 args: &[ArgAbi<'tcx, Ty<'tcx>>],
1623 ) -> usize {
1624 let tuple = self.codegen_operand(bx, operand);
1625
1626 if let Ref(place_val) = tuple.val {
1628 if place_val.llextra.is_some() {
1629 bug!("closure arguments must be sized");
1630 }
1631 let tuple_ptr = place_val.with_type(tuple.layout);
1632 for i in 0..tuple.layout.fields.count() {
1633 let field_ptr = tuple_ptr.project_field(bx, i);
1634 let field = bx.load_operand(field_ptr);
1635 self.codegen_argument(bx, field, llargs, &args[i]);
1636 }
1637 } else {
1638 for i in 0..tuple.layout.fields.count() {
1640 let op = tuple.extract_field(self, bx, i);
1641 self.codegen_argument(bx, op, llargs, &args[i]);
1642 }
1643 }
1644 tuple.layout.fields.count()
1645 }
1646
1647 fn get_caller_location(
1648 &mut self,
1649 bx: &mut Bx,
1650 source_info: mir::SourceInfo,
1651 ) -> OperandRef<'tcx, Bx::Value> {
1652 self.mir.caller_location_span(source_info, self.caller_location, bx.tcx(), |span: Span| {
1653 let const_loc = bx.tcx().span_as_caller_location(span);
1654 OperandRef::from_const(bx, const_loc, bx.tcx().caller_location_ty())
1655 })
1656 }
1657
1658 fn get_personality_slot(&mut self, bx: &mut Bx) -> PlaceRef<'tcx, Bx::Value> {
1659 let cx = bx.cx();
1660 if let Some(slot) = self.personality_slot {
1661 slot
1662 } else {
1663 let layout = cx.layout_of(Ty::new_tup(
1664 cx.tcx(),
1665 &[Ty::new_mut_ptr(cx.tcx(), cx.tcx().types.u8), cx.tcx().types.i32],
1666 ));
1667 let slot = PlaceRef::alloca(bx, layout);
1668 self.personality_slot = Some(slot);
1669 slot
1670 }
1671 }
1672
1673 fn landing_pad_for(&mut self, bb: mir::BasicBlock) -> Bx::BasicBlock {
1676 if let Some(landing_pad) = self.landing_pads[bb] {
1677 return landing_pad;
1678 }
1679
1680 let landing_pad = self.landing_pad_for_uncached(bb);
1681 self.landing_pads[bb] = Some(landing_pad);
1682 landing_pad
1683 }
1684
1685 fn landing_pad_for_uncached(&mut self, bb: mir::BasicBlock) -> Bx::BasicBlock {
1687 let llbb = self.llbb(bb);
1688 if base::wants_new_eh_instructions(self.cx.sess()) {
1689 let cleanup_bb = Bx::append_block(self.cx, self.llfn, &format!("funclet_{bb:?}"));
1690 let mut cleanup_bx = Bx::build(self.cx, cleanup_bb);
1691 let funclet = cleanup_bx.cleanup_pad(None, &[]);
1692 cleanup_bx.br(llbb);
1693 self.funclets[bb] = Some(funclet);
1694 cleanup_bb
1695 } else {
1696 let cleanup_llbb = Bx::append_block(self.cx, self.llfn, "cleanup");
1697 let mut cleanup_bx = Bx::build(self.cx, cleanup_llbb);
1698
1699 let llpersonality = self.cx.eh_personality();
1700 let (exn0, exn1) = cleanup_bx.cleanup_landing_pad(llpersonality);
1701
1702 let slot = self.get_personality_slot(&mut cleanup_bx);
1703 slot.storage_live(&mut cleanup_bx);
1704 Pair(exn0, exn1).store(&mut cleanup_bx, slot);
1705
1706 cleanup_bx.br(llbb);
1707 cleanup_llbb
1708 }
1709 }
1710
1711 fn unreachable_block(&mut self) -> Bx::BasicBlock {
1712 self.unreachable_block.unwrap_or_else(|| {
1713 let llbb = Bx::append_block(self.cx, self.llfn, "unreachable");
1714 let mut bx = Bx::build(self.cx, llbb);
1715 bx.unreachable();
1716 self.unreachable_block = Some(llbb);
1717 llbb
1718 })
1719 }
1720
1721 fn terminate_block(&mut self, reason: UnwindTerminateReason) -> Bx::BasicBlock {
1722 if let Some((cached_bb, cached_reason)) = self.terminate_block
1723 && reason == cached_reason
1724 {
1725 return cached_bb;
1726 }
1727
1728 let funclet;
1729 let llbb;
1730 let mut bx;
1731 if base::wants_new_eh_instructions(self.cx.sess()) {
1732 llbb = Bx::append_block(self.cx, self.llfn, "cs_terminate");
1762 let cp_llbb = Bx::append_block(self.cx, self.llfn, "cp_terminate");
1763
1764 let mut cs_bx = Bx::build(self.cx, llbb);
1765 let cs = cs_bx.catch_switch(None, None, &[cp_llbb]);
1766
1767 bx = Bx::build(self.cx, cp_llbb);
1768 let null =
1769 bx.const_null(bx.type_ptr_ext(bx.cx().data_layout().instruction_address_space));
1770
1771 let args = if base::wants_msvc_seh(self.cx.sess()) {
1775 let adjectives = bx.const_i32(0x40);
1782 &[null, adjectives, null] as &[_]
1783 } else {
1784 &[null] as &[_]
1790 };
1791
1792 funclet = Some(bx.catch_pad(cs, args));
1793 } else {
1794 llbb = Bx::append_block(self.cx, self.llfn, "terminate");
1795 bx = Bx::build(self.cx, llbb);
1796
1797 let llpersonality = self.cx.eh_personality();
1798 bx.filter_landing_pad(llpersonality);
1799
1800 funclet = None;
1801 }
1802
1803 self.set_debug_loc(&mut bx, mir::SourceInfo::outermost(self.mir.span));
1804
1805 let (fn_abi, fn_ptr, instance) = common::build_langcall(&bx, None, reason.lang_item());
1806 if is_call_from_compiler_builtins_to_upstream_monomorphization(bx.tcx(), instance) {
1807 bx.abort();
1808 } else {
1809 let fn_ty = bx.fn_decl_backend_type(fn_abi);
1810
1811 let llret = bx.call(fn_ty, None, Some(fn_abi), fn_ptr, &[], funclet.as_ref(), None);
1812 bx.apply_attrs_to_cleanup_callsite(llret);
1813 }
1814
1815 bx.unreachable();
1816
1817 self.terminate_block = Some((llbb, reason));
1818 llbb
1819 }
1820
1821 pub fn llbb(&mut self, bb: mir::BasicBlock) -> Bx::BasicBlock {
1826 self.try_llbb(bb).unwrap()
1827 }
1828
1829 pub(crate) fn try_llbb(&mut self, bb: mir::BasicBlock) -> Option<Bx::BasicBlock> {
1831 match self.cached_llbbs[bb] {
1832 CachedLlbb::None => {
1833 let llbb = Bx::append_block(self.cx, self.llfn, &format!("{bb:?}"));
1834 self.cached_llbbs[bb] = CachedLlbb::Some(llbb);
1835 Some(llbb)
1836 }
1837 CachedLlbb::Some(llbb) => Some(llbb),
1838 CachedLlbb::Skip => None,
1839 }
1840 }
1841
1842 fn make_return_dest(
1843 &mut self,
1844 bx: &mut Bx,
1845 dest: mir::Place<'tcx>,
1846 fn_ret: &ArgAbi<'tcx, Ty<'tcx>>,
1847 llargs: &mut Vec<Bx::Value>,
1848 intrinsic: Option<ty::IntrinsicDef>,
1849 ) -> ReturnDest<'tcx, Bx::Value> {
1850 if fn_ret.is_ignore() {
1852 return ReturnDest::Nothing;
1853 }
1854 let dest = if let Some(index) = dest.as_local() {
1855 match self.locals[index] {
1856 LocalRef::Place(dest) => dest,
1857 LocalRef::UnsizedPlace(_) => bug!("return type must be sized"),
1858 LocalRef::PendingOperand => {
1859 return if fn_ret.is_indirect() {
1862 let tmp = PlaceRef::alloca(bx, fn_ret.layout);
1865 tmp.storage_live(bx);
1866 llargs.push(tmp.val.llval);
1867 ReturnDest::IndirectOperand(tmp, index)
1868 } else if intrinsic.is_some() {
1869 let tmp = PlaceRef::alloca(bx, fn_ret.layout);
1873 tmp.storage_live(bx);
1874 ReturnDest::IndirectOperand(tmp, index)
1875 } else {
1876 ReturnDest::DirectOperand(index)
1877 };
1878 }
1879 LocalRef::Operand(_) => {
1880 bug!("place local already assigned to");
1881 }
1882 }
1883 } else {
1884 self.codegen_place(bx, mir::PlaceRef { local: dest.local, projection: dest.projection })
1885 };
1886 if fn_ret.is_indirect() {
1887 if dest.val.align < dest.layout.align.abi {
1888 span_bug!(self.mir.span, "can't directly store to unaligned value");
1895 }
1896 llargs.push(dest.val.llval);
1897 ReturnDest::Nothing
1898 } else {
1899 ReturnDest::Store(dest)
1900 }
1901 }
1902
1903 fn store_return(
1905 &mut self,
1906 bx: &mut Bx,
1907 dest: ReturnDest<'tcx, Bx::Value>,
1908 ret_abi: &ArgAbi<'tcx, Ty<'tcx>>,
1909 llval: Bx::Value,
1910 ) {
1911 use self::ReturnDest::*;
1912
1913 match dest {
1914 Nothing => (),
1915 Store(dst) => bx.store_arg(ret_abi, llval, dst),
1916 IndirectOperand(tmp, index) => {
1917 let op = bx.load_operand(tmp);
1918 tmp.storage_dead(bx);
1919 self.overwrite_local(index, LocalRef::Operand(op));
1920 self.debug_introduce_local(bx, index);
1921 }
1922 DirectOperand(index) => {
1923 let op = if let PassMode::Cast { .. } = ret_abi.mode {
1925 let tmp = PlaceRef::alloca(bx, ret_abi.layout);
1926 tmp.storage_live(bx);
1927 bx.store_arg(ret_abi, llval, tmp);
1928 let op = bx.load_operand(tmp);
1929 tmp.storage_dead(bx);
1930 op
1931 } else {
1932 OperandRef::from_immediate_or_packed_pair(bx, llval, ret_abi.layout)
1933 };
1934 self.overwrite_local(index, LocalRef::Operand(op));
1935 self.debug_introduce_local(bx, index);
1936 }
1937 }
1938 }
1939}
1940
1941enum ReturnDest<'tcx, V> {
1942 Nothing,
1944 Store(PlaceRef<'tcx, V>),
1946 IndirectOperand(PlaceRef<'tcx, V>, mir::Local),
1948 DirectOperand(mir::Local),
1950}