]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/build/matches/mod.rs
Remove PlaceBase enum and make Place base field be local: Local
[rust.git] / src / librustc_mir / build / matches / mod.rs
1 //! Code related to match expressions. These are sufficiently complex to
2 //! warrant their own module and submodules. :) This main module includes the
3 //! high-level algorithm, the submodules contain the details.
4 //!
5 //! This also includes code for pattern bindings in `let` statements and
6 //! function parameters.
7
8 use crate::build::scope::DropKind;
9 use crate::build::ForGuard::{self, OutsideGuard, RefWithinGuard};
10 use crate::build::{BlockAnd, BlockAndExtension, Builder};
11 use crate::build::{GuardFrame, GuardFrameLocal, LocalsForNode};
12 use crate::hair::{self, *};
13 use rustc::middle::region;
14 use rustc::mir::*;
15 use rustc::ty::layout::VariantIdx;
16 use rustc::ty::{self, CanonicalUserTypeAnnotation, Ty};
17 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
18 use rustc_hir::HirId;
19 use rustc_index::bit_set::BitSet;
20 use rustc_span::Span;
21 use smallvec::{smallvec, SmallVec};
22 use syntax::ast::Name;
23
24 // helper functions, broken out by category:
25 mod simplify;
26 mod test;
27 mod util;
28
29 use itertools::Itertools;
30 use std::convert::TryFrom;
31
32 impl<'a, 'tcx> Builder<'a, 'tcx> {
33     /// Generates MIR for a `match` expression.
34     ///
35     /// The MIR that we generate for a match looks like this.
36     ///
37     /// ```text
38     /// [ 0. Pre-match ]
39     ///        |
40     /// [ 1. Evaluate Scrutinee (expression being matched on) ]
41     /// [ (fake read of scrutinee) ]
42     ///        |
43     /// [ 2. Decision tree -- check discriminants ] <--------+
44     ///        |                                             |
45     ///        | (once a specific arm is chosen)             |
46     ///        |                                             |
47     /// [pre_binding_block]                           [otherwise_block]
48     ///        |                                             |
49     /// [ 3. Create "guard bindings" for arm ]               |
50     /// [ (create fake borrows) ]                            |
51     ///        |                                             |
52     /// [ 4. Execute guard code ]                            |
53     /// [ (read fake borrows) ] --(guard is false)-----------+
54     ///        |
55     ///        | (guard results in true)
56     ///        |
57     /// [ 5. Create real bindings and execute arm ]
58     ///        |
59     /// [ Exit match ]
60     /// ```
61     ///
62     /// All of the different arms have been stacked on top of each other to
63     /// simplify the diagram. For an arm with no guard the blocks marked 3 and
64     /// 4 and the fake borrows are omitted.
65     ///
66     /// We generate MIR in the following steps:
67     ///
68     /// 1. Evaluate the scrutinee and add the fake read of it ([Builder::lower_scrutinee]).
69     /// 2. Create the prebinding and otherwise blocks ([Builder::create_match_candidates]).
70     /// 3. Create the decision tree ([Builder::lower_match_tree]).
71     /// 4. Determine the fake borrows that are needed from the places that were
72     ///    matched against and create the required temporaries for them
73     ///    ([Builder::calculate_fake_borrows]).
74     /// 5. Create everything else: the guards and the arms ([Builder::lower_match_arms]).
75     ///
76     /// ## False edges
77     ///
78     /// We don't want to have the exact structure of the decision tree be
79     /// visible through borrow checking. False edges ensure that the CFG as
80     /// seen by borrow checking doesn't encode this. False edges are added:
81     ///
82     /// * From each prebinding block to the next prebinding block.
83     /// * From each otherwise block to the next prebinding block.
84     pub fn match_expr(
85         &mut self,
86         destination: &Place<'tcx>,
87         span: Span,
88         mut block: BasicBlock,
89         scrutinee: ExprRef<'tcx>,
90         arms: Vec<Arm<'tcx>>,
91     ) -> BlockAnd<()> {
92         let scrutinee_span = scrutinee.span();
93         let scrutinee_place =
94             unpack!(block = self.lower_scrutinee(block, scrutinee, scrutinee_span,));
95
96         let mut arm_candidates = self.create_match_candidates(&scrutinee_place, &arms);
97
98         let match_has_guard = arms.iter().any(|arm| arm.guard.is_some());
99         let candidates =
100             arm_candidates.iter_mut().flat_map(|(_, candidates)| candidates).collect::<Vec<_>>();
101
102         let fake_borrow_temps =
103             self.lower_match_tree(block, scrutinee_span, match_has_guard, candidates);
104
105         self.lower_match_arms(
106             &destination,
107             scrutinee_place,
108             scrutinee_span,
109             arm_candidates,
110             self.source_info(span),
111             fake_borrow_temps,
112         )
113     }
114
115     /// Evaluate the scrutinee and add the fake read of it.
116     fn lower_scrutinee(
117         &mut self,
118         mut block: BasicBlock,
119         scrutinee: ExprRef<'tcx>,
120         scrutinee_span: Span,
121     ) -> BlockAnd<Place<'tcx>> {
122         let scrutinee_place = unpack!(block = self.as_place(block, scrutinee));
123         // Matching on a `scrutinee_place` with an uninhabited type doesn't
124         // generate any memory reads by itself, and so if the place "expression"
125         // contains unsafe operations like raw pointer dereferences or union
126         // field projections, we wouldn't know to require an `unsafe` block
127         // around a `match` equivalent to `std::intrinsics::unreachable()`.
128         // See issue #47412 for this hole being discovered in the wild.
129         //
130         // HACK(eddyb) Work around the above issue by adding a dummy inspection
131         // of `scrutinee_place`, specifically by applying `ReadForMatch`.
132         //
133         // NOTE: ReadForMatch also checks that the scrutinee is initialized.
134         // This is currently needed to not allow matching on an uninitialized,
135         // uninhabited value. If we get never patterns, those will check that
136         // the place is initialized, and so this read would only be used to
137         // check safety.
138         let cause_matched_place = FakeReadCause::ForMatchedPlace;
139         let source_info = self.source_info(scrutinee_span);
140         self.cfg.push_fake_read(block, source_info, cause_matched_place, scrutinee_place.clone());
141
142         block.and(scrutinee_place)
143     }
144
145     /// Create the initial `Candidate`s for a `match` expression.
146     fn create_match_candidates<'pat>(
147         &mut self,
148         scrutinee: &Place<'tcx>,
149         arms: &'pat [Arm<'tcx>],
150     ) -> Vec<(&'pat Arm<'tcx>, Vec<Candidate<'pat, 'tcx>>)> {
151         let candidate_count = arms.iter().map(|c| c.top_pats_hack().len()).sum::<usize>();
152         let pre_binding_blocks: Vec<_> =
153             (0..candidate_count).map(|_| self.cfg.start_new_block()).collect();
154
155         let mut candidate_pre_binding_blocks = pre_binding_blocks.iter();
156         let mut next_candidate_pre_binding_blocks = pre_binding_blocks.iter().skip(1);
157
158         // Assemble a list of candidates: there is one candidate per pattern,
159         // which means there may be more than one candidate *per arm*.
160         arms.iter()
161             .map(|arm| {
162                 let arm_has_guard = arm.guard.is_some();
163                 let arm_candidates: Vec<_> = arm
164                     .top_pats_hack()
165                     .iter()
166                     .zip(candidate_pre_binding_blocks.by_ref())
167                     .map(|(pattern, pre_binding_block)| Candidate {
168                         span: pattern.span,
169                         match_pairs: smallvec![MatchPair::new(scrutinee.clone(), pattern)],
170                         bindings: vec![],
171                         ascriptions: vec![],
172                         otherwise_block: if arm_has_guard {
173                             Some(self.cfg.start_new_block())
174                         } else {
175                             None
176                         },
177                         pre_binding_block: *pre_binding_block,
178                         next_candidate_pre_binding_block: next_candidate_pre_binding_blocks
179                             .next()
180                             .copied(),
181                     })
182                     .collect();
183                 (arm, arm_candidates)
184             })
185             .collect()
186     }
187
188     /// Create the decision tree for the match expression, starting from `block`.
189     ///
190     /// Modifies `candidates` to store the bindings and type ascriptions for
191     /// that candidate.
192     ///
193     /// Returns the places that need fake borrows because we bind or test them.
194     fn lower_match_tree<'pat>(
195         &mut self,
196         block: BasicBlock,
197         scrutinee_span: Span,
198         match_has_guard: bool,
199         mut candidates: Vec<&mut Candidate<'pat, 'tcx>>,
200     ) -> Vec<(Place<'tcx>, Local)> {
201         // The set of places that we are creating fake borrows of. If there are
202         // no match guards then we don't need any fake borrows, so don't track
203         // them.
204         let mut fake_borrows = if match_has_guard { Some(FxHashSet::default()) } else { None };
205
206         // This will generate code to test scrutinee_place and
207         // branch to the appropriate arm block
208         self.match_candidates(
209             scrutinee_span,
210             &mut Some(block),
211             None,
212             &mut candidates,
213             &mut fake_borrows,
214         );
215
216         if let Some(ref borrows) = fake_borrows {
217             self.calculate_fake_borrows(borrows, scrutinee_span)
218         } else {
219             Vec::new()
220         }
221     }
222
223     /// Lower the bindings, guards and arm bodies of a `match` expression.
224     ///
225     /// The decision tree should have already been created
226     /// (by [Builder::lower_match_tree]).
227     ///
228     /// `outer_source_info` is the SourceInfo for the whole match.
229     fn lower_match_arms(
230         &mut self,
231         destination: &Place<'tcx>,
232         scrutinee_place: Place<'tcx>,
233         scrutinee_span: Span,
234         arm_candidates: Vec<(&'_ Arm<'tcx>, Vec<Candidate<'_, 'tcx>>)>,
235         outer_source_info: SourceInfo,
236         fake_borrow_temps: Vec<(Place<'tcx>, Local)>,
237     ) -> BlockAnd<()> {
238         let match_scope = self.scopes.topmost();
239
240         let arm_end_blocks: Vec<_> = arm_candidates
241             .into_iter()
242             .map(|(arm, candidates)| {
243                 debug!("lowering arm {:?}\ncanidates = {:?}", arm, candidates);
244
245                 let arm_source_info = self.source_info(arm.span);
246                 let arm_scope = (arm.scope, arm_source_info);
247                 self.in_scope(arm_scope, arm.lint_level, |this| {
248                     let body = this.hir.mirror(arm.body.clone());
249                     let scope = this.declare_bindings(
250                         None,
251                         arm.span,
252                         &arm.top_pats_hack()[0],
253                         ArmHasGuard(arm.guard.is_some()),
254                         Some((Some(&scrutinee_place), scrutinee_span)),
255                     );
256
257                     let arm_block = this.bind_pattern(
258                         outer_source_info,
259                         candidates,
260                         arm.guard.as_ref().map(|g| (g, match_scope)),
261                         &fake_borrow_temps,
262                         scrutinee_span,
263                         arm.scope,
264                     );
265
266                     if let Some(source_scope) = scope {
267                         this.source_scope = source_scope;
268                     }
269
270                     this.into(destination, arm_block, body)
271                 })
272             })
273             .collect();
274
275         // all the arm blocks will rejoin here
276         let end_block = self.cfg.start_new_block();
277
278         for arm_block in arm_end_blocks {
279             self.cfg.goto(unpack!(arm_block), outer_source_info, end_block);
280         }
281
282         self.source_scope = outer_source_info.scope;
283
284         end_block.unit()
285     }
286
287     /// Binds the variables and ascribes types for a given `match` arm.
288     ///
289     /// Also check if the guard matches, if it's provided.
290     fn bind_pattern(
291         &mut self,
292         outer_source_info: SourceInfo,
293         mut candidates: Vec<Candidate<'_, 'tcx>>,
294         guard: Option<(&Guard<'tcx>, region::Scope)>,
295         fake_borrow_temps: &Vec<(Place<'tcx>, Local)>,
296         scrutinee_span: Span,
297         arm_scope: region::Scope,
298     ) -> BasicBlock {
299         if candidates.len() == 1 {
300             // Avoid generating another `BasicBlock` when we only have one
301             // candidate.
302             self.bind_and_guard_matched_candidate(
303                 candidates.pop().unwrap(),
304                 guard,
305                 fake_borrow_temps,
306                 scrutinee_span,
307             )
308         } else {
309             let arm_block = self.cfg.start_new_block();
310             for candidate in candidates {
311                 // Avoid scheduling drops multiple times.
312                 self.clear_top_scope(arm_scope);
313                 let binding_end = self.bind_and_guard_matched_candidate(
314                     candidate,
315                     guard,
316                     fake_borrow_temps,
317                     scrutinee_span,
318                 );
319                 self.cfg.goto(binding_end, outer_source_info, arm_block);
320             }
321             arm_block
322         }
323     }
324
325     pub(super) fn expr_into_pattern(
326         &mut self,
327         mut block: BasicBlock,
328         irrefutable_pat: Pat<'tcx>,
329         initializer: ExprRef<'tcx>,
330     ) -> BlockAnd<()> {
331         match *irrefutable_pat.kind {
332             // Optimize the case of `let x = ...` to write directly into `x`
333             PatKind::Binding { mode: BindingMode::ByValue, var, subpattern: None, .. } => {
334                 let place =
335                     self.storage_live_binding(block, var, irrefutable_pat.span, OutsideGuard);
336                 unpack!(block = self.into(&place, block, initializer));
337
338                 // Inject a fake read, see comments on `FakeReadCause::ForLet`.
339                 let source_info = self.source_info(irrefutable_pat.span);
340                 self.cfg.push_fake_read(block, source_info, FakeReadCause::ForLet, place);
341
342                 self.schedule_drop_for_binding(var, irrefutable_pat.span, OutsideGuard);
343                 block.unit()
344             }
345
346             // Optimize the case of `let x: T = ...` to write directly
347             // into `x` and then require that `T == typeof(x)`.
348             //
349             // Weirdly, this is needed to prevent the
350             // `intrinsic-move-val.rs` test case from crashing. That
351             // test works with uninitialized values in a rather
352             // dubious way, so it may be that the test is kind of
353             // broken.
354             PatKind::AscribeUserType {
355                 subpattern:
356                     Pat {
357                         kind:
358                             box PatKind::Binding {
359                                 mode: BindingMode::ByValue,
360                                 var,
361                                 subpattern: None,
362                                 ..
363                             },
364                         ..
365                     },
366                 ascription:
367                     hair::pattern::Ascription { user_ty: pat_ascription_ty, variance: _, user_ty_span },
368             } => {
369                 let place =
370                     self.storage_live_binding(block, var, irrefutable_pat.span, OutsideGuard);
371                 unpack!(block = self.into(&place, block, initializer));
372
373                 // Inject a fake read, see comments on `FakeReadCause::ForLet`.
374                 let pattern_source_info = self.source_info(irrefutable_pat.span);
375                 let cause_let = FakeReadCause::ForLet;
376                 self.cfg.push_fake_read(block, pattern_source_info, cause_let, place.clone());
377
378                 let ty_source_info = self.source_info(user_ty_span);
379                 let user_ty = pat_ascription_ty.user_ty(
380                     &mut self.canonical_user_type_annotations,
381                     place.ty(&self.local_decls, self.hir.tcx()).ty,
382                     ty_source_info.span,
383                 );
384                 self.cfg.push(
385                     block,
386                     Statement {
387                         source_info: ty_source_info,
388                         kind: StatementKind::AscribeUserType(
389                             box (place, user_ty),
390                             // We always use invariant as the variance here. This is because the
391                             // variance field from the ascription refers to the variance to use
392                             // when applying the type to the value being matched, but this
393                             // ascription applies rather to the type of the binding. e.g., in this
394                             // example:
395                             //
396                             // ```
397                             // let x: T = <expr>
398                             // ```
399                             //
400                             // We are creating an ascription that defines the type of `x` to be
401                             // exactly `T` (i.e., with invariance). The variance field, in
402                             // contrast, is intended to be used to relate `T` to the type of
403                             // `<expr>`.
404                             ty::Variance::Invariant,
405                         ),
406                     },
407                 );
408
409                 self.schedule_drop_for_binding(var, irrefutable_pat.span, OutsideGuard);
410                 block.unit()
411             }
412
413             _ => {
414                 let place = unpack!(block = self.as_place(block, initializer));
415                 self.place_into_pattern(block, irrefutable_pat, &place, true)
416             }
417         }
418     }
419
420     pub fn place_into_pattern(
421         &mut self,
422         block: BasicBlock,
423         irrefutable_pat: Pat<'tcx>,
424         initializer: &Place<'tcx>,
425         set_match_place: bool,
426     ) -> BlockAnd<()> {
427         // create a dummy candidate
428         let mut candidate = Candidate {
429             span: irrefutable_pat.span,
430             match_pairs: smallvec![MatchPair::new(initializer.clone(), &irrefutable_pat)],
431             bindings: vec![],
432             ascriptions: vec![],
433
434             // since we don't call `match_candidates`, next fields are unused
435             otherwise_block: None,
436             pre_binding_block: block,
437             next_candidate_pre_binding_block: None,
438         };
439
440         // Simplify the candidate. Since the pattern is irrefutable, this should
441         // always convert all match-pairs into bindings.
442         self.simplify_candidate(&mut candidate);
443
444         if !candidate.match_pairs.is_empty() {
445             // ICE if no other errors have been emitted. This used to be a hard error that wouldn't
446             // be reached because `hair::pattern::check_match::check_match` wouldn't have let the
447             // compiler continue. In our tests this is only ever hit by
448             // `ui/consts/const-match-check.rs` with `--cfg eval1`, and that file already generates
449             // a different error before hand.
450             self.hir.tcx().sess.delay_span_bug(
451                 candidate.match_pairs[0].pattern.span,
452                 &format!(
453                     "match pairs {:?} remaining after simplifying irrefutable pattern",
454                     candidate.match_pairs,
455                 ),
456             );
457         }
458
459         // for matches and function arguments, the place that is being matched
460         // can be set when creating the variables. But the place for
461         // let PATTERN = ... might not even exist until we do the assignment.
462         // so we set it here instead
463         if set_match_place {
464             for binding in &candidate.bindings {
465                 let local = self.var_local_id(binding.var_id, OutsideGuard);
466
467                 if let LocalInfo::User(ClearCrossCrate::Set(BindingForm::Var(VarBindingForm {
468                     opt_match_place: Some((ref mut match_place, _)),
469                     ..
470                 }))) = self.local_decls[local].local_info
471                 {
472                     *match_place = Some(initializer.clone());
473                 } else {
474                     bug!("Let binding to non-user variable.")
475                 }
476             }
477         }
478
479         self.ascribe_types(block, &candidate.ascriptions);
480
481         // now apply the bindings, which will also declare the variables
482         self.bind_matched_candidate_for_arm_body(block, &candidate.bindings);
483
484         block.unit()
485     }
486
487     /// Declares the bindings of the given patterns and returns the visibility
488     /// scope for the bindings in these patterns, if such a scope had to be
489     /// created. NOTE: Declaring the bindings should always be done in their
490     /// drop scope.
491     pub fn declare_bindings(
492         &mut self,
493         mut visibility_scope: Option<SourceScope>,
494         scope_span: Span,
495         pattern: &Pat<'tcx>,
496         has_guard: ArmHasGuard,
497         opt_match_place: Option<(Option<&Place<'tcx>>, Span)>,
498     ) -> Option<SourceScope> {
499         debug!("declare_bindings: pattern={:?}", pattern);
500         self.visit_bindings(
501             &pattern,
502             UserTypeProjections::none(),
503             &mut |this, mutability, name, mode, var, span, ty, user_ty| {
504                 if visibility_scope.is_none() {
505                     visibility_scope =
506                         Some(this.new_source_scope(scope_span, LintLevel::Inherited, None));
507                 }
508                 let source_info = SourceInfo { span, scope: this.source_scope };
509                 let visibility_scope = visibility_scope.unwrap();
510                 this.declare_binding(
511                     source_info,
512                     visibility_scope,
513                     mutability,
514                     name,
515                     mode,
516                     var,
517                     ty,
518                     user_ty,
519                     has_guard,
520                     opt_match_place.map(|(x, y)| (x.cloned(), y)),
521                     pattern.span,
522                 );
523             },
524         );
525         visibility_scope
526     }
527
528     pub fn storage_live_binding(
529         &mut self,
530         block: BasicBlock,
531         var: HirId,
532         span: Span,
533         for_guard: ForGuard,
534     ) -> Place<'tcx> {
535         let local_id = self.var_local_id(var, for_guard);
536         let source_info = self.source_info(span);
537         self.cfg.push(block, Statement { source_info, kind: StatementKind::StorageLive(local_id) });
538         let region_scope = self.hir.region_scope_tree.var_scope(var.local_id);
539         self.schedule_drop(span, region_scope, local_id, DropKind::Storage);
540         Place::from(local_id)
541     }
542
543     pub fn schedule_drop_for_binding(&mut self, var: HirId, span: Span, for_guard: ForGuard) {
544         let local_id = self.var_local_id(var, for_guard);
545         let region_scope = self.hir.region_scope_tree.var_scope(var.local_id);
546         self.schedule_drop(span, region_scope, local_id, DropKind::Value);
547     }
548
549     pub(super) fn visit_bindings(
550         &mut self,
551         pattern: &Pat<'tcx>,
552         pattern_user_ty: UserTypeProjections,
553         f: &mut impl FnMut(
554             &mut Self,
555             Mutability,
556             Name,
557             BindingMode,
558             HirId,
559             Span,
560             Ty<'tcx>,
561             UserTypeProjections,
562         ),
563     ) {
564         debug!("visit_bindings: pattern={:?} pattern_user_ty={:?}", pattern, pattern_user_ty);
565         match *pattern.kind {
566             PatKind::Binding { mutability, name, mode, var, ty, ref subpattern, .. } => {
567                 f(self, mutability, name, mode, var, pattern.span, ty, pattern_user_ty.clone());
568                 if let Some(subpattern) = subpattern.as_ref() {
569                     self.visit_bindings(subpattern, pattern_user_ty, f);
570                 }
571             }
572
573             PatKind::Array { ref prefix, ref slice, ref suffix }
574             | PatKind::Slice { ref prefix, ref slice, ref suffix } => {
575                 let from = u32::try_from(prefix.len()).unwrap();
576                 let to = u32::try_from(suffix.len()).unwrap();
577                 for subpattern in prefix {
578                     self.visit_bindings(subpattern, pattern_user_ty.clone().index(), f);
579                 }
580                 for subpattern in slice {
581                     self.visit_bindings(subpattern, pattern_user_ty.clone().subslice(from, to), f);
582                 }
583                 for subpattern in suffix {
584                     self.visit_bindings(subpattern, pattern_user_ty.clone().index(), f);
585                 }
586             }
587
588             PatKind::Constant { .. } | PatKind::Range { .. } | PatKind::Wild => {}
589
590             PatKind::Deref { ref subpattern } => {
591                 self.visit_bindings(subpattern, pattern_user_ty.deref(), f);
592             }
593
594             PatKind::AscribeUserType {
595                 ref subpattern,
596                 ascription: hair::pattern::Ascription { ref user_ty, user_ty_span, variance: _ },
597             } => {
598                 // This corresponds to something like
599                 //
600                 // ```
601                 // let A::<'a>(_): A<'static> = ...;
602                 // ```
603                 //
604                 // Note that the variance doesn't apply here, as we are tracking the effect
605                 // of `user_ty` on any bindings contained with subpattern.
606                 let annotation = CanonicalUserTypeAnnotation {
607                     span: user_ty_span,
608                     user_ty: user_ty.user_ty,
609                     inferred_ty: subpattern.ty,
610                 };
611                 let projection = UserTypeProjection {
612                     base: self.canonical_user_type_annotations.push(annotation),
613                     projs: Vec::new(),
614                 };
615                 let subpattern_user_ty = pattern_user_ty.push_projection(&projection, user_ty_span);
616                 self.visit_bindings(subpattern, subpattern_user_ty, f)
617             }
618
619             PatKind::Leaf { ref subpatterns } => {
620                 for subpattern in subpatterns {
621                     let subpattern_user_ty = pattern_user_ty.clone().leaf(subpattern.field);
622                     debug!("visit_bindings: subpattern_user_ty={:?}", subpattern_user_ty);
623                     self.visit_bindings(&subpattern.pattern, subpattern_user_ty, f);
624                 }
625             }
626
627             PatKind::Variant { adt_def, substs: _, variant_index, ref subpatterns } => {
628                 for subpattern in subpatterns {
629                     let subpattern_user_ty =
630                         pattern_user_ty.clone().variant(adt_def, variant_index, subpattern.field);
631                     self.visit_bindings(&subpattern.pattern, subpattern_user_ty, f);
632                 }
633             }
634             PatKind::Or { ref pats } => {
635                 for pat in pats {
636                     self.visit_bindings(&pat, pattern_user_ty.clone(), f);
637                 }
638             }
639         }
640     }
641 }
642
643 #[derive(Debug)]
644 pub struct Candidate<'pat, 'tcx> {
645     // span of the original pattern that gave rise to this candidate
646     span: Span,
647
648     // all of these must be satisfied...
649     match_pairs: SmallVec<[MatchPair<'pat, 'tcx>; 1]>,
650
651     // ...these bindings established...
652     bindings: Vec<Binding<'tcx>>,
653
654     // ...and these types asserted...
655     ascriptions: Vec<Ascription<'tcx>>,
656
657     // ...and the guard must be evaluated, if false branch to Block...
658     otherwise_block: Option<BasicBlock>,
659
660     // ...and the blocks for add false edges between candidates
661     pre_binding_block: BasicBlock,
662     next_candidate_pre_binding_block: Option<BasicBlock>,
663 }
664
665 #[derive(Clone, Debug)]
666 struct Binding<'tcx> {
667     span: Span,
668     source: Place<'tcx>,
669     name: Name,
670     var_id: HirId,
671     var_ty: Ty<'tcx>,
672     mutability: Mutability,
673     binding_mode: BindingMode,
674 }
675
676 /// Indicates that the type of `source` must be a subtype of the
677 /// user-given type `user_ty`; this is basically a no-op but can
678 /// influence region inference.
679 #[derive(Clone, Debug)]
680 struct Ascription<'tcx> {
681     span: Span,
682     source: Place<'tcx>,
683     user_ty: PatTyProj<'tcx>,
684     variance: ty::Variance,
685 }
686
687 #[derive(Clone, Debug)]
688 pub struct MatchPair<'pat, 'tcx> {
689     // this place...
690     place: Place<'tcx>,
691
692     // ... must match this pattern.
693     pattern: &'pat Pat<'tcx>,
694 }
695
696 #[derive(Clone, Debug, PartialEq)]
697 enum TestKind<'tcx> {
698     /// Test the branches of enum.
699     Switch {
700         /// The enum being tested
701         adt_def: &'tcx ty::AdtDef,
702         /// The set of variants that we should create a branch for. We also
703         /// create an additional "otherwise" case.
704         variants: BitSet<VariantIdx>,
705     },
706
707     /// Test what value an `integer`, `bool` or `char` has.
708     SwitchInt {
709         /// The type of the value that we're testing.
710         switch_ty: Ty<'tcx>,
711         /// The (ordered) set of values that we test for.
712         ///
713         /// For integers and `char`s we create a branch to each of the values in
714         /// `options`, as well as an "otherwise" branch for all other values, even
715         /// in the (rare) case that options is exhaustive.
716         ///
717         /// For `bool` we always generate two edges, one for `true` and one for
718         /// `false`.
719         options: Vec<u128>,
720         /// Reverse map used to ensure that the values in `options` are unique.
721         indices: FxHashMap<&'tcx ty::Const<'tcx>, usize>,
722     },
723
724     /// Test for equality with value, possibly after an unsizing coercion to
725     /// `ty`,
726     Eq {
727         value: &'tcx ty::Const<'tcx>,
728         // Integer types are handled by `SwitchInt`, and constants with ADT
729         // types are converted back into patterns, so this can only be `&str`,
730         // `&[T]`, `f32` or `f64`.
731         ty: Ty<'tcx>,
732     },
733
734     /// Test whether the value falls within an inclusive or exclusive range
735     Range(PatRange<'tcx>),
736
737     /// Test length of the slice is equal to len
738     Len { len: u64, op: BinOp },
739 }
740
741 #[derive(Debug)]
742 pub struct Test<'tcx> {
743     span: Span,
744     kind: TestKind<'tcx>,
745 }
746
747 /// ArmHasGuard is isomorphic to a boolean flag. It indicates whether
748 /// a match arm has a guard expression attached to it.
749 #[derive(Copy, Clone, Debug)]
750 pub(crate) struct ArmHasGuard(pub bool);
751
752 ///////////////////////////////////////////////////////////////////////////
753 // Main matching algorithm
754
755 impl<'a, 'tcx> Builder<'a, 'tcx> {
756     /// The main match algorithm. It begins with a set of candidates
757     /// `candidates` and has the job of generating code to determine
758     /// which of these candidates, if any, is the correct one. The
759     /// candidates are sorted such that the first item in the list
760     /// has the highest priority. When a candidate is found to match
761     /// the value, we will generate a branch to the appropriate
762     /// prebinding block.
763     ///
764     /// If we find that *NONE* of the candidates apply, we branch to the
765     /// `otherwise_block`. In principle, this means that the input list was not
766     /// exhaustive, though at present we sometimes are not smart enough to
767     /// recognize all exhaustive inputs.
768     ///
769     /// It might be surprising that the input can be inexhaustive.
770     /// Indeed, initially, it is not, because all matches are
771     /// exhaustive in Rust. But during processing we sometimes divide
772     /// up the list of candidates and recurse with a non-exhaustive
773     /// list. This is important to keep the size of the generated code
774     /// under control. See `test_candidates` for more details.
775     ///
776     /// If `fake_borrows` is Some, then places which need fake borrows
777     /// will be added to it.
778     fn match_candidates<'pat>(
779         &mut self,
780         span: Span,
781         start_block: &mut Option<BasicBlock>,
782         otherwise_block: Option<BasicBlock>,
783         candidates: &mut [&mut Candidate<'pat, 'tcx>],
784         fake_borrows: &mut Option<FxHashSet<Place<'tcx>>>,
785     ) {
786         debug!(
787             "matched_candidate(span={:?}, candidates={:?}, start_block={:?}, otherwise_block={:?})",
788             span, candidates, start_block, otherwise_block,
789         );
790
791         // Start by simplifying candidates. Once this process is complete, all
792         // the match pairs which remain require some form of test, whether it
793         // be a switch or pattern comparison.
794         for candidate in &mut *candidates {
795             self.simplify_candidate(candidate);
796         }
797
798         // The candidates are sorted by priority. Check to see whether the
799         // higher priority candidates (and hence at the front of the slice)
800         // have satisfied all their match pairs.
801         let fully_matched = candidates.iter().take_while(|c| c.match_pairs.is_empty()).count();
802         debug!("match_candidates: {:?} candidates fully matched", fully_matched);
803         let (matched_candidates, unmatched_candidates) = candidates.split_at_mut(fully_matched);
804
805         let block: BasicBlock = if !matched_candidates.is_empty() {
806             let otherwise_block =
807                 self.select_matched_candidates(matched_candidates, start_block, fake_borrows);
808
809             if let Some(last_otherwise_block) = otherwise_block {
810                 last_otherwise_block
811             } else {
812                 // Any remaining candidates are unreachable.
813                 if unmatched_candidates.is_empty() {
814                     return;
815                 }
816                 self.cfg.start_new_block()
817             }
818         } else {
819             *start_block.get_or_insert_with(|| self.cfg.start_new_block())
820         };
821
822         // If there are no candidates that still need testing, we're
823         // done. Since all matches are exhaustive, execution should
824         // never reach this point.
825         if unmatched_candidates.is_empty() {
826             let source_info = self.source_info(span);
827             match otherwise_block {
828                 Some(otherwise) => self.cfg.goto(block, source_info, otherwise),
829                 None => self.cfg.terminate(block, source_info, TerminatorKind::Unreachable),
830             }
831             return;
832         }
833
834         // Test for the remaining candidates.
835         self.test_candidates(span, unmatched_candidates, block, otherwise_block, fake_borrows);
836     }
837
838     /// Link up matched candidates. For example, if we have something like
839     /// this:
840     ///
841     /// ...
842     /// Some(x) if cond => ...
843     /// Some(x) => ...
844     /// Some(x) if cond => ...
845     /// ...
846     ///
847     /// We generate real edges from:
848     /// * `start_block` to the `prebinding_block` of the first pattern,
849     /// * the otherwise block of the first pattern to the second pattern,
850     /// * the otherwise block of the third pattern to the a block with an
851     ///   Unreachable terminator.
852     ///
853     /// As well as that we add fake edges from the otherwise blocks to the
854     /// prebinding block of the next candidate in the original set of
855     /// candidates.
856     fn select_matched_candidates(
857         &mut self,
858         matched_candidates: &mut [&mut Candidate<'_, 'tcx>],
859         start_block: &mut Option<BasicBlock>,
860         fake_borrows: &mut Option<FxHashSet<Place<'tcx>>>,
861     ) -> Option<BasicBlock> {
862         debug_assert!(
863             !matched_candidates.is_empty(),
864             "select_matched_candidates called with no candidates",
865         );
866
867         // Insert a borrows of prefixes of places that are bound and are
868         // behind a dereference projection.
869         //
870         // These borrows are taken to avoid situations like the following:
871         //
872         // match x[10] {
873         //     _ if { x = &[0]; false } => (),
874         //     y => (), // Out of bounds array access!
875         // }
876         //
877         // match *x {
878         //     // y is bound by reference in the guard and then by copy in the
879         //     // arm, so y is 2 in the arm!
880         //     y if { y == 1 && (x = &2) == () } => y,
881         //     _ => 3,
882         // }
883         if let Some(fake_borrows) = fake_borrows {
884             for Binding { source, .. } in
885                 matched_candidates.iter().flat_map(|candidate| &candidate.bindings)
886             {
887                 if let Some(i) =
888                     source.projection.iter().rposition(|elem| *elem == ProjectionElem::Deref)
889                 {
890                     let proj_base = &source.projection[..i];
891
892                     fake_borrows.insert(Place {
893                         local: source.local.clone(),
894                         projection: self.hir.tcx().intern_place_elems(proj_base),
895                     });
896                 }
897             }
898         }
899
900         let fully_matched_with_guard = matched_candidates
901             .iter()
902             .position(|c| c.otherwise_block.is_none())
903             .unwrap_or(matched_candidates.len() - 1);
904
905         let (reachable_candidates, unreachable_candidates) =
906             matched_candidates.split_at_mut(fully_matched_with_guard + 1);
907
908         let first_candidate = &reachable_candidates[0];
909         let first_prebinding_block = first_candidate.pre_binding_block;
910
911         // `goto -> first_prebinding_block` from the `start_block` if there is one.
912         if let Some(start_block) = *start_block {
913             let source_info = self.source_info(first_candidate.span);
914             self.cfg.goto(start_block, source_info, first_prebinding_block);
915         } else {
916             *start_block = Some(first_prebinding_block);
917         }
918
919         for (first_candidate, second_candidate) in reachable_candidates.iter().tuple_windows() {
920             let source_info = self.source_info(first_candidate.span);
921             if let Some(otherwise_block) = first_candidate.otherwise_block {
922                 self.false_edges(
923                     otherwise_block,
924                     second_candidate.pre_binding_block,
925                     first_candidate.next_candidate_pre_binding_block,
926                     source_info,
927                 );
928             } else {
929                 bug!("candidate other than the last has no guard");
930             }
931         }
932
933         debug!("match_candidates: add false edges for unreachable {:?}", unreachable_candidates);
934         for candidate in unreachable_candidates {
935             if let Some(otherwise) = candidate.otherwise_block {
936                 let source_info = self.source_info(candidate.span);
937                 let unreachable = self.cfg.start_new_block();
938                 self.false_edges(
939                     otherwise,
940                     unreachable,
941                     candidate.next_candidate_pre_binding_block,
942                     source_info,
943                 );
944                 self.cfg.terminate(unreachable, source_info, TerminatorKind::Unreachable);
945             }
946         }
947
948         let last_candidate = reachable_candidates.last().unwrap();
949         if let Some(otherwise) = last_candidate.otherwise_block {
950             let source_info = self.source_info(last_candidate.span);
951             let block = self.cfg.start_new_block();
952             self.false_edges(
953                 otherwise,
954                 block,
955                 last_candidate.next_candidate_pre_binding_block,
956                 source_info,
957             );
958             Some(block)
959         } else {
960             None
961         }
962     }
963
964     /// This is the most subtle part of the matching algorithm. At
965     /// this point, the input candidates have been fully simplified,
966     /// and so we know that all remaining match-pairs require some
967     /// sort of test. To decide what test to do, we take the highest
968     /// priority candidate (last one in the list) and extract the
969     /// first match-pair from the list. From this we decide what kind
970     /// of test is needed using `test`, defined in the `test` module.
971     ///
972     /// *Note:* taking the first match pair is somewhat arbitrary, and
973     /// we might do better here by choosing more carefully what to
974     /// test.
975     ///
976     /// For example, consider the following possible match-pairs:
977     ///
978     /// 1. `x @ Some(P)` -- we will do a `Switch` to decide what variant `x` has
979     /// 2. `x @ 22` -- we will do a `SwitchInt`
980     /// 3. `x @ 3..5` -- we will do a range test
981     /// 4. etc.
982     ///
983     /// Once we know what sort of test we are going to perform, this
984     /// Tests may also help us with other candidates. So we walk over
985     /// the candidates (from high to low priority) and check. This
986     /// gives us, for each outcome of the test, a transformed list of
987     /// candidates. For example, if we are testing the current
988     /// variant of `x.0`, and we have a candidate `{x.0 @ Some(v), x.1
989     /// @ 22}`, then we would have a resulting candidate of `{(x.0 as
990     /// Some).0 @ v, x.1 @ 22}`. Note that the first match-pair is now
991     /// simpler (and, in fact, irrefutable).
992     ///
993     /// But there may also be candidates that the test just doesn't
994     /// apply to. The classical example involves wildcards:
995     ///
996     /// ```
997     /// # let (x, y, z) = (true, true, true);
998     /// match (x, y, z) {
999     ///     (true, _, true) => true,    // (0)
1000     ///     (_, true, _) => true,       // (1)
1001     ///     (false, false, _) => false, // (2)
1002     ///     (true, _, false) => false,  // (3)
1003     /// }
1004     /// ```
1005     ///
1006     /// In that case, after we test on `x`, there are 2 overlapping candidate
1007     /// sets:
1008     ///
1009     /// - If the outcome is that `x` is true, candidates 0, 1, and 3
1010     /// - If the outcome is that `x` is false, candidates 1 and 2
1011     ///
1012     /// Here, the traditional "decision tree" method would generate 2
1013     /// separate code-paths for the 2 separate cases.
1014     ///
1015     /// In some cases, this duplication can create an exponential amount of
1016     /// code. This is most easily seen by noticing that this method terminates
1017     /// with precisely the reachable arms being reachable - but that problem
1018     /// is trivially NP-complete:
1019     ///
1020     /// ```rust
1021     ///     match (var0, var1, var2, var3, ..) {
1022     ///         (true, _, _, false, true, ...) => false,
1023     ///         (_, true, true, false, _, ...) => false,
1024     ///         (false, _, false, false, _, ...) => false,
1025     ///         ...
1026     ///         _ => true
1027     ///     }
1028     /// ```
1029     ///
1030     /// Here the last arm is reachable only if there is an assignment to
1031     /// the variables that does not match any of the literals. Therefore,
1032     /// compilation would take an exponential amount of time in some cases.
1033     ///
1034     /// That kind of exponential worst-case might not occur in practice, but
1035     /// our simplistic treatment of constants and guards would make it occur
1036     /// in very common situations - for example #29740:
1037     ///
1038     /// ```rust
1039     /// match x {
1040     ///     "foo" if foo_guard => ...,
1041     ///     "bar" if bar_guard => ...,
1042     ///     "baz" if baz_guard => ...,
1043     ///     ...
1044     /// }
1045     /// ```
1046     ///
1047     /// Here we first test the match-pair `x @ "foo"`, which is an `Eq` test.
1048     ///
1049     /// It might seem that we would end up with 2 disjoint candidate
1050     /// sets, consisting of the first candidate or the other 3, but our
1051     /// algorithm doesn't reason about "foo" being distinct from the other
1052     /// constants; it considers the latter arms to potentially match after
1053     /// both outcomes, which obviously leads to an exponential amount
1054     /// of tests.
1055     ///
1056     /// To avoid these kinds of problems, our algorithm tries to ensure
1057     /// the amount of generated tests is linear. When we do a k-way test,
1058     /// we return an additional "unmatched" set alongside the obvious `k`
1059     /// sets. When we encounter a candidate that would be present in more
1060     /// than one of the sets, we put it and all candidates below it into the
1061     /// "unmatched" set. This ensures these `k+1` sets are disjoint.
1062     ///
1063     /// After we perform our test, we branch into the appropriate candidate
1064     /// set and recurse with `match_candidates`. These sub-matches are
1065     /// obviously inexhaustive - as we discarded our otherwise set - so
1066     /// we set their continuation to do `match_candidates` on the
1067     /// "unmatched" set (which is again inexhaustive).
1068     ///
1069     /// If you apply this to the above test, you basically wind up
1070     /// with an if-else-if chain, testing each candidate in turn,
1071     /// which is precisely what we want.
1072     ///
1073     /// In addition to avoiding exponential-time blowups, this algorithm
1074     /// also has nice property that each guard and arm is only generated
1075     /// once.
1076     fn test_candidates<'pat, 'b, 'c>(
1077         &mut self,
1078         span: Span,
1079         mut candidates: &'b mut [&'c mut Candidate<'pat, 'tcx>],
1080         block: BasicBlock,
1081         mut otherwise_block: Option<BasicBlock>,
1082         fake_borrows: &mut Option<FxHashSet<Place<'tcx>>>,
1083     ) {
1084         // extract the match-pair from the highest priority candidate
1085         let match_pair = &candidates.first().unwrap().match_pairs[0];
1086         let mut test = self.test(match_pair);
1087         let match_place = match_pair.place.clone();
1088
1089         // most of the time, the test to perform is simply a function
1090         // of the main candidate; but for a test like SwitchInt, we
1091         // may want to add cases based on the candidates that are
1092         // available
1093         match test.kind {
1094             TestKind::SwitchInt { switch_ty, ref mut options, ref mut indices } => {
1095                 for candidate in candidates.iter() {
1096                     if !self.add_cases_to_switch(
1097                         &match_place,
1098                         candidate,
1099                         switch_ty,
1100                         options,
1101                         indices,
1102                     ) {
1103                         break;
1104                     }
1105                 }
1106             }
1107             TestKind::Switch { adt_def: _, ref mut variants } => {
1108                 for candidate in candidates.iter() {
1109                     if !self.add_variants_to_switch(&match_place, candidate, variants) {
1110                         break;
1111                     }
1112                 }
1113             }
1114             _ => {}
1115         }
1116
1117         // Insert a Shallow borrow of any places that is switched on.
1118         fake_borrows.as_mut().map(|fb| fb.insert(match_place.clone()));
1119
1120         // perform the test, branching to one of N blocks. For each of
1121         // those N possible outcomes, create a (initially empty)
1122         // vector of candidates. Those are the candidates that still
1123         // apply if the test has that particular outcome.
1124         debug!("match_candidates: test={:?} match_pair={:?}", test, match_pair);
1125         let mut target_candidates: Vec<Vec<&mut Candidate<'pat, 'tcx>>> = vec![];
1126         target_candidates.resize_with(test.targets(), Default::default);
1127
1128         let total_candidate_count = candidates.len();
1129
1130         // Sort the candidates into the appropriate vector in
1131         // `target_candidates`. Note that at some point we may
1132         // encounter a candidate where the test is not relevant; at
1133         // that point, we stop sorting.
1134         while let Some(candidate) = candidates.first_mut() {
1135             if let Some(idx) = self.sort_candidate(&match_place, &test, candidate) {
1136                 let (candidate, rest) = candidates.split_first_mut().unwrap();
1137                 target_candidates[idx].push(candidate);
1138                 candidates = rest;
1139             } else {
1140                 break;
1141             }
1142         }
1143         // at least the first candidate ought to be tested
1144         assert!(total_candidate_count > candidates.len());
1145         debug!("tested_candidates: {}", total_candidate_count - candidates.len());
1146         debug!("untested_candidates: {}", candidates.len());
1147
1148         // HACK(matthewjasper) This is a closure so that we can let the test
1149         // create its blocks before the rest of the match. This currently
1150         // improves the speed of llvm when optimizing long string literal
1151         // matches
1152         let make_target_blocks = move |this: &mut Self| -> Vec<BasicBlock> {
1153             // For each outcome of test, process the candidates that still
1154             // apply. Collect a list of blocks where control flow will
1155             // branch if one of the `target_candidate` sets is not
1156             // exhaustive.
1157             if !candidates.is_empty() {
1158                 let remainder_start = &mut None;
1159                 this.match_candidates(
1160                     span,
1161                     remainder_start,
1162                     otherwise_block,
1163                     candidates,
1164                     fake_borrows,
1165                 );
1166                 otherwise_block = Some(remainder_start.unwrap());
1167             };
1168
1169             target_candidates
1170                 .into_iter()
1171                 .map(|mut candidates| {
1172                     if candidates.len() != 0 {
1173                         let candidate_start = &mut None;
1174                         this.match_candidates(
1175                             span,
1176                             candidate_start,
1177                             otherwise_block,
1178                             &mut *candidates,
1179                             fake_borrows,
1180                         );
1181                         candidate_start.unwrap()
1182                     } else {
1183                         *otherwise_block.get_or_insert_with(|| {
1184                             let unreachable = this.cfg.start_new_block();
1185                             let source_info = this.source_info(span);
1186                             this.cfg.terminate(
1187                                 unreachable,
1188                                 source_info,
1189                                 TerminatorKind::Unreachable,
1190                             );
1191                             unreachable
1192                         })
1193                     }
1194                 })
1195                 .collect()
1196         };
1197
1198         self.perform_test(block, &match_place, &test, make_target_blocks);
1199     }
1200
1201     /// Determine the fake borrows that are needed from a set of places that
1202     /// have to be stable across match guards.
1203     ///
1204     /// Returns a list of places that need a fake borrow and the temporary
1205     /// that's used to store the fake borrow.
1206     ///
1207     /// Match exhaustiveness checking is not able to handle the case where the
1208     /// place being matched on is mutated in the guards. We add "fake borrows"
1209     /// to the guards that prevent any mutation of the place being matched.
1210     /// There are a some subtleties:
1211     ///
1212     /// 1. Borrowing `*x` doesn't prevent assigning to `x`. If `x` is a shared
1213     ///    reference, the borrow isn't even tracked. As such we have to add fake
1214     ///    borrows of any prefixes of a place
1215     /// 2. We don't want `match x { _ => (), }` to conflict with mutable
1216     ///    borrows of `x`, so we only add fake borrows for places which are
1217     ///    bound or tested by the match.
1218     /// 3. We don't want the fake borrows to conflict with `ref mut` bindings,
1219     ///    so we use a special BorrowKind for them.
1220     /// 4. The fake borrows may be of places in inactive variants, so it would
1221     ///    be UB to generate code for them. They therefore have to be removed
1222     ///    by a MIR pass run after borrow checking.
1223     fn calculate_fake_borrows<'b>(
1224         &mut self,
1225         fake_borrows: &'b FxHashSet<Place<'tcx>>,
1226         temp_span: Span,
1227     ) -> Vec<(Place<'tcx>, Local)> {
1228         let tcx = self.hir.tcx();
1229
1230         debug!("add_fake_borrows fake_borrows = {:?}", fake_borrows);
1231
1232         let mut all_fake_borrows = Vec::with_capacity(fake_borrows.len());
1233
1234         // Insert a Shallow borrow of the prefixes of any fake borrows.
1235         for place in fake_borrows {
1236             let mut cursor = place.projection.as_ref();
1237             while let [proj_base @ .., elem] = cursor {
1238                 cursor = proj_base;
1239
1240                 if let ProjectionElem::Deref = elem {
1241                     // Insert a shallow borrow after a deref. For other
1242                     // projections the borrow of prefix_cursor will
1243                     // conflict with any mutation of base.
1244                     all_fake_borrows.push(PlaceRef { local: &place.local, projection: proj_base });
1245                 }
1246             }
1247
1248             all_fake_borrows.push(place.as_ref());
1249         }
1250
1251         // Deduplicate and ensure a deterministic order.
1252         all_fake_borrows.sort();
1253         all_fake_borrows.dedup();
1254
1255         debug!("add_fake_borrows all_fake_borrows = {:?}", all_fake_borrows);
1256
1257         all_fake_borrows
1258             .into_iter()
1259             .map(|matched_place_ref| {
1260                 let matched_place = Place {
1261                     local: matched_place_ref.local.clone(),
1262                     projection: tcx.intern_place_elems(matched_place_ref.projection),
1263                 };
1264                 let fake_borrow_deref_ty = matched_place.ty(&self.local_decls, tcx).ty;
1265                 let fake_borrow_ty = tcx.mk_imm_ref(tcx.lifetimes.re_erased, fake_borrow_deref_ty);
1266                 let fake_borrow_temp =
1267                     self.local_decls.push(LocalDecl::new_temp(fake_borrow_ty, temp_span));
1268
1269                 (matched_place, fake_borrow_temp)
1270             })
1271             .collect()
1272     }
1273 }
1274
1275 ///////////////////////////////////////////////////////////////////////////
1276 // Pat binding - used for `let` and function parameters as well.
1277
1278 impl<'a, 'tcx> Builder<'a, 'tcx> {
1279     /// Initializes each of the bindings from the candidate by
1280     /// moving/copying/ref'ing the source as appropriate. Tests the guard, if
1281     /// any, and then branches to the arm. Returns the block for the case where
1282     /// the guard fails.
1283     ///
1284     /// Note: we do not check earlier that if there is a guard,
1285     /// there cannot be move bindings. We avoid a use-after-move by only
1286     /// moving the binding once the guard has evaluated to true (see below).
1287     fn bind_and_guard_matched_candidate<'pat>(
1288         &mut self,
1289         candidate: Candidate<'pat, 'tcx>,
1290         guard: Option<(&Guard<'tcx>, region::Scope)>,
1291         fake_borrows: &Vec<(Place<'tcx>, Local)>,
1292         scrutinee_span: Span,
1293     ) -> BasicBlock {
1294         debug!("bind_and_guard_matched_candidate(candidate={:?})", candidate);
1295
1296         debug_assert!(candidate.match_pairs.is_empty());
1297
1298         let candidate_source_info = self.source_info(candidate.span);
1299
1300         let mut block = candidate.pre_binding_block;
1301
1302         // If we are adding our own statements, then we need a fresh block.
1303         let create_fresh_block = candidate.next_candidate_pre_binding_block.is_some()
1304             || !candidate.bindings.is_empty()
1305             || !candidate.ascriptions.is_empty()
1306             || guard.is_some();
1307
1308         if create_fresh_block {
1309             let fresh_block = self.cfg.start_new_block();
1310             self.false_edges(
1311                 block,
1312                 fresh_block,
1313                 candidate.next_candidate_pre_binding_block,
1314                 candidate_source_info,
1315             );
1316             block = fresh_block;
1317             self.ascribe_types(block, &candidate.ascriptions);
1318         } else {
1319             return block;
1320         }
1321
1322         // rust-lang/rust#27282: The `autoref` business deserves some
1323         // explanation here.
1324         //
1325         // The intent of the `autoref` flag is that when it is true,
1326         // then any pattern bindings of type T will map to a `&T`
1327         // within the context of the guard expression, but will
1328         // continue to map to a `T` in the context of the arm body. To
1329         // avoid surfacing this distinction in the user source code
1330         // (which would be a severe change to the language and require
1331         // far more revision to the compiler), when `autoref` is true,
1332         // then any occurrence of the identifier in the guard
1333         // expression will automatically get a deref op applied to it.
1334         //
1335         // So an input like:
1336         //
1337         // ```
1338         // let place = Foo::new();
1339         // match place { foo if inspect(foo)
1340         //     => feed(foo), ...  }
1341         // ```
1342         //
1343         // will be treated as if it were really something like:
1344         //
1345         // ```
1346         // let place = Foo::new();
1347         // match place { Foo { .. } if { let tmp1 = &place; inspect(*tmp1) }
1348         //     => { let tmp2 = place; feed(tmp2) }, ... }
1349         //
1350         // And an input like:
1351         //
1352         // ```
1353         // let place = Foo::new();
1354         // match place { ref mut foo if inspect(foo)
1355         //     => feed(foo), ...  }
1356         // ```
1357         //
1358         // will be treated as if it were really something like:
1359         //
1360         // ```
1361         // let place = Foo::new();
1362         // match place { Foo { .. } if { let tmp1 = & &mut place; inspect(*tmp1) }
1363         //     => { let tmp2 = &mut place; feed(tmp2) }, ... }
1364         // ```
1365         //
1366         // In short, any pattern binding will always look like *some*
1367         // kind of `&T` within the guard at least in terms of how the
1368         // MIR-borrowck views it, and this will ensure that guard
1369         // expressions cannot mutate their the match inputs via such
1370         // bindings. (It also ensures that guard expressions can at
1371         // most *copy* values from such bindings; non-Copy things
1372         // cannot be moved via pattern bindings in guard expressions.)
1373         //
1374         // ----
1375         //
1376         // Implementation notes (under assumption `autoref` is true).
1377         //
1378         // To encode the distinction above, we must inject the
1379         // temporaries `tmp1` and `tmp2`.
1380         //
1381         // There are two cases of interest: binding by-value, and binding by-ref.
1382         //
1383         // 1. Binding by-value: Things are simple.
1384         //
1385         //    * Establishing `tmp1` creates a reference into the
1386         //      matched place. This code is emitted by
1387         //      bind_matched_candidate_for_guard.
1388         //
1389         //    * `tmp2` is only initialized "lazily", after we have
1390         //      checked the guard. Thus, the code that can trigger
1391         //      moves out of the candidate can only fire after the
1392         //      guard evaluated to true. This initialization code is
1393         //      emitted by bind_matched_candidate_for_arm.
1394         //
1395         // 2. Binding by-reference: Things are tricky.
1396         //
1397         //    * Here, the guard expression wants a `&&` or `&&mut`
1398         //      into the original input. This means we need to borrow
1399         //      the reference that we create for the arm.
1400         //    * So we eagerly create the reference for the arm and then take a
1401         //      reference to that.
1402         if let Some((guard, region_scope)) = guard {
1403             let tcx = self.hir.tcx();
1404
1405             self.bind_matched_candidate_for_guard(block, &candidate.bindings);
1406             let guard_frame = GuardFrame {
1407                 locals: candidate
1408                     .bindings
1409                     .iter()
1410                     .map(|b| GuardFrameLocal::new(b.var_id, b.binding_mode))
1411                     .collect(),
1412             };
1413             debug!("entering guard building context: {:?}", guard_frame);
1414             self.guard_context.push(guard_frame);
1415
1416             let re_erased = tcx.lifetimes.re_erased;
1417             let scrutinee_source_info = self.source_info(scrutinee_span);
1418             for (place, temp) in fake_borrows {
1419                 let borrow = Rvalue::Ref(re_erased, BorrowKind::Shallow, place.clone());
1420                 self.cfg.push_assign(block, scrutinee_source_info, &Place::from(*temp), borrow);
1421             }
1422
1423             // the block to branch to if the guard fails; if there is no
1424             // guard, this block is simply unreachable
1425             let guard = match guard {
1426                 Guard::If(e) => self.hir.mirror(e.clone()),
1427             };
1428             let source_info = self.source_info(guard.span);
1429             let guard_end = self.source_info(tcx.sess.source_map().end_point(guard.span));
1430             let (post_guard_block, otherwise_post_guard_block) =
1431                 self.test_bool(block, guard, source_info);
1432             let guard_frame = self.guard_context.pop().unwrap();
1433             debug!("Exiting guard building context with locals: {:?}", guard_frame);
1434
1435             for &(_, temp) in fake_borrows {
1436                 let cause = FakeReadCause::ForMatchGuard;
1437                 self.cfg.push_fake_read(post_guard_block, guard_end, cause, Place::from(temp));
1438             }
1439
1440             self.exit_scope(
1441                 source_info.span,
1442                 region_scope,
1443                 otherwise_post_guard_block,
1444                 candidate.otherwise_block.unwrap(),
1445             );
1446
1447             // We want to ensure that the matched candidates are bound
1448             // after we have confirmed this candidate *and* any
1449             // associated guard; Binding them on `block` is too soon,
1450             // because that would be before we've checked the result
1451             // from the guard.
1452             //
1453             // But binding them on the arm is *too late*, because
1454             // then all of the candidates for a single arm would be
1455             // bound in the same place, that would cause a case like:
1456             //
1457             // ```rust
1458             // match (30, 2) {
1459             //     (mut x, 1) | (2, mut x) if { true } => { ... }
1460             //     ...                                 // ^^^^^^^ (this is `arm_block`)
1461             // }
1462             // ```
1463             //
1464             // would yield a `arm_block` something like:
1465             //
1466             // ```
1467             // StorageLive(_4);        // _4 is `x`
1468             // _4 = &mut (_1.0: i32);  // this is handling `(mut x, 1)` case
1469             // _4 = &mut (_1.1: i32);  // this is handling `(2, mut x)` case
1470             // ```
1471             //
1472             // and that is clearly not correct.
1473             let by_value_bindings = candidate.bindings.iter().filter(|binding| {
1474                 if let BindingMode::ByValue = binding.binding_mode { true } else { false }
1475             });
1476             // Read all of the by reference bindings to ensure that the
1477             // place they refer to can't be modified by the guard.
1478             for binding in by_value_bindings.clone() {
1479                 let local_id = self.var_local_id(binding.var_id, RefWithinGuard);
1480                 let cause = FakeReadCause::ForGuardBinding;
1481                 self.cfg.push_fake_read(post_guard_block, guard_end, cause, Place::from(local_id));
1482             }
1483             self.bind_matched_candidate_for_arm_body(post_guard_block, by_value_bindings);
1484
1485             post_guard_block
1486         } else {
1487             assert!(candidate.otherwise_block.is_none());
1488             // (Here, it is not too early to bind the matched
1489             // candidate on `block`, because there is no guard result
1490             // that we have to inspect before we bind them.)
1491             self.bind_matched_candidate_for_arm_body(block, &candidate.bindings);
1492             block
1493         }
1494     }
1495
1496     /// Append `AscribeUserType` statements onto the end of `block`
1497     /// for each ascription
1498     fn ascribe_types(&mut self, block: BasicBlock, ascriptions: &[Ascription<'tcx>]) {
1499         for ascription in ascriptions {
1500             let source_info = self.source_info(ascription.span);
1501
1502             debug!(
1503                 "adding user ascription at span {:?} of place {:?} and {:?}",
1504                 source_info.span, ascription.source, ascription.user_ty,
1505             );
1506
1507             let user_ty = ascription.user_ty.clone().user_ty(
1508                 &mut self.canonical_user_type_annotations,
1509                 ascription.source.ty(&self.local_decls, self.hir.tcx()).ty,
1510                 source_info.span,
1511             );
1512             self.cfg.push(
1513                 block,
1514                 Statement {
1515                     source_info,
1516                     kind: StatementKind::AscribeUserType(
1517                         box (ascription.source.clone(), user_ty),
1518                         ascription.variance,
1519                     ),
1520                 },
1521             );
1522         }
1523     }
1524
1525     fn bind_matched_candidate_for_guard(&mut self, block: BasicBlock, bindings: &[Binding<'tcx>]) {
1526         debug!("bind_matched_candidate_for_guard(block={:?}, bindings={:?})", block, bindings);
1527
1528         // Assign each of the bindings. Since we are binding for a
1529         // guard expression, this will never trigger moves out of the
1530         // candidate.
1531         let re_erased = self.hir.tcx().lifetimes.re_erased;
1532         for binding in bindings {
1533             let source_info = self.source_info(binding.span);
1534
1535             // For each pattern ident P of type T, `ref_for_guard` is
1536             // a reference R: &T pointing to the location matched by
1537             // the pattern, and every occurrence of P within a guard
1538             // denotes *R.
1539             let ref_for_guard =
1540                 self.storage_live_binding(block, binding.var_id, binding.span, RefWithinGuard);
1541             match binding.binding_mode {
1542                 BindingMode::ByValue => {
1543                     let rvalue = Rvalue::Ref(re_erased, BorrowKind::Shared, binding.source.clone());
1544                     self.cfg.push_assign(block, source_info, &ref_for_guard, rvalue);
1545                 }
1546                 BindingMode::ByRef(borrow_kind) => {
1547                     let value_for_arm = self.storage_live_binding(
1548                         block,
1549                         binding.var_id,
1550                         binding.span,
1551                         OutsideGuard,
1552                     );
1553
1554                     let rvalue = Rvalue::Ref(re_erased, borrow_kind, binding.source.clone());
1555                     self.cfg.push_assign(block, source_info, &value_for_arm, rvalue);
1556                     let rvalue = Rvalue::Ref(re_erased, BorrowKind::Shared, value_for_arm);
1557                     self.cfg.push_assign(block, source_info, &ref_for_guard, rvalue);
1558                 }
1559             }
1560         }
1561     }
1562
1563     fn bind_matched_candidate_for_arm_body<'b>(
1564         &mut self,
1565         block: BasicBlock,
1566         bindings: impl IntoIterator<Item = &'b Binding<'tcx>>,
1567     ) where
1568         'tcx: 'b,
1569     {
1570         debug!("bind_matched_candidate_for_arm_body(block={:?})", block);
1571
1572         let re_erased = self.hir.tcx().lifetimes.re_erased;
1573         // Assign each of the bindings. This may trigger moves out of the candidate.
1574         for binding in bindings {
1575             let source_info = self.source_info(binding.span);
1576             let local =
1577                 self.storage_live_binding(block, binding.var_id, binding.span, OutsideGuard);
1578             self.schedule_drop_for_binding(binding.var_id, binding.span, OutsideGuard);
1579             let rvalue = match binding.binding_mode {
1580                 BindingMode::ByValue => {
1581                     Rvalue::Use(self.consume_by_copy_or_move(binding.source.clone()))
1582                 }
1583                 BindingMode::ByRef(borrow_kind) => {
1584                     Rvalue::Ref(re_erased, borrow_kind, binding.source.clone())
1585                 }
1586             };
1587             self.cfg.push_assign(block, source_info, &local, rvalue);
1588         }
1589     }
1590
1591     /// Each binding (`ref mut var`/`ref var`/`mut var`/`var`, where the bound
1592     /// `var` has type `T` in the arm body) in a pattern maps to 2 locals. The
1593     /// first local is a binding for occurrences of `var` in the guard, which
1594     /// will have type `&T`. The second local is a binding for occurrences of
1595     /// `var` in the arm body, which will have type `T`.
1596     fn declare_binding(
1597         &mut self,
1598         source_info: SourceInfo,
1599         visibility_scope: SourceScope,
1600         mutability: Mutability,
1601         name: Name,
1602         mode: BindingMode,
1603         var_id: HirId,
1604         var_ty: Ty<'tcx>,
1605         user_ty: UserTypeProjections,
1606         has_guard: ArmHasGuard,
1607         opt_match_place: Option<(Option<Place<'tcx>>, Span)>,
1608         pat_span: Span,
1609     ) {
1610         debug!(
1611             "declare_binding(var_id={:?}, name={:?}, mode={:?}, var_ty={:?}, \
1612              visibility_scope={:?}, source_info={:?})",
1613             var_id, name, mode, var_ty, visibility_scope, source_info
1614         );
1615
1616         let tcx = self.hir.tcx();
1617         let debug_source_info = SourceInfo { span: source_info.span, scope: visibility_scope };
1618         let binding_mode = match mode {
1619             BindingMode::ByValue => ty::BindingMode::BindByValue(mutability.into()),
1620             BindingMode::ByRef(_) => ty::BindingMode::BindByReference(mutability.into()),
1621         };
1622         debug!("declare_binding: user_ty={:?}", user_ty);
1623         let local = LocalDecl::<'tcx> {
1624             mutability,
1625             ty: var_ty,
1626             user_ty,
1627             source_info,
1628             internal: false,
1629             is_block_tail: None,
1630             local_info: LocalInfo::User(ClearCrossCrate::Set(BindingForm::Var(VarBindingForm {
1631                 binding_mode,
1632                 // hypothetically, `visit_bindings` could try to unzip
1633                 // an outermost hir::Ty as we descend, matching up
1634                 // idents in pat; but complex w/ unclear UI payoff.
1635                 // Instead, just abandon providing diagnostic info.
1636                 opt_ty_info: None,
1637                 opt_match_place,
1638                 pat_span,
1639             }))),
1640         };
1641         let for_arm_body = self.local_decls.push(local);
1642         self.var_debug_info.push(VarDebugInfo {
1643             name,
1644             source_info: debug_source_info,
1645             place: for_arm_body.into(),
1646         });
1647         let locals = if has_guard.0 {
1648             let ref_for_guard = self.local_decls.push(LocalDecl::<'tcx> {
1649                 // This variable isn't mutated but has a name, so has to be
1650                 // immutable to avoid the unused mut lint.
1651                 mutability: Mutability::Not,
1652                 ty: tcx.mk_imm_ref(tcx.lifetimes.re_erased, var_ty),
1653                 user_ty: UserTypeProjections::none(),
1654                 source_info,
1655                 internal: false,
1656                 is_block_tail: None,
1657                 local_info: LocalInfo::User(ClearCrossCrate::Set(BindingForm::RefForGuard)),
1658             });
1659             self.var_debug_info.push(VarDebugInfo {
1660                 name,
1661                 source_info: debug_source_info,
1662                 place: ref_for_guard.into(),
1663             });
1664             LocalsForNode::ForGuard { ref_for_guard, for_arm_body }
1665         } else {
1666             LocalsForNode::One(for_arm_body)
1667         };
1668         debug!("declare_binding: vars={:?}", locals);
1669         self.var_indices.insert(var_id, locals);
1670     }
1671 }