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.
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.
12 use llvm::{self, ValueRef, BasicBlockRef};
13 use llvm::debuginfo::DIScope;
14 use rustc::ty::{self, layout};
15 use rustc::mir::{self, Mir};
16 use rustc::mir::tcx::LvalueTy;
17 use rustc::ty::subst::Substs;
18 use rustc::infer::TransNormalize;
19 use rustc::ty::TypeFoldable;
20 use session::config::FullDebugInfo;
23 use common::{self, CrateContext, C_null, Funclet};
24 use debuginfo::{self, declare_local, VariableAccess, VariableKind, FunctionDebugContext};
25 use monomorphize::{self, Instance};
29 use syntax_pos::{DUMMY_SP, NO_EXPANSION, COMMAND_LINE_EXPN, BytePos, Span};
30 use syntax::symbol::keywords;
35 use rustc_data_structures::bitvec::BitVector;
36 use rustc_data_structures::indexed_vec::{IndexVec, Idx};
38 pub use self::constant::trans_static_initializer;
40 use self::analyze::CleanupKind;
41 use self::lvalue::LvalueRef;
42 use rustc::mir::traversal;
44 use self::operand::{OperandRef, OperandValue};
46 /// Master context for translating MIR.
47 pub struct MirContext<'a, 'tcx:'a> {
48 mir: &'a mir::Mir<'tcx>,
50 debug_context: debuginfo::FunctionDebugContext,
54 ccx: &'a CrateContext<'a, 'tcx>,
58 /// When unwinding is initiated, we have to store this personality
59 /// value somewhere so that we can load it and re-use it in the
60 /// resume instruction. The personality is (afaik) some kind of
61 /// value used for C++ unwinding, which must filter by type: we
62 /// don't really care about it very much. Anyway, this value
63 /// contains an alloca into which the personality is stored and
64 /// then later loaded when generating the DIVERGE_BLOCK.
65 llpersonalityslot: Option<ValueRef>,
67 /// A `Block` for each MIR `BasicBlock`
68 blocks: IndexVec<mir::BasicBlock, BasicBlockRef>,
70 /// The funclet status of each basic block
71 cleanup_kinds: IndexVec<mir::BasicBlock, analyze::CleanupKind>,
73 /// This stores the landing-pad block for a given BB, computed lazily on GNU
74 /// and eagerly on MSVC.
75 landing_pads: IndexVec<mir::BasicBlock, Option<BasicBlockRef>>,
77 /// Cached unreachable block
78 unreachable_block: Option<BasicBlockRef>,
80 /// The location where each MIR arg/var/tmp/ret is stored. This is
81 /// usually an `LvalueRef` representing an alloca, but not always:
82 /// sometimes we can skip the alloca and just store the value
83 /// directly using an `OperandRef`, which makes for tighter LLVM
84 /// IR. The conditions for using an `OperandRef` are as follows:
86 /// - the type of the local must be judged "immediate" by `type_is_immediate`
87 /// - the operand must never be referenced indirectly
88 /// - we should not take its address using the `&` operator
89 /// - nor should it appear in an lvalue path like `tmp.a`
90 /// - the operand must be defined by an rvalue that can generate immediate
93 /// Avoiding allocs can also be important for certain intrinsics,
95 locals: IndexVec<mir::Local, LocalRef<'tcx>>,
97 /// Debug information for MIR scopes.
98 scopes: IndexVec<mir::VisibilityScope, debuginfo::MirDebugScope>,
100 /// If this function is being monomorphized, this contains the type substitutions used.
101 param_substs: &'tcx Substs<'tcx>,
104 impl<'a, 'tcx> MirContext<'a, 'tcx> {
105 pub fn monomorphize<T>(&self, value: &T) -> T
106 where T: TransNormalize<'tcx> {
107 monomorphize::apply_param_substs(self.ccx.shared(), self.param_substs, value)
110 pub fn set_debug_loc(&mut self, bcx: &Builder, source_info: mir::SourceInfo) {
111 let (scope, span) = self.debug_loc(source_info);
112 debuginfo::set_source_location(&self.debug_context, bcx, scope, span);
115 pub fn debug_loc(&mut self, source_info: mir::SourceInfo) -> (DIScope, Span) {
116 // Bail out if debug info emission is not enabled.
117 match self.debug_context {
118 FunctionDebugContext::DebugInfoDisabled |
119 FunctionDebugContext::FunctionWithoutDebugInfo => {
120 return (self.scopes[source_info.scope].scope_metadata, source_info.span);
122 FunctionDebugContext::RegularContext(_) =>{}
125 // In order to have a good line stepping behavior in debugger, we overwrite debug
126 // locations of macro expansions with that of the outermost expansion site
127 // (unless the crate is being compiled with `-Z debug-macros`).
128 if source_info.span.expn_id == NO_EXPANSION ||
129 source_info.span.expn_id == COMMAND_LINE_EXPN ||
130 self.ccx.sess().opts.debugging_opts.debug_macros {
132 let scope = self.scope_metadata_for_loc(source_info.scope, source_info.span.lo);
133 (scope, source_info.span)
135 let cm = self.ccx.sess().codemap();
136 // Walk up the macro expansion chain until we reach a non-expanded span.
137 let mut span = source_info.span;
138 while span.expn_id != NO_EXPANSION && span.expn_id != COMMAND_LINE_EXPN {
139 if let Some(callsite_span) = cm.with_expn_info(span.expn_id,
140 |ei| ei.map(|ei| ei.call_site.clone())) {
141 span = callsite_span;
146 let scope = self.scope_metadata_for_loc(source_info.scope, span.lo);
147 // Use span of the outermost call site, while keeping the original lexical scope
152 // DILocations inherit source file name from the parent DIScope. Due to macro expansions
153 // it may so happen that the current span belongs to a different file than the DIScope
154 // corresponding to span's containing visibility scope. If so, we need to create a DIScope
155 // "extension" into that file.
156 fn scope_metadata_for_loc(&self, scope_id: mir::VisibilityScope, pos: BytePos)
157 -> llvm::debuginfo::DIScope {
158 let scope_metadata = self.scopes[scope_id].scope_metadata;
159 if pos < self.scopes[scope_id].file_start_pos ||
160 pos >= self.scopes[scope_id].file_end_pos {
161 let cm = self.ccx.sess().codemap();
162 debuginfo::extend_scope_to_file(self.ccx, scope_metadata, &cm.lookup_char_pos(pos).file)
169 enum LocalRef<'tcx> {
170 Lvalue(LvalueRef<'tcx>),
171 Operand(Option<OperandRef<'tcx>>),
174 impl<'tcx> LocalRef<'tcx> {
175 fn new_operand<'a>(ccx: &CrateContext<'a, 'tcx>,
176 ty: ty::Ty<'tcx>) -> LocalRef<'tcx> {
177 if common::type_is_zero_size(ccx, ty) {
178 // Zero-size temporaries aren't always initialized, which
179 // doesn't matter because they don't contain data, but
180 // we need something in the operand.
181 let llty = type_of::type_of(ccx, ty);
182 let val = if common::type_is_imm_pair(ccx, ty) {
183 let fields = llty.field_types();
184 OperandValue::Pair(C_null(fields[0]), C_null(fields[1]))
186 OperandValue::Immediate(C_null(llty))
188 let op = OperandRef {
192 LocalRef::Operand(Some(op))
194 LocalRef::Operand(None)
199 ///////////////////////////////////////////////////////////////////////////
201 pub fn trans_mir<'a, 'tcx: 'a>(
202 ccx: &'a CrateContext<'a, 'tcx>,
206 instance: Instance<'tcx>,
207 sig: &ty::FnSig<'tcx>,
210 debug!("fn_ty: {:?}", fn_ty);
212 debuginfo::create_function_debug_context(ccx, instance, sig, abi, llfn, mir);
213 let bcx = Builder::new_block(ccx, llfn, "entry-block");
215 let cleanup_kinds = analyze::cleanup_kinds(&mir);
217 // Allocate a `Block` for every basic block
218 let block_bcxs: IndexVec<mir::BasicBlock, BasicBlockRef> =
219 mir.basic_blocks().indices().map(|bb| {
220 if bb == mir::START_BLOCK {
221 bcx.build_sibling_block("start").llbb()
223 bcx.build_sibling_block(&format!("{:?}", bb)).llbb()
227 // Compute debuginfo scopes from MIR scopes.
228 let scopes = debuginfo::create_mir_scopes(ccx, mir, &debug_context);
230 let mut mircx = MirContext {
235 llpersonalityslot: None,
237 unreachable_block: None,
238 cleanup_kinds: cleanup_kinds,
239 landing_pads: IndexVec::from_elem(None, mir.basic_blocks()),
241 locals: IndexVec::new(),
242 debug_context: debug_context,
244 assert!(!instance.substs.needs_infer());
249 let lvalue_locals = analyze::lvalue_locals(&mircx);
251 // Allocate variable and temp allocas
253 let args = arg_local_refs(&bcx, &mircx, &mircx.scopes, &lvalue_locals);
255 let mut allocate_local = |local| {
256 let decl = &mir.local_decls[local];
257 let ty = mircx.monomorphize(&decl.ty);
259 if let Some(name) = decl.name {
261 let source_info = decl.source_info.unwrap();
262 let debug_scope = mircx.scopes[source_info.scope];
263 let dbg = debug_scope.is_valid() && bcx.sess().opts.debuginfo == FullDebugInfo;
265 if !lvalue_locals.contains(local.index()) && !dbg {
266 debug!("alloc: {:?} ({}) -> operand", local, name);
267 return LocalRef::new_operand(bcx.ccx, ty);
270 debug!("alloc: {:?} ({}) -> lvalue", local, name);
271 assert!(!ty.has_erasable_regions());
272 let lltemp = bcx.alloca_ty(ty, &name.as_str());
273 let lvalue = LvalueRef::new_sized(lltemp, LvalueTy::from_ty(ty));
275 let (scope, span) = mircx.debug_loc(source_info);
276 declare_local(&bcx, &mircx.debug_context, name, ty, scope,
277 VariableAccess::DirectVariable { alloca: lvalue.llval },
278 VariableKind::LocalVariable, span);
280 LocalRef::Lvalue(lvalue)
282 // Temporary or return pointer
283 if local == mir::RETURN_POINTER && mircx.fn_ty.ret.is_indirect() {
284 debug!("alloc: {:?} (return pointer) -> lvalue", local);
285 let llretptr = llvm::get_param(llfn, 0);
286 LocalRef::Lvalue(LvalueRef::new_sized(llretptr, LvalueTy::from_ty(ty)))
287 } else if lvalue_locals.contains(local.index()) {
288 debug!("alloc: {:?} -> lvalue", local);
289 assert!(!ty.has_erasable_regions());
290 let lltemp = bcx.alloca_ty(ty, &format!("{:?}", local));
291 LocalRef::Lvalue(LvalueRef::new_sized(lltemp, LvalueTy::from_ty(ty)))
293 // If this is an immediate local, we do not create an
294 // alloca in advance. Instead we wait until we see the
295 // definition and update the operand there.
296 debug!("alloc: {:?} -> operand", local);
297 LocalRef::new_operand(bcx.ccx, ty)
302 let retptr = allocate_local(mir::RETURN_POINTER);
304 .chain(args.into_iter())
305 .chain(mir.vars_and_temps_iter().map(allocate_local))
309 // Branch to the START block
310 let start_bcx = mircx.blocks[mir::START_BLOCK];
313 // Up until here, IR instructions for this function have explicitly not been annotated with
314 // source code location, so we don't step into call setup code. From here on, source location
315 // emitting should be enabled.
316 debuginfo::start_emitting_source_locations(&mircx.debug_context);
318 let funclets: IndexVec<mir::BasicBlock, Option<Funclet>> =
319 mircx.cleanup_kinds.iter_enumerated().map(|(bb, cleanup_kind)| {
320 if let CleanupKind::Funclet = *cleanup_kind {
321 let bcx = mircx.get_builder(bb);
323 llvm::LLVMSetPersonalityFn(mircx.llfn, mircx.ccx.eh_personality());
325 if base::wants_msvc_seh(ccx.sess()) {
326 return Some(Funclet::new(bcx.cleanup_pad(None, &[])));
333 let rpo = traversal::reverse_postorder(&mir);
334 let mut visited = BitVector::new(mir.basic_blocks().len());
336 // Translate the body of each block using reverse postorder
338 visited.insert(bb.index());
339 mircx.trans_block(bb, &funclets);
342 // Remove blocks that haven't been visited, or have no
344 for bb in mir.basic_blocks().indices() {
346 if !visited.contains(bb.index()) {
347 debug!("trans_mir: block {:?} was not visited", bb);
349 llvm::LLVMDeleteBasicBlock(mircx.blocks[bb]);
355 /// Produce, for each argument, a `ValueRef` pointing at the
356 /// argument's value. As arguments are lvalues, these are always
358 fn arg_local_refs<'a, 'tcx>(bcx: &Builder<'a, 'tcx>,
359 mircx: &MirContext<'a, 'tcx>,
360 scopes: &IndexVec<mir::VisibilityScope, debuginfo::MirDebugScope>,
361 lvalue_locals: &BitVector)
362 -> Vec<LocalRef<'tcx>> {
366 let mut llarg_idx = mircx.fn_ty.ret.is_indirect() as usize;
368 // Get the argument scope, if it exists and if we need it.
369 let arg_scope = scopes[mir::ARGUMENT_VISIBILITY_SCOPE];
370 let arg_scope = if arg_scope.is_valid() && bcx.sess().opts.debuginfo == FullDebugInfo {
371 Some(arg_scope.scope_metadata)
376 mir.args_iter().enumerate().map(|(arg_index, local)| {
377 let arg_decl = &mir.local_decls[local];
378 let arg_ty = mircx.monomorphize(&arg_decl.ty);
380 if Some(local) == mir.spread_arg {
381 // This argument (e.g. the last argument in the "rust-call" ABI)
382 // is a tuple that was spread at the ABI level and now we have
383 // to reconstruct it into a tuple local variable, from multiple
384 // individual LLVM function arguments.
386 let tupled_arg_tys = match arg_ty.sty {
387 ty::TyTuple(ref tys, _) => tys,
388 _ => bug!("spread argument isn't a tuple?!")
391 let lltemp = bcx.alloca_ty(arg_ty, &format!("arg{}", arg_index));
392 for (i, &tupled_arg_ty) in tupled_arg_tys.iter().enumerate() {
393 let dst = bcx.struct_gep(lltemp, i);
394 let arg = &mircx.fn_ty.args[idx];
396 if common::type_is_fat_ptr(bcx.ccx, tupled_arg_ty) {
397 // We pass fat pointers as two words, but inside the tuple
398 // they are the two sub-fields of a single aggregate field.
399 let meta = &mircx.fn_ty.args[idx];
401 arg.store_fn_arg(bcx, &mut llarg_idx, base::get_dataptr(bcx, dst));
402 meta.store_fn_arg(bcx, &mut llarg_idx, base::get_meta(bcx, dst));
404 arg.store_fn_arg(bcx, &mut llarg_idx, dst);
408 // Now that we have one alloca that contains the aggregate value,
409 // we can create one debuginfo entry for the argument.
410 arg_scope.map(|scope| {
411 let variable_access = VariableAccess::DirectVariable {
416 &mircx.debug_context,
417 arg_decl.name.unwrap_or(keywords::Invalid.name()),
420 VariableKind::ArgumentVariable(arg_index + 1),
425 return LocalRef::Lvalue(LvalueRef::new_sized(lltemp, LvalueTy::from_ty(arg_ty)));
428 let arg = &mircx.fn_ty.args[idx];
430 let llval = if arg.is_indirect() && bcx.sess().opts.debuginfo != FullDebugInfo {
431 // Don't copy an indirect argument to an alloca, the caller
432 // already put it in a temporary alloca and gave it up, unless
433 // we emit extra-debug-info, which requires local allocas :(.
435 if arg.pad.is_some() {
438 let llarg = llvm::get_param(bcx.llfn(), llarg_idx as c_uint);
441 } else if !lvalue_locals.contains(local.index()) &&
442 !arg.is_indirect() && arg.cast.is_none() &&
443 arg_scope.is_none() {
445 return LocalRef::new_operand(bcx.ccx, arg_ty);
448 // We don't have to cast or keep the argument in the alloca.
449 // FIXME(eddyb): We should figure out how to use llvm.dbg.value instead
450 // of putting everything in allocas just so we can use llvm.dbg.declare.
451 if arg.pad.is_some() {
454 let llarg = llvm::get_param(bcx.llfn(), llarg_idx as c_uint);
456 let val = if common::type_is_fat_ptr(bcx.ccx, arg_ty) {
457 let meta = &mircx.fn_ty.args[idx];
459 assert_eq!((meta.cast, meta.pad), (None, None));
460 let llmeta = llvm::get_param(bcx.llfn(), llarg_idx as c_uint);
462 OperandValue::Pair(llarg, llmeta)
464 OperandValue::Immediate(llarg)
466 let operand = OperandRef {
470 return LocalRef::Operand(Some(operand.unpack_if_pair(bcx)));
472 let lltemp = bcx.alloca_ty(arg_ty, &format!("arg{}", arg_index));
473 if common::type_is_fat_ptr(bcx.ccx, arg_ty) {
474 // we pass fat pointers as two words, but we want to
475 // represent them internally as a pointer to two words,
476 // so make an alloca to store them in.
477 let meta = &mircx.fn_ty.args[idx];
479 arg.store_fn_arg(bcx, &mut llarg_idx, base::get_dataptr(bcx, lltemp));
480 meta.store_fn_arg(bcx, &mut llarg_idx, base::get_meta(bcx, lltemp));
482 // otherwise, arg is passed by value, so make a
483 // temporary and store it there
484 arg.store_fn_arg(bcx, &mut llarg_idx, lltemp);
488 arg_scope.map(|scope| {
489 // Is this a regular argument?
490 if arg_index > 0 || mir.upvar_decls.is_empty() {
493 &mircx.debug_context,
494 arg_decl.name.unwrap_or(keywords::Invalid.name()),
497 VariableAccess::DirectVariable { alloca: llval },
498 VariableKind::ArgumentVariable(arg_index + 1),
504 // Or is it the closure environment?
505 let (closure_ty, env_ref) = if let ty::TyRef(_, mt) = arg_ty.sty {
510 let upvar_tys = if let ty::TyClosure(def_id, substs) = closure_ty.sty {
511 substs.upvar_tys(def_id, tcx)
513 bug!("upvar_decls with non-closure arg0 type `{}`", closure_ty);
516 // Store the pointer to closure data in an alloca for debuginfo
517 // because that's what the llvm.dbg.declare intrinsic expects.
519 // FIXME(eddyb) this shouldn't be necessary but SROA seems to
520 // mishandle DW_OP_plus not preceded by DW_OP_deref, i.e. it
521 // doesn't actually strip the offset when splitting the closure
522 // environment into its components so it ends up out of bounds.
523 let env_ptr = if !env_ref {
524 let alloc = bcx.alloca(common::val_ty(llval), "__debuginfo_env_ptr");
525 bcx.store(llval, alloc, None);
531 let layout = bcx.ccx.layout_of(closure_ty);
532 let offsets = match *layout {
533 layout::Univariant { ref variant, .. } => &variant.offsets[..],
534 _ => bug!("Closures are only supposed to be Univariant")
537 for (i, (decl, ty)) in mir.upvar_decls.iter().zip(upvar_tys).enumerate() {
538 let byte_offset_of_var_in_env = offsets[i].bytes();
541 [llvm::LLVMRustDIBuilderCreateOpDeref(),
542 llvm::LLVMRustDIBuilderCreateOpPlus(),
543 byte_offset_of_var_in_env as i64,
544 llvm::LLVMRustDIBuilderCreateOpDeref()]
547 // The environment and the capture can each be indirect.
549 // FIXME(eddyb) see above why we have to keep
550 // a pointer in an alloca for debuginfo atm.
551 let mut ops = if env_ref || true { &ops[..] } else { &ops[1..] };
553 let ty = if let (true, &ty::TyRef(_, mt)) = (decl.by_ref, &ty.sty) {
556 ops = &ops[..ops.len() - 1];
560 let variable_access = VariableAccess::IndirectVariable {
562 address_operations: &ops
566 &mircx.debug_context,
571 VariableKind::CapturedVariable,
576 LocalRef::Lvalue(LvalueRef::new_sized(llval, LvalueTy::from_ty(arg_ty)))