1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
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
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
use libc::c_uint;
use llvm::{self, ValueRef, BasicBlockRef};
use llvm::debuginfo::DIScope;
use rustc::ty::{self, layout};
use rustc::mir::{self, Mir};
use rustc::mir::tcx::LvalueTy;
use rustc::ty::subst::Substs;
use rustc::infer::TransNormalize;
use rustc::ty::TypeFoldable;
use session::config::FullDebugInfo;
use base;
use builder::Builder;
use common::{self, CrateContext, C_null, Funclet};
use debuginfo::{self, declare_local, VariableAccess, VariableKind, FunctionDebugContext};
use monomorphize::{self, Instance};
use abi::FnType;
use type_of;
use syntax_pos::{DUMMY_SP, NO_EXPANSION, COMMAND_LINE_EXPN, BytePos, Span};
use syntax::symbol::keywords;
use std::iter;
use rustc_data_structures::bitvec::BitVector;
use rustc_data_structures::indexed_vec::{IndexVec, Idx};
pub use self::constant::trans_static_initializer;
use self::analyze::CleanupKind;
use self::lvalue::{Alignment, LvalueRef};
use rustc::mir::traversal;
use self::operand::{OperandRef, OperandValue};
pub struct MirContext<'a, 'tcx:'a> {
mir: &'a mir::Mir<'tcx>,
debug_context: debuginfo::FunctionDebugContext,
llfn: ValueRef,
ccx: &'a CrateContext<'a, 'tcx>,
fn_ty: FnType,
llpersonalityslot: Option<ValueRef>,
blocks: IndexVec<mir::BasicBlock, BasicBlockRef>,
cleanup_kinds: IndexVec<mir::BasicBlock, analyze::CleanupKind>,
landing_pads: IndexVec<mir::BasicBlock, Option<BasicBlockRef>>,
unreachable_block: Option<BasicBlockRef>,
locals: IndexVec<mir::Local, LocalRef<'tcx>>,
scopes: IndexVec<mir::VisibilityScope, debuginfo::MirDebugScope>,
param_substs: &'tcx Substs<'tcx>,
}
impl<'a, 'tcx> MirContext<'a, 'tcx> {
pub fn monomorphize<T>(&self, value: &T) -> T
where T: TransNormalize<'tcx> {
monomorphize::apply_param_substs(self.ccx.shared(), self.param_substs, value)
}
pub fn set_debug_loc(&mut self, bcx: &Builder, source_info: mir::SourceInfo) {
let (scope, span) = self.debug_loc(source_info);
debuginfo::set_source_location(&self.debug_context, bcx, scope, span);
}
pub fn debug_loc(&mut self, source_info: mir::SourceInfo) -> (DIScope, Span) {
match self.debug_context {
FunctionDebugContext::DebugInfoDisabled |
FunctionDebugContext::FunctionWithoutDebugInfo => {
return (self.scopes[source_info.scope].scope_metadata, source_info.span);
}
FunctionDebugContext::RegularContext(_) =>{}
}
if source_info.span.expn_id == NO_EXPANSION ||
source_info.span.expn_id == COMMAND_LINE_EXPN ||
self.ccx.sess().opts.debugging_opts.debug_macros {
let scope = self.scope_metadata_for_loc(source_info.scope, source_info.span.lo);
(scope, source_info.span)
} else {
let cm = self.ccx.sess().codemap();
let mut span = source_info.span;
while span.expn_id != NO_EXPANSION &&
span.expn_id != COMMAND_LINE_EXPN &&
span.expn_id != self.mir.span.expn_id {
if let Some(callsite_span) = cm.with_expn_info(span.expn_id,
|ei| ei.map(|ei| ei.call_site.clone())) {
span = callsite_span;
} else {
break;
}
}
let scope = self.scope_metadata_for_loc(source_info.scope, span.lo);
(scope, span)
}
}
fn scope_metadata_for_loc(&self, scope_id: mir::VisibilityScope, pos: BytePos)
-> llvm::debuginfo::DIScope {
let scope_metadata = self.scopes[scope_id].scope_metadata;
if pos < self.scopes[scope_id].file_start_pos ||
pos >= self.scopes[scope_id].file_end_pos {
let cm = self.ccx.sess().codemap();
debuginfo::extend_scope_to_file(self.ccx, scope_metadata, &cm.lookup_char_pos(pos).file)
} else {
scope_metadata
}
}
}
enum LocalRef<'tcx> {
Lvalue(LvalueRef<'tcx>),
Operand(Option<OperandRef<'tcx>>),
}
impl<'tcx> LocalRef<'tcx> {
fn new_operand<'a>(ccx: &CrateContext<'a, 'tcx>,
ty: ty::Ty<'tcx>) -> LocalRef<'tcx> {
if common::type_is_zero_size(ccx, ty) {
let llty = type_of::type_of(ccx, ty);
let val = if common::type_is_imm_pair(ccx, ty) {
let fields = llty.field_types();
OperandValue::Pair(C_null(fields[0]), C_null(fields[1]))
} else {
OperandValue::Immediate(C_null(llty))
};
let op = OperandRef {
val: val,
ty: ty
};
LocalRef::Operand(Some(op))
} else {
LocalRef::Operand(None)
}
}
}
pub fn trans_mir<'a, 'tcx: 'a>(
ccx: &'a CrateContext<'a, 'tcx>,
llfn: ValueRef,
mir: &'a Mir<'tcx>,
instance: Instance<'tcx>,
sig: ty::FnSig<'tcx>,
) {
let fn_ty = FnType::new(ccx, sig, &[]);
debug!("fn_ty: {:?}", fn_ty);
let debug_context =
debuginfo::create_function_debug_context(ccx, instance, sig, llfn, mir);
let bcx = Builder::new_block(ccx, llfn, "entry-block");
let cleanup_kinds = analyze::cleanup_kinds(&mir);
let block_bcxs: IndexVec<mir::BasicBlock, BasicBlockRef> =
mir.basic_blocks().indices().map(|bb| {
if bb == mir::START_BLOCK {
bcx.build_sibling_block("start").llbb()
} else {
bcx.build_sibling_block(&format!("{:?}", bb)).llbb()
}
}).collect();
let scopes = debuginfo::create_mir_scopes(ccx, mir, &debug_context);
let mut mircx = MirContext {
mir: mir,
llfn: llfn,
fn_ty: fn_ty,
ccx: ccx,
llpersonalityslot: None,
blocks: block_bcxs,
unreachable_block: None,
cleanup_kinds: cleanup_kinds,
landing_pads: IndexVec::from_elem(None, mir.basic_blocks()),
scopes: scopes,
locals: IndexVec::new(),
debug_context: debug_context,
param_substs: {
assert!(!instance.substs.needs_infer());
instance.substs
},
};
let lvalue_locals = analyze::lvalue_locals(&mircx);
mircx.locals = {
let args = arg_local_refs(&bcx, &mircx, &mircx.scopes, &lvalue_locals);
let mut allocate_local = |local| {
let decl = &mir.local_decls[local];
let ty = mircx.monomorphize(&decl.ty);
if let Some(name) = decl.name {
let source_info = decl.source_info.unwrap();
let debug_scope = mircx.scopes[source_info.scope];
let dbg = debug_scope.is_valid() && bcx.sess().opts.debuginfo == FullDebugInfo;
if !lvalue_locals.contains(local.index()) && !dbg {
debug!("alloc: {:?} ({}) -> operand", local, name);
return LocalRef::new_operand(bcx.ccx, ty);
}
debug!("alloc: {:?} ({}) -> lvalue", local, name);
assert!(!ty.has_erasable_regions());
let lvalue = LvalueRef::alloca(&bcx, ty, &name.as_str());
if dbg {
let (scope, span) = mircx.debug_loc(source_info);
declare_local(&bcx, &mircx.debug_context, name, ty, scope,
VariableAccess::DirectVariable { alloca: lvalue.llval },
VariableKind::LocalVariable, span);
}
LocalRef::Lvalue(lvalue)
} else {
if local == mir::RETURN_POINTER && mircx.fn_ty.ret.is_indirect() {
debug!("alloc: {:?} (return pointer) -> lvalue", local);
let llretptr = llvm::get_param(llfn, 0);
LocalRef::Lvalue(LvalueRef::new_sized(llretptr, LvalueTy::from_ty(ty),
Alignment::AbiAligned))
} else if lvalue_locals.contains(local.index()) {
debug!("alloc: {:?} -> lvalue", local);
assert!(!ty.has_erasable_regions());
LocalRef::Lvalue(LvalueRef::alloca(&bcx, ty, &format!("{:?}", local)))
} else {
debug!("alloc: {:?} -> operand", local);
LocalRef::new_operand(bcx.ccx, ty)
}
}
};
let retptr = allocate_local(mir::RETURN_POINTER);
iter::once(retptr)
.chain(args.into_iter())
.chain(mir.vars_and_temps_iter().map(allocate_local))
.collect()
};
let start_bcx = mircx.blocks[mir::START_BLOCK];
bcx.br(start_bcx);
debuginfo::start_emitting_source_locations(&mircx.debug_context);
let funclets: IndexVec<mir::BasicBlock, Option<Funclet>> =
mircx.cleanup_kinds.iter_enumerated().map(|(bb, cleanup_kind)| {
if let CleanupKind::Funclet = *cleanup_kind {
let bcx = mircx.get_builder(bb);
unsafe {
llvm::LLVMSetPersonalityFn(mircx.llfn, mircx.ccx.eh_personality());
}
if base::wants_msvc_seh(ccx.sess()) {
return Some(Funclet::new(bcx.cleanup_pad(None, &[])));
}
}
None
}).collect();
let rpo = traversal::reverse_postorder(&mir);
let mut visited = BitVector::new(mir.basic_blocks().len());
for (bb, _) in rpo {
visited.insert(bb.index());
mircx.trans_block(bb, &funclets);
}
for bb in mir.basic_blocks().indices() {
if !visited.contains(bb.index()) {
debug!("trans_mir: block {:?} was not visited", bb);
unsafe {
llvm::LLVMDeleteBasicBlock(mircx.blocks[bb]);
}
}
}
}
fn arg_local_refs<'a, 'tcx>(bcx: &Builder<'a, 'tcx>,
mircx: &MirContext<'a, 'tcx>,
scopes: &IndexVec<mir::VisibilityScope, debuginfo::MirDebugScope>,
lvalue_locals: &BitVector)
-> Vec<LocalRef<'tcx>> {
let mir = mircx.mir;
let tcx = bcx.tcx();
let mut idx = 0;
let mut llarg_idx = mircx.fn_ty.ret.is_indirect() as usize;
let arg_scope = scopes[mir::ARGUMENT_VISIBILITY_SCOPE];
let arg_scope = if arg_scope.is_valid() && bcx.sess().opts.debuginfo == FullDebugInfo {
Some(arg_scope.scope_metadata)
} else {
None
};
mir.args_iter().enumerate().map(|(arg_index, local)| {
let arg_decl = &mir.local_decls[local];
let arg_ty = mircx.monomorphize(&arg_decl.ty);
if Some(local) == mir.spread_arg {
let tupled_arg_tys = match arg_ty.sty {
ty::TyTuple(ref tys, _) => tys,
_ => bug!("spread argument isn't a tuple?!")
};
let lvalue = LvalueRef::alloca(bcx, arg_ty, &format!("arg{}", arg_index));
for (i, &tupled_arg_ty) in tupled_arg_tys.iter().enumerate() {
let dst = bcx.struct_gep(lvalue.llval, i);
let arg = &mircx.fn_ty.args[idx];
idx += 1;
if common::type_is_fat_ptr(bcx.ccx, tupled_arg_ty) {
let meta = &mircx.fn_ty.args[idx];
idx += 1;
arg.store_fn_arg(bcx, &mut llarg_idx, base::get_dataptr(bcx, dst));
meta.store_fn_arg(bcx, &mut llarg_idx, base::get_meta(bcx, dst));
} else {
arg.store_fn_arg(bcx, &mut llarg_idx, dst);
}
}
arg_scope.map(|scope| {
let variable_access = VariableAccess::DirectVariable {
alloca: lvalue.llval
};
declare_local(
bcx,
&mircx.debug_context,
arg_decl.name.unwrap_or(keywords::Invalid.name()),
arg_ty, scope,
variable_access,
VariableKind::ArgumentVariable(arg_index + 1),
DUMMY_SP
);
});
return LocalRef::Lvalue(lvalue);
}
let arg = &mircx.fn_ty.args[idx];
idx += 1;
let llval = if arg.is_indirect() && bcx.sess().opts.debuginfo != FullDebugInfo {
if arg.pad.is_some() {
llarg_idx += 1;
}
let llarg = llvm::get_param(bcx.llfn(), llarg_idx as c_uint);
llarg_idx += 1;
llarg
} else if !lvalue_locals.contains(local.index()) &&
!arg.is_indirect() && arg.cast.is_none() &&
arg_scope.is_none() {
if arg.is_ignore() {
return LocalRef::new_operand(bcx.ccx, arg_ty);
}
if arg.pad.is_some() {
llarg_idx += 1;
}
let llarg = llvm::get_param(bcx.llfn(), llarg_idx as c_uint);
llarg_idx += 1;
let val = if common::type_is_fat_ptr(bcx.ccx, arg_ty) {
let meta = &mircx.fn_ty.args[idx];
idx += 1;
assert_eq!((meta.cast, meta.pad), (None, None));
let llmeta = llvm::get_param(bcx.llfn(), llarg_idx as c_uint);
llarg_idx += 1;
OperandValue::Pair(llarg, llmeta)
} else {
OperandValue::Immediate(llarg)
};
let operand = OperandRef {
val: val,
ty: arg_ty
};
return LocalRef::Operand(Some(operand.unpack_if_pair(bcx)));
} else {
let lltemp = LvalueRef::alloca(bcx, arg_ty, &format!("arg{}", arg_index));
if common::type_is_fat_ptr(bcx.ccx, arg_ty) {
let meta = &mircx.fn_ty.args[idx];
idx += 1;
arg.store_fn_arg(bcx, &mut llarg_idx, base::get_dataptr(bcx, lltemp.llval));
meta.store_fn_arg(bcx, &mut llarg_idx, base::get_meta(bcx, lltemp.llval));
} else {
arg.store_fn_arg(bcx, &mut llarg_idx, lltemp.llval);
}
lltemp.llval
};
arg_scope.map(|scope| {
if arg_index > 0 || mir.upvar_decls.is_empty() {
declare_local(
bcx,
&mircx.debug_context,
arg_decl.name.unwrap_or(keywords::Invalid.name()),
arg_ty,
scope,
VariableAccess::DirectVariable { alloca: llval },
VariableKind::ArgumentVariable(arg_index + 1),
DUMMY_SP
);
return;
}
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(def_id, substs) = closure_ty.sty {
substs.upvar_tys(def_id, tcx)
} else {
bug!("upvar_decls with non-closure arg0 type `{}`", closure_ty);
};
let env_ptr = if !env_ref {
let alloc = bcx.alloca(common::val_ty(llval), "__debuginfo_env_ptr");
bcx.store(llval, alloc, None);
alloc
} else {
llval
};
let layout = bcx.ccx.layout_of(closure_ty);
let offsets = match *layout {
layout::Univariant { ref variant, .. } => &variant.offsets[..],
_ => bug!("Closures are only supposed to be Univariant")
};
for (i, (decl, ty)) in mir.upvar_decls.iter().zip(upvar_tys).enumerate() {
let byte_offset_of_var_in_env = offsets[i].bytes();
let ops = unsafe {
[llvm::LLVMRustDIBuilderCreateOpDeref(),
llvm::LLVMRustDIBuilderCreateOpPlus(),
byte_offset_of_var_in_env as i64,
llvm::LLVMRustDIBuilderCreateOpDeref()]
};
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,
&mircx.debug_context,
decl.debug_name,
ty,
scope,
variable_access,
VariableKind::CapturedVariable,
DUMMY_SP
);
}
});
LocalRef::Lvalue(LvalueRef::new_sized(llval, LvalueTy::from_ty(arg_ty),
Alignment::AbiAligned))
}).collect()
}
mod analyze;
mod block;
mod constant;
pub mod lvalue;
mod operand;
mod rvalue;
mod statement;