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