1 use rustc_index::vec::Idx;
2 use rustc::middle::lang_items;
3 use rustc::ty::{self, Ty, TypeFoldable, Instance};
4 use rustc::ty::layout::{self, LayoutOf, HasTyCtxt, FnTypeExt};
5 use rustc::mir::{self, Place, PlaceBase, Static, StaticKind};
6 use rustc::mir::interpret::PanicInfo;
7 use rustc_target::abi::call::{ArgType, FnType, PassMode};
8 use rustc_target::spec::abi::Abi;
11 use crate::common::{self, IntPredicate};
18 use syntax::symbol::Symbol;
21 use super::{FunctionCx, LocalRef};
22 use super::place::PlaceRef;
23 use super::operand::OperandRef;
24 use super::operand::OperandValue::{Pair, Ref, Immediate};
26 /// Used by `FunctionCx::codegen_terminator` for emitting common patterns
27 /// e.g., creating a basic block, calling a function, etc.
28 struct TerminatorCodegenHelper<'a, 'tcx> {
29 bb: &'a mir::BasicBlock,
30 terminator: &'a mir::Terminator<'tcx>,
31 funclet_bb: Option<mir::BasicBlock>,
34 impl<'a, 'tcx> TerminatorCodegenHelper<'a, 'tcx> {
35 /// Returns the associated funclet from `FunctionCx::funclets` for the
36 /// `funclet_bb` member if it is not `None`.
37 fn funclet<'c, 'b, Bx: BuilderMethods<'b, 'tcx>>(
39 fx: &'c mut FunctionCx<'b, 'tcx, Bx>,
40 ) -> Option<&'c Bx::Funclet> {
41 match self.funclet_bb {
42 Some(funcl) => fx.funclets[funcl].as_ref(),
47 fn lltarget<'b, 'c, Bx: BuilderMethods<'b, 'tcx>>(
49 fx: &'c mut FunctionCx<'b, 'tcx, Bx>,
50 target: mir::BasicBlock,
51 ) -> (Bx::BasicBlock, bool) {
52 let span = self.terminator.source_info.span;
53 let lltarget = fx.blocks[target];
54 let target_funclet = fx.cleanup_kinds[target].funclet_bb(target);
55 match (self.funclet_bb, target_funclet) {
56 (None, None) => (lltarget, false),
57 (Some(f), Some(t_f)) if f == t_f || !base::wants_msvc_seh(fx.cx.tcx().sess) =>
59 // jump *into* cleanup - need a landing pad if GNU
60 (None, Some(_)) => (fx.landing_pad_to(target), false),
61 (Some(_), None) => span_bug!(span, "{:?} - jump out of cleanup?", self.terminator),
62 (Some(_), Some(_)) => (fx.landing_pad_to(target), true),
66 /// Create a basic block.
67 fn llblock<'c, 'b, Bx: BuilderMethods<'b, 'tcx>>(
69 fx: &'c mut FunctionCx<'b, 'tcx, Bx>,
70 target: mir::BasicBlock,
72 let (lltarget, is_cleanupret) = self.lltarget(fx, target);
74 // MSVC cross-funclet jump - need a trampoline
76 debug!("llblock: creating cleanup trampoline for {:?}", target);
77 let name = &format!("{:?}_cleanup_trampoline_{:?}", self.bb, target);
78 let mut trampoline = fx.new_block(name);
79 trampoline.cleanup_ret(self.funclet(fx).unwrap(),
87 fn funclet_br<'c, 'b, Bx: BuilderMethods<'b, 'tcx>>(
89 fx: &'c mut FunctionCx<'b, 'tcx, Bx>,
91 target: mir::BasicBlock,
93 let (lltarget, is_cleanupret) = self.lltarget(fx, target);
95 // micro-optimization: generate a `ret` rather than a jump
97 bx.cleanup_ret(self.funclet(fx).unwrap(), Some(lltarget));
103 /// Call `fn_ptr` of `fn_ty` with the arguments `llargs`, the optional
104 /// return destination `destination` and the cleanup function `cleanup`.
105 fn do_call<'c, 'b, Bx: BuilderMethods<'b, 'tcx>>(
107 fx: &'c mut FunctionCx<'b, 'tcx, Bx>,
109 fn_ty: FnType<'tcx, Ty<'tcx>>,
111 llargs: &[Bx::Value],
112 destination: Option<(ReturnDest<'tcx, Bx::Value>, mir::BasicBlock)>,
113 cleanup: Option<mir::BasicBlock>,
115 if let Some(cleanup) = cleanup {
116 let ret_bx = if let Some((_, target)) = destination {
119 fx.unreachable_block()
121 let invokeret = bx.invoke(fn_ptr,
124 self.llblock(fx, cleanup),
126 bx.apply_attrs_callsite(&fn_ty, invokeret);
128 if let Some((ret_dest, target)) = destination {
129 let mut ret_bx = fx.build_block(target);
130 fx.set_debug_loc(&mut ret_bx, self.terminator.source_info);
131 fx.store_return(&mut ret_bx, ret_dest, &fn_ty.ret, invokeret);
134 let llret = bx.call(fn_ptr, &llargs, self.funclet(fx));
135 bx.apply_attrs_callsite(&fn_ty, llret);
136 if fx.mir[*self.bb].is_cleanup {
137 // Cleanup is always the cold path. Don't inline
138 // drop glue. Also, when there is a deeply-nested
139 // struct, there are "symmetry" issues that cause
140 // exponential inlining - see issue #41696.
141 bx.do_not_inline(llret);
144 if let Some((ret_dest, target)) = destination {
145 fx.store_return(bx, ret_dest, &fn_ty.ret, llret);
146 self.funclet_br(fx, bx, target);
154 /// Codegen implementations for some terminator variants.
155 impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
156 /// Generates code for a `Resume` terminator.
157 fn codegen_resume_terminator<'b>(
159 helper: TerminatorCodegenHelper<'b, 'tcx>,
162 if let Some(funclet) = helper.funclet(self) {
163 bx.cleanup_ret(funclet, None);
165 let slot = self.get_personality_slot(&mut bx);
166 let lp0 = slot.project_field(&mut bx, 0);
167 let lp0 = bx.load_operand(lp0).immediate();
168 let lp1 = slot.project_field(&mut bx, 1);
169 let lp1 = bx.load_operand(lp1).immediate();
170 slot.storage_dead(&mut bx);
172 if !bx.sess().target.target.options.custom_unwind_resume {
173 let mut lp = bx.const_undef(self.landing_pad_type());
174 lp = bx.insert_value(lp, lp0, 0);
175 lp = bx.insert_value(lp, lp1, 1);
178 bx.call(bx.eh_unwind_resume(), &[lp0],
179 helper.funclet(self));
185 fn codegen_switchint_terminator<'b>(
187 helper: TerminatorCodegenHelper<'b, 'tcx>,
189 discr: &mir::Operand<'tcx>,
191 values: &Cow<'tcx, [u128]>,
192 targets: &Vec<mir::BasicBlock>,
194 let discr = self.codegen_operand(&mut bx, &discr);
195 if targets.len() == 2 {
196 // If there are two targets, emit br instead of switch
197 let lltrue = helper.llblock(self, targets[0]);
198 let llfalse = helper.llblock(self, targets[1]);
199 if switch_ty == bx.tcx().types.bool {
200 // Don't generate trivial icmps when switching on bool
201 if let [0] = values[..] {
202 bx.cond_br(discr.immediate(), llfalse, lltrue);
204 assert_eq!(&values[..], &[1]);
205 bx.cond_br(discr.immediate(), lltrue, llfalse);
208 let switch_llty = bx.immediate_backend_type(
209 bx.layout_of(switch_ty)
211 let llval = bx.const_uint_big(switch_llty, values[0]);
212 let cmp = bx.icmp(IntPredicate::IntEQ, discr.immediate(), llval);
213 bx.cond_br(cmp, lltrue, llfalse);
216 let (otherwise, targets) = targets.split_last().unwrap();
219 helper.llblock(self, *otherwise),
220 values.iter().zip(targets).map(|(&value, target)| {
221 (value, helper.llblock(self, *target))
227 fn codegen_return_terminator(&mut self, mut bx: Bx) {
228 // Call `va_end` if this is the definition of a C-variadic function.
229 if self.fn_ty.c_variadic {
230 // The `VaList` "spoofed" argument is just after all the real arguments.
231 let va_list_arg_idx = self.fn_ty.args.len();
232 match self.locals[mir::Local::new(1 + va_list_arg_idx)] {
233 LocalRef::Place(va_list) => {
234 bx.va_end(va_list.llval);
236 _ => bug!("C-variadic function must have a `VaList` place"),
239 if self.fn_ty.ret.layout.abi.is_uninhabited() {
240 // Functions with uninhabited return values are marked `noreturn`,
241 // so we should make sure that we never actually do.
246 let llval = match self.fn_ty.ret.mode {
247 PassMode::Ignore | PassMode::Indirect(..) => {
252 PassMode::Direct(_) | PassMode::Pair(..) => {
254 self.codegen_consume(&mut bx, &mir::Place::return_place().as_ref());
255 if let Ref(llval, _, align) = op.val {
256 bx.load(llval, align)
258 op.immediate_or_packed_pair(&mut bx)
262 PassMode::Cast(cast_ty) => {
263 let op = match self.locals[mir::RETURN_PLACE] {
264 LocalRef::Operand(Some(op)) => op,
265 LocalRef::Operand(None) => bug!("use of return before def"),
266 LocalRef::Place(cg_place) => {
268 val: Ref(cg_place.llval, None, cg_place.align),
269 layout: cg_place.layout
272 LocalRef::UnsizedPlace(_) => bug!("return type must be sized"),
274 let llslot = match op.val {
275 Immediate(_) | Pair(..) => {
277 PlaceRef::alloca(&mut bx, self.fn_ty.ret.layout);
278 op.val.store(&mut bx, scratch);
281 Ref(llval, _, align) => {
282 assert_eq!(align, op.layout.align.abi,
283 "return place is unaligned!");
287 let addr = bx.pointercast(llslot, bx.type_ptr_to(
288 bx.cast_backend_type(&cast_ty)
290 bx.load(addr, self.fn_ty.ret.layout.align.abi)
297 fn codegen_drop_terminator<'b>(
299 helper: TerminatorCodegenHelper<'b, 'tcx>,
301 location: &mir::Place<'tcx>,
302 target: mir::BasicBlock,
303 unwind: Option<mir::BasicBlock>,
305 let ty = location.ty(self.mir, bx.tcx()).ty;
306 let ty = self.monomorphize(&ty);
307 let drop_fn = Instance::resolve_drop_in_place(bx.tcx(), ty);
309 if let ty::InstanceDef::DropGlue(_, None) = drop_fn.def {
310 // we don't actually need to drop anything.
311 helper.funclet_br(self, &mut bx, target);
315 let place = self.codegen_place(&mut bx, &location.as_ref());
317 let mut args = if let Some(llextra) = place.llextra {
318 args2 = [place.llval, llextra];
321 args1 = [place.llval];
324 let (drop_fn, fn_ty) = match ty.kind {
326 let sig = drop_fn.fn_sig(self.cx.tcx());
327 let sig = self.cx.tcx().normalize_erasing_late_bound_regions(
328 ty::ParamEnv::reveal_all(),
331 let fn_ty = FnType::new_vtable(&bx, sig, &[]);
332 let vtable = args[1];
334 (meth::DESTRUCTOR.get_fn(&mut bx, vtable, &fn_ty), fn_ty)
338 FnType::of_instance(&bx, drop_fn))
341 helper.do_call(self, &mut bx, fn_ty, drop_fn, args,
342 Some((ReturnDest::Nothing, target)),
346 fn codegen_assert_terminator<'b>(
348 helper: TerminatorCodegenHelper<'b, 'tcx>,
350 terminator: &mir::Terminator<'tcx>,
351 cond: &mir::Operand<'tcx>,
353 msg: &mir::AssertMessage<'tcx>,
354 target: mir::BasicBlock,
355 cleanup: Option<mir::BasicBlock>,
357 let span = terminator.source_info.span;
358 let cond = self.codegen_operand(&mut bx, cond).immediate();
359 let mut const_cond = bx.const_to_opt_u128(cond, false).map(|c| c == 1);
361 // This case can currently arise only from functions marked
362 // with #[rustc_inherit_overflow_checks] and inlined from
363 // another crate (mostly core::num generic/#[inline] fns),
364 // while the current crate doesn't use overflow checks.
365 // NOTE: Unlike binops, negation doesn't have its own
366 // checked operation, just a comparison with the minimum
367 // value, so we have to check for the assert message.
368 if !bx.check_overflow() {
369 if let PanicInfo::OverflowNeg = *msg {
370 const_cond = Some(expected);
374 // Don't codegen the panic block if success if known.
375 if const_cond == Some(expected) {
376 helper.funclet_br(self, &mut bx, target);
380 // Pass the condition through llvm.expect for branch hinting.
381 let cond = bx.expect(cond, expected);
383 // Create the failure block and the conditional branch to it.
384 let lltarget = helper.llblock(self, target);
385 let panic_block = self.new_block("panic");
387 bx.cond_br(cond, lltarget, panic_block.llbb());
389 bx.cond_br(cond, panic_block.llbb(), lltarget);
392 // After this point, bx is the block for the call to panic.
394 self.set_debug_loc(&mut bx, terminator.source_info);
396 // Get the location information.
397 let loc = bx.sess().source_map().lookup_char_pos(span.lo());
398 let filename = Symbol::intern(&loc.file.name.to_string());
399 let line = bx.const_u32(loc.line as u32);
400 let col = bx.const_u32(loc.col.to_usize() as u32 + 1);
402 // Put together the arguments to the panic entry point.
403 let (lang_item, args) = match msg {
404 PanicInfo::BoundsCheck { ref len, ref index } => {
405 let len = self.codegen_operand(&mut bx, len).immediate();
406 let index = self.codegen_operand(&mut bx, index).immediate();
408 let file_line_col = bx.static_panic_msg(
413 "panic_bounds_check_loc",
415 (lang_items::PanicBoundsCheckFnLangItem,
416 vec![file_line_col, index, len])
419 let msg_str = Symbol::intern(msg.description());
420 let msg_file_line_col = bx.static_panic_msg(
427 (lang_items::PanicFnLangItem,
428 vec![msg_file_line_col])
432 // Obtain the panic entry point.
433 let def_id = common::langcall(bx.tcx(), Some(span), "", lang_item);
434 let instance = ty::Instance::mono(bx.tcx(), def_id);
435 let fn_ty = FnType::of_instance(&bx, instance);
436 let llfn = bx.get_fn(instance);
438 // Codegen the actual panic invoke/call.
439 helper.do_call(self, &mut bx, fn_ty, llfn, &args, None, cleanup);
442 fn codegen_call_terminator<'b>(
444 helper: TerminatorCodegenHelper<'b, 'tcx>,
446 terminator: &mir::Terminator<'tcx>,
447 func: &mir::Operand<'tcx>,
448 args: &Vec<mir::Operand<'tcx>>,
449 destination: &Option<(mir::Place<'tcx>, mir::BasicBlock)>,
450 cleanup: Option<mir::BasicBlock>,
452 let span = terminator.source_info.span;
453 // Create the callee. This is a fn ptr or zero-sized and hence a kind of scalar.
454 let callee = self.codegen_operand(&mut bx, func);
456 let (instance, mut llfn) = match callee.layout.ty.kind {
457 ty::FnDef(def_id, substs) => {
458 (Some(ty::Instance::resolve(bx.tcx(),
459 ty::ParamEnv::reveal_all(),
465 (None, Some(callee.immediate()))
467 _ => bug!("{} is not callable", callee.layout.ty),
469 let def = instance.map(|i| i.def);
470 let sig = callee.layout.ty.fn_sig(bx.tcx());
471 let sig = bx.tcx().normalize_erasing_late_bound_regions(
472 ty::ParamEnv::reveal_all(),
477 // Handle intrinsics old codegen wants Expr's for, ourselves.
478 let intrinsic = match def {
479 Some(ty::InstanceDef::Intrinsic(def_id)) =>
480 Some(bx.tcx().item_name(def_id).as_str()),
483 let intrinsic = intrinsic.as_ref().map(|s| &s[..]);
485 if intrinsic == Some("transmute") {
486 if let Some(destination_ref) = destination.as_ref() {
487 let &(ref dest, target) = destination_ref;
488 self.codegen_transmute(&mut bx, &args[0], dest);
489 helper.funclet_br(self, &mut bx, target);
491 // If we are trying to transmute to an uninhabited type,
492 // it is likely there is no allotted destination. In fact,
493 // transmuting to an uninhabited type is UB, which means
494 // we can do what we like. Here, we declare that transmuting
495 // into an uninhabited type is impossible, so anything following
496 // it must be unreachable.
497 assert_eq!(bx.layout_of(sig.output()).abi, layout::Abi::Uninhabited);
503 let extra_args = &args[sig.inputs().len()..];
504 let extra_args = extra_args.iter().map(|op_arg| {
505 let op_ty = op_arg.ty(self.mir, bx.tcx());
506 self.monomorphize(&op_ty)
507 }).collect::<Vec<_>>();
509 let fn_ty = match def {
510 Some(ty::InstanceDef::Virtual(..)) => {
511 FnType::new_vtable(&bx, sig, &extra_args)
513 Some(ty::InstanceDef::DropGlue(_, None)) => {
514 // Empty drop glue; a no-op.
515 let &(_, target) = destination.as_ref().unwrap();
516 helper.funclet_br(self, &mut bx, target);
519 _ => FnType::new(&bx, sig, &extra_args)
522 // Emit a panic or a no-op for `panic_if_uninhabited`.
523 if intrinsic == Some("panic_if_uninhabited") {
524 let ty = instance.unwrap().substs.type_at(0);
525 let layout = bx.layout_of(ty);
526 if layout.abi.is_uninhabited() {
527 let loc = bx.sess().source_map().lookup_char_pos(span.lo());
528 let filename = Symbol::intern(&loc.file.name.to_string());
529 let line = bx.const_u32(loc.line as u32);
530 let col = bx.const_u32(loc.col.to_usize() as u32 + 1);
533 "Attempted to instantiate uninhabited type {}",
536 let msg_str = Symbol::intern(&str);
537 let msg_file_line_col = bx.static_panic_msg(
545 // Obtain the panic entry point.
547 common::langcall(bx.tcx(), Some(span), "", lang_items::PanicFnLangItem);
548 let instance = ty::Instance::mono(bx.tcx(), def_id);
549 let fn_ty = FnType::of_instance(&bx, instance);
550 let llfn = bx.get_fn(instance);
552 // Codegen the actual panic invoke/call.
558 &[msg_file_line_col],
559 destination.as_ref().map(|(_, bb)| (ReturnDest::Nothing, *bb)),
564 helper.funclet_br(self, &mut bx, destination.as_ref().unwrap().1)
569 // The arguments we'll be passing. Plus one to account for outptr, if used.
570 let arg_count = fn_ty.args.len() + fn_ty.ret.is_indirect() as usize;
571 let mut llargs = Vec::with_capacity(arg_count);
573 // Prepare the return value destination
574 let ret_dest = if let Some((ref dest, _)) = *destination {
575 let is_intrinsic = intrinsic.is_some();
576 self.make_return_dest(&mut bx, dest, &fn_ty.ret, &mut llargs,
582 if intrinsic.is_some() && intrinsic != Some("drop_in_place") {
583 let dest = match ret_dest {
584 _ if fn_ty.ret.is_indirect() => llargs[0],
585 ReturnDest::Nothing =>
586 bx.const_undef(bx.type_ptr_to(bx.memory_ty(&fn_ty.ret))),
587 ReturnDest::IndirectOperand(dst, _) | ReturnDest::Store(dst) =>
589 ReturnDest::DirectOperand(_) =>
590 bug!("Cannot use direct operand with an intrinsic call"),
593 let args: Vec<_> = args.iter().enumerate().map(|(i, arg)| {
594 // The indices passed to simd_shuffle* in the
595 // third argument must be constant. This is
596 // checked by const-qualification, which also
597 // promotes any complex rvalues to constants.
598 if i == 2 && intrinsic.unwrap().starts_with("simd_shuffle") {
600 // The shuffle array argument is usually not an explicit constant,
601 // but specified directly in the code. This means it gets promoted
602 // and we can then extract the value by evaluating the promoted.
605 base: PlaceBase::Static(box Static {
606 kind: StaticKind::Promoted(promoted, _),
615 base: PlaceBase::Static(box Static {
616 kind: StaticKind::Promoted(promoted, _),
623 let param_env = ty::ParamEnv::reveal_all();
624 let cid = mir::interpret::GlobalId {
625 instance: self.instance,
626 promoted: Some(promoted),
628 let c = bx.tcx().const_eval(param_env.and(cid));
629 let (llval, ty) = self.simd_shuffle_indices(
631 terminator.source_info.span,
636 val: Immediate(llval),
637 layout: bx.layout_of(ty),
641 mir::Operand::Copy(_) |
642 mir::Operand::Move(_) => {
643 span_bug!(span, "shuffle indices must be constant");
645 mir::Operand::Constant(ref constant) => {
646 let c = self.eval_mir_constant(constant);
647 let (llval, ty) = self.simd_shuffle_indices(
654 val: Immediate(llval),
655 layout: bx.layout_of(ty)
661 self.codegen_operand(&mut bx, arg)
665 bx.codegen_intrinsic_call(*instance.as_ref().unwrap(), &fn_ty, &args, dest,
666 terminator.source_info.span);
668 if let ReturnDest::IndirectOperand(dst, _) = ret_dest {
669 self.store_return(&mut bx, ret_dest, &fn_ty.ret, dst.llval);
672 if let Some((_, target)) = *destination {
673 helper.funclet_br(self, &mut bx, target);
681 // Split the rust-call tupled arguments off.
682 let (first_args, untuple) = if abi == Abi::RustCall && !args.is_empty() {
683 let (tup, args) = args.split_last().unwrap();
689 'make_args: for (i, arg) in first_args.iter().enumerate() {
690 let mut op = self.codegen_operand(&mut bx, arg);
692 if let (0, Some(ty::InstanceDef::Virtual(_, idx))) = (i, def) {
693 if let Pair(..) = op.val {
694 // In the case of Rc<Self>, we need to explicitly pass a
695 // *mut RcBox<Self> with a Scalar (not ScalarPair) ABI. This is a hack
696 // that is understood elsewhere in the compiler as a method on
698 // To get a `*mut RcBox<Self>`, we just keep unwrapping newtypes until
699 // we get a value of a built-in pointer type
700 'descend_newtypes: while !op.layout.ty.is_unsafe_ptr()
701 && !op.layout.ty.is_region_ptr()
703 'iter_fields: for i in 0..op.layout.fields.count() {
704 let field = op.extract_field(&mut bx, i);
705 if !field.layout.is_zst() {
706 // we found the one non-zero-sized field that is allowed
707 // now find *its* non-zero-sized field, or stop if it's a
710 continue 'descend_newtypes
714 span_bug!(span, "receiver has no non-zero-sized fields {:?}", op);
717 // now that we have `*dyn Trait` or `&dyn Trait`, split it up into its
718 // data pointer and vtable. Look up the method in the vtable, and pass
719 // the data pointer as the first argument
721 Pair(data_ptr, meta) => {
722 llfn = Some(meth::VirtualIndex::from_index(idx)
723 .get_fn(&mut bx, meta, &fn_ty));
724 llargs.push(data_ptr);
727 other => bug!("expected a Pair, got {:?}", other),
729 } else if let Ref(data_ptr, Some(meta), _) = op.val {
730 // by-value dynamic dispatch
731 llfn = Some(meth::VirtualIndex::from_index(idx)
732 .get_fn(&mut bx, meta, &fn_ty));
733 llargs.push(data_ptr);
736 span_bug!(span, "can't codegen a virtual call on {:?}", op);
740 // The callee needs to own the argument memory if we pass it
741 // by-ref, so make a local copy of non-immediate constants.
742 match (arg, op.val) {
743 (&mir::Operand::Copy(_), Ref(_, None, _)) |
744 (&mir::Operand::Constant(_), Ref(_, None, _)) => {
745 let tmp = PlaceRef::alloca(&mut bx, op.layout);
746 op.val.store(&mut bx, tmp);
747 op.val = Ref(tmp.llval, None, tmp.align);
752 self.codegen_argument(&mut bx, op, &mut llargs, &fn_ty.args[i]);
754 if let Some(tup) = untuple {
755 self.codegen_arguments_untupled(&mut bx, tup, &mut llargs,
756 &fn_ty.args[first_args.len()..])
759 let fn_ptr = match (llfn, instance) {
760 (Some(llfn), _) => llfn,
761 (None, Some(instance)) => bx.get_fn(instance),
762 _ => span_bug!(span, "no llfn for call"),
765 helper.do_call(self, &mut bx, fn_ty, fn_ptr, &llargs,
766 destination.as_ref().map(|&(_, target)| (ret_dest, target)),
771 impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
772 pub fn codegen_block(
776 let mut bx = self.build_block(bb);
777 let data = &self.mir[bb];
779 debug!("codegen_block({:?}={:?})", bb, data);
781 for statement in &data.statements {
782 bx = self.codegen_statement(bx, statement);
785 self.codegen_terminator(bx, bb, data.terminator());
788 fn codegen_terminator(
792 terminator: &mir::Terminator<'tcx>
794 debug!("codegen_terminator: {:?}", terminator);
796 // Create the cleanup bundle, if needed.
797 let funclet_bb = self.cleanup_kinds[bb].funclet_bb(bb);
798 let helper = TerminatorCodegenHelper {
799 bb: &bb, terminator, funclet_bb
802 self.set_debug_loc(&mut bx, terminator.source_info);
803 match terminator.kind {
804 mir::TerminatorKind::Resume => {
805 self.codegen_resume_terminator(helper, bx)
808 mir::TerminatorKind::Abort => {
813 mir::TerminatorKind::Goto { target } => {
814 helper.funclet_br(self, &mut bx, target);
817 mir::TerminatorKind::SwitchInt {
818 ref discr, switch_ty, ref values, ref targets
820 self.codegen_switchint_terminator(helper, bx, discr, switch_ty,
824 mir::TerminatorKind::Return => {
825 self.codegen_return_terminator(bx);
828 mir::TerminatorKind::Unreachable => {
832 mir::TerminatorKind::Drop { ref location, target, unwind } => {
833 self.codegen_drop_terminator(helper, bx, location, target, unwind);
836 mir::TerminatorKind::Assert { ref cond, expected, ref msg, target, cleanup } => {
837 self.codegen_assert_terminator(helper, bx, terminator, cond,
838 expected, msg, target, cleanup);
841 mir::TerminatorKind::DropAndReplace { .. } => {
842 bug!("undesugared DropAndReplace in codegen: {:?}", terminator);
845 mir::TerminatorKind::Call {
852 self.codegen_call_terminator(helper, bx, terminator, func,
853 args, destination, cleanup);
855 mir::TerminatorKind::GeneratorDrop |
856 mir::TerminatorKind::Yield { .. } => bug!("generator ops in codegen"),
857 mir::TerminatorKind::FalseEdges { .. } |
858 mir::TerminatorKind::FalseUnwind { .. } => bug!("borrowck false edges in codegen"),
865 op: OperandRef<'tcx, Bx::Value>,
866 llargs: &mut Vec<Bx::Value>,
867 arg: &ArgType<'tcx, Ty<'tcx>>
869 // Fill padding with undef value, where applicable.
870 if let Some(ty) = arg.pad {
871 llargs.push(bx.const_undef(bx.reg_backend_type(&ty)))
878 if let PassMode::Pair(..) = arg.mode {
885 _ => bug!("codegen_argument: {:?} invalid for pair argument", op)
887 } else if arg.is_unsized_indirect() {
889 Ref(a, Some(b), _) => {
894 _ => bug!("codegen_argument: {:?} invalid for unsized indirect argument", op)
898 // Force by-ref if we have to load through a cast pointer.
899 let (mut llval, align, by_ref) = match op.val {
900 Immediate(_) | Pair(..) => {
902 PassMode::Indirect(..) | PassMode::Cast(_) => {
903 let scratch = PlaceRef::alloca(bx, arg.layout);
904 op.val.store(bx, scratch);
905 (scratch.llval, scratch.align, true)
908 (op.immediate_or_packed_pair(bx), arg.layout.align.abi, false)
912 Ref(llval, _, align) => {
913 if arg.is_indirect() && align < arg.layout.align.abi {
914 // `foo(packed.large_field)`. We can't pass the (unaligned) field directly. I
915 // think that ATM (Rust 1.16) we only pass temporaries, but we shouldn't
916 // have scary latent bugs around.
918 let scratch = PlaceRef::alloca(bx, arg.layout);
919 base::memcpy_ty(bx, scratch.llval, scratch.align, llval, align,
920 op.layout, MemFlags::empty());
921 (scratch.llval, scratch.align, true)
928 if by_ref && !arg.is_indirect() {
929 // Have to load the argument, maybe while casting it.
930 if let PassMode::Cast(ty) = arg.mode {
931 let addr = bx.pointercast(llval, bx.type_ptr_to(
932 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: &[ArgType<'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_personality_slot(
986 ) -> PlaceRef<'tcx, Bx::Value> {
988 if let Some(slot) = self.personality_slot {
991 let layout = cx.layout_of(cx.tcx().intern_tup(&[
992 cx.tcx().mk_mut_ptr(cx.tcx().types.u8),
995 let slot = PlaceRef::alloca(bx, layout);
996 self.personality_slot = Some(slot);
1001 /// Returns the landing-pad wrapper around the given basic block.
1003 /// No-op in MSVC SEH scheme.
1006 target_bb: mir::BasicBlock
1007 ) -> Bx::BasicBlock {
1008 if let Some(block) = self.landing_pads[target_bb] {
1012 let block = self.blocks[target_bb];
1013 let landing_pad = self.landing_pad_uncached(block);
1014 self.landing_pads[target_bb] = Some(landing_pad);
1018 fn landing_pad_uncached(
1020 target_bb: Bx::BasicBlock
1021 ) -> Bx::BasicBlock {
1022 if base::wants_msvc_seh(self.cx.sess()) {
1023 span_bug!(self.mir.span, "landing pad was not inserted?")
1026 let mut bx = self.new_block("cleanup");
1028 let llpersonality = self.cx.eh_personality();
1029 let llretty = self.landing_pad_type();
1030 let lp = bx.landing_pad(llretty, llpersonality, 1);
1033 let slot = self.get_personality_slot(&mut bx);
1034 slot.storage_live(&mut bx);
1035 Pair(bx.extract_value(lp, 0), bx.extract_value(lp, 1)).store(&mut bx, slot);
1041 fn landing_pad_type(&self) -> Bx::Type {
1043 cx.type_struct(&[cx.type_i8p(), cx.type_i32()], false)
1046 fn unreachable_block(
1048 ) -> Bx::BasicBlock {
1049 self.unreachable_block.unwrap_or_else(|| {
1050 let mut bx = self.new_block("unreachable");
1052 self.unreachable_block = Some(bx.llbb());
1057 pub fn new_block(&self, name: &str) -> Bx {
1058 Bx::new_block(self.cx, self.llfn, name)
1065 let mut bx = Bx::with_cx(self.cx);
1066 bx.position_at_end(self.blocks[bb]);
1070 fn make_return_dest(
1073 dest: &mir::Place<'tcx>,
1074 fn_ret: &ArgType<'tcx, Ty<'tcx>>,
1075 llargs: &mut Vec<Bx::Value>, is_intrinsic: bool
1076 ) -> ReturnDest<'tcx, Bx::Value> {
1077 // If the return is ignored, we can just return a do-nothing `ReturnDest`.
1078 if fn_ret.is_ignore() {
1079 return ReturnDest::Nothing;
1081 let dest = if let mir::Place {
1082 base: mir::PlaceBase::Local(index),
1085 match self.locals[index] {
1086 LocalRef::Place(dest) => dest,
1087 LocalRef::UnsizedPlace(_) => bug!("return type must be sized"),
1088 LocalRef::Operand(None) => {
1089 // Handle temporary places, specifically `Operand` ones, as
1090 // they don't have `alloca`s.
1091 return if fn_ret.is_indirect() {
1092 // Odd, but possible, case, we have an operand temporary,
1093 // but the calling convention has an indirect return.
1094 let tmp = PlaceRef::alloca(bx, fn_ret.layout);
1095 tmp.storage_live(bx);
1096 llargs.push(tmp.llval);
1097 ReturnDest::IndirectOperand(tmp, index)
1098 } else if is_intrinsic {
1099 // Currently, intrinsics always need a location to store
1100 // the result, so we create a temporary `alloca` for the
1102 let tmp = PlaceRef::alloca(bx, fn_ret.layout);
1103 tmp.storage_live(bx);
1104 ReturnDest::IndirectOperand(tmp, index)
1106 ReturnDest::DirectOperand(index)
1109 LocalRef::Operand(Some(_)) => {
1110 bug!("place local already assigned to");
1114 self.codegen_place(bx, &mir::PlaceRef {
1116 projection: &dest.projection,
1119 if fn_ret.is_indirect() {
1120 if dest.align < dest.layout.align.abi {
1121 // Currently, MIR code generation does not create calls
1122 // that store directly to fields of packed structs (in
1123 // fact, the calls it creates write only to temps).
1125 // If someone changes that, please update this code path
1126 // to create a temporary.
1127 span_bug!(self.mir.span, "can't directly store to unaligned value");
1129 llargs.push(dest.llval);
1132 ReturnDest::Store(dest)
1136 fn codegen_transmute(
1139 src: &mir::Operand<'tcx>,
1140 dst: &mir::Place<'tcx>
1143 base: mir::PlaceBase::Local(index),
1146 match self.locals[index] {
1147 LocalRef::Place(place) => self.codegen_transmute_into(bx, src, place),
1148 LocalRef::UnsizedPlace(_) => bug!("transmute must not involve unsized locals"),
1149 LocalRef::Operand(None) => {
1150 let dst_layout = bx.layout_of(self.monomorphized_place_ty(&dst.as_ref()));
1151 assert!(!dst_layout.ty.has_erasable_regions());
1152 let place = PlaceRef::alloca(bx, dst_layout);
1153 place.storage_live(bx);
1154 self.codegen_transmute_into(bx, src, place);
1155 let op = bx.load_operand(place);
1156 place.storage_dead(bx);
1157 self.locals[index] = LocalRef::Operand(Some(op));
1159 LocalRef::Operand(Some(op)) => {
1160 assert!(op.layout.is_zst(),
1161 "assigning to initialized SSAtemp");
1165 let dst = self.codegen_place(bx, &dst.as_ref());
1166 self.codegen_transmute_into(bx, src, dst);
1170 fn codegen_transmute_into(
1173 src: &mir::Operand<'tcx>,
1174 dst: PlaceRef<'tcx, Bx::Value>
1176 let src = self.codegen_operand(bx, src);
1177 let llty = bx.backend_type(src.layout);
1178 let cast_ptr = bx.pointercast(dst.llval, bx.type_ptr_to(llty));
1179 let align = src.layout.align.abi.min(dst.align);
1180 src.val.store(bx, PlaceRef::new_sized_aligned(cast_ptr, src.layout, align));
1184 // Stores the return value of a function call into it's final location.
1188 dest: ReturnDest<'tcx, Bx::Value>,
1189 ret_ty: &ArgType<'tcx, Ty<'tcx>>,
1192 use self::ReturnDest::*;
1196 Store(dst) => bx.store_arg_ty(&ret_ty, llval, dst),
1197 IndirectOperand(tmp, index) => {
1198 let op = bx.load_operand(tmp);
1199 tmp.storage_dead(bx);
1200 self.locals[index] = LocalRef::Operand(Some(op));
1202 DirectOperand(index) => {
1203 // If there is a cast, we have to store and reload.
1204 let op = if let PassMode::Cast(_) = ret_ty.mode {
1205 let tmp = PlaceRef::alloca(bx, ret_ty.layout);
1206 tmp.storage_live(bx);
1207 bx.store_arg_ty(&ret_ty, llval, tmp);
1208 let op = bx.load_operand(tmp);
1209 tmp.storage_dead(bx);
1212 OperandRef::from_immediate_or_packed_pair(bx, llval, ret_ty.layout)
1214 self.locals[index] = LocalRef::Operand(Some(op));
1220 enum ReturnDest<'tcx, V> {
1221 // Do nothing; the return value is indirect or ignored.
1223 // Store the return value to the pointer.
1224 Store(PlaceRef<'tcx, V>),
1225 // Store an indirect return value to an operand local place.
1226 IndirectOperand(PlaceRef<'tcx, V>, mir::Local),
1227 // Store a direct return value to an operand local place.
1228 DirectOperand(mir::Local)