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};
12 use rustc::middle::lang_items;
14 use rustc::mir::interpret::PanicInfo;
15 use rustc::ty::layout::{self, FnAbiExt, HasTyCtxt, LayoutOf};
16 use rustc::ty::{self, Instance, Ty, TypeFoldable};
17 use rustc_index::vec::Idx;
18 use rustc_span::{source_map::Span, symbol::Symbol};
19 use rustc_target::abi::call::{ArgAbi, FnAbi, PassMode};
20 use rustc_target::spec::abi::Abi;
24 /// Used by `FunctionCx::codegen_terminator` for emitting common patterns
25 /// e.g., creating a basic block, calling a function, etc.
26 struct TerminatorCodegenHelper<'tcx> {
28 terminator: &'tcx mir::Terminator<'tcx>,
29 funclet_bb: Option<mir::BasicBlock>,
32 impl<'a, 'tcx> TerminatorCodegenHelper<'tcx> {
33 /// Returns the associated funclet from `FunctionCx::funclets` for the
34 /// `funclet_bb` member if it is not `None`.
35 fn funclet<'b, Bx: BuilderMethods<'a, 'tcx>>(
37 fx: &'b mut FunctionCx<'a, 'tcx, Bx>,
38 ) -> Option<&'b Bx::Funclet> {
39 match self.funclet_bb {
40 Some(funcl) => fx.funclets[funcl].as_ref(),
45 fn lltarget<Bx: BuilderMethods<'a, 'tcx>>(
47 fx: &mut FunctionCx<'a, 'tcx, Bx>,
48 target: mir::BasicBlock,
49 ) -> (Bx::BasicBlock, bool) {
50 let span = self.terminator.source_info.span;
51 let lltarget = fx.blocks[target];
52 let target_funclet = fx.cleanup_kinds[target].funclet_bb(target);
53 match (self.funclet_bb, target_funclet) {
54 (None, None) => (lltarget, false),
55 (Some(f), Some(t_f)) if f == t_f || !base::wants_msvc_seh(fx.cx.tcx().sess) => {
58 // jump *into* cleanup - need a landing pad if GNU
59 (None, Some(_)) => (fx.landing_pad_to(target), false),
60 (Some(_), None) => span_bug!(span, "{:?} - jump out of cleanup?", self.terminator),
61 (Some(_), Some(_)) => (fx.landing_pad_to(target), true),
65 /// Create a basic block.
66 fn llblock<Bx: BuilderMethods<'a, 'tcx>>(
68 fx: &mut FunctionCx<'a, 'tcx, Bx>,
69 target: mir::BasicBlock,
71 let (lltarget, is_cleanupret) = self.lltarget(fx, target);
73 // MSVC cross-funclet jump - need a trampoline
75 debug!("llblock: creating cleanup trampoline for {:?}", target);
76 let name = &format!("{:?}_cleanup_trampoline_{:?}", self.bb, target);
77 let mut trampoline = fx.new_block(name);
78 trampoline.cleanup_ret(self.funclet(fx).unwrap(), Some(lltarget));
85 fn funclet_br<Bx: BuilderMethods<'a, 'tcx>>(
87 fx: &mut FunctionCx<'a, 'tcx, Bx>,
89 target: mir::BasicBlock,
91 let (lltarget, is_cleanupret) = self.lltarget(fx, target);
93 // micro-optimization: generate a `ret` rather than a jump
95 bx.cleanup_ret(self.funclet(fx).unwrap(), Some(lltarget));
101 /// Call `fn_ptr` of `fn_abi` with the arguments `llargs`, the optional
102 /// return destination `destination` and the cleanup function `cleanup`.
103 fn do_call<Bx: BuilderMethods<'a, 'tcx>>(
105 fx: &mut FunctionCx<'a, 'tcx, Bx>,
107 fn_abi: FnAbi<'tcx, Ty<'tcx>>,
109 llargs: &[Bx::Value],
110 destination: Option<(ReturnDest<'tcx, Bx::Value>, mir::BasicBlock)>,
111 cleanup: Option<mir::BasicBlock>,
113 if let Some(cleanup) = cleanup {
114 let ret_bx = if let Some((_, target)) = destination {
117 fx.unreachable_block()
120 bx.invoke(fn_ptr, &llargs, ret_bx, self.llblock(fx, cleanup), self.funclet(fx));
121 bx.apply_attrs_callsite(&fn_abi, invokeret);
123 if let Some((ret_dest, target)) = destination {
124 let mut ret_bx = fx.build_block(target);
125 fx.set_debug_loc(&mut ret_bx, self.terminator.source_info);
126 fx.store_return(&mut ret_bx, ret_dest, &fn_abi.ret, invokeret);
129 let llret = bx.call(fn_ptr, &llargs, self.funclet(fx));
130 bx.apply_attrs_callsite(&fn_abi, llret);
131 if fx.mir[self.bb].is_cleanup {
132 // Cleanup is always the cold path. Don't inline
133 // drop glue. Also, when there is a deeply-nested
134 // struct, there are "symmetry" issues that cause
135 // exponential inlining - see issue #41696.
136 bx.do_not_inline(llret);
139 if let Some((ret_dest, target)) = destination {
140 fx.store_return(bx, ret_dest, &fn_abi.ret, llret);
141 self.funclet_br(fx, bx, target);
148 // Generate sideeffect intrinsic if jumping to any of the targets can form
150 fn maybe_sideeffect<Bx: BuilderMethods<'a, 'tcx>>(
152 mir: mir::ReadOnlyBodyAndCache<'tcx, 'tcx>,
154 targets: &[mir::BasicBlock],
156 if bx.tcx().sess.opts.debugging_opts.insert_sideeffect {
157 if targets.iter().any(|&target| {
159 && target.start_location().is_predecessor_of(self.bb.start_location(), mir)
167 /// Codegen implementations for some terminator variants.
168 impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
169 /// Generates code for a `Resume` terminator.
170 fn codegen_resume_terminator(&mut self, helper: TerminatorCodegenHelper<'tcx>, mut bx: Bx) {
171 if let Some(funclet) = helper.funclet(self) {
172 bx.cleanup_ret(funclet, None);
174 let slot = self.get_personality_slot(&mut bx);
175 let lp0 = slot.project_field(&mut bx, 0);
176 let lp0 = bx.load_operand(lp0).immediate();
177 let lp1 = slot.project_field(&mut bx, 1);
178 let lp1 = bx.load_operand(lp1).immediate();
179 slot.storage_dead(&mut bx);
181 if !bx.sess().target.target.options.custom_unwind_resume {
182 let mut lp = bx.const_undef(self.landing_pad_type());
183 lp = bx.insert_value(lp, lp0, 0);
184 lp = bx.insert_value(lp, lp1, 1);
187 bx.call(bx.eh_unwind_resume(), &[lp0], helper.funclet(self));
193 fn codegen_switchint_terminator(
195 helper: TerminatorCodegenHelper<'tcx>,
197 discr: &mir::Operand<'tcx>,
199 values: &Cow<'tcx, [u128]>,
200 targets: &Vec<mir::BasicBlock>,
202 let discr = self.codegen_operand(&mut bx, &discr);
203 if targets.len() == 2 {
204 // If there are two targets, emit br instead of switch
205 let lltrue = helper.llblock(self, targets[0]);
206 let llfalse = helper.llblock(self, targets[1]);
207 if switch_ty == bx.tcx().types.bool {
208 helper.maybe_sideeffect(self.mir, &mut bx, targets.as_slice());
209 // Don't generate trivial icmps when switching on bool
210 if let [0] = values[..] {
211 bx.cond_br(discr.immediate(), llfalse, lltrue);
213 assert_eq!(&values[..], &[1]);
214 bx.cond_br(discr.immediate(), lltrue, llfalse);
217 let switch_llty = bx.immediate_backend_type(bx.layout_of(switch_ty));
218 let llval = bx.const_uint_big(switch_llty, values[0]);
219 let cmp = bx.icmp(IntPredicate::IntEQ, discr.immediate(), llval);
220 helper.maybe_sideeffect(self.mir, &mut bx, targets.as_slice());
221 bx.cond_br(cmp, lltrue, llfalse);
224 helper.maybe_sideeffect(self.mir, &mut bx, targets.as_slice());
225 let (otherwise, targets) = targets.split_last().unwrap();
228 helper.llblock(self, *otherwise),
232 .map(|(&value, target)| (value, helper.llblock(self, *target))),
237 fn codegen_return_terminator(&mut self, mut bx: Bx) {
238 // Call `va_end` if this is the definition of a C-variadic function.
239 if self.fn_abi.c_variadic {
240 // The `VaList` "spoofed" argument is just after all the real arguments.
241 let va_list_arg_idx = self.fn_abi.args.len();
242 match self.locals[mir::Local::new(1 + va_list_arg_idx)] {
243 LocalRef::Place(va_list) => {
244 bx.va_end(va_list.llval);
246 _ => bug!("C-variadic function must have a `VaList` place"),
249 if self.fn_abi.ret.layout.abi.is_uninhabited() {
250 // Functions with uninhabited return values are marked `noreturn`,
251 // so we should make sure that we never actually do.
252 // We play it safe by using a well-defined `abort`, but we could go for immediate UB
253 // if that turns out to be helpful.
255 // `abort` does not terminate the block, so we still need to generate
256 // an `unreachable` terminator after it.
260 let llval = match self.fn_abi.ret.mode {
261 PassMode::Ignore | PassMode::Indirect(..) => {
266 PassMode::Direct(_) | PassMode::Pair(..) => {
267 let op = self.codegen_consume(&mut bx, &mir::Place::return_place().as_ref());
268 if let Ref(llval, _, align) = op.val {
269 bx.load(llval, align)
271 op.immediate_or_packed_pair(&mut bx)
275 PassMode::Cast(cast_ty) => {
276 let op = match self.locals[mir::RETURN_PLACE] {
277 LocalRef::Operand(Some(op)) => op,
278 LocalRef::Operand(None) => bug!("use of return before def"),
279 LocalRef::Place(cg_place) => OperandRef {
280 val: Ref(cg_place.llval, None, cg_place.align),
281 layout: cg_place.layout,
283 LocalRef::UnsizedPlace(_) => bug!("return type must be sized"),
285 let llslot = match op.val {
286 Immediate(_) | Pair(..) => {
287 let scratch = PlaceRef::alloca(&mut bx, self.fn_abi.ret.layout);
288 op.val.store(&mut bx, scratch);
291 Ref(llval, _, align) => {
292 assert_eq!(align, op.layout.align.abi, "return place is unaligned!");
296 let addr = bx.pointercast(llslot, bx.type_ptr_to(bx.cast_backend_type(&cast_ty)));
297 bx.load(addr, self.fn_abi.ret.layout.align.abi)
303 fn codegen_drop_terminator(
305 helper: TerminatorCodegenHelper<'tcx>,
307 location: &mir::Place<'tcx>,
308 target: mir::BasicBlock,
309 unwind: Option<mir::BasicBlock>,
311 let ty = location.ty(*self.mir, bx.tcx()).ty;
312 let ty = self.monomorphize(&ty);
313 let drop_fn = Instance::resolve_drop_in_place(bx.tcx(), ty);
315 if let ty::InstanceDef::DropGlue(_, None) = drop_fn.def {
316 // we don't actually need to drop anything.
317 helper.maybe_sideeffect(self.mir, &mut bx, &[target]);
318 helper.funclet_br(self, &mut bx, target);
322 let place = self.codegen_place(&mut bx, &location.as_ref());
324 let mut args = if let Some(llextra) = place.llextra {
325 args2 = [place.llval, llextra];
328 args1 = [place.llval];
331 let (drop_fn, fn_abi) = match ty.kind {
332 // FIXME(eddyb) perhaps move some of this logic into
333 // `Instance::resolve_drop_in_place`?
335 let virtual_drop = Instance {
336 def: ty::InstanceDef::Virtual(drop_fn.def_id(), 0),
337 substs: drop_fn.substs,
339 let fn_abi = FnAbi::of_instance(&bx, virtual_drop, &[]);
340 let vtable = args[1];
342 (meth::DESTRUCTOR.get_fn(&mut bx, vtable, &fn_abi), fn_abi)
344 _ => (bx.get_fn_addr(drop_fn), FnAbi::of_instance(&bx, drop_fn, &[])),
346 helper.maybe_sideeffect(self.mir, &mut bx, &[target]);
353 Some((ReturnDest::Nothing, target)),
358 fn codegen_assert_terminator(
360 helper: TerminatorCodegenHelper<'tcx>,
362 terminator: &mir::Terminator<'tcx>,
363 cond: &mir::Operand<'tcx>,
365 msg: &mir::AssertMessage<'tcx>,
366 target: mir::BasicBlock,
367 cleanup: Option<mir::BasicBlock>,
369 let span = terminator.source_info.span;
370 let cond = self.codegen_operand(&mut bx, cond).immediate();
371 let mut const_cond = bx.const_to_opt_u128(cond, false).map(|c| c == 1);
373 // This case can currently arise only from functions marked
374 // with #[rustc_inherit_overflow_checks] and inlined from
375 // another crate (mostly core::num generic/#[inline] fns),
376 // while the current crate doesn't use overflow checks.
377 // NOTE: Unlike binops, negation doesn't have its own
378 // checked operation, just a comparison with the minimum
379 // value, so we have to check for the assert message.
380 if !bx.check_overflow() {
381 if let PanicInfo::OverflowNeg = *msg {
382 const_cond = Some(expected);
386 // Don't codegen the panic block if success if known.
387 if const_cond == Some(expected) {
388 helper.maybe_sideeffect(self.mir, &mut bx, &[target]);
389 helper.funclet_br(self, &mut bx, target);
393 // Pass the condition through llvm.expect for branch hinting.
394 let cond = bx.expect(cond, expected);
396 // Create the failure block and the conditional branch to it.
397 let lltarget = helper.llblock(self, target);
398 let panic_block = self.new_block("panic");
399 helper.maybe_sideeffect(self.mir, &mut bx, &[target]);
401 bx.cond_br(cond, lltarget, panic_block.llbb());
403 bx.cond_br(cond, panic_block.llbb(), lltarget);
406 // After this point, bx is the block for the call to panic.
408 self.set_debug_loc(&mut bx, terminator.source_info);
410 // Get the location information.
411 let location = self.get_caller_location(&mut bx, span).immediate();
413 // Put together the arguments to the panic entry point.
414 let (lang_item, args) = match msg {
415 PanicInfo::BoundsCheck { ref len, ref index } => {
416 let len = self.codegen_operand(&mut bx, len).immediate();
417 let index = self.codegen_operand(&mut bx, index).immediate();
418 (lang_items::PanicBoundsCheckFnLangItem, vec![location, index, len])
421 let msg_str = Symbol::intern(msg.description());
422 let msg = bx.const_str(msg_str);
423 (lang_items::PanicFnLangItem, vec![msg.0, msg.1, location])
427 // Obtain the panic entry point.
428 let def_id = common::langcall(bx.tcx(), Some(span), "", lang_item);
429 let instance = ty::Instance::mono(bx.tcx(), def_id);
430 let fn_abi = FnAbi::of_instance(&bx, instance, &[]);
431 let llfn = bx.get_fn_addr(instance);
433 // Codegen the actual panic invoke/call.
434 helper.do_call(self, &mut bx, fn_abi, llfn, &args, None, cleanup);
437 fn codegen_call_terminator(
439 helper: TerminatorCodegenHelper<'tcx>,
441 terminator: &mir::Terminator<'tcx>,
442 func: &mir::Operand<'tcx>,
443 args: &Vec<mir::Operand<'tcx>>,
444 destination: &Option<(mir::Place<'tcx>, mir::BasicBlock)>,
445 cleanup: Option<mir::BasicBlock>,
447 let span = terminator.source_info.span;
448 // Create the callee. This is a fn ptr or zero-sized and hence a kind of scalar.
449 let callee = self.codegen_operand(&mut bx, func);
451 let (instance, mut llfn) = match callee.layout.ty.kind {
452 ty::FnDef(def_id, substs) => (
454 ty::Instance::resolve(bx.tcx(), ty::ParamEnv::reveal_all(), def_id, substs)
459 ty::FnPtr(_) => (None, Some(callee.immediate())),
460 _ => bug!("{} is not callable", callee.layout.ty),
462 let def = instance.map(|i| i.def);
464 if let Some(ty::InstanceDef::DropGlue(_, None)) = def {
465 // Empty drop glue; a no-op.
466 let &(_, target) = destination.as_ref().unwrap();
467 helper.maybe_sideeffect(self.mir, &mut bx, &[target]);
468 helper.funclet_br(self, &mut bx, target);
472 // FIXME(eddyb) avoid computing this if possible, when `instance` is
473 // available - right now `sig` is only needed for getting the `abi`
474 // and figuring out how many extra args were passed to a C-variadic `fn`.
475 let sig = callee.layout.ty.fn_sig(bx.tcx());
478 // Handle intrinsics old codegen wants Expr's for, ourselves.
479 let intrinsic = match def {
480 Some(ty::InstanceDef::Intrinsic(def_id)) => Some(bx.tcx().item_name(def_id).as_str()),
483 let intrinsic = intrinsic.as_ref().map(|s| &s[..]);
485 let extra_args = &args[sig.inputs().skip_binder().len()..];
486 let extra_args = extra_args
489 let op_ty = op_arg.ty(*self.mir, bx.tcx());
490 self.monomorphize(&op_ty)
492 .collect::<Vec<_>>();
494 let fn_abi = match instance {
495 Some(instance) => FnAbi::of_instance(&bx, instance, &extra_args),
496 None => FnAbi::of_fn_ptr(&bx, sig, &extra_args),
499 if intrinsic == Some("transmute") {
500 if let Some(destination_ref) = destination.as_ref() {
501 let &(ref dest, target) = destination_ref;
502 self.codegen_transmute(&mut bx, &args[0], dest);
503 helper.maybe_sideeffect(self.mir, &mut bx, &[target]);
504 helper.funclet_br(self, &mut bx, target);
506 // If we are trying to transmute to an uninhabited type,
507 // it is likely there is no allotted destination. In fact,
508 // transmuting to an uninhabited type is UB, which means
509 // we can do what we like. Here, we declare that transmuting
510 // into an uninhabited type is impossible, so anything following
511 // it must be unreachable.
512 assert_eq!(fn_abi.ret.layout.abi, layout::Abi::Uninhabited);
518 // For normal codegen, this Miri-specific intrinsic is just a NOP.
519 if intrinsic == Some("miri_start_panic") {
520 let target = destination.as_ref().unwrap().1;
521 helper.maybe_sideeffect(self.mir, &mut bx, &[target]);
522 helper.funclet_br(self, &mut bx, target);
526 // Emit a panic or a no-op for `panic_if_uninhabited`.
527 if intrinsic == Some("panic_if_uninhabited") {
528 let ty = instance.unwrap().substs.type_at(0);
529 let layout = bx.layout_of(ty);
530 if layout.abi.is_uninhabited() {
531 let msg_str = format!("Attempted to instantiate uninhabited type {}", ty);
532 let msg = bx.const_str(Symbol::intern(&msg_str));
533 let location = self.get_caller_location(&mut bx, span).immediate();
535 // Obtain the panic entry point.
537 common::langcall(bx.tcx(), Some(span), "", lang_items::PanicFnLangItem);
538 let instance = ty::Instance::mono(bx.tcx(), def_id);
539 let fn_abi = FnAbi::of_instance(&bx, instance, &[]);
540 let llfn = bx.get_fn_addr(instance);
542 if let Some((_, target)) = destination.as_ref() {
543 helper.maybe_sideeffect(self.mir, &mut bx, &[*target]);
545 // Codegen the actual panic invoke/call.
551 &[msg.0, msg.1, location],
552 destination.as_ref().map(|(_, bb)| (ReturnDest::Nothing, *bb)),
557 let target = destination.as_ref().unwrap().1;
558 helper.maybe_sideeffect(self.mir, &mut bx, &[target]);
559 helper.funclet_br(self, &mut bx, target)
564 // The arguments we'll be passing. Plus one to account for outptr, if used.
565 let arg_count = fn_abi.args.len() + fn_abi.ret.is_indirect() as usize;
566 let mut llargs = Vec::with_capacity(arg_count);
568 // Prepare the return value destination
569 let ret_dest = if let Some((ref dest, _)) = *destination {
570 let is_intrinsic = intrinsic.is_some();
571 self.make_return_dest(&mut bx, dest, &fn_abi.ret, &mut llargs, is_intrinsic)
576 if intrinsic == Some("caller_location") {
577 if let Some((_, target)) = destination.as_ref() {
578 let location = self.get_caller_location(&mut bx, span);
580 if let ReturnDest::IndirectOperand(tmp, _) = ret_dest {
581 location.val.store(&mut bx, tmp);
583 self.store_return(&mut bx, ret_dest, &fn_abi.ret, location.immediate());
585 helper.maybe_sideeffect(self.mir, &mut bx, &[*target]);
586 helper.funclet_br(self, &mut bx, *target);
591 if intrinsic.is_some() && intrinsic != Some("drop_in_place") {
592 let dest = match ret_dest {
593 _ if fn_abi.ret.is_indirect() => llargs[0],
594 ReturnDest::Nothing => {
595 bx.const_undef(bx.type_ptr_to(bx.arg_memory_ty(&fn_abi.ret)))
597 ReturnDest::IndirectOperand(dst, _) | ReturnDest::Store(dst) => dst.llval,
598 ReturnDest::DirectOperand(_) => {
599 bug!("Cannot use direct operand with an intrinsic call")
603 let args: Vec<_> = args
607 // The indices passed to simd_shuffle* in the
608 // third argument must be constant. This is
609 // checked by const-qualification, which also
610 // promotes any complex rvalues to constants.
611 if i == 2 && intrinsic.unwrap().starts_with("simd_shuffle") {
612 if let mir::Operand::Constant(constant) = arg {
613 let c = self.eval_mir_constant(constant);
614 let (llval, ty) = self.simd_shuffle_indices(
620 return OperandRef { val: Immediate(llval), layout: bx.layout_of(ty) };
624 self.codegen_operand(&mut bx, arg)
628 bx.codegen_intrinsic_call(
629 *instance.as_ref().unwrap(),
633 terminator.source_info.span,
636 if let ReturnDest::IndirectOperand(dst, _) = ret_dest {
637 self.store_return(&mut bx, ret_dest, &fn_abi.ret, dst.llval);
640 if let Some((_, target)) = *destination {
641 helper.maybe_sideeffect(self.mir, &mut bx, &[target]);
642 helper.funclet_br(self, &mut bx, target);
650 // Split the rust-call tupled arguments off.
651 let (first_args, untuple) = if abi == Abi::RustCall && !args.is_empty() {
652 let (tup, args) = args.split_last().unwrap();
658 'make_args: for (i, arg) in first_args.iter().enumerate() {
659 let mut op = self.codegen_operand(&mut bx, arg);
661 if let (0, Some(ty::InstanceDef::Virtual(_, idx))) = (i, def) {
662 if let Pair(..) = op.val {
663 // In the case of Rc<Self>, we need to explicitly pass a
664 // *mut RcBox<Self> with a Scalar (not ScalarPair) ABI. This is a hack
665 // that is understood elsewhere in the compiler as a method on
667 // To get a `*mut RcBox<Self>`, we just keep unwrapping newtypes until
668 // we get a value of a built-in pointer type
669 'descend_newtypes: while !op.layout.ty.is_unsafe_ptr()
670 && !op.layout.ty.is_region_ptr()
672 for i in 0..op.layout.fields.count() {
673 let field = op.extract_field(&mut bx, i);
674 if !field.layout.is_zst() {
675 // we found the one non-zero-sized field that is allowed
676 // now find *its* non-zero-sized field, or stop if it's a
679 continue 'descend_newtypes;
683 span_bug!(span, "receiver has no non-zero-sized fields {:?}", op);
686 // now that we have `*dyn Trait` or `&dyn Trait`, split it up into its
687 // data pointer and vtable. Look up the method in the vtable, and pass
688 // the data pointer as the first argument
690 Pair(data_ptr, meta) => {
692 meth::VirtualIndex::from_index(idx).get_fn(&mut bx, meta, &fn_abi),
694 llargs.push(data_ptr);
697 other => bug!("expected a Pair, got {:?}", other),
699 } else if let Ref(data_ptr, Some(meta), _) = op.val {
700 // by-value dynamic dispatch
701 llfn = Some(meth::VirtualIndex::from_index(idx).get_fn(&mut bx, meta, &fn_abi));
702 llargs.push(data_ptr);
705 span_bug!(span, "can't codegen a virtual call on {:?}", op);
709 // The callee needs to own the argument memory if we pass it
710 // by-ref, so make a local copy of non-immediate constants.
711 match (arg, op.val) {
712 (&mir::Operand::Copy(_), Ref(_, None, _))
713 | (&mir::Operand::Constant(_), Ref(_, None, _)) => {
714 let tmp = PlaceRef::alloca(&mut bx, op.layout);
715 op.val.store(&mut bx, tmp);
716 op.val = Ref(tmp.llval, None, tmp.align);
721 self.codegen_argument(&mut bx, op, &mut llargs, &fn_abi.args[i]);
723 if let Some(tup) = untuple {
724 self.codegen_arguments_untupled(
728 &fn_abi.args[first_args.len()..],
733 instance.map_or(false, |i| i.def.requires_caller_location(self.cx.tcx()));
738 "#[track_caller] fn's must have 1 more argument in their ABI than in their MIR",
740 let location = self.get_caller_location(&mut bx, span);
741 let last_arg = fn_abi.args.last().unwrap();
742 self.codegen_argument(&mut bx, location, &mut llargs, last_arg);
745 let fn_ptr = match (llfn, instance) {
746 (Some(llfn), _) => llfn,
747 (None, Some(instance)) => bx.get_fn_addr(instance),
748 _ => span_bug!(span, "no llfn for call"),
751 if let Some((_, target)) = destination.as_ref() {
752 helper.maybe_sideeffect(self.mir, &mut bx, &[*target]);
760 destination.as_ref().map(|&(_, target)| (ret_dest, target)),
766 impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
767 pub fn codegen_block(&mut self, bb: mir::BasicBlock) {
768 let mut bx = self.build_block(bb);
772 debug!("codegen_block({:?}={:?})", bb, data);
774 for statement in &data.statements {
775 bx = self.codegen_statement(bx, statement);
778 self.codegen_terminator(bx, bb, data.terminator());
781 fn codegen_terminator(
785 terminator: &'tcx mir::Terminator<'tcx>,
787 debug!("codegen_terminator: {:?}", terminator);
789 // Create the cleanup bundle, if needed.
790 let funclet_bb = self.cleanup_kinds[bb].funclet_bb(bb);
791 let helper = TerminatorCodegenHelper { bb, terminator, funclet_bb };
793 self.set_debug_loc(&mut bx, terminator.source_info);
794 match terminator.kind {
795 mir::TerminatorKind::Resume => self.codegen_resume_terminator(helper, bx),
797 mir::TerminatorKind::Abort => {
799 // `abort` does not terminate the block, so we still need to generate
800 // an `unreachable` terminator after it.
804 mir::TerminatorKind::Goto { target } => {
805 helper.maybe_sideeffect(self.mir, &mut bx, &[target]);
806 helper.funclet_br(self, &mut bx, target);
809 mir::TerminatorKind::SwitchInt { ref discr, switch_ty, ref values, ref targets } => {
810 self.codegen_switchint_terminator(helper, bx, discr, switch_ty, values, targets);
813 mir::TerminatorKind::Return => {
814 self.codegen_return_terminator(bx);
817 mir::TerminatorKind::Unreachable => {
821 mir::TerminatorKind::Drop { ref location, target, unwind } => {
822 self.codegen_drop_terminator(helper, bx, location, target, unwind);
825 mir::TerminatorKind::Assert { ref cond, expected, ref msg, target, cleanup } => {
826 self.codegen_assert_terminator(
827 helper, bx, terminator, cond, expected, msg, target, cleanup,
831 mir::TerminatorKind::DropAndReplace { .. } => {
832 bug!("undesugared DropAndReplace in codegen: {:?}", terminator);
835 mir::TerminatorKind::Call {
842 self.codegen_call_terminator(
852 mir::TerminatorKind::GeneratorDrop | mir::TerminatorKind::Yield { .. } => {
853 bug!("generator ops in codegen")
855 mir::TerminatorKind::FalseEdges { .. } | mir::TerminatorKind::FalseUnwind { .. } => {
856 bug!("borrowck false edges in codegen")
864 op: OperandRef<'tcx, Bx::Value>,
865 llargs: &mut Vec<Bx::Value>,
866 arg: &ArgAbi<'tcx, Ty<'tcx>>,
868 // Fill padding with undef value, where applicable.
869 if let Some(ty) = arg.pad {
870 llargs.push(bx.const_undef(bx.reg_backend_type(&ty)))
877 if let PassMode::Pair(..) = arg.mode {
884 _ => bug!("codegen_argument: {:?} invalid for pair argument", op),
886 } else if arg.is_unsized_indirect() {
888 Ref(a, Some(b), _) => {
893 _ => bug!("codegen_argument: {:?} invalid for unsized indirect argument", op),
897 // Force by-ref if we have to load through a cast pointer.
898 let (mut llval, align, by_ref) = match op.val {
899 Immediate(_) | Pair(..) => match arg.mode {
900 PassMode::Indirect(..) | PassMode::Cast(_) => {
901 let scratch = PlaceRef::alloca(bx, arg.layout);
902 op.val.store(bx, scratch);
903 (scratch.llval, scratch.align, true)
905 _ => (op.immediate_or_packed_pair(bx), arg.layout.align.abi, false),
907 Ref(llval, _, align) => {
908 if arg.is_indirect() && align < arg.layout.align.abi {
909 // `foo(packed.large_field)`. We can't pass the (unaligned) field directly. I
910 // think that ATM (Rust 1.16) we only pass temporaries, but we shouldn't
911 // have scary latent bugs around.
913 let scratch = PlaceRef::alloca(bx, arg.layout);
923 (scratch.llval, scratch.align, true)
930 if by_ref && !arg.is_indirect() {
931 // Have to load the argument, maybe while casting it.
932 if let PassMode::Cast(ty) = arg.mode {
933 let addr = bx.pointercast(llval, bx.type_ptr_to(bx.cast_backend_type(&ty)));
934 llval = bx.load(addr, align.min(arg.layout.align.abi));
936 // We can't use `PlaceRef::load` here because the argument
937 // may have a type we don't treat as immediate, but the ABI
938 // used for this call is passing it by-value. In that case,
939 // the load would just produce `OperandValue::Ref` instead
940 // of the `OperandValue::Immediate` we need for the call.
941 llval = bx.load(llval, align);
942 if let layout::Abi::Scalar(ref scalar) = arg.layout.abi {
943 if scalar.is_bool() {
944 bx.range_metadata(llval, 0..2);
947 // We store bools as `i8` so we need to truncate to `i1`.
948 llval = base::to_immediate(bx, llval, arg.layout);
955 fn codegen_arguments_untupled(
958 operand: &mir::Operand<'tcx>,
959 llargs: &mut Vec<Bx::Value>,
960 args: &[ArgAbi<'tcx, Ty<'tcx>>],
962 let tuple = self.codegen_operand(bx, operand);
964 // Handle both by-ref and immediate tuples.
965 if let Ref(llval, None, align) = tuple.val {
966 let tuple_ptr = PlaceRef::new_sized_aligned(llval, tuple.layout, align);
967 for i in 0..tuple.layout.fields.count() {
968 let field_ptr = tuple_ptr.project_field(bx, i);
969 let field = bx.load_operand(field_ptr);
970 self.codegen_argument(bx, field, llargs, &args[i]);
972 } else if let Ref(_, Some(_), _) = tuple.val {
973 bug!("closure arguments must be sized")
975 // If the tuple is immediate, the elements are as well.
976 for i in 0..tuple.layout.fields.count() {
977 let op = tuple.extract_field(bx, i);
978 self.codegen_argument(bx, op, llargs, &args[i]);
983 fn get_caller_location(&mut self, bx: &mut Bx, span: Span) -> OperandRef<'tcx, Bx::Value> {
984 self.caller_location.unwrap_or_else(|| {
985 let topmost = span.ctxt().outer_expn().expansion_cause().unwrap_or(span);
986 let caller = bx.tcx().sess.source_map().lookup_char_pos(topmost.lo());
987 let const_loc = bx.tcx().const_caller_location((
988 Symbol::intern(&caller.file.name.to_string()),
990 caller.col_display as u32 + 1,
992 OperandRef::from_const(bx, const_loc)
996 fn get_personality_slot(&mut self, bx: &mut Bx) -> PlaceRef<'tcx, Bx::Value> {
998 if let Some(slot) = self.personality_slot {
1001 let layout = cx.layout_of(
1002 cx.tcx().intern_tup(&[cx.tcx().mk_mut_ptr(cx.tcx().types.u8), cx.tcx().types.i32]),
1004 let slot = PlaceRef::alloca(bx, layout);
1005 self.personality_slot = Some(slot);
1010 /// Returns the landing-pad wrapper around the given basic block.
1012 /// No-op in MSVC SEH scheme.
1013 fn landing_pad_to(&mut self, target_bb: mir::BasicBlock) -> Bx::BasicBlock {
1014 if let Some(block) = self.landing_pads[target_bb] {
1018 let block = self.blocks[target_bb];
1019 let landing_pad = self.landing_pad_uncached(block);
1020 self.landing_pads[target_bb] = Some(landing_pad);
1024 fn landing_pad_uncached(&mut self, target_bb: Bx::BasicBlock) -> Bx::BasicBlock {
1025 if base::wants_msvc_seh(self.cx.sess()) {
1026 span_bug!(self.mir.span, "landing pad was not inserted?")
1029 let mut bx = self.new_block("cleanup");
1031 let llpersonality = self.cx.eh_personality();
1032 let llretty = self.landing_pad_type();
1033 let lp = bx.landing_pad(llretty, llpersonality, 1);
1036 let slot = self.get_personality_slot(&mut bx);
1037 slot.storage_live(&mut bx);
1038 Pair(bx.extract_value(lp, 0), bx.extract_value(lp, 1)).store(&mut bx, slot);
1044 fn landing_pad_type(&self) -> Bx::Type {
1046 cx.type_struct(&[cx.type_i8p(), cx.type_i32()], false)
1049 fn unreachable_block(&mut self) -> Bx::BasicBlock {
1050 self.unreachable_block.unwrap_or_else(|| {
1051 let mut bx = self.new_block("unreachable");
1053 self.unreachable_block = Some(bx.llbb());
1058 pub fn new_block(&self, name: &str) -> Bx {
1059 Bx::new_block(self.cx, self.llfn, name)
1062 pub fn build_block(&self, bb: mir::BasicBlock) -> Bx {
1063 let mut bx = Bx::with_cx(self.cx);
1064 bx.position_at_end(self.blocks[bb]);
1068 fn make_return_dest(
1071 dest: &mir::Place<'tcx>,
1072 fn_ret: &ArgAbi<'tcx, Ty<'tcx>>,
1073 llargs: &mut Vec<Bx::Value>,
1075 ) -> ReturnDest<'tcx, Bx::Value> {
1076 // If the return is ignored, we can just return a do-nothing `ReturnDest`.
1077 if fn_ret.is_ignore() {
1078 return ReturnDest::Nothing;
1080 let dest = if let Some(index) = dest.as_local() {
1081 match self.locals[index] {
1082 LocalRef::Place(dest) => dest,
1083 LocalRef::UnsizedPlace(_) => bug!("return type must be sized"),
1084 LocalRef::Operand(None) => {
1085 // Handle temporary places, specifically `Operand` ones, as
1086 // they don't have `alloca`s.
1087 return if fn_ret.is_indirect() {
1088 // Odd, but possible, case, we have an operand temporary,
1089 // but the calling convention has an indirect return.
1090 let tmp = PlaceRef::alloca(bx, fn_ret.layout);
1091 tmp.storage_live(bx);
1092 llargs.push(tmp.llval);
1093 ReturnDest::IndirectOperand(tmp, index)
1094 } else if is_intrinsic {
1095 // Currently, intrinsics always need a location to store
1096 // the result, so we create a temporary `alloca` for the
1098 let tmp = PlaceRef::alloca(bx, fn_ret.layout);
1099 tmp.storage_live(bx);
1100 ReturnDest::IndirectOperand(tmp, index)
1102 ReturnDest::DirectOperand(index)
1105 LocalRef::Operand(Some(_)) => {
1106 bug!("place local already assigned to");
1112 &mir::PlaceRef { base: &dest.base, projection: &dest.projection },
1115 if fn_ret.is_indirect() {
1116 if dest.align < dest.layout.align.abi {
1117 // Currently, MIR code generation does not create calls
1118 // that store directly to fields of packed structs (in
1119 // fact, the calls it creates write only to temps).
1121 // If someone changes that, please update this code path
1122 // to create a temporary.
1123 span_bug!(self.mir.span, "can't directly store to unaligned value");
1125 llargs.push(dest.llval);
1128 ReturnDest::Store(dest)
1132 fn codegen_transmute(&mut self, bx: &mut Bx, src: &mir::Operand<'tcx>, dst: &mir::Place<'tcx>) {
1133 if let Some(index) = dst.as_local() {
1134 match self.locals[index] {
1135 LocalRef::Place(place) => self.codegen_transmute_into(bx, src, place),
1136 LocalRef::UnsizedPlace(_) => bug!("transmute must not involve unsized locals"),
1137 LocalRef::Operand(None) => {
1138 let dst_layout = bx.layout_of(self.monomorphized_place_ty(&dst.as_ref()));
1139 assert!(!dst_layout.ty.has_erasable_regions());
1140 let place = PlaceRef::alloca(bx, dst_layout);
1141 place.storage_live(bx);
1142 self.codegen_transmute_into(bx, src, place);
1143 let op = bx.load_operand(place);
1144 place.storage_dead(bx);
1145 self.locals[index] = LocalRef::Operand(Some(op));
1147 LocalRef::Operand(Some(op)) => {
1148 assert!(op.layout.is_zst(), "assigning to initialized SSAtemp");
1152 let dst = self.codegen_place(bx, &dst.as_ref());
1153 self.codegen_transmute_into(bx, src, dst);
1157 fn codegen_transmute_into(
1160 src: &mir::Operand<'tcx>,
1161 dst: PlaceRef<'tcx, Bx::Value>,
1163 let src = self.codegen_operand(bx, src);
1164 let llty = bx.backend_type(src.layout);
1165 let cast_ptr = bx.pointercast(dst.llval, bx.type_ptr_to(llty));
1166 let align = src.layout.align.abi.min(dst.align);
1167 src.val.store(bx, PlaceRef::new_sized_aligned(cast_ptr, src.layout, align));
1170 // Stores the return value of a function call into it's final location.
1174 dest: ReturnDest<'tcx, Bx::Value>,
1175 ret_abi: &ArgAbi<'tcx, Ty<'tcx>>,
1178 use self::ReturnDest::*;
1182 Store(dst) => bx.store_arg(&ret_abi, llval, dst),
1183 IndirectOperand(tmp, index) => {
1184 let op = bx.load_operand(tmp);
1185 tmp.storage_dead(bx);
1186 self.locals[index] = LocalRef::Operand(Some(op));
1188 DirectOperand(index) => {
1189 // If there is a cast, we have to store and reload.
1190 let op = if let PassMode::Cast(_) = ret_abi.mode {
1191 let tmp = PlaceRef::alloca(bx, ret_abi.layout);
1192 tmp.storage_live(bx);
1193 bx.store_arg(&ret_abi, llval, tmp);
1194 let op = bx.load_operand(tmp);
1195 tmp.storage_dead(bx);
1198 OperandRef::from_immediate_or_packed_pair(bx, llval, ret_abi.layout)
1200 self.locals[index] = LocalRef::Operand(Some(op));
1206 enum ReturnDest<'tcx, V> {
1207 // Do nothing; the return value is indirect or ignored.
1209 // Store the return value to the pointer.
1210 Store(PlaceRef<'tcx, V>),
1211 // Store an indirect return value to an operand local place.
1212 IndirectOperand(PlaceRef<'tcx, V>, mir::Local),
1213 // Store a direct return value to an operand local place.
1214 DirectOperand(mir::Local),