1 use super::operand::OperandRef;
2 use super::operand::OperandValue::{Immediate, Pair, Ref};
3 use super::place::PlaceRef;
4 use super::{FunctionCx, LocalRef};
7 use crate::common::{self, IntPredicate};
13 use rustc_hir::lang_items::LangItem;
14 use rustc_index::vec::Idx;
15 use rustc_middle::mir;
16 use rustc_middle::mir::interpret::{AllocId, ConstValue, Pointer, Scalar};
17 use rustc_middle::mir::AssertKind;
18 use rustc_middle::ty::layout::{FnAbiExt, HasTyCtxt};
19 use rustc_middle::ty::print::with_no_trimmed_paths;
20 use rustc_middle::ty::{self, Instance, Ty, TypeFoldable};
21 use rustc_span::source_map::Span;
22 use rustc_span::{sym, Symbol};
23 use rustc_target::abi::call::{ArgAbi, FnAbi, PassMode};
24 use rustc_target::abi::{self, LayoutOf};
25 use rustc_target::spec::abi::Abi;
29 /// Used by `FunctionCx::codegen_terminator` for emitting common patterns
30 /// e.g., creating a basic block, calling a function, etc.
31 struct TerminatorCodegenHelper<'tcx> {
33 terminator: &'tcx mir::Terminator<'tcx>,
34 funclet_bb: Option<mir::BasicBlock>,
37 impl<'a, 'tcx> TerminatorCodegenHelper<'tcx> {
38 /// Returns the associated funclet from `FunctionCx::funclets` for the
39 /// `funclet_bb` member if it is not `None`.
40 fn funclet<'b, Bx: BuilderMethods<'a, 'tcx>>(
42 fx: &'b mut FunctionCx<'a, 'tcx, Bx>,
43 ) -> Option<&'b Bx::Funclet> {
44 match self.funclet_bb {
45 Some(funcl) => fx.funclets[funcl].as_ref(),
50 fn lltarget<Bx: BuilderMethods<'a, 'tcx>>(
52 fx: &mut FunctionCx<'a, 'tcx, Bx>,
53 target: mir::BasicBlock,
54 ) -> (Bx::BasicBlock, bool) {
55 let span = self.terminator.source_info.span;
56 let lltarget = fx.blocks[target];
57 let target_funclet = fx.cleanup_kinds[target].funclet_bb(target);
58 match (self.funclet_bb, target_funclet) {
59 (None, None) => (lltarget, false),
60 (Some(f), Some(t_f)) if f == t_f || !base::wants_msvc_seh(fx.cx.tcx().sess) => {
63 // jump *into* cleanup - need a landing pad if GNU
64 (None, Some(_)) => (fx.landing_pad_to(target), false),
65 (Some(_), None) => span_bug!(span, "{:?} - jump out of cleanup?", self.terminator),
66 (Some(_), Some(_)) => (fx.landing_pad_to(target), true),
70 /// Create a basic block.
71 fn llblock<Bx: BuilderMethods<'a, 'tcx>>(
73 fx: &mut FunctionCx<'a, 'tcx, Bx>,
74 target: mir::BasicBlock,
76 let (lltarget, is_cleanupret) = self.lltarget(fx, target);
78 // MSVC cross-funclet jump - need a trampoline
80 debug!("llblock: creating cleanup trampoline for {:?}", target);
81 let name = &format!("{:?}_cleanup_trampoline_{:?}", self.bb, target);
82 let mut trampoline = fx.new_block(name);
83 trampoline.cleanup_ret(self.funclet(fx).unwrap(), Some(lltarget));
90 fn funclet_br<Bx: BuilderMethods<'a, 'tcx>>(
92 fx: &mut FunctionCx<'a, 'tcx, Bx>,
94 target: mir::BasicBlock,
96 let (lltarget, is_cleanupret) = self.lltarget(fx, target);
98 // micro-optimization: generate a `ret` rather than a jump
100 bx.cleanup_ret(self.funclet(fx).unwrap(), Some(lltarget));
106 /// Call `fn_ptr` of `fn_abi` with the arguments `llargs`, the optional
107 /// return destination `destination` and the cleanup function `cleanup`.
108 fn do_call<Bx: BuilderMethods<'a, 'tcx>>(
110 fx: &mut FunctionCx<'a, 'tcx, Bx>,
112 fn_abi: FnAbi<'tcx, Ty<'tcx>>,
114 llargs: &[Bx::Value],
115 destination: Option<(ReturnDest<'tcx, Bx::Value>, mir::BasicBlock)>,
116 cleanup: Option<mir::BasicBlock>,
118 // If there is a cleanup block and the function we're calling can unwind, then
119 // do an invoke, otherwise do a call.
120 if let Some(cleanup) = cleanup.filter(|_| fn_abi.can_unwind) {
121 let ret_bx = if let Some((_, target)) = destination {
124 fx.unreachable_block()
127 bx.invoke(fn_ptr, &llargs, ret_bx, self.llblock(fx, cleanup), self.funclet(fx));
128 bx.apply_attrs_callsite(&fn_abi, invokeret);
130 if let Some((ret_dest, target)) = destination {
131 let mut ret_bx = fx.build_block(target);
132 fx.set_debug_loc(&mut ret_bx, self.terminator.source_info);
133 fx.store_return(&mut ret_bx, ret_dest, &fn_abi.ret, invokeret);
136 let llret = bx.call(fn_ptr, &llargs, self.funclet(fx));
137 bx.apply_attrs_callsite(&fn_abi, llret);
138 if fx.mir[self.bb].is_cleanup {
139 // Cleanup is always the cold path. Don't inline
140 // drop glue. Also, when there is a deeply-nested
141 // struct, there are "symmetry" issues that cause
142 // exponential inlining - see issue #41696.
143 bx.do_not_inline(llret);
146 if let Some((ret_dest, target)) = destination {
147 fx.store_return(bx, ret_dest, &fn_abi.ret, llret);
148 self.funclet_br(fx, bx, target);
155 // Generate sideeffect intrinsic if jumping to any of the targets can form
157 fn maybe_sideeffect<Bx: BuilderMethods<'a, 'tcx>>(
159 mir: &'tcx mir::Body<'tcx>,
161 targets: &[mir::BasicBlock],
163 if bx.tcx().sess.opts.debugging_opts.insert_sideeffect {
164 if targets.iter().any(|&target| {
166 && target.start_location().is_predecessor_of(self.bb.start_location(), mir)
174 /// Codegen implementations for some terminator variants.
175 impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
176 /// Generates code for a `Resume` terminator.
177 fn codegen_resume_terminator(&mut self, helper: TerminatorCodegenHelper<'tcx>, mut bx: Bx) {
178 if let Some(funclet) = helper.funclet(self) {
179 bx.cleanup_ret(funclet, None);
181 let slot = self.get_personality_slot(&mut bx);
182 let lp0 = slot.project_field(&mut bx, 0);
183 let lp0 = bx.load_operand(lp0).immediate();
184 let lp1 = slot.project_field(&mut bx, 1);
185 let lp1 = bx.load_operand(lp1).immediate();
186 slot.storage_dead(&mut bx);
188 let mut lp = bx.const_undef(self.landing_pad_type());
189 lp = bx.insert_value(lp, lp0, 0);
190 lp = bx.insert_value(lp, lp1, 1);
195 fn codegen_switchint_terminator(
197 helper: TerminatorCodegenHelper<'tcx>,
199 discr: &mir::Operand<'tcx>,
201 values: &Cow<'tcx, [u128]>,
202 targets: &Vec<mir::BasicBlock>,
204 let discr = self.codegen_operand(&mut bx, &discr);
205 // `switch_ty` is redundant, sanity-check that.
206 assert_eq!(discr.layout.ty, switch_ty);
207 if targets.len() == 2 {
208 // If there are two targets, emit br instead of switch
209 let lltrue = helper.llblock(self, targets[0]);
210 let llfalse = helper.llblock(self, targets[1]);
211 if switch_ty == bx.tcx().types.bool {
212 helper.maybe_sideeffect(self.mir, &mut bx, targets.as_slice());
213 // Don't generate trivial icmps when switching on bool
214 if let [0] = values[..] {
215 bx.cond_br(discr.immediate(), llfalse, lltrue);
217 assert_eq!(&values[..], &[1]);
218 bx.cond_br(discr.immediate(), lltrue, llfalse);
221 let switch_llty = bx.immediate_backend_type(bx.layout_of(switch_ty));
222 let llval = bx.const_uint_big(switch_llty, values[0]);
223 let cmp = bx.icmp(IntPredicate::IntEQ, discr.immediate(), llval);
224 helper.maybe_sideeffect(self.mir, &mut bx, targets.as_slice());
225 bx.cond_br(cmp, lltrue, llfalse);
228 helper.maybe_sideeffect(self.mir, &mut bx, targets.as_slice());
229 let (otherwise, targets) = targets.split_last().unwrap();
232 helper.llblock(self, *otherwise),
236 .map(|(&value, target)| (value, helper.llblock(self, *target))),
241 fn codegen_return_terminator(&mut self, mut bx: Bx) {
242 // Call `va_end` if this is the definition of a C-variadic function.
243 if self.fn_abi.c_variadic {
244 // The `VaList` "spoofed" argument is just after all the real arguments.
245 let va_list_arg_idx = self.fn_abi.args.len();
246 match self.locals[mir::Local::new(1 + va_list_arg_idx)] {
247 LocalRef::Place(va_list) => {
248 bx.va_end(va_list.llval);
250 _ => bug!("C-variadic function must have a `VaList` place"),
253 if self.fn_abi.ret.layout.abi.is_uninhabited() {
254 // Functions with uninhabited return values are marked `noreturn`,
255 // so we should make sure that we never actually do.
256 // We play it safe by using a well-defined `abort`, but we could go for immediate UB
257 // if that turns out to be helpful.
259 // `abort` does not terminate the block, so we still need to generate
260 // an `unreachable` terminator after it.
264 let llval = match self.fn_abi.ret.mode {
265 PassMode::Ignore | PassMode::Indirect(..) => {
270 PassMode::Direct(_) | PassMode::Pair(..) => {
271 let op = self.codegen_consume(&mut bx, mir::Place::return_place().as_ref());
272 if let Ref(llval, _, align) = op.val {
273 bx.load(llval, align)
275 op.immediate_or_packed_pair(&mut bx)
279 PassMode::Cast(cast_ty) => {
280 let op = match self.locals[mir::RETURN_PLACE] {
281 LocalRef::Operand(Some(op)) => op,
282 LocalRef::Operand(None) => bug!("use of return before def"),
283 LocalRef::Place(cg_place) => OperandRef {
284 val: Ref(cg_place.llval, None, cg_place.align),
285 layout: cg_place.layout,
287 LocalRef::UnsizedPlace(_) => bug!("return type must be sized"),
289 let llslot = match op.val {
290 Immediate(_) | Pair(..) => {
291 let scratch = PlaceRef::alloca(&mut bx, self.fn_abi.ret.layout);
292 op.val.store(&mut bx, scratch);
295 Ref(llval, _, align) => {
296 assert_eq!(align, op.layout.align.abi, "return place is unaligned!");
300 let addr = bx.pointercast(llslot, bx.type_ptr_to(bx.cast_backend_type(&cast_ty)));
301 bx.load(addr, self.fn_abi.ret.layout.align.abi)
307 fn codegen_drop_terminator(
309 helper: TerminatorCodegenHelper<'tcx>,
311 location: mir::Place<'tcx>,
312 target: mir::BasicBlock,
313 unwind: Option<mir::BasicBlock>,
315 let ty = location.ty(self.mir, bx.tcx()).ty;
316 let ty = self.monomorphize(&ty);
317 let drop_fn = Instance::resolve_drop_in_place(bx.tcx(), ty);
319 if let ty::InstanceDef::DropGlue(_, None) = drop_fn.def {
320 // we don't actually need to drop anything.
321 helper.maybe_sideeffect(self.mir, &mut bx, &[target]);
322 helper.funclet_br(self, &mut bx, target);
326 let place = self.codegen_place(&mut bx, location.as_ref());
328 let mut args = if let Some(llextra) = place.llextra {
329 args2 = [place.llval, llextra];
332 args1 = [place.llval];
335 let (drop_fn, fn_abi) = match ty.kind() {
336 // FIXME(eddyb) perhaps move some of this logic into
337 // `Instance::resolve_drop_in_place`?
339 let virtual_drop = Instance {
340 def: ty::InstanceDef::Virtual(drop_fn.def_id(), 0),
341 substs: drop_fn.substs,
343 let fn_abi = FnAbi::of_instance(&bx, virtual_drop, &[]);
344 let vtable = args[1];
346 (meth::DESTRUCTOR.get_fn(&mut bx, vtable, &fn_abi), fn_abi)
348 _ => (bx.get_fn_addr(drop_fn), FnAbi::of_instance(&bx, drop_fn, &[])),
350 helper.maybe_sideeffect(self.mir, &mut bx, &[target]);
357 Some((ReturnDest::Nothing, target)),
362 fn codegen_assert_terminator(
364 helper: TerminatorCodegenHelper<'tcx>,
366 terminator: &mir::Terminator<'tcx>,
367 cond: &mir::Operand<'tcx>,
369 msg: &mir::AssertMessage<'tcx>,
370 target: mir::BasicBlock,
371 cleanup: Option<mir::BasicBlock>,
373 let span = terminator.source_info.span;
374 let cond = self.codegen_operand(&mut bx, cond).immediate();
375 let mut const_cond = bx.const_to_opt_u128(cond, false).map(|c| c == 1);
377 // This case can currently arise only from functions marked
378 // with #[rustc_inherit_overflow_checks] and inlined from
379 // another crate (mostly core::num generic/#[inline] fns),
380 // while the current crate doesn't use overflow checks.
381 // NOTE: Unlike binops, negation doesn't have its own
382 // checked operation, just a comparison with the minimum
383 // value, so we have to check for the assert message.
384 if !bx.check_overflow() {
385 if let AssertKind::OverflowNeg(_) = *msg {
386 const_cond = Some(expected);
390 // Don't codegen the panic block if success if known.
391 if const_cond == Some(expected) {
392 helper.maybe_sideeffect(self.mir, &mut bx, &[target]);
393 helper.funclet_br(self, &mut bx, target);
397 // Pass the condition through llvm.expect for branch hinting.
398 let cond = bx.expect(cond, expected);
400 // Create the failure block and the conditional branch to it.
401 let lltarget = helper.llblock(self, target);
402 let panic_block = self.new_block("panic");
403 helper.maybe_sideeffect(self.mir, &mut bx, &[target]);
405 bx.cond_br(cond, lltarget, panic_block.llbb());
407 bx.cond_br(cond, panic_block.llbb(), lltarget);
410 // After this point, bx is the block for the call to panic.
412 self.set_debug_loc(&mut bx, terminator.source_info);
414 // Get the location information.
415 let location = self.get_caller_location(&mut bx, span).immediate();
417 // Put together the arguments to the panic entry point.
418 let (lang_item, args) = match msg {
419 AssertKind::BoundsCheck { ref len, ref index } => {
420 let len = self.codegen_operand(&mut bx, len).immediate();
421 let index = self.codegen_operand(&mut bx, index).immediate();
422 // It's `fn panic_bounds_check(index: usize, len: usize)`,
423 // and `#[track_caller]` adds an implicit third argument.
424 (LangItem::PanicBoundsCheck, vec![index, len, location])
427 let msg_str = Symbol::intern(msg.description());
428 let msg = bx.const_str(msg_str);
429 // It's `pub fn panic(expr: &str)`, with the wide reference being passed
430 // as two arguments, and `#[track_caller]` adds an implicit third argument.
431 (LangItem::Panic, vec![msg.0, msg.1, location])
435 // Obtain the panic entry point.
436 let def_id = common::langcall(bx.tcx(), Some(span), "", lang_item);
437 let instance = ty::Instance::mono(bx.tcx(), def_id);
438 let fn_abi = FnAbi::of_instance(&bx, instance, &[]);
439 let llfn = bx.get_fn_addr(instance);
441 // Codegen the actual panic invoke/call.
442 helper.do_call(self, &mut bx, fn_abi, llfn, &args, None, cleanup);
445 /// Returns `true` if this is indeed a panic intrinsic and codegen is done.
446 fn codegen_panic_intrinsic(
448 helper: &TerminatorCodegenHelper<'tcx>,
450 intrinsic: Option<Symbol>,
451 instance: Option<Instance<'tcx>>,
453 destination: &Option<(mir::Place<'tcx>, mir::BasicBlock)>,
454 cleanup: Option<mir::BasicBlock>,
456 // Emit a panic or a no-op for `assert_*` intrinsics.
457 // These are intrinsics that compile to panics so that we can get a message
458 // which mentions the offending type, even from a const context.
459 #[derive(Debug, PartialEq)]
460 enum AssertIntrinsic {
465 let panic_intrinsic = intrinsic.and_then(|i| match i {
466 sym::assert_inhabited => Some(AssertIntrinsic::Inhabited),
467 sym::assert_zero_valid => Some(AssertIntrinsic::ZeroValid),
468 sym::assert_uninit_valid => Some(AssertIntrinsic::UninitValid),
471 if let Some(intrinsic) = panic_intrinsic {
472 use AssertIntrinsic::*;
473 let ty = instance.unwrap().substs.type_at(0);
474 let layout = bx.layout_of(ty);
475 let do_panic = match intrinsic {
476 Inhabited => layout.abi.is_uninhabited(),
477 // We unwrap as the error type is `!`.
478 ZeroValid => !layout.might_permit_raw_init(bx, /*zero:*/ true).unwrap(),
479 // We unwrap as the error type is `!`.
480 UninitValid => !layout.might_permit_raw_init(bx, /*zero:*/ false).unwrap(),
483 let msg_str = with_no_trimmed_paths(|| {
484 if layout.abi.is_uninhabited() {
485 // Use this error even for the other intrinsics as it is more precise.
486 format!("attempted to instantiate uninhabited type `{}`", ty)
487 } else if intrinsic == ZeroValid {
488 format!("attempted to zero-initialize type `{}`, which is invalid", ty)
490 format!("attempted to leave type `{}` uninitialized, which is invalid", ty)
493 let msg = bx.const_str(Symbol::intern(&msg_str));
494 let location = self.get_caller_location(bx, span).immediate();
496 // Obtain the panic entry point.
497 // FIXME: dedup this with `codegen_assert_terminator` above.
498 let def_id = common::langcall(bx.tcx(), Some(span), "", LangItem::Panic);
499 let instance = ty::Instance::mono(bx.tcx(), def_id);
500 let fn_abi = FnAbi::of_instance(bx, instance, &[]);
501 let llfn = bx.get_fn_addr(instance);
503 if let Some((_, target)) = destination.as_ref() {
504 helper.maybe_sideeffect(self.mir, bx, &[*target]);
506 // Codegen the actual panic invoke/call.
512 &[msg.0, msg.1, location],
513 destination.as_ref().map(|(_, bb)| (ReturnDest::Nothing, *bb)),
518 let target = destination.as_ref().unwrap().1;
519 helper.maybe_sideeffect(self.mir, bx, &[target]);
520 helper.funclet_br(self, bx, target)
528 fn codegen_call_terminator(
530 helper: TerminatorCodegenHelper<'tcx>,
532 terminator: &mir::Terminator<'tcx>,
533 func: &mir::Operand<'tcx>,
534 args: &Vec<mir::Operand<'tcx>>,
535 destination: &Option<(mir::Place<'tcx>, mir::BasicBlock)>,
536 cleanup: Option<mir::BasicBlock>,
539 let span = terminator.source_info.span;
540 // Create the callee. This is a fn ptr or zero-sized and hence a kind of scalar.
541 let callee = self.codegen_operand(&mut bx, func);
543 let (instance, mut llfn) = match *callee.layout.ty.kind() {
544 ty::FnDef(def_id, substs) => (
546 ty::Instance::resolve(bx.tcx(), ty::ParamEnv::reveal_all(), def_id, substs)
549 .polymorphize(bx.tcx()),
553 ty::FnPtr(_) => (None, Some(callee.immediate())),
554 _ => bug!("{} is not callable", callee.layout.ty),
556 let def = instance.map(|i| i.def);
558 if let Some(ty::InstanceDef::DropGlue(_, None)) = def {
559 // Empty drop glue; a no-op.
560 let &(_, target) = destination.as_ref().unwrap();
561 helper.maybe_sideeffect(self.mir, &mut bx, &[target]);
562 helper.funclet_br(self, &mut bx, target);
566 // FIXME(eddyb) avoid computing this if possible, when `instance` is
567 // available - right now `sig` is only needed for getting the `abi`
568 // and figuring out how many extra args were passed to a C-variadic `fn`.
569 let sig = callee.layout.ty.fn_sig(bx.tcx());
572 // Handle intrinsics old codegen wants Expr's for, ourselves.
573 let intrinsic = match def {
574 Some(ty::InstanceDef::Intrinsic(def_id)) => Some(bx.tcx().item_name(def_id)),
578 let extra_args = &args[sig.inputs().skip_binder().len()..];
579 let extra_args = extra_args
582 let op_ty = op_arg.ty(self.mir, bx.tcx());
583 self.monomorphize(&op_ty)
585 .collect::<Vec<_>>();
587 let fn_abi = match instance {
588 Some(instance) => FnAbi::of_instance(&bx, instance, &extra_args),
589 None => FnAbi::of_fn_ptr(&bx, sig, &extra_args),
592 if intrinsic == Some(sym::transmute) {
593 if let Some(destination_ref) = destination.as_ref() {
594 let &(dest, target) = destination_ref;
595 self.codegen_transmute(&mut bx, &args[0], dest);
596 helper.maybe_sideeffect(self.mir, &mut bx, &[target]);
597 helper.funclet_br(self, &mut bx, target);
599 // If we are trying to transmute to an uninhabited type,
600 // it is likely there is no allotted destination. In fact,
601 // transmuting to an uninhabited type is UB, which means
602 // we can do what we like. Here, we declare that transmuting
603 // into an uninhabited type is impossible, so anything following
604 // it must be unreachable.
605 assert_eq!(fn_abi.ret.layout.abi, abi::Abi::Uninhabited);
611 if self.codegen_panic_intrinsic(
623 // The arguments we'll be passing. Plus one to account for outptr, if used.
624 let arg_count = fn_abi.args.len() + fn_abi.ret.is_indirect() as usize;
625 let mut llargs = Vec::with_capacity(arg_count);
627 // Prepare the return value destination
628 let ret_dest = if let Some((dest, _)) = *destination {
629 let is_intrinsic = intrinsic.is_some();
630 self.make_return_dest(&mut bx, dest, &fn_abi.ret, &mut llargs, is_intrinsic)
635 if intrinsic == Some(sym::caller_location) {
636 if let Some((_, target)) = destination.as_ref() {
637 let location = self.get_caller_location(&mut bx, fn_span);
639 if let ReturnDest::IndirectOperand(tmp, _) = ret_dest {
640 location.val.store(&mut bx, tmp);
642 self.store_return(&mut bx, ret_dest, &fn_abi.ret, location.immediate());
644 helper.maybe_sideeffect(self.mir, &mut bx, &[*target]);
645 helper.funclet_br(self, &mut bx, *target);
650 if intrinsic.is_some() && intrinsic != Some(sym::drop_in_place) {
651 let intrinsic = intrinsic.unwrap();
652 let dest = match ret_dest {
653 _ if fn_abi.ret.is_indirect() => llargs[0],
654 ReturnDest::Nothing => {
655 bx.const_undef(bx.type_ptr_to(bx.arg_memory_ty(&fn_abi.ret)))
657 ReturnDest::IndirectOperand(dst, _) | ReturnDest::Store(dst) => dst.llval,
658 ReturnDest::DirectOperand(_) => {
659 bug!("Cannot use direct operand with an intrinsic call")
663 let args: Vec<_> = args
667 // The indices passed to simd_shuffle* in the
668 // third argument must be constant. This is
669 // checked by const-qualification, which also
670 // promotes any complex rvalues to constants.
671 if i == 2 && intrinsic.as_str().starts_with("simd_shuffle") {
672 if let mir::Operand::Constant(constant) = arg {
673 let c = self.eval_mir_constant(constant);
674 let (llval, ty) = self.simd_shuffle_indices(
680 return OperandRef { val: Immediate(llval), layout: bx.layout_of(ty) };
682 span_bug!(span, "shuffle indices must be constant");
686 self.codegen_operand(&mut bx, arg)
690 bx.codegen_intrinsic_call(
691 *instance.as_ref().unwrap(),
695 terminator.source_info.span,
698 if let ReturnDest::IndirectOperand(dst, _) = ret_dest {
699 self.store_return(&mut bx, ret_dest, &fn_abi.ret, dst.llval);
702 if let Some((_, target)) = *destination {
703 helper.maybe_sideeffect(self.mir, &mut bx, &[target]);
704 helper.funclet_br(self, &mut bx, target);
712 // Split the rust-call tupled arguments off.
713 let (first_args, untuple) = if abi == Abi::RustCall && !args.is_empty() {
714 let (tup, args) = args.split_last().unwrap();
720 'make_args: for (i, arg) in first_args.iter().enumerate() {
721 let mut op = self.codegen_operand(&mut bx, arg);
723 if let (0, Some(ty::InstanceDef::Virtual(_, idx))) = (i, def) {
724 if let Pair(..) = op.val {
725 // In the case of Rc<Self>, we need to explicitly pass a
726 // *mut RcBox<Self> with a Scalar (not ScalarPair) ABI. This is a hack
727 // that is understood elsewhere in the compiler as a method on
729 // To get a `*mut RcBox<Self>`, we just keep unwrapping newtypes until
730 // we get a value of a built-in pointer type
731 'descend_newtypes: while !op.layout.ty.is_unsafe_ptr()
732 && !op.layout.ty.is_region_ptr()
734 for i in 0..op.layout.fields.count() {
735 let field = op.extract_field(&mut bx, i);
736 if !field.layout.is_zst() {
737 // we found the one non-zero-sized field that is allowed
738 // now find *its* non-zero-sized field, or stop if it's a
741 continue 'descend_newtypes;
745 span_bug!(span, "receiver has no non-zero-sized fields {:?}", op);
748 // now that we have `*dyn Trait` or `&dyn Trait`, split it up into its
749 // data pointer and vtable. Look up the method in the vtable, and pass
750 // the data pointer as the first argument
752 Pair(data_ptr, meta) => {
754 meth::VirtualIndex::from_index(idx).get_fn(&mut bx, meta, &fn_abi),
756 llargs.push(data_ptr);
759 other => bug!("expected a Pair, got {:?}", other),
761 } else if let Ref(data_ptr, Some(meta), _) = op.val {
762 // by-value dynamic dispatch
763 llfn = Some(meth::VirtualIndex::from_index(idx).get_fn(&mut bx, meta, &fn_abi));
764 llargs.push(data_ptr);
767 span_bug!(span, "can't codegen a virtual call on {:?}", op);
771 // The callee needs to own the argument memory if we pass it
772 // by-ref, so make a local copy of non-immediate constants.
773 match (arg, op.val) {
774 (&mir::Operand::Copy(_), Ref(_, None, _))
775 | (&mir::Operand::Constant(_), Ref(_, None, _)) => {
776 let tmp = PlaceRef::alloca(&mut bx, op.layout);
777 op.val.store(&mut bx, tmp);
778 op.val = Ref(tmp.llval, None, tmp.align);
783 self.codegen_argument(&mut bx, op, &mut llargs, &fn_abi.args[i]);
785 if let Some(tup) = untuple {
786 self.codegen_arguments_untupled(
790 &fn_abi.args[first_args.len()..],
795 instance.map_or(false, |i| i.def.requires_caller_location(self.cx.tcx()));
800 "#[track_caller] fn's must have 1 more argument in their ABI than in their MIR",
802 let location = self.get_caller_location(&mut bx, fn_span);
804 "codegen_call_terminator({:?}): location={:?} (fn_span {:?})",
805 terminator, location, fn_span
808 let last_arg = fn_abi.args.last().unwrap();
809 self.codegen_argument(&mut bx, location, &mut llargs, last_arg);
812 let fn_ptr = match (llfn, instance) {
813 (Some(llfn), _) => llfn,
814 (None, Some(instance)) => bx.get_fn_addr(instance),
815 _ => span_bug!(span, "no llfn for call"),
818 if let Some((_, target)) = destination.as_ref() {
819 helper.maybe_sideeffect(self.mir, &mut bx, &[*target]);
827 destination.as_ref().map(|&(_, target)| (ret_dest, target)),
832 fn codegen_asm_terminator(
834 helper: TerminatorCodegenHelper<'tcx>,
836 terminator: &mir::Terminator<'tcx>,
837 template: &[ast::InlineAsmTemplatePiece],
838 operands: &[mir::InlineAsmOperand<'tcx>],
839 options: ast::InlineAsmOptions,
841 destination: Option<mir::BasicBlock>,
843 let span = terminator.source_info.span;
845 let operands: Vec<_> = operands
847 .map(|op| match *op {
848 mir::InlineAsmOperand::In { reg, ref value } => {
849 let value = self.codegen_operand(&mut bx, value);
850 InlineAsmOperandRef::In { reg, value }
852 mir::InlineAsmOperand::Out { reg, late, ref place } => {
853 let place = place.map(|place| self.codegen_place(&mut bx, place.as_ref()));
854 InlineAsmOperandRef::Out { reg, late, place }
856 mir::InlineAsmOperand::InOut { reg, late, ref in_value, ref out_place } => {
857 let in_value = self.codegen_operand(&mut bx, in_value);
859 out_place.map(|out_place| self.codegen_place(&mut bx, out_place.as_ref()));
860 InlineAsmOperandRef::InOut { reg, late, in_value, out_place }
862 mir::InlineAsmOperand::Const { ref value } => {
863 if let mir::Operand::Constant(constant) = value {
864 let const_value = self
865 .eval_mir_constant(constant)
866 .unwrap_or_else(|_| span_bug!(span, "asm const cannot be resolved"));
867 let ty = constant.literal.ty;
868 let size = bx.layout_of(ty).size;
869 let scalar = match const_value {
870 // Promoted constants are evaluated into a ByRef instead of a Scalar,
871 // but we want the scalar value here.
872 ConstValue::ByRef { alloc, offset } => {
873 let ptr = Pointer::new(AllocId(0), offset);
875 .read_scalar(&bx, ptr, size)
876 .and_then(|s| s.check_init())
877 .unwrap_or_else(|e| {
878 bx.tcx().sess.span_err(
880 &format!("Could not evaluate asm const: {}", e),
883 // We are erroring out, just emit a dummy constant.
887 _ => span_bug!(span, "expected ByRef for promoted asm const"),
889 let value = scalar.assert_bits(size);
890 let string = match ty.kind() {
891 ty::Uint(_) => value.to_string(),
893 match int_ty.normalize(bx.tcx().sess.target.ptr_width) {
894 ast::IntTy::I8 => (value as i8).to_string(),
895 ast::IntTy::I16 => (value as i16).to_string(),
896 ast::IntTy::I32 => (value as i32).to_string(),
897 ast::IntTy::I64 => (value as i64).to_string(),
898 ast::IntTy::I128 => (value as i128).to_string(),
899 ast::IntTy::Isize => unreachable!(),
902 ty::Float(ast::FloatTy::F32) => {
903 f32::from_bits(value as u32).to_string()
905 ty::Float(ast::FloatTy::F64) => {
906 f64::from_bits(value as u64).to_string()
908 _ => span_bug!(span, "asm const has bad type {}", ty),
910 InlineAsmOperandRef::Const { string }
912 span_bug!(span, "asm const is not a constant");
915 mir::InlineAsmOperand::SymFn { ref value } => {
916 let literal = self.monomorphize(&value.literal);
917 if let ty::FnDef(def_id, substs) = *literal.ty.kind() {
918 let instance = ty::Instance::resolve_for_fn_ptr(
920 ty::ParamEnv::reveal_all(),
925 InlineAsmOperandRef::SymFn { instance }
927 span_bug!(span, "invalid type for asm sym (fn)");
930 mir::InlineAsmOperand::SymStatic { def_id } => {
931 InlineAsmOperandRef::SymStatic { def_id }
936 bx.codegen_inline_asm(template, &operands, options, line_spans);
938 if let Some(target) = destination {
939 helper.funclet_br(self, &mut bx, target);
946 impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
947 pub fn codegen_block(&mut self, bb: mir::BasicBlock) {
948 let mut bx = self.build_block(bb);
952 debug!("codegen_block({:?}={:?})", bb, data);
954 for statement in &data.statements {
955 bx = self.codegen_statement(bx, statement);
958 self.codegen_terminator(bx, bb, data.terminator());
961 fn codegen_terminator(
965 terminator: &'tcx mir::Terminator<'tcx>,
967 debug!("codegen_terminator: {:?}", terminator);
969 // Create the cleanup bundle, if needed.
970 let funclet_bb = self.cleanup_kinds[bb].funclet_bb(bb);
971 let helper = TerminatorCodegenHelper { bb, terminator, funclet_bb };
973 self.set_debug_loc(&mut bx, terminator.source_info);
974 match terminator.kind {
975 mir::TerminatorKind::Resume => self.codegen_resume_terminator(helper, bx),
977 mir::TerminatorKind::Abort => {
979 // `abort` does not terminate the block, so we still need to generate
980 // an `unreachable` terminator after it.
984 mir::TerminatorKind::Goto { target } => {
985 helper.maybe_sideeffect(self.mir, &mut bx, &[target]);
986 helper.funclet_br(self, &mut bx, target);
989 mir::TerminatorKind::SwitchInt { ref discr, switch_ty, ref values, ref targets } => {
990 self.codegen_switchint_terminator(helper, bx, discr, switch_ty, values, targets);
993 mir::TerminatorKind::Return => {
994 self.codegen_return_terminator(bx);
997 mir::TerminatorKind::Unreachable => {
1001 mir::TerminatorKind::Drop { place, target, unwind } => {
1002 self.codegen_drop_terminator(helper, bx, place, target, unwind);
1005 mir::TerminatorKind::Assert { ref cond, expected, ref msg, target, cleanup } => {
1006 self.codegen_assert_terminator(
1007 helper, bx, terminator, cond, expected, msg, target, cleanup,
1011 mir::TerminatorKind::DropAndReplace { .. } => {
1012 bug!("undesugared DropAndReplace in codegen: {:?}", terminator);
1015 mir::TerminatorKind::Call {
1023 self.codegen_call_terminator(
1034 mir::TerminatorKind::GeneratorDrop | mir::TerminatorKind::Yield { .. } => {
1035 bug!("generator ops in codegen")
1037 mir::TerminatorKind::FalseEdge { .. } | mir::TerminatorKind::FalseUnwind { .. } => {
1038 bug!("borrowck false edges in codegen")
1041 mir::TerminatorKind::InlineAsm {
1048 self.codegen_asm_terminator(
1062 fn codegen_argument(
1065 op: OperandRef<'tcx, Bx::Value>,
1066 llargs: &mut Vec<Bx::Value>,
1067 arg: &ArgAbi<'tcx, Ty<'tcx>>,
1069 // Fill padding with undef value, where applicable.
1070 if let Some(ty) = arg.pad {
1071 llargs.push(bx.const_undef(bx.reg_backend_type(&ty)))
1074 if arg.is_ignore() {
1078 if let PassMode::Pair(..) = arg.mode {
1085 _ => bug!("codegen_argument: {:?} invalid for pair argument", op),
1087 } else if arg.is_unsized_indirect() {
1089 Ref(a, Some(b), _) => {
1094 _ => bug!("codegen_argument: {:?} invalid for unsized indirect argument", op),
1098 // Force by-ref if we have to load through a cast pointer.
1099 let (mut llval, align, by_ref) = match op.val {
1100 Immediate(_) | Pair(..) => match arg.mode {
1101 PassMode::Indirect(..) | PassMode::Cast(_) => {
1102 let scratch = PlaceRef::alloca(bx, arg.layout);
1103 op.val.store(bx, scratch);
1104 (scratch.llval, scratch.align, true)
1106 _ => (op.immediate_or_packed_pair(bx), arg.layout.align.abi, false),
1108 Ref(llval, _, align) => {
1109 if arg.is_indirect() && align < arg.layout.align.abi {
1110 // `foo(packed.large_field)`. We can't pass the (unaligned) field directly. I
1111 // think that ATM (Rust 1.16) we only pass temporaries, but we shouldn't
1112 // have scary latent bugs around.
1114 let scratch = PlaceRef::alloca(bx, arg.layout);
1124 (scratch.llval, scratch.align, true)
1126 (llval, align, true)
1131 if by_ref && !arg.is_indirect() {
1132 // Have to load the argument, maybe while casting it.
1133 if let PassMode::Cast(ty) = arg.mode {
1134 let addr = bx.pointercast(llval, bx.type_ptr_to(bx.cast_backend_type(&ty)));
1135 llval = bx.load(addr, align.min(arg.layout.align.abi));
1137 // We can't use `PlaceRef::load` here because the argument
1138 // may have a type we don't treat as immediate, but the ABI
1139 // used for this call is passing it by-value. In that case,
1140 // the load would just produce `OperandValue::Ref` instead
1141 // of the `OperandValue::Immediate` we need for the call.
1142 llval = bx.load(llval, align);
1143 if let abi::Abi::Scalar(ref scalar) = arg.layout.abi {
1144 if scalar.is_bool() {
1145 bx.range_metadata(llval, 0..2);
1148 // We store bools as `i8` so we need to truncate to `i1`.
1149 llval = bx.to_immediate(llval, arg.layout);
1156 fn codegen_arguments_untupled(
1159 operand: &mir::Operand<'tcx>,
1160 llargs: &mut Vec<Bx::Value>,
1161 args: &[ArgAbi<'tcx, Ty<'tcx>>],
1163 let tuple = self.codegen_operand(bx, operand);
1165 // Handle both by-ref and immediate tuples.
1166 if let Ref(llval, None, align) = tuple.val {
1167 let tuple_ptr = PlaceRef::new_sized_aligned(llval, tuple.layout, align);
1168 for i in 0..tuple.layout.fields.count() {
1169 let field_ptr = tuple_ptr.project_field(bx, i);
1170 let field = bx.load_operand(field_ptr);
1171 self.codegen_argument(bx, field, llargs, &args[i]);
1173 } else if let Ref(_, Some(_), _) = tuple.val {
1174 bug!("closure arguments must be sized")
1176 // If the tuple is immediate, the elements are as well.
1177 for i in 0..tuple.layout.fields.count() {
1178 let op = tuple.extract_field(bx, i);
1179 self.codegen_argument(bx, op, llargs, &args[i]);
1184 fn get_caller_location(&mut self, bx: &mut Bx, span: Span) -> OperandRef<'tcx, Bx::Value> {
1185 self.caller_location.unwrap_or_else(|| {
1186 let topmost = span.ctxt().outer_expn().expansion_cause().unwrap_or(span);
1187 let caller = bx.tcx().sess.source_map().lookup_char_pos(topmost.lo());
1188 let const_loc = bx.tcx().const_caller_location((
1189 Symbol::intern(&caller.file.name.to_string()),
1191 caller.col_display as u32 + 1,
1193 OperandRef::from_const(bx, const_loc, bx.tcx().caller_location_ty())
1197 fn get_personality_slot(&mut self, bx: &mut Bx) -> PlaceRef<'tcx, Bx::Value> {
1199 if let Some(slot) = self.personality_slot {
1202 let layout = cx.layout_of(
1203 cx.tcx().intern_tup(&[cx.tcx().mk_mut_ptr(cx.tcx().types.u8), cx.tcx().types.i32]),
1205 let slot = PlaceRef::alloca(bx, layout);
1206 self.personality_slot = Some(slot);
1211 /// Returns the landing-pad wrapper around the given basic block.
1213 /// No-op in MSVC SEH scheme.
1214 fn landing_pad_to(&mut self, target_bb: mir::BasicBlock) -> Bx::BasicBlock {
1215 if let Some(block) = self.landing_pads[target_bb] {
1219 let block = self.blocks[target_bb];
1220 let landing_pad = self.landing_pad_uncached(block);
1221 self.landing_pads[target_bb] = Some(landing_pad);
1225 fn landing_pad_uncached(&mut self, target_bb: Bx::BasicBlock) -> Bx::BasicBlock {
1226 if base::wants_msvc_seh(self.cx.sess()) {
1227 span_bug!(self.mir.span, "landing pad was not inserted?")
1230 let mut bx = self.new_block("cleanup");
1232 let llpersonality = self.cx.eh_personality();
1233 let llretty = self.landing_pad_type();
1234 let lp = bx.landing_pad(llretty, llpersonality, 1);
1237 let slot = self.get_personality_slot(&mut bx);
1238 slot.storage_live(&mut bx);
1239 Pair(bx.extract_value(lp, 0), bx.extract_value(lp, 1)).store(&mut bx, slot);
1245 fn landing_pad_type(&self) -> Bx::Type {
1247 cx.type_struct(&[cx.type_i8p(), cx.type_i32()], false)
1250 fn unreachable_block(&mut self) -> Bx::BasicBlock {
1251 self.unreachable_block.unwrap_or_else(|| {
1252 let mut bx = self.new_block("unreachable");
1254 self.unreachable_block = Some(bx.llbb());
1259 pub fn new_block(&self, name: &str) -> Bx {
1260 Bx::new_block(self.cx, self.llfn, name)
1263 pub fn build_block(&self, bb: mir::BasicBlock) -> Bx {
1264 let mut bx = Bx::with_cx(self.cx);
1265 bx.position_at_end(self.blocks[bb]);
1269 fn make_return_dest(
1272 dest: mir::Place<'tcx>,
1273 fn_ret: &ArgAbi<'tcx, Ty<'tcx>>,
1274 llargs: &mut Vec<Bx::Value>,
1276 ) -> ReturnDest<'tcx, Bx::Value> {
1277 // If the return is ignored, we can just return a do-nothing `ReturnDest`.
1278 if fn_ret.is_ignore() {
1279 return ReturnDest::Nothing;
1281 let dest = if let Some(index) = dest.as_local() {
1282 match self.locals[index] {
1283 LocalRef::Place(dest) => dest,
1284 LocalRef::UnsizedPlace(_) => bug!("return type must be sized"),
1285 LocalRef::Operand(None) => {
1286 // Handle temporary places, specifically `Operand` ones, as
1287 // they don't have `alloca`s.
1288 return if fn_ret.is_indirect() {
1289 // Odd, but possible, case, we have an operand temporary,
1290 // but the calling convention has an indirect return.
1291 let tmp = PlaceRef::alloca(bx, fn_ret.layout);
1292 tmp.storage_live(bx);
1293 llargs.push(tmp.llval);
1294 ReturnDest::IndirectOperand(tmp, index)
1295 } else if is_intrinsic {
1296 // Currently, intrinsics always need a location to store
1297 // the result, so we create a temporary `alloca` for the
1299 let tmp = PlaceRef::alloca(bx, fn_ret.layout);
1300 tmp.storage_live(bx);
1301 ReturnDest::IndirectOperand(tmp, index)
1303 ReturnDest::DirectOperand(index)
1306 LocalRef::Operand(Some(_)) => {
1307 bug!("place local already assigned to");
1313 mir::PlaceRef { local: dest.local, projection: &dest.projection },
1316 if fn_ret.is_indirect() {
1317 if dest.align < dest.layout.align.abi {
1318 // Currently, MIR code generation does not create calls
1319 // that store directly to fields of packed structs (in
1320 // fact, the calls it creates write only to temps).
1322 // If someone changes that, please update this code path
1323 // to create a temporary.
1324 span_bug!(self.mir.span, "can't directly store to unaligned value");
1326 llargs.push(dest.llval);
1329 ReturnDest::Store(dest)
1333 fn codegen_transmute(&mut self, bx: &mut Bx, src: &mir::Operand<'tcx>, dst: mir::Place<'tcx>) {
1334 if let Some(index) = dst.as_local() {
1335 match self.locals[index] {
1336 LocalRef::Place(place) => self.codegen_transmute_into(bx, src, place),
1337 LocalRef::UnsizedPlace(_) => bug!("transmute must not involve unsized locals"),
1338 LocalRef::Operand(None) => {
1339 let dst_layout = bx.layout_of(self.monomorphized_place_ty(dst.as_ref()));
1340 assert!(!dst_layout.ty.has_erasable_regions());
1341 let place = PlaceRef::alloca(bx, dst_layout);
1342 place.storage_live(bx);
1343 self.codegen_transmute_into(bx, src, place);
1344 let op = bx.load_operand(place);
1345 place.storage_dead(bx);
1346 self.locals[index] = LocalRef::Operand(Some(op));
1347 self.debug_introduce_local(bx, index);
1349 LocalRef::Operand(Some(op)) => {
1350 assert!(op.layout.is_zst(), "assigning to initialized SSAtemp");
1354 let dst = self.codegen_place(bx, dst.as_ref());
1355 self.codegen_transmute_into(bx, src, dst);
1359 fn codegen_transmute_into(
1362 src: &mir::Operand<'tcx>,
1363 dst: PlaceRef<'tcx, Bx::Value>,
1365 let src = self.codegen_operand(bx, src);
1366 let llty = bx.backend_type(src.layout);
1367 let cast_ptr = bx.pointercast(dst.llval, bx.type_ptr_to(llty));
1368 let align = src.layout.align.abi.min(dst.align);
1369 src.val.store(bx, PlaceRef::new_sized_aligned(cast_ptr, src.layout, align));
1372 // Stores the return value of a function call into it's final location.
1376 dest: ReturnDest<'tcx, Bx::Value>,
1377 ret_abi: &ArgAbi<'tcx, Ty<'tcx>>,
1380 use self::ReturnDest::*;
1384 Store(dst) => bx.store_arg(&ret_abi, llval, dst),
1385 IndirectOperand(tmp, index) => {
1386 let op = bx.load_operand(tmp);
1387 tmp.storage_dead(bx);
1388 self.locals[index] = LocalRef::Operand(Some(op));
1389 self.debug_introduce_local(bx, index);
1391 DirectOperand(index) => {
1392 // If there is a cast, we have to store and reload.
1393 let op = if let PassMode::Cast(_) = ret_abi.mode {
1394 let tmp = PlaceRef::alloca(bx, ret_abi.layout);
1395 tmp.storage_live(bx);
1396 bx.store_arg(&ret_abi, llval, tmp);
1397 let op = bx.load_operand(tmp);
1398 tmp.storage_dead(bx);
1401 OperandRef::from_immediate_or_packed_pair(bx, llval, ret_abi.layout)
1403 self.locals[index] = LocalRef::Operand(Some(op));
1404 self.debug_introduce_local(bx, index);
1410 enum ReturnDest<'tcx, V> {
1411 // Do nothing; the return value is indirect or ignored.
1413 // Store the return value to the pointer.
1414 Store(PlaceRef<'tcx, V>),
1415 // Store an indirect return value to an operand local place.
1416 IndirectOperand(PlaceRef<'tcx, V>, mir::Local),
1417 // Store a direct return value to an operand local place.
1418 DirectOperand(mir::Local),