-
Notifications
You must be signed in to change notification settings - Fork 2
/
prof.cpp
4570 lines (3993 loc) · 164 KB
/
prof.cpp
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
// rsvp | (C) 2012 Tim C. Schroeder | www.blitzcode.net
#include <cstdio>
#include <cstdlib>
#include <cassert>
#include <cmath>
#include <vector>
#include <list>
#include <string>
#include <memory>
#include <map>
#include <set>
#include <stack>
#include <sys/sysctl.h>
#include <sys/time.h>
#include <libproc.h>
#include <mach/mach.h>
#include <mach/mach_vm.h> // for mach_vm_ instead of vm_
#include <pthread.h>
#include <errno.h>
#include <signal.h>
#include <fcntl.h>
#include <OpenGL/gl.h>
#include <OpenGL/glu.h>
#include <GLUT/glut.h>
// Static assert
template <bool> struct StaticAssert;
template<> struct StaticAssert<true> { };
#define STATIC_ASSERT(x) (StaticAssert<(x) != 0>())
// Integer types
typedef char int8;
typedef short int16;
typedef int int32;
typedef long long int64;
typedef unsigned int uint;
typedef unsigned char uchar;
typedef unsigned char uint8;
typedef unsigned short uint16;
typedef unsigned int uint32;
typedef unsigned long long uint64;
void TestTypes()
{
// Static size checks
STATIC_ASSERT(sizeof(int8) == 1);
STATIC_ASSERT(sizeof(int16) == 2);
STATIC_ASSERT(sizeof(int32) == 4);
STATIC_ASSERT(sizeof(int64) == 8);
STATIC_ASSERT(sizeof(uint8) == 1);
STATIC_ASSERT(sizeof(uint16) == 2);
STATIC_ASSERT(sizeof(uint32) == 4);
STATIC_ASSERT(sizeof(uint64) == 8);
}
// Global state and constants
pthread_t g_sampling_thread;
volatile bool g_stop_sampling_thread = false;
volatile bool g_freeze_sampling_thread = false;
uint g_num_smp_target = 2500; // Per >= 1/2 second
uint g_num_smp_profile = 8000;
const uint g_max_fps = 30; // Frame limiter
const uint g_col_wdh = 485; // For the two column GUI layout
const uint g_wnd_wdh = g_col_wdh * 2 - 3;
uint g_wnd_hgt = 678; // Window height is adjustable
float g_ui_scale = 1.0f;
uint g_real_wnd_wdh = g_wnd_hgt; // Actual window size, needed for UI scaling
uint g_real_wnd_hgt = g_wnd_wdh;
uint g_cur_func_sel = 0; // Current function index selected in the function profile
bool g_call_tree_incoming = true; // Show incoming or outgoing call tree?
volatile bool g_reset_profile = false; // Trigger a reset of the profile in the HF sampling thread
const char g_project_url[] = "https://github.com/blitzcode/rsvp";
bool g_show_call_tree = true; // Show call tree or source view?
// g_font, g_symbol, g_fs_usage, g_source and g_prof_data further down
void FatalExit(const char *error)
{
// Error exit function
std::printf("ERROR: %s\n", error);
std::exit(1);
}
double TimerGetTick()
{
// High precision timer, return in seconds
// Make returned tick smaller
static bool first_call = true;
static timeval start;
if (first_call)
{
first_call = false;
gettimeofday(&start, NULL);
}
timeval time;
gettimeofday(&time, NULL);
return
double(time.tv_sec - start.tv_sec) +
double(time.tv_usec - start.tv_usec) / 1000000.0;
}
class Lockable
{
public:
Lockable() { if (pthread_mutex_init (&m_mutex, NULL) != 0) assert(!"Mutex init failed"); }
~Lockable() { if (pthread_mutex_destroy(&m_mutex) != 0) assert(!"Mutex destroy failed"); }
void Lock() { if (pthread_mutex_lock (&m_mutex) != 0) assert(!"Mutex lock failed"); }
void Unlock() { if (pthread_mutex_unlock (&m_mutex) != 0) assert(!"Mutex unlock failed"); }
protected:
pthread_mutex_t m_mutex;
};
// Wrapper around atos tool
//
// http://developer.apple.com/library/mac/#documentation/Darwin/Reference/ManPages/man1/atos.1.html
//
// Duplicating the full functionality of this tool would be rather difficult. Its source is not
// available, some of the underlying APIs are poorly documented, plus it does exactly what we need
// and seems reasonably fast and reliable
class ATOS_Pipe
{
public:
ATOS_Pipe(pid_t pid)
{
// Check for atos
//
// Since 10.9 calling atos directly seems to be deprecated. The warning suggest
// to invoke it through xcrun, which seems to work fine on 10.6 already
//
// Also see here:
//
// http://root.cern.ch/phpBB3/viewtopic.php?f=3&t=17190&start=30
// https://github.com/allending/Kiwi/pull/365
if (std::system("xcrun atos 2> /dev/null") != 0)
FatalExit("Can't find 'atos' command line utility - dev. tools not installed?");
// TODO: The bi-directional popen() only works with this environment
// variable set to avoid a deadlock due to buffering, nasty
if (setenv("NSUnbufferedIO", "YES", 1) != 0)
assert(!"setenv failed");
char buf[64];
std::snprintf(buf, sizeof(buf), "xcrun atos -p %i", pid);
m_pipe = popen(buf, "r+");
assert(m_pipe != NULL);
}
~ATOS_Pipe()
{
if (m_pipe != NULL)
if (pclose(m_pipe ) != 0)
assert(!"pclose() failed");
}
void AddressToSymbol(uint64 addr, char *buf, size_t buf_len) const
{
// Communicate with atos program for address resolution, needs to have
// buffering disabled to not deadlock
// The addresses need to be in hexadecimal, since 10.7 atos only resolves those
if (std::fprintf(m_pipe, "0x%llx\n", addr) <= 0)
assert(!"Writing to atos pipe failed");
if (std::fgets(buf, buf_len, m_pipe) == NULL)
assert(!"Reading from atos pipe failed");
}
protected:
std::FILE *m_pipe;
};
class SymbolManager : private Lockable
{
public:
SymbolManager(pid_t pid) :
m_atos(pid),
m_cache_hit(0),
m_cache_miss(0),
m_unresolved_sym_name("(Unresolved)")
{ }
uint32 AddressToSymbolID(
uint64 addr,
uint16 *file_name_id_out = NULL, // Optional source & line information starts here
uint16 *line_number_out = NULL)
{
// Resolve an address into a symbol ID common to all addresses resolving into that symbol.
// We return source and line information on the spot. We can't cache them here as they are
// tied to the address and not the symbol
Lock();
// Check address cache
CacheEntry &cache = m_cache[addr % (sizeof(m_cache) / sizeof(CacheEntry))];
if (cache.m_pc == addr &&
cache.m_sym_id != uint32(-1)) // Sometimes we get a null address and a false hit
{
m_cache_hit++;
}
else
{
m_cache_miss++;
// Obtain symbol string from atos
char symbol[8192];
m_atos.AddressToSymbol(addr, symbol, sizeof(symbol));
// Module and file name / line
char module[1024];
char file_name[1024];
uint line_number;
ExtractModuleAndFileName(
symbol,
module,
sizeof(module),
file_name,
sizeof(file_name),
&line_number);
// De-mangle atos output into clean and display friendly symbol name
PrettyPrintSymbol(symbol);
// Just convert all hex addresses to a single unresolved token
if (std::strncmp(symbol, "0x", 2) == 0)
std::strncpy(symbol, GetUnresolvedSymbolName(), sizeof(symbol));
// Check if we already have that symbol name in the table
const uint64 sym_hash = BernsteinHash(symbol) ^ BernsteinHash(module);
std::map<uint64, uint32>::iterator it_sym = m_hash_to_sym_id.find(sym_hash);
if (it_sym == m_hash_to_sym_id.end())
{
// Add to symbol and module name string table
uint32 new_id = uint32(m_sym_table.size());
m_sym_table.push_back(SymbolName());
m_sym_table.back().m_symbol = std::string(symbol);
m_sym_table.back().m_module = std::string(module);
// Hash-to-ID translation entry
it_sym = m_hash_to_sym_id.insert
(std::map<uint64, uint32>::value_type(sym_hash, new_id)).first;
}
// Check if we already have that file name in the table
const uint64 file_hash = BernsteinHash(file_name);
std::map<uint64, uint16>::iterator it_file = m_hash_to_file_name_id.find(file_hash);
if (it_file == m_hash_to_file_name_id.end())
{
// Add to file name string table
uint16 new_id = uint16(m_file_name_table.size());
m_file_name_table.push_back(std::string(file_name));
// Hash-to-ID translation entry
it_file = m_hash_to_file_name_id.insert
(std::map<uint64, uint16>::value_type(file_hash, new_id)).first;
}
// Update cache
cache.m_pc = addr;
cache.m_sym_id = (* it_sym).second;
cache.m_file_name_id = (* it_file).second;
cache.m_line_number = line_number;
if (std::strcmp(symbol, SymbolIDToName ((* it_sym ).second)) != 0)
{
printf("'%s' != '%s'\n", symbol, SymbolIDToName((* it_sym ).second));
}
assert(std::strcmp(symbol, SymbolIDToName ((* it_sym ).second)) == 0);
assert(std::strcmp(module, SymbolIDToModule((* it_sym ).second)) == 0);
assert(std::strcmp(file_name, FileIDToName ((* it_file).second)) == 0);
}
// Return results from cache
if (file_name_id_out != NULL)
(* file_name_id_out) = cache.m_file_name_id;
if (line_number_out != NULL)
(* line_number_out) = cache.m_line_number;
const uint32 sym_id = cache.m_sym_id;
Unlock();
return sym_id;
}
const char * SymbolIDToName(uint32 id) const
{
assert(id < m_sym_table.size());
return m_sym_table[id].m_symbol.c_str();
}
const char * SymbolIDToModule(uint32 id) const
{
assert(id < m_sym_table.size());
return m_sym_table[id].m_module.c_str();
}
const char * FileIDToName(uint16 id) const
{
assert(id < m_file_name_table.size());
return m_file_name_table[id].c_str();
}
float GetCacheHitPercentage() const
{
return float(m_cache_hit) / float(m_cache_hit + m_cache_miss) * 100.0f;
}
const char * GetUnresolvedSymbolName() const { return m_unresolved_sym_name.c_str(); }
protected:
ATOS_Pipe m_atos;
// Address -> Symbol ID cache
uint m_cache_hit;
uint m_cache_miss;
struct CacheEntry
{
CacheEntry() : m_pc(0), m_sym_id(-1), m_file_name_id(-1), m_line_number(-1) { }
uint64 m_pc;
uint32 m_sym_id;
// Have to store this here instead of the symbol table as they vary by address, not symbol
uint16 m_file_name_id;
uint16 m_line_number;
} m_cache[65536 * 32]; // 32MB
// Table of unique symbol names and map to translate string hash -> table location
std::map<uint64, uint32> m_hash_to_sym_id;
struct SymbolName
{
std::string m_symbol;
std::string m_module;
};
std::vector<SymbolName> m_sym_table;
// Table of unique file names and map to translate string hash -> table location
std::map<uint64, uint16> m_hash_to_file_name_id;
std::vector<std::string> m_file_name_table;
std::string m_unresolved_sym_name;
uint64 BernsteinHash(const char *str_) const
{
// The original Bernstein hash enventually had some collisions, this is a simple
// 64 bit extension of it
const uchar *str = reinterpret_cast<const uchar *> (str_);
uint32 hash_a = 5381;
uint32 hash_b = 5387;
int c;
while ((c = *str++))
{
hash_a = hash_a * 33 ^ c;
hash_b = hash_b * 35 ^ c;
}
return uint64(hash_a) | (uint64(hash_b) << 32);
}
void ExtractModuleAndFileName(
const char *sym,
char *module,
size_t module_len,
char *file,
size_t file_len,
uint *line_number) const
{
// Extract the module and file / line from a symbol string. Can pass NULL for all out
// parameters to skip them
// Initialize with failure defaults in case we abort
if (module != NULL)
std::strncpy(module, GetUnresolvedSymbolName(), module_len);
if (file != NULL)
std::strncpy(file, GetUnresolvedSymbolName(), file_len);
if (line_number != NULL)
(* line_number) = 0;
// Find module name part
const char module_token[] = " (in ";
const char *module_begin = std::strstr(sym, module_token);
if (module_begin == NULL)
return; // Not present
module_begin += std::strlen(module_token);
// Find end of module name part
const char *module_end = std::strchr(module_begin, ')');
if (module_end == NULL)
return; // Must be terminated by closing brace
const size_t module_idx = module_end - module_begin;
// Extract module name
if (module != NULL)
{
std::strncpy(module, module_begin, module_len);
module[std::min(module_idx, module_len)] = '\0';
}
// Find file name part
const char file_token[] = " (";
const char *file_begin = std::strstr(module_end, file_token);
if (file_begin == NULL)
return; // Not present
file_begin += std::strlen(file_token);
// Find end of file name part
const char *file_end = std::strchr(file_begin, ':');
if (file_end == NULL)
return; // Need colon
const size_t file_idx = file_end - file_begin;
// Extract file name
if (file != NULL)
{
std::strncpy(file, file_begin, file_len);
file[std::min(file_idx, file_len)] = '\0';
}
// Extract line number
if (line_number != NULL)
std::sscanf(file_end + 1, "%i", line_number);
}
void PrettyPrintSymbol(char *sym) const
{
// Convert the output of atos into a name that is readable and compact. We inevitably throw
// away some information like template arguments, function overloads and module information
// etc., it's a trade-off. This function also makes certain assumptions on how atos formats
// its symbols, will likely need to be tweaked if anything changes
if (sym[0] == '+' || sym[0] == '-')
{
// Objective C. We just cut off the parameter list and everything after the brackets
while (*sym++ != '\0')
{
if (*sym == ']' || *sym == ':')
{
*sym++ = ']';
*sym = '\0';
}
}
}
else
{
// Assume C / C++
// Remove module, source file and offset information
{
char *cut = std::strstr(sym, " (in ");
if (cut != NULL)
*cut = '\0';
}
// Remove newline
if (sym[std::strlen(sym) - 1] == '\n')
sym[std::strlen(sym) - 1] = '\0';
// Shorten '(anonymous namespace)' to 'anon'
{
char *anon = NULL;
const char search[] = "(anonymous namespace)";
const size_t len_s = sizeof(search) - 1;
while ((anon = std::strstr(sym, search)))
{
const char replace[] = "anon";
const size_t len_r = sizeof(replace) - 1;
std::memcpy(anon, replace, len_r);
std::memmove(anon + len_r, anon + len_s, std::strlen(sym + len_s) + 1);
}
}
char *orig_ptr = sym;
// Compact braces and angle brackets
int angle_level = 0, brace_level = 0;
char *angle_start = NULL, *brace_start = NULL;
while (*sym != '\0')
{
// Angle brackets confuse our parser, skip operators which have them
const char ops[][16] =
{
"operator<<=", "operator <<=", "operator>>=", "operator >>=", // Shift Assign
"operator<<", "operator <<", "operator>>", "operator >>", // Shift
"operator<", "operator <", "operator>", "operator >", // Compare
"operator->", "operator ->" // Dereference
};
for (uint i=0; i<sizeof(ops) / sizeof(ops[0]); i++)
if (std::strncmp(sym, ops[i], std::strlen(ops[i])) == 0)
{
sym += std::strlen(ops[i]);
break;
}
// Don't bother inside braces, we just remove it all anyway
if (brace_level == 0)
{
// Increment nesting level and store position of first open angle
// bracket so we know where to start deleting
if (*sym == '<')
if (angle_level++ == 0)
angle_start = sym;
// Decrement nesting level and replace on encountering final angle bracket
if (*sym == '>')
if (--angle_level == 0)
{
std::memmove(angle_start + 1, sym, strlen(sym) + 1);
sym = angle_start + 1;
}
assert(angle_level >= 0);
}
// Don't bother inside angle brackets, we just remove it all anyway
if (angle_level == 0)
{
// Increment nesting level and store position of first open
// brace so we know where to start deleting
if (*sym == '(')
if (brace_level++ == 0)
brace_start = sym;
// Decrement nesting level and delete on encountering final brace
if (*sym == ')')
if (--brace_level == 0)
{
if (sym - brace_start > 1)
{
std::memmove(brace_start + 1, sym, strlen(sym) + 1);
sym = brace_start + 1;
}
}
assert(brace_level >= 0);
}
sym++;
}
assert(angle_level == 0);
assert(brace_level == 0);
// Remove leading types and trailing qualifiers
{
sym = orig_ptr;
// Trailing const
char *const_trail = std::strstr(sym, " const");
if (const_trail != NULL)
*const_trail = '\0';
// Leading types (return values) are sometimes included in the symbol, remove them
while (*sym != '\0')
{
// Operator function names have spaces in them, don't throw them
// away as leading segments
const char ops[][16] = { " operator", ":operator", "$operator" };
bool break_outer = false;
for (uint i=0; i<sizeof(ops) / sizeof(ops[0]); i++)
if (std::strncmp(sym, ops[i], std::strlen(ops[i])) == 0)
break_outer = true;
if (break_outer)
break;
// Remove all space separated segments before the last one
if (*sym == ' ')
{
std::memmove(orig_ptr, sym + 1, std::strlen(sym) + 1);
sym = orig_ptr;
continue;
}
sym++;
}
}
}
}
};
std::auto_ptr<SymbolManager> g_symbol;
// Fixed size and stack allocated version of std::stack
template <typename T, size_t N> class FixedStackStack
{
public:
FixedStackStack() : m_top(0) { }
const T& Pop() { return m_stack[--m_top]; }
void Push(const T& top) { assert(m_top != N - 1); m_stack[m_top++] = top; }
void Clear() { m_top = 0; }
size_t Size() const { return m_top; }
bool Empty() const { return m_top == 0; }
const T * GetStack() const { return Empty() ? NULL : &m_stack[0]; }
protected:
T m_stack[N];
size_t m_top;
};
class CallTree
{
public:
void MergeCallStack(const uint32 *stack, size_t size, uint hits = 1)
{
// Merge the given call stack into our tree
uint32 cur_node = m_tree.empty() ? uint32(-1) : 0;
uint32 parent = uint32(-1);
// Merge all the levels of the call stack
for (uint level=0; level<size; level++)
{
// See if we already got the symbol at the current level
uint32 last_sibling = uint32(-1);
while (cur_node != uint32(-1))
{
if (m_tree[cur_node].m_sym_id == stack[level])
break; // Found it
last_sibling = cur_node;
cur_node = m_tree[cur_node].m_sibling; // Next
}
// We either found a match or we're at the end of the sibling list
if (cur_node != uint32(-1))
{
// Found it, just increment the hit count
m_tree[cur_node].m_hits += hits;
parent = cur_node;
cur_node = m_tree[cur_node].m_child;
}
else
{
// At the end, add new node
{
Node new_node;
new_node.m_sym_id = stack[level];
new_node.m_hits = hits;
m_tree.push_back(new_node);
}
const uint32 new_node = uint32(m_tree.size() - 1);
if (last_sibling == uint32(-1))
{
// No siblings, link with parent
if (parent != uint32(-1))
m_tree[parent].m_child = new_node;
}
else
{
// Link up with the last sibling
m_tree[last_sibling].m_sibling = new_node;
}
parent = new_node;
cur_node = uint32(-1);
}
}
}
void MergeCallTree(const CallTree& merge)
{
// Merge the given tree into this one
//
// TODO: This function is basically a combination of MergeCallStack() and the traversal
// from DebugPrint(). Can we maybe refactor all three functions to share code?
if (merge.m_tree.empty())
return;
if (m_tree.empty())
{
(* this) = merge;
return;
}
// Merging trees is tricky, some sanity checks before and after
#ifdef DEBUG_MERGE_CALL_TREE
const uint dbg_count_1 = merge.DebugPrint(true);
const uint dbg_count_2 = DebugPrint(true);
assert(merge.DebugHasDuplicates() == false);
assert(DebugHasDuplicates() == false);
#endif // DEBUG_MERGE_CALL_TREE
// Merging tree_1 into tree_2
const std::vector<Node>& tree_1 = merge.m_tree;
std::vector<Node>& tree_2 = m_tree;
FixedStackStack<uint32, 512> stack_1, stack_2;
stack_1.Push(0);
stack_2.Push(0);
uint32 cur_node_1, cur_node_2;
// Traverse the merge tree
while (stack_1.Empty() == false)
{
cur_node_1 = stack_1.Pop();
cur_node_2 = stack_2.Pop();
// We basically go down tree_1, then right, and then work our way
// back up through the outer loop
uint32 parent = uint32(-1);
while (cur_node_1 != uint32(-1))
{
// See if we already got the symbol from tree_1 one the same level in tree_2
// TODO: This is O(n^2) in the worst case (seems fine in practice, though)
uint32 first_sibling = cur_node_2;
uint32 last_sibling = uint32(-1);
while (cur_node_2 != uint32(-1))
{
if (tree_2[cur_node_2].m_sym_id == tree_1[cur_node_1].m_sym_id)
break; // Found it
last_sibling = cur_node_2;
cur_node_2 = tree_2[cur_node_2].m_sibling; // Next
}
// We either found a match or we're at the end of the sibling list
if (cur_node_2 != uint32(-1))
{
// Found it, just add up the counts from both trees
tree_2[cur_node_2].m_hits += tree_1[cur_node_1].m_hits;
parent = cur_node_2; // In case we have children in tree_1 and descent
}
else
{
// At the end, add new node to tree_2
{
// Just copy from tree_1
Node new_node;
new_node.m_sym_id = tree_1[cur_node_1].m_sym_id;
new_node.m_hits = tree_1[cur_node_1].m_hits;
tree_2.push_back(new_node);
}
const uint32 new_node = uint32(tree_2.size() - 1);
if (last_sibling == uint32(-1))
{
// No siblings, link with parent. We know there always is a
// parent since we don't merge empty trees
tree_2[parent].m_child = new_node;
first_sibling = new_node; // What we push on the stack if we descent
}
else
tree_2[last_sibling].m_sibling = new_node; // Link with last sibling
cur_node_2 = new_node;
parent = new_node;
}
// Traverse tree_1 depth first
if (tree_1[cur_node_1].m_child != uint32(-1))
{
// Continue with the next sibling once we go back up
stack_1.Push(tree_1[cur_node_1].m_sibling);
// We need to search for a match from tree_1 at the first sibling
stack_2.Push(first_sibling);
// Go down both trees
cur_node_1 = tree_1[cur_node_1].m_child;
cur_node_2 = tree_2[cur_node_2].m_child;
}
else
{
cur_node_1 = tree_1[cur_node_1].m_sibling; // Can't go deeper, go right
cur_node_2 = first_sibling; // Start again at first sibling
}
}
}
#ifdef DEBUG_MERGE_CALL_TREE
assert(DebugPrint(true) == dbg_count_1 + dbg_count_2);
assert(DebugHasDuplicates() == false);
#endif // DEBUG_MERGE_CALL_TREE
}
void SortSiblingLists()
{
// Sort all sibling lists by their m_hits member in descending order
// Enumerate all sibling lists
std::vector<uint32> first_siblings;
GetAllNonZeroSiblingLists(first_siblings);
// Sort
for (std::vector<uint32>::const_iterator it=first_siblings.begin();
it!=first_siblings.end();
it++)
{
uint32 cur_node;
// Create vector of nodes
std::vector<Node> nodes;
cur_node = (* it);
do
{
nodes.push_back(m_tree[cur_node]);
cur_node = m_tree[cur_node].m_sibling;
} while (cur_node != uint32(-1));
// Sort copy
std::sort(nodes.begin(), nodes.end());
// Write the sorted vector back into the node slots
cur_node = (* it);
for (std::vector<Node>::const_iterator it=nodes.begin();
it!=nodes.end();
it++)
{
assert(cur_node != uint32(-1));
const uint32 next_node = m_tree[cur_node].m_sibling;
m_tree[cur_node] = (* it);
m_tree[cur_node].m_sibling = next_node;
cur_node = next_node;
}
}
}
void ExtractOutgoingCallArcs(
uint32 symbol_id,
uint32 root_symbol_id,
CallTree *outgoing) const
{
// Search this incoming tree tree for call arcs from symbol_id and merge them into outgoing.
// We need the root symbol of the incoming tree as it is not stored in the tree itself.
// Pretty straightforward, except for the bit ensuring that we only take the longest part of
// an arc in the case of cycles
//
// TODO: Maybe write some tests to make sure this really works completely as intended...
if (m_tree.empty())
return;
FixedStackStack<uint32, 512> st;
st.Push(0);
uint32 cur_node;
bool arc_already_merged = true;
bool seen_root = false;
while (st.Empty() == false)
{
cur_node = st.Pop();
// Found the symbol we're looking for?
if (m_tree[cur_node].m_sym_id == symbol_id && arc_already_merged == false)
{
// Flip our arc and add the root symbol at the end
uint32 arc[512];
for (uint i=0; i<st.Size(); i++)
arc[i] = m_tree[st.GetStack()[st.Size() - (i + 1)]].m_sym_id;
arc[st.Size()] = root_symbol_id;
// Merge into the outgoing graph for symbol_id
// TODO: We merge the arc with only one hit count for all levels. This should allow
// us to reconstruct the first-level times for the outgoing call tree, but we
// could do better
outgoing->MergeCallStack(arc, st.Size() + 1, m_tree[cur_node].m_hits);
// Only add the longest sequence on the arc, meaning for recursion / cycles
// we only use the bottom one
arc_already_merged = true;
}
// Little hack so we keep the actual path on the stack instead of the next siblings
if (cur_node == 0 && seen_root == false)
seen_root = true;
else
cur_node = m_tree[cur_node].m_sibling;
// Depth-first
while (cur_node != uint32(-1))
{
if (m_tree[cur_node].m_sym_id == symbol_id)
{
// We're about to push a new instance of the arc start symbol onto the stack,
// meaning we're on a new arc again and should stop ignoring its occurrence
arc_already_merged = false;
}
// Go deeper, go right in the outer loop if there's no child
st.Push(cur_node);
cur_node = m_tree[cur_node].m_child;
}
}
}
uint DebugPrint(bool silent) const
{
// Traverse the tree depth-first and print it to stdout. Also check for
// orphaned nodes and return the sum of the hit count of all nodes
if (m_tree.empty())
return 0;
std::stack<uint32> st;
st.push(0);
uint32 cur_node;
uint num_nodes_printed = 0;
uint total_count = 0;
while (st.empty() == false)
{
cur_node = st.top();
st.pop();
while (cur_node != uint32(-1))
{
num_nodes_printed++;
total_count += m_tree[cur_node].m_hits;
if (silent == false)
{
for (uint i=0; i<st.size() + 1; i++)
std::printf(" ");
std::printf("%s : %i\n", g_symbol->SymbolIDToName(
m_tree[cur_node].m_sym_id), m_tree[cur_node].m_hits);
}
if (m_tree[cur_node].m_child != uint32(-1))
{
st.push(m_tree[cur_node].m_sibling);
cur_node = m_tree[cur_node].m_child;
}
else
cur_node = m_tree[cur_node].m_sibling;
}
}
if (silent == false)
std::printf("\n");
assert(num_nodes_printed == m_tree.size()); // Did we get everything, no orphaned nodes?
return total_count;
}
bool DebugHasDuplicates() const
{
// Return true if we have duplicate siblings at any level
std::vector<uint32> first_siblings;
GetAllNonZeroSiblingLists(first_siblings);
for (std::vector<uint32>::const_iterator it=first_siblings.begin();
it!=first_siblings.end();
it++)
{
uint32 cur_node_1 = (* it);
while (cur_node_1 != uint32(-1))
{
uint duplicates = 0;
uint32 cur_node_2 = (* it);
while (cur_node_2 != uint32(-1))
{
if (m_tree[cur_node_1].m_sym_id == m_tree[cur_node_2].m_sym_id)
duplicates++;
cur_node_2 = m_tree[cur_node_2].m_sibling;
}
assert(duplicates > 0);
if (duplicates > 1)
return true;
cur_node_1 = m_tree[cur_node_1].m_sibling;
}
}
return false;
}
void DebugSerializeToDisk(const char *file_name) const
{
std::FILE *file = std::fopen(file_name, "wb");
size_t size = m_tree.size();
std::fwrite(&size, sizeof(size_t), 1, file);
std::fwrite(&m_tree[0], sizeof(Node), size,file);
std::fclose(file);
}
void DebugSerializeFromDisk(const char *file_name)
{
std::FILE *file = std::fopen(file_name, "rb");
size_t size;
std::fread(&size, sizeof(size_t), 1, file);
m_tree.resize(size);
std::fread(&m_tree[0], sizeof(Node), size,file);
std::fclose(file);
}
struct Node
{
Node() : m_sibling(-1), m_child(-1), m_sym_id(-1), m_hits(1) { }
uint32 m_sibling;
uint32 m_child;
uint32 m_sym_id;
uint32 m_hits;
// Sort by hit count
bool operator < (const Node& rhs) const
{