]> git.lizzy.rs Git - rust.git/blob - src/librustc_trans/trans/_match.rs
Auto merge of #28846 - Ms2ger:categorization, r=nikomatsakis
[rust.git] / src / librustc_trans / trans / _match.rs
1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! # Compilation of match statements
12 //!
13 //! I will endeavor to explain the code as best I can.  I have only a loose
14 //! understanding of some parts of it.
15 //!
16 //! ## Matching
17 //!
18 //! The basic state of the code is maintained in an array `m` of `Match`
19 //! objects.  Each `Match` describes some list of patterns, all of which must
20 //! match against the current list of values.  If those patterns match, then
21 //! the arm listed in the match is the correct arm.  A given arm may have
22 //! multiple corresponding match entries, one for each alternative that
23 //! remains.  As we proceed these sets of matches are adjusted by the various
24 //! `enter_XXX()` functions, each of which adjusts the set of options given
25 //! some information about the value which has been matched.
26 //!
27 //! So, initially, there is one value and N matches, each of which have one
28 //! constituent pattern.  N here is usually the number of arms but may be
29 //! greater, if some arms have multiple alternatives.  For example, here:
30 //!
31 //!     enum Foo { A, B(int), C(usize, usize) }
32 //!     match foo {
33 //!         A => ...,
34 //!         B(x) => ...,
35 //!         C(1, 2) => ...,
36 //!         C(_) => ...
37 //!     }
38 //!
39 //! The value would be `foo`.  There would be four matches, each of which
40 //! contains one pattern (and, in one case, a guard).  We could collect the
41 //! various options and then compile the code for the case where `foo` is an
42 //! `A`, a `B`, and a `C`.  When we generate the code for `C`, we would (1)
43 //! drop the two matches that do not match a `C` and (2) expand the other two
44 //! into two patterns each.  In the first case, the two patterns would be `1`
45 //! and `2`, and the in the second case the _ pattern would be expanded into
46 //! `_` and `_`.  The two values are of course the arguments to `C`.
47 //!
48 //! Here is a quick guide to the various functions:
49 //!
50 //! - `compile_submatch()`: The main workhouse.  It takes a list of values and
51 //!   a list of matches and finds the various possibilities that could occur.
52 //!
53 //! - `enter_XXX()`: modifies the list of matches based on some information
54 //!   about the value that has been matched.  For example,
55 //!   `enter_rec_or_struct()` adjusts the values given that a record or struct
56 //!   has been matched.  This is an infallible pattern, so *all* of the matches
57 //!   must be either wildcards or record/struct patterns.  `enter_opt()`
58 //!   handles the fallible cases, and it is correspondingly more complex.
59 //!
60 //! ## Bindings
61 //!
62 //! We store information about the bound variables for each arm as part of the
63 //! per-arm `ArmData` struct.  There is a mapping from identifiers to
64 //! `BindingInfo` structs.  These structs contain the mode/id/type of the
65 //! binding, but they also contain an LLVM value which points at an alloca
66 //! called `llmatch`. For by value bindings that are Copy, we also create
67 //! an extra alloca that we copy the matched value to so that any changes
68 //! we do to our copy is not reflected in the original and vice-versa.
69 //! We don't do this if it's a move since the original value can't be used
70 //! and thus allowing us to cheat in not creating an extra alloca.
71 //!
72 //! The `llmatch` binding always stores a pointer into the value being matched
73 //! which points at the data for the binding.  If the value being matched has
74 //! type `T`, then, `llmatch` will point at an alloca of type `T*` (and hence
75 //! `llmatch` has type `T**`).  So, if you have a pattern like:
76 //!
77 //!    let a: A = ...;
78 //!    let b: B = ...;
79 //!    match (a, b) { (ref c, d) => { ... } }
80 //!
81 //! For `c` and `d`, we would generate allocas of type `C*` and `D*`
82 //! respectively.  These are called the `llmatch`.  As we match, when we come
83 //! up against an identifier, we store the current pointer into the
84 //! corresponding alloca.
85 //!
86 //! Once a pattern is completely matched, and assuming that there is no guard
87 //! pattern, we will branch to a block that leads to the body itself.  For any
88 //! by-value bindings, this block will first load the ptr from `llmatch` (the
89 //! one of type `D*`) and then load a second time to get the actual value (the
90 //! one of type `D`). For by ref bindings, the value of the local variable is
91 //! simply the first alloca.
92 //!
93 //! So, for the example above, we would generate a setup kind of like this:
94 //!
95 //!        +-------+
96 //!        | Entry |
97 //!        +-------+
98 //!            |
99 //!        +--------------------------------------------+
100 //!        | llmatch_c = (addr of first half of tuple)  |
101 //!        | llmatch_d = (addr of second half of tuple) |
102 //!        +--------------------------------------------+
103 //!            |
104 //!        +--------------------------------------+
105 //!        | *llbinding_d = **llmatch_d           |
106 //!        +--------------------------------------+
107 //!
108 //! If there is a guard, the situation is slightly different, because we must
109 //! execute the guard code.  Moreover, we need to do so once for each of the
110 //! alternatives that lead to the arm, because if the guard fails, they may
111 //! have different points from which to continue the search. Therefore, in that
112 //! case, we generate code that looks more like:
113 //!
114 //!        +-------+
115 //!        | Entry |
116 //!        +-------+
117 //!            |
118 //!        +-------------------------------------------+
119 //!        | llmatch_c = (addr of first half of tuple) |
120 //!        | llmatch_d = (addr of first half of tuple) |
121 //!        +-------------------------------------------+
122 //!            |
123 //!        +-------------------------------------------------+
124 //!        | *llbinding_d = **llmatch_d                      |
125 //!        | check condition                                 |
126 //!        | if false { goto next case }                     |
127 //!        | if true { goto body }                           |
128 //!        +-------------------------------------------------+
129 //!
130 //! The handling for the cleanups is a bit... sensitive.  Basically, the body
131 //! is the one that invokes `add_clean()` for each binding.  During the guard
132 //! evaluation, we add temporary cleanups and revoke them after the guard is
133 //! evaluated (it could fail, after all). Note that guards and moves are
134 //! just plain incompatible.
135 //!
136 //! Some relevant helper functions that manage bindings:
137 //! - `create_bindings_map()`
138 //! - `insert_lllocals()`
139 //!
140 //!
141 //! ## Notes on vector pattern matching.
142 //!
143 //! Vector pattern matching is surprisingly tricky. The problem is that
144 //! the structure of the vector isn't fully known, and slice matches
145 //! can be done on subparts of it.
146 //!
147 //! The way that vector pattern matches are dealt with, then, is as
148 //! follows. First, we make the actual condition associated with a
149 //! vector pattern simply a vector length comparison. So the pattern
150 //! [1, .. x] gets the condition "vec len >= 1", and the pattern
151 //! [.. x] gets the condition "vec len >= 0". The problem here is that
152 //! having the condition "vec len >= 1" hold clearly does not mean that
153 //! only a pattern that has exactly that condition will match. This
154 //! means that it may well be the case that a condition holds, but none
155 //! of the patterns matching that condition match; to deal with this,
156 //! when doing vector length matches, we have match failures proceed to
157 //! the next condition to check.
158 //!
159 //! There are a couple more subtleties to deal with. While the "actual"
160 //! condition associated with vector length tests is simply a test on
161 //! the vector length, the actual vec_len Opt entry contains more
162 //! information used to restrict which matches are associated with it.
163 //! So that all matches in a submatch are matching against the same
164 //! values from inside the vector, they are split up by how many
165 //! elements they match at the front and at the back of the vector. In
166 //! order to make sure that arms are properly checked in order, even
167 //! with the overmatching conditions, each vec_len Opt entry is
168 //! associated with a range of matches.
169 //! Consider the following:
170 //!
171 //!   match &[1, 2, 3] {
172 //!       [1, 1, .. _] => 0,
173 //!       [1, 2, 2, .. _] => 1,
174 //!       [1, 2, 3, .. _] => 2,
175 //!       [1, 2, .. _] => 3,
176 //!       _ => 4
177 //!   }
178 //! The proper arm to match is arm 2, but arms 0 and 3 both have the
179 //! condition "len >= 2". If arm 3 was lumped in with arm 0, then the
180 //! wrong branch would be taken. Instead, vec_len Opts are associated
181 //! with a contiguous range of matches that have the same "shape".
182 //! This is sort of ugly and requires a bunch of special handling of
183 //! vec_len options.
184
185 pub use self::BranchKind::*;
186 pub use self::OptResult::*;
187 pub use self::TransBindingMode::*;
188 use self::Opt::*;
189 use self::FailureHandler::*;
190
191 use llvm::{ValueRef, BasicBlockRef};
192 use middle::check_match::StaticInliner;
193 use middle::check_match;
194 use middle::const_eval;
195 use middle::def::{self, DefMap};
196 use middle::def_id::DefId;
197 use middle::expr_use_visitor as euv;
198 use middle::infer;
199 use middle::lang_items::StrEqFnLangItem;
200 use middle::mem_categorization as mc;
201 use middle::mem_categorization::Categorization;
202 use middle::pat_util::*;
203 use trans::adt;
204 use trans::base::*;
205 use trans::build::{AddCase, And, Br, CondBr, GEPi, InBoundsGEP, Load, PointerCast};
206 use trans::build::{Not, Store, Sub, add_comment};
207 use trans::build;
208 use trans::callee;
209 use trans::cleanup::{self, CleanupMethods, DropHintMethods};
210 use trans::common::*;
211 use trans::consts;
212 use trans::datum::*;
213 use trans::debuginfo::{self, DebugLoc, ToDebugLoc};
214 use trans::expr::{self, Dest};
215 use trans::monomorphize;
216 use trans::tvec;
217 use trans::type_of;
218 use middle::ty::{self, Ty};
219 use session::config::NoDebugInfo;
220 use util::common::indenter;
221 use util::nodemap::FnvHashMap;
222 use util::ppaux;
223
224 use std;
225 use std::cmp::Ordering;
226 use std::fmt;
227 use std::rc::Rc;
228 use rustc_front::hir;
229 use syntax::ast::{self, DUMMY_NODE_ID, NodeId};
230 use syntax::codemap::Span;
231 use rustc_front::fold::Folder;
232 use syntax::ptr::P;
233
234 #[derive(Copy, Clone, Debug)]
235 struct ConstantExpr<'a>(&'a hir::Expr);
236
237 impl<'a> ConstantExpr<'a> {
238     fn eq(self, other: ConstantExpr<'a>, tcx: &ty::ctxt) -> bool {
239         match const_eval::compare_lit_exprs(tcx, self.0, other.0) {
240             Some(result) => result == Ordering::Equal,
241             None => panic!("compare_list_exprs: type mismatch"),
242         }
243     }
244 }
245
246 // An option identifying a branch (either a literal, an enum variant or a range)
247 #[derive(Debug)]
248 enum Opt<'a, 'tcx> {
249     ConstantValue(ConstantExpr<'a>, DebugLoc),
250     ConstantRange(ConstantExpr<'a>, ConstantExpr<'a>, DebugLoc),
251     Variant(ty::Disr, Rc<adt::Repr<'tcx>>, DefId, DebugLoc),
252     SliceLengthEqual(usize, DebugLoc),
253     SliceLengthGreaterOrEqual(/* prefix length */ usize,
254                               /* suffix length */ usize,
255                               DebugLoc),
256 }
257
258 impl<'a, 'tcx> Opt<'a, 'tcx> {
259     fn eq(&self, other: &Opt<'a, 'tcx>, tcx: &ty::ctxt<'tcx>) -> bool {
260         match (self, other) {
261             (&ConstantValue(a, _), &ConstantValue(b, _)) => a.eq(b, tcx),
262             (&ConstantRange(a1, a2, _), &ConstantRange(b1, b2, _)) => {
263                 a1.eq(b1, tcx) && a2.eq(b2, tcx)
264             }
265             (&Variant(a_disr, ref a_repr, a_def, _),
266              &Variant(b_disr, ref b_repr, b_def, _)) => {
267                 a_disr == b_disr && *a_repr == *b_repr && a_def == b_def
268             }
269             (&SliceLengthEqual(a, _), &SliceLengthEqual(b, _)) => a == b,
270             (&SliceLengthGreaterOrEqual(a1, a2, _),
271              &SliceLengthGreaterOrEqual(b1, b2, _)) => {
272                 a1 == b1 && a2 == b2
273             }
274             _ => false
275         }
276     }
277
278     fn trans<'blk>(&self, mut bcx: Block<'blk, 'tcx>) -> OptResult<'blk, 'tcx> {
279         use trans::consts::TrueConst::Yes;
280         let _icx = push_ctxt("match::trans_opt");
281         let ccx = bcx.ccx();
282         match *self {
283             ConstantValue(ConstantExpr(lit_expr), _) => {
284                 let lit_ty = bcx.tcx().node_id_to_type(lit_expr.id);
285                 let expr = consts::const_expr(ccx, &*lit_expr, bcx.fcx.param_substs, None, Yes);
286                 let llval = match expr {
287                     Ok((llval, _)) => llval,
288                     Err(err) => bcx.ccx().sess().span_fatal(lit_expr.span, &err.description()),
289                 };
290                 let lit_datum = immediate_rvalue(llval, lit_ty);
291                 let lit_datum = unpack_datum!(bcx, lit_datum.to_appropriate_datum(bcx));
292                 SingleResult(Result::new(bcx, lit_datum.val))
293             }
294             ConstantRange(ConstantExpr(ref l1), ConstantExpr(ref l2), _) => {
295                 let l1 = match consts::const_expr(ccx, &**l1, bcx.fcx.param_substs, None, Yes) {
296                     Ok((l1, _)) => l1,
297                     Err(err) => bcx.ccx().sess().span_fatal(l1.span, &err.description()),
298                 };
299                 let l2 = match consts::const_expr(ccx, &**l2, bcx.fcx.param_substs, None, Yes) {
300                     Ok((l2, _)) => l2,
301                     Err(err) => bcx.ccx().sess().span_fatal(l2.span, &err.description()),
302                 };
303                 RangeResult(Result::new(bcx, l1), Result::new(bcx, l2))
304             }
305             Variant(disr_val, ref repr, _, _) => {
306                 adt::trans_case(bcx, &**repr, disr_val)
307             }
308             SliceLengthEqual(length, _) => {
309                 SingleResult(Result::new(bcx, C_uint(ccx, length)))
310             }
311             SliceLengthGreaterOrEqual(prefix, suffix, _) => {
312                 LowerBound(Result::new(bcx, C_uint(ccx, prefix + suffix)))
313             }
314         }
315     }
316
317     fn debug_loc(&self) -> DebugLoc {
318         match *self {
319             ConstantValue(_,debug_loc)                 |
320             ConstantRange(_, _, debug_loc)             |
321             Variant(_, _, _, debug_loc)                |
322             SliceLengthEqual(_, debug_loc)             |
323             SliceLengthGreaterOrEqual(_, _, debug_loc) => debug_loc
324         }
325     }
326 }
327
328 #[derive(Copy, Clone, PartialEq)]
329 pub enum BranchKind {
330     NoBranch,
331     Single,
332     Switch,
333     Compare,
334     CompareSliceLength
335 }
336
337 pub enum OptResult<'blk, 'tcx: 'blk> {
338     SingleResult(Result<'blk, 'tcx>),
339     RangeResult(Result<'blk, 'tcx>, Result<'blk, 'tcx>),
340     LowerBound(Result<'blk, 'tcx>)
341 }
342
343 #[derive(Clone, Copy, PartialEq)]
344 pub enum TransBindingMode {
345     /// By-value binding for a copy type: copies from matched data
346     /// into a fresh LLVM alloca.
347     TrByCopy(/* llbinding */ ValueRef),
348
349     /// By-value binding for a non-copy type where we copy into a
350     /// fresh LLVM alloca; this most accurately reflects the language
351     /// semantics (e.g. it properly handles overwrites of the matched
352     /// input), but potentially injects an unwanted copy.
353     TrByMoveIntoCopy(/* llbinding */ ValueRef),
354
355     /// Binding a non-copy type by reference under the hood; this is
356     /// a codegen optimization to avoid unnecessary memory traffic.
357     TrByMoveRef,
358
359     /// By-ref binding exposed in the original source input.
360     TrByRef,
361 }
362
363 impl TransBindingMode {
364     /// if binding by making a fresh copy; returns the alloca that it
365     /// will copy into; otherwise None.
366     fn alloca_if_copy(&self) -> Option<ValueRef> {
367         match *self {
368             TrByCopy(llbinding) | TrByMoveIntoCopy(llbinding) => Some(llbinding),
369             TrByMoveRef | TrByRef => None,
370         }
371     }
372 }
373
374 /// Information about a pattern binding:
375 /// - `llmatch` is a pointer to a stack slot.  The stack slot contains a
376 ///   pointer into the value being matched.  Hence, llmatch has type `T**`
377 ///   where `T` is the value being matched.
378 /// - `trmode` is the trans binding mode
379 /// - `id` is the node id of the binding
380 /// - `ty` is the Rust type of the binding
381 #[derive(Clone, Copy)]
382 pub struct BindingInfo<'tcx> {
383     pub llmatch: ValueRef,
384     pub trmode: TransBindingMode,
385     pub id: ast::NodeId,
386     pub span: Span,
387     pub ty: Ty<'tcx>,
388 }
389
390 type BindingsMap<'tcx> = FnvHashMap<ast::Name, BindingInfo<'tcx>>;
391
392 struct ArmData<'p, 'blk, 'tcx: 'blk> {
393     bodycx: Block<'blk, 'tcx>,
394     arm: &'p hir::Arm,
395     bindings_map: BindingsMap<'tcx>
396 }
397
398 /// Info about Match.
399 /// If all `pats` are matched then arm `data` will be executed.
400 /// As we proceed `bound_ptrs` are filled with pointers to values to be bound,
401 /// these pointers are stored in llmatch variables just before executing `data` arm.
402 struct Match<'a, 'p: 'a, 'blk: 'a, 'tcx: 'blk> {
403     pats: Vec<&'p hir::Pat>,
404     data: &'a ArmData<'p, 'blk, 'tcx>,
405     bound_ptrs: Vec<(ast::Name, ValueRef)>,
406     // Thread along renamings done by the check_match::StaticInliner, so we can
407     // map back to original NodeIds
408     pat_renaming_map: Option<&'a FnvHashMap<(NodeId, Span), NodeId>>
409 }
410
411 impl<'a, 'p, 'blk, 'tcx> fmt::Debug for Match<'a, 'p, 'blk, 'tcx> {
412     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
413         if ppaux::verbose() {
414             // for many programs, this just take too long to serialize
415             write!(f, "{:?}", self.pats)
416         } else {
417             write!(f, "{} pats", self.pats.len())
418         }
419     }
420 }
421
422 fn has_nested_bindings(m: &[Match], col: usize) -> bool {
423     for br in m {
424         match br.pats[col].node {
425             hir::PatIdent(_, _, Some(_)) => return true,
426             _ => ()
427         }
428     }
429     return false;
430 }
431
432 // As noted in `fn match_datum`, we should eventually pass around a
433 // `Datum<Lvalue>` for the `val`; but until we get to that point, this
434 // `MatchInput` struct will serve -- it has everything `Datum<Lvalue>`
435 // does except for the type field.
436 #[derive(Copy, Clone)]
437 pub struct MatchInput { val: ValueRef, lval: Lvalue }
438
439 impl<'tcx> Datum<'tcx, Lvalue> {
440     pub fn match_input(&self) -> MatchInput {
441         MatchInput {
442             val: self.val,
443             lval: self.kind,
444         }
445     }
446 }
447
448 impl MatchInput {
449     fn from_val(val: ValueRef) -> MatchInput {
450         MatchInput {
451             val: val,
452             lval: Lvalue::new("MatchInput::from_val"),
453         }
454     }
455
456     fn to_datum<'tcx>(self, ty: Ty<'tcx>) -> Datum<'tcx, Lvalue> {
457         Datum::new(self.val, ty, self.lval)
458     }
459 }
460
461 fn expand_nested_bindings<'a, 'p, 'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
462                                               m: &[Match<'a, 'p, 'blk, 'tcx>],
463                                               col: usize,
464                                               val: MatchInput)
465                                               -> Vec<Match<'a, 'p, 'blk, 'tcx>> {
466     debug!("expand_nested_bindings(bcx={}, m={:?}, col={}, val={})",
467            bcx.to_str(),
468            m,
469            col,
470            bcx.val_to_string(val.val));
471     let _indenter = indenter();
472
473     m.iter().map(|br| {
474         let mut bound_ptrs = br.bound_ptrs.clone();
475         let mut pat = br.pats[col];
476         loop {
477             pat = match pat.node {
478                 hir::PatIdent(_, ref path, Some(ref inner)) => {
479                     bound_ptrs.push((path.node.name, val.val));
480                     &**inner
481                 },
482                 _ => break
483             }
484         }
485
486         let mut pats = br.pats.clone();
487         pats[col] = pat;
488         Match {
489             pats: pats,
490             data: &*br.data,
491             bound_ptrs: bound_ptrs,
492             pat_renaming_map: br.pat_renaming_map,
493         }
494     }).collect()
495 }
496
497 fn enter_match<'a, 'b, 'p, 'blk, 'tcx, F>(bcx: Block<'blk, 'tcx>,
498                                           dm: &DefMap,
499                                           m: &[Match<'a, 'p, 'blk, 'tcx>],
500                                           col: usize,
501                                           val: MatchInput,
502                                           mut e: F)
503                                           -> Vec<Match<'a, 'p, 'blk, 'tcx>> where
504     F: FnMut(&[&'p hir::Pat]) -> Option<Vec<&'p hir::Pat>>,
505 {
506     debug!("enter_match(bcx={}, m={:?}, col={}, val={})",
507            bcx.to_str(),
508            m,
509            col,
510            bcx.val_to_string(val.val));
511     let _indenter = indenter();
512
513     m.iter().filter_map(|br| {
514         e(&br.pats).map(|pats| {
515             let this = br.pats[col];
516             let mut bound_ptrs = br.bound_ptrs.clone();
517             match this.node {
518                 hir::PatIdent(_, ref path, None) => {
519                     if pat_is_binding(dm, &*this) {
520                         bound_ptrs.push((path.node.name, val.val));
521                     }
522                 }
523                 hir::PatVec(ref before, Some(ref slice), ref after) => {
524                     if let hir::PatIdent(_, ref path, None) = slice.node {
525                         let subslice_val = bind_subslice_pat(
526                             bcx, this.id, val,
527                             before.len(), after.len());
528                         bound_ptrs.push((path.node.name, subslice_val));
529                     }
530                 }
531                 _ => {}
532             }
533             Match {
534                 pats: pats,
535                 data: br.data,
536                 bound_ptrs: bound_ptrs,
537                 pat_renaming_map: br.pat_renaming_map,
538             }
539         })
540     }).collect()
541 }
542
543 fn enter_default<'a, 'p, 'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
544                                      dm: &DefMap,
545                                      m: &[Match<'a, 'p, 'blk, 'tcx>],
546                                      col: usize,
547                                      val: MatchInput)
548                                      -> Vec<Match<'a, 'p, 'blk, 'tcx>> {
549     debug!("enter_default(bcx={}, m={:?}, col={}, val={})",
550            bcx.to_str(),
551            m,
552            col,
553            bcx.val_to_string(val.val));
554     let _indenter = indenter();
555
556     // Collect all of the matches that can match against anything.
557     enter_match(bcx, dm, m, col, val, |pats| {
558         if pat_is_binding_or_wild(dm, &*pats[col]) {
559             let mut r = pats[..col].to_vec();
560             r.push_all(&pats[col + 1..]);
561             Some(r)
562         } else {
563             None
564         }
565     })
566 }
567
568 // <pcwalton> nmatsakis: what does enter_opt do?
569 // <pcwalton> in trans/match
570 // <pcwalton> trans/match.rs is like stumbling around in a dark cave
571 // <nmatsakis> pcwalton: the enter family of functions adjust the set of
572 //             patterns as needed
573 // <nmatsakis> yeah, at some point I kind of achieved some level of
574 //             understanding
575 // <nmatsakis> anyhow, they adjust the patterns given that something of that
576 //             kind has been found
577 // <nmatsakis> pcwalton: ok, right, so enter_XXX() adjusts the patterns, as I
578 //             said
579 // <nmatsakis> enter_match() kind of embodies the generic code
580 // <nmatsakis> it is provided with a function that tests each pattern to see
581 //             if it might possibly apply and so forth
582 // <nmatsakis> so, if you have a pattern like {a: _, b: _, _} and one like _
583 // <nmatsakis> then _ would be expanded to (_, _)
584 // <nmatsakis> one spot for each of the sub-patterns
585 // <nmatsakis> enter_opt() is one of the more complex; it covers the fallible
586 //             cases
587 // <nmatsakis> enter_rec_or_struct() or enter_tuple() are simpler, since they
588 //             are infallible patterns
589 // <nmatsakis> so all patterns must either be records (resp. tuples) or
590 //             wildcards
591
592 /// The above is now outdated in that enter_match() now takes a function that
593 /// takes the complete row of patterns rather than just the first one.
594 /// Also, most of the enter_() family functions have been unified with
595 /// the check_match specialization step.
596 fn enter_opt<'a, 'p, 'blk, 'tcx>(
597              bcx: Block<'blk, 'tcx>,
598              _: ast::NodeId,
599              dm: &DefMap,
600              m: &[Match<'a, 'p, 'blk, 'tcx>],
601              opt: &Opt,
602              col: usize,
603              variant_size: usize,
604              val: MatchInput)
605              -> Vec<Match<'a, 'p, 'blk, 'tcx>> {
606     debug!("enter_opt(bcx={}, m={:?}, opt={:?}, col={}, val={})",
607            bcx.to_str(),
608            m,
609            *opt,
610            col,
611            bcx.val_to_string(val.val));
612     let _indenter = indenter();
613
614     let ctor = match opt {
615         &ConstantValue(ConstantExpr(expr), _) => check_match::ConstantValue(
616             const_eval::eval_const_expr(bcx.tcx(), &*expr)
617         ),
618         &ConstantRange(ConstantExpr(lo), ConstantExpr(hi), _) => check_match::ConstantRange(
619             const_eval::eval_const_expr(bcx.tcx(), &*lo),
620             const_eval::eval_const_expr(bcx.tcx(), &*hi)
621         ),
622         &SliceLengthEqual(n, _) =>
623             check_match::Slice(n),
624         &SliceLengthGreaterOrEqual(before, after, _) =>
625             check_match::SliceWithSubslice(before, after),
626         &Variant(_, _, def_id, _) =>
627             check_match::Constructor::Variant(def_id)
628     };
629
630     let param_env = bcx.tcx().empty_parameter_environment();
631     let mcx = check_match::MatchCheckCtxt {
632         tcx: bcx.tcx(),
633         param_env: param_env,
634     };
635     enter_match(bcx, dm, m, col, val, |pats|
636         check_match::specialize(&mcx, &pats[..], &ctor, col, variant_size)
637     )
638 }
639
640 // Returns the options in one column of matches. An option is something that
641 // needs to be conditionally matched at runtime; for example, the discriminant
642 // on a set of enum variants or a literal.
643 fn get_branches<'a, 'p, 'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
644                                     m: &[Match<'a, 'p, 'blk, 'tcx>],
645                                     col: usize)
646                                     -> Vec<Opt<'p, 'tcx>> {
647     let tcx = bcx.tcx();
648
649     let mut found: Vec<Opt> = vec![];
650     for br in m {
651         let cur = br.pats[col];
652         let debug_loc = match br.pat_renaming_map {
653             Some(pat_renaming_map) => {
654                 match pat_renaming_map.get(&(cur.id, cur.span)) {
655                     Some(&id) => DebugLoc::At(id, cur.span),
656                     None => DebugLoc::At(cur.id, cur.span),
657                 }
658             }
659             None => DebugLoc::None
660         };
661
662         let opt = match cur.node {
663             hir::PatLit(ref l) => {
664                 ConstantValue(ConstantExpr(&**l), debug_loc)
665             }
666             hir::PatIdent(..) | hir::PatEnum(..) | hir::PatStruct(..) => {
667                 // This is either an enum variant or a variable binding.
668                 let opt_def = tcx.def_map.borrow().get(&cur.id).map(|d| d.full_def());
669                 match opt_def {
670                     Some(def::DefVariant(enum_id, var_id, _)) => {
671                         let variant = tcx.lookup_adt_def(enum_id).variant_with_id(var_id);
672                         Variant(variant.disr_val,
673                                 adt::represent_node(bcx, cur.id),
674                                 var_id,
675                                 debug_loc)
676                     }
677                     _ => continue
678                 }
679             }
680             hir::PatRange(ref l1, ref l2) => {
681                 ConstantRange(ConstantExpr(&**l1), ConstantExpr(&**l2), debug_loc)
682             }
683             hir::PatVec(ref before, None, ref after) => {
684                 SliceLengthEqual(before.len() + after.len(), debug_loc)
685             }
686             hir::PatVec(ref before, Some(_), ref after) => {
687                 SliceLengthGreaterOrEqual(before.len(), after.len(), debug_loc)
688             }
689             _ => continue
690         };
691
692         if !found.iter().any(|x| x.eq(&opt, tcx)) {
693             found.push(opt);
694         }
695     }
696     found
697 }
698
699 struct ExtractedBlock<'blk, 'tcx: 'blk> {
700     vals: Vec<ValueRef>,
701     bcx: Block<'blk, 'tcx>,
702 }
703
704 fn extract_variant_args<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
705                                     repr: &adt::Repr<'tcx>,
706                                     disr_val: ty::Disr,
707                                     val: MatchInput)
708                                     -> ExtractedBlock<'blk, 'tcx> {
709     let _icx = push_ctxt("match::extract_variant_args");
710     let args = (0..adt::num_args(repr, disr_val)).map(|i| {
711         adt::trans_field_ptr(bcx, repr, val.val, disr_val, i)
712     }).collect();
713
714     ExtractedBlock { vals: args, bcx: bcx }
715 }
716
717 /// Helper for converting from the ValueRef that we pass around in the match code, which is always
718 /// an lvalue, into a Datum. Eventually we should just pass around a Datum and be done with it.
719 fn match_datum<'tcx>(val: MatchInput, left_ty: Ty<'tcx>) -> Datum<'tcx, Lvalue> {
720     val.to_datum(left_ty)
721 }
722
723 fn bind_subslice_pat(bcx: Block,
724                      pat_id: ast::NodeId,
725                      val: MatchInput,
726                      offset_left: usize,
727                      offset_right: usize) -> ValueRef {
728     let _icx = push_ctxt("match::bind_subslice_pat");
729     let vec_ty = node_id_type(bcx, pat_id);
730     let vec_ty_contents = match vec_ty.sty {
731         ty::TyBox(ty) => ty,
732         ty::TyRef(_, mt) | ty::TyRawPtr(mt) => mt.ty,
733         _ => vec_ty
734     };
735     let unit_ty = vec_ty_contents.sequence_element_type(bcx.tcx());
736     let vec_datum = match_datum(val, vec_ty);
737     let (base, len) = vec_datum.get_vec_base_and_len(bcx);
738
739     let slice_begin = InBoundsGEP(bcx, base, &[C_uint(bcx.ccx(), offset_left)]);
740     let slice_len_offset = C_uint(bcx.ccx(), offset_left + offset_right);
741     let slice_len = Sub(bcx, len, slice_len_offset, DebugLoc::None);
742     let slice_ty = bcx.tcx().mk_imm_ref(bcx.tcx().mk_region(ty::ReStatic),
743                                          bcx.tcx().mk_slice(unit_ty));
744     let scratch = rvalue_scratch_datum(bcx, slice_ty, "");
745     Store(bcx, slice_begin, expr::get_dataptr(bcx, scratch.val));
746     Store(bcx, slice_len, expr::get_meta(bcx, scratch.val));
747     scratch.val
748 }
749
750 fn extract_vec_elems<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
751                                  left_ty: Ty<'tcx>,
752                                  before: usize,
753                                  after: usize,
754                                  val: MatchInput)
755                                  -> ExtractedBlock<'blk, 'tcx> {
756     let _icx = push_ctxt("match::extract_vec_elems");
757     let vec_datum = match_datum(val, left_ty);
758     let (base, len) = vec_datum.get_vec_base_and_len(bcx);
759     let mut elems = vec![];
760     elems.extend((0..before).map(|i| GEPi(bcx, base, &[i])));
761     elems.extend((0..after).rev().map(|i| {
762         InBoundsGEP(bcx, base, &[
763             Sub(bcx, len, C_uint(bcx.ccx(), i + 1), DebugLoc::None)
764         ])
765     }));
766     ExtractedBlock { vals: elems, bcx: bcx }
767 }
768
769 // Macro for deciding whether any of the remaining matches fit a given kind of
770 // pattern.  Note that, because the macro is well-typed, either ALL of the
771 // matches should fit that sort of pattern or NONE (however, some of the
772 // matches may be wildcards like _ or identifiers).
773 macro_rules! any_pat {
774     ($m:expr, $col:expr, $pattern:pat) => (
775         ($m).iter().any(|br| {
776             match br.pats[$col].node {
777                 $pattern => true,
778                 _ => false
779             }
780         })
781     )
782 }
783
784 fn any_uniq_pat(m: &[Match], col: usize) -> bool {
785     any_pat!(m, col, hir::PatBox(_))
786 }
787
788 fn any_region_pat(m: &[Match], col: usize) -> bool {
789     any_pat!(m, col, hir::PatRegion(..))
790 }
791
792 fn any_irrefutable_adt_pat(tcx: &ty::ctxt, m: &[Match], col: usize) -> bool {
793     m.iter().any(|br| {
794         let pat = br.pats[col];
795         match pat.node {
796             hir::PatTup(_) => true,
797             hir::PatStruct(..) => {
798                 match tcx.def_map.borrow().get(&pat.id).map(|d| d.full_def()) {
799                     Some(def::DefVariant(..)) => false,
800                     _ => true,
801                 }
802             }
803             hir::PatEnum(..) | hir::PatIdent(_, _, None) => {
804                 match tcx.def_map.borrow().get(&pat.id).map(|d| d.full_def()) {
805                     Some(def::DefStruct(..)) => true,
806                     _ => false
807                 }
808             }
809             _ => false
810         }
811     })
812 }
813
814 /// What to do when the pattern match fails.
815 enum FailureHandler {
816     Infallible,
817     JumpToBasicBlock(BasicBlockRef),
818     Unreachable
819 }
820
821 impl FailureHandler {
822     fn is_fallible(&self) -> bool {
823         match *self {
824             Infallible => false,
825             _ => true
826         }
827     }
828
829     fn is_infallible(&self) -> bool {
830         !self.is_fallible()
831     }
832
833     fn handle_fail(&self, bcx: Block) {
834         match *self {
835             Infallible =>
836                 panic!("attempted to panic in a non-panicking panic handler!"),
837             JumpToBasicBlock(basic_block) =>
838                 Br(bcx, basic_block, DebugLoc::None),
839             Unreachable =>
840                 build::Unreachable(bcx)
841         }
842     }
843 }
844
845 fn pick_column_to_specialize(def_map: &DefMap, m: &[Match]) -> Option<usize> {
846     fn pat_score(def_map: &DefMap, pat: &hir::Pat) -> usize {
847         match pat.node {
848             hir::PatIdent(_, _, Some(ref inner)) => pat_score(def_map, &**inner),
849             _ if pat_is_refutable(def_map, pat) => 1,
850             _ => 0
851         }
852     }
853
854     let column_score = |m: &[Match], col: usize| -> usize {
855         let total_score = m.iter()
856             .map(|row| row.pats[col])
857             .map(|pat| pat_score(def_map, pat))
858             .sum();
859
860         // Irrefutable columns always go first, they'd only be duplicated in the branches.
861         if total_score == 0 {
862             std::usize::MAX
863         } else {
864             total_score
865         }
866     };
867
868     let column_contains_any_nonwild_patterns = |&col: &usize| -> bool {
869         m.iter().any(|row| match row.pats[col].node {
870             hir::PatWild => false,
871             _ => true
872         })
873     };
874
875     (0..m[0].pats.len())
876         .filter(column_contains_any_nonwild_patterns)
877         .map(|col| (col, column_score(m, col)))
878         .max_by(|&(_, score)| score)
879         .map(|(col, _)| col)
880 }
881
882 // Compiles a comparison between two things.
883 fn compare_values<'blk, 'tcx>(cx: Block<'blk, 'tcx>,
884                               lhs: ValueRef,
885                               rhs: ValueRef,
886                               rhs_t: Ty<'tcx>,
887                               debug_loc: DebugLoc)
888                               -> Result<'blk, 'tcx> {
889     fn compare_str<'blk, 'tcx>(cx: Block<'blk, 'tcx>,
890                                lhs_data: ValueRef,
891                                lhs_len: ValueRef,
892                                rhs_data: ValueRef,
893                                rhs_len: ValueRef,
894                                rhs_t: Ty<'tcx>,
895                                debug_loc: DebugLoc)
896                                -> Result<'blk, 'tcx> {
897         let did = langcall(cx,
898                            None,
899                            &format!("comparison of `{}`", rhs_t),
900                            StrEqFnLangItem);
901         callee::trans_lang_call(cx, did, &[lhs_data, lhs_len, rhs_data, rhs_len], None, debug_loc)
902     }
903
904     let _icx = push_ctxt("compare_values");
905     if rhs_t.is_scalar() {
906         let cmp = compare_scalar_types(cx, lhs, rhs, rhs_t, hir::BiEq, debug_loc);
907         return Result::new(cx, cmp);
908     }
909
910     match rhs_t.sty {
911         ty::TyRef(_, mt) => match mt.ty.sty {
912             ty::TyStr => {
913                 let lhs_data = Load(cx, expr::get_dataptr(cx, lhs));
914                 let lhs_len = Load(cx, expr::get_meta(cx, lhs));
915                 let rhs_data = Load(cx, expr::get_dataptr(cx, rhs));
916                 let rhs_len = Load(cx, expr::get_meta(cx, rhs));
917                 compare_str(cx, lhs_data, lhs_len, rhs_data, rhs_len, rhs_t, debug_loc)
918             }
919             ty::TyArray(ty, _) | ty::TySlice(ty) => match ty.sty {
920                 ty::TyUint(ast::TyU8) => {
921                     // NOTE: cast &[u8] and &[u8; N] to &str and abuse the str_eq lang item,
922                     // which calls memcmp().
923                     let pat_len = val_ty(rhs).element_type().array_length();
924                     let ty_str_slice = cx.tcx().mk_static_str();
925
926                     let rhs_data = GEPi(cx, rhs, &[0, 0]);
927                     let rhs_len = C_uint(cx.ccx(), pat_len);
928
929                     let lhs_data;
930                     let lhs_len;
931                     if val_ty(lhs) == val_ty(rhs) {
932                         // Both the discriminant and the pattern are thin pointers
933                         lhs_data = GEPi(cx, lhs, &[0, 0]);
934                         lhs_len = C_uint(cx.ccx(), pat_len);
935                     } else {
936                         // The discriminant is a fat pointer
937                         let llty_str_slice = type_of::type_of(cx.ccx(), ty_str_slice).ptr_to();
938                         let lhs_str = PointerCast(cx, lhs, llty_str_slice);
939                         lhs_data = Load(cx, expr::get_dataptr(cx, lhs_str));
940                         lhs_len = Load(cx, expr::get_meta(cx, lhs_str));
941                     }
942
943                     compare_str(cx, lhs_data, lhs_len, rhs_data, rhs_len, rhs_t, debug_loc)
944                 },
945                 _ => cx.sess().bug("only byte strings supported in compare_values"),
946             },
947             _ => cx.sess().bug("only string and byte strings supported in compare_values"),
948         },
949         _ => cx.sess().bug("only scalars, byte strings, and strings supported in compare_values"),
950     }
951 }
952
953 /// For each binding in `data.bindings_map`, adds an appropriate entry into the `fcx.lllocals` map
954 fn insert_lllocals<'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>,
955                                bindings_map: &BindingsMap<'tcx>,
956                                cs: Option<cleanup::ScopeId>)
957                                -> Block<'blk, 'tcx> {
958     for (&name, &binding_info) in bindings_map {
959         let (llval, aliases_other_state) = match binding_info.trmode {
960             // By value mut binding for a copy type: load from the ptr
961             // into the matched value and copy to our alloca
962             TrByCopy(llbinding) |
963             TrByMoveIntoCopy(llbinding) => {
964                 let llval = Load(bcx, binding_info.llmatch);
965                 let lvalue = match binding_info.trmode {
966                     TrByCopy(..) =>
967                         Lvalue::new("_match::insert_lllocals"),
968                     TrByMoveIntoCopy(..) => {
969                         // match_input moves from the input into a
970                         // separate stack slot.
971                         //
972                         // E.g. consider moving the value `D(A)` out
973                         // of the tuple `(D(A), D(B))` and into the
974                         // local variable `x` via the pattern `(x,_)`,
975                         // leaving the remainder of the tuple `(_,
976                         // D(B))` still to be dropped in the future.
977                         //
978                         // Thus, here we must zero the place that we
979                         // are moving *from*, because we do not yet
980                         // track drop flags for a fragmented parent
981                         // match input expression.
982                         //
983                         // Longer term we will be able to map the move
984                         // into `(x, _)` up to the parent path that
985                         // owns the whole tuple, and mark the
986                         // corresponding stack-local drop-flag
987                         // tracking the first component of the tuple.
988                         let hint_kind = HintKind::ZeroAndMaintain;
989                         Lvalue::new_with_hint("_match::insert_lllocals (match_input)",
990                                               bcx, binding_info.id, hint_kind)
991                     }
992                     _ => unreachable!(),
993                 };
994                 let datum = Datum::new(llval, binding_info.ty, lvalue);
995                 call_lifetime_start(bcx, llbinding);
996                 bcx = datum.store_to(bcx, llbinding);
997                 if let Some(cs) = cs {
998                     bcx.fcx.schedule_lifetime_end(cs, llbinding);
999                 }
1000
1001                 (llbinding, false)
1002             },
1003
1004             // By value move bindings: load from the ptr into the matched value
1005             TrByMoveRef => (Load(bcx, binding_info.llmatch), true),
1006
1007             // By ref binding: use the ptr into the matched value
1008             TrByRef => (binding_info.llmatch, true),
1009         };
1010
1011
1012         // A local that aliases some other state must be zeroed, since
1013         // the other state (e.g. some parent data that we matched
1014         // into) will still have its subcomponents (such as this
1015         // local) destructed at the end of the parent's scope. Longer
1016         // term, we will properly map such parents to the set of
1017         // unique drop flags for its fragments.
1018         let hint_kind = if aliases_other_state {
1019             HintKind::ZeroAndMaintain
1020         } else {
1021             HintKind::DontZeroJustUse
1022         };
1023         let lvalue = Lvalue::new_with_hint("_match::insert_lllocals (local)",
1024                                            bcx,
1025                                            binding_info.id,
1026                                            hint_kind);
1027         let datum = Datum::new(llval, binding_info.ty, lvalue);
1028         if let Some(cs) = cs {
1029             let opt_datum = lvalue.dropflag_hint(bcx);
1030             bcx.fcx.schedule_lifetime_end(cs, binding_info.llmatch);
1031             bcx.fcx.schedule_drop_and_fill_mem(cs, llval, binding_info.ty, opt_datum);
1032         }
1033
1034         debug!("binding {} to {}", binding_info.id, bcx.val_to_string(llval));
1035         bcx.fcx.lllocals.borrow_mut().insert(binding_info.id, datum);
1036         debuginfo::create_match_binding_metadata(bcx, name, binding_info);
1037     }
1038     bcx
1039 }
1040
1041 fn compile_guard<'a, 'p, 'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1042                                      guard_expr: &hir::Expr,
1043                                      data: &ArmData<'p, 'blk, 'tcx>,
1044                                      m: &[Match<'a, 'p, 'blk, 'tcx>],
1045                                      vals: &[MatchInput],
1046                                      chk: &FailureHandler,
1047                                      has_genuine_default: bool)
1048                                      -> Block<'blk, 'tcx> {
1049     debug!("compile_guard(bcx={}, guard_expr={:?}, m={:?}, vals=[{}])",
1050            bcx.to_str(),
1051            guard_expr,
1052            m,
1053            vals.iter().map(|v| bcx.val_to_string(v.val)).collect::<Vec<_>>().join(", "));
1054     let _indenter = indenter();
1055
1056     let mut bcx = insert_lllocals(bcx, &data.bindings_map, None);
1057
1058     let val = unpack_datum!(bcx, expr::trans(bcx, guard_expr));
1059     let val = val.to_llbool(bcx);
1060
1061     for (_, &binding_info) in &data.bindings_map {
1062         if let Some(llbinding) = binding_info.trmode.alloca_if_copy() {
1063             call_lifetime_end(bcx, llbinding)
1064         }
1065     }
1066
1067     for (_, &binding_info) in &data.bindings_map {
1068         bcx.fcx.lllocals.borrow_mut().remove(&binding_info.id);
1069     }
1070
1071     with_cond(bcx, Not(bcx, val, guard_expr.debug_loc()), |bcx| {
1072         for (_, &binding_info) in &data.bindings_map {
1073             call_lifetime_end(bcx, binding_info.llmatch);
1074         }
1075         match chk {
1076             // If the default arm is the only one left, move on to the next
1077             // condition explicitly rather than (possibly) falling back to
1078             // the default arm.
1079             &JumpToBasicBlock(_) if m.len() == 1 && has_genuine_default => {
1080                 chk.handle_fail(bcx);
1081             }
1082             _ => {
1083                 compile_submatch(bcx, m, vals, chk, has_genuine_default);
1084             }
1085         };
1086         bcx
1087     })
1088 }
1089
1090 fn compile_submatch<'a, 'p, 'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1091                                         m: &[Match<'a, 'p, 'blk, 'tcx>],
1092                                         vals: &[MatchInput],
1093                                         chk: &FailureHandler,
1094                                         has_genuine_default: bool) {
1095     debug!("compile_submatch(bcx={}, m={:?}, vals=[{}])",
1096            bcx.to_str(),
1097            m,
1098            vals.iter().map(|v| bcx.val_to_string(v.val)).collect::<Vec<_>>().join(", "));
1099     let _indenter = indenter();
1100     let _icx = push_ctxt("match::compile_submatch");
1101     let mut bcx = bcx;
1102     if m.is_empty() {
1103         if chk.is_fallible() {
1104             chk.handle_fail(bcx);
1105         }
1106         return;
1107     }
1108
1109     let tcx = bcx.tcx();
1110     let def_map = &tcx.def_map;
1111     match pick_column_to_specialize(def_map, m) {
1112         Some(col) => {
1113             let val = vals[col];
1114             if has_nested_bindings(m, col) {
1115                 let expanded = expand_nested_bindings(bcx, m, col, val);
1116                 compile_submatch_continue(bcx,
1117                                           &expanded[..],
1118                                           vals,
1119                                           chk,
1120                                           col,
1121                                           val,
1122                                           has_genuine_default)
1123             } else {
1124                 compile_submatch_continue(bcx, m, vals, chk, col, val, has_genuine_default)
1125             }
1126         }
1127         None => {
1128             let data = &m[0].data;
1129             for &(ref ident, ref value_ptr) in &m[0].bound_ptrs {
1130                 let binfo = *data.bindings_map.get(ident).unwrap();
1131                 call_lifetime_start(bcx, binfo.llmatch);
1132                 if binfo.trmode == TrByRef && type_is_fat_ptr(bcx.tcx(), binfo.ty) {
1133                     expr::copy_fat_ptr(bcx, *value_ptr, binfo.llmatch);
1134                 }
1135                 else {
1136                     Store(bcx, *value_ptr, binfo.llmatch);
1137                 }
1138             }
1139             match data.arm.guard {
1140                 Some(ref guard_expr) => {
1141                     bcx = compile_guard(bcx,
1142                                         &**guard_expr,
1143                                         m[0].data,
1144                                         &m[1..m.len()],
1145                                         vals,
1146                                         chk,
1147                                         has_genuine_default);
1148                 }
1149                 _ => ()
1150             }
1151             Br(bcx, data.bodycx.llbb, DebugLoc::None);
1152         }
1153     }
1154 }
1155
1156 fn compile_submatch_continue<'a, 'p, 'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>,
1157                                                  m: &[Match<'a, 'p, 'blk, 'tcx>],
1158                                                  vals: &[MatchInput],
1159                                                  chk: &FailureHandler,
1160                                                  col: usize,
1161                                                  val: MatchInput,
1162                                                  has_genuine_default: bool) {
1163     let fcx = bcx.fcx;
1164     let tcx = bcx.tcx();
1165     let dm = &tcx.def_map;
1166
1167     let mut vals_left = vals[0..col].to_vec();
1168     vals_left.push_all(&vals[col + 1..]);
1169     let ccx = bcx.fcx.ccx;
1170
1171     // Find a real id (we're adding placeholder wildcard patterns, but
1172     // each column is guaranteed to have at least one real pattern)
1173     let pat_id = m.iter().map(|br| br.pats[col].id)
1174                          .find(|&id| id != DUMMY_NODE_ID)
1175                          .unwrap_or(DUMMY_NODE_ID);
1176
1177     let left_ty = if pat_id == DUMMY_NODE_ID {
1178         tcx.mk_nil()
1179     } else {
1180         node_id_type(bcx, pat_id)
1181     };
1182
1183     let mcx = check_match::MatchCheckCtxt {
1184         tcx: bcx.tcx(),
1185         param_env: bcx.tcx().empty_parameter_environment(),
1186     };
1187     let adt_vals = if any_irrefutable_adt_pat(bcx.tcx(), m, col) {
1188         let repr = adt::represent_type(bcx.ccx(), left_ty);
1189         let arg_count = adt::num_args(&*repr, 0);
1190         let (arg_count, struct_val) = if type_is_sized(bcx.tcx(), left_ty) {
1191             (arg_count, val.val)
1192         } else {
1193             // For an unsized ADT (i.e. DST struct), we need to treat
1194             // the last field specially: instead of simply passing a
1195             // ValueRef pointing to that field, as with all the others,
1196             // we skip it and instead construct a 'fat ptr' below.
1197             (arg_count - 1, Load(bcx, expr::get_dataptr(bcx, val.val)))
1198         };
1199         let mut field_vals: Vec<ValueRef> = (0..arg_count).map(|ix|
1200             adt::trans_field_ptr(bcx, &*repr, struct_val, 0, ix)
1201         ).collect();
1202
1203         match left_ty.sty {
1204             ty::TyStruct(def, substs) if !type_is_sized(bcx.tcx(), left_ty) => {
1205                 // The last field is technically unsized but
1206                 // since we can only ever match that field behind
1207                 // a reference we construct a fat ptr here.
1208                 let unsized_ty = def.struct_variant().fields.last().map(|field| {
1209                     monomorphize::field_ty(bcx.tcx(), substs, field)
1210                 }).unwrap();
1211                 let scratch = alloc_ty(bcx, unsized_ty, "__struct_field_fat_ptr");
1212                 let data = adt::trans_field_ptr(bcx, &*repr, struct_val, 0, arg_count);
1213                 let len = Load(bcx, expr::get_meta(bcx, val.val));
1214                 Store(bcx, data, expr::get_dataptr(bcx, scratch));
1215                 Store(bcx, len, expr::get_meta(bcx, scratch));
1216                 field_vals.push(scratch);
1217             }
1218             _ => {}
1219         }
1220         Some(field_vals)
1221     } else if any_uniq_pat(m, col) || any_region_pat(m, col) {
1222         Some(vec!(Load(bcx, val.val)))
1223     } else {
1224         match left_ty.sty {
1225             ty::TyArray(_, n) => {
1226                 let args = extract_vec_elems(bcx, left_ty, n, 0, val);
1227                 Some(args.vals)
1228             }
1229             _ => None
1230         }
1231     };
1232     match adt_vals {
1233         Some(field_vals) => {
1234             let pats = enter_match(bcx, dm, m, col, val, |pats|
1235                 check_match::specialize(&mcx, pats,
1236                                         &check_match::Single, col,
1237                                         field_vals.len())
1238             );
1239             let mut vals: Vec<_> = field_vals.into_iter()
1240                 .map(|v|MatchInput::from_val(v))
1241                 .collect();
1242             vals.push_all(&vals_left);
1243             compile_submatch(bcx, &pats, &vals, chk, has_genuine_default);
1244             return;
1245         }
1246         _ => ()
1247     }
1248
1249     // Decide what kind of branch we need
1250     let opts = get_branches(bcx, m, col);
1251     debug!("options={:?}", opts);
1252     let mut kind = NoBranch;
1253     let mut test_val = val.val;
1254     debug!("test_val={}", bcx.val_to_string(test_val));
1255     if !opts.is_empty() {
1256         match opts[0] {
1257             ConstantValue(..) | ConstantRange(..) => {
1258                 test_val = load_if_immediate(bcx, val.val, left_ty);
1259                 kind = if left_ty.is_integral() {
1260                     Switch
1261                 } else {
1262                     Compare
1263                 };
1264             }
1265             Variant(_, ref repr, _, _) => {
1266                 let (the_kind, val_opt) = adt::trans_switch(bcx, &**repr, val.val);
1267                 kind = the_kind;
1268                 if let Some(tval) = val_opt { test_val = tval; }
1269             }
1270             SliceLengthEqual(..) | SliceLengthGreaterOrEqual(..) => {
1271                 let (_, len) = tvec::get_base_and_len(bcx, val.val, left_ty);
1272                 test_val = len;
1273                 kind = Switch;
1274             }
1275         }
1276     }
1277     for o in &opts {
1278         match *o {
1279             ConstantRange(..) => { kind = Compare; break },
1280             SliceLengthGreaterOrEqual(..) => { kind = CompareSliceLength; break },
1281             _ => ()
1282         }
1283     }
1284     let else_cx = match kind {
1285         NoBranch | Single => bcx,
1286         _ => bcx.fcx.new_temp_block("match_else")
1287     };
1288     let sw = if kind == Switch {
1289         build::Switch(bcx, test_val, else_cx.llbb, opts.len())
1290     } else {
1291         C_int(ccx, 0) // Placeholder for when not using a switch
1292     };
1293
1294     let defaults = enter_default(else_cx, dm, m, col, val);
1295     let exhaustive = chk.is_infallible() && defaults.is_empty();
1296     let len = opts.len();
1297
1298     if exhaustive && kind == Switch {
1299         build::Unreachable(else_cx);
1300     }
1301
1302     // Compile subtrees for each option
1303     for (i, opt) in opts.iter().enumerate() {
1304         // In some cases of range and vector pattern matching, we need to
1305         // override the failure case so that instead of failing, it proceeds
1306         // to try more matching. branch_chk, then, is the proper failure case
1307         // for the current conditional branch.
1308         let mut branch_chk = None;
1309         let mut opt_cx = else_cx;
1310         let debug_loc = opt.debug_loc();
1311
1312         if kind == Switch || !exhaustive || i + 1 < len {
1313             opt_cx = bcx.fcx.new_temp_block("match_case");
1314             match kind {
1315                 Single => Br(bcx, opt_cx.llbb, debug_loc),
1316                 Switch => {
1317                     match opt.trans(bcx) {
1318                         SingleResult(r) => {
1319                             AddCase(sw, r.val, opt_cx.llbb);
1320                             bcx = r.bcx;
1321                         }
1322                         _ => {
1323                             bcx.sess().bug(
1324                                 "in compile_submatch, expected \
1325                                  opt.trans() to return a SingleResult")
1326                         }
1327                     }
1328                 }
1329                 Compare | CompareSliceLength => {
1330                     let t = if kind == Compare {
1331                         left_ty
1332                     } else {
1333                         tcx.types.usize // vector length
1334                     };
1335                     let Result { bcx: after_cx, val: matches } = {
1336                         match opt.trans(bcx) {
1337                             SingleResult(Result { bcx, val }) => {
1338                                 compare_values(bcx, test_val, val, t, debug_loc)
1339                             }
1340                             RangeResult(Result { val: vbegin, .. },
1341                                         Result { bcx, val: vend }) => {
1342                                 let llge = compare_scalar_types(bcx, test_val, vbegin,
1343                                                                 t, hir::BiGe, debug_loc);
1344                                 let llle = compare_scalar_types(bcx, test_val, vend,
1345                                                                 t, hir::BiLe, debug_loc);
1346                                 Result::new(bcx, And(bcx, llge, llle, DebugLoc::None))
1347                             }
1348                             LowerBound(Result { bcx, val }) => {
1349                                 Result::new(bcx, compare_scalar_types(bcx, test_val,
1350                                                                       val, t, hir::BiGe,
1351                                                                       debug_loc))
1352                             }
1353                         }
1354                     };
1355                     bcx = fcx.new_temp_block("compare_next");
1356
1357                     // If none of the sub-cases match, and the current condition
1358                     // is guarded or has multiple patterns, move on to the next
1359                     // condition, if there is any, rather than falling back to
1360                     // the default.
1361                     let guarded = m[i].data.arm.guard.is_some();
1362                     let multi_pats = m[i].pats.len() > 1;
1363                     if i + 1 < len && (guarded || multi_pats || kind == CompareSliceLength) {
1364                         branch_chk = Some(JumpToBasicBlock(bcx.llbb));
1365                     }
1366                     CondBr(after_cx, matches, opt_cx.llbb, bcx.llbb, debug_loc);
1367                 }
1368                 _ => ()
1369             }
1370         } else if kind == Compare || kind == CompareSliceLength {
1371             Br(bcx, else_cx.llbb, debug_loc);
1372         }
1373
1374         let mut size = 0;
1375         let mut unpacked = Vec::new();
1376         match *opt {
1377             Variant(disr_val, ref repr, _, _) => {
1378                 let ExtractedBlock {vals: argvals, bcx: new_bcx} =
1379                     extract_variant_args(opt_cx, &**repr, disr_val, val);
1380                 size = argvals.len();
1381                 unpacked = argvals;
1382                 opt_cx = new_bcx;
1383             }
1384             SliceLengthEqual(len, _) => {
1385                 let args = extract_vec_elems(opt_cx, left_ty, len, 0, val);
1386                 size = args.vals.len();
1387                 unpacked = args.vals.clone();
1388                 opt_cx = args.bcx;
1389             }
1390             SliceLengthGreaterOrEqual(before, after, _) => {
1391                 let args = extract_vec_elems(opt_cx, left_ty, before, after, val);
1392                 size = args.vals.len();
1393                 unpacked = args.vals.clone();
1394                 opt_cx = args.bcx;
1395             }
1396             ConstantValue(..) | ConstantRange(..) => ()
1397         }
1398         let opt_ms = enter_opt(opt_cx, pat_id, dm, m, opt, col, size, val);
1399         let mut opt_vals: Vec<_> = unpacked.into_iter()
1400             .map(|v|MatchInput::from_val(v))
1401             .collect();
1402         opt_vals.push_all(&vals_left[..]);
1403         compile_submatch(opt_cx,
1404                          &opt_ms[..],
1405                          &opt_vals[..],
1406                          branch_chk.as_ref().unwrap_or(chk),
1407                          has_genuine_default);
1408     }
1409
1410     // Compile the fall-through case, if any
1411     if !exhaustive && kind != Single {
1412         if kind == Compare || kind == CompareSliceLength {
1413             Br(bcx, else_cx.llbb, DebugLoc::None);
1414         }
1415         match chk {
1416             // If there is only one default arm left, move on to the next
1417             // condition explicitly rather than (eventually) falling back to
1418             // the last default arm.
1419             &JumpToBasicBlock(_) if defaults.len() == 1 && has_genuine_default => {
1420                 chk.handle_fail(else_cx);
1421             }
1422             _ => {
1423                 compile_submatch(else_cx,
1424                                  &defaults[..],
1425                                  &vals_left[..],
1426                                  chk,
1427                                  has_genuine_default);
1428             }
1429         }
1430     }
1431 }
1432
1433 pub fn trans_match<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1434                                match_expr: &hir::Expr,
1435                                discr_expr: &hir::Expr,
1436                                arms: &[hir::Arm],
1437                                dest: Dest)
1438                                -> Block<'blk, 'tcx> {
1439     let _icx = push_ctxt("match::trans_match");
1440     trans_match_inner(bcx, match_expr.id, discr_expr, arms, dest)
1441 }
1442
1443 /// Checks whether the binding in `discr` is assigned to anywhere in the expression `body`
1444 fn is_discr_reassigned(bcx: Block, discr: &hir::Expr, body: &hir::Expr) -> bool {
1445     let (vid, field) = match discr.node {
1446         hir::ExprPath(..) => match bcx.def(discr.id) {
1447             def::DefLocal(_, vid) | def::DefUpvar(_, vid, _, _) => (vid, None),
1448             _ => return false
1449         },
1450         hir::ExprField(ref base, field) => {
1451             let vid = match bcx.tcx().def_map.borrow().get(&base.id).map(|d| d.full_def()) {
1452                 Some(def::DefLocal(_, vid)) | Some(def::DefUpvar(_, vid, _, _)) => vid,
1453                 _ => return false
1454             };
1455             (vid, Some(mc::NamedField(field.node)))
1456         },
1457         hir::ExprTupField(ref base, field) => {
1458             let vid = match bcx.tcx().def_map.borrow().get(&base.id).map(|d| d.full_def()) {
1459                 Some(def::DefLocal(_, vid)) | Some(def::DefUpvar(_, vid, _, _)) => vid,
1460                 _ => return false
1461             };
1462             (vid, Some(mc::PositionalField(field.node)))
1463         },
1464         _ => return false
1465     };
1466
1467     let mut rc = ReassignmentChecker {
1468         node: vid,
1469         field: field,
1470         reassigned: false
1471     };
1472     {
1473         let infcx = infer::normalizing_infer_ctxt(bcx.tcx(), &bcx.tcx().tables);
1474         let mut visitor = euv::ExprUseVisitor::new(&mut rc, &infcx);
1475         visitor.walk_expr(body);
1476     }
1477     rc.reassigned
1478 }
1479
1480 struct ReassignmentChecker {
1481     node: ast::NodeId,
1482     field: Option<mc::FieldName>,
1483     reassigned: bool
1484 }
1485
1486 // Determine if the expression we're matching on is reassigned to within
1487 // the body of the match's arm.
1488 // We only care for the `mutate` callback since this check only matters
1489 // for cases where the matched value is moved.
1490 impl<'tcx> euv::Delegate<'tcx> for ReassignmentChecker {
1491     fn consume(&mut self, _: ast::NodeId, _: Span, _: mc::cmt, _: euv::ConsumeMode) {}
1492     fn matched_pat(&mut self, _: &hir::Pat, _: mc::cmt, _: euv::MatchMode) {}
1493     fn consume_pat(&mut self, _: &hir::Pat, _: mc::cmt, _: euv::ConsumeMode) {}
1494     fn borrow(&mut self, _: ast::NodeId, _: Span, _: mc::cmt, _: ty::Region,
1495               _: ty::BorrowKind, _: euv::LoanCause) {}
1496     fn decl_without_init(&mut self, _: ast::NodeId, _: Span) {}
1497
1498     fn mutate(&mut self, _: ast::NodeId, _: Span, cmt: mc::cmt, _: euv::MutateMode) {
1499         match cmt.cat {
1500             Categorization::Upvar(mc::Upvar { id: ty::UpvarId { var_id: vid, .. }, .. }) |
1501             Categorization::Local(vid) => self.reassigned |= self.node == vid,
1502             Categorization::Interior(ref base_cmt, mc::InteriorField(field)) => {
1503                 match base_cmt.cat {
1504                     Categorization::Upvar(mc::Upvar { id: ty::UpvarId { var_id: vid, .. }, .. }) |
1505                     Categorization::Local(vid) => {
1506                         self.reassigned |= self.node == vid &&
1507                             (self.field.is_none() || Some(field) == self.field)
1508                     },
1509                     _ => {}
1510                 }
1511             },
1512             _ => {}
1513         }
1514     }
1515 }
1516
1517 fn create_bindings_map<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, pat: &hir::Pat,
1518                                    discr: &hir::Expr, body: &hir::Expr)
1519                                    -> BindingsMap<'tcx> {
1520     // Create the bindings map, which is a mapping from each binding name
1521     // to an alloca() that will be the value for that local variable.
1522     // Note that we use the names because each binding will have many ids
1523     // from the various alternatives.
1524     let ccx = bcx.ccx();
1525     let tcx = bcx.tcx();
1526     let reassigned = is_discr_reassigned(bcx, discr, body);
1527     let mut bindings_map = FnvHashMap();
1528     pat_bindings(&tcx.def_map, &*pat, |bm, p_id, span, path1| {
1529         let name = path1.node;
1530         let variable_ty = node_id_type(bcx, p_id);
1531         let llvariable_ty = type_of::type_of(ccx, variable_ty);
1532         let tcx = bcx.tcx();
1533         let param_env = tcx.empty_parameter_environment();
1534
1535         let llmatch;
1536         let trmode;
1537         let moves_by_default = variable_ty.moves_by_default(&param_env, span);
1538         match bm {
1539             hir::BindByValue(_) if !moves_by_default || reassigned =>
1540             {
1541                 llmatch = alloca(bcx, llvariable_ty.ptr_to(), "__llmatch");
1542                 let llcopy = alloca(bcx, llvariable_ty, &bcx.name(name));
1543                 trmode = if moves_by_default {
1544                     TrByMoveIntoCopy(llcopy)
1545                 } else {
1546                     TrByCopy(llcopy)
1547                 };
1548             }
1549             hir::BindByValue(_) => {
1550                 // in this case, the final type of the variable will be T,
1551                 // but during matching we need to store a *T as explained
1552                 // above
1553                 llmatch = alloca(bcx, llvariable_ty.ptr_to(), &bcx.name(name));
1554                 trmode = TrByMoveRef;
1555             }
1556             hir::BindByRef(_) => {
1557                 llmatch = alloca(bcx, llvariable_ty, &bcx.name(name));
1558                 trmode = TrByRef;
1559             }
1560         };
1561         bindings_map.insert(name, BindingInfo {
1562             llmatch: llmatch,
1563             trmode: trmode,
1564             id: p_id,
1565             span: span,
1566             ty: variable_ty
1567         });
1568     });
1569     return bindings_map;
1570 }
1571
1572 fn trans_match_inner<'blk, 'tcx>(scope_cx: Block<'blk, 'tcx>,
1573                                  match_id: ast::NodeId,
1574                                  discr_expr: &hir::Expr,
1575                                  arms: &[hir::Arm],
1576                                  dest: Dest) -> Block<'blk, 'tcx> {
1577     let _icx = push_ctxt("match::trans_match_inner");
1578     let fcx = scope_cx.fcx;
1579     let mut bcx = scope_cx;
1580     let tcx = bcx.tcx();
1581
1582     let discr_datum = unpack_datum!(bcx, expr::trans_to_lvalue(bcx, discr_expr,
1583                                                                "match"));
1584     if bcx.unreachable.get() {
1585         return bcx;
1586     }
1587
1588     let t = node_id_type(bcx, discr_expr.id);
1589     let chk = if t.is_empty(tcx) {
1590         Unreachable
1591     } else {
1592         Infallible
1593     };
1594
1595     let arm_datas: Vec<ArmData> = arms.iter().map(|arm| ArmData {
1596         bodycx: fcx.new_id_block("case_body", arm.body.id),
1597         arm: arm,
1598         bindings_map: create_bindings_map(bcx, &*arm.pats[0], discr_expr, &*arm.body)
1599     }).collect();
1600
1601     let mut pat_renaming_map = if scope_cx.sess().opts.debuginfo != NoDebugInfo {
1602         Some(FnvHashMap())
1603     } else {
1604         None
1605     };
1606
1607     let arm_pats: Vec<Vec<P<hir::Pat>>> = {
1608         let mut static_inliner = StaticInliner::new(scope_cx.tcx(),
1609                                                     pat_renaming_map.as_mut());
1610         arm_datas.iter().map(|arm_data| {
1611             arm_data.arm.pats.iter().map(|p| static_inliner.fold_pat((*p).clone())).collect()
1612         }).collect()
1613     };
1614
1615     let mut matches = Vec::new();
1616     for (arm_data, pats) in arm_datas.iter().zip(&arm_pats) {
1617         matches.extend(pats.iter().map(|p| Match {
1618             pats: vec![&**p],
1619             data: arm_data,
1620             bound_ptrs: Vec::new(),
1621             pat_renaming_map: pat_renaming_map.as_ref()
1622         }));
1623     }
1624
1625     // `compile_submatch` works one column of arm patterns a time and
1626     // then peels that column off. So as we progress, it may become
1627     // impossible to tell whether we have a genuine default arm, i.e.
1628     // `_ => foo` or not. Sometimes it is important to know that in order
1629     // to decide whether moving on to the next condition or falling back
1630     // to the default arm.
1631     let has_default = arms.last().map_or(false, |arm| {
1632         arm.pats.len() == 1
1633         && arm.pats.last().unwrap().node == hir::PatWild
1634     });
1635
1636     compile_submatch(bcx, &matches[..], &[discr_datum.match_input()], &chk, has_default);
1637
1638     let mut arm_cxs = Vec::new();
1639     for arm_data in &arm_datas {
1640         let mut bcx = arm_data.bodycx;
1641
1642         // insert bindings into the lllocals map and add cleanups
1643         let cs = fcx.push_custom_cleanup_scope();
1644         bcx = insert_lllocals(bcx, &arm_data.bindings_map, Some(cleanup::CustomScope(cs)));
1645         bcx = expr::trans_into(bcx, &*arm_data.arm.body, dest);
1646         bcx = fcx.pop_and_trans_custom_cleanup_scope(bcx, cs);
1647         arm_cxs.push(bcx);
1648     }
1649
1650     bcx = scope_cx.fcx.join_blocks(match_id, &arm_cxs[..]);
1651     return bcx;
1652 }
1653
1654 /// Generates code for a local variable declaration like `let <pat>;` or `let <pat> =
1655 /// <opt_init_expr>`.
1656 pub fn store_local<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1657                                local: &hir::Local)
1658                                -> Block<'blk, 'tcx> {
1659     let _icx = push_ctxt("match::store_local");
1660     let mut bcx = bcx;
1661     let tcx = bcx.tcx();
1662     let pat = &*local.pat;
1663
1664     fn create_dummy_locals<'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>,
1665                                        pat: &hir::Pat)
1666                                        -> Block<'blk, 'tcx> {
1667         let _icx = push_ctxt("create_dummy_locals");
1668         // create dummy memory for the variables if we have no
1669         // value to store into them immediately
1670         let tcx = bcx.tcx();
1671         pat_bindings(&tcx.def_map, pat, |_, p_id, _, path1| {
1672             let scope = cleanup::var_scope(tcx, p_id);
1673             bcx = mk_binding_alloca(
1674                 bcx, p_id, path1.node, scope, (),
1675                 "_match::store_local::create_dummy_locals",
1676                 |(), bcx, Datum { val: llval, ty, kind }| {
1677                     // Dummy-locals start out uninitialized, so set their
1678                     // drop-flag hints (if any) to "moved."
1679                     if let Some(hint) = kind.dropflag_hint(bcx) {
1680                         let moved_hint = adt::DTOR_MOVED_HINT;
1681                         debug!("store moved_hint={} for hint={:?}, uninitialized dummy",
1682                                moved_hint, hint);
1683                         Store(bcx, C_u8(bcx.fcx.ccx, moved_hint), hint.to_value().value());
1684                     }
1685
1686                     if kind.drop_flag_info.must_zero() {
1687                         // if no drop-flag hint, or the hint requires
1688                         // we maintain the embedded drop-flag, then
1689                         // mark embedded drop-flag(s) as moved
1690                         // (i.e. "already dropped").
1691                         drop_done_fill_mem(bcx, llval, ty);
1692                     }
1693                     bcx
1694                 });
1695         });
1696         bcx
1697     }
1698
1699     match local.init {
1700         Some(ref init_expr) => {
1701             // Optimize the "let x = expr" case. This just writes
1702             // the result of evaluating `expr` directly into the alloca
1703             // for `x`. Often the general path results in similar or the
1704             // same code post-optimization, but not always. In particular,
1705             // in unsafe code, you can have expressions like
1706             //
1707             //    let x = intrinsics::uninit();
1708             //
1709             // In such cases, the more general path is unsafe, because
1710             // it assumes it is matching against a valid value.
1711             match simple_name(pat) {
1712                 Some(name) => {
1713                     let var_scope = cleanup::var_scope(tcx, local.id);
1714                     return mk_binding_alloca(
1715                         bcx, pat.id, name, var_scope, (),
1716                         "_match::store_local",
1717                         |(), bcx, Datum { val: v, .. }| expr::trans_into(bcx, &**init_expr,
1718                                                                          expr::SaveIn(v)));
1719                 }
1720
1721                 None => {}
1722             }
1723
1724             // General path.
1725             let init_datum =
1726                 unpack_datum!(bcx, expr::trans_to_lvalue(bcx, &**init_expr, "let"));
1727             if bcx.sess().asm_comments() {
1728                 add_comment(bcx, "creating zeroable ref llval");
1729             }
1730             let var_scope = cleanup::var_scope(tcx, local.id);
1731             bind_irrefutable_pat(bcx, pat, init_datum.match_input(), var_scope)
1732         }
1733         None => {
1734             create_dummy_locals(bcx, pat)
1735         }
1736     }
1737 }
1738
1739 fn mk_binding_alloca<'blk, 'tcx, A, F>(bcx: Block<'blk, 'tcx>,
1740                                        p_id: ast::NodeId,
1741                                        name: ast::Name,
1742                                        cleanup_scope: cleanup::ScopeId,
1743                                        arg: A,
1744                                        caller_name: &'static str,
1745                                        populate: F)
1746                                        -> Block<'blk, 'tcx> where
1747     F: FnOnce(A, Block<'blk, 'tcx>, Datum<'tcx, Lvalue>) -> Block<'blk, 'tcx>,
1748 {
1749     let var_ty = node_id_type(bcx, p_id);
1750
1751     // Allocate memory on stack for the binding.
1752     let llval = alloc_ty(bcx, var_ty, &bcx.name(name));
1753     let lvalue = Lvalue::new_with_hint(caller_name, bcx, p_id, HintKind::DontZeroJustUse);
1754     let datum = Datum::new(llval, var_ty, lvalue);
1755
1756     // Subtle: be sure that we *populate* the memory *before*
1757     // we schedule the cleanup.
1758     call_lifetime_start(bcx, llval);
1759     let bcx = populate(arg, bcx, datum);
1760     bcx.fcx.schedule_lifetime_end(cleanup_scope, llval);
1761     bcx.fcx.schedule_drop_mem(cleanup_scope, llval, var_ty, lvalue.dropflag_hint(bcx));
1762
1763     // Now that memory is initialized and has cleanup scheduled,
1764     // insert datum into the local variable map.
1765     bcx.fcx.lllocals.borrow_mut().insert(p_id, datum);
1766     bcx
1767 }
1768
1769 /// A simple version of the pattern matching code that only handles
1770 /// irrefutable patterns. This is used in let/argument patterns,
1771 /// not in match statements. Unifying this code with the code above
1772 /// sounds nice, but in practice it produces very inefficient code,
1773 /// since the match code is so much more general. In most cases,
1774 /// LLVM is able to optimize the code, but it causes longer compile
1775 /// times and makes the generated code nigh impossible to read.
1776 ///
1777 /// # Arguments
1778 /// - bcx: starting basic block context
1779 /// - pat: the irrefutable pattern being matched.
1780 /// - val: the value being matched -- must be an lvalue (by ref, with cleanup)
1781 pub fn bind_irrefutable_pat<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1782                                     pat: &hir::Pat,
1783                                     val: MatchInput,
1784                                     cleanup_scope: cleanup::ScopeId)
1785                                     -> Block<'blk, 'tcx> {
1786     debug!("bind_irrefutable_pat(bcx={}, pat={:?})",
1787            bcx.to_str(),
1788            pat);
1789
1790     if bcx.sess().asm_comments() {
1791         add_comment(bcx, &format!("bind_irrefutable_pat(pat={:?})",
1792                                  pat));
1793     }
1794
1795     let _indenter = indenter();
1796
1797     let _icx = push_ctxt("match::bind_irrefutable_pat");
1798     let mut bcx = bcx;
1799     let tcx = bcx.tcx();
1800     let ccx = bcx.ccx();
1801     match pat.node {
1802         hir::PatIdent(pat_binding_mode, ref path1, ref inner) => {
1803             if pat_is_binding(&tcx.def_map, &*pat) {
1804                 // Allocate the stack slot where the value of this
1805                 // binding will live and place it into the appropriate
1806                 // map.
1807                 bcx = mk_binding_alloca(
1808                     bcx, pat.id, path1.node.name, cleanup_scope, (),
1809                     "_match::bind_irrefutable_pat",
1810                     |(), bcx, Datum { val: llval, ty, kind: _ }| {
1811                         match pat_binding_mode {
1812                             hir::BindByValue(_) => {
1813                                 // By value binding: move the value that `val`
1814                                 // points at into the binding's stack slot.
1815                                 let d = val.to_datum(ty);
1816                                 d.store_to(bcx, llval)
1817                             }
1818
1819                             hir::BindByRef(_) => {
1820                                 // By ref binding: the value of the variable
1821                                 // is the pointer `val` itself or fat pointer referenced by `val`
1822                                 if type_is_fat_ptr(bcx.tcx(), ty) {
1823                                     expr::copy_fat_ptr(bcx, val.val, llval);
1824                                 }
1825                                 else {
1826                                     Store(bcx, val.val, llval);
1827                                 }
1828
1829                                 bcx
1830                             }
1831                         }
1832                     });
1833             }
1834
1835             if let Some(ref inner_pat) = *inner {
1836                 bcx = bind_irrefutable_pat(bcx, &**inner_pat, val, cleanup_scope);
1837             }
1838         }
1839         hir::PatEnum(_, ref sub_pats) => {
1840             let opt_def = bcx.tcx().def_map.borrow().get(&pat.id).map(|d| d.full_def());
1841             match opt_def {
1842                 Some(def::DefVariant(enum_id, var_id, _)) => {
1843                     let repr = adt::represent_node(bcx, pat.id);
1844                     let vinfo = ccx.tcx().lookup_adt_def(enum_id).variant_with_id(var_id);
1845                     let args = extract_variant_args(bcx,
1846                                                     &*repr,
1847                                                     vinfo.disr_val,
1848                                                     val);
1849                     if let Some(ref sub_pat) = *sub_pats {
1850                         for (i, &argval) in args.vals.iter().enumerate() {
1851                             bcx = bind_irrefutable_pat(
1852                                 bcx,
1853                                 &*sub_pat[i],
1854                                 MatchInput::from_val(argval),
1855                                 cleanup_scope);
1856                         }
1857                     }
1858                 }
1859                 Some(def::DefStruct(..)) => {
1860                     match *sub_pats {
1861                         None => {
1862                             // This is a unit-like struct. Nothing to do here.
1863                         }
1864                         Some(ref elems) => {
1865                             // This is the tuple struct case.
1866                             let repr = adt::represent_node(bcx, pat.id);
1867                             for (i, elem) in elems.iter().enumerate() {
1868                                 let fldptr = adt::trans_field_ptr(bcx, &*repr,
1869                                                                   val.val, 0, i);
1870                                 bcx = bind_irrefutable_pat(
1871                                     bcx,
1872                                     &**elem,
1873                                     MatchInput::from_val(fldptr),
1874                                     cleanup_scope);
1875                             }
1876                         }
1877                     }
1878                 }
1879                 _ => {
1880                     // Nothing to do here.
1881                 }
1882             }
1883         }
1884         hir::PatStruct(_, ref fields, _) => {
1885             let tcx = bcx.tcx();
1886             let pat_ty = node_id_type(bcx, pat.id);
1887             let pat_repr = adt::represent_type(bcx.ccx(), pat_ty);
1888             let pat_v = VariantInfo::of_node(tcx, pat_ty, pat.id);
1889             for f in fields {
1890                 let name = f.node.name;
1891                 let fldptr = adt::trans_field_ptr(
1892                     bcx,
1893                     &*pat_repr,
1894                     val.val,
1895                     pat_v.discr,
1896                     pat_v.field_index(name));
1897                 bcx = bind_irrefutable_pat(bcx,
1898                                            &*f.node.pat,
1899                                            MatchInput::from_val(fldptr),
1900                                            cleanup_scope);
1901             }
1902         }
1903         hir::PatTup(ref elems) => {
1904             let repr = adt::represent_node(bcx, pat.id);
1905             for (i, elem) in elems.iter().enumerate() {
1906                 let fldptr = adt::trans_field_ptr(bcx, &*repr, val.val, 0, i);
1907                 bcx = bind_irrefutable_pat(
1908                     bcx,
1909                     &**elem,
1910                     MatchInput::from_val(fldptr),
1911                     cleanup_scope);
1912             }
1913         }
1914         hir::PatBox(ref inner) => {
1915             let llbox = Load(bcx, val.val);
1916             bcx = bind_irrefutable_pat(
1917                 bcx, &**inner, MatchInput::from_val(llbox), cleanup_scope);
1918         }
1919         hir::PatRegion(ref inner, _) => {
1920             let loaded_val = Load(bcx, val.val);
1921             bcx = bind_irrefutable_pat(
1922                 bcx,
1923                 &**inner,
1924                 MatchInput::from_val(loaded_val),
1925                 cleanup_scope);
1926         }
1927         hir::PatVec(ref before, ref slice, ref after) => {
1928             let pat_ty = node_id_type(bcx, pat.id);
1929             let mut extracted = extract_vec_elems(bcx, pat_ty, before.len(), after.len(), val);
1930             match slice {
1931                 &Some(_) => {
1932                     extracted.vals.insert(
1933                         before.len(),
1934                         bind_subslice_pat(bcx, pat.id, val, before.len(), after.len())
1935                     );
1936                 }
1937                 &None => ()
1938             }
1939             bcx = before
1940                 .iter()
1941                 .chain(slice.iter())
1942                 .chain(after.iter())
1943                 .zip(extracted.vals)
1944                 .fold(bcx, |bcx, (inner, elem)| {
1945                     bind_irrefutable_pat(
1946                         bcx,
1947                         &**inner,
1948                         MatchInput::from_val(elem),
1949                         cleanup_scope)
1950                 });
1951         }
1952         hir::PatQPath(..) | hir::PatWild | hir::PatLit(_) |
1953         hir::PatRange(_, _) => ()
1954     }
1955     return bcx;
1956 }