2 use crate::build::scope::DropKind;
3 use crate::hair::cx::Cx;
4 use crate::hair::{LintLevel, BindingMode, PatternKind};
5 use crate::transform::MirSource;
6 use crate::util as mir_util;
9 use rustc::hir::def_id::DefId;
10 use rustc::middle::region;
12 use rustc::ty::{self, Ty, TyCtxt};
13 use rustc::util::nodemap::HirIdMap;
14 use rustc_target::spec::PanicStrategy;
15 use rustc_data_structures::indexed_vec::{IndexVec, Idx};
17 use rustc_target::spec::abi::Abi;
18 use syntax::attr::{self, UnwindAttr};
19 use syntax::symbol::kw;
24 /// Construct the MIR for a given `DefId`.
25 pub fn mir_build<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId) -> Body<'tcx> {
26 let id = tcx.hir().as_local_hir_id(def_id).unwrap();
28 // Figure out what primary body this item has.
29 let (body_id, return_ty_span) = match tcx.hir().get(id) {
30 Node::Expr(hir::Expr { node: hir::ExprKind::Closure(_, decl, body_id, _, _), .. })
31 | Node::Item(hir::Item { node: hir::ItemKind::Fn(decl, _, _, body_id), .. })
34 node: hir::ImplItemKind::Method(hir::MethodSig { decl, .. }, body_id),
40 node: hir::TraitItemKind::Method(
41 hir::MethodSig { decl, .. },
42 hir::TraitMethod::Provided(body_id),
47 (*body_id, decl.output.span())
49 Node::Item(hir::Item { node: hir::ItemKind::Static(ty, _, body_id), .. })
50 | Node::Item(hir::Item { node: hir::ItemKind::Const(ty, body_id), .. })
51 | Node::ImplItem(hir::ImplItem { node: hir::ImplItemKind::Const(ty, body_id), .. })
53 hir::TraitItem { node: hir::TraitItemKind::Const(ty, Some(body_id)), .. }
57 Node::AnonConst(hir::AnonConst { body, hir_id, .. }) => {
58 (*body, tcx.hir().span(*hir_id))
61 _ => span_bug!(tcx.hir().span(id), "can't build MIR for {:?}", def_id),
64 tcx.infer_ctxt().enter(|infcx| {
65 let cx = Cx::new(&infcx, id);
66 let body = if cx.tables().tainted_by_errors {
67 build::construct_error(cx, body_id)
68 } else if cx.body_owner_kind.is_fn_or_closure() {
69 // fetch the fully liberated fn signature (that is, all bound
70 // types/lifetimes replaced)
71 let fn_sig = cx.tables().liberated_fn_sigs()[id].clone();
72 let fn_def_id = tcx.hir().local_def_id_from_hir_id(id);
74 let ty = tcx.type_of(fn_def_id);
75 let mut abi = fn_sig.abi;
76 let implicit_argument = match ty.sty {
78 // HACK(eddyb) Avoid having RustCall on closures,
79 // as it adds unnecessary (and wrong) auto-tupling.
81 Some(ArgInfo(liberated_closure_env_ty(tcx, id, body_id), None, None, None))
83 ty::Generator(..) => {
84 let gen_ty = tcx.body_tables(body_id).node_type(id);
85 Some(ArgInfo(gen_ty, None, None, None))
90 let safety = match fn_sig.unsafety {
91 hir::Unsafety::Normal => Safety::Safe,
92 hir::Unsafety::Unsafe => Safety::FnUnsafe,
95 let body = tcx.hir().body(body_id);
96 let explicit_arguments =
100 .map(|(index, arg)| {
101 let owner_id = tcx.hir().body_owner(body_id);
104 if let Some(ref fn_decl) = tcx.hir().fn_decl_by_hir_id(owner_id) {
105 let ty_hir_id = fn_decl.inputs[index].hir_id;
106 let ty_span = tcx.hir().span(ty_hir_id);
107 opt_ty_info = Some(ty_span);
108 self_arg = if index == 0 && fn_decl.implicit_self.has_implicit_self() {
109 match fn_decl.implicit_self {
110 hir::ImplicitSelfKind::Imm => Some(ImplicitSelfKind::Imm),
111 hir::ImplicitSelfKind::Mut => Some(ImplicitSelfKind::Mut),
112 hir::ImplicitSelfKind::ImmRef => Some(ImplicitSelfKind::ImmRef),
113 hir::ImplicitSelfKind::MutRef => Some(ImplicitSelfKind::MutRef),
124 ArgInfo(fn_sig.inputs()[index], opt_ty_info, Some(&*arg.pat), self_arg)
127 let arguments = implicit_argument.into_iter().chain(explicit_arguments);
129 let (yield_ty, return_ty) = if body.generator_kind.is_some() {
130 let gen_sig = match ty.sty {
131 ty::Generator(gen_def_id, gen_substs, ..) =>
132 gen_substs.sig(gen_def_id, tcx),
134 span_bug!(tcx.hir().span(id),
135 "generator w/o generator type: {:?}", ty),
137 (Some(gen_sig.yield_ty), gen_sig.return_ty)
139 (None, fn_sig.output())
142 build::construct_fn(cx, id, arguments, safety, abi,
143 return_ty, yield_ty, return_ty_span, body)
145 // Get the revealed type of this const. This is *not* the adjusted
146 // type of its body, which may be a subtype of this type. For
150 // static X: fn(&'static ()) = foo;
152 // The adjusted type of the body of X is `for<'a> fn(&'a ())` which
153 // is not the same as the type of X. We need the type of the return
154 // place to be the type of the constant because NLL typeck will
157 let return_ty = cx.tables().node_type(id);
159 build::construct_const(cx, body_id, return_ty, return_ty_span)
162 mir_util::dump_mir(tcx, None, "mir_map", &0,
163 MirSource::item(def_id), &body, |_, _| Ok(()) );
165 lints::check(tcx, &body, def_id);
171 ///////////////////////////////////////////////////////////////////////////
172 // BuildMir -- walks a crate, looking for fn items and methods to build MIR from
174 fn liberated_closure_env_ty<'tcx>(
176 closure_expr_id: hir::HirId,
177 body_id: hir::BodyId,
179 let closure_ty = tcx.body_tables(body_id).node_type(closure_expr_id);
181 let (closure_def_id, closure_substs) = match closure_ty.sty {
182 ty::Closure(closure_def_id, closure_substs) => (closure_def_id, closure_substs),
183 _ => bug!("closure expr does not have closure type: {:?}", closure_ty)
186 let closure_env_ty = tcx.closure_env_ty(closure_def_id, closure_substs).unwrap();
187 tcx.liberate_late_bound_regions(closure_def_id, &closure_env_ty)
190 #[derive(Debug, PartialEq, Eq)]
191 pub enum BlockFrame {
192 /// Evaluation is currently within a statement.
194 /// Examples include:
196 /// 2. `let _ = EXPR;`
197 /// 3. `let x = EXPR;`
199 /// If true, then statement discards result from evaluating
200 /// the expression (such as examples 1 and 2 above).
201 ignores_expr_result: bool
204 /// Evaluation is currently within the tail expression of a block.
206 /// Example: `{ STMT_1; STMT_2; EXPR }`
208 /// If true, then the surrounding context of the block ignores
209 /// the result of evaluating the block's tail expression.
211 /// Example: `let _ = { STMT_1; EXPR };`
212 tail_result_is_ignored: bool
215 /// Generic mark meaning that the block occurred as a subexpression
216 /// where the result might be used.
218 /// Examples: `foo(EXPR)`, `match EXPR { ... }`
223 fn is_tail_expr(&self) -> bool {
225 BlockFrame::TailExpr { .. } => true,
227 BlockFrame::Statement { .. } |
228 BlockFrame::SubExpr => false,
231 fn is_statement(&self) -> bool {
233 BlockFrame::Statement { .. } => true,
235 BlockFrame::TailExpr { .. } |
236 BlockFrame::SubExpr => false,
242 struct BlockContext(Vec<BlockFrame>);
244 struct Builder<'a, 'tcx> {
252 /// The current set of scopes, updated as we traverse;
253 /// see the `scope` module for more details.
254 scopes: Vec<scope::Scope<'tcx>>,
256 /// The block-context: each time we build the code within an hair::Block,
257 /// we push a frame here tracking whether we are building a statement or
258 /// if we are pushing the tail expression of the block. This is used to
259 /// embed information in generated temps about whether they were created
260 /// for a block tail expression or not.
262 /// It would be great if we could fold this into `self.scopes`
263 /// somehow, but right now I think that is very tightly tied to
264 /// the code generation in ways that we cannot (or should not)
265 /// start just throwing new entries onto that vector in order to
266 /// distinguish the context of EXPR1 from the context of EXPR2 in
267 /// `{ STMTS; EXPR1 } + EXPR2`.
268 block_context: BlockContext,
270 /// The current unsafe block in scope, even if it is hidden by
271 /// a `PushUnsafeBlock`.
272 unpushed_unsafe: Safety,
274 /// The number of `push_unsafe_block` levels in scope.
275 push_unsafe_count: usize,
277 /// The current set of breakables; see the `scope` module for more
279 breakable_scopes: Vec<scope::BreakableScope<'tcx>>,
281 /// The vector of all scopes that we have created thus far;
282 /// we track this for debuginfo later.
283 source_scopes: IndexVec<SourceScope, SourceScopeData>,
284 source_scope_local_data: IndexVec<SourceScope, SourceScopeLocalData>,
285 source_scope: SourceScope,
287 /// The guard-context: each time we build the guard expression for
288 /// a match arm, we push onto this stack, and then pop when we
289 /// finish building it.
290 guard_context: Vec<GuardFrame>,
292 /// Maps `HirId`s of variable bindings to the `Local`s created for them.
293 /// (A match binding can have two locals; the 2nd is for the arm's guard.)
294 var_indices: HirIdMap<LocalsForNode>,
295 local_decls: IndexVec<Local, LocalDecl<'tcx>>,
296 canonical_user_type_annotations: ty::CanonicalUserTypeAnnotations<'tcx>,
297 __upvar_debuginfo_codegen_only_do_not_use: Vec<UpvarDebuginfo>,
298 upvar_mutbls: Vec<Mutability>,
299 unit_temp: Option<Place<'tcx>>,
301 /// Cached block with the `RESUME` terminator; this is created
302 /// when first set of cleanups are built.
303 cached_resume_block: Option<BasicBlock>,
304 /// Cached block with the `RETURN` terminator.
305 cached_return_block: Option<BasicBlock>,
306 /// Cached block with the `UNREACHABLE` terminator.
307 cached_unreachable_block: Option<BasicBlock>,
310 impl<'a, 'tcx> Builder<'a, 'tcx> {
311 fn is_bound_var_in_guard(&self, id: hir::HirId) -> bool {
312 self.guard_context.iter().any(|frame| frame.locals.iter().any(|local| local.id == id))
315 fn var_local_id(&self, id: hir::HirId, for_guard: ForGuard) -> Local {
316 self.var_indices[&id].local_id(for_guard)
321 fn new() -> Self { BlockContext(vec![]) }
322 fn push(&mut self, bf: BlockFrame) { self.0.push(bf); }
323 fn pop(&mut self) -> Option<BlockFrame> { self.0.pop() }
325 /// Traverses the frames on the `BlockContext`, searching for either
326 /// the first block-tail expression frame with no intervening
329 /// Notably, this skips over `SubExpr` frames; this method is
330 /// meant to be used in the context of understanding the
331 /// relationship of a temp (created within some complicated
332 /// expression) with its containing expression, and whether the
333 /// value of that *containing expression* (not the temp!) is
335 fn currently_in_block_tail(&self) -> Option<BlockTailInfo> {
336 for bf in self.0.iter().rev() {
338 BlockFrame::SubExpr => continue,
339 BlockFrame::Statement { .. } => break,
340 &BlockFrame::TailExpr { tail_result_is_ignored } =>
341 return Some(BlockTailInfo { tail_result_is_ignored })
348 /// Looks at the topmost frame on the BlockContext and reports
349 /// whether its one that would discard a block tail result.
351 /// Unlike `currently_within_ignored_tail_expression`, this does
352 /// *not* skip over `SubExpr` frames: here, we want to know
353 /// whether the block result itself is discarded.
354 fn currently_ignores_tail_results(&self) -> bool {
355 match self.0.last() {
356 // no context: conservatively assume result is read
359 // sub-expression: block result feeds into some computation
360 Some(BlockFrame::SubExpr) => false,
362 // otherwise: use accumulated is_ignored state.
363 Some(BlockFrame::TailExpr { tail_result_is_ignored: ignored }) |
364 Some(BlockFrame::Statement { ignores_expr_result: ignored }) => *ignored,
371 /// In the usual case, a `HirId` for an identifier maps to at most
372 /// one `Local` declaration.
375 /// The exceptional case is identifiers in a match arm's pattern
376 /// that are referenced in a guard of that match arm. For these,
377 /// we have `2` Locals.
379 /// * `for_arm_body` is the Local used in the arm body (which is
380 /// just like the `One` case above),
382 /// * `ref_for_guard` is the Local used in the arm's guard (which
383 /// is a reference to a temp that is an alias of
385 ForGuard { ref_for_guard: Local, for_arm_body: Local },
389 struct GuardFrameLocal {
393 impl GuardFrameLocal {
394 fn new(id: hir::HirId, _binding_mode: BindingMode) -> Self {
403 /// These are the id's of names that are bound by patterns of the
404 /// arm of *this* guard.
406 /// (Frames higher up the stack will have the id's bound in arms
407 /// further out, such as in a case like:
410 /// P1(id1) if (... (match E2 { P2(id2) if ... => B2 })) => B1,
413 /// here, when building for FIXME.
414 locals: Vec<GuardFrameLocal>,
417 /// `ForGuard` indicates whether we are talking about:
418 /// 1. The variable for use outside of guard expressions, or
419 /// 2. The temp that holds reference to (1.), which is actually what the
420 /// guard expressions see.
421 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
428 fn local_id(&self, for_guard: ForGuard) -> Local {
429 match (self, for_guard) {
430 (&LocalsForNode::One(local_id), ForGuard::OutsideGuard) |
431 (&LocalsForNode::ForGuard { ref_for_guard: local_id, .. }, ForGuard::RefWithinGuard) |
432 (&LocalsForNode::ForGuard { for_arm_body: local_id, .. }, ForGuard::OutsideGuard) =>
435 (&LocalsForNode::One(_), ForGuard::RefWithinGuard) =>
436 bug!("anything with one local should never be within a guard."),
442 basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
446 pub struct ScopeId { .. }
449 ///////////////////////////////////////////////////////////////////////////
450 /// The `BlockAnd` "monad" packages up the new basic block along with a
451 /// produced value (sometimes just unit, of course). The `unpack!`
452 /// macro (and methods below) makes working with `BlockAnd` much more
455 #[must_use = "if you don't use one of these results, you're leaving a dangling edge"]
456 struct BlockAnd<T>(BasicBlock, T);
458 trait BlockAndExtension {
459 fn and<T>(self, v: T) -> BlockAnd<T>;
460 fn unit(self) -> BlockAnd<()>;
463 impl BlockAndExtension for BasicBlock {
464 fn and<T>(self, v: T) -> BlockAnd<T> {
468 fn unit(self) -> BlockAnd<()> {
473 /// Update a block pointer and return the value.
474 /// Use it like `let x = unpack!(block = self.foo(block, foo))`.
475 macro_rules! unpack {
476 ($x:ident = $c:expr) => {
478 let BlockAnd(b, v) = $c;
486 let BlockAnd(b, ()) = $c;
492 fn should_abort_on_panic<'tcx>(tcx: TyCtxt<'tcx>, fn_def_id: DefId, abi: Abi) -> bool {
493 // Not callable from C, so we can safely unwind through these
494 if abi == Abi::Rust || abi == Abi::RustCall { return false; }
496 // Validate `#[unwind]` syntax regardless of platform-specific panic strategy
497 let attrs = &tcx.get_attrs(fn_def_id);
498 let unwind_attr = attr::find_unwind_attr(Some(tcx.sess.diagnostic()), attrs);
500 // We never unwind, so it's not relevant to stop an unwind
501 if tcx.sess.panic_strategy() != PanicStrategy::Unwind { return false; }
503 // We cannot add landing pads, so don't add one
504 if tcx.sess.no_landing_pads() { return false; }
506 // This is a special case: some functions have a C abi but are meant to
507 // unwind anyway. Don't stop them.
510 Some(UnwindAttr::Allowed) => false,
511 Some(UnwindAttr::Aborts) => true,
515 ///////////////////////////////////////////////////////////////////////////
516 /// the main entry point for building MIR for a function
518 struct ArgInfo<'tcx>(Ty<'tcx>, Option<Span>, Option<&'tcx hir::Pat>, Option<ImplicitSelfKind>);
520 fn construct_fn<'a, 'tcx, A>(
527 yield_ty: Option<Ty<'tcx>>,
528 return_ty_span: Span,
529 body: &'tcx hir::Body,
532 A: Iterator<Item=ArgInfo<'tcx>>
534 let arguments: Vec<_> = arguments.collect();
537 let tcx_hir = tcx.hir();
538 let span = tcx_hir.span(fn_id);
540 let hir_tables = hir.tables();
541 let fn_def_id = tcx_hir.local_def_id_from_hir_id(fn_id);
543 // Gather the upvars of a closure, if any.
544 let mut upvar_mutbls = vec![];
545 // In analyze_closure() in upvar.rs we gathered a list of upvars used by a
546 // closure and we stored in a map called upvar_list in TypeckTables indexed
547 // with the closure's DefId. Here, we run through that vec of UpvarIds for
548 // the given closure and use the necessary information to create UpvarDecl.
549 let upvar_debuginfo: Vec<_> = hir_tables
554 .map(|(&var_hir_id, &upvar_id)| {
555 let capture = hir_tables.upvar_capture(upvar_id);
556 let by_ref = match capture {
557 ty::UpvarCapture::ByValue => false,
558 ty::UpvarCapture::ByRef(..) => true,
560 let mut debuginfo = UpvarDebuginfo {
561 debug_name: kw::Invalid,
564 let mut mutability = Mutability::Not;
565 if let Some(Node::Binding(pat)) = tcx_hir.find_by_hir_id(var_hir_id) {
566 if let hir::PatKind::Binding(_, _, ident, _) = pat.node {
567 debuginfo.debug_name = ident.name;
568 if let Some(&bm) = hir.tables.pat_binding_modes().get(pat.hir_id) {
569 if bm == ty::BindByValue(hir::MutMutable) {
570 mutability = Mutability::Mut;
572 mutability = Mutability::Not;
575 tcx.sess.delay_span_bug(pat.span, "missing binding mode");
579 upvar_mutbls.push(mutability);
584 let mut builder = Builder::new(hir,
592 body.generator_kind.is_some());
594 let call_site_scope = region::Scope {
595 id: body.value.hir_id.local_id,
596 data: region::ScopeData::CallSite
598 let arg_scope = region::Scope {
599 id: body.value.hir_id.local_id,
600 data: region::ScopeData::Arguments
602 let mut block = START_BLOCK;
603 let source_info = builder.source_info(span);
604 let call_site_s = (call_site_scope, source_info);
605 unpack!(block = builder.in_scope(call_site_s, LintLevel::Inherited, |builder| {
606 if should_abort_on_panic(tcx, fn_def_id, abi) {
607 builder.schedule_abort();
610 let arg_scope_s = (arg_scope, source_info);
611 unpack!(block = builder.in_scope(arg_scope_s, LintLevel::Inherited, |builder| {
612 builder.args_and_body(block, &arguments, arg_scope, &body.value)
614 // Attribute epilogue to function's closing brace
615 let fn_end = span.shrink_to_hi();
616 let source_info = builder.source_info(fn_end);
617 let return_block = builder.return_block();
618 builder.cfg.terminate(block, source_info,
619 TerminatorKind::Goto { target: return_block });
620 builder.cfg.terminate(return_block, source_info,
621 TerminatorKind::Return);
622 // Attribute any unreachable codepaths to the function's closing brace
623 if let Some(unreachable_block) = builder.cached_unreachable_block {
624 builder.cfg.terminate(unreachable_block, source_info,
625 TerminatorKind::Unreachable);
629 assert_eq!(block, builder.return_block());
631 let mut spread_arg = None;
632 if abi == Abi::RustCall {
633 // RustCall pseudo-ABI untuples the last argument.
634 spread_arg = Some(Local::new(arguments.len()));
636 info!("fn_id {:?} has attrs {:?}", fn_def_id,
637 tcx.get_attrs(fn_def_id));
639 let mut body = builder.finish(yield_ty);
640 body.spread_arg = spread_arg;
644 fn construct_const<'a, 'tcx>(
646 body_id: hir::BodyId,
651 let owner_id = tcx.hir().body_owner(body_id);
652 let span = tcx.hir().span(owner_id);
653 let mut builder = Builder::new(
665 let mut block = START_BLOCK;
666 let ast_expr = &tcx.hir().body(body_id).value;
667 let expr = builder.hir.mirror(ast_expr);
668 unpack!(block = builder.into_expr(&Place::RETURN_PLACE, block, expr));
670 let source_info = builder.source_info(span);
671 builder.cfg.terminate(block, source_info, TerminatorKind::Return);
673 // Constants can't `return` so a return block should not be created.
674 assert_eq!(builder.cached_return_block, None);
676 // Constants may be match expressions in which case an unreachable block may
677 // be created, so terminate it properly.
678 if let Some(unreachable_block) = builder.cached_unreachable_block {
679 builder.cfg.terminate(unreachable_block, source_info,
680 TerminatorKind::Unreachable);
686 fn construct_error<'a, 'tcx>(
690 let owner_id = hir.tcx().hir().body_owner(body_id);
691 let span = hir.tcx().hir().span(owner_id);
692 let ty = hir.tcx().types.err;
693 let mut builder = Builder::new(hir, span, 0, Safety::Safe, ty, span, vec![], vec![], false);
694 let source_info = builder.source_info(span);
695 builder.cfg.terminate(START_BLOCK, source_info, TerminatorKind::Unreachable);
699 impl<'a, 'tcx> Builder<'a, 'tcx> {
700 fn new(hir: Cx<'a, 'tcx>,
706 __upvar_debuginfo_codegen_only_do_not_use: Vec<UpvarDebuginfo>,
707 upvar_mutbls: Vec<Mutability>,
709 -> Builder<'a, 'tcx> {
710 let lint_level = LintLevel::Explicit(hir.root_lint_level);
711 let mut builder = Builder {
713 cfg: CFG { basic_blocks: IndexVec::new() },
718 block_context: BlockContext::new(),
719 source_scopes: IndexVec::new(),
720 source_scope: OUTERMOST_SOURCE_SCOPE,
721 source_scope_local_data: IndexVec::new(),
722 guard_context: vec![],
723 push_unsafe_count: 0,
724 unpushed_unsafe: safety,
725 breakable_scopes: vec![],
726 local_decls: IndexVec::from_elem_n(
727 LocalDecl::new_return_place(return_ty, return_span),
730 canonical_user_type_annotations: IndexVec::new(),
731 __upvar_debuginfo_codegen_only_do_not_use,
733 var_indices: Default::default(),
735 cached_resume_block: None,
736 cached_return_block: None,
737 cached_unreachable_block: None,
740 assert_eq!(builder.cfg.start_new_block(), START_BLOCK);
742 builder.new_source_scope(span, lint_level, Some(safety)),
743 OUTERMOST_SOURCE_SCOPE);
744 builder.source_scopes[OUTERMOST_SOURCE_SCOPE].parent_scope = None;
750 yield_ty: Option<Ty<'tcx>>)
752 for (index, block) in self.cfg.basic_blocks.iter().enumerate() {
753 if block.terminator.is_none() {
754 span_bug!(self.fn_span, "no terminator on block {:?}", index);
759 self.cfg.basic_blocks,
761 ClearCrossCrate::Set(self.source_scope_local_data),
765 self.canonical_user_type_annotations,
767 self.__upvar_debuginfo_codegen_only_do_not_use,
769 self.hir.control_flow_destroyed(),
773 fn args_and_body(&mut self,
774 mut block: BasicBlock,
775 arguments: &[ArgInfo<'tcx>],
776 argument_scope: region::Scope,
777 ast_body: &'tcx hir::Expr)
780 // Allocate locals for the function arguments
781 for &ArgInfo(ty, _, pattern, _) in arguments.iter() {
782 // If this is a simple binding pattern, give the local a name for
783 // debuginfo and so that error reporting knows that this is a user
784 // variable. For any other pattern the pattern introduces new
785 // variables which will be named instead.
786 let (name, span) = if let Some(pat) = pattern {
787 (pat.simple_ident().map(|ident| ident.name), pat.span)
792 let source_info = SourceInfo { scope: OUTERMOST_SOURCE_SCOPE, span, };
793 self.local_decls.push(LocalDecl {
794 mutability: Mutability::Mut,
796 user_ty: UserTypeProjections::none(),
798 visibility_scope: source_info.scope,
801 is_user_variable: None,
806 let mut scope = None;
807 // Bind the argument patterns
808 for (index, arg_info) in arguments.iter().enumerate() {
809 // Function arguments always get the first Local indices after the return place
810 let local = Local::new(index + 1);
811 let place = Place::Base(PlaceBase::Local(local));
812 let &ArgInfo(ty, opt_ty_info, pattern, ref self_binding) = arg_info;
814 // Make sure we drop (parts of) the argument even when not matched on.
816 pattern.as_ref().map_or(ast_body.span, |pat| pat.span),
817 argument_scope, &place, ty, DropKind::Value,
820 if let Some(pattern) = pattern {
821 let pattern = self.hir.pattern_from_hir(pattern);
822 let span = pattern.span;
824 match *pattern.kind {
825 // Don't introduce extra copies for simple bindings
826 PatternKind::Binding {
829 mode: BindingMode::ByValue,
833 self.local_decls[local].mutability = mutability;
834 self.local_decls[local].is_user_variable =
835 if let Some(kind) = self_binding {
836 Some(ClearCrossCrate::Set(BindingForm::ImplicitSelf(*kind)))
838 let binding_mode = ty::BindingMode::BindByValue(mutability.into());
839 Some(ClearCrossCrate::Set(BindingForm::Var(VarBindingForm {
842 opt_match_place: Some((Some(place.clone()), span)),
846 self.var_indices.insert(var, LocalsForNode::One(local));
849 scope = self.declare_bindings(
853 matches::ArmHasGuard(false),
854 Some((Some(&place), span)),
856 unpack!(block = self.place_into_pattern(block, pattern, &place, false));
862 // Enter the argument pattern bindings source scope, if it exists.
863 if let Some(source_scope) = scope {
864 self.source_scope = source_scope;
867 let body = self.hir.mirror(ast_body);
868 self.into(&Place::RETURN_PLACE, block, body)
871 fn get_unit_temp(&mut self) -> Place<'tcx> {
872 match self.unit_temp {
873 Some(ref tmp) => tmp.clone(),
875 let ty = self.hir.unit_ty();
876 let fn_span = self.fn_span;
877 let tmp = self.temp(ty, fn_span);
878 self.unit_temp = Some(tmp.clone());
884 fn return_block(&mut self) -> BasicBlock {
885 match self.cached_return_block {
888 let rb = self.cfg.start_new_block();
889 self.cached_return_block = Some(rb);
896 ///////////////////////////////////////////////////////////////////////////
897 // Builder methods are broken up into modules, depending on what kind
898 // of thing is being lowered. Note that they use the `unpack` macro
899 // above extensively.