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