mod.rs 17.4 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use libc::c_uint;
use llvm::{self, ValueRef};
13
use llvm::debuginfo::DIScope;
14
use rustc::ty;
15 16
use rustc::mir::repr as mir;
use rustc::mir::tcx::LvalueTy;
17
use session::config::FullDebugInfo;
18
use base;
19
use common::{self, Block, BlockAndBuilder, CrateContext, FunctionContext};
20 21 22 23 24
use debuginfo::{self, declare_local, DebugLoc, VariableAccess, VariableKind};
use machine;
use type_of;

use syntax::codemap::DUMMY_SP;
25
use syntax::parse::token::keywords;
26

27 28 29
use std::ops::Deref;
use std::rc::Rc;

30
use basic_block::BasicBlock;
31

32 33
use rustc_data_structures::bitvec::BitVector;

34 35
pub use self::constant::trans_static_initializer;

36
use self::lvalue::{LvalueRef, get_dataptr, get_meta};
37 38
use rustc_mir::traversal;

39
use self::operand::{OperandRef, OperandValue};
40

41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
#[derive(Clone)]
pub enum CachedMir<'mir, 'tcx: 'mir> {
    Ref(&'mir mir::Mir<'tcx>),
    Owned(Rc<mir::Mir<'tcx>>)
}

impl<'mir, 'tcx: 'mir> Deref for CachedMir<'mir, 'tcx> {
    type Target = mir::Mir<'tcx>;
    fn deref(&self) -> &mir::Mir<'tcx> {
        match *self {
            CachedMir::Ref(r) => r,
            CachedMir::Owned(ref rc) => rc
        }
    }
}

57 58
/// Master context for translating MIR.
pub struct MirContext<'bcx, 'tcx:'bcx> {
59
    mir: CachedMir<'bcx, 'tcx>,
60

61 62 63
    /// Function context
    fcx: &'bcx common::FunctionContext<'bcx, 'tcx>,

64 65 66 67 68 69 70 71 72 73 74 75
    /// When unwinding is initiated, we have to store this personality
    /// value somewhere so that we can load it and re-use it in the
    /// resume instruction. The personality is (afaik) some kind of
    /// value used for C++ unwinding, which must filter by type: we
    /// don't really care about it very much. Anyway, this value
    /// contains an alloca into which the personality is stored and
    /// then later loaded when generating the DIVERGE_BLOCK.
    llpersonalityslot: Option<ValueRef>,

    /// A `Block` for each MIR `BasicBlock`
    blocks: Vec<Block<'bcx, 'tcx>>,

76 77 78 79 80 81 82
    /// The funclet status of each basic block
    cleanup_kinds: Vec<analyze::CleanupKind>,

    /// This stores the landing-pad block for a given BB, computed lazily on GNU
    /// and eagerly on MSVC.
    landing_pads: Vec<Option<Block<'bcx, 'tcx>>>,

83 84 85
    /// Cached unreachable block
    unreachable_block: Option<Block<'bcx, 'tcx>>,

86 87 88
    /// An LLVM alloca for each MIR `VarDecl`
    vars: Vec<LvalueRef<'tcx>>,

89 90 91 92 93 94 95 96 97 98 99 100
    /// The location where each MIR `TempDecl` is stored. This is
    /// usually an `LvalueRef` representing an alloca, but not always:
    /// sometimes we can skip the alloca and just store the value
    /// directly using an `OperandRef`, which makes for tighter LLVM
    /// IR. The conditions for using an `OperandRef` are as follows:
    ///
    /// - the type of the temporary must be judged "immediate" by `type_is_immediate`
    /// - the operand must never be referenced indirectly
    ///     - we should not take its address using the `&` operator
    ///     - nor should it appear in an lvalue path like `tmp.a`
    /// - the operand must be defined by an rvalue that can generate immediate
    ///   values
N
Niko Matsakis 已提交
101 102 103
    ///
    /// Avoiding allocs can also be important for certain intrinsics,
    /// notably `expect`.
104
    temps: Vec<TempRef<'tcx>>,
105 106 107 108 109

    /// The arguments to the function; as args are lvalues, these are
    /// always indirect, though we try to avoid creating an alloca
    /// when we can (and just reuse the pointer the caller provided).
    args: Vec<LvalueRef<'tcx>>,
110 111 112

    /// Debug information for MIR scopes.
    scopes: Vec<DIScope>
113 114
}

115 116 117 118 119 120
impl<'blk, 'tcx> MirContext<'blk, 'tcx> {
    pub fn debug_loc(&self, source_info: mir::SourceInfo) -> DebugLoc {
        DebugLoc::ScopeAt(self.scopes[source_info.scope.index()], source_info.span)
    }
}

121 122 123 124 125
enum TempRef<'tcx> {
    Lvalue(LvalueRef<'tcx>),
    Operand(Option<OperandRef<'tcx>>),
}

J
James Miller 已提交
126
impl<'tcx> TempRef<'tcx> {
127 128 129 130 131 132 133 134 135 136 137 138 139 140 141
    fn new_operand<'bcx>(ccx: &CrateContext<'bcx, 'tcx>,
                         ty: ty::Ty<'tcx>) -> TempRef<'tcx> {
        if common::type_is_zero_size(ccx, ty) {
            // Zero-size temporaries aren't always initialized, which
            // doesn't matter because they don't contain data, but
            // we need something in the operand.
            let val = OperandValue::Immediate(common::C_nil(ccx));
            let op = OperandRef {
                val: val,
                ty: ty
            };
            TempRef::Operand(Some(op))
        } else {
            TempRef::Operand(None)
        }
J
James Miller 已提交
142 143 144
    }
}

145 146
///////////////////////////////////////////////////////////////////////////

147
pub fn trans_mir<'blk, 'tcx: 'blk>(fcx: &'blk FunctionContext<'blk, 'tcx>) {
148
    let bcx = fcx.init(false, None).build();
149 150
    let mir = bcx.mir();

151
    let mir_blocks = mir.all_basic_blocks();
152

153 154
    // Analyze the temps to determine which must be lvalues
    // FIXME
155 156 157
    let (lvalue_temps, cleanup_kinds) = bcx.with_block(|bcx| {
        (analyze::lvalue_temps(bcx, &mir),
         analyze::cleanup_kinds(bcx, &mir))
158
    });
159

160 161 162
    // Compute debuginfo scopes from MIR scopes.
    let scopes = debuginfo::create_mir_scopes(fcx);

163
    // Allocate variable and temp allocas
164
    let args = arg_value_refs(&bcx, &mir, &scopes);
165
    let vars = mir.var_decls.iter()
166 167 168 169
                            .map(|decl| (bcx.monomorphize(&decl.ty), decl))
                            .map(|(mty, decl)| {
        let lvalue = LvalueRef::alloca(&bcx, mty, &decl.name.as_str());

170
        let scope = scopes[decl.source_info.scope.index()];
171 172 173 174
        if !scope.is_null() && bcx.sess().opts.debuginfo == FullDebugInfo {
            bcx.with_block(|bcx| {
                declare_local(bcx, decl.name, mty, scope,
                              VariableAccess::DirectVariable { alloca: lvalue.llval },
175
                              VariableKind::LocalVariable, decl.source_info.span);
176 177 178 179 180
            });
        }

        lvalue
    }).collect();
181 182 183
    let temps = mir.temp_decls.iter()
                              .map(|decl| bcx.monomorphize(&decl.ty))
                              .enumerate()
184
                              .map(|(i, mty)| if lvalue_temps.contains(i) {
185
                                  TempRef::Lvalue(LvalueRef::alloca(&bcx,
186 187 188 189 190 191
                                                                    mty,
                                                                    &format!("temp{:?}", i)))
                              } else {
                                  // If this is an immediate temp, we do not create an
                                  // alloca in advance. Instead we wait until we see the
                                  // definition and update the operand there.
192
                                  TempRef::new_operand(bcx.ccx(), mty)
193
                              })
194 195 196
                              .collect();

    // Allocate a `Block` for every basic block
197
    let block_bcxs: Vec<Block<'blk,'tcx>> =
198
        mir_blocks.iter()
199
                  .map(|&bb|{
200 201 202 203 204
                      if bb == mir::START_BLOCK {
                          fcx.new_block("start", None)
                      } else {
                          fcx.new_block(&format!("{:?}", bb), None)
                      }
205
                  })
206 207 208 209
                  .collect();

    // Branch to the START block
    let start_bcx = block_bcxs[mir::START_BLOCK.index()];
210
    bcx.br(start_bcx.llbb);
211

212 213 214 215 216
    // Up until here, IR instructions for this function have explicitly not been annotated with
    // source code location, so we don't step into call setup code. From here on, source location
    // emitting should be enabled.
    debuginfo::start_emitting_source_locations(fcx);

217
    let mut mircx = MirContext {
218
        mir: mir.clone(),
219
        fcx: fcx,
220 221
        llpersonalityslot: None,
        blocks: block_bcxs,
222
        unreachable_block: None,
223 224
        cleanup_kinds: cleanup_kinds,
        landing_pads: mir_blocks.iter().map(|_| None).collect(),
225 226 227
        vars: vars,
        temps: temps,
        args: args,
228
        scopes: scopes
229 230
    };

231 232
    let mut visited = BitVector::new(mir_blocks.len());

233 234 235 236 237 238 239 240
    let mut rpo = traversal::reverse_postorder(&mir);

    // Prepare each block for translation.
    for (bb, _) in rpo.by_ref() {
        mircx.init_cpad(bb);
    }
    rpo.reset();

241 242
    // Translate the body of each block using reverse postorder
    for (bb, _) in rpo {
243
        visited.insert(bb.index());
S
Simonas Kazlauskas 已提交
244
        mircx.trans_block(bb);
245
    }
246

247 248
    // Remove blocks that haven't been visited, or have no
    // predecessors.
249
    for &bb in &mir_blocks {
250 251 252
        let block = mircx.blocks[bb.index()];
        let block = BasicBlock(block.llbb);
        // Unreachable block
253
        if !visited.contains(bb.index()) {
254
            debug!("trans_mir: block {:?} was not visited", bb);
255
            block.delete();
256 257 258
        }
    }

259
    DebugLoc::None.apply(fcx);
260
    fcx.cleanup();
261 262 263 264 265
}

/// Produce, for each argument, a `ValueRef` pointing at the
/// argument's value. As arguments are lvalues, these are always
/// indirect.
266
fn arg_value_refs<'bcx, 'tcx>(bcx: &BlockAndBuilder<'bcx, 'tcx>,
267 268
                              mir: &mir::Mir<'tcx>,
                              scopes: &[DIScope])
269
                              -> Vec<LvalueRef<'tcx>> {
270
    let fcx = bcx.fcx();
271
    let tcx = bcx.tcx();
272 273
    let mut idx = 0;
    let mut llarg_idx = fcx.fn_ty.ret.is_indirect() as usize;
274

275 276 277 278 279 280 281
    // Get the argument scope, if it exists and if we need it.
    let arg_scope = scopes[mir::ARGUMENT_VISIBILITY_SCOPE.index()];
    let arg_scope = if !arg_scope.is_null() && bcx.sess().opts.debuginfo == FullDebugInfo {
        Some(arg_scope)
    } else {
        None
    };
282

283
    mir.arg_decls.iter().enumerate().map(|(arg_index, arg_decl)| {
284 285 286 287 288 289 290 291 292
        let arg_ty = bcx.monomorphize(&arg_decl.ty);
        if arg_decl.spread {
            // This argument (e.g. the last argument in the "rust-call" ABI)
            // is a tuple that was spread at the ABI level and now we have
            // to reconstruct it into a tuple local variable, from multiple
            // individual LLVM function arguments.

            let tupled_arg_tys = match arg_ty.sty {
                ty::TyTuple(ref tys) => tys,
293
                _ => bug!("spread argument isn't a tuple?!")
294 295
            };

296
            let lltuplety = type_of::type_of(bcx.ccx(), arg_ty);
297 298 299 300 301 302
            let lltemp = bcx.with_block(|bcx| {
                base::alloc_ty(bcx, arg_ty, &format!("arg{}", arg_index))
            });
            for (i, &tupled_arg_ty) in tupled_arg_tys.iter().enumerate() {
                let dst = bcx.struct_gep(lltemp, i);
                let arg = &fcx.fn_ty.args[idx];
303
                idx += 1;
304
                if common::type_is_fat_ptr(tcx, tupled_arg_ty) {
305 306
                        // We pass fat pointers as two words, but inside the tuple
                        // they are the two sub-fields of a single aggregate field.
307 308 309 310 311 312
                    let meta = &fcx.fn_ty.args[idx];
                    idx += 1;
                    arg.store_fn_arg(bcx, &mut llarg_idx, get_dataptr(bcx, dst));
                    meta.store_fn_arg(bcx, &mut llarg_idx, get_meta(bcx, dst));
                } else {
                    arg.store_fn_arg(bcx, &mut llarg_idx, dst);
313
                }
314 315 316 317 318

                bcx.with_block(|bcx| arg_scope.map(|scope| {
                    let byte_offset_of_var_in_tuple =
                        machine::llelement_offset(bcx.ccx(), lltuplety, i);

319
                    let ops = unsafe {
320 321 322 323 324 325 326
                        [llvm::LLVMDIBuilderCreateOpDeref(),
                         llvm::LLVMDIBuilderCreateOpPlus(),
                         byte_offset_of_var_in_tuple as i64]
                    };

                    let variable_access = VariableAccess::IndirectVariable {
                        alloca: lltemp,
327
                        address_operations: &ops
328
                    };
329
                    declare_local(bcx, keywords::Invalid.name(),
330 331 332 333
                                  tupled_arg_ty, scope, variable_access,
                                  VariableKind::ArgumentVariable(arg_index + i + 1),
                                  bcx.fcx().span.unwrap_or(DUMMY_SP));
                }));
334 335
            }
            return LvalueRef::new_sized(lltemp, LvalueTy::from_ty(arg_ty));
336 337
        }

338 339
        let arg = &fcx.fn_ty.args[idx];
        idx += 1;
340
        let llval = if arg.is_indirect() && bcx.sess().opts.debuginfo != FullDebugInfo {
341 342 343
            // Don't copy an indirect argument to an alloca, the caller
            // already put it in a temporary alloca and gave it up, unless
            // we emit extra-debug-info, which requires local allocas :(.
344
            // FIXME: lifetimes
345 346 347 348
            let llarg = llvm::get_param(fcx.llfn, llarg_idx as c_uint);
            llarg_idx += 1;
            llarg
        } else {
349
            if common::type_is_fat_ptr(tcx, arg_ty) {
S
Simonas Kazlauskas 已提交
350 351 352
                let lltemp = bcx.with_block(|bcx| {
                    base::alloc_ty(bcx, arg_ty, &format!("arg{}", arg_index))
                });
353 354 355 356 357 358 359
                // we pass fat pointers as two words, but we want to
                // represent them internally as a pointer to two words,
                // so make an alloca to store them in.
                let meta = &fcx.fn_ty.args[idx];
                idx += 1;
                arg.store_fn_arg(bcx, &mut llarg_idx, get_dataptr(bcx, lltemp));
                meta.store_fn_arg(bcx, &mut llarg_idx, get_meta(bcx, lltemp));
S
Simonas Kazlauskas 已提交
360
                lltemp
361
            } else  {
S
Simonas Kazlauskas 已提交
362 363 364 365 366
                // otherwise, arg is passed by value, so store it into a temporary.
                let llarg_ty = arg.cast.unwrap_or(arg.memory_ty(bcx.ccx()));
                let lltemp = bcx.with_block(|bcx| {
                    base::alloca(bcx, llarg_ty, &format!("arg{}", arg_index))
                });
367
                arg.store_fn_arg(bcx, &mut llarg_idx, lltemp);
S
Simonas Kazlauskas 已提交
368 369
                // And coerce the temporary into the type we expect.
                bcx.pointercast(lltemp, arg.memory_ty(bcx.ccx()).ptr_to())
370
            }
371
        };
372
        bcx.with_block(|bcx| arg_scope.map(|scope| {
373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444
            // Is this a regular argument?
            if arg_index > 0 || mir.upvar_decls.is_empty() {
                declare_local(bcx, arg_decl.debug_name, arg_ty, scope,
                              VariableAccess::DirectVariable { alloca: llval },
                              VariableKind::ArgumentVariable(arg_index + 1),
                              bcx.fcx().span.unwrap_or(DUMMY_SP));
                return;
            }

            // Or is it the closure environment?
            let (closure_ty, env_ref) = if let ty::TyRef(_, mt) = arg_ty.sty {
                (mt.ty, true)
            } else {
                (arg_ty, false)
            };
            let upvar_tys = if let ty::TyClosure(_, ref substs) = closure_ty.sty {
                &substs.upvar_tys[..]
            } else {
                bug!("upvar_decls with non-closure arg0 type `{}`", closure_ty);
            };

            // Store the pointer to closure data in an alloca for debuginfo
            // because that's what the llvm.dbg.declare intrinsic expects.

            // FIXME(eddyb) this shouldn't be necessary but SROA seems to
            // mishandle DW_OP_plus not preceded by DW_OP_deref, i.e. it
            // doesn't actually strip the offset when splitting the closure
            // environment into its components so it ends up out of bounds.
            let env_ptr = if !env_ref {
                use base::*;
                use build::*;
                use common::*;
                let alloc = alloca(bcx, val_ty(llval), "__debuginfo_env_ptr");
                Store(bcx, llval, alloc);
                alloc
            } else {
                llval
            };

            let llclosurety = type_of::type_of(bcx.ccx(), closure_ty);
            for (i, (decl, ty)) in mir.upvar_decls.iter().zip(upvar_tys).enumerate() {
                let byte_offset_of_var_in_env =
                    machine::llelement_offset(bcx.ccx(), llclosurety, i);

                let ops = unsafe {
                    [llvm::LLVMDIBuilderCreateOpDeref(),
                     llvm::LLVMDIBuilderCreateOpPlus(),
                     byte_offset_of_var_in_env as i64,
                     llvm::LLVMDIBuilderCreateOpDeref()]
                };

                // The environment and the capture can each be indirect.

                // FIXME(eddyb) see above why we have to keep
                // a pointer in an alloca for debuginfo atm.
                let mut ops = if env_ref || true { &ops[..] } else { &ops[1..] };

                let ty = if let (true, &ty::TyRef(_, mt)) = (decl.by_ref, &ty.sty) {
                    mt.ty
                } else {
                    ops = &ops[..ops.len() - 1];
                    ty
                };

                let variable_access = VariableAccess::IndirectVariable {
                    alloca: env_ptr,
                    address_operations: &ops
                };
                declare_local(bcx, decl.debug_name, ty, scope, variable_access,
                              VariableKind::CapturedVariable,
                              bcx.fcx().span.unwrap_or(DUMMY_SP));
            }
445
        }));
446 447
        LvalueRef::new_sized(llval, LvalueTy::from_ty(arg_ty))
    }).collect()
448 449
}

450
mod analyze;
451 452 453 454
mod block;
mod constant;
mod lvalue;
mod operand;
455
mod rvalue;
456
mod statement;