]> git.lizzy.rs Git - rust.git/blob - src/librustc_codegen_ssa/mir/mod.rs
Various minor/cosmetic improvements to code
[rust.git] / src / librustc_codegen_ssa / mir / mod.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 use libc::c_uint;
12 use rustc::ty::{self, Ty, TypeFoldable, UpvarSubsts};
13 use rustc::ty::layout::{TyLayout, HasTyCtxt};
14 use rustc::mir::{self, Mir};
15 use rustc::ty::subst::Substs;
16 use rustc::session::config::DebugInfo;
17 use base;
18 use debuginfo::{self, VariableAccess, VariableKind, FunctionDebugContext};
19 use rustc_mir::monomorphize::Instance;
20 use rustc_target::abi::call::{FnType, PassMode};
21 use traits::*;
22
23 use syntax_pos::{DUMMY_SP, NO_EXPANSION, BytePos, Span};
24 use syntax::symbol::keywords;
25
26 use std::iter;
27
28 use rustc_data_structures::bit_set::BitSet;
29 use rustc_data_structures::indexed_vec::IndexVec;
30
31 use self::analyze::CleanupKind;
32 use self::place::PlaceRef;
33 use rustc::mir::traversal;
34
35 use self::operand::{OperandRef, OperandValue};
36
37 /// Master context for codegenning from MIR.
38 pub struct FunctionCx<'a, 'tcx: 'a, Bx: BuilderMethods<'a, 'tcx>> {
39     instance: Instance<'tcx>,
40
41     mir: &'a mir::Mir<'tcx>,
42
43     debug_context: FunctionDebugContext<Bx::DIScope>,
44
45     llfn: Bx::Value,
46
47     cx: &'a Bx::CodegenCx,
48
49     fn_ty: FnType<'tcx, Ty<'tcx>>,
50
51     /// When unwinding is initiated, we have to store this personality
52     /// value somewhere so that we can load it and re-use it in the
53     /// resume instruction. The personality is (afaik) some kind of
54     /// value used for C++ unwinding, which must filter by type: we
55     /// don't really care about it very much. Anyway, this value
56     /// contains an alloca into which the personality is stored and
57     /// then later loaded when generating the DIVERGE_BLOCK.
58     personality_slot: Option<PlaceRef<'tcx, Bx::Value,>>,
59
60     /// A `Block` for each MIR `BasicBlock`
61     blocks: IndexVec<mir::BasicBlock, Bx::BasicBlock>,
62
63     /// The funclet status of each basic block
64     cleanup_kinds: IndexVec<mir::BasicBlock, analyze::CleanupKind>,
65
66     /// When targeting MSVC, this stores the cleanup info for each funclet
67     /// BB. This is initialized as we compute the funclets' head block in RPO.
68     funclets: IndexVec<mir::BasicBlock, Option<Bx::Funclet>>,
69
70     /// This stores the landing-pad block for a given BB, computed lazily on GNU
71     /// and eagerly on MSVC.
72     landing_pads: IndexVec<mir::BasicBlock, Option<Bx::BasicBlock>>,
73
74     /// Cached unreachable block
75     unreachable_block: Option<Bx::BasicBlock>,
76
77     /// The location where each MIR arg/var/tmp/ret is stored. This is
78     /// usually an `PlaceRef` representing an alloca, but not always:
79     /// sometimes we can skip the alloca and just store the value
80     /// directly using an `OperandRef`, which makes for tighter LLVM
81     /// IR. The conditions for using an `OperandRef` are as follows:
82     ///
83     /// - the type of the local must be judged "immediate" by `is_llvm_immediate`
84     /// - the operand must never be referenced indirectly
85     ///     - we should not take its address using the `&` operator
86     ///     - nor should it appear in a place path like `tmp.a`
87     /// - the operand must be defined by an rvalue that can generate immediate
88     ///   values
89     ///
90     /// Avoiding allocs can also be important for certain intrinsics,
91     /// notably `expect`.
92     locals: IndexVec<mir::Local, LocalRef<'tcx, Bx::Value>>,
93
94     /// Debug information for MIR scopes.
95     scopes: IndexVec<mir::SourceScope, debuginfo::MirDebugScope<Bx::DIScope>>,
96
97     /// If this function is being monomorphized, this contains the type substitutions used.
98     param_substs: &'tcx Substs<'tcx>,
99 }
100
101 impl<'a, 'tcx: 'a, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
102     pub fn monomorphize<T>(&self, value: &T) -> T
103         where T: TypeFoldable<'tcx>
104     {
105         self.cx.tcx().subst_and_normalize_erasing_regions(
106             self.param_substs,
107             ty::ParamEnv::reveal_all(),
108             value,
109         )
110     }
111
112     pub fn set_debug_loc(
113         &mut self,
114         bx: &mut Bx,
115         source_info: mir::SourceInfo
116     ) {
117         let (scope, span) = self.debug_loc(source_info);
118         bx.set_source_location(&self.debug_context, scope, span);
119     }
120
121     pub fn debug_loc(&self, source_info: mir::SourceInfo) -> (Option<Bx::DIScope>, Span) {
122         // Bail out if debug info emission is not enabled.
123         match self.debug_context {
124             FunctionDebugContext::DebugInfoDisabled |
125             FunctionDebugContext::FunctionWithoutDebugInfo => {
126                 return (self.scopes[source_info.scope].scope_metadata, source_info.span);
127             }
128             FunctionDebugContext::RegularContext(_) =>{}
129         }
130
131         // In order to have a good line stepping behavior in debugger, we overwrite debug
132         // locations of macro expansions with that of the outermost expansion site
133         // (unless the crate is being compiled with `-Z debug-macros`).
134         if source_info.span.ctxt() == NO_EXPANSION ||
135            self.cx.sess().opts.debugging_opts.debug_macros {
136             let scope = self.scope_metadata_for_loc(source_info.scope, source_info.span.lo());
137             (scope, source_info.span)
138         } else {
139             // Walk up the macro expansion chain until we reach a non-expanded span.
140             // We also stop at the function body level because no line stepping can occur
141             // at the level above that.
142             let mut span = source_info.span;
143             while span.ctxt() != NO_EXPANSION && span.ctxt() != self.mir.span.ctxt() {
144                 if let Some(info) = span.ctxt().outer().expn_info() {
145                     span = info.call_site;
146                 } else {
147                     break;
148                 }
149             }
150             let scope = self.scope_metadata_for_loc(source_info.scope, span.lo());
151             // Use span of the outermost expansion site, while keeping the original lexical scope.
152             (scope, span)
153         }
154     }
155
156     // DILocations inherit source file name from the parent DIScope.  Due to macro expansions
157     // it may so happen that the current span belongs to a different file than the DIScope
158     // corresponding to span's containing source scope.  If so, we need to create a DIScope
159     // "extension" into that file.
160     fn scope_metadata_for_loc(&self, scope_id: mir::SourceScope, pos: BytePos)
161                               -> Option<Bx::DIScope> {
162         let scope_metadata = self.scopes[scope_id].scope_metadata;
163         if pos < self.scopes[scope_id].file_start_pos ||
164            pos >= self.scopes[scope_id].file_end_pos {
165             let sm = self.cx.sess().source_map();
166             let defining_crate = self.debug_context.get_ref(DUMMY_SP).defining_crate;
167             Some(self.cx.extend_scope_to_file(
168                 scope_metadata.unwrap(),
169                 &sm.lookup_char_pos(pos).file,
170                 defining_crate
171             ))
172         } else {
173             scope_metadata
174         }
175     }
176 }
177
178 enum LocalRef<'tcx, V> {
179     Place(PlaceRef<'tcx, V>),
180     /// `UnsizedPlace(p)`: `p` itself is a thin pointer (indirect place).
181     /// `*p` is the fat pointer that references the actual unsized place.
182     /// Every time it is initialized, we have to reallocate the place
183     /// and update the fat pointer. That's the reason why it is indirect.
184     UnsizedPlace(PlaceRef<'tcx, V>),
185     Operand(Option<OperandRef<'tcx, V>>),
186 }
187
188 impl<'tcx, V: CodegenObject> LocalRef<'tcx, V> {
189     fn new_operand<Cx: CodegenMethods<'tcx, Value = V>>(
190         cx: &Cx,
191         layout: TyLayout<'tcx>,
192     ) -> LocalRef<'tcx, V> {
193         if layout.is_zst() {
194             // Zero-size temporaries aren't always initialized, which
195             // doesn't matter because they don't contain data, but
196             // we need something in the operand.
197             LocalRef::Operand(Some(OperandRef::new_zst(cx, layout)))
198         } else {
199             LocalRef::Operand(None)
200         }
201     }
202 }
203
204 ///////////////////////////////////////////////////////////////////////////
205
206 pub fn codegen_mir<'a, 'tcx: 'a, Bx: BuilderMethods<'a, 'tcx>>(
207     cx: &'a Bx::CodegenCx,
208     llfn: Bx::Value,
209     mir: &'a Mir<'tcx>,
210     instance: Instance<'tcx>,
211     sig: ty::FnSig<'tcx>,
212 ) {
213     let fn_ty = cx.new_fn_type(sig, &[]);
214     debug!("fn_ty: {:?}", fn_ty);
215     let debug_context =
216         cx.create_function_debug_context(instance, sig, llfn, mir);
217     let mut bx = Bx::new_block(cx, llfn, "start");
218
219     if mir.basic_blocks().iter().any(|bb| bb.is_cleanup) {
220         bx.set_personality_fn(cx.eh_personality());
221     }
222
223     let cleanup_kinds = analyze::cleanup_kinds(&mir);
224     // Allocate a `Block` for every basic block, except
225     // the start block, if nothing loops back to it.
226     let reentrant_start_block = !mir.predecessors_for(mir::START_BLOCK).is_empty();
227     let block_bxs: IndexVec<mir::BasicBlock, Bx::BasicBlock> =
228         mir.basic_blocks().indices().map(|bb| {
229             if bb == mir::START_BLOCK && !reentrant_start_block {
230                 bx.llbb()
231             } else {
232                 bx.build_sibling_block(&format!("{:?}", bb)).llbb()
233             }
234         }).collect();
235
236     // Compute debuginfo scopes from MIR scopes.
237     let scopes = cx.create_mir_scopes(mir, &debug_context);
238     let (landing_pads, funclets) = create_funclets(mir, &mut bx, &cleanup_kinds, &block_bxs);
239
240     let mut fx = FunctionCx {
241         instance,
242         mir,
243         llfn,
244         fn_ty,
245         cx,
246         personality_slot: None,
247         blocks: block_bxs,
248         unreachable_block: None,
249         cleanup_kinds,
250         landing_pads,
251         funclets,
252         scopes,
253         locals: IndexVec::new(),
254         debug_context,
255         param_substs: {
256             assert!(!instance.substs.needs_infer());
257             instance.substs
258         },
259     };
260
261     let memory_locals = analyze::non_ssa_locals(&fx);
262
263     // Allocate variable and temp allocas
264     fx.locals = {
265         let args = arg_local_refs(&mut bx, &fx, &fx.scopes, &memory_locals);
266
267         let mut allocate_local = |local| {
268             let decl = &mir.local_decls[local];
269             let layout = bx.layout_of(fx.monomorphize(&decl.ty));
270             assert!(!layout.ty.has_erasable_regions());
271
272             if let Some(name) = decl.name {
273                 // User variable
274                 let debug_scope = fx.scopes[decl.visibility_scope];
275                 let dbg = debug_scope.is_valid() &&
276                     bx.sess().opts.debuginfo == DebugInfo::Full;
277
278                 if !memory_locals.contains(local) && !dbg {
279                     debug!("alloc: {:?} ({}) -> operand", local, name);
280                     return LocalRef::new_operand(bx.cx(), layout);
281                 }
282
283                 debug!("alloc: {:?} ({}) -> place", local, name);
284                 if layout.is_unsized() {
285                     let indirect_place =
286                         PlaceRef::alloca_unsized_indirect(&mut bx, layout, &name.as_str());
287                     // FIXME: add an appropriate debuginfo
288                     LocalRef::UnsizedPlace(indirect_place)
289                 } else {
290                     let place = PlaceRef::alloca(&mut bx, layout, &name.as_str());
291                     if dbg {
292                         let (scope, span) = fx.debug_loc(mir::SourceInfo {
293                             span: decl.source_info.span,
294                             scope: decl.visibility_scope,
295                         });
296                         bx.declare_local(&fx.debug_context, name, layout.ty, scope.unwrap(),
297                             VariableAccess::DirectVariable { alloca: place.llval },
298                             VariableKind::LocalVariable, span);
299                     }
300                     LocalRef::Place(place)
301                 }
302             } else {
303                 // Temporary or return place
304                 if local == mir::RETURN_PLACE && fx.fn_ty.ret.is_indirect() {
305                     debug!("alloc: {:?} (return place) -> place", local);
306                     let llretptr = fx.cx.get_param(llfn, 0);
307                     LocalRef::Place(PlaceRef::new_sized(llretptr, layout, layout.align.abi))
308                 } else if memory_locals.contains(local) {
309                     debug!("alloc: {:?} -> place", local);
310                     if layout.is_unsized() {
311                         let indirect_place = PlaceRef::alloca_unsized_indirect(
312                             &mut bx,
313                             layout,
314                             &format!("{:?}", local),
315                         );
316                         LocalRef::UnsizedPlace(indirect_place)
317                     } else {
318                         LocalRef::Place(PlaceRef::alloca(&mut bx, layout, &format!("{:?}", local)))
319                     }
320                 } else {
321                     // If this is an immediate local, we do not create an
322                     // alloca in advance. Instead we wait until we see the
323                     // definition and update the operand there.
324                     debug!("alloc: {:?} -> operand", local);
325                     LocalRef::new_operand(bx.cx(), layout)
326                 }
327             }
328         };
329
330         let retptr = allocate_local(mir::RETURN_PLACE);
331         iter::once(retptr)
332             .chain(args.into_iter())
333             .chain(mir.vars_and_temps_iter().map(allocate_local))
334             .collect()
335     };
336
337     // Branch to the START block, if it's not the entry block.
338     if reentrant_start_block {
339         bx.br(fx.blocks[mir::START_BLOCK]);
340     }
341
342     // Up until here, IR instructions for this function have explicitly not been annotated with
343     // source code location, so we don't step into call setup code. From here on, source location
344     // emitting should be enabled.
345     debuginfo::start_emitting_source_locations(&fx.debug_context);
346
347     let rpo = traversal::reverse_postorder(&mir);
348     let mut visited = BitSet::new_empty(mir.basic_blocks().len());
349
350     // Codegen the body of each block using reverse postorder
351     for (bb, _) in rpo {
352         visited.insert(bb.index());
353         fx.codegen_block(bb);
354     }
355
356     // Remove blocks that haven't been visited, or have no
357     // predecessors.
358     for bb in mir.basic_blocks().indices() {
359         // Unreachable block
360         if !visited.contains(bb.index()) {
361             debug!("codegen_mir: block {:?} was not visited", bb);
362             unsafe {
363                 bx.delete_basic_block(fx.blocks[bb]);
364             }
365         }
366     }
367 }
368
369 fn create_funclets<'a, 'tcx: 'a, Bx: BuilderMethods<'a, 'tcx>>(
370     mir: &'a Mir<'tcx>,
371     bx: &mut Bx,
372     cleanup_kinds: &IndexVec<mir::BasicBlock, CleanupKind>,
373     block_bxs: &IndexVec<mir::BasicBlock, Bx::BasicBlock>)
374     -> (IndexVec<mir::BasicBlock, Option<Bx::BasicBlock>>,
375         IndexVec<mir::BasicBlock, Option<Bx::Funclet>>)
376 {
377     block_bxs.iter_enumerated().zip(cleanup_kinds).map(|((bb, &llbb), cleanup_kind)| {
378         match *cleanup_kind {
379             CleanupKind::Funclet if base::wants_msvc_seh(bx.sess()) => {}
380             _ => return (None, None)
381         }
382
383         let funclet;
384         let ret_llbb;
385         match mir[bb].terminator.as_ref().map(|t| &t.kind) {
386             // This is a basic block that we're aborting the program for,
387             // notably in an `extern` function. These basic blocks are inserted
388             // so that we assert that `extern` functions do indeed not panic,
389             // and if they do we abort the process.
390             //
391             // On MSVC these are tricky though (where we're doing funclets). If
392             // we were to do a cleanuppad (like below) the normal functions like
393             // `longjmp` would trigger the abort logic, terminating the
394             // program. Instead we insert the equivalent of `catch(...)` for C++
395             // which magically doesn't trigger when `longjmp` files over this
396             // frame.
397             //
398             // Lots more discussion can be found on #48251 but this codegen is
399             // modeled after clang's for:
400             //
401             //      try {
402             //          foo();
403             //      } catch (...) {
404             //          bar();
405             //      }
406             Some(&mir::TerminatorKind::Abort) => {
407                 let mut cs_bx = bx.build_sibling_block(&format!("cs_funclet{:?}", bb));
408                 let mut cp_bx = bx.build_sibling_block(&format!("cp_funclet{:?}", bb));
409                 ret_llbb = cs_bx.llbb();
410
411                 let cs = cs_bx.catch_switch(None, None, 1);
412                 cs_bx.add_handler(cs, cp_bx.llbb());
413
414                 // The "null" here is actually a RTTI type descriptor for the
415                 // C++ personality function, but `catch (...)` has no type so
416                 // it's null. The 64 here is actually a bitfield which
417                 // represents that this is a catch-all block.
418                 let null = bx.const_null(bx.type_i8p());
419                 let sixty_four = bx.const_i32(64);
420                 funclet = cp_bx.catch_pad(cs, &[null, sixty_four, null]);
421                 cp_bx.br(llbb);
422             }
423             _ => {
424                 let mut cleanup_bx = bx.build_sibling_block(&format!("funclet_{:?}", bb));
425                 ret_llbb = cleanup_bx.llbb();
426                 funclet = cleanup_bx.cleanup_pad(None, &[]);
427                 cleanup_bx.br(llbb);
428             }
429         };
430
431         (Some(ret_llbb), Some(funclet))
432     }).unzip()
433 }
434
435 /// Produce, for each argument, a `Value` pointing at the
436 /// argument's value. As arguments are places, these are always
437 /// indirect.
438 fn arg_local_refs<'a, 'tcx: 'a, Bx: BuilderMethods<'a, 'tcx>>(
439     bx: &mut Bx,
440     fx: &FunctionCx<'a, 'tcx, Bx>,
441     scopes: &IndexVec<
442         mir::SourceScope,
443         debuginfo::MirDebugScope<Bx::DIScope>
444     >,
445     memory_locals: &BitSet<mir::Local>,
446 ) -> Vec<LocalRef<'tcx, Bx::Value>> {
447     let mir = fx.mir;
448     let tcx = fx.cx.tcx();
449     let mut idx = 0;
450     let mut llarg_idx = fx.fn_ty.ret.is_indirect() as usize;
451
452     // Get the argument scope, if it exists and if we need it.
453     let arg_scope = scopes[mir::OUTERMOST_SOURCE_SCOPE];
454     let arg_scope = if bx.sess().opts.debuginfo == DebugInfo::Full {
455         arg_scope.scope_metadata
456     } else {
457         None
458     };
459
460     mir.args_iter().enumerate().map(|(arg_index, local)| {
461         let arg_decl = &mir.local_decls[local];
462
463         let name = if let Some(name) = arg_decl.name {
464             name.as_str().to_string()
465         } else {
466             format!("arg{}", arg_index)
467         };
468
469         if Some(local) == mir.spread_arg {
470             // This argument (e.g., the last argument in the "rust-call" ABI)
471             // is a tuple that was spread at the ABI level and now we have
472             // to reconstruct it into a tuple local variable, from multiple
473             // individual LLVM function arguments.
474
475             let arg_ty = fx.monomorphize(&arg_decl.ty);
476             let tupled_arg_tys = match arg_ty.sty {
477                 ty::Tuple(ref tys) => tys,
478                 _ => bug!("spread argument isn't a tuple?!")
479             };
480
481             let place = PlaceRef::alloca(bx, bx.layout_of(arg_ty), &name);
482             for i in 0..tupled_arg_tys.len() {
483                 let arg = &fx.fn_ty.args[idx];
484                 idx += 1;
485                 if arg.pad.is_some() {
486                     llarg_idx += 1;
487                 }
488                 let pr_field = place.project_field(bx, i);
489                 bx.store_fn_arg(arg, &mut llarg_idx, pr_field);
490             }
491
492             // Now that we have one alloca that contains the aggregate value,
493             // we can create one debuginfo entry for the argument.
494             arg_scope.map(|scope| {
495                 let variable_access = VariableAccess::DirectVariable {
496                     alloca: place.llval
497                 };
498                 bx.declare_local(
499                     &fx.debug_context,
500                     arg_decl.name.unwrap_or(keywords::Invalid.name()),
501                     arg_ty, scope,
502                     variable_access,
503                     VariableKind::ArgumentVariable(arg_index + 1),
504                     DUMMY_SP
505                 );
506             });
507
508             return LocalRef::Place(place);
509         }
510
511         let arg = &fx.fn_ty.args[idx];
512         idx += 1;
513         if arg.pad.is_some() {
514             llarg_idx += 1;
515         }
516
517         if arg_scope.is_none() && !memory_locals.contains(local) {
518             // We don't have to cast or keep the argument in the alloca.
519             // FIXME(eddyb): We should figure out how to use llvm.dbg.value instead
520             // of putting everything in allocas just so we can use llvm.dbg.declare.
521             let local = |op| LocalRef::Operand(Some(op));
522             match arg.mode {
523                 PassMode::Ignore => {
524                     return local(OperandRef::new_zst(bx.cx(), arg.layout));
525                 }
526                 PassMode::Direct(_) => {
527                     let llarg = bx.get_param(bx.llfn(), llarg_idx as c_uint);
528                     bx.set_value_name(llarg, &name);
529                     llarg_idx += 1;
530                     return local(
531                         OperandRef::from_immediate_or_packed_pair(bx, llarg, arg.layout));
532                 }
533                 PassMode::Pair(..) => {
534                     let a = bx.get_param(bx.llfn(), llarg_idx as c_uint);
535                     bx.set_value_name(a, &(name.clone() + ".0"));
536                     llarg_idx += 1;
537
538                     let b = bx.get_param(bx.llfn(), llarg_idx as c_uint);
539                     bx.set_value_name(b, &(name + ".1"));
540                     llarg_idx += 1;
541
542                     return local(OperandRef {
543                         val: OperandValue::Pair(a, b),
544                         layout: arg.layout
545                     });
546                 }
547                 _ => {}
548             }
549         }
550
551         let place = if arg.is_sized_indirect() {
552             // Don't copy an indirect argument to an alloca, the caller
553             // already put it in a temporary alloca and gave it up.
554             // FIXME: lifetimes
555             let llarg = bx.get_param(bx.llfn(), llarg_idx as c_uint);
556             bx.set_value_name(llarg, &name);
557             llarg_idx += 1;
558             PlaceRef::new_sized(llarg, arg.layout, arg.layout.align.abi)
559         } else if arg.is_unsized_indirect() {
560             // As the storage for the indirect argument lives during
561             // the whole function call, we just copy the fat pointer.
562             let llarg = bx.get_param(bx.llfn(), llarg_idx as c_uint);
563             llarg_idx += 1;
564             let llextra = bx.get_param(bx.llfn(), llarg_idx as c_uint);
565             llarg_idx += 1;
566             let indirect_operand = OperandValue::Pair(llarg, llextra);
567
568             let tmp = PlaceRef::alloca_unsized_indirect(bx, arg.layout, &name);
569             indirect_operand.store(bx, tmp);
570             tmp
571         } else {
572             let tmp = PlaceRef::alloca(bx, arg.layout, &name);
573             bx.store_fn_arg(arg, &mut llarg_idx, tmp);
574             tmp
575         };
576         arg_scope.map(|scope| {
577             // Is this a regular argument?
578             if arg_index > 0 || mir.upvar_decls.is_empty() {
579                 // The Rust ABI passes indirect variables using a pointer and a manual copy, so we
580                 // need to insert a deref here, but the C ABI uses a pointer and a copy using the
581                 // byval attribute, for which LLVM always does the deref itself,
582                 // so we must not add it.
583                 let variable_access = VariableAccess::DirectVariable {
584                     alloca: place.llval
585                 };
586
587                 bx.declare_local(
588                     &fx.debug_context,
589                     arg_decl.name.unwrap_or(keywords::Invalid.name()),
590                     arg.layout.ty,
591                     scope,
592                     variable_access,
593                     VariableKind::ArgumentVariable(arg_index + 1),
594                     DUMMY_SP
595                 );
596                 return;
597             }
598
599             // Or is it the closure environment?
600             let (closure_layout, env_ref) = match arg.layout.ty.sty {
601                 ty::RawPtr(ty::TypeAndMut { ty, .. }) |
602                 ty::Ref(_, ty, _)  => (bx.layout_of(ty), true),
603                 _ => (arg.layout, false)
604             };
605
606             let (def_id, upvar_substs) = match closure_layout.ty.sty {
607                 ty::Closure(def_id, substs) => (def_id, UpvarSubsts::Closure(substs)),
608                 ty::Generator(def_id, substs, _) => (def_id, UpvarSubsts::Generator(substs)),
609                 _ => bug!("upvar_decls with non-closure arg0 type `{}`", closure_layout.ty)
610             };
611             let upvar_tys = upvar_substs.upvar_tys(def_id, tcx);
612
613             // Store the pointer to closure data in an alloca for debuginfo
614             // because that's what the llvm.dbg.declare intrinsic expects.
615
616             // FIXME(eddyb) this shouldn't be necessary but SROA seems to
617             // mishandle DW_OP_plus not preceded by DW_OP_deref, i.e., it
618             // doesn't actually strip the offset when splitting the closure
619             // environment into its components so it ends up out of bounds.
620             // (cuviper) It seems to be fine without the alloca on LLVM 6 and later.
621             let env_alloca = !env_ref && bx.closure_env_needs_indirect_debuginfo();
622             let env_ptr = if env_alloca {
623                 let scratch = PlaceRef::alloca(bx,
624                     bx.layout_of(tcx.mk_mut_ptr(arg.layout.ty)),
625                     "__debuginfo_env_ptr");
626                 bx.store(place.llval, scratch.llval, scratch.align);
627                 scratch.llval
628             } else {
629                 place.llval
630             };
631
632             for (i, (decl, ty)) in mir.upvar_decls.iter().zip(upvar_tys).enumerate() {
633                 let byte_offset_of_var_in_env = closure_layout.fields.offset(i).bytes();
634
635                 let ops = bx.debuginfo_upvar_decls_ops_sequence(byte_offset_of_var_in_env);
636
637                 // The environment and the capture can each be indirect.
638
639                 // FIXME(eddyb) see above why we sometimes have to keep
640                 // a pointer in an alloca for debuginfo atm.
641                 let mut ops = if env_ref || env_alloca { &ops[..] } else { &ops[1..] };
642
643                 let ty = if let (true, &ty::Ref(_, ty, _)) = (decl.by_ref, &ty.sty) {
644                     ty
645                 } else {
646                     ops = &ops[..ops.len() - 1];
647                     ty
648                 };
649
650                 let variable_access = VariableAccess::IndirectVariable {
651                     alloca: env_ptr,
652                     address_operations: &ops
653                 };
654                 bx.declare_local(
655                     &fx.debug_context,
656                     decl.debug_name,
657                     ty,
658                     scope,
659                     variable_access,
660                     VariableKind::LocalVariable,
661                     DUMMY_SP
662                 );
663             }
664         });
665         if arg.is_unsized_indirect() {
666             LocalRef::UnsizedPlace(place)
667         } else {
668             LocalRef::Place(place)
669         }
670     }).collect()
671 }
672
673 mod analyze;
674 mod block;
675 pub mod constant;
676 pub mod place;
677 pub mod operand;
678 mod rvalue;
679 mod statement;