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, Ty, TypeFoldable};
15 use rustc::ty::layout::{self, LayoutTyper};
16 use rustc::mir::{self, Mir};
17 use rustc::mir::tcx::LvalueTy;
18 use rustc::ty::subst::Substs;
19 use rustc::infer::TransNormalize;
20 use session::config::FullDebugInfo;
23 use common::{self, CrateContext, Funclet};
24 use debuginfo::{self, declare_local, VariableAccess, VariableKind, FunctionDebugContext};
25 use monomorphize::{self, Instance};
29 use syntax_pos::{DUMMY_SP, NO_EXPANSION, BytePos, Span};
30 use syntax::symbol::keywords;
34 use rustc_data_structures::bitvec::BitVector;
35 use rustc_data_structures::indexed_vec::{IndexVec, Idx};
37 pub use self::constant::trans_static_initializer;
39 use self::analyze::CleanupKind;
40 use self::lvalue::{Alignment, LvalueRef};
41 use rustc::mir::traversal;
43 use self::operand::{OperandRef, OperandValue};
45 /// Master context for translating MIR.
46 pub struct MirContext<'a, 'tcx:'a> {
47 mir: &'a mir::Mir<'tcx>,
49 debug_context: debuginfo::FunctionDebugContext,
53 ccx: &'a CrateContext<'a, 'tcx>,
57 /// When unwinding is initiated, we have to store this personality
58 /// value somewhere so that we can load it and re-use it in the
59 /// resume instruction. The personality is (afaik) some kind of
60 /// value used for C++ unwinding, which must filter by type: we
61 /// don't really care about it very much. Anyway, this value
62 /// contains an alloca into which the personality is stored and
63 /// then later loaded when generating the DIVERGE_BLOCK.
64 llpersonalityslot: Option<ValueRef>,
66 /// A `Block` for each MIR `BasicBlock`
67 blocks: IndexVec<mir::BasicBlock, BasicBlockRef>,
69 /// The funclet status of each basic block
70 cleanup_kinds: IndexVec<mir::BasicBlock, analyze::CleanupKind>,
72 /// This stores the landing-pad block for a given BB, computed lazily on GNU
73 /// and eagerly on MSVC.
74 landing_pads: IndexVec<mir::BasicBlock, Option<BasicBlockRef>>,
76 /// Cached unreachable block
77 unreachable_block: Option<BasicBlockRef>,
79 /// The location where each MIR arg/var/tmp/ret is stored. This is
80 /// usually an `LvalueRef` representing an alloca, but not always:
81 /// sometimes we can skip the alloca and just store the value
82 /// directly using an `OperandRef`, which makes for tighter LLVM
83 /// IR. The conditions for using an `OperandRef` are as follows:
85 /// - the type of the local must be judged "immediate" by `type_is_immediate`
86 /// - the operand must never be referenced indirectly
87 /// - we should not take its address using the `&` operator
88 /// - nor should it appear in an lvalue path like `tmp.a`
89 /// - the operand must be defined by an rvalue that can generate immediate
92 /// Avoiding allocs can also be important for certain intrinsics,
94 locals: IndexVec<mir::Local, LocalRef<'tcx>>,
96 /// Debug information for MIR scopes.
97 scopes: IndexVec<mir::VisibilityScope, debuginfo::MirDebugScope>,
99 /// If this function is being monomorphized, this contains the type substitutions used.
100 param_substs: &'tcx Substs<'tcx>,
103 impl<'a, 'tcx> MirContext<'a, 'tcx> {
104 pub fn monomorphize<T>(&self, value: &T) -> T
105 where T: TransNormalize<'tcx> {
106 monomorphize::apply_param_substs(self.ccx.shared(), self.param_substs, value)
109 pub fn set_debug_loc(&mut self, bcx: &Builder, source_info: mir::SourceInfo) {
110 let (scope, span) = self.debug_loc(source_info);
111 debuginfo::set_source_location(&self.debug_context, bcx, scope, span);
114 pub fn debug_loc(&mut self, source_info: mir::SourceInfo) -> (DIScope, Span) {
115 // Bail out if debug info emission is not enabled.
116 match self.debug_context {
117 FunctionDebugContext::DebugInfoDisabled |
118 FunctionDebugContext::FunctionWithoutDebugInfo => {
119 return (self.scopes[source_info.scope].scope_metadata, source_info.span);
121 FunctionDebugContext::RegularContext(_) =>{}
124 // In order to have a good line stepping behavior in debugger, we overwrite debug
125 // locations of macro expansions with that of the outermost expansion site
126 // (unless the crate is being compiled with `-Z debug-macros`).
127 if source_info.span.ctxt == NO_EXPANSION ||
128 self.ccx.sess().opts.debugging_opts.debug_macros {
129 let scope = self.scope_metadata_for_loc(source_info.scope, source_info.span.lo);
130 (scope, source_info.span)
132 // Walk up the macro expansion chain until we reach a non-expanded span.
133 // We also stop at the function body level because no line stepping can occurr
134 // at the level above that.
135 let mut span = source_info.span;
136 while span.ctxt != NO_EXPANSION && span.ctxt != self.mir.span.ctxt {
137 if let Some(info) = span.ctxt.outer().expn_info() {
138 span = info.call_site;
143 let scope = self.scope_metadata_for_loc(source_info.scope, span.lo);
144 // Use span of the outermost expansion site, while keeping the original lexical scope.
149 // DILocations inherit source file name from the parent DIScope. Due to macro expansions
150 // it may so happen that the current span belongs to a different file than the DIScope
151 // corresponding to span's containing visibility scope. If so, we need to create a DIScope
152 // "extension" into that file.
153 fn scope_metadata_for_loc(&self, scope_id: mir::VisibilityScope, pos: BytePos)
154 -> llvm::debuginfo::DIScope {
155 let scope_metadata = self.scopes[scope_id].scope_metadata;
156 if pos < self.scopes[scope_id].file_start_pos ||
157 pos >= self.scopes[scope_id].file_end_pos {
158 let cm = self.ccx.sess().codemap();
159 debuginfo::extend_scope_to_file(self.ccx, scope_metadata, &cm.lookup_char_pos(pos).file)
166 enum LocalRef<'tcx> {
167 Lvalue(LvalueRef<'tcx>),
168 Operand(Option<OperandRef<'tcx>>),
171 impl<'tcx> LocalRef<'tcx> {
172 fn new_operand<'a>(ccx: &CrateContext<'a, 'tcx>,
173 ty: Ty<'tcx>) -> LocalRef<'tcx> {
174 if common::type_is_zero_size(ccx, ty) {
175 // Zero-size temporaries aren't always initialized, which
176 // doesn't matter because they don't contain data, but
177 // we need something in the operand.
178 LocalRef::Operand(Some(OperandRef::new_zst(ccx, ty)))
180 LocalRef::Operand(None)
185 ///////////////////////////////////////////////////////////////////////////
187 pub fn trans_mir<'a, 'tcx: 'a>(
188 ccx: &'a CrateContext<'a, 'tcx>,
191 instance: Instance<'tcx>,
192 sig: ty::FnSig<'tcx>,
194 let fn_ty = FnType::new(ccx, sig, &[]);
195 debug!("fn_ty: {:?}", fn_ty);
197 debuginfo::create_function_debug_context(ccx, instance, sig, llfn, mir);
198 let bcx = Builder::new_block(ccx, llfn, "start");
200 let cleanup_kinds = analyze::cleanup_kinds(&mir);
202 // Allocate a `Block` for every basic block, except
203 // the start block, if nothing loops back to it.
204 let reentrant_start_block = !mir.predecessors_for(mir::START_BLOCK).is_empty();
205 let block_bcxs: IndexVec<mir::BasicBlock, BasicBlockRef> =
206 mir.basic_blocks().indices().map(|bb| {
207 if bb == mir::START_BLOCK && !reentrant_start_block {
210 bcx.build_sibling_block(&format!("{:?}", bb)).llbb()
214 // Compute debuginfo scopes from MIR scopes.
215 let scopes = debuginfo::create_mir_scopes(ccx, mir, &debug_context);
217 let mut mircx = MirContext {
222 llpersonalityslot: None,
224 unreachable_block: None,
225 cleanup_kinds: cleanup_kinds,
226 landing_pads: IndexVec::from_elem(None, mir.basic_blocks()),
228 locals: IndexVec::new(),
229 debug_context: debug_context,
231 assert!(!instance.substs.needs_infer());
236 let lvalue_locals = analyze::lvalue_locals(&mircx);
238 // Allocate variable and temp allocas
240 let args = arg_local_refs(&bcx, &mircx, &mircx.scopes, &lvalue_locals);
242 let mut allocate_local = |local| {
243 let decl = &mir.local_decls[local];
244 let ty = mircx.monomorphize(&decl.ty);
246 if let Some(name) = decl.name {
248 let debug_scope = mircx.scopes[decl.source_info.scope];
249 let dbg = debug_scope.is_valid() && bcx.sess().opts.debuginfo == FullDebugInfo;
251 if !lvalue_locals.contains(local.index()) && !dbg {
252 debug!("alloc: {:?} ({}) -> operand", local, name);
253 return LocalRef::new_operand(bcx.ccx, ty);
256 debug!("alloc: {:?} ({}) -> lvalue", local, name);
257 assert!(!ty.has_erasable_regions());
258 let lvalue = LvalueRef::alloca(&bcx, ty, &name.as_str());
260 let (scope, span) = mircx.debug_loc(decl.source_info);
261 declare_local(&bcx, &mircx.debug_context, name, ty, scope,
262 VariableAccess::DirectVariable { alloca: lvalue.llval },
263 VariableKind::LocalVariable, span);
265 LocalRef::Lvalue(lvalue)
267 // Temporary or return pointer
268 if local == mir::RETURN_POINTER && mircx.fn_ty.ret.is_indirect() {
269 debug!("alloc: {:?} (return pointer) -> lvalue", local);
270 let llretptr = llvm::get_param(llfn, 0);
271 LocalRef::Lvalue(LvalueRef::new_sized(llretptr, LvalueTy::from_ty(ty),
272 Alignment::AbiAligned))
273 } else if lvalue_locals.contains(local.index()) {
274 debug!("alloc: {:?} -> lvalue", local);
275 assert!(!ty.has_erasable_regions());
276 LocalRef::Lvalue(LvalueRef::alloca(&bcx, ty, &format!("{:?}", local)))
278 // If this is an immediate local, we do not create an
279 // alloca in advance. Instead we wait until we see the
280 // definition and update the operand there.
281 debug!("alloc: {:?} -> operand", local);
282 LocalRef::new_operand(bcx.ccx, ty)
287 let retptr = allocate_local(mir::RETURN_POINTER);
289 .chain(args.into_iter())
290 .chain(mir.vars_and_temps_iter().map(allocate_local))
294 // Branch to the START block, if it's not the entry block.
295 if reentrant_start_block {
296 bcx.br(mircx.blocks[mir::START_BLOCK]);
299 // Up until here, IR instructions for this function have explicitly not been annotated with
300 // source code location, so we don't step into call setup code. From here on, source location
301 // emitting should be enabled.
302 debuginfo::start_emitting_source_locations(&mircx.debug_context);
304 let funclets: IndexVec<mir::BasicBlock, Option<Funclet>> =
305 mircx.cleanup_kinds.iter_enumerated().map(|(bb, cleanup_kind)| {
306 if let CleanupKind::Funclet = *cleanup_kind {
307 let bcx = mircx.get_builder(bb);
309 llvm::LLVMSetPersonalityFn(mircx.llfn, mircx.ccx.eh_personality());
311 if base::wants_msvc_seh(ccx.sess()) {
312 return Some(Funclet::new(bcx.cleanup_pad(None, &[])));
319 let rpo = traversal::reverse_postorder(&mir);
320 let mut visited = BitVector::new(mir.basic_blocks().len());
322 // Translate the body of each block using reverse postorder
324 visited.insert(bb.index());
325 mircx.trans_block(bb, &funclets);
328 // Remove blocks that haven't been visited, or have no
330 for bb in mir.basic_blocks().indices() {
332 if !visited.contains(bb.index()) {
333 debug!("trans_mir: block {:?} was not visited", bb);
335 llvm::LLVMDeleteBasicBlock(mircx.blocks[bb]);
341 /// Produce, for each argument, a `ValueRef` pointing at the
342 /// argument's value. As arguments are lvalues, these are always
344 fn arg_local_refs<'a, 'tcx>(bcx: &Builder<'a, 'tcx>,
345 mircx: &MirContext<'a, 'tcx>,
346 scopes: &IndexVec<mir::VisibilityScope, debuginfo::MirDebugScope>,
347 lvalue_locals: &BitVector)
348 -> Vec<LocalRef<'tcx>> {
352 let mut llarg_idx = mircx.fn_ty.ret.is_indirect() as usize;
354 // Get the argument scope, if it exists and if we need it.
355 let arg_scope = scopes[mir::ARGUMENT_VISIBILITY_SCOPE];
356 let arg_scope = if arg_scope.is_valid() && bcx.sess().opts.debuginfo == FullDebugInfo {
357 Some(arg_scope.scope_metadata)
362 mir.args_iter().enumerate().map(|(arg_index, local)| {
363 let arg_decl = &mir.local_decls[local];
364 let arg_ty = mircx.monomorphize(&arg_decl.ty);
366 if Some(local) == mir.spread_arg {
367 // This argument (e.g. the last argument in the "rust-call" ABI)
368 // is a tuple that was spread at the ABI level and now we have
369 // to reconstruct it into a tuple local variable, from multiple
370 // individual LLVM function arguments.
372 let tupled_arg_tys = match arg_ty.sty {
373 ty::TyTuple(ref tys, _) => tys,
374 _ => bug!("spread argument isn't a tuple?!")
377 let lvalue = LvalueRef::alloca(bcx, arg_ty, &format!("arg{}", arg_index));
378 for (i, &tupled_arg_ty) in tupled_arg_tys.iter().enumerate() {
379 let (dst, _) = lvalue.trans_field_ptr(bcx, i);
380 let arg = &mircx.fn_ty.args[idx];
382 if common::type_is_fat_ptr(bcx.ccx, tupled_arg_ty) {
383 // We pass fat pointers as two words, but inside the tuple
384 // they are the two sub-fields of a single aggregate field.
385 let meta = &mircx.fn_ty.args[idx];
387 arg.store_fn_arg(bcx, &mut llarg_idx, base::get_dataptr(bcx, dst));
388 meta.store_fn_arg(bcx, &mut llarg_idx, base::get_meta(bcx, dst));
390 arg.store_fn_arg(bcx, &mut llarg_idx, dst);
394 // Now that we have one alloca that contains the aggregate value,
395 // we can create one debuginfo entry for the argument.
396 arg_scope.map(|scope| {
397 let variable_access = VariableAccess::DirectVariable {
402 &mircx.debug_context,
403 arg_decl.name.unwrap_or(keywords::Invalid.name()),
406 VariableKind::ArgumentVariable(arg_index + 1),
411 return LocalRef::Lvalue(lvalue);
414 let arg = &mircx.fn_ty.args[idx];
416 let llval = if arg.is_indirect() && bcx.sess().opts.debuginfo != FullDebugInfo {
417 // Don't copy an indirect argument to an alloca, the caller
418 // already put it in a temporary alloca and gave it up, unless
419 // we emit extra-debug-info, which requires local allocas :(.
421 if arg.pad.is_some() {
424 let llarg = llvm::get_param(bcx.llfn(), llarg_idx as c_uint);
427 } else if !lvalue_locals.contains(local.index()) &&
428 !arg.is_indirect() && arg.cast.is_none() &&
429 arg_scope.is_none() {
431 return LocalRef::new_operand(bcx.ccx, arg_ty);
434 // We don't have to cast or keep the argument in the alloca.
435 // FIXME(eddyb): We should figure out how to use llvm.dbg.value instead
436 // of putting everything in allocas just so we can use llvm.dbg.declare.
437 if arg.pad.is_some() {
440 let llarg = llvm::get_param(bcx.llfn(), llarg_idx as c_uint);
442 let val = if common::type_is_fat_ptr(bcx.ccx, arg_ty) {
443 let meta = &mircx.fn_ty.args[idx];
445 assert_eq!((meta.cast, meta.pad), (None, None));
446 let llmeta = llvm::get_param(bcx.llfn(), llarg_idx as c_uint);
449 // FIXME(eddyb) As we can't perfectly represent the data and/or
450 // vtable pointer in a fat pointers in Rust's typesystem, and
451 // because we split fat pointers into two ArgType's, they're
452 // not the right type so we have to cast them for now.
453 let pointee = match arg_ty.sty {
454 ty::TyRef(_, ty::TypeAndMut{ty, ..}) |
455 ty::TyRawPtr(ty::TypeAndMut{ty, ..}) => ty,
456 ty::TyAdt(def, _) if def.is_box() => arg_ty.boxed_ty(),
459 let data_llty = type_of::in_memory_type_of(bcx.ccx, pointee);
460 let meta_llty = type_of::unsized_info_ty(bcx.ccx, pointee);
462 let llarg = bcx.pointercast(llarg, data_llty.ptr_to());
463 let llmeta = bcx.pointercast(llmeta, meta_llty);
465 OperandValue::Pair(llarg, llmeta)
467 OperandValue::Immediate(llarg)
469 let operand = OperandRef {
473 return LocalRef::Operand(Some(operand.unpack_if_pair(bcx)));
475 let lltemp = LvalueRef::alloca(bcx, arg_ty, &format!("arg{}", arg_index));
476 if common::type_is_fat_ptr(bcx.ccx, arg_ty) {
477 // we pass fat pointers as two words, but we want to
478 // represent them internally as a pointer to two words,
479 // so make an alloca to store them in.
480 let meta = &mircx.fn_ty.args[idx];
482 arg.store_fn_arg(bcx, &mut llarg_idx, base::get_dataptr(bcx, lltemp.llval));
483 meta.store_fn_arg(bcx, &mut llarg_idx, base::get_meta(bcx, lltemp.llval));
485 // otherwise, arg is passed by value, so make a
486 // temporary and store it there
487 arg.store_fn_arg(bcx, &mut llarg_idx, lltemp.llval);
491 arg_scope.map(|scope| {
492 // Is this a regular argument?
493 if arg_index > 0 || mir.upvar_decls.is_empty() {
496 &mircx.debug_context,
497 arg_decl.name.unwrap_or(keywords::Invalid.name()),
500 VariableAccess::DirectVariable { alloca: llval },
501 VariableKind::ArgumentVariable(arg_index + 1),
507 // Or is it the closure environment?
508 let (closure_ty, env_ref) = if let ty::TyRef(_, mt) = arg_ty.sty {
513 let upvar_tys = if let ty::TyClosure(def_id, substs) = closure_ty.sty {
514 substs.upvar_tys(def_id, tcx)
516 bug!("upvar_decls with non-closure arg0 type `{}`", closure_ty);
519 // Store the pointer to closure data in an alloca for debuginfo
520 // because that's what the llvm.dbg.declare intrinsic expects.
522 // FIXME(eddyb) this shouldn't be necessary but SROA seems to
523 // mishandle DW_OP_plus not preceded by DW_OP_deref, i.e. it
524 // doesn't actually strip the offset when splitting the closure
525 // environment into its components so it ends up out of bounds.
526 let env_ptr = if !env_ref {
527 let alloc = bcx.alloca(common::val_ty(llval), "__debuginfo_env_ptr");
528 bcx.store(llval, alloc, None);
534 let layout = bcx.ccx.layout_of(closure_ty);
535 let offsets = match *layout {
536 layout::Univariant { ref variant, .. } => &variant.offsets[..],
537 _ => bug!("Closures are only supposed to be Univariant")
540 for (i, (decl, ty)) in mir.upvar_decls.iter().zip(upvar_tys).enumerate() {
541 let byte_offset_of_var_in_env = offsets[i].bytes();
544 [llvm::LLVMRustDIBuilderCreateOpDeref(),
545 llvm::LLVMRustDIBuilderCreateOpPlus(),
546 byte_offset_of_var_in_env as i64,
547 llvm::LLVMRustDIBuilderCreateOpDeref()]
550 // The environment and the capture can each be indirect.
552 // FIXME(eddyb) see above why we have to keep
553 // a pointer in an alloca for debuginfo atm.
554 let mut ops = if env_ref || true { &ops[..] } else { &ops[1..] };
556 let ty = if let (true, &ty::TyRef(_, mt)) = (decl.by_ref, &ty.sty) {
559 ops = &ops[..ops.len() - 1];
563 let variable_access = VariableAccess::IndirectVariable {
565 address_operations: &ops
569 &mircx.debug_context,
574 VariableKind::CapturedVariable,
579 LocalRef::Lvalue(LvalueRef::new_sized(llval, LvalueTy::from_ty(arg_ty),
580 Alignment::AbiAligned))