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