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::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>
107 self.ccx.tcx().trans_apply_param_substs(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.ctxt == NO_EXPANSION ||
129 self.ccx.sess().opts.debugging_opts.debug_macros {
130 let scope = self.scope_metadata_for_loc(source_info.scope, source_info.span.lo);
131 (scope, source_info.span)
133 // Walk up the macro expansion chain until we reach a non-expanded span.
134 // We also stop at the function body level because no line stepping can occurr
135 // at the level above that.
136 let mut span = source_info.span;
137 while span.ctxt != NO_EXPANSION && span.ctxt != self.mir.span.ctxt {
138 if let Some(info) = span.ctxt.outer().expn_info() {
139 span = info.call_site;
144 let scope = self.scope_metadata_for_loc(source_info.scope, span.lo);
145 // Use span of the outermost expansion site, while keeping the original lexical scope.
150 // DILocations inherit source file name from the parent DIScope. Due to macro expansions
151 // it may so happen that the current span belongs to a different file than the DIScope
152 // corresponding to span's containing visibility scope. If so, we need to create a DIScope
153 // "extension" into that file.
154 fn scope_metadata_for_loc(&self, scope_id: mir::VisibilityScope, pos: BytePos)
155 -> llvm::debuginfo::DIScope {
156 let scope_metadata = self.scopes[scope_id].scope_metadata;
157 if pos < self.scopes[scope_id].file_start_pos ||
158 pos >= self.scopes[scope_id].file_end_pos {
159 let cm = self.ccx.sess().codemap();
160 debuginfo::extend_scope_to_file(self.ccx, scope_metadata, &cm.lookup_char_pos(pos).file)
167 enum LocalRef<'tcx> {
168 Lvalue(LvalueRef<'tcx>),
169 Operand(Option<OperandRef<'tcx>>),
172 impl<'tcx> LocalRef<'tcx> {
173 fn new_operand<'a>(ccx: &CrateContext<'a, 'tcx>,
174 ty: Ty<'tcx>) -> LocalRef<'tcx> {
175 if common::type_is_zero_size(ccx, ty) {
176 // Zero-size temporaries aren't always initialized, which
177 // doesn't matter because they don't contain data, but
178 // we need something in the operand.
179 LocalRef::Operand(Some(OperandRef::new_zst(ccx, ty)))
181 LocalRef::Operand(None)
186 ///////////////////////////////////////////////////////////////////////////
188 pub fn trans_mir<'a, 'tcx: 'a>(
189 ccx: &'a CrateContext<'a, 'tcx>,
192 instance: Instance<'tcx>,
193 sig: ty::FnSig<'tcx>,
195 let fn_ty = FnType::new(ccx, sig, &[]);
196 debug!("fn_ty: {:?}", fn_ty);
198 debuginfo::create_function_debug_context(ccx, instance, sig, llfn, mir);
199 let bcx = Builder::new_block(ccx, llfn, "start");
201 let cleanup_kinds = analyze::cleanup_kinds(&mir);
203 // Allocate a `Block` for every basic block, except
204 // the start block, if nothing loops back to it.
205 let reentrant_start_block = !mir.predecessors_for(mir::START_BLOCK).is_empty();
206 let block_bcxs: IndexVec<mir::BasicBlock, BasicBlockRef> =
207 mir.basic_blocks().indices().map(|bb| {
208 if bb == mir::START_BLOCK && !reentrant_start_block {
211 bcx.build_sibling_block(&format!("{:?}", bb)).llbb()
215 // Compute debuginfo scopes from MIR scopes.
216 let scopes = debuginfo::create_mir_scopes(ccx, mir, &debug_context);
218 let mut mircx = MirContext {
223 llpersonalityslot: None,
225 unreachable_block: None,
226 cleanup_kinds: cleanup_kinds,
227 landing_pads: IndexVec::from_elem(None, mir.basic_blocks()),
229 locals: IndexVec::new(),
230 debug_context: debug_context,
232 assert!(!instance.substs.needs_infer());
237 let lvalue_locals = analyze::lvalue_locals(&mircx);
239 // Allocate variable and temp allocas
241 let args = arg_local_refs(&bcx, &mircx, &mircx.scopes, &lvalue_locals);
243 let mut allocate_local = |local| {
244 let decl = &mir.local_decls[local];
245 let ty = mircx.monomorphize(&decl.ty);
247 if let Some(name) = decl.name {
249 let debug_scope = mircx.scopes[decl.source_info.scope];
250 let dbg = debug_scope.is_valid() && bcx.sess().opts.debuginfo == FullDebugInfo;
252 if !lvalue_locals.contains(local.index()) && !dbg {
253 debug!("alloc: {:?} ({}) -> operand", local, name);
254 return LocalRef::new_operand(bcx.ccx, ty);
257 debug!("alloc: {:?} ({}) -> lvalue", local, name);
258 assert!(!ty.has_erasable_regions());
259 let lvalue = LvalueRef::alloca(&bcx, ty, &name.as_str());
261 let (scope, span) = mircx.debug_loc(decl.source_info);
262 declare_local(&bcx, &mircx.debug_context, name, ty, scope,
263 VariableAccess::DirectVariable { alloca: lvalue.llval },
264 VariableKind::LocalVariable, span);
266 LocalRef::Lvalue(lvalue)
268 // Temporary or return pointer
269 if local == mir::RETURN_POINTER && mircx.fn_ty.ret.is_indirect() {
270 debug!("alloc: {:?} (return pointer) -> lvalue", local);
271 let llretptr = llvm::get_param(llfn, 0);
272 LocalRef::Lvalue(LvalueRef::new_sized(llretptr, LvalueTy::from_ty(ty),
273 Alignment::AbiAligned))
274 } else if lvalue_locals.contains(local.index()) {
275 debug!("alloc: {:?} -> lvalue", local);
276 assert!(!ty.has_erasable_regions());
277 LocalRef::Lvalue(LvalueRef::alloca(&bcx, ty, &format!("{:?}", local)))
279 // If this is an immediate local, we do not create an
280 // alloca in advance. Instead we wait until we see the
281 // definition and update the operand there.
282 debug!("alloc: {:?} -> operand", local);
283 LocalRef::new_operand(bcx.ccx, ty)
288 let retptr = allocate_local(mir::RETURN_POINTER);
290 .chain(args.into_iter())
291 .chain(mir.vars_and_temps_iter().map(allocate_local))
295 // Branch to the START block, if it's not the entry block.
296 if reentrant_start_block {
297 bcx.br(mircx.blocks[mir::START_BLOCK]);
300 // Up until here, IR instructions for this function have explicitly not been annotated with
301 // source code location, so we don't step into call setup code. From here on, source location
302 // emitting should be enabled.
303 debuginfo::start_emitting_source_locations(&mircx.debug_context);
305 let funclets: IndexVec<mir::BasicBlock, Option<Funclet>> =
306 mircx.cleanup_kinds.iter_enumerated().map(|(bb, cleanup_kind)| {
307 if let CleanupKind::Funclet = *cleanup_kind {
308 let bcx = mircx.get_builder(bb);
310 llvm::LLVMSetPersonalityFn(mircx.llfn, mircx.ccx.eh_personality());
312 if base::wants_msvc_seh(ccx.sess()) {
313 return Some(Funclet::new(bcx.cleanup_pad(None, &[])));
320 let rpo = traversal::reverse_postorder(&mir);
321 let mut visited = BitVector::new(mir.basic_blocks().len());
323 // Translate the body of each block using reverse postorder
325 visited.insert(bb.index());
326 mircx.trans_block(bb, &funclets);
329 // Remove blocks that haven't been visited, or have no
331 for bb in mir.basic_blocks().indices() {
333 if !visited.contains(bb.index()) {
334 debug!("trans_mir: block {:?} was not visited", bb);
336 llvm::LLVMDeleteBasicBlock(mircx.blocks[bb]);
342 /// Produce, for each argument, a `ValueRef` pointing at the
343 /// argument's value. As arguments are lvalues, these are always
345 fn arg_local_refs<'a, 'tcx>(bcx: &Builder<'a, 'tcx>,
346 mircx: &MirContext<'a, 'tcx>,
347 scopes: &IndexVec<mir::VisibilityScope, debuginfo::MirDebugScope>,
348 lvalue_locals: &BitVector)
349 -> Vec<LocalRef<'tcx>> {
353 let mut llarg_idx = mircx.fn_ty.ret.is_indirect() as usize;
355 // Get the argument scope, if it exists and if we need it.
356 let arg_scope = scopes[mir::ARGUMENT_VISIBILITY_SCOPE];
357 let arg_scope = if arg_scope.is_valid() && bcx.sess().opts.debuginfo == FullDebugInfo {
358 Some(arg_scope.scope_metadata)
363 mir.args_iter().enumerate().map(|(arg_index, local)| {
364 let arg_decl = &mir.local_decls[local];
365 let arg_ty = mircx.monomorphize(&arg_decl.ty);
367 if Some(local) == mir.spread_arg {
368 // This argument (e.g. the last argument in the "rust-call" ABI)
369 // is a tuple that was spread at the ABI level and now we have
370 // to reconstruct it into a tuple local variable, from multiple
371 // individual LLVM function arguments.
373 let tupled_arg_tys = match arg_ty.sty {
374 ty::TyTuple(ref tys, _) => tys,
375 _ => bug!("spread argument isn't a tuple?!")
378 let lvalue = LvalueRef::alloca(bcx, arg_ty, &format!("arg{}", arg_index));
379 for (i, &tupled_arg_ty) in tupled_arg_tys.iter().enumerate() {
380 let (dst, _) = lvalue.trans_field_ptr(bcx, i);
381 let arg = &mircx.fn_ty.args[idx];
383 if common::type_is_fat_ptr(bcx.ccx, tupled_arg_ty) {
384 // We pass fat pointers as two words, but inside the tuple
385 // they are the two sub-fields of a single aggregate field.
386 let meta = &mircx.fn_ty.args[idx];
388 arg.store_fn_arg(bcx, &mut llarg_idx, base::get_dataptr(bcx, dst));
389 meta.store_fn_arg(bcx, &mut llarg_idx, base::get_meta(bcx, dst));
391 arg.store_fn_arg(bcx, &mut llarg_idx, dst);
395 // Now that we have one alloca that contains the aggregate value,
396 // we can create one debuginfo entry for the argument.
397 arg_scope.map(|scope| {
398 let variable_access = VariableAccess::DirectVariable {
403 &mircx.debug_context,
404 arg_decl.name.unwrap_or(keywords::Invalid.name()),
407 VariableKind::ArgumentVariable(arg_index + 1),
412 return LocalRef::Lvalue(lvalue);
415 let arg = &mircx.fn_ty.args[idx];
417 let llval = if arg.is_indirect() && bcx.sess().opts.debuginfo != FullDebugInfo {
418 // Don't copy an indirect argument to an alloca, the caller
419 // already put it in a temporary alloca and gave it up, unless
420 // we emit extra-debug-info, which requires local allocas :(.
422 if arg.pad.is_some() {
425 let llarg = llvm::get_param(bcx.llfn(), llarg_idx as c_uint);
428 } else if !lvalue_locals.contains(local.index()) &&
429 !arg.is_indirect() && arg.cast.is_none() &&
430 arg_scope.is_none() {
432 return LocalRef::new_operand(bcx.ccx, arg_ty);
435 // We don't have to cast or keep the argument in the alloca.
436 // FIXME(eddyb): We should figure out how to use llvm.dbg.value instead
437 // of putting everything in allocas just so we can use llvm.dbg.declare.
438 if arg.pad.is_some() {
441 let llarg = llvm::get_param(bcx.llfn(), llarg_idx as c_uint);
443 let val = if common::type_is_fat_ptr(bcx.ccx, arg_ty) {
444 let meta = &mircx.fn_ty.args[idx];
446 assert_eq!((meta.cast, meta.pad), (None, None));
447 let llmeta = llvm::get_param(bcx.llfn(), llarg_idx as c_uint);
450 // FIXME(eddyb) As we can't perfectly represent the data and/or
451 // vtable pointer in a fat pointers in Rust's typesystem, and
452 // because we split fat pointers into two ArgType's, they're
453 // not the right type so we have to cast them for now.
454 let pointee = match arg_ty.sty {
455 ty::TyRef(_, ty::TypeAndMut{ty, ..}) |
456 ty::TyRawPtr(ty::TypeAndMut{ty, ..}) => ty,
457 ty::TyAdt(def, _) if def.is_box() => arg_ty.boxed_ty(),
460 let data_llty = type_of::in_memory_type_of(bcx.ccx, pointee);
461 let meta_llty = type_of::unsized_info_ty(bcx.ccx, pointee);
463 let llarg = bcx.pointercast(llarg, data_llty.ptr_to());
464 let llmeta = bcx.pointercast(llmeta, meta_llty);
466 OperandValue::Pair(llarg, llmeta)
468 OperandValue::Immediate(llarg)
470 let operand = OperandRef {
474 return LocalRef::Operand(Some(operand.unpack_if_pair(bcx)));
476 let lltemp = LvalueRef::alloca(bcx, arg_ty, &format!("arg{}", arg_index));
477 if common::type_is_fat_ptr(bcx.ccx, arg_ty) {
478 // we pass fat pointers as two words, but we want to
479 // represent them internally as a pointer to two words,
480 // so make an alloca to store them in.
481 let meta = &mircx.fn_ty.args[idx];
483 arg.store_fn_arg(bcx, &mut llarg_idx, base::get_dataptr(bcx, lltemp.llval));
484 meta.store_fn_arg(bcx, &mut llarg_idx, base::get_meta(bcx, lltemp.llval));
486 // otherwise, arg is passed by value, so make a
487 // temporary and store it there
488 arg.store_fn_arg(bcx, &mut llarg_idx, lltemp.llval);
492 arg_scope.map(|scope| {
493 // Is this a regular argument?
494 if arg_index > 0 || mir.upvar_decls.is_empty() {
497 &mircx.debug_context,
498 arg_decl.name.unwrap_or(keywords::Invalid.name()),
501 VariableAccess::DirectVariable { alloca: llval },
502 VariableKind::ArgumentVariable(arg_index + 1),
508 // Or is it the closure environment?
509 let (closure_ty, env_ref) = if let ty::TyRef(_, mt) = arg_ty.sty {
514 let upvar_tys = if let ty::TyClosure(def_id, substs) = closure_ty.sty {
515 substs.upvar_tys(def_id, tcx)
517 bug!("upvar_decls with non-closure arg0 type `{}`", closure_ty);
520 // Store the pointer to closure data in an alloca for debuginfo
521 // because that's what the llvm.dbg.declare intrinsic expects.
523 // FIXME(eddyb) this shouldn't be necessary but SROA seems to
524 // mishandle DW_OP_plus not preceded by DW_OP_deref, i.e. it
525 // doesn't actually strip the offset when splitting the closure
526 // environment into its components so it ends up out of bounds.
527 let env_ptr = if !env_ref {
528 let alloc = bcx.alloca(common::val_ty(llval), "__debuginfo_env_ptr", None);
529 bcx.store(llval, alloc, None);
535 let layout = bcx.ccx.layout_of(closure_ty);
536 let offsets = match *layout {
537 layout::Univariant { ref variant, .. } => &variant.offsets[..],
538 _ => bug!("Closures are only supposed to be Univariant")
541 for (i, (decl, ty)) in mir.upvar_decls.iter().zip(upvar_tys).enumerate() {
542 let byte_offset_of_var_in_env = offsets[i].bytes();
545 [llvm::LLVMRustDIBuilderCreateOpDeref(),
546 llvm::LLVMRustDIBuilderCreateOpPlus(),
547 byte_offset_of_var_in_env as i64,
548 llvm::LLVMRustDIBuilderCreateOpDeref()]
551 // The environment and the capture can each be indirect.
553 // FIXME(eddyb) see above why we have to keep
554 // a pointer in an alloca for debuginfo atm.
555 let mut ops = if env_ref || true { &ops[..] } else { &ops[1..] };
557 let ty = if let (true, &ty::TyRef(_, mt)) = (decl.by_ref, &ty.sty) {
560 ops = &ops[..ops.len() - 1];
564 let variable_access = VariableAccess::IndirectVariable {
566 address_operations: &ops
570 &mircx.debug_context,
575 VariableKind::CapturedVariable,
580 LocalRef::Lvalue(LvalueRef::new_sized(llval, LvalueTy::from_ty(arg_ty),
581 Alignment::AbiAligned))