/
debuginfo.rs
2815 lines (2443 loc) · 106 KB
/
debuginfo.rs
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
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2012-2013 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.
/*!
# Debug Info Module
This module serves the purpose of generating debug symbols. We use LLVM's
[source level debugging](http://llvm.org/docs/SourceLevelDebugging.html) features for generating
the debug information. The general principle is this:
Given the right metadata in the LLVM IR, the LLVM code generator is able to create DWARF debug
symbols for the given code. The [metadata](http://llvm.org/docs/LangRef.html#metadata-type) is
structured much like DWARF *debugging information entries* (DIE), representing type information
such as datatype layout, function signatures, block layout, variable location and scope information,
etc. It is the purpose of this module to generate correct metadata and insert it into the LLVM IR.
As the exact format of metadata trees may change between different LLVM versions, we now use LLVM
[DIBuilder](http://llvm.org/docs/doxygen/html/classllvm_1_1DIBuilder.html) to create metadata
where possible. This will hopefully ease the adaption of this module to future LLVM versions.
The public API of the module is a set of functions that will insert the correct metadata into the
LLVM IR when called with the right parameters. The module is thus driven from an outside client with
functions like `debuginfo::create_local_var_metadata(bcx: block, local: &ast::local)`.
Internally the module will try to reuse already created metadata by utilizing a cache. The way to
get a shared metadata node when needed is thus to just call the corresponding function in this
module:
let file_metadata = file_metadata(crate_context, path);
The function will take care of probing the cache for an existing node for that exact file path.
All private state used by the module is stored within either the CrateDebugContext struct (owned by
the CrateContext) or the FunctionDebugContext (owned by the FunctionContext).
This file consists of three conceptual sections:
1. The public interface of the module
2. Module-internal metadata creation functions
3. Minor utility functions
## Recursive Types
Some kinds of types, such as structs and enums can be recursive. That means that the type definition
of some type X refers to some other type which in turn (transitively) refers to X. This introduces
cycles into the type referral graph. A naive algorithm doing an on-demand, depth-first traversal of
this graph when describing types, can get trapped in an endless loop when it reaches such a cycle.
For example, the following simple type for a singly-linked list...
```
struct List {
value: int,
tail: Option<@List>,
}
```
will generate the following callstack with a naive DFS algorithm:
```
describe(t = List)
describe(t = int)
describe(t = Option<@List>)
describe(t = @List)
describe(t = List) // at the beginning again...
...
```
To break cycles like these, we use "forward declarations". That is, when the algorithm encounters a
possibly recursive type (any struct or enum), it immediately creates a type description node and
inserts it into the cache *before* describing the members of the type. This type description is just
a stub (as type members are not described and added to it yet) but it allows the algorithm to
already refer to the type. After the stub is inserted into the cache, the algorithm continues as
before. If it now encounters a recursive reference, it will hit the cache and does not try to
describe the type anew.
This behaviour is encapsulated in the 'RecursiveTypeDescription' enum, which represents a kind of
continuation, storing all state needed to continue traversal at the type members after the type has
been registered with the cache. (This implementation approach might be a tad over-engineered and
may change in the future)
## Source Locations and Line Information
In addition to data type descriptions the debugging information must also allow to map machine code
locations back to source code locations in order to be useful. This functionality is also handled in
this module. The following functions allow to control source mappings:
+ set_source_location()
+ clear_source_location()
+ start_emitting_source_locations()
`set_source_location()` allows to set the current source location. All IR instructions created after
a call to this function will be linked to the given source location, until another location is
specified with `set_source_location()` or the source location is cleared with
`clear_source_location()`. In the later case, subsequent IR instruction will not be linked to any
source location. As you can see, this is a stateful API (mimicking the one in LLVM), so be careful
with source locations set by previous calls. It's probably best to not rely on any specific state
being present at a given point in code.
One topic that deserves some extra attention is *function prologues*. At the beginning of a
function's machine code there are typically a few instructions for loading argument values into
allocas and checking if there's enough stack space for the function to execute. This *prologue* is
not visible in the source code and LLVM puts a special PROLOGUE END marker into the line table at
the first non-prologue instruction of the function. In order to find out where the prologue ends,
LLVM looks for the first instruction in the function body that is linked to a source location. So,
when generating prologue instructions we have to make sure that we don't emit source location
information until the 'real' function body begins. For this reason, source location emission is
disabled by default for any new function being translated and is only activated after a call to the
third function from the list above, `start_emitting_source_locations()`. This function should be
called right before regularly starting to translate the top-level block of the given function.
There is one exception to the above rule: `llvm.dbg.declare` instruction must be linked to the
source location of the variable being declared. For function parameters these `llvm.dbg.declare`
instructions typically occur in the middle of the prologue, however, they are ignored by LLVM's
prologue detection. The `create_argument_metadata()` and related functions take care of linking the
`llvm.dbg.declare` instructions to the correct source locations even while source location emission
is still disabled, so there is no need to do anything special with source location handling here.
*/
use driver::session;
use driver::session::{FullDebugInfo, LimitedDebugInfo, NoDebugInfo};
use lib::llvm::llvm;
use lib::llvm::{ModuleRef, ContextRef, ValueRef};
use lib::llvm::debuginfo::*;
use middle::trans::adt;
use middle::trans::common::*;
use middle::trans::datum::{Datum, Lvalue};
use middle::trans::machine;
use middle::trans::type_of;
use middle::trans::type_::Type;
use middle::trans;
use middle::ty;
use middle::pat_util;
use util::ppaux;
use std::c_str::{CString, ToCStr};
use std::cell::{Cell, RefCell};
use collections::HashMap;
use collections::HashSet;
use std::libc::{c_uint, c_ulonglong, c_longlong};
use std::ptr;
use std::sync::atomics;
use std::vec;
use syntax::codemap::{Span, Pos};
use syntax::{abi, ast, codemap, ast_util, ast_map, opt_vec};
use syntax::parse::token;
use syntax::parse::token::special_idents;
static DW_LANG_RUST: c_uint = 0x9000;
static DW_TAG_auto_variable: c_uint = 0x100;
static DW_TAG_arg_variable: c_uint = 0x101;
static DW_ATE_boolean: c_uint = 0x02;
static DW_ATE_float: c_uint = 0x04;
static DW_ATE_signed: c_uint = 0x05;
// static DW_ATE_signed_char: c_uint = 0x06;
static DW_ATE_unsigned: c_uint = 0x07;
static DW_ATE_unsigned_char: c_uint = 0x08;
//=-------------------------------------------------------------------------------------------------
// Public Interface of debuginfo module
//=-------------------------------------------------------------------------------------------------
/// A context object for maintaining all state needed by the debuginfo module.
pub struct CrateDebugContext {
priv llcontext: ContextRef,
priv builder: DIBuilderRef,
priv current_debug_location: Cell<DebugLocation>,
priv created_files: RefCell<HashMap<~str, DIFile>>,
priv created_types: RefCell<HashMap<uint, DIType>>,
priv namespace_map: RefCell<HashMap<~[ast::Name], @NamespaceTreeNode>>,
// This collection is used to assert that composite types (structs, enums, ...) have their
// members only set once:
priv composite_types_completed: RefCell<HashSet<DIType>>,
}
impl CrateDebugContext {
pub fn new(llmod: ModuleRef) -> CrateDebugContext {
debug!("CrateDebugContext::new");
let builder = unsafe { llvm::LLVMDIBuilderCreate(llmod) };
// DIBuilder inherits context from the module, so we'd better use the same one
let llcontext = unsafe { llvm::LLVMGetModuleContext(llmod) };
return CrateDebugContext {
llcontext: llcontext,
builder: builder,
current_debug_location: Cell::new(UnknownLocation),
created_files: RefCell::new(HashMap::new()),
created_types: RefCell::new(HashMap::new()),
namespace_map: RefCell::new(HashMap::new()),
composite_types_completed: RefCell::new(HashSet::new()),
};
}
}
pub enum FunctionDebugContext {
priv FunctionDebugContext(~FunctionDebugContextData),
priv DebugInfoDisabled,
priv FunctionWithoutDebugInfo,
}
impl FunctionDebugContext {
fn get_ref<'a>(&'a self, cx: &CrateContext, span: Span) -> &'a FunctionDebugContextData {
match *self {
FunctionDebugContext(~ref data) => data,
DebugInfoDisabled => {
cx.sess.span_bug(span, FunctionDebugContext::debuginfo_disabled_message());
}
FunctionWithoutDebugInfo => {
cx.sess.span_bug(span, FunctionDebugContext::should_be_ignored_message());
}
}
}
fn debuginfo_disabled_message() -> &'static str {
"debuginfo: Error trying to access FunctionDebugContext although debug info is disabled!"
}
fn should_be_ignored_message() -> &'static str {
"debuginfo: Error trying to access FunctionDebugContext for function that should be \
ignored by debug info!"
}
}
struct FunctionDebugContextData {
scope_map: RefCell<HashMap<ast::NodeId, DIScope>>,
fn_metadata: DISubprogram,
argument_counter: Cell<uint>,
source_locations_enabled: Cell<bool>,
}
enum VariableAccess<'a> {
// The llptr given is an alloca containing the variable's value
DirectVariable { alloca: ValueRef },
// The llptr given is an alloca containing the start of some pointer chain leading to the
// variable's content.
IndirectVariable { alloca: ValueRef, address_operations: &'a [ValueRef] }
}
enum VariableKind {
ArgumentVariable(uint /*index*/),
LocalVariable,
CapturedVariable,
}
/// Create any deferred debug metadata nodes
pub fn finalize(cx: @CrateContext) {
if cx.dbg_cx.is_none() {
return;
}
debug!("finalize");
compile_unit_metadata(cx);
unsafe {
llvm::LLVMDIBuilderFinalize(DIB(cx));
llvm::LLVMDIBuilderDispose(DIB(cx));
// Debuginfo generation in LLVM by default uses a higher
// version of dwarf than OS X currently understands. We can
// instruct LLVM to emit an older version of dwarf, however,
// for OS X to understand. For more info see #11352
// This can be overridden using --llvm-opts -dwarf-version,N.
if cx.sess.targ_cfg.os == abi::OsMacos {
"Dwarf Version".with_c_str(
|s| llvm::LLVMRustAddModuleFlag(cx.llmod, s, 2));
}
// Prevent bitcode readers from deleting the debug info.
"Debug Info Version".with_c_str(
|s| llvm::LLVMRustAddModuleFlag(cx.llmod, s,
llvm::LLVMRustDebugMetadataVersion));
};
}
/// Creates debug information for the given local variable.
///
/// Adds the created metadata nodes directly to the crate's IR.
pub fn create_local_var_metadata(bcx: &Block, local: &ast::Local) {
if fn_should_be_ignored(bcx.fcx) {
return;
}
let cx = bcx.ccx();
let def_map = cx.tcx.def_map;
pat_util::pat_bindings(def_map, local.pat, |_, node_id, span, path_ref| {
let var_ident = ast_util::path_to_ident(path_ref);
let datum = {
let lllocals = bcx.fcx.lllocals.borrow();
match lllocals.get().find_copy(&node_id) {
Some(datum) => datum,
None => {
bcx.tcx().sess.span_bug(span,
format!("no entry in lllocals table for {:?}",
node_id));
}
}
};
let scope_metadata = scope_metadata(bcx.fcx, node_id, span);
declare_local(bcx,
var_ident,
datum.ty,
scope_metadata,
DirectVariable { alloca: datum.val },
LocalVariable,
span);
})
}
/// Creates debug information for a variable captured in a closure.
///
/// Adds the created metadata nodes directly to the crate's IR.
pub fn create_captured_var_metadata(bcx: &Block,
node_id: ast::NodeId,
env_data_type: ty::t,
env_pointer: ValueRef,
env_index: uint,
closure_sigil: ast::Sigil,
span: Span) {
if fn_should_be_ignored(bcx.fcx) {
return;
}
let cx = bcx.ccx();
let ast_item = cx.tcx.map.find(node_id);
let variable_ident = match ast_item {
None => {
cx.sess.span_bug(span, "debuginfo::create_captured_var_metadata() - NodeId not found");
}
Some(ast_map::NodeLocal(pat)) | Some(ast_map::NodeArg(pat)) => {
match pat.node {
ast::PatIdent(_, ref path, _) => {
ast_util::path_to_ident(path)
}
_ => {
cx.sess
.span_bug(span,
format!(
"debuginfo::create_captured_var_metadata() - \
Captured var-id refers to unexpected \
ast_map variant: {:?}",
ast_item));
}
}
}
_ => {
cx.sess.span_bug(span, format!("debuginfo::create_captured_var_metadata() - \
Captured var-id refers to unexpected ast_map variant: {:?}", ast_item));
}
};
let variable_type = node_id_type(bcx, node_id);
let scope_metadata = bcx.fcx.debug_context.get_ref(cx, span).fn_metadata;
let llvm_env_data_type = type_of::type_of(cx, env_data_type);
let byte_offset_of_var_in_env = machine::llelement_offset(cx, llvm_env_data_type, env_index);
let address_operations = unsafe {
[llvm::LLVMDIBuilderCreateOpDeref(Type::i64().to_ref()),
llvm::LLVMDIBuilderCreateOpPlus(Type::i64().to_ref()),
C_i64(byte_offset_of_var_in_env as i64),
llvm::LLVMDIBuilderCreateOpDeref(Type::i64().to_ref())]
};
let address_op_count = match closure_sigil {
ast::BorrowedSigil => {
address_operations.len()
}
ast::ManagedSigil | ast::OwnedSigil => {
address_operations.len() - 1
}
};
let variable_access = IndirectVariable {
alloca: env_pointer,
address_operations: address_operations.slice_to(address_op_count)
};
declare_local(bcx,
variable_ident,
variable_type,
scope_metadata,
variable_access,
CapturedVariable,
span);
}
/// Creates debug information for a local variable introduced in the head of a match-statement arm.
///
/// Adds the created metadata nodes directly to the crate's IR.
pub fn create_match_binding_metadata(bcx: &Block,
variable_ident: ast::Ident,
node_id: ast::NodeId,
span: Span,
datum: Datum<Lvalue>) {
if fn_should_be_ignored(bcx.fcx) {
return;
}
let scope_metadata = scope_metadata(bcx.fcx, node_id, span);
declare_local(bcx,
variable_ident,
datum.ty,
scope_metadata,
DirectVariable { alloca: datum.val },
LocalVariable,
span);
}
/// Creates debug information for the given function argument.
///
/// Adds the created metadata nodes directly to the crate's IR.
pub fn create_argument_metadata(bcx: &Block, arg: &ast::Arg) {
if fn_should_be_ignored(bcx.fcx) {
return;
}
let fcx = bcx.fcx;
let cx = fcx.ccx;
let def_map = cx.tcx.def_map;
let scope_metadata = bcx.fcx.debug_context.get_ref(cx, arg.pat.span).fn_metadata;
pat_util::pat_bindings(def_map, arg.pat, |_, node_id, span, path_ref| {
let llarg = {
let llargs = bcx.fcx.llargs.borrow();
match llargs.get().find_copy(&node_id) {
Some(v) => v,
None => {
bcx.tcx().sess.span_bug(span,
format!("no entry in llargs table for {:?}",
node_id));
}
}
};
if unsafe { llvm::LLVMIsAAllocaInst(llarg.val) } == ptr::null() {
cx.sess.span_bug(span, "debuginfo::create_argument_metadata() - \
Referenced variable location is not an alloca!");
}
let argument_ident = ast_util::path_to_ident(path_ref);
let argument_index = {
let counter = &fcx.debug_context.get_ref(cx, span).argument_counter;
let argument_index = counter.get();
counter.set(argument_index + 1);
argument_index
};
declare_local(bcx,
argument_ident,
llarg.ty,
scope_metadata,
DirectVariable { alloca: llarg.val },
ArgumentVariable(argument_index),
span);
})
}
/// Sets the current debug location at the beginning of the span.
///
/// Maps to a call to llvm::LLVMSetCurrentDebugLocation(...). The node_id parameter is used to
/// reliably find the correct visibility scope for the code position.
pub fn set_source_location(fcx: &FunctionContext,
node_id: ast::NodeId,
span: Span) {
if fn_should_be_ignored(fcx) {
return;
}
let cx = fcx.ccx;
debug!("set_source_location: {}", cx.sess.codemap.span_to_str(span));
if fcx.debug_context.get_ref(cx, span).source_locations_enabled.get() {
let loc = span_start(cx, span);
let scope = scope_metadata(fcx, node_id, span);
set_debug_location(cx, DebugLocation::new(scope, loc.line, loc.col.to_uint()));
} else {
set_debug_location(cx, UnknownLocation);
}
}
/// Clears the current debug location.
///
/// Instructions generated hereafter won't be assigned a source location.
pub fn clear_source_location(fcx: &FunctionContext) {
if fn_should_be_ignored(fcx) {
return;
}
set_debug_location(fcx.ccx, UnknownLocation);
}
/// Enables emitting source locations for the given functions.
///
/// Since we don't want source locations to be emitted for the function prelude, they are disabled
/// when beginning to translate a new function. This functions switches source location emitting on
/// and must therefore be called before the first real statement/expression of the function is
/// translated.
pub fn start_emitting_source_locations(fcx: &FunctionContext) {
match fcx.debug_context {
FunctionDebugContext(~ref data) => {
data.source_locations_enabled.set(true)
},
_ => { /* safe to ignore */ }
}
}
/// Creates the function-specific debug context.
///
/// Returns the FunctionDebugContext for the function which holds state needed for debug info
/// creation. The function may also return another variant of the FunctionDebugContext enum which
/// indicates why no debuginfo should be created for the function.
pub fn create_function_debug_context(cx: &CrateContext,
fn_ast_id: ast::NodeId,
param_substs: Option<@param_substs>,
llfn: ValueRef) -> FunctionDebugContext {
if cx.sess.opts.debuginfo == NoDebugInfo {
return DebugInfoDisabled;
}
if fn_ast_id == -1 {
return FunctionWithoutDebugInfo;
}
let empty_generics = ast::Generics { lifetimes: opt_vec::Empty, ty_params: opt_vec::Empty };
let fnitem = cx.tcx.map.get(fn_ast_id);
let (ident, fn_decl, generics, top_level_block, span, has_path) = match fnitem {
ast_map::NodeItem(ref item) => {
match item.node {
ast::ItemFn(fn_decl, _, _, ref generics, top_level_block) => {
(item.ident, fn_decl, generics, top_level_block, item.span, true)
}
_ => {
cx.sess.span_bug(item.span,
"create_function_debug_context: item bound to non-function");
}
}
}
ast_map::NodeMethod(method) => {
(method.ident,
method.decl,
&method.generics,
method.body,
method.span,
true)
}
ast_map::NodeExpr(ref expr) => {
match expr.node {
ast::ExprFnBlock(fn_decl, top_level_block) |
ast::ExprProc(fn_decl, top_level_block) => {
let name = format!("fn{}", token::gensym("fn"));
let name = token::str_to_ident(name);
(name, fn_decl,
// This is not quite right. It should actually inherit the generics of the
// enclosing function.
&empty_generics,
top_level_block,
expr.span,
// Don't try to lookup the item path:
false)
}
_ => cx.sess.span_bug(expr.span,
"create_function_debug_context: expected an expr_fn_block here")
}
}
ast_map::NodeTraitMethod(trait_method) => {
match *trait_method {
ast::Provided(method) => {
(method.ident,
method.decl,
&method.generics,
method.body,
method.span,
true)
}
_ => {
cx.sess
.bug(format!("create_function_debug_context: \
unexpected sort of node: {:?}",
fnitem))
}
}
}
ast_map::NodeForeignItem(..) |
ast_map::NodeVariant(..) |
ast_map::NodeStructCtor(..) => {
return FunctionWithoutDebugInfo;
}
_ => cx.sess.bug(format!("create_function_debug_context: \
unexpected sort of node: {:?}", fnitem))
};
// This can be the case for functions inlined from another crate
if span == codemap::DUMMY_SP {
return FunctionWithoutDebugInfo;
}
let loc = span_start(cx, span);
let file_metadata = file_metadata(cx, loc.file.name);
let function_type_metadata = unsafe {
let fn_signature = get_function_signature(cx, fn_ast_id, fn_decl, param_substs, span);
llvm::LLVMDIBuilderCreateSubroutineType(DIB(cx), file_metadata, fn_signature)
};
// get_template_parameters() will append a `<...>` clause to the function name if necessary.
let mut function_name = token::get_ident(ident).get().to_str();
let template_parameters = get_template_parameters(cx,
generics,
param_substs,
file_metadata,
&mut function_name);
// There is no ast_map::Path for ast::ExprFnBlock-type functions. For now, just don't put them
// into a namespace. In the future this could be improved somehow (storing a path in the
// ast_map, or construct a path using the enclosing function).
let (linkage_name, containing_scope) = if has_path {
let namespace_node = namespace_for_item(cx, ast_util::local_def(fn_ast_id));
let linkage_name = namespace_node.mangled_name_of_contained_item(function_name);
let containing_scope = namespace_node.scope;
(linkage_name, containing_scope)
} else {
(function_name.clone(), file_metadata)
};
// Clang sets this parameter to the opening brace of the function's block, so let's do this too.
let scope_line = span_start(cx, top_level_block.span).line;
// The is_local_to_unit flag indicates whether a function is local to the current compilation
// unit (i.e. if it is *static* in the C-sense). The *reachable* set should provide a good
// approximation of this, as it contains everything that might leak out of the current crate
// (by being externally visible or by being inlined into something externally visible). It might
// better to use the `exported_items` set from `driver::CrateAnalysis` in the future, but (atm)
// this set is not available in the translation pass.
let is_local_to_unit = {
let reachable = cx.reachable.borrow();
!reachable.get().contains(&fn_ast_id)
};
let fn_metadata = function_name.with_c_str(|function_name| {
linkage_name.with_c_str(|linkage_name| {
unsafe {
llvm::LLVMDIBuilderCreateFunction(
DIB(cx),
containing_scope,
function_name,
linkage_name,
file_metadata,
loc.line as c_uint,
function_type_metadata,
is_local_to_unit,
true,
scope_line as c_uint,
FlagPrototyped as c_uint,
cx.sess.opts.optimize != session::No,
llfn,
template_parameters,
ptr::null())
}
})
});
// Initialize fn debug context (including scope map and namespace map)
let fn_debug_context = ~FunctionDebugContextData {
scope_map: RefCell::new(HashMap::new()),
fn_metadata: fn_metadata,
argument_counter: Cell::new(1),
source_locations_enabled: Cell::new(false),
};
let arg_pats = fn_decl.inputs.map(|arg_ref| arg_ref.pat);
{
let mut scope_map = fn_debug_context.scope_map.borrow_mut();
populate_scope_map(cx,
arg_pats.as_slice(),
top_level_block,
fn_metadata,
scope_map.get());
}
// Clear the debug location so we don't assign them in the function prelude
set_debug_location(cx, UnknownLocation);
return FunctionDebugContext(fn_debug_context);
fn get_function_signature(cx: &CrateContext,
fn_ast_id: ast::NodeId,
fn_decl: &ast::FnDecl,
param_substs: Option<@param_substs>,
error_span: Span) -> DIArray {
if cx.sess.opts.debuginfo == LimitedDebugInfo {
return create_DIArray(DIB(cx), []);
}
let mut signature = vec::with_capacity(fn_decl.inputs.len() + 1);
// Return type -- llvm::DIBuilder wants this at index 0
match fn_decl.output.node {
ast::TyNil => {
signature.push(ptr::null());
}
_ => {
assert_type_for_node_id(cx, fn_ast_id, error_span);
let return_type = ty::node_id_to_type(cx.tcx, fn_ast_id);
let return_type = match param_substs {
None => return_type,
Some(substs) => {
ty::subst_tps(cx.tcx, substs.tys, substs.self_ty, return_type)
}
};
signature.push(type_metadata(cx, return_type, codemap::DUMMY_SP));
}
}
// Arguments types
for arg in fn_decl.inputs.iter() {
assert_type_for_node_id(cx, arg.pat.id, arg.pat.span);
let arg_type = ty::node_id_to_type(cx.tcx, arg.pat.id);
let arg_type = match param_substs {
None => arg_type,
Some(substs) => {
ty::subst_tps(cx.tcx, substs.tys, substs.self_ty, arg_type)
}
};
signature.push(type_metadata(cx, arg_type, codemap::DUMMY_SP));
}
return create_DIArray(DIB(cx), signature);
}
fn get_template_parameters(cx: &CrateContext,
generics: &ast::Generics,
param_substs: Option<@param_substs>,
file_metadata: DIFile,
name_to_append_suffix_to: &mut ~str)
-> DIArray {
let self_type = match param_substs {
Some(param_substs) => param_substs.self_ty,
_ => None
};
// Only true for static default methods:
let has_self_type = self_type.is_some();
if !generics.is_type_parameterized() && !has_self_type {
return create_DIArray(DIB(cx), []);
}
name_to_append_suffix_to.push_char('<');
// The list to be filled with template parameters:
let mut template_params: ~[DIDescriptor] = vec::with_capacity(generics.ty_params.len() + 1);
// Handle self type
if has_self_type {
let actual_self_type = self_type.unwrap();
// Add self type name to <...> clause of function name
let actual_self_type_name = ppaux::ty_to_str(cx.tcx, actual_self_type);
name_to_append_suffix_to.push_str(actual_self_type_name);
if generics.is_type_parameterized() {
name_to_append_suffix_to.push_str(",");
}
// Only create type information if full debuginfo is enabled
if cx.sess.opts.debuginfo == FullDebugInfo {
let actual_self_type_metadata = type_metadata(cx,
actual_self_type,
codemap::DUMMY_SP);
let ident = special_idents::type_self;
let param_metadata = token::get_ident(ident).get()
.with_c_str(|name| {
unsafe {
llvm::LLVMDIBuilderCreateTemplateTypeParameter(
DIB(cx),
file_metadata,
name,
actual_self_type_metadata,
ptr::null(),
0,
0)
}
});
template_params.push(param_metadata);
}
}
// Handle other generic parameters
let actual_types = match param_substs {
Some(param_substs) => ¶m_substs.tys,
None => {
return create_DIArray(DIB(cx), template_params);
}
};
for (index, &ast::TyParam{ ident: ident, .. }) in generics.ty_params.iter().enumerate() {
let actual_type = actual_types[index];
// Add actual type name to <...> clause of function name
let actual_type_name = ppaux::ty_to_str(cx.tcx, actual_type);
name_to_append_suffix_to.push_str(actual_type_name);
if index != generics.ty_params.len() - 1 {
name_to_append_suffix_to.push_str(",");
}
// Again, only create type information if full debuginfo is enabled
if cx.sess.opts.debuginfo == FullDebugInfo {
let actual_type_metadata = type_metadata(cx, actual_type, codemap::DUMMY_SP);
let param_metadata = token::get_ident(ident).get()
.with_c_str(|name| {
unsafe {
llvm::LLVMDIBuilderCreateTemplateTypeParameter(
DIB(cx),
file_metadata,
name,
actual_type_metadata,
ptr::null(),
0,
0)
}
});
template_params.push(param_metadata);
}
}
name_to_append_suffix_to.push_char('>');
return create_DIArray(DIB(cx), template_params);
}
}
//=-------------------------------------------------------------------------------------------------
// Module-Internal debug info creation functions
//=-------------------------------------------------------------------------------------------------
fn create_DIArray(builder: DIBuilderRef, arr: &[DIDescriptor]) -> DIArray {
return unsafe {
llvm::LLVMDIBuilderGetOrCreateArray(builder, arr.as_ptr(), arr.len() as u32)
};
}
fn compile_unit_metadata(cx: &CrateContext) {
let work_dir = &cx.sess.working_dir;
let compile_unit_name = match cx.sess.local_crate_source_file {
None => fallback_path(cx),
Some(ref abs_path) => {
if abs_path.is_relative() {
cx.sess.warn("debuginfo: Invalid path to crate's local root source file!");
fallback_path(cx)
} else {
match abs_path.path_relative_from(work_dir) {
Some(ref p) if p.is_relative() => {
// prepend "./" if necessary
let dotdot = bytes!("..");
let prefix = &[dotdot[0], ::std::path::SEP_BYTE];
let mut path_bytes = p.as_vec().to_owned();
if path_bytes.slice_to(2) != prefix &&
path_bytes.slice_to(2) != dotdot {
path_bytes.insert(0, prefix[0]);
path_bytes.insert(1, prefix[1]);
}
path_bytes.to_c_str()
}
_ => fallback_path(cx)
}
}
}
};
debug!("compile_unit_metadata: {:?}", compile_unit_name);
let producer = format!("rustc version {}", env!("CFG_VERSION"));
compile_unit_name.with_ref(|compile_unit_name| {
work_dir.as_vec().with_c_str(|work_dir| {
producer.with_c_str(|producer| {
"".with_c_str(|flags| {
"".with_c_str(|split_name| {
unsafe {
llvm::LLVMDIBuilderCreateCompileUnit(
debug_context(cx).builder,
DW_LANG_RUST,
compile_unit_name,
work_dir,
producer,
cx.sess.opts.optimize != session::No,
flags,
0,
split_name);
}
})
})
})
})
});
fn fallback_path(cx: &CrateContext) -> CString {
cx.link_meta.crateid.name.to_c_str()
}
}
fn declare_local(bcx: &Block,
variable_ident: ast::Ident,
variable_type: ty::t,
scope_metadata: DIScope,
variable_access: VariableAccess,
variable_kind: VariableKind,
span: Span) {
let cx: &CrateContext = bcx.ccx();
let filename = span_start(cx, span).file.name.clone();
let file_metadata = file_metadata(cx, filename);
let name = token::get_ident(variable_ident);
let loc = span_start(cx, span);
let type_metadata = type_metadata(cx, variable_type, span);
let (argument_index, dwarf_tag) = match variable_kind {
ArgumentVariable(index) => (index as c_uint, DW_TAG_arg_variable),
LocalVariable |
CapturedVariable => (0, DW_TAG_auto_variable)
};
let (var_alloca, var_metadata) = name.get().with_c_str(|name| {
match variable_access {
DirectVariable { alloca } => (
alloca,
unsafe {
llvm::LLVMDIBuilderCreateLocalVariable(
DIB(cx),
dwarf_tag,
scope_metadata,
name,
file_metadata,
loc.line as c_uint,
type_metadata,
cx.sess.opts.optimize != session::No,
0,
argument_index)
}
),
IndirectVariable { alloca, address_operations } => (
alloca,
unsafe {
llvm::LLVMDIBuilderCreateComplexVariable(
DIB(cx),
dwarf_tag,
scope_metadata,
name,
file_metadata,
loc.line as c_uint,
type_metadata,
address_operations.as_ptr(),
address_operations.len() as c_uint,
argument_index)
}
)
}
});
set_debug_location(cx, DebugLocation::new(scope_metadata, loc.line, loc.col.to_uint()));
unsafe {
let instr = llvm::LLVMDIBuilderInsertDeclareAtEnd(
DIB(cx),
var_alloca,
var_metadata,
bcx.llbb);
llvm::LLVMSetInstDebugLocation(trans::build::B(bcx).llbuilder, instr);
}
match variable_kind {
ArgumentVariable(_) | CapturedVariable => {
assert!(!bcx.fcx