]> git.lizzy.rs Git - rust.git/blob - src/librustc_trans/trans/_match.rs
Change some instances of .connect() to .join()
[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 back::abi;
192 use llvm::{ValueRef, BasicBlockRef};
193 use middle::check_match::StaticInliner;
194 use middle::check_match;
195 use middle::const_eval;
196 use middle::def::{self, DefMap};
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::pat_util::*;
202 use trans::adt;
203 use trans::base::*;
204 use trans::build::{AddCase, And, Br, CondBr, GEPi, InBoundsGEP, Load, PointerCast};
205 use trans::build::{Not, Store, Sub, add_comment};
206 use trans::build;
207 use trans::callee;
208 use trans::cleanup::{self, CleanupMethods};
209 use trans::common::*;
210 use trans::consts;
211 use trans::datum::*;
212 use trans::debuginfo::{self, DebugLoc, ToDebugLoc};
213 use trans::expr::{self, Dest};
214 use trans::monomorphize;
215 use trans::tvec;
216 use trans::type_of;
217 use middle::ty::{self, Ty};
218 use session::config::NoDebugInfo;
219 use util::common::indenter;
220 use util::nodemap::FnvHashMap;
221 use util::ppaux;
222
223 use std;
224 use std::cmp::Ordering;
225 use std::fmt;
226 use std::rc::Rc;
227 use syntax::ast;
228 use syntax::ast::{DUMMY_NODE_ID, NodeId};
229 use syntax::codemap::Span;
230 use syntax::fold::Folder;
231 use syntax::ptr::P;
232
233 #[derive(Copy, Clone, Debug)]
234 struct ConstantExpr<'a>(&'a ast::Expr);
235
236 impl<'a> ConstantExpr<'a> {
237     fn eq(self, other: ConstantExpr<'a>, tcx: &ty::ctxt) -> bool {
238         match const_eval::compare_lit_exprs(tcx, self.0, other.0, None,
239                                             |id| {tcx.node_id_item_substs(id).substs}) {
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>>, ast::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         let _icx = push_ctxt("match::trans_opt");
280         let ccx = bcx.ccx();
281         match *self {
282             ConstantValue(ConstantExpr(lit_expr), _) => {
283                 let lit_ty = bcx.tcx().node_id_to_type(lit_expr.id);
284                 let (llval, _) = consts::const_expr(ccx, &*lit_expr, bcx.fcx.param_substs, None);
285                 let lit_datum = immediate_rvalue(llval, lit_ty);
286                 let lit_datum = unpack_datum!(bcx, lit_datum.to_appropriate_datum(bcx));
287                 SingleResult(Result::new(bcx, lit_datum.val))
288             }
289             ConstantRange(ConstantExpr(ref l1), ConstantExpr(ref l2), _) => {
290                 let (l1, _) = consts::const_expr(ccx, &**l1, bcx.fcx.param_substs, None);
291                 let (l2, _) = consts::const_expr(ccx, &**l2, bcx.fcx.param_substs, None);
292                 RangeResult(Result::new(bcx, l1), Result::new(bcx, l2))
293             }
294             Variant(disr_val, ref repr, _, _) => {
295                 adt::trans_case(bcx, &**repr, disr_val)
296             }
297             SliceLengthEqual(length, _) => {
298                 SingleResult(Result::new(bcx, C_uint(ccx, length)))
299             }
300             SliceLengthGreaterOrEqual(prefix, suffix, _) => {
301                 LowerBound(Result::new(bcx, C_uint(ccx, prefix + suffix)))
302             }
303         }
304     }
305
306     fn debug_loc(&self) -> DebugLoc {
307         match *self {
308             ConstantValue(_,debug_loc)                 |
309             ConstantRange(_, _, debug_loc)             |
310             Variant(_, _, _, debug_loc)                |
311             SliceLengthEqual(_, debug_loc)             |
312             SliceLengthGreaterOrEqual(_, _, debug_loc) => debug_loc
313         }
314     }
315 }
316
317 #[derive(Copy, Clone, PartialEq)]
318 pub enum BranchKind {
319     NoBranch,
320     Single,
321     Switch,
322     Compare,
323     CompareSliceLength
324 }
325
326 pub enum OptResult<'blk, 'tcx: 'blk> {
327     SingleResult(Result<'blk, 'tcx>),
328     RangeResult(Result<'blk, 'tcx>, Result<'blk, 'tcx>),
329     LowerBound(Result<'blk, 'tcx>)
330 }
331
332 #[derive(Clone, Copy, PartialEq)]
333 pub enum TransBindingMode {
334     TrByCopy(/* llbinding */ ValueRef),
335     TrByMove,
336     TrByRef,
337 }
338
339 /// Information about a pattern binding:
340 /// - `llmatch` is a pointer to a stack slot.  The stack slot contains a
341 ///   pointer into the value being matched.  Hence, llmatch has type `T**`
342 ///   where `T` is the value being matched.
343 /// - `trmode` is the trans binding mode
344 /// - `id` is the node id of the binding
345 /// - `ty` is the Rust type of the binding
346 #[derive(Clone, Copy)]
347 pub struct BindingInfo<'tcx> {
348     pub llmatch: ValueRef,
349     pub trmode: TransBindingMode,
350     pub id: ast::NodeId,
351     pub span: Span,
352     pub ty: Ty<'tcx>,
353 }
354
355 type BindingsMap<'tcx> = FnvHashMap<ast::Ident, BindingInfo<'tcx>>;
356
357 struct ArmData<'p, 'blk, 'tcx: 'blk> {
358     bodycx: Block<'blk, 'tcx>,
359     arm: &'p ast::Arm,
360     bindings_map: BindingsMap<'tcx>
361 }
362
363 /// Info about Match.
364 /// If all `pats` are matched then arm `data` will be executed.
365 /// As we proceed `bound_ptrs` are filled with pointers to values to be bound,
366 /// these pointers are stored in llmatch variables just before executing `data` arm.
367 struct Match<'a, 'p: 'a, 'blk: 'a, 'tcx: 'blk> {
368     pats: Vec<&'p ast::Pat>,
369     data: &'a ArmData<'p, 'blk, 'tcx>,
370     bound_ptrs: Vec<(ast::Ident, ValueRef)>,
371     // Thread along renamings done by the check_match::StaticInliner, so we can
372     // map back to original NodeIds
373     pat_renaming_map: Option<&'a FnvHashMap<(NodeId, Span), NodeId>>
374 }
375
376 impl<'a, 'p, 'blk, 'tcx> fmt::Debug for Match<'a, 'p, 'blk, 'tcx> {
377     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
378         if ppaux::verbose() {
379             // for many programs, this just take too long to serialize
380             write!(f, "{:?}", self.pats)
381         } else {
382             write!(f, "{} pats", self.pats.len())
383         }
384     }
385 }
386
387 fn has_nested_bindings(m: &[Match], col: usize) -> bool {
388     for br in m {
389         match br.pats[col].node {
390             ast::PatIdent(_, _, Some(_)) => return true,
391             _ => ()
392         }
393     }
394     return false;
395 }
396
397 fn expand_nested_bindings<'a, 'p, 'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
398                                               m: &[Match<'a, 'p, 'blk, 'tcx>],
399                                               col: usize,
400                                               val: ValueRef)
401                                               -> Vec<Match<'a, 'p, 'blk, 'tcx>> {
402     debug!("expand_nested_bindings(bcx={}, m={:?}, col={}, val={})",
403            bcx.to_str(),
404            m,
405            col,
406            bcx.val_to_string(val));
407     let _indenter = indenter();
408
409     m.iter().map(|br| {
410         let mut bound_ptrs = br.bound_ptrs.clone();
411         let mut pat = br.pats[col];
412         loop {
413             pat = match pat.node {
414                 ast::PatIdent(_, ref path, Some(ref inner)) => {
415                     bound_ptrs.push((path.node, val));
416                     &**inner
417                 },
418                 _ => break
419             }
420         }
421
422         let mut pats = br.pats.clone();
423         pats[col] = pat;
424         Match {
425             pats: pats,
426             data: &*br.data,
427             bound_ptrs: bound_ptrs,
428             pat_renaming_map: br.pat_renaming_map,
429         }
430     }).collect()
431 }
432
433 fn enter_match<'a, 'b, 'p, 'blk, 'tcx, F>(bcx: Block<'blk, 'tcx>,
434                                           dm: &DefMap,
435                                           m: &[Match<'a, 'p, 'blk, 'tcx>],
436                                           col: usize,
437                                           val: ValueRef,
438                                           mut e: F)
439                                           -> Vec<Match<'a, 'p, 'blk, 'tcx>> where
440     F: FnMut(&[&'p ast::Pat]) -> Option<Vec<&'p ast::Pat>>,
441 {
442     debug!("enter_match(bcx={}, m={:?}, col={}, val={})",
443            bcx.to_str(),
444            m,
445            col,
446            bcx.val_to_string(val));
447     let _indenter = indenter();
448
449     m.iter().filter_map(|br| {
450         e(&br.pats).map(|pats| {
451             let this = br.pats[col];
452             let mut bound_ptrs = br.bound_ptrs.clone();
453             match this.node {
454                 ast::PatIdent(_, ref path, None) => {
455                     if pat_is_binding(dm, &*this) {
456                         bound_ptrs.push((path.node, val));
457                     }
458                 }
459                 ast::PatVec(ref before, Some(ref slice), ref after) => {
460                     if let ast::PatIdent(_, ref path, None) = slice.node {
461                         let subslice_val = bind_subslice_pat(
462                             bcx, this.id, val,
463                             before.len(), after.len());
464                         bound_ptrs.push((path.node, subslice_val));
465                     }
466                 }
467                 _ => {}
468             }
469             Match {
470                 pats: pats,
471                 data: br.data,
472                 bound_ptrs: bound_ptrs,
473                 pat_renaming_map: br.pat_renaming_map,
474             }
475         })
476     }).collect()
477 }
478
479 fn enter_default<'a, 'p, 'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
480                                      dm: &DefMap,
481                                      m: &[Match<'a, 'p, 'blk, 'tcx>],
482                                      col: usize,
483                                      val: ValueRef)
484                                      -> Vec<Match<'a, 'p, 'blk, 'tcx>> {
485     debug!("enter_default(bcx={}, m={:?}, col={}, val={})",
486            bcx.to_str(),
487            m,
488            col,
489            bcx.val_to_string(val));
490     let _indenter = indenter();
491
492     // Collect all of the matches that can match against anything.
493     enter_match(bcx, dm, m, col, val, |pats| {
494         if pat_is_binding_or_wild(dm, &*pats[col]) {
495             let mut r = pats[..col].to_vec();
496             r.push_all(&pats[col + 1..]);
497             Some(r)
498         } else {
499             None
500         }
501     })
502 }
503
504 // <pcwalton> nmatsakis: what does enter_opt do?
505 // <pcwalton> in trans/match
506 // <pcwalton> trans/match.rs is like stumbling around in a dark cave
507 // <nmatsakis> pcwalton: the enter family of functions adjust the set of
508 //             patterns as needed
509 // <nmatsakis> yeah, at some point I kind of achieved some level of
510 //             understanding
511 // <nmatsakis> anyhow, they adjust the patterns given that something of that
512 //             kind has been found
513 // <nmatsakis> pcwalton: ok, right, so enter_XXX() adjusts the patterns, as I
514 //             said
515 // <nmatsakis> enter_match() kind of embodies the generic code
516 // <nmatsakis> it is provided with a function that tests each pattern to see
517 //             if it might possibly apply and so forth
518 // <nmatsakis> so, if you have a pattern like {a: _, b: _, _} and one like _
519 // <nmatsakis> then _ would be expanded to (_, _)
520 // <nmatsakis> one spot for each of the sub-patterns
521 // <nmatsakis> enter_opt() is one of the more complex; it covers the fallible
522 //             cases
523 // <nmatsakis> enter_rec_or_struct() or enter_tuple() are simpler, since they
524 //             are infallible patterns
525 // <nmatsakis> so all patterns must either be records (resp. tuples) or
526 //             wildcards
527
528 /// The above is now outdated in that enter_match() now takes a function that
529 /// takes the complete row of patterns rather than just the first one.
530 /// Also, most of the enter_() family functions have been unified with
531 /// the check_match specialization step.
532 fn enter_opt<'a, 'p, 'blk, 'tcx>(
533              bcx: Block<'blk, 'tcx>,
534              _: ast::NodeId,
535              dm: &DefMap,
536              m: &[Match<'a, 'p, 'blk, 'tcx>],
537              opt: &Opt,
538              col: usize,
539              variant_size: usize,
540              val: ValueRef)
541              -> Vec<Match<'a, 'p, 'blk, 'tcx>> {
542     debug!("enter_opt(bcx={}, m={:?}, opt={:?}, col={}, val={})",
543            bcx.to_str(),
544            m,
545            *opt,
546            col,
547            bcx.val_to_string(val));
548     let _indenter = indenter();
549
550     let ctor = match opt {
551         &ConstantValue(ConstantExpr(expr), _) => check_match::ConstantValue(
552             const_eval::eval_const_expr(bcx.tcx(), &*expr)
553         ),
554         &ConstantRange(ConstantExpr(lo), ConstantExpr(hi), _) => check_match::ConstantRange(
555             const_eval::eval_const_expr(bcx.tcx(), &*lo),
556             const_eval::eval_const_expr(bcx.tcx(), &*hi)
557         ),
558         &SliceLengthEqual(n, _) =>
559             check_match::Slice(n),
560         &SliceLengthGreaterOrEqual(before, after, _) =>
561             check_match::SliceWithSubslice(before, after),
562         &Variant(_, _, def_id, _) =>
563             check_match::Constructor::Variant(def_id)
564     };
565
566     let param_env = bcx.tcx().empty_parameter_environment();
567     let mcx = check_match::MatchCheckCtxt {
568         tcx: bcx.tcx(),
569         param_env: param_env,
570     };
571     enter_match(bcx, dm, m, col, val, |pats|
572         check_match::specialize(&mcx, &pats[..], &ctor, col, variant_size)
573     )
574 }
575
576 // Returns the options in one column of matches. An option is something that
577 // needs to be conditionally matched at runtime; for example, the discriminant
578 // on a set of enum variants or a literal.
579 fn get_branches<'a, 'p, 'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
580                                     m: &[Match<'a, 'p, 'blk, 'tcx>],
581                                     col: usize)
582                                     -> Vec<Opt<'p, 'tcx>> {
583     let tcx = bcx.tcx();
584
585     let mut found: Vec<Opt> = vec![];
586     for br in m {
587         let cur = br.pats[col];
588         let debug_loc = match br.pat_renaming_map {
589             Some(pat_renaming_map) => {
590                 match pat_renaming_map.get(&(cur.id, cur.span)) {
591                     Some(&id) => DebugLoc::At(id, cur.span),
592                     None => DebugLoc::At(cur.id, cur.span),
593                 }
594             }
595             None => DebugLoc::None
596         };
597
598         let opt = match cur.node {
599             ast::PatLit(ref l) => {
600                 ConstantValue(ConstantExpr(&**l), debug_loc)
601             }
602             ast::PatIdent(..) | ast::PatEnum(..) | ast::PatStruct(..) => {
603                 // This is either an enum variant or a variable binding.
604                 let opt_def = tcx.def_map.borrow().get(&cur.id).map(|d| d.full_def());
605                 match opt_def {
606                     Some(def::DefVariant(enum_id, var_id, _)) => {
607                         let variant = tcx.enum_variant_with_id(enum_id, var_id);
608                         Variant(variant.disr_val,
609                                 adt::represent_node(bcx, cur.id),
610                                 var_id,
611                                 debug_loc)
612                     }
613                     _ => continue
614                 }
615             }
616             ast::PatRange(ref l1, ref l2) => {
617                 ConstantRange(ConstantExpr(&**l1), ConstantExpr(&**l2), debug_loc)
618             }
619             ast::PatVec(ref before, None, ref after) => {
620                 SliceLengthEqual(before.len() + after.len(), debug_loc)
621             }
622             ast::PatVec(ref before, Some(_), ref after) => {
623                 SliceLengthGreaterOrEqual(before.len(), after.len(), debug_loc)
624             }
625             _ => continue
626         };
627
628         if !found.iter().any(|x| x.eq(&opt, tcx)) {
629             found.push(opt);
630         }
631     }
632     found
633 }
634
635 struct ExtractedBlock<'blk, 'tcx: 'blk> {
636     vals: Vec<ValueRef>,
637     bcx: Block<'blk, 'tcx>,
638 }
639
640 fn extract_variant_args<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
641                                     repr: &adt::Repr<'tcx>,
642                                     disr_val: ty::Disr,
643                                     val: ValueRef)
644                                     -> ExtractedBlock<'blk, 'tcx> {
645     let _icx = push_ctxt("match::extract_variant_args");
646     let args = (0..adt::num_args(repr, disr_val)).map(|i| {
647         adt::trans_field_ptr(bcx, repr, val, disr_val, i)
648     }).collect();
649
650     ExtractedBlock { vals: args, bcx: bcx }
651 }
652
653 /// Helper for converting from the ValueRef that we pass around in the match code, which is always
654 /// an lvalue, into a Datum. Eventually we should just pass around a Datum and be done with it.
655 fn match_datum<'tcx>(val: ValueRef, left_ty: Ty<'tcx>) -> Datum<'tcx, Lvalue> {
656     Datum::new(val, left_ty, Lvalue)
657 }
658
659 fn bind_subslice_pat(bcx: Block,
660                      pat_id: ast::NodeId,
661                      val: ValueRef,
662                      offset_left: usize,
663                      offset_right: usize) -> ValueRef {
664     let _icx = push_ctxt("match::bind_subslice_pat");
665     let vec_ty = node_id_type(bcx, pat_id);
666     let vec_ty_contents = match vec_ty.sty {
667         ty::TyBox(ty) => ty,
668         ty::TyRef(_, mt) | ty::TyRawPtr(mt) => mt.ty,
669         _ => vec_ty
670     };
671     let unit_ty = vec_ty_contents.sequence_element_type(bcx.tcx());
672     let vec_datum = match_datum(val, vec_ty);
673     let (base, len) = vec_datum.get_vec_base_and_len(bcx);
674
675     let slice_begin = InBoundsGEP(bcx, base, &[C_uint(bcx.ccx(), offset_left)]);
676     let slice_len_offset = C_uint(bcx.ccx(), offset_left + offset_right);
677     let slice_len = Sub(bcx, len, slice_len_offset, DebugLoc::None);
678     let slice_ty = bcx.tcx().mk_imm_ref(bcx.tcx().mk_region(ty::ReStatic),
679                                          bcx.tcx().mk_slice(unit_ty));
680     let scratch = rvalue_scratch_datum(bcx, slice_ty, "");
681     Store(bcx, slice_begin,
682           GEPi(bcx, scratch.val, &[0, abi::FAT_PTR_ADDR]));
683     Store(bcx, slice_len, GEPi(bcx, scratch.val, &[0, abi::FAT_PTR_EXTRA]));
684     scratch.val
685 }
686
687 fn extract_vec_elems<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
688                                  left_ty: Ty<'tcx>,
689                                  before: usize,
690                                  after: usize,
691                                  val: ValueRef)
692                                  -> ExtractedBlock<'blk, 'tcx> {
693     let _icx = push_ctxt("match::extract_vec_elems");
694     let vec_datum = match_datum(val, left_ty);
695     let (base, len) = vec_datum.get_vec_base_and_len(bcx);
696     let mut elems = vec![];
697     elems.extend((0..before).map(|i| GEPi(bcx, base, &[i])));
698     elems.extend((0..after).rev().map(|i| {
699         InBoundsGEP(bcx, base, &[
700             Sub(bcx, len, C_uint(bcx.ccx(), i + 1), DebugLoc::None)
701         ])
702     }));
703     ExtractedBlock { vals: elems, bcx: bcx }
704 }
705
706 // Macro for deciding whether any of the remaining matches fit a given kind of
707 // pattern.  Note that, because the macro is well-typed, either ALL of the
708 // matches should fit that sort of pattern or NONE (however, some of the
709 // matches may be wildcards like _ or identifiers).
710 macro_rules! any_pat {
711     ($m:expr, $col:expr, $pattern:pat) => (
712         ($m).iter().any(|br| {
713             match br.pats[$col].node {
714                 $pattern => true,
715                 _ => false
716             }
717         })
718     )
719 }
720
721 fn any_uniq_pat(m: &[Match], col: usize) -> bool {
722     any_pat!(m, col, ast::PatBox(_))
723 }
724
725 fn any_region_pat(m: &[Match], col: usize) -> bool {
726     any_pat!(m, col, ast::PatRegion(..))
727 }
728
729 fn any_irrefutable_adt_pat(tcx: &ty::ctxt, m: &[Match], col: usize) -> bool {
730     m.iter().any(|br| {
731         let pat = br.pats[col];
732         match pat.node {
733             ast::PatTup(_) => true,
734             ast::PatStruct(..) => {
735                 match tcx.def_map.borrow().get(&pat.id).map(|d| d.full_def()) {
736                     Some(def::DefVariant(..)) => false,
737                     _ => true,
738                 }
739             }
740             ast::PatEnum(..) | ast::PatIdent(_, _, None) => {
741                 match tcx.def_map.borrow().get(&pat.id).map(|d| d.full_def()) {
742                     Some(def::DefStruct(..)) => true,
743                     _ => false
744                 }
745             }
746             _ => false
747         }
748     })
749 }
750
751 /// What to do when the pattern match fails.
752 enum FailureHandler {
753     Infallible,
754     JumpToBasicBlock(BasicBlockRef),
755     Unreachable
756 }
757
758 impl FailureHandler {
759     fn is_fallible(&self) -> bool {
760         match *self {
761             Infallible => false,
762             _ => true
763         }
764     }
765
766     fn is_infallible(&self) -> bool {
767         !self.is_fallible()
768     }
769
770     fn handle_fail(&self, bcx: Block) {
771         match *self {
772             Infallible =>
773                 panic!("attempted to panic in a non-panicking panic handler!"),
774             JumpToBasicBlock(basic_block) =>
775                 Br(bcx, basic_block, DebugLoc::None),
776             Unreachable =>
777                 build::Unreachable(bcx)
778         }
779     }
780 }
781
782 fn pick_column_to_specialize(def_map: &DefMap, m: &[Match]) -> Option<usize> {
783     fn pat_score(def_map: &DefMap, pat: &ast::Pat) -> usize {
784         match pat.node {
785             ast::PatIdent(_, _, Some(ref inner)) => pat_score(def_map, &**inner),
786             _ if pat_is_refutable(def_map, pat) => 1,
787             _ => 0
788         }
789     }
790
791     let column_score = |m: &[Match], col: usize| -> usize {
792         let total_score = m.iter()
793             .map(|row| row.pats[col])
794             .map(|pat| pat_score(def_map, pat))
795             .sum();
796
797         // Irrefutable columns always go first, they'd only be duplicated in the branches.
798         if total_score == 0 {
799             std::usize::MAX
800         } else {
801             total_score
802         }
803     };
804
805     let column_contains_any_nonwild_patterns = |&col: &usize| -> bool {
806         m.iter().any(|row| match row.pats[col].node {
807             ast::PatWild(_) => false,
808             _ => true
809         })
810     };
811
812     (0..m[0].pats.len())
813         .filter(column_contains_any_nonwild_patterns)
814         .map(|col| (col, column_score(m, col)))
815         .max_by(|&(_, score)| score)
816         .map(|(col, _)| col)
817 }
818
819 // Compiles a comparison between two things.
820 fn compare_values<'blk, 'tcx>(cx: Block<'blk, 'tcx>,
821                               lhs: ValueRef,
822                               rhs: ValueRef,
823                               rhs_t: Ty<'tcx>,
824                               debug_loc: DebugLoc)
825                               -> Result<'blk, 'tcx> {
826     fn compare_str<'blk, 'tcx>(cx: Block<'blk, 'tcx>,
827                                lhs: ValueRef,
828                                rhs: ValueRef,
829                                rhs_t: Ty<'tcx>,
830                                debug_loc: DebugLoc)
831                                -> Result<'blk, 'tcx> {
832         let did = langcall(cx,
833                            None,
834                            &format!("comparison of `{}`", rhs_t),
835                            StrEqFnLangItem);
836         let lhs_data = Load(cx, expr::get_dataptr(cx, lhs));
837         let lhs_len = Load(cx, expr::get_len(cx, lhs));
838         let rhs_data = Load(cx, expr::get_dataptr(cx, rhs));
839         let rhs_len = Load(cx, expr::get_len(cx, rhs));
840         callee::trans_lang_call(cx, did, &[lhs_data, lhs_len, rhs_data, rhs_len], None, debug_loc)
841     }
842
843     let _icx = push_ctxt("compare_values");
844     if rhs_t.is_scalar() {
845         let cmp = compare_scalar_types(cx, lhs, rhs, rhs_t, ast::BiEq, debug_loc);
846         return Result::new(cx, cmp);
847     }
848
849     match rhs_t.sty {
850         ty::TyRef(_, mt) => match mt.ty.sty {
851             ty::TyStr => compare_str(cx, lhs, rhs, rhs_t, debug_loc),
852             ty::TyArray(ty, _) | ty::TySlice(ty) => match ty.sty {
853                 ty::TyUint(ast::TyU8) => {
854                     // NOTE: cast &[u8] and &[u8; N] to &str and abuse the str_eq lang item,
855                     // which calls memcmp().
856                     let pat_len = val_ty(rhs).element_type().array_length();
857                     let ty_str_slice = cx.tcx().mk_static_str();
858
859                     let rhs_str = alloc_ty(cx, ty_str_slice, "rhs_str");
860                     Store(cx, GEPi(cx, rhs, &[0, 0]), expr::get_dataptr(cx, rhs_str));
861                     Store(cx, C_uint(cx.ccx(), pat_len), expr::get_len(cx, rhs_str));
862
863                     let lhs_str;
864                     if val_ty(lhs) == val_ty(rhs) {
865                         // Both the discriminant and the pattern are thin pointers
866                         lhs_str = alloc_ty(cx, ty_str_slice, "lhs_str");
867                         Store(cx, GEPi(cx, lhs, &[0, 0]), expr::get_dataptr(cx, lhs_str));
868                         Store(cx, C_uint(cx.ccx(), pat_len), expr::get_len(cx, lhs_str));
869                     }
870                     else {
871                         // The discriminant is a fat pointer
872                         let llty_str_slice = type_of::type_of(cx.ccx(), ty_str_slice).ptr_to();
873                         lhs_str = PointerCast(cx, lhs, llty_str_slice);
874                     }
875
876                     compare_str(cx, lhs_str, rhs_str, rhs_t, debug_loc)
877                 },
878                 _ => cx.sess().bug("only byte strings supported in compare_values"),
879             },
880             _ => cx.sess().bug("only string and byte strings supported in compare_values"),
881         },
882         _ => cx.sess().bug("only scalars, byte strings, and strings supported in compare_values"),
883     }
884 }
885
886 /// For each binding in `data.bindings_map`, adds an appropriate entry into the `fcx.lllocals` map
887 fn insert_lllocals<'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>,
888                                bindings_map: &BindingsMap<'tcx>,
889                                cs: Option<cleanup::ScopeId>)
890                                -> Block<'blk, 'tcx> {
891     for (&ident, &binding_info) in bindings_map {
892         let llval = match binding_info.trmode {
893             // By value mut binding for a copy type: load from the ptr
894             // into the matched value and copy to our alloca
895             TrByCopy(llbinding) => {
896                 let llval = Load(bcx, binding_info.llmatch);
897                 let datum = Datum::new(llval, binding_info.ty, Lvalue);
898                 call_lifetime_start(bcx, llbinding);
899                 bcx = datum.store_to(bcx, llbinding);
900                 if let Some(cs) = cs {
901                     bcx.fcx.schedule_lifetime_end(cs, llbinding);
902                 }
903
904                 llbinding
905             },
906
907             // By value move bindings: load from the ptr into the matched value
908             TrByMove => Load(bcx, binding_info.llmatch),
909
910             // By ref binding: use the ptr into the matched value
911             TrByRef => binding_info.llmatch
912         };
913
914         let datum = Datum::new(llval, binding_info.ty, Lvalue);
915         if let Some(cs) = cs {
916             bcx.fcx.schedule_lifetime_end(cs, binding_info.llmatch);
917             bcx.fcx.schedule_drop_and_fill_mem(cs, llval, binding_info.ty);
918         }
919
920         debug!("binding {} to {}", binding_info.id, bcx.val_to_string(llval));
921         bcx.fcx.lllocals.borrow_mut().insert(binding_info.id, datum);
922         debuginfo::create_match_binding_metadata(bcx, ident.name, binding_info);
923     }
924     bcx
925 }
926
927 fn compile_guard<'a, 'p, 'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
928                                      guard_expr: &ast::Expr,
929                                      data: &ArmData<'p, 'blk, 'tcx>,
930                                      m: &[Match<'a, 'p, 'blk, 'tcx>],
931                                      vals: &[ValueRef],
932                                      chk: &FailureHandler,
933                                      has_genuine_default: bool)
934                                      -> Block<'blk, 'tcx> {
935     debug!("compile_guard(bcx={}, guard_expr={:?}, m={:?}, vals=[{}])",
936            bcx.to_str(),
937            guard_expr,
938            m,
939            vals.iter().map(|v| bcx.val_to_string(*v)).collect::<Vec<_>>().join(", "));
940     let _indenter = indenter();
941
942     let mut bcx = insert_lllocals(bcx, &data.bindings_map, None);
943
944     let val = unpack_datum!(bcx, expr::trans(bcx, guard_expr));
945     let val = val.to_llbool(bcx);
946
947     for (_, &binding_info) in &data.bindings_map {
948         if let TrByCopy(llbinding) = binding_info.trmode {
949             call_lifetime_end(bcx, llbinding);
950         }
951     }
952
953     for (_, &binding_info) in &data.bindings_map {
954         bcx.fcx.lllocals.borrow_mut().remove(&binding_info.id);
955     }
956
957     with_cond(bcx, Not(bcx, val, guard_expr.debug_loc()), |bcx| {
958         for (_, &binding_info) in &data.bindings_map {
959             call_lifetime_end(bcx, binding_info.llmatch);
960         }
961         match chk {
962             // If the default arm is the only one left, move on to the next
963             // condition explicitly rather than (possibly) falling back to
964             // the default arm.
965             &JumpToBasicBlock(_) if m.len() == 1 && has_genuine_default => {
966                 chk.handle_fail(bcx);
967             }
968             _ => {
969                 compile_submatch(bcx, m, vals, chk, has_genuine_default);
970             }
971         };
972         bcx
973     })
974 }
975
976 fn compile_submatch<'a, 'p, 'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
977                                         m: &[Match<'a, 'p, 'blk, 'tcx>],
978                                         vals: &[ValueRef],
979                                         chk: &FailureHandler,
980                                         has_genuine_default: bool) {
981     debug!("compile_submatch(bcx={}, m={:?}, vals=[{}])",
982            bcx.to_str(),
983            m,
984            vals.iter().map(|v| bcx.val_to_string(*v)).collect::<Vec<_>>().join(", "));
985     let _indenter = indenter();
986     let _icx = push_ctxt("match::compile_submatch");
987     let mut bcx = bcx;
988     if m.is_empty() {
989         if chk.is_fallible() {
990             chk.handle_fail(bcx);
991         }
992         return;
993     }
994
995     let tcx = bcx.tcx();
996     let def_map = &tcx.def_map;
997     match pick_column_to_specialize(def_map, m) {
998         Some(col) => {
999             let val = vals[col];
1000             if has_nested_bindings(m, col) {
1001                 let expanded = expand_nested_bindings(bcx, m, col, val);
1002                 compile_submatch_continue(bcx,
1003                                           &expanded[..],
1004                                           vals,
1005                                           chk,
1006                                           col,
1007                                           val,
1008                                           has_genuine_default)
1009             } else {
1010                 compile_submatch_continue(bcx, m, vals, chk, col, val, has_genuine_default)
1011             }
1012         }
1013         None => {
1014             let data = &m[0].data;
1015             for &(ref ident, ref value_ptr) in &m[0].bound_ptrs {
1016                 let binfo = *data.bindings_map.get(ident).unwrap();
1017                 call_lifetime_start(bcx, binfo.llmatch);
1018                 if binfo.trmode == TrByRef && type_is_fat_ptr(bcx.tcx(), binfo.ty) {
1019                     expr::copy_fat_ptr(bcx, *value_ptr, binfo.llmatch);
1020                 }
1021                 else {
1022                     Store(bcx, *value_ptr, binfo.llmatch);
1023                 }
1024             }
1025             match data.arm.guard {
1026                 Some(ref guard_expr) => {
1027                     bcx = compile_guard(bcx,
1028                                         &**guard_expr,
1029                                         m[0].data,
1030                                         &m[1..m.len()],
1031                                         vals,
1032                                         chk,
1033                                         has_genuine_default);
1034                 }
1035                 _ => ()
1036             }
1037             Br(bcx, data.bodycx.llbb, DebugLoc::None);
1038         }
1039     }
1040 }
1041
1042 fn compile_submatch_continue<'a, 'p, 'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>,
1043                                                  m: &[Match<'a, 'p, 'blk, 'tcx>],
1044                                                  vals: &[ValueRef],
1045                                                  chk: &FailureHandler,
1046                                                  col: usize,
1047                                                  val: ValueRef,
1048                                                  has_genuine_default: bool) {
1049     let fcx = bcx.fcx;
1050     let tcx = bcx.tcx();
1051     let dm = &tcx.def_map;
1052
1053     let mut vals_left = vals[0..col].to_vec();
1054     vals_left.push_all(&vals[col + 1..]);
1055     let ccx = bcx.fcx.ccx;
1056
1057     // Find a real id (we're adding placeholder wildcard patterns, but
1058     // each column is guaranteed to have at least one real pattern)
1059     let pat_id = m.iter().map(|br| br.pats[col].id)
1060                          .find(|&id| id != DUMMY_NODE_ID)
1061                          .unwrap_or(DUMMY_NODE_ID);
1062
1063     let left_ty = if pat_id == DUMMY_NODE_ID {
1064         tcx.mk_nil()
1065     } else {
1066         node_id_type(bcx, pat_id)
1067     };
1068
1069     let mcx = check_match::MatchCheckCtxt {
1070         tcx: bcx.tcx(),
1071         param_env: bcx.tcx().empty_parameter_environment(),
1072     };
1073     let adt_vals = if any_irrefutable_adt_pat(bcx.tcx(), m, col) {
1074         let repr = adt::represent_type(bcx.ccx(), left_ty);
1075         let arg_count = adt::num_args(&*repr, 0);
1076         let (arg_count, struct_val) = if type_is_sized(bcx.tcx(), left_ty) {
1077             (arg_count, val)
1078         } else {
1079             // For an unsized ADT (i.e. DST struct), we need to treat
1080             // the last field specially: instead of simply passing a
1081             // ValueRef pointing to that field, as with all the others,
1082             // we skip it and instead construct a 'fat ptr' below.
1083             (arg_count - 1, Load(bcx, expr::get_dataptr(bcx, val)))
1084         };
1085         let mut field_vals: Vec<ValueRef> = (0..arg_count).map(|ix|
1086             adt::trans_field_ptr(bcx, &*repr, struct_val, 0, ix)
1087         ).collect();
1088
1089         match left_ty.sty {
1090             ty::TyStruct(def_id, substs) if !type_is_sized(bcx.tcx(), left_ty) => {
1091                 // The last field is technically unsized but
1092                 // since we can only ever match that field behind
1093                 // a reference we construct a fat ptr here.
1094                 let fields = bcx.tcx().lookup_struct_fields(def_id);
1095                 let unsized_ty = fields.iter().last().map(|field| {
1096                     let fty = bcx.tcx().lookup_field_type(def_id, field.id, substs);
1097                     monomorphize::normalize_associated_type(bcx.tcx(), &fty)
1098                 }).unwrap();
1099                 let llty = type_of::type_of(bcx.ccx(), unsized_ty);
1100                 let scratch = alloca_no_lifetime(bcx, llty, "__struct_field_fat_ptr");
1101                 let data = adt::trans_field_ptr(bcx, &*repr, struct_val, 0, arg_count);
1102                 let len = Load(bcx, expr::get_len(bcx, val));
1103                 Store(bcx, data, expr::get_dataptr(bcx, scratch));
1104                 Store(bcx, len, expr::get_len(bcx, scratch));
1105                 field_vals.push(scratch);
1106             }
1107             _ => {}
1108         }
1109         Some(field_vals)
1110     } else if any_uniq_pat(m, col) || any_region_pat(m, col) {
1111         Some(vec!(Load(bcx, val)))
1112     } else {
1113         match left_ty.sty {
1114             ty::TyArray(_, n) => {
1115                 let args = extract_vec_elems(bcx, left_ty, n, 0, val);
1116                 Some(args.vals)
1117             }
1118             _ => None
1119         }
1120     };
1121     match adt_vals {
1122         Some(field_vals) => {
1123             let pats = enter_match(bcx, dm, m, col, val, |pats|
1124                 check_match::specialize(&mcx, pats,
1125                                         &check_match::Single, col,
1126                                         field_vals.len())
1127             );
1128             let mut vals = field_vals;
1129             vals.push_all(&vals_left);
1130             compile_submatch(bcx, &pats, &vals, chk, has_genuine_default);
1131             return;
1132         }
1133         _ => ()
1134     }
1135
1136     // Decide what kind of branch we need
1137     let opts = get_branches(bcx, m, col);
1138     debug!("options={:?}", opts);
1139     let mut kind = NoBranch;
1140     let mut test_val = val;
1141     debug!("test_val={}", bcx.val_to_string(test_val));
1142     if !opts.is_empty() {
1143         match opts[0] {
1144             ConstantValue(..) | ConstantRange(..) => {
1145                 test_val = load_if_immediate(bcx, val, left_ty);
1146                 kind = if left_ty.is_integral() {
1147                     Switch
1148                 } else {
1149                     Compare
1150                 };
1151             }
1152             Variant(_, ref repr, _, _) => {
1153                 let (the_kind, val_opt) = adt::trans_switch(bcx, &**repr, val);
1154                 kind = the_kind;
1155                 if let Some(tval) = val_opt { test_val = tval; }
1156             }
1157             SliceLengthEqual(..) | SliceLengthGreaterOrEqual(..) => {
1158                 let (_, len) = tvec::get_base_and_len(bcx, val, left_ty);
1159                 test_val = len;
1160                 kind = Switch;
1161             }
1162         }
1163     }
1164     for o in &opts {
1165         match *o {
1166             ConstantRange(..) => { kind = Compare; break },
1167             SliceLengthGreaterOrEqual(..) => { kind = CompareSliceLength; break },
1168             _ => ()
1169         }
1170     }
1171     let else_cx = match kind {
1172         NoBranch | Single => bcx,
1173         _ => bcx.fcx.new_temp_block("match_else")
1174     };
1175     let sw = if kind == Switch {
1176         build::Switch(bcx, test_val, else_cx.llbb, opts.len())
1177     } else {
1178         C_int(ccx, 0) // Placeholder for when not using a switch
1179     };
1180
1181     let defaults = enter_default(else_cx, dm, m, col, val);
1182     let exhaustive = chk.is_infallible() && defaults.is_empty();
1183     let len = opts.len();
1184
1185     // Compile subtrees for each option
1186     for (i, opt) in opts.iter().enumerate() {
1187         // In some cases of range and vector pattern matching, we need to
1188         // override the failure case so that instead of failing, it proceeds
1189         // to try more matching. branch_chk, then, is the proper failure case
1190         // for the current conditional branch.
1191         let mut branch_chk = None;
1192         let mut opt_cx = else_cx;
1193         let debug_loc = opt.debug_loc();
1194
1195         if !exhaustive || i + 1 < len {
1196             opt_cx = bcx.fcx.new_temp_block("match_case");
1197             match kind {
1198                 Single => Br(bcx, opt_cx.llbb, debug_loc),
1199                 Switch => {
1200                     match opt.trans(bcx) {
1201                         SingleResult(r) => {
1202                             AddCase(sw, r.val, opt_cx.llbb);
1203                             bcx = r.bcx;
1204                         }
1205                         _ => {
1206                             bcx.sess().bug(
1207                                 "in compile_submatch, expected \
1208                                  opt.trans() to return a SingleResult")
1209                         }
1210                     }
1211                 }
1212                 Compare | CompareSliceLength => {
1213                     let t = if kind == Compare {
1214                         left_ty
1215                     } else {
1216                         tcx.types.usize // vector length
1217                     };
1218                     let Result { bcx: after_cx, val: matches } = {
1219                         match opt.trans(bcx) {
1220                             SingleResult(Result { bcx, val }) => {
1221                                 compare_values(bcx, test_val, val, t, debug_loc)
1222                             }
1223                             RangeResult(Result { val: vbegin, .. },
1224                                         Result { bcx, val: vend }) => {
1225                                 let llge = compare_scalar_types(bcx, test_val, vbegin,
1226                                                                 t, ast::BiGe, debug_loc);
1227                                 let llle = compare_scalar_types(bcx, test_val, vend,
1228                                                                 t, ast::BiLe, debug_loc);
1229                                 Result::new(bcx, And(bcx, llge, llle, DebugLoc::None))
1230                             }
1231                             LowerBound(Result { bcx, val }) => {
1232                                 Result::new(bcx, compare_scalar_types(bcx, test_val,
1233                                                                       val, t, ast::BiGe,
1234                                                                       debug_loc))
1235                             }
1236                         }
1237                     };
1238                     bcx = fcx.new_temp_block("compare_next");
1239
1240                     // If none of the sub-cases match, and the current condition
1241                     // is guarded or has multiple patterns, move on to the next
1242                     // condition, if there is any, rather than falling back to
1243                     // the default.
1244                     let guarded = m[i].data.arm.guard.is_some();
1245                     let multi_pats = m[i].pats.len() > 1;
1246                     if i + 1 < len && (guarded || multi_pats || kind == CompareSliceLength) {
1247                         branch_chk = Some(JumpToBasicBlock(bcx.llbb));
1248                     }
1249                     CondBr(after_cx, matches, opt_cx.llbb, bcx.llbb, debug_loc);
1250                 }
1251                 _ => ()
1252             }
1253         } else if kind == Compare || kind == CompareSliceLength {
1254             Br(bcx, else_cx.llbb, debug_loc);
1255         }
1256
1257         let mut size = 0;
1258         let mut unpacked = Vec::new();
1259         match *opt {
1260             Variant(disr_val, ref repr, _, _) => {
1261                 let ExtractedBlock {vals: argvals, bcx: new_bcx} =
1262                     extract_variant_args(opt_cx, &**repr, disr_val, val);
1263                 size = argvals.len();
1264                 unpacked = argvals;
1265                 opt_cx = new_bcx;
1266             }
1267             SliceLengthEqual(len, _) => {
1268                 let args = extract_vec_elems(opt_cx, left_ty, len, 0, val);
1269                 size = args.vals.len();
1270                 unpacked = args.vals.clone();
1271                 opt_cx = args.bcx;
1272             }
1273             SliceLengthGreaterOrEqual(before, after, _) => {
1274                 let args = extract_vec_elems(opt_cx, left_ty, before, after, val);
1275                 size = args.vals.len();
1276                 unpacked = args.vals.clone();
1277                 opt_cx = args.bcx;
1278             }
1279             ConstantValue(..) | ConstantRange(..) => ()
1280         }
1281         let opt_ms = enter_opt(opt_cx, pat_id, dm, m, opt, col, size, val);
1282         let mut opt_vals = unpacked;
1283         opt_vals.push_all(&vals_left[..]);
1284         compile_submatch(opt_cx,
1285                          &opt_ms[..],
1286                          &opt_vals[..],
1287                          branch_chk.as_ref().unwrap_or(chk),
1288                          has_genuine_default);
1289     }
1290
1291     // Compile the fall-through case, if any
1292     if !exhaustive && kind != Single {
1293         if kind == Compare || kind == CompareSliceLength {
1294             Br(bcx, else_cx.llbb, DebugLoc::None);
1295         }
1296         match chk {
1297             // If there is only one default arm left, move on to the next
1298             // condition explicitly rather than (eventually) falling back to
1299             // the last default arm.
1300             &JumpToBasicBlock(_) if defaults.len() == 1 && has_genuine_default => {
1301                 chk.handle_fail(else_cx);
1302             }
1303             _ => {
1304                 compile_submatch(else_cx,
1305                                  &defaults[..],
1306                                  &vals_left[..],
1307                                  chk,
1308                                  has_genuine_default);
1309             }
1310         }
1311     }
1312 }
1313
1314 pub fn trans_match<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1315                                match_expr: &ast::Expr,
1316                                discr_expr: &ast::Expr,
1317                                arms: &[ast::Arm],
1318                                dest: Dest)
1319                                -> Block<'blk, 'tcx> {
1320     let _icx = push_ctxt("match::trans_match");
1321     trans_match_inner(bcx, match_expr.id, discr_expr, arms, dest)
1322 }
1323
1324 /// Checks whether the binding in `discr` is assigned to anywhere in the expression `body`
1325 fn is_discr_reassigned(bcx: Block, discr: &ast::Expr, body: &ast::Expr) -> bool {
1326     let (vid, field) = match discr.node {
1327         ast::ExprPath(..) => match bcx.def(discr.id) {
1328             def::DefLocal(vid) | def::DefUpvar(vid, _) => (vid, None),
1329             _ => return false
1330         },
1331         ast::ExprField(ref base, field) => {
1332             let vid = match bcx.tcx().def_map.borrow().get(&base.id).map(|d| d.full_def()) {
1333                 Some(def::DefLocal(vid)) | Some(def::DefUpvar(vid, _)) => vid,
1334                 _ => return false
1335             };
1336             (vid, Some(mc::NamedField(field.node.name)))
1337         },
1338         ast::ExprTupField(ref base, field) => {
1339             let vid = match bcx.tcx().def_map.borrow().get(&base.id).map(|d| d.full_def()) {
1340                 Some(def::DefLocal(vid)) | Some(def::DefUpvar(vid, _)) => vid,
1341                 _ => return false
1342             };
1343             (vid, Some(mc::PositionalField(field.node)))
1344         },
1345         _ => return false
1346     };
1347
1348     let mut rc = ReassignmentChecker {
1349         node: vid,
1350         field: field,
1351         reassigned: false
1352     };
1353     {
1354         let infcx = infer::normalizing_infer_ctxt(bcx.tcx(), &bcx.tcx().tables);
1355         let mut visitor = euv::ExprUseVisitor::new(&mut rc, &infcx);
1356         visitor.walk_expr(body);
1357     }
1358     rc.reassigned
1359 }
1360
1361 struct ReassignmentChecker {
1362     node: ast::NodeId,
1363     field: Option<mc::FieldName>,
1364     reassigned: bool
1365 }
1366
1367 // Determine if the expression we're matching on is reassigned to within
1368 // the body of the match's arm.
1369 // We only care for the `mutate` callback since this check only matters
1370 // for cases where the matched value is moved.
1371 impl<'tcx> euv::Delegate<'tcx> for ReassignmentChecker {
1372     fn consume(&mut self, _: ast::NodeId, _: Span, _: mc::cmt, _: euv::ConsumeMode) {}
1373     fn matched_pat(&mut self, _: &ast::Pat, _: mc::cmt, _: euv::MatchMode) {}
1374     fn consume_pat(&mut self, _: &ast::Pat, _: mc::cmt, _: euv::ConsumeMode) {}
1375     fn borrow(&mut self, _: ast::NodeId, _: Span, _: mc::cmt, _: ty::Region,
1376               _: ty::BorrowKind, _: euv::LoanCause) {}
1377     fn decl_without_init(&mut self, _: ast::NodeId, _: Span) {}
1378
1379     fn mutate(&mut self, _: ast::NodeId, _: Span, cmt: mc::cmt, _: euv::MutateMode) {
1380         match cmt.cat {
1381             mc::cat_upvar(mc::Upvar { id: ty::UpvarId { var_id: vid, .. }, .. }) |
1382             mc::cat_local(vid) => self.reassigned |= self.node == vid,
1383             mc::cat_interior(ref base_cmt, mc::InteriorField(field)) => {
1384                 match base_cmt.cat {
1385                     mc::cat_upvar(mc::Upvar { id: ty::UpvarId { var_id: vid, .. }, .. }) |
1386                     mc::cat_local(vid) => {
1387                         self.reassigned |= self.node == vid && Some(field) == self.field
1388                     },
1389                     _ => {}
1390                 }
1391             },
1392             _ => {}
1393         }
1394     }
1395 }
1396
1397 fn create_bindings_map<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, pat: &ast::Pat,
1398                                    discr: &ast::Expr, body: &ast::Expr)
1399                                    -> BindingsMap<'tcx> {
1400     // Create the bindings map, which is a mapping from each binding name
1401     // to an alloca() that will be the value for that local variable.
1402     // Note that we use the names because each binding will have many ids
1403     // from the various alternatives.
1404     let ccx = bcx.ccx();
1405     let tcx = bcx.tcx();
1406     let reassigned = is_discr_reassigned(bcx, discr, body);
1407     let mut bindings_map = FnvHashMap();
1408     pat_bindings(&tcx.def_map, &*pat, |bm, p_id, span, path1| {
1409         let ident = path1.node;
1410         let name = ident.name;
1411         let variable_ty = node_id_type(bcx, p_id);
1412         let llvariable_ty = type_of::type_of(ccx, variable_ty);
1413         let tcx = bcx.tcx();
1414         let param_env = tcx.empty_parameter_environment();
1415
1416         let llmatch;
1417         let trmode;
1418         match bm {
1419             ast::BindByValue(_)
1420                 if !variable_ty.moves_by_default(&param_env, span) || reassigned =>
1421             {
1422                 llmatch = alloca_no_lifetime(bcx,
1423                                  llvariable_ty.ptr_to(),
1424                                  "__llmatch");
1425                 trmode = TrByCopy(alloca_no_lifetime(bcx,
1426                                          llvariable_ty,
1427                                          &bcx.name(name)));
1428             }
1429             ast::BindByValue(_) => {
1430                 // in this case, the final type of the variable will be T,
1431                 // but during matching we need to store a *T as explained
1432                 // above
1433                 llmatch = alloca_no_lifetime(bcx,
1434                                  llvariable_ty.ptr_to(),
1435                                  &bcx.name(name));
1436                 trmode = TrByMove;
1437             }
1438             ast::BindByRef(_) => {
1439                 llmatch = alloca_no_lifetime(bcx,
1440                                  llvariable_ty,
1441                                  &bcx.name(name));
1442                 trmode = TrByRef;
1443             }
1444         };
1445         bindings_map.insert(ident, BindingInfo {
1446             llmatch: llmatch,
1447             trmode: trmode,
1448             id: p_id,
1449             span: span,
1450             ty: variable_ty
1451         });
1452     });
1453     return bindings_map;
1454 }
1455
1456 fn trans_match_inner<'blk, 'tcx>(scope_cx: Block<'blk, 'tcx>,
1457                                  match_id: ast::NodeId,
1458                                  discr_expr: &ast::Expr,
1459                                  arms: &[ast::Arm],
1460                                  dest: Dest) -> Block<'blk, 'tcx> {
1461     let _icx = push_ctxt("match::trans_match_inner");
1462     let fcx = scope_cx.fcx;
1463     let mut bcx = scope_cx;
1464     let tcx = bcx.tcx();
1465
1466     let discr_datum = unpack_datum!(bcx, expr::trans_to_lvalue(bcx, discr_expr,
1467                                                                "match"));
1468     if bcx.unreachable.get() {
1469         return bcx;
1470     }
1471
1472     let t = node_id_type(bcx, discr_expr.id);
1473     let chk = if t.is_empty(tcx) {
1474         Unreachable
1475     } else {
1476         Infallible
1477     };
1478
1479     let arm_datas: Vec<ArmData> = arms.iter().map(|arm| ArmData {
1480         bodycx: fcx.new_id_block("case_body", arm.body.id),
1481         arm: arm,
1482         bindings_map: create_bindings_map(bcx, &*arm.pats[0], discr_expr, &*arm.body)
1483     }).collect();
1484
1485     let mut pat_renaming_map = if scope_cx.sess().opts.debuginfo != NoDebugInfo {
1486         Some(FnvHashMap())
1487     } else {
1488         None
1489     };
1490
1491     let arm_pats: Vec<Vec<P<ast::Pat>>> = {
1492         let mut static_inliner = StaticInliner::new(scope_cx.tcx(),
1493                                                     pat_renaming_map.as_mut());
1494         arm_datas.iter().map(|arm_data| {
1495             arm_data.arm.pats.iter().map(|p| static_inliner.fold_pat((*p).clone())).collect()
1496         }).collect()
1497     };
1498
1499     let mut matches = Vec::new();
1500     for (arm_data, pats) in arm_datas.iter().zip(&arm_pats) {
1501         matches.extend(pats.iter().map(|p| Match {
1502             pats: vec![&**p],
1503             data: arm_data,
1504             bound_ptrs: Vec::new(),
1505             pat_renaming_map: pat_renaming_map.as_ref()
1506         }));
1507     }
1508
1509     // `compile_submatch` works one column of arm patterns a time and
1510     // then peels that column off. So as we progress, it may become
1511     // impossible to tell whether we have a genuine default arm, i.e.
1512     // `_ => foo` or not. Sometimes it is important to know that in order
1513     // to decide whether moving on to the next condition or falling back
1514     // to the default arm.
1515     let has_default = arms.last().map_or(false, |arm| {
1516         arm.pats.len() == 1
1517         && arm.pats.last().unwrap().node == ast::PatWild(ast::PatWildSingle)
1518     });
1519
1520     compile_submatch(bcx, &matches[..], &[discr_datum.val], &chk, has_default);
1521
1522     let mut arm_cxs = Vec::new();
1523     for arm_data in &arm_datas {
1524         let mut bcx = arm_data.bodycx;
1525
1526         // insert bindings into the lllocals map and add cleanups
1527         let cs = fcx.push_custom_cleanup_scope();
1528         bcx = insert_lllocals(bcx, &arm_data.bindings_map, Some(cleanup::CustomScope(cs)));
1529         bcx = expr::trans_into(bcx, &*arm_data.arm.body, dest);
1530         bcx = fcx.pop_and_trans_custom_cleanup_scope(bcx, cs);
1531         arm_cxs.push(bcx);
1532     }
1533
1534     bcx = scope_cx.fcx.join_blocks(match_id, &arm_cxs[..]);
1535     return bcx;
1536 }
1537
1538 /// Generates code for a local variable declaration like `let <pat>;` or `let <pat> =
1539 /// <opt_init_expr>`.
1540 pub fn store_local<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1541                                local: &ast::Local)
1542                                -> Block<'blk, 'tcx> {
1543     let _icx = push_ctxt("match::store_local");
1544     let mut bcx = bcx;
1545     let tcx = bcx.tcx();
1546     let pat = &*local.pat;
1547
1548     fn create_dummy_locals<'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>,
1549                                        pat: &ast::Pat)
1550                                        -> Block<'blk, 'tcx> {
1551         let _icx = push_ctxt("create_dummy_locals");
1552         // create dummy memory for the variables if we have no
1553         // value to store into them immediately
1554         let tcx = bcx.tcx();
1555         pat_bindings(&tcx.def_map, pat, |_, p_id, _, path1| {
1556             let scope = cleanup::var_scope(tcx, p_id);
1557             bcx = mk_binding_alloca(
1558                 bcx, p_id, path1.node.name, scope, (),
1559                 |(), bcx, llval, ty| { drop_done_fill_mem(bcx, llval, ty); bcx });
1560         });
1561         bcx
1562     }
1563
1564     match local.init {
1565         Some(ref init_expr) => {
1566             // Optimize the "let x = expr" case. This just writes
1567             // the result of evaluating `expr` directly into the alloca
1568             // for `x`. Often the general path results in similar or the
1569             // same code post-optimization, but not always. In particular,
1570             // in unsafe code, you can have expressions like
1571             //
1572             //    let x = intrinsics::uninit();
1573             //
1574             // In such cases, the more general path is unsafe, because
1575             // it assumes it is matching against a valid value.
1576             match simple_identifier(&*pat) {
1577                 Some(ident) => {
1578                     let var_scope = cleanup::var_scope(tcx, local.id);
1579                     return mk_binding_alloca(
1580                         bcx, pat.id, ident.name, var_scope, (),
1581                         |(), bcx, v, _| expr::trans_into(bcx, &**init_expr,
1582                                                          expr::SaveIn(v)));
1583                 }
1584
1585                 None => {}
1586             }
1587
1588             // General path.
1589             let init_datum =
1590                 unpack_datum!(bcx, expr::trans_to_lvalue(bcx, &**init_expr, "let"));
1591             if bcx.sess().asm_comments() {
1592                 add_comment(bcx, "creating zeroable ref llval");
1593             }
1594             let var_scope = cleanup::var_scope(tcx, local.id);
1595             bind_irrefutable_pat(bcx, pat, init_datum.val, var_scope)
1596         }
1597         None => {
1598             create_dummy_locals(bcx, pat)
1599         }
1600     }
1601 }
1602
1603 fn mk_binding_alloca<'blk, 'tcx, A, F>(bcx: Block<'blk, 'tcx>,
1604                                        p_id: ast::NodeId,
1605                                        name: ast::Name,
1606                                        cleanup_scope: cleanup::ScopeId,
1607                                        arg: A,
1608                                        populate: F)
1609                                        -> Block<'blk, 'tcx> where
1610     F: FnOnce(A, Block<'blk, 'tcx>, ValueRef, Ty<'tcx>) -> Block<'blk, 'tcx>,
1611 {
1612     let var_ty = node_id_type(bcx, p_id);
1613
1614     // Allocate memory on stack for the binding.
1615     let llval = alloc_ty(bcx, var_ty, &bcx.name(name));
1616
1617     // Subtle: be sure that we *populate* the memory *before*
1618     // we schedule the cleanup.
1619     let bcx = populate(arg, bcx, llval, var_ty);
1620     bcx.fcx.schedule_lifetime_end(cleanup_scope, llval);
1621     bcx.fcx.schedule_drop_mem(cleanup_scope, llval, var_ty);
1622
1623     // Now that memory is initialized and has cleanup scheduled,
1624     // create the datum and insert into the local variable map.
1625     let datum = Datum::new(llval, var_ty, Lvalue);
1626     bcx.fcx.lllocals.borrow_mut().insert(p_id, datum);
1627     bcx
1628 }
1629
1630 /// A simple version of the pattern matching code that only handles
1631 /// irrefutable patterns. This is used in let/argument patterns,
1632 /// not in match statements. Unifying this code with the code above
1633 /// sounds nice, but in practice it produces very inefficient code,
1634 /// since the match code is so much more general. In most cases,
1635 /// LLVM is able to optimize the code, but it causes longer compile
1636 /// times and makes the generated code nigh impossible to read.
1637 ///
1638 /// # Arguments
1639 /// - bcx: starting basic block context
1640 /// - pat: the irrefutable pattern being matched.
1641 /// - val: the value being matched -- must be an lvalue (by ref, with cleanup)
1642 pub fn bind_irrefutable_pat<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1643                                     pat: &ast::Pat,
1644                                     val: ValueRef,
1645                                     cleanup_scope: cleanup::ScopeId)
1646                                     -> Block<'blk, 'tcx> {
1647     debug!("bind_irrefutable_pat(bcx={}, pat={:?})",
1648            bcx.to_str(),
1649            pat);
1650
1651     if bcx.sess().asm_comments() {
1652         add_comment(bcx, &format!("bind_irrefutable_pat(pat={:?})",
1653                                  pat));
1654     }
1655
1656     let _indenter = indenter();
1657
1658     let _icx = push_ctxt("match::bind_irrefutable_pat");
1659     let mut bcx = bcx;
1660     let tcx = bcx.tcx();
1661     let ccx = bcx.ccx();
1662     match pat.node {
1663         ast::PatIdent(pat_binding_mode, ref path1, ref inner) => {
1664             if pat_is_binding(&tcx.def_map, &*pat) {
1665                 // Allocate the stack slot where the value of this
1666                 // binding will live and place it into the appropriate
1667                 // map.
1668                 bcx = mk_binding_alloca(
1669                     bcx, pat.id, path1.node.name, cleanup_scope, (),
1670                     |(), bcx, llval, ty| {
1671                         match pat_binding_mode {
1672                             ast::BindByValue(_) => {
1673                                 // By value binding: move the value that `val`
1674                                 // points at into the binding's stack slot.
1675                                 let d = Datum::new(val, ty, Lvalue);
1676                                 d.store_to(bcx, llval)
1677                             }
1678
1679                             ast::BindByRef(_) => {
1680                                 // By ref binding: the value of the variable
1681                                 // is the pointer `val` itself or fat pointer referenced by `val`
1682                                 if type_is_fat_ptr(bcx.tcx(), ty) {
1683                                     expr::copy_fat_ptr(bcx, val, llval);
1684                                 }
1685                                 else {
1686                                     Store(bcx, val, llval);
1687                                 }
1688
1689                                 bcx
1690                             }
1691                         }
1692                     });
1693             }
1694
1695             if let Some(ref inner_pat) = *inner {
1696                 bcx = bind_irrefutable_pat(bcx, &**inner_pat, val, cleanup_scope);
1697             }
1698         }
1699         ast::PatEnum(_, ref sub_pats) => {
1700             let opt_def = bcx.tcx().def_map.borrow().get(&pat.id).map(|d| d.full_def());
1701             match opt_def {
1702                 Some(def::DefVariant(enum_id, var_id, _)) => {
1703                     let repr = adt::represent_node(bcx, pat.id);
1704                     let vinfo = ccx.tcx().enum_variant_with_id(enum_id, var_id);
1705                     let args = extract_variant_args(bcx,
1706                                                     &*repr,
1707                                                     vinfo.disr_val,
1708                                                     val);
1709                     if let Some(ref sub_pat) = *sub_pats {
1710                         for (i, &argval) in args.vals.iter().enumerate() {
1711                             bcx = bind_irrefutable_pat(bcx, &*sub_pat[i],
1712                                                        argval, cleanup_scope);
1713                         }
1714                     }
1715                 }
1716                 Some(def::DefStruct(..)) => {
1717                     match *sub_pats {
1718                         None => {
1719                             // This is a unit-like struct. Nothing to do here.
1720                         }
1721                         Some(ref elems) => {
1722                             // This is the tuple struct case.
1723                             let repr = adt::represent_node(bcx, pat.id);
1724                             for (i, elem) in elems.iter().enumerate() {
1725                                 let fldptr = adt::trans_field_ptr(bcx, &*repr,
1726                                                                   val, 0, i);
1727                                 bcx = bind_irrefutable_pat(bcx, &**elem,
1728                                                            fldptr, cleanup_scope);
1729                             }
1730                         }
1731                     }
1732                 }
1733                 _ => {
1734                     // Nothing to do here.
1735                 }
1736             }
1737         }
1738         ast::PatStruct(_, ref fields, _) => {
1739             let tcx = bcx.tcx();
1740             let pat_ty = node_id_type(bcx, pat.id);
1741             let pat_repr = adt::represent_type(bcx.ccx(), pat_ty);
1742             expr::with_field_tys(tcx, pat_ty, Some(pat.id), |discr, field_tys| {
1743                 for f in fields {
1744                     let ix = tcx.field_idx_strict(f.node.ident.name, field_tys);
1745                     let fldptr = adt::trans_field_ptr(bcx, &*pat_repr, val,
1746                                                       discr, ix);
1747                     bcx = bind_irrefutable_pat(bcx, &*f.node.pat, fldptr, cleanup_scope);
1748                 }
1749             })
1750         }
1751         ast::PatTup(ref elems) => {
1752             let repr = adt::represent_node(bcx, pat.id);
1753             for (i, elem) in elems.iter().enumerate() {
1754                 let fldptr = adt::trans_field_ptr(bcx, &*repr, val, 0, i);
1755                 bcx = bind_irrefutable_pat(bcx, &**elem, fldptr, cleanup_scope);
1756             }
1757         }
1758         ast::PatBox(ref inner) => {
1759             let llbox = Load(bcx, val);
1760             bcx = bind_irrefutable_pat(bcx, &**inner, llbox, cleanup_scope);
1761         }
1762         ast::PatRegion(ref inner, _) => {
1763             let loaded_val = Load(bcx, val);
1764             bcx = bind_irrefutable_pat(bcx, &**inner, loaded_val, cleanup_scope);
1765         }
1766         ast::PatVec(ref before, ref slice, ref after) => {
1767             let pat_ty = node_id_type(bcx, pat.id);
1768             let mut extracted = extract_vec_elems(bcx, pat_ty, before.len(), after.len(), val);
1769             match slice {
1770                 &Some(_) => {
1771                     extracted.vals.insert(
1772                         before.len(),
1773                         bind_subslice_pat(bcx, pat.id, val, before.len(), after.len())
1774                     );
1775                 }
1776                 &None => ()
1777             }
1778             bcx = before
1779                 .iter()
1780                 .chain(slice.iter())
1781                 .chain(after.iter())
1782                 .zip(extracted.vals)
1783                 .fold(bcx, |bcx, (inner, elem)|
1784                     bind_irrefutable_pat(bcx, &**inner, elem, cleanup_scope)
1785                 );
1786         }
1787         ast::PatMac(..) => {
1788             bcx.sess().span_bug(pat.span, "unexpanded macro");
1789         }
1790         ast::PatQPath(..) | ast::PatWild(_) | ast::PatLit(_) |
1791         ast::PatRange(_, _) => ()
1792     }
1793     return bcx;
1794 }