#! /bin/perl

use strict;
use Getopt::Std;

#
# Flags:
#	-d	print debug messages
#	-s	dump context stacks at end
use vars qw($opt_d $opt_s);
getopts('ds') or die;

#
# Per-record debug messages.
#
sub dprint
{
    if ($opt_d) {
	print @_;
    }
}


#
# addValues(\@state, \@vals)
#
# Add a vector of stat values to a cumulative state vector.
# Both parameters are array references.
#
sub addValues
{
    my ($state, $vals) = @_;

    # state array should either have the same number of values as the
    # incremental value array, or should be empty (if it's
    # uninitialized)
    if (@$state != @$vals && @$state != 0) {
	die "Value count mismatch: ", scalar @$state, " != ", scalar @$vals;
    }

    my $i;
    foreach $i (0..$#$vals) {
	@$state[$i] += @$vals[$i];
    }
}

########################################################################
#
# Object declarations
#
########################################################################

package StatUnit;

#
# 'Static' method: get object by label, creating a new one if necessary.
#
sub get
{
    my $class = shift;
    my $label = shift;
    my $obj = ${$class->map}{$label};
    if (!defined($obj)) {
	$obj = $class->new($label);
	${$class->map}{$label} = $obj;
    }
    return $obj;
}


#
# 'Static' method: return object count
#
sub numObjects
{
    my $class = shift;
    return scalar keys %{$class->map()};
}


#
# 'Static' method: return list of all objects, sorted by the
# first stat value (currently accumulated cycles) in descending order.
#
sub getAllByStat
{
    my $class = shift;
    return sort { ${$b->stats()}[0] <=> ${$a->stats()}[0] }
			values %{$class->map()};
}


package Context;

@Context::ISA = ('StatUnit');

#
# This hash tracks all of the context objects by label.
#
sub map
{
    return \%Context::theMap;
}


#
# A Context object is a three-element array:
#  0: label (string)
#  1: stack (array ref)
#  2: stats (array ref)
#
sub new
{
    my $class = shift;
    my $label = shift;
    my $self = bless [ $label, [ 'init' ], [ ] ], $class;
    return $self;
}

sub label { my $self = shift; return $$self[0]; }

sub stack { my $self = shift; return $$self[1]; }

sub stats { my $self = shift; return $$self[2]; }

sub depth { my $self = shift; return scalar @{$self->stack()}; }

# Return top entry of stack
sub tos
{
    my $self = shift;
    my $stack = $self->stack();
    return $$stack[$#$stack];
}


sub push
{
    my $self = shift;
    push @{$self->stack()}, @_;
    my $depth = $self->depth();
    ::dprint "ctx ", $self->label, " push (depth ", $depth, ")\n";
    return $depth;
}

sub pop
{
    my $self = shift;
    my $stack = $self->stack();
    my $oldLbl = pop @$stack;
    my $depth = scalar @$stack;
    ::dprint "ctx ", $self->label, " popping $oldLbl (depth ", $depth, ")\n";
    if ($depth == 0) {
	# stack underflow... create a new dummy record
	my $newLbl;
	if ($oldLbl eq 'init') {
	    $newLbl = 'init-1';
	} elsif ($oldLbl =~ /init-(\d+)/) {
	    $newLbl = sprintf "init-%d", $1 + 1;
	} else {
	    die "Stack underflow on unrecognized label: $oldLbl\n";
	}
	push @$stack, $newLbl;
    }
    return $oldLbl;
}

package Mode;

@Mode::ISA = ('StatUnit');

#
# This hash tracks all of the mode objects by label.
#
sub map
{
    return \%Mode::theMap;
}


#
# A Mode object is a two-element array:
#  0: label (string)
#  1: stats (array ref)
#
sub new
{
    my $class = shift;
    my $label = shift;
    my $self = bless [ $label, [ ] ], $class;
    return $self;
}

sub label { my $self = shift; return $$self[0]; }

sub stats { my $self = shift; return $$self[1]; }

package Function;

@Function::ISA = ('Mode');

#
# This hash tracks all of the function objects by label.
#
sub map
{
    return \%Function::theMap;
}

########################################################################
#
# End of object declarations; back to main code.
#
########################################################################
package main;

use vars qw($curCtx $curMode);

$curCtx = Context->new('initial-context');

$curMode = Mode->new('initial-mode');

while (<>)
{
    # dprint($_);
    next if /^#/;	# skip comments

    my ($label, $values) = split(':');

    # stip off leading & trailing whitespace
    $label =~ s/^\s//;
    $label =~ s/\s$//;

    # Split value string into array.  The "$_ + 0" forces conversion
    # from strings to ints.
    my @values = map { $_ + 0 } split(',', $values);

    # The first value is the absolute cycle number, which is not
    # useful to sum.  Strip it off here.
    my $cycle = shift @values;
    dprint "$label @ $cycle : ";

    # statistics values correspond to *current* interval (i.e., the
    # one specified by the *previous* label

    addValues($curMode->stats(), \@values);
    addValues(Function->get($curCtx->tos())->stats(), \@values);
    addValues($curCtx->stats(), \@values);

    if ($label =~ /^context (.*)/) {
	# context switch

	dprint $curCtx->label(), " --> $1";

	$curCtx = Context->get($1);

	dprint " (depth ", $curCtx->depth(), ")\n";
    }
    elsif ($label =~ /^mode (.*)/) {
	# kernel / user mode switch
	dprint $curMode->label(), "  --> $1\n";
	
	$curMode = Mode->get($1);
    }
    elsif ($label =~ /trap (5|6|11rei)/) {
	# Trap 5 is a DTB miss, trap 6 is a nested DTB miss, tap 11 is
	# an ITB miss.  Push on current stack.  Unlike other traps,
	# there is no rti associated with these, so don't push an
	# extra 'pal entry' record.
	$curCtx->push($label);
    }
    elsif ($label =~ /^trap (.*)/ ||
	   $label =~ /^callsys (.*)/) {
	# push on current stack, along with extra pal-entry marker
	$curCtx->push($label, "$label pal entry");
    }
    elsif ($label =~ /^callpal (.*)/) {
	# push on current stack, along with extra pal-entry marker
	$curCtx->push($label);
    }
    elsif ($label eq 'rti' || $label eq 'retsys' || $label eq 'rei') {
	# pop on current stack
	my $oldLabel = $curCtx->pop();
	if (($label eq 'rti' && $oldLabel !~ /^trap/) ||
	    ($label eq 'retsys' && $oldLabel !~ /^callsys/) ||
	    ($label eq 'rei' && ($oldLabel !~ /^callpal/ &&
				 $oldLabel !~ /trap (5|6|11rei)/ &&
				 $oldLabel !~ /pal entry/))) {
	    print "stack mismatch, ctx ", $curCtx->label(),
	      " $label $oldLabel\n";
	}
	if ($label eq 'rti' || $label eq 'retsys') {
	    $curCtx->push("$label pal entry");
	}
    }
    else {
	die "unrecognized label: $label\n";
    }
}


#
# Print summary information
#

print "Number of modes: ", Mode->numObjects(), "\n";

foreach my $mode (Mode->getAllByStat()) {
    print "\t", $mode->label(), " ";
    print join(' ', @{$mode->stats()});
    print "\n";
}

print "Number of contexts: ", Context->numObjects(), "\n";

foreach my $ctx (Context->getAllByStat()) {
    my $depth = $ctx->depth();
    print "\t", $ctx->label(), " depth $depth ";
    my $stats = $ctx->stats();
    print join(' ', @$stats);
    if ($opt_s) {
	my $stack = $ctx->stack();
	foreach my $i (@$stack) {
	    print "\n\t\t$i";
	}
    }
    print "\n";
}

print "Number of functions: ", Function->numObjects(), "\n";

foreach my $func (Function->getAllByStat()) {
    print "\t", $func->label(), " ";
    print join(' ', @{$func->stats()});
    print "\n";
}


