]> git.lizzy.rs Git - rust.git/blob - src/librustc_codegen_ssa/mir/mod.rs
All Builder methods now take &mut self instead of &self
[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::{LayoutOf, 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 interfaces::*;
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.cx().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.cx().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))
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             bx.delete_basic_block(fx.blocks[bb]);
363         }
364     }
365 }
366
367 fn create_funclets<'a, 'tcx: 'a, Bx: BuilderMethods<'a, 'tcx>>(
368     mir: &'a Mir<'tcx>,
369     bx: &mut Bx,
370     cleanup_kinds: &IndexVec<mir::BasicBlock, CleanupKind>,
371     block_bxs: &IndexVec<mir::BasicBlock, Bx::BasicBlock>)
372     -> (IndexVec<mir::BasicBlock, Option<Bx::BasicBlock>>,
373         IndexVec<mir::BasicBlock, Option<Bx::Funclet>>)
374 {
375     block_bxs.iter_enumerated().zip(cleanup_kinds).map(|((bb, &llbb), cleanup_kind)| {
376         match *cleanup_kind {
377             CleanupKind::Funclet if base::wants_msvc_seh(bx.cx().sess()) => {}
378             _ => return (None, None)
379         }
380
381         let funclet;
382         let ret_llbb;
383         match mir[bb].terminator.as_ref().map(|t| &t.kind) {
384             // This is a basic block that we're aborting the program for,
385             // notably in an `extern` function. These basic blocks are inserted
386             // so that we assert that `extern` functions do indeed not panic,
387             // and if they do we abort the process.
388             //
389             // On MSVC these are tricky though (where we're doing funclets). If
390             // we were to do a cleanuppad (like below) the normal functions like
391             // `longjmp` would trigger the abort logic, terminating the
392             // program. Instead we insert the equivalent of `catch(...)` for C++
393             // which magically doesn't trigger when `longjmp` files over this
394             // frame.
395             //
396             // Lots more discussion can be found on #48251 but this codegen is
397             // modeled after clang's for:
398             //
399             //      try {
400             //          foo();
401             //      } catch (...) {
402             //          bar();
403             //      }
404             Some(&mir::TerminatorKind::Abort) => {
405                 let mut cs_bx = bx.build_sibling_block(&format!("cs_funclet{:?}", bb));
406                 let mut cp_bx = bx.build_sibling_block(&format!("cp_funclet{:?}", bb));
407                 ret_llbb = cs_bx.llbb();
408
409                 let cs = cs_bx.catch_switch(None, None, 1);
410                 cs_bx.add_handler(cs, cp_bx.llbb());
411
412                 // The "null" here is actually a RTTI type descriptor for the
413                 // C++ personality function, but `catch (...)` has no type so
414                 // it's null. The 64 here is actually a bitfield which
415                 // represents that this is a catch-all block.
416                 let null = bx.cx().const_null(bx.cx().type_i8p());
417                 let sixty_four = bx.cx().const_i32(64);
418                 funclet = cp_bx.catch_pad(cs, &[null, sixty_four, null]);
419                 cp_bx.br(llbb);
420             }
421             _ => {
422                 let mut cleanup_bx = bx.build_sibling_block(&format!("funclet_{:?}", bb));
423                 ret_llbb = cleanup_bx.llbb();
424                 funclet = cleanup_bx.cleanup_pad(None, &[]);
425                 cleanup_bx.br(llbb);
426             }
427         };
428
429         (Some(ret_llbb), Some(funclet))
430     }).unzip()
431 }
432
433 /// Produce, for each argument, a `Value` pointing at the
434 /// argument's value. As arguments are places, these are always
435 /// indirect.
436 fn arg_local_refs<'a, 'tcx: 'a, Bx: BuilderMethods<'a, 'tcx>>(
437     bx: &mut Bx,
438     fx: &FunctionCx<'a, 'tcx, Bx>,
439     scopes: &IndexVec<
440         mir::SourceScope,
441         debuginfo::MirDebugScope<Bx::DIScope>
442     >,
443     memory_locals: &BitSet<mir::Local>,
444 ) -> Vec<LocalRef<'tcx, Bx::Value>> {
445     let mir = fx.mir;
446     let tcx = fx.cx.tcx();
447     let mut idx = 0;
448     let mut llarg_idx = fx.fn_ty.ret.is_indirect() as usize;
449
450     // Get the argument scope, if it exists and if we need it.
451     let arg_scope = scopes[mir::OUTERMOST_SOURCE_SCOPE];
452     let arg_scope = if bx.cx().sess().opts.debuginfo == DebugInfo::Full {
453         arg_scope.scope_metadata
454     } else {
455         None
456     };
457
458     mir.args_iter().enumerate().map(|(arg_index, local)| {
459         let arg_decl = &mir.local_decls[local];
460
461         let name = if let Some(name) = arg_decl.name {
462             name.as_str().to_string()
463         } else {
464             format!("arg{}", arg_index)
465         };
466
467         if Some(local) == mir.spread_arg {
468             // This argument (e.g. the last argument in the "rust-call" ABI)
469             // is a tuple that was spread at the ABI level and now we have
470             // to reconstruct it into a tuple local variable, from multiple
471             // individual LLVM function arguments.
472
473             let arg_ty = fx.monomorphize(&arg_decl.ty);
474             let tupled_arg_tys = match arg_ty.sty {
475                 ty::Tuple(ref tys) => tys,
476                 _ => bug!("spread argument isn't a tuple?!")
477             };
478
479             let place = PlaceRef::alloca(bx, bx.cx().layout_of(arg_ty), &name);
480             for i in 0..tupled_arg_tys.len() {
481                 let arg = &fx.fn_ty.args[idx];
482                 idx += 1;
483                 if arg.pad.is_some() {
484                     llarg_idx += 1;
485                 }
486                 let pr_field = place.project_field(bx, i);
487                 bx.store_fn_arg(arg, &mut llarg_idx, pr_field);
488             }
489
490             // Now that we have one alloca that contains the aggregate value,
491             // we can create one debuginfo entry for the argument.
492             arg_scope.map(|scope| {
493                 let variable_access = VariableAccess::DirectVariable {
494                     alloca: place.llval
495                 };
496                 bx.declare_local(
497                     &fx.debug_context,
498                     arg_decl.name.unwrap_or(keywords::Invalid.name()),
499                     arg_ty, scope,
500                     variable_access,
501                     VariableKind::ArgumentVariable(arg_index + 1),
502                     DUMMY_SP
503                 );
504             });
505
506             return LocalRef::Place(place);
507         }
508
509         let arg = &fx.fn_ty.args[idx];
510         idx += 1;
511         if arg.pad.is_some() {
512             llarg_idx += 1;
513         }
514
515         if arg_scope.is_none() && !memory_locals.contains(local) {
516             // We don't have to cast or keep the argument in the alloca.
517             // FIXME(eddyb): We should figure out how to use llvm.dbg.value instead
518             // of putting everything in allocas just so we can use llvm.dbg.declare.
519             let local = |op| LocalRef::Operand(Some(op));
520             match arg.mode {
521                 PassMode::Ignore => {
522                     return local(OperandRef::new_zst(bx.cx(), arg.layout));
523                 }
524                 PassMode::Direct(_) => {
525                     let llarg = bx.cx().get_param(bx.llfn(), llarg_idx as c_uint);
526                     bx.set_value_name(llarg, &name);
527                     llarg_idx += 1;
528                     return local(
529                         OperandRef::from_immediate_or_packed_pair(bx, llarg, arg.layout));
530                 }
531                 PassMode::Pair(..) => {
532                     let a = bx.cx().get_param(bx.llfn(), llarg_idx as c_uint);
533                     bx.set_value_name(a, &(name.clone() + ".0"));
534                     llarg_idx += 1;
535
536                     let b = bx.cx().get_param(bx.llfn(), llarg_idx as c_uint);
537                     bx.set_value_name(b, &(name + ".1"));
538                     llarg_idx += 1;
539
540                     return local(OperandRef {
541                         val: OperandValue::Pair(a, b),
542                         layout: arg.layout
543                     });
544                 }
545                 _ => {}
546             }
547         }
548
549         let place = if arg.is_sized_indirect() {
550             // Don't copy an indirect argument to an alloca, the caller
551             // already put it in a temporary alloca and gave it up.
552             // FIXME: lifetimes
553             let llarg = bx.cx().get_param(bx.llfn(), llarg_idx as c_uint);
554             bx.set_value_name(llarg, &name);
555             llarg_idx += 1;
556             PlaceRef::new_sized(llarg, arg.layout, arg.layout.align)
557         } else if arg.is_unsized_indirect() {
558             // As the storage for the indirect argument lives during
559             // the whole function call, we just copy the fat pointer.
560             let llarg = bx.cx().get_param(bx.llfn(), llarg_idx as c_uint);
561             llarg_idx += 1;
562             let llextra = bx.cx().get_param(bx.llfn(), llarg_idx as c_uint);
563             llarg_idx += 1;
564             let indirect_operand = OperandValue::Pair(llarg, llextra);
565
566             let tmp = PlaceRef::alloca_unsized_indirect(bx, arg.layout, &name);
567             indirect_operand.store(bx, tmp);
568             tmp
569         } else {
570             let tmp = PlaceRef::alloca(bx, arg.layout, &name);
571             bx.store_fn_arg(arg, &mut llarg_idx, tmp);
572             tmp
573         };
574         arg_scope.map(|scope| {
575             // Is this a regular argument?
576             if arg_index > 0 || mir.upvar_decls.is_empty() {
577                 // The Rust ABI passes indirect variables using a pointer and a manual copy, so we
578                 // need to insert a deref here, but the C ABI uses a pointer and a copy using the
579                 // byval attribute, for which LLVM always does the deref itself,
580                 // so we must not add it.
581                 let variable_access = VariableAccess::DirectVariable {
582                     alloca: place.llval
583                 };
584
585                 bx.declare_local(
586                     &fx.debug_context,
587                     arg_decl.name.unwrap_or(keywords::Invalid.name()),
588                     arg.layout.ty,
589                     scope,
590                     variable_access,
591                     VariableKind::ArgumentVariable(arg_index + 1),
592                     DUMMY_SP
593                 );
594                 return;
595             }
596
597             // Or is it the closure environment?
598             let (closure_layout, env_ref) = match arg.layout.ty.sty {
599                 ty::RawPtr(ty::TypeAndMut { ty, .. }) |
600                 ty::Ref(_, ty, _)  => (bx.cx().layout_of(ty), true),
601                 _ => (arg.layout, false)
602             };
603
604             let (def_id, upvar_substs) = match closure_layout.ty.sty {
605                 ty::Closure(def_id, substs) => (def_id, UpvarSubsts::Closure(substs)),
606                 ty::Generator(def_id, substs, _) => (def_id, UpvarSubsts::Generator(substs)),
607                 _ => bug!("upvar_decls with non-closure arg0 type `{}`", closure_layout.ty)
608             };
609             let upvar_tys = upvar_substs.upvar_tys(def_id, tcx);
610
611             // Store the pointer to closure data in an alloca for debuginfo
612             // because that's what the llvm.dbg.declare intrinsic expects.
613
614             // FIXME(eddyb) this shouldn't be necessary but SROA seems to
615             // mishandle DW_OP_plus not preceded by DW_OP_deref, i.e. it
616             // doesn't actually strip the offset when splitting the closure
617             // environment into its components so it ends up out of bounds.
618             // (cuviper) It seems to be fine without the alloca on LLVM 6 and later.
619             let env_alloca = !env_ref && bx.cx().closure_env_needs_indirect_debuginfo();
620             let env_ptr = if env_alloca {
621                 let scratch = PlaceRef::alloca(bx,
622                     bx.cx().layout_of(tcx.mk_mut_ptr(arg.layout.ty)),
623                     "__debuginfo_env_ptr");
624                 bx.store(place.llval, scratch.llval, scratch.align);
625                 scratch.llval
626             } else {
627                 place.llval
628             };
629
630             for (i, (decl, ty)) in mir.upvar_decls.iter().zip(upvar_tys).enumerate() {
631                 let byte_offset_of_var_in_env = closure_layout.fields.offset(i).bytes();
632
633                 let ops = bx.cx().debuginfo_upvar_decls_ops_sequence(byte_offset_of_var_in_env);
634
635                 // The environment and the capture can each be indirect.
636
637                 // FIXME(eddyb) see above why we sometimes have to keep
638                 // a pointer in an alloca for debuginfo atm.
639                 let mut ops = if env_ref || env_alloca { &ops[..] } else { &ops[1..] };
640
641                 let ty = if let (true, &ty::Ref(_, ty, _)) = (decl.by_ref, &ty.sty) {
642                     ty
643                 } else {
644                     ops = &ops[..ops.len() - 1];
645                     ty
646                 };
647
648                 let variable_access = VariableAccess::IndirectVariable {
649                     alloca: env_ptr,
650                     address_operations: &ops
651                 };
652                 bx.declare_local(
653                     &fx.debug_context,
654                     decl.debug_name,
655                     ty,
656                     scope,
657                     variable_access,
658                     VariableKind::LocalVariable,
659                     DUMMY_SP
660                 );
661             }
662         });
663         if arg.is_unsized_indirect() {
664             LocalRef::UnsizedPlace(place)
665         } else {
666             LocalRef::Place(place)
667         }
668     }).collect()
669 }
670
671 mod analyze;
672 mod block;
673 pub mod constant;
674 pub mod place;
675 pub mod operand;
676 mod rvalue;
677 mod statement;