1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 use rustc::middle::lang_items;
12 use rustc::ty::{self, Ty, TypeFoldable};
13 use rustc::ty::layout::{self, LayoutOf, HasTyCtxt};
15 use rustc::mir::interpret::EvalErrorKind;
16 use rustc_target::abi::call::{ArgType, FnType, PassMode};
17 use rustc_target::spec::abi::Abi;
20 use common::{self, IntPredicate};
22 use rustc_mir::monomorphize;
26 use syntax::symbol::Symbol;
29 use super::{FunctionCx, LocalRef};
30 use super::place::PlaceRef;
31 use super::operand::OperandRef;
32 use super::operand::OperandValue::{Pair, Ref, Immediate};
34 impl<'a, 'tcx: 'a, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
39 let mut bx = self.build_block(bb);
40 let data = &self.mir[bb];
42 debug!("codegen_block({:?}={:?})", bb, data);
44 for statement in &data.statements {
45 bx = self.codegen_statement(bx, statement);
48 self.codegen_terminator(bx, bb, data.terminator());
51 fn codegen_terminator(
55 terminator: &mir::Terminator<'tcx>
57 debug!("codegen_terminator: {:?}", terminator);
59 // Create the cleanup bundle, if needed.
60 let tcx = self.cx.tcx();
61 let span = terminator.source_info.span;
62 let funclet_bb = self.cleanup_kinds[bb].funclet_bb(bb);
64 // HACK(eddyb) force the right lifetimes, NLL can't figure them out.
65 fn funclet_closure_factory<'a, 'tcx: 'a, Bx: BuilderMethods<'a, 'tcx>>(
66 funclet_bb: Option<mir::BasicBlock>
68 &'b FunctionCx<'a, 'tcx, Bx>,
69 ) -> Option<&'b Bx::Funclet> {
72 Some(funclet_bb) => this.funclets[funclet_bb].as_ref(),
77 let funclet = funclet_closure_factory(funclet_bb);
79 let lltarget = |this: &mut Self, target: mir::BasicBlock| {
80 let lltarget = this.blocks[target];
81 let target_funclet = this.cleanup_kinds[target].funclet_bb(target);
82 match (funclet_bb, target_funclet) {
83 (None, None) => (lltarget, false),
85 if f == t_f || !base::wants_msvc_seh(tcx.sess)
88 // jump *into* cleanup - need a landing pad if GNU
89 (this.landing_pad_to(target), false)
91 (Some(_), None) => span_bug!(span, "{:?} - jump out of cleanup?", terminator),
92 (Some(_), Some(_)) => {
93 (this.landing_pad_to(target), true)
98 let llblock = |this: &mut Self, target: mir::BasicBlock| {
99 let (lltarget, is_cleanupret) = lltarget(this, target);
101 // MSVC cross-funclet jump - need a trampoline
103 debug!("llblock: creating cleanup trampoline for {:?}", target);
104 let name = &format!("{:?}_cleanup_trampoline_{:?}", bb, target);
105 let trampoline = this.new_block(name);
106 trampoline.cleanup_ret(funclet(this).unwrap(), Some(lltarget));
114 |this: &mut Self, bx: &mut Bx, target: mir::BasicBlock| {
115 let (lltarget, is_cleanupret) = lltarget(this, target);
117 // micro-optimization: generate a `ret` rather than a jump
119 bx.cleanup_ret(funclet(this).unwrap(), Some(lltarget));
128 fn_ty: FnType<'tcx, Ty<'tcx>>,
130 llargs: &[Bx::Value],
131 destination: Option<(ReturnDest<'tcx, Bx::Value>, mir::BasicBlock)>,
132 cleanup: Option<mir::BasicBlock>
134 if let Some(cleanup) = cleanup {
135 let ret_bx = if let Some((_, target)) = destination {
138 this.unreachable_block()
140 let invokeret = bx.invoke(fn_ptr,
143 llblock(this, cleanup),
145 bx.apply_attrs_callsite(&fn_ty, invokeret);
147 if let Some((ret_dest, target)) = destination {
148 let ret_bx = this.build_block(target);
149 this.set_debug_loc(&ret_bx, terminator.source_info);
150 this.store_return(&ret_bx, ret_dest, &fn_ty.ret, invokeret);
153 let llret = bx.call(fn_ptr, &llargs, funclet(this));
154 bx.apply_attrs_callsite(&fn_ty, llret);
155 if this.mir[bb].is_cleanup {
156 // Cleanup is always the cold path. Don't inline
157 // drop glue. Also, when there is a deeply-nested
158 // struct, there are "symmetry" issues that cause
159 // exponential inlining - see issue #41696.
160 bx.do_not_inline(llret);
163 if let Some((ret_dest, target)) = destination {
164 this.store_return(bx, ret_dest, &fn_ty.ret, llret);
165 funclet_br(this, bx, target);
172 self.set_debug_loc(&bx, terminator.source_info);
173 match terminator.kind {
174 mir::TerminatorKind::Resume => {
175 if let Some(funclet) = funclet(self) {
176 bx.cleanup_ret(funclet, None);
178 let slot = self.get_personality_slot(&bx);
179 let lp0 = bx.load_operand(slot.project_field(&bx, 0)).immediate();
180 let lp1 = bx.load_operand(slot.project_field(&bx, 1)).immediate();
181 slot.storage_dead(&bx);
183 if !bx.cx().sess().target.target.options.custom_unwind_resume {
184 let mut lp = bx.cx().const_undef(self.landing_pad_type());
185 lp = bx.insert_value(lp, lp0, 0);
186 lp = bx.insert_value(lp, lp1, 1);
189 bx.call(bx.cx().eh_unwind_resume(), &[lp0], funclet(self));
195 mir::TerminatorKind::Abort => {
196 // Call core::intrinsics::abort()
197 let fnname = bx.cx().get_intrinsic(&("llvm.trap"));
198 bx.call(fnname, &[], None);
202 mir::TerminatorKind::Goto { target } => {
203 funclet_br(self, &mut bx, target);
206 mir::TerminatorKind::SwitchInt { ref discr, switch_ty, ref values, ref targets } => {
207 let discr = self.codegen_operand(&bx, discr);
208 if targets.len() == 2 {
209 // If there are two targets, emit br instead of switch
210 let lltrue = llblock(self, targets[0]);
211 let llfalse = llblock(self, targets[1]);
212 if switch_ty == bx.tcx().types.bool {
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.cx().immediate_backend_type(
222 bx.cx().layout_of(switch_ty)
224 let llval = bx.cx().const_uint_big(switch_llty, values[0]);
225 let cmp = bx.icmp(IntPredicate::IntEQ, discr.immediate(), llval);
226 bx.cond_br(cmp, lltrue, llfalse);
229 let (otherwise, targets) = targets.split_last().unwrap();
230 let switch = bx.switch(discr.immediate(),
231 llblock(self, *otherwise),
233 let switch_llty = bx.cx().immediate_backend_type(
234 bx.cx().layout_of(switch_ty)
236 for (&value, target) in values.iter().zip(targets) {
237 let llval = bx.cx().const_uint_big(switch_llty, value);
238 let llbb = llblock(self, *target);
239 bx.add_case(switch, llval, llbb)
244 mir::TerminatorKind::Return => {
245 let llval = match self.fn_ty.ret.mode {
246 PassMode::Ignore | PassMode::Indirect(..) => {
251 PassMode::Direct(_) | PassMode::Pair(..) => {
252 let op = self.codegen_consume(&bx, &mir::Place::Local(mir::RETURN_PLACE));
253 if let Ref(llval, _, align) = op.val {
254 bx.load(llval, align)
256 op.immediate_or_packed_pair(&bx)
260 PassMode::Cast(cast_ty) => {
261 let op = match self.locals[mir::RETURN_PLACE] {
262 LocalRef::Operand(Some(op)) => op,
263 LocalRef::Operand(None) => bug!("use of return before def"),
264 LocalRef::Place(cg_place) => {
266 val: Ref(cg_place.llval, None, cg_place.align),
267 layout: cg_place.layout
270 LocalRef::UnsizedPlace(_) => bug!("return type must be sized"),
272 let llslot = match op.val {
273 Immediate(_) | Pair(..) => {
274 let scratch = PlaceRef::alloca(&bx, self.fn_ty.ret.layout, "ret");
275 op.val.store(&bx, scratch);
278 Ref(llval, _, align) => {
279 assert_eq!(align.abi(), op.layout.align.abi(),
280 "return place is unaligned!");
285 bx.pointercast(llslot, bx.cx().type_ptr_to(
286 bx.cx().cast_backend_type(&cast_ty)
288 self.fn_ty.ret.layout.align)
294 mir::TerminatorKind::Unreachable => {
298 mir::TerminatorKind::Drop { ref location, target, unwind } => {
299 let ty = location.ty(self.mir, bx.tcx()).to_ty(bx.tcx());
300 let ty = self.monomorphize(&ty);
301 let drop_fn = monomorphize::resolve_drop_in_place(bx.cx().tcx(), ty);
303 if let ty::InstanceDef::DropGlue(_, None) = drop_fn.def {
304 // we don't actually need to drop anything.
305 funclet_br(self, &mut bx, target);
309 let place = self.codegen_place(&bx, location);
311 let mut args = if let Some(llextra) = place.llextra {
312 args2 = [place.llval, llextra];
315 args1 = [place.llval];
318 let (drop_fn, fn_ty) = match ty.sty {
320 let sig = drop_fn.fn_sig(tcx);
321 let sig = tcx.normalize_erasing_late_bound_regions(
322 ty::ParamEnv::reveal_all(),
325 let fn_ty = bx.cx().new_vtable(sig, &[]);
326 let vtable = args[1];
328 (meth::DESTRUCTOR.get_fn(&bx, vtable, &fn_ty), fn_ty)
331 (bx.cx().get_fn(drop_fn),
332 bx.cx().fn_type_of_instance(&drop_fn))
335 do_call(self, &mut bx, fn_ty, drop_fn, args,
336 Some((ReturnDest::Nothing, target)),
340 mir::TerminatorKind::Assert { ref cond, expected, ref msg, target, cleanup } => {
341 let cond = self.codegen_operand(&bx, cond).immediate();
342 let mut const_cond = bx.cx().const_to_opt_u128(cond, false).map(|c| c == 1);
344 // This case can currently arise only from functions marked
345 // with #[rustc_inherit_overflow_checks] and inlined from
346 // another crate (mostly core::num generic/#[inline] fns),
347 // while the current crate doesn't use overflow checks.
348 // NOTE: Unlike binops, negation doesn't have its own
349 // checked operation, just a comparison with the minimum
350 // value, so we have to check for the assert message.
351 if !bx.cx().check_overflow() {
352 if let mir::interpret::EvalErrorKind::OverflowNeg = *msg {
353 const_cond = Some(expected);
357 // Don't codegen the panic block if success if known.
358 if const_cond == Some(expected) {
359 funclet_br(self, &mut bx, target);
363 // Pass the condition through llvm.expect for branch hinting.
364 let expect = bx.cx().get_intrinsic(&"llvm.expect.i1");
365 let cond = bx.call(expect, &[cond, bx.cx().const_bool(expected)], None);
367 // Create the failure block and the conditional branch to it.
368 let lltarget = llblock(self, target);
369 let panic_block = self.new_block("panic");
371 bx.cond_br(cond, lltarget, panic_block.llbb());
373 bx.cond_br(cond, panic_block.llbb(), lltarget);
376 // After this point, bx is the block for the call to panic.
378 self.set_debug_loc(&bx, terminator.source_info);
380 // Get the location information.
381 let loc = bx.cx().sess().source_map().lookup_char_pos(span.lo());
382 let filename = Symbol::intern(&loc.file.name.to_string()).as_str();
383 let filename = bx.cx().const_str_slice(filename);
384 let line = bx.cx().const_u32(loc.line as u32);
385 let col = bx.cx().const_u32(loc.col.to_usize() as u32 + 1);
386 let align = tcx.data_layout.aggregate_align
387 .max(tcx.data_layout.i32_align)
388 .max(tcx.data_layout.pointer_align);
390 // Put together the arguments to the panic entry point.
391 let (lang_item, args) = match *msg {
392 EvalErrorKind::BoundsCheck { ref len, ref index } => {
393 let len = self.codegen_operand(&bx, len).immediate();
394 let index = self.codegen_operand(&bx, index).immediate();
396 let file_line_col = bx.cx().const_struct(&[filename, line, col], false);
397 let file_line_col = bx.cx().static_addr_of(
400 Some("panic_bounds_check_loc")
402 (lang_items::PanicBoundsCheckFnLangItem,
403 vec![file_line_col, index, len])
406 let str = msg.description();
407 let msg_str = Symbol::intern(str).as_str();
408 let msg_str = bx.cx().const_str_slice(msg_str);
409 let msg_file_line_col = bx.cx().const_struct(
410 &[msg_str, filename, line, col],
413 let msg_file_line_col = bx.cx().static_addr_of(
418 (lang_items::PanicFnLangItem,
419 vec![msg_file_line_col])
423 // Obtain the panic entry point.
424 let def_id = common::langcall(bx.tcx(), Some(span), "", lang_item);
425 let instance = ty::Instance::mono(bx.tcx(), def_id);
426 let fn_ty = bx.cx().fn_type_of_instance(&instance);
427 let llfn = bx.cx().get_fn(instance);
429 // Codegen the actual panic invoke/call.
430 do_call(self, &mut bx, fn_ty, llfn, &args, None, cleanup);
433 mir::TerminatorKind::DropAndReplace { .. } => {
434 bug!("undesugared DropAndReplace in codegen: {:?}", terminator);
437 mir::TerminatorKind::Call {
444 // Create the callee. This is a fn ptr or zero-sized and hence a kind of scalar.
445 let callee = self.codegen_operand(&bx, func);
447 let (instance, mut llfn) = match callee.layout.ty.sty {
448 ty::FnDef(def_id, substs) => {
449 (Some(ty::Instance::resolve(bx.cx().tcx(),
450 ty::ParamEnv::reveal_all(),
456 (None, Some(callee.immediate()))
458 _ => bug!("{} is not callable", callee.layout.ty)
460 let def = instance.map(|i| i.def);
461 let sig = callee.layout.ty.fn_sig(bx.tcx());
462 let sig = bx.tcx().normalize_erasing_late_bound_regions(
463 ty::ParamEnv::reveal_all(),
468 // Handle intrinsics old codegen wants Expr's for, ourselves.
469 let intrinsic = match def {
470 Some(ty::InstanceDef::Intrinsic(def_id))
471 => Some(bx.tcx().item_name(def_id).as_str()),
474 let intrinsic = intrinsic.as_ref().map(|s| &s[..]);
476 if intrinsic == Some("transmute") {
477 if let Some(destination_ref) = destination.as_ref() {
478 let &(ref dest, target) = destination_ref;
479 self.codegen_transmute(&bx, &args[0], dest);
480 funclet_br(self, &mut bx, target);
482 // If we are trying to transmute to an uninhabited type,
483 // it is likely there is no allotted destination. In fact,
484 // transmuting to an uninhabited type is UB, which means
485 // we can do what we like. Here, we declare that transmuting
486 // into an uninhabited type is impossible, so anything following
487 // it must be unreachable.
488 assert_eq!(bx.cx().layout_of(sig.output()).abi, layout::Abi::Uninhabited);
494 let extra_args = &args[sig.inputs().len()..];
495 let extra_args = extra_args.iter().map(|op_arg| {
496 let op_ty = op_arg.ty(self.mir, bx.tcx());
497 self.monomorphize(&op_ty)
498 }).collect::<Vec<_>>();
500 let fn_ty = match def {
501 Some(ty::InstanceDef::Virtual(..)) => {
502 bx.cx().new_vtable(sig, &extra_args)
504 Some(ty::InstanceDef::DropGlue(_, None)) => {
505 // empty drop glue - a nop.
506 let &(_, target) = destination.as_ref().unwrap();
507 funclet_br(self, &mut bx, target);
510 _ => bx.cx().new_fn_type(sig, &extra_args)
513 // emit a panic instead of instantiating an uninhabited type
514 if (intrinsic == Some("init") || intrinsic == Some("uninit")) &&
515 fn_ty.ret.layout.abi.is_uninhabited()
517 let loc = bx.cx().sess().source_map().lookup_char_pos(span.lo());
518 let filename = Symbol::intern(&loc.file.name.to_string()).as_str();
519 let filename = bx.cx().const_str_slice(filename);
520 let line = bx.cx().const_u32(loc.line as u32);
521 let col = bx.cx().const_u32(loc.col.to_usize() as u32 + 1);
522 let align = tcx.data_layout.aggregate_align
523 .max(tcx.data_layout.i32_align)
524 .max(tcx.data_layout.pointer_align);
527 "Attempted to instantiate uninhabited type {} using mem::{}",
529 if intrinsic == Some("init") { "zeroed" } else { "uninitialized" }
531 let msg_str = Symbol::intern(&str).as_str();
532 let msg_str = bx.cx().const_str_slice(msg_str);
533 let msg_file_line_col = bx.cx().const_struct(
534 &[msg_str, filename, line, col],
537 let msg_file_line_col = bx.cx().static_addr_of(
543 // Obtain the panic entry point.
545 common::langcall(bx.tcx(), Some(span), "", lang_items::PanicFnLangItem);
546 let instance = ty::Instance::mono(bx.tcx(), def_id);
547 let fn_ty = bx.cx().fn_type_of_instance(&instance);
548 let llfn = bx.cx().get_fn(instance);
550 // Codegen the actual panic invoke/call.
556 &[msg_file_line_col],
557 destination.as_ref().map(|(_, bb)| (ReturnDest::Nothing, *bb)),
563 // The arguments we'll be passing. Plus one to account for outptr, if used.
564 let arg_count = fn_ty.args.len() + fn_ty.ret.is_indirect() as usize;
565 let mut llargs = Vec::with_capacity(arg_count);
567 // Prepare the return value destination
568 let ret_dest = if let Some((ref dest, _)) = *destination {
569 let is_intrinsic = intrinsic.is_some();
570 self.make_return_dest(&bx, dest, &fn_ty.ret, &mut llargs,
576 if intrinsic.is_some() && intrinsic != Some("drop_in_place") {
577 let dest = match ret_dest {
578 _ if fn_ty.ret.is_indirect() => llargs[0],
579 ReturnDest::Nothing => {
580 bx.cx().const_undef(bx.cx().type_ptr_to(bx.memory_ty(&fn_ty.ret)))
582 ReturnDest::IndirectOperand(dst, _) |
583 ReturnDest::Store(dst) => dst.llval,
584 ReturnDest::DirectOperand(_) =>
585 bug!("Cannot use direct operand with an intrinsic call")
588 let args: Vec<_> = args.iter().enumerate().map(|(i, arg)| {
589 // The indices passed to simd_shuffle* in the
590 // third argument must be constant. This is
591 // checked by const-qualification, which also
592 // promotes any complex rvalues to constants.
593 if i == 2 && intrinsic.unwrap().starts_with("simd_shuffle") {
595 // The shuffle array argument is usually not an explicit constant,
596 // but specified directly in the code. This means it gets promoted
597 // and we can then extract the value by evaluating the promoted.
598 mir::Operand::Copy(mir::Place::Promoted(box(index, ty))) |
599 mir::Operand::Move(mir::Place::Promoted(box(index, ty))) => {
600 let param_env = ty::ParamEnv::reveal_all();
601 let cid = mir::interpret::GlobalId {
602 instance: self.instance,
603 promoted: Some(index),
605 let c = bx.tcx().const_eval(param_env.and(cid));
606 let (llval, ty) = self.simd_shuffle_indices(
608 terminator.source_info.span,
613 val: Immediate(llval),
614 layout: bx.cx().layout_of(ty),
618 mir::Operand::Copy(_) |
619 mir::Operand::Move(_) => {
620 span_bug!(span, "shuffle indices must be constant");
622 mir::Operand::Constant(ref constant) => {
623 let c = self.eval_mir_constant(&bx, constant);
624 let (llval, ty) = self.simd_shuffle_indices(
631 val: Immediate(llval),
632 layout: bx.cx().layout_of(ty)
638 self.codegen_operand(&bx, arg)
642 let callee_ty = instance.as_ref().unwrap().ty(bx.cx().tcx());
643 bx.codegen_intrinsic_call(callee_ty, &fn_ty, &args, dest,
644 terminator.source_info.span);
646 if let ReturnDest::IndirectOperand(dst, _) = ret_dest {
647 self.store_return(&bx, ret_dest, &fn_ty.ret, dst.llval);
650 if let Some((_, target)) = *destination {
651 funclet_br(self, &mut bx, target);
659 // Split the rust-call tupled arguments off.
660 let (first_args, untuple) = if abi == Abi::RustCall && !args.is_empty() {
661 let (tup, args) = args.split_last().unwrap();
667 'make_args: for (i, arg) in first_args.iter().enumerate() {
668 let mut op = self.codegen_operand(&bx, arg);
670 if let (0, Some(ty::InstanceDef::Virtual(_, idx))) = (i, def) {
671 if let Pair(..) = op.val {
672 // In the case of Rc<Self>, we need to explicitly pass a
673 // *mut RcBox<Self> with a Scalar (not ScalarPair) ABI. This is a hack
674 // that is understood elsewhere in the compiler as a method on
676 // To get a `*mut RcBox<Self>`, we just keep unwrapping newtypes until
677 // we get a value of a built-in pointer type
678 'descend_newtypes: while !op.layout.ty.is_unsafe_ptr()
679 && !op.layout.ty.is_region_ptr()
681 'iter_fields: for i in 0..op.layout.fields.count() {
682 let field = op.extract_field(&bx, i);
683 if !field.layout.is_zst() {
684 // we found the one non-zero-sized field that is allowed
685 // now find *its* non-zero-sized field, or stop if it's a
688 continue 'descend_newtypes
692 span_bug!(span, "receiver has no non-zero-sized fields {:?}", op);
695 // now that we have `*dyn Trait` or `&dyn Trait`, split it up into its
696 // data pointer and vtable. Look up the method in the vtable, and pass
697 // the data pointer as the first argument
699 Pair(data_ptr, meta) => {
700 llfn = Some(meth::VirtualIndex::from_index(idx)
701 .get_fn(&bx, meta, &fn_ty));
702 llargs.push(data_ptr);
705 other => bug!("expected a Pair, got {:?}", other)
707 } else if let Ref(data_ptr, Some(meta), _) = op.val {
708 // by-value dynamic dispatch
709 llfn = Some(meth::VirtualIndex::from_index(idx)
710 .get_fn(&bx, meta, &fn_ty));
711 llargs.push(data_ptr);
714 span_bug!(span, "can't codegen a virtual call on {:?}", op);
718 // The callee needs to own the argument memory if we pass it
719 // by-ref, so make a local copy of non-immediate constants.
720 match (arg, op.val) {
721 (&mir::Operand::Copy(_), Ref(_, None, _)) |
722 (&mir::Operand::Constant(_), Ref(_, None, _)) => {
723 let tmp = PlaceRef::alloca(&bx, op.layout, "const");
724 op.val.store(&bx, tmp);
725 op.val = Ref(tmp.llval, None, tmp.align);
730 self.codegen_argument(&bx, op, &mut llargs, &fn_ty.args[i]);
732 if let Some(tup) = untuple {
733 self.codegen_arguments_untupled(&bx, tup, &mut llargs,
734 &fn_ty.args[first_args.len()..])
737 let fn_ptr = match (llfn, instance) {
738 (Some(llfn), _) => llfn,
739 (None, Some(instance)) => bx.cx().get_fn(instance),
740 _ => span_bug!(span, "no llfn for call"),
743 do_call(self, &mut bx, fn_ty, fn_ptr, &llargs,
744 destination.as_ref().map(|&(_, target)| (ret_dest, target)),
747 mir::TerminatorKind::GeneratorDrop |
748 mir::TerminatorKind::Yield { .. } => bug!("generator ops in codegen"),
749 mir::TerminatorKind::FalseEdges { .. } |
750 mir::TerminatorKind::FalseUnwind { .. } => bug!("borrowck false edges in codegen"),
757 op: OperandRef<'tcx, Bx::Value>,
758 llargs: &mut Vec<Bx::Value>,
759 arg: &ArgType<'tcx, Ty<'tcx>>
761 // Fill padding with undef value, where applicable.
762 if let Some(ty) = arg.pad {
763 llargs.push(bx.cx().const_undef(bx.cx().reg_backend_type(&ty)))
770 if let PassMode::Pair(..) = arg.mode {
777 _ => bug!("codegen_argument: {:?} invalid for pair argument", op)
779 } else if arg.is_unsized_indirect() {
781 Ref(a, Some(b), _) => {
786 _ => bug!("codegen_argument: {:?} invalid for unsized indirect argument", op)
790 // Force by-ref if we have to load through a cast pointer.
791 let (mut llval, align, by_ref) = match op.val {
792 Immediate(_) | Pair(..) => {
794 PassMode::Indirect(..) | PassMode::Cast(_) => {
795 let scratch = PlaceRef::alloca(bx, arg.layout, "arg");
796 op.val.store(bx, scratch);
797 (scratch.llval, scratch.align, true)
800 (op.immediate_or_packed_pair(bx), arg.layout.align, false)
804 Ref(llval, _, align) => {
805 if arg.is_indirect() && align.abi() < arg.layout.align.abi() {
806 // `foo(packed.large_field)`. We can't pass the (unaligned) field directly. I
807 // think that ATM (Rust 1.16) we only pass temporaries, but we shouldn't
808 // have scary latent bugs around.
810 let scratch = PlaceRef::alloca(bx, arg.layout, "arg");
811 base::memcpy_ty(bx, scratch.llval, scratch.align, llval, align,
812 op.layout, MemFlags::empty());
813 (scratch.llval, scratch.align, true)
820 if by_ref && !arg.is_indirect() {
821 // Have to load the argument, maybe while casting it.
822 if let PassMode::Cast(ty) = arg.mode {
823 llval = bx.load(bx.pointercast(llval, bx.cx().type_ptr_to(
824 bx.cx().cast_backend_type(&ty))
825 ), align.min(arg.layout.align));
827 // We can't use `PlaceRef::load` here because the argument
828 // may have a type we don't treat as immediate, but the ABI
829 // used for this call is passing it by-value. In that case,
830 // the load would just produce `OperandValue::Ref` instead
831 // of the `OperandValue::Immediate` we need for the call.
832 llval = bx.load(llval, align);
833 if let layout::Abi::Scalar(ref scalar) = arg.layout.abi {
834 if scalar.is_bool() {
835 bx.range_metadata(llval, 0..2);
838 // We store bools as i8 so we need to truncate to i1.
839 llval = base::to_immediate(bx, llval, arg.layout);
846 fn codegen_arguments_untupled(
849 operand: &mir::Operand<'tcx>,
850 llargs: &mut Vec<Bx::Value>,
851 args: &[ArgType<'tcx, Ty<'tcx>>]
853 let tuple = self.codegen_operand(bx, operand);
855 // Handle both by-ref and immediate tuples.
856 if let Ref(llval, None, align) = tuple.val {
857 let tuple_ptr = PlaceRef::new_sized(llval, tuple.layout, align);
858 for i in 0..tuple.layout.fields.count() {
859 let field_ptr = tuple_ptr.project_field(bx, i);
860 self.codegen_argument(bx, bx.load_operand(field_ptr), llargs, &args[i]);
862 } else if let Ref(_, Some(_), _) = tuple.val {
863 bug!("closure arguments must be sized")
865 // If the tuple is immediate, the elements are as well.
866 for i in 0..tuple.layout.fields.count() {
867 let op = tuple.extract_field(bx, i);
868 self.codegen_argument(bx, op, llargs, &args[i]);
873 fn get_personality_slot(
876 ) -> PlaceRef<'tcx, Bx::Value> {
878 if let Some(slot) = self.personality_slot {
881 let layout = cx.layout_of(cx.tcx().intern_tup(&[
882 cx.tcx().mk_mut_ptr(cx.tcx().types.u8),
885 let slot = PlaceRef::alloca(bx, layout, "personalityslot");
886 self.personality_slot = Some(slot);
891 /// Return the landingpad wrapper around the given basic block
893 /// No-op in MSVC SEH scheme.
896 target_bb: mir::BasicBlock
897 ) -> Bx::BasicBlock {
898 if let Some(block) = self.landing_pads[target_bb] {
902 let block = self.blocks[target_bb];
903 let landing_pad = self.landing_pad_uncached(block);
904 self.landing_pads[target_bb] = Some(landing_pad);
908 fn landing_pad_uncached(
910 target_bb: Bx::BasicBlock
911 ) -> Bx::BasicBlock {
912 if base::wants_msvc_seh(self.cx.sess()) {
913 span_bug!(self.mir.span, "landing pad was not inserted?")
916 let mut bx = self.new_block("cleanup");
918 let llpersonality = self.cx.eh_personality();
919 let llretty = self.landing_pad_type();
920 let lp = bx.landing_pad(llretty, llpersonality, 1);
923 let slot = self.get_personality_slot(&bx);
924 slot.storage_live(&bx);
925 Pair(bx.extract_value(lp, 0), bx.extract_value(lp, 1)).store(&bx, slot);
931 fn landing_pad_type(&self) -> Bx::Type {
933 cx.type_struct(&[cx.type_i8p(), cx.type_i32()], false)
936 fn unreachable_block(
938 ) -> Bx::BasicBlock {
939 self.unreachable_block.unwrap_or_else(|| {
940 let bx = self.new_block("unreachable");
942 self.unreachable_block = Some(bx.llbb());
947 pub fn new_block(&self, name: &str) -> Bx {
948 Bx::new_block(self.cx, self.llfn, name)
955 let mut bx = Bx::with_cx(self.cx);
956 bx.position_at_end(self.blocks[bb]);
963 dest: &mir::Place<'tcx>,
964 fn_ret: &ArgType<'tcx, Ty<'tcx>>,
965 llargs: &mut Vec<Bx::Value>, is_intrinsic: bool
966 ) -> ReturnDest<'tcx, Bx::Value> {
967 // If the return is ignored, we can just return a do-nothing ReturnDest
968 if fn_ret.is_ignore() {
969 return ReturnDest::Nothing;
971 let dest = if let mir::Place::Local(index) = *dest {
972 match self.locals[index] {
973 LocalRef::Place(dest) => dest,
974 LocalRef::UnsizedPlace(_) => bug!("return type must be sized"),
975 LocalRef::Operand(None) => {
976 // Handle temporary places, specifically Operand ones, as
977 // they don't have allocas
978 return if fn_ret.is_indirect() {
979 // Odd, but possible, case, we have an operand temporary,
980 // but the calling convention has an indirect return.
981 let tmp = PlaceRef::alloca(bx, fn_ret.layout, "tmp_ret");
982 tmp.storage_live(bx);
983 llargs.push(tmp.llval);
984 ReturnDest::IndirectOperand(tmp, index)
985 } else if is_intrinsic {
986 // Currently, intrinsics always need a location to store
987 // the result. so we create a temporary alloca for the
989 let tmp = PlaceRef::alloca(bx, fn_ret.layout, "tmp_ret");
990 tmp.storage_live(bx);
991 ReturnDest::IndirectOperand(tmp, index)
993 ReturnDest::DirectOperand(index)
996 LocalRef::Operand(Some(_)) => {
997 bug!("place local already assigned to");
1001 self.codegen_place(bx, dest)
1003 if fn_ret.is_indirect() {
1004 if dest.align.abi() < dest.layout.align.abi() {
1005 // Currently, MIR code generation does not create calls
1006 // that store directly to fields of packed structs (in
1007 // fact, the calls it creates write only to temps),
1009 // If someone changes that, please update this code path
1010 // to create a temporary.
1011 span_bug!(self.mir.span, "can't directly store to unaligned value");
1013 llargs.push(dest.llval);
1016 ReturnDest::Store(dest)
1020 fn codegen_transmute(
1023 src: &mir::Operand<'tcx>,
1024 dst: &mir::Place<'tcx>
1026 if let mir::Place::Local(index) = *dst {
1027 match self.locals[index] {
1028 LocalRef::Place(place) => self.codegen_transmute_into(bx, src, place),
1029 LocalRef::UnsizedPlace(_) => bug!("transmute must not involve unsized locals"),
1030 LocalRef::Operand(None) => {
1031 let dst_layout = bx.cx().layout_of(self.monomorphized_place_ty(dst));
1032 assert!(!dst_layout.ty.has_erasable_regions());
1033 let place = PlaceRef::alloca(bx, dst_layout, "transmute_temp");
1034 place.storage_live(bx);
1035 self.codegen_transmute_into(bx, src, place);
1036 let op = bx.load_operand(place);
1037 place.storage_dead(bx);
1038 self.locals[index] = LocalRef::Operand(Some(op));
1040 LocalRef::Operand(Some(op)) => {
1041 assert!(op.layout.is_zst(),
1042 "assigning to initialized SSAtemp");
1046 let dst = self.codegen_place(bx, dst);
1047 self.codegen_transmute_into(bx, src, dst);
1051 fn codegen_transmute_into(
1054 src: &mir::Operand<'tcx>,
1055 dst: PlaceRef<'tcx, Bx::Value>
1057 let src = self.codegen_operand(bx, src);
1058 let llty = bx.cx().backend_type(src.layout);
1059 let cast_ptr = bx.pointercast(dst.llval, bx.cx().type_ptr_to(llty));
1060 let align = src.layout.align.min(dst.layout.align);
1061 src.val.store(bx, PlaceRef::new_sized(cast_ptr, src.layout, align));
1065 // Stores the return value of a function call into it's final location.
1069 dest: ReturnDest<'tcx, Bx::Value>,
1070 ret_ty: &ArgType<'tcx, Ty<'tcx>>,
1073 use self::ReturnDest::*;
1077 Store(dst) => bx.store_arg_ty(&ret_ty, llval, dst),
1078 IndirectOperand(tmp, index) => {
1079 let op = bx.load_operand(tmp);
1080 tmp.storage_dead(bx);
1081 self.locals[index] = LocalRef::Operand(Some(op));
1083 DirectOperand(index) => {
1084 // If there is a cast, we have to store and reload.
1085 let op = if let PassMode::Cast(_) = ret_ty.mode {
1086 let tmp = PlaceRef::alloca(bx, ret_ty.layout, "tmp_ret");
1087 tmp.storage_live(bx);
1088 bx.store_arg_ty(&ret_ty, llval, tmp);
1089 let op = bx.load_operand(tmp);
1090 tmp.storage_dead(bx);
1093 OperandRef::from_immediate_or_packed_pair(bx, llval, ret_ty.layout)
1095 self.locals[index] = LocalRef::Operand(Some(op));
1101 enum ReturnDest<'tcx, V> {
1102 // Do nothing, the return value is indirect or ignored
1104 // Store the return value to the pointer
1105 Store(PlaceRef<'tcx, V>),
1106 // Stores an indirect return value to an operand local place
1107 IndirectOperand(PlaceRef<'tcx, V>, mir::Local),
1108 // Stores a direct return value to an operand local place
1109 DirectOperand(mir::Local)