Netlist.pm 52.7 KB
Newer Older
1
2
#** @file Netlist.pm
# @verbatim
Christian Fibich's avatar
Christian Fibich committed
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#-------------------------------------------------------------------------------
#  University of Applied Sciences Technikum Wien
#
#  Department of Embedded Systems
#  http://embsys.technikum-wien.at
#
#  Josef Ressel Center for Verification of Embedded Computing Systems
#  http://vecs.technikum-wien.at
#
#-------------------------------------------------------------------------------
#  File:              Netlist.pm
#  Created on:        29.04.2015
#  $LastChangedBy$
#  $LastChangedDate$
#
#  Description:
#
20
#  FIJI Netlist class: Functions to instrument & export a Verilog::Netlist
Christian Fibich's avatar
Christian Fibich committed
21
#-------------------------------------------------------------------------------
22
23
# @endverbatim
#*
Christian Fibich's avatar
Christian Fibich committed
24

Christian Fibich's avatar
Christian Fibich committed
25
26
27
28
29
## @file Netlist.pm
# @brief Contains class \ref FIJI::Netlist

## @class FIJI::Netlist
# @brief Functions to instrument & export a Verilog::Netlist
30
31
32
33
34
package FIJI::Netlist;

use strict;
use warnings;

35
use Scalar::Util 'blessed';
36
use Log::Log4perl qw(get_logger :easy);
37
use File::Basename qw(basename);
38

39
40
use Verilog::Netlist 99.415;
use Verilog::Language 99.415;
41
42
43
44
use Data::Dumper;

use FIJI::VHDL;

Christian Fibich's avatar
Christian Fibich committed
45
use constant HIERSEP               => "|";
46
use constant FIJI_NAMESPACE_PREFIX      => "fiji_";
Christian Fibich's avatar
Christian Fibich committed
47
48
use constant FIJI_PORT_IN_POSTFIX  => "_inj_i";
use constant FIJI_PORT_OUT_POSTFIX => "_ori_o";
49
use constant MAX_UNIQUE_TRIES => 10;
50

Christian Fibich's avatar
Christian Fibich committed
51
use constant FIJI_LOGO => <<logo_end;
52
53
54
55
56
57
//  FIJIFIJIFIJIFIJIFIJIFIJIFIJIFIJIFIJIFIJI
//  FIJIFIJIFIJIFIJIF   FIJIFIJIFIJIFIJIFIJI
//  FIJIFIJIFIJIFIJ    IFIJIFIJIFIJIFIJIFIJI
//  FIJIF       FI           IJIFIJIFIJIFIJI
//  FIJIFIJIFI            JIFIJIFIJIFIJIFIJI
//  FIJIFIJI            FIJIFIJIFIJIFIJIFIJI
58
59
//  FIJIFI    JI   IFI   IJIFIJIFIJIFIJIFIJI
//  FIJIF   FIJ   JIFIJ   JIFIJIFIJIFIJIFIJI
60
61
62
63
64
65
66
67
68
69
//  FIJIFIJIFI   IJIFIJI   IFIJIFIJIFIJIFIJI
//  FIJIFIJIF    IJIFIJIFIJIFIJIFIJIFIJIFIJI
//  FIJIFIJI    FIJIFIJIFIJIFIJIFIJIFIJIFIJI
//  FIJIFIJ     FIJIF           FIJIFIJIFIJI
//  FIJIFI     IFI      Fault      IFIJIFIJI
//  FIJIF             InJection     FIJIFIJI
//  FIJ              Instrumenter    IJIFIJI
//  F                                    IJI
//  FIJIFIJIFIJIFIJIFIJIFIJIFIJIFIJIFIJIFIJI
logo_end
70

71
72
## @function public new ()
# @brief creates a new FIJI::Netlist object
Christian Fibich's avatar
Christian Fibich committed
73
#
74
75
# @returns the newly created FIJI::Netlist object
sub new {
Christian Fibich's avatar
Christian Fibich committed
76

77
    my ($class) = @_;
Christian Fibich's avatar
Christian Fibich committed
78

79
80
    my $self = {};
    bless $self, $class;
Christian Fibich's avatar
Christian Fibich committed
81

82
    $self->{'nl'} = new Verilog::Netlist(
Christian Fibich's avatar
Christian Fibich committed
83

84
85
86
87
88
89
        # options => $opt,
        # keep_comments => 1, # include comments in netlist
        link_read_nonfatal => 1,    # do not fail if module description not found
        use_vars           => 1,
    );
    return $self;
90
91
}

92
93
94
95
96
97
98
99
## @method public read_file ($filename)
# @brief Tries to read a Verilog netlist from the given file
#
# @param filename    The Verilog file to read
#
# @returns 1   if an error occurred
# @returns 0   if successful
sub read_file {
100
    my $logger = get_logger("");
Christian Fibich's avatar
Christian Fibich committed
101
    my ($self, $filename) = @_;
102

103
104
    ## Netlist synthesized from VHDL could contain SV keywords at this point.
    Verilog::Language::language_standard("1364-2001");
105

106
    $logger->info("Reading in netlist from file \"$filename\".");
107
    eval {
Christian Fibich's avatar
Christian Fibich committed
108
109
        $self->{'nl'}->read_file(filename => $filename);    # read Verilog file
        $self->{'nl'}->link();                              # Read in any sub-modules
110
    };
111

Christian Fibich's avatar
Christian Fibich committed
112
113
    if ($self->{'nl'}->errors() != 0 || $@) {
        $logger->error("Could not parse $filename!", $@ ? "\n" . $@ : "");
114
115
        return 1;
    }
116

117
    $self->{'filename'} = $filename;
118

119
120
    $logger->info("Successfully read in netlist from file \"$filename\".");
    return 0;
121
122
}

123
124
125
126
127
## @method public get_toplevel_port_names ()
# @brief retrieves the port names of all toplevel modules
#
# @returns an array of Verilog::Port references
sub get_toplevel_port_names {
Christian Fibich's avatar
Christian Fibich committed
128
    my ($self, $dir) = @_;
129
    my $ports_ref = [];
Christian Fibich's avatar
Christian Fibich committed
130
    foreach my $mod ($self->{'nl'}->top_modules_sorted) {
131
        foreach my $port ($mod->ports) {
Christian Fibich's avatar
Christian Fibich committed
132
133
134
135
            if (   !defined($dir)
                || ($dir eq "o" && $port->direction eq "out")
                || ($dir eq "i" && $port->direction eq "in"))
            {
Christian Fibich's avatar
Christian Fibich committed
136
137
                push @{$ports_ref}, $port->name;
            }
138
139
140
        }
    }
    return $ports_ref;
141
142
}

Christian Fibich's avatar
Christian Fibich committed
143
144
145
146
147
148
## @method public get_toplevel_module ()
# @brief retrieves the port names of all toplevel modules
#
# @returns a Verilog::Module reference
sub get_toplevel_module {
    my ($self) = @_;
Christian Fibich's avatar
Christian Fibich committed
149
150
151
152
153
    my @m      = $self->{'nl'}->top_modules_sorted;
    my $n      = @m;
    return $m[0] if ($n == 1);
    return "More than one toplevel module present in netlist." if ($n > 1);
    return "No toplevel module found.";
Christian Fibich's avatar
Christian Fibich committed
154
155
}

156
157
158
159
## @method public get_nets ()
# @brief retrieves all nets in the netlist
#
# @returns an array of hashes for all nets containing:
160
161
162
# 'name' the name of the net
# 'path' the hierarchical path of the net
# 'net'  the Verilog::Netlist::Net reference to the net
163
sub get_nets {
164
165
166
167
168
    my ($self) = @_;

    # my $nets_ref = {'metadata' => [], 'names' => [], 'nets' => []};
    my $nets_ref = [];
    my $hier     = "";
Christian Fibich's avatar
Christian Fibich committed
169
170
    foreach my $mod ($self->{'nl'}->top_modules_sorted) {
        $self->_get_subnets($nets_ref, $mod, $hier);
171
172
    }
    return $nets_ref;
173
174
}

175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
sub _extract_low_high {
    my ($in_low, $in_high) = @_;
    my ($out_low, $out_high);

    # msb might be lower than lsb if index range is "upto" -> swap
    if ($in_high < $in_low) {
        $out_low = $in_high;
        $out_high = $in_low;
    } else {
        $out_low = $in_low;
        $out_high = $in_high;
    }
    return ($out_low, $out_high);
}

190
191
192
193
194
195
196
197
198
#** @method private _get_subnets ($nets_ref,$mod,$hier)
# @brief retrieves all nets in the given module
#
# @param nets_ref    the central reference to push found nets (name,path,netref) to
# @param mod         the module to search
# @param hier        a string representing the current hierarchy level, separated
#                    be HIERSEP
sub _get_subnets {

199
    my $logger = get_logger("");
Christian Fibich's avatar
Christian Fibich committed
200
    my ($self, $nets_ref, $mod, $hier) = @_;
201

202
    my $thishier = $hier;
Christian Fibich's avatar
Christian Fibich committed
203
    $thishier .= HIERSEP if $thishier ne "";
204
    $thishier .= $mod->name;
205

Christian Fibich's avatar
Christian Fibich committed
206
    foreach my $n ($mod->nets) {
207
        if (defined($n->msb) && defined($n->lsb)) {
208
            my ($low, $high) = _extract_low_high($n->lsb, $n->msb);
209
            for (my $sub = $low ; $sub <= $high ; $sub++) {
Christian Fibich's avatar
Christian Fibich committed
210
                my $thisnet_ref = {name => $n->name . "[$sub]", path => $thishier, net => $n, index => $sub};
211
212
213
214
215
216
217
                push(@{$nets_ref}, $thisnet_ref);
            }
        } else {
            my $thisnet_ref = {name => $n->name, path => $thishier, net => $n};
            push(@{$nets_ref}, $thisnet_ref);
        }

218
    }
219

220
    foreach my $cell ($mod->cells) {
Christian Fibich's avatar
Christian Fibich committed
221
222
        if (defined($cell->submod)) {
            $self->_get_subnets($nets_ref, $cell->submod, $thishier);
223
        }
224
225
226
    }
}

227
228
229
## @function private _check_name_in_hierarchy ($startmod,$name)
# @brief checks if a given name exists
# checks if the $name exists as port, net, or cell name in the instantiation tree.
230
#
231
232
# @param startmod    the module to start with
# @param name        the name to check against
233
sub _check_name_in_hierarchy {
234

235
    my $logger = get_logger("");
Christian Fibich's avatar
Christian Fibich committed
236
    my ($startmod, $name) = @_;
237
238
    my $nl = $startmod->netlist;

239
    $logger->debug("Checking \"" . $startmod->name . "\" for name \"$name\"");
240
241

    # check if a net is named the same
242
    for my $net ($startmod->nets) {
Christian Fibich's avatar
Christian Fibich committed
243
        if ($net->name eq $name) {
244
            my $msg = "Name \"$name\" does already exist as net in " . $startmod->name;
245
            return $msg;
246
247
248
249
        }
    }

    # check if a port is named the same
250
    for my $port ($startmod->ports) {
Christian Fibich's avatar
Christian Fibich committed
251
        if ($port->name eq $name) {
252
            my $msg = "Name \"$name\" does already exist as port in " . $startmod->name;
253
            return $msg;
254
255
256
        }
    }

257
    for my $cell ($startmod->cells) {
Christian Fibich's avatar
Christian Fibich committed
258
        if ($cell->name eq $name) {
259
            my $msg = "Name \"$name\" does already exist as cell in " . $startmod->name;
260
            return $msg;
261
262
263
264
        }
    }

    # find any module instantiating the current start module
265
266
    foreach my $mod ($nl->modules) {
        foreach my $cell ($mod->cells) {
Christian Fibich's avatar
Christian Fibich committed
267
268
            if (defined $cell->submod && $cell->submod == $startmod) {
                my $msg = _check_name_in_hierarchy($mod, $name);
269
                return $msg if defined $msg;
270
271
272
            }
        }
    }
273

274
    return undef;
275
276
}

277
278
## @function private _add_port_to_hierarchy ($startmod,$name,$function,$index,$indent)
# @brief adds a port to all modules starting from a leaf node
279
#
280
281
282
283
284
285
286
287
# @param startmod    the module to start with
# @param name        the port name to be generated
# @param function    the function of this port in FIJI (FIJI::VHDL->FIJI_PORTTYPE_xxx)
# @param index       for ORIGINAL,MODIFIED and FAULT_DETECT: the index of this net
# @param indent      optional, needed just for formatting logging output
#
# @returns undef if the given port $name is already found
# @returns Verilog::Port reference to the new port if successful
Christian Fibich's avatar
Christian Fibich committed
288
sub _add_port_to_hierarchy {
289

290
    my $logger = get_logger("");
Christian Fibich's avatar
Christian Fibich committed
291
    my ($startmod, $name, $function, $index, $indent) = @_;
292
    my $nl        = $startmod->netlist;
293
    my $direction = "undef";
Christian Fibich's avatar
Christian Fibich committed
294
    if (!defined $indent) {
295
296
297
298
299
        $indent = "";
    } else {
        $indent .= "  ";
    }

Christian Fibich's avatar
Christian Fibich committed
300
    return undef if ($startmod->find_port($name));
301

302
    $logger->debug($indent . "Adding port \"$name\" to module \"" . $startmod->name . "\"");
303
304

    # decide direction
305
    if (   $function == FIJI::VHDL->FIJI_PORTTYPE_MODIFIED
Christian Fibich's avatar
Christian Fibich committed
306
        || $function == FIJI::VHDL->FIJI_PORTTYPE_RESET_TO_DUT)
307
    {
308
        $direction = "in";
309
    } else {
310
311
312
313
        $direction = "out";
    }

    # generate port
Christian Fibich's avatar
Christian Fibich committed
314
    my $np = $startmod->new_port(name => $name, direction => $direction);
315
316

    # set port type for wrapper generation
Christian Fibich's avatar
Christian Fibich committed
317
    $np->userdata(FIJI::VHDL->FIJI_USERDATA_PORTTYPE, $function);
318
319

    # set indices
320
    if (   $function == FIJI::VHDL->FIJI_PORTTYPE_MODIFIED
Christian Fibich's avatar
Christian Fibich committed
321
        || $function == FIJI::VHDL->FIJI_PORTTYPE_ORIGINAL)
322
    {
Christian Fibich's avatar
Christian Fibich committed
323
324
325
        $np->userdata(FIJI::VHDL->FIJI_USERDATA_FIU_INDEX, $index);
    } elsif ($function == FIJI::VHDL->FIJI_PORTTYPE_FAULT_DETECTION) {
        $np->userdata(FIJI::VHDL->FIJI_USERDATA_FD_INDEX, $index);
326
327
    }

Christian Fibich's avatar
Christian Fibich committed
328
329
    # let Verilog-Perl create a new net for the new port.
    $startmod->link;
330
331

    # find all modules instantiating the current module
Christian Fibich's avatar
Christian Fibich committed
332
    foreach my $mod ($nl->modules_sorted) {
333
        foreach my $cell ($mod->cells) {
Christian Fibich's avatar
Christian Fibich committed
334
            if (defined $cell->submod && $cell->submod == $startmod) {
335
336
                $logger->debug($indent . "Adding pin \"$name\" to cell \"" . $cell->name . "\"");
                $logger->debug($indent . "Connecting pin \"" . $cell->name . HIERSEP . $name . "\" to port \"" . $np->module->name . HIERSEP . $np->name . "\"");
337
338
339
                $cell->new_pin(
                    name     => $name,
                    portname => $np->name,
340
                    netnames => [{'netname' => $np->net->name}],
341
342
                );

Christian Fibich's avatar
Christian Fibich committed
343
                # let verilog-perl find the net and port.
Christian Fibich's avatar
Christian Fibich committed
344
                # @FIXME sufficient to link "mod" here?
Christian Fibich's avatar
Christian Fibich committed
345
                $mod->link;
Christian Fibich's avatar
Christian Fibich committed
346
                _add_port_to_hierarchy($mod, $name, $function, $index, $indent);
347
348
349
            }
        }
    }
350

351
352
353
    return $np;
}

354
355
356
## @method public net_add_function($net, $function, $port_name, $index)
# @brief Generate external access to a single net
#
Christian Fibich's avatar
Christian Fibich committed
357
358
359
360
361
362
# Performs the following steps:
#    1.  check if the default port name does not yet exist
#    1a. if it exists, generate a new net name
#    2.  add a port through the entire hierarchy
#    3.  assign the net to the port using a contassign statement
#
363
364
365
366
367
368
369
# @param net         the Verilog::Net object to be used
# @param function    the function out of FIJI::VHDL->FIJI_PORTTYPE_xxx
# @param port_name   how the port shall be named (will be prefixed with "fiji_")
# @param index       for some FIJI_PORTTYPEs, an index is needed (FIU and Fault Detect)
#
# @returns undef
sub net_add_function {
370
    my $logger = get_logger("");
Christian Fibich's avatar
Christian Fibich committed
371
    my ($self, $net, $function, $port_name, $index) = @_;
372

373
    $logger->debug("Adding function to \"" . $net->module->name . "\", net \"" . $net->name . "\"");
374
375

    my $prefix = "fiji_";
376
377
378
379
380

    my $unique_name = _unique_name($net->module,$prefix.$port_name);

    if (!defined $unique_name) {
        $logger->error("Could not find a unique name for prefix ".$prefix.$port_name)
381
382
    }

383
384
    $logger->debug("\"" . $unique_name . "\" can be used as fiji connector");
    my $op = _add_port_to_hierarchy($net->module, $unique_name, $function, $index);
385

386
    $logger->debug("Connecting Port \"" . $op->name . "\" to net \"" . $net->name . "\"");
387

Christian Fibich's avatar
Christian Fibich committed
388
    # connect the net to the newly created port
389
390
391
392
393
394
395
    $net->module->new_contassign(
        keyword => "assign",
        lhs     => $op->name,
        rhs     => $net->name,
        module  => $op->module,
        netlist => $op->module->netlist
    );
396

397
398
399
    return undef;
}

400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
# tries to generate a unique but recognizable net name by appending a
# random hex number if necessary
sub _unique_name {
    my $logger = get_logger("");
    my ($mod,$requested_name) = @_;

    # check if requested name is OK
    my $msg = _check_name_in_hierarchy($mod, $requested_name);
    
    if (!defined $msg) {
        return $requested_name;
    }

    # else try up to 10 times to generate a unique name by appending
    # a 4-digit random hex number
    for (my $tries = 0; $tries < MAX_UNIQUE_TRIES; $tries++) {
        my $name = sprintf("%s_%04x", $requested_name, rand(0xffff));
        $msg = _check_name_in_hierarchy($mod, $name);
        return $name if (!defined $msg);
    }
    
    return undef
}

424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
# take a possible escaped identifier and make it a legal _and_ sane verilog identifier
sub _sanitize_identifier {
    my $insane = shift;

    # Verilog allows "non-alphanumeric" characters in identifiers if they start with a backslash and end with whitespace (escaped identifiers) but we don't want to.
    my $sane = ($insane =~ s/[^a-zA-Z0-9_]+/_/gr);
    # VHDL signals must not contain multiple subsequent underscores
    $sane =~ s/__+/_/g;
    return $sane
}

sub generate_contassign {
    my $logger = get_logger("");
    my ($module, $lhs, $rhs) = @_;
    $logger->trace("Setting \"$lhs = $rhs\"");
    $module->new_contassign(
        keyword => "assign",
        lhs     => $lhs,
        rhs     => $rhs,
        module  => $module,
        netlist => $module->netlist
    );
}

448
449
450
451
## @method public instrument_net($net,$fiu_idx, $driver, $driver_type)
# @brief instruments a single net for fault injection
#
# This method performs the following steps
Christian Fibich's avatar
Christian Fibich committed
452
453
454
455
#   1. tries to determine the driver, or otherwise prompts the user to select it
#   2. generate external access output and input ports
#   3. interconnects these ports to the matching driver and driven cells
#
456
# @param net_path        the Verilog::Net to instrument
457
# @param fiu_idx         the FIU number this external access shall be connected to
458
459
# @param driver_path     the path to the driver of this net (optional but depends on driver_type)
# @param driver_type     the type of the driver (can be PIN, PORT, ASSIGN) (optional but depends on driver_path)
460
461
462
463
#
# @returns STRING          if an error occurred
# @returns undef           if successful
sub instrument_net {
464

465
    my $logger = get_logger("");
466
    my ($self, $net_path, $fiu_idx, $driver_path, $driver_type) = @_;
467
    my $msg;
468

469
    # split hierarchical net path
470
    my $net_descriptor = $self->get_netdescriptor_from_path($net_path);
471
472

    if (ref($net_descriptor) ne "HASH") {
473
        return $net_descriptor;
474
475
476
477
478
    }

    my $net = $net_descriptor->{'net'};
    my $msb = $net_descriptor->{'msb'};
    my $lsb = $net_descriptor->{'lsb'};
479
    my $mod = $net_descriptor->{'mod'};
480
481
482
    my $idx = '';
    my $idx_postfix = '';

483
484
485
486
487
488
    # We need to produce names for the i/o ports that route the signals
    # to the FIC. To allow to instrument multiple indices of a single
    # signal we need to make these names unique thus we even include the
    # indices if used.
    if (defined $msb && defined $lsb) {
        if ($msb ne $lsb) {
489
490
491
492
            # We dont support the instrumentation of vectors (only sinlge indices of busses).
            return "The given net to instrument is a vector with multiple bits.\nThis is not supported.\nMay you want to instrument a single bit of said vector instead?";
            # $idx         = "[".$msb.":".$lsb."]";
            # $idx_postfix = "_".$msb."_".$lsb."_";
493
        } else {
494
495
            $idx         = "[".$msb."]";
            $idx_postfix = "_".$msb."_";
496
497
498
        }
    }

499
    $logger->info("Instrumenting \"" . $net->module->name . "\", net \"" . $net->name.$idx . "\"");
500

501
502
503
504
    my $output_name = (FIJI_NAMESPACE_PREFIX . $net->name . $idx_postfix . FIJI_PORT_OUT_POSTFIX);
    $output_name = _sanitize_identifier($output_name);
    my $input_name  = (FIJI_NAMESPACE_PREFIX . $net->name . $idx_postfix . FIJI_PORT_IN_POSTFIX);
    $input_name = _sanitize_identifier($input_name);
505

506
    # generate unique name for output port, return with error message if that fails
507
    my $unique_output_name = _unique_name($mod, $output_name);
508
    return "Could not generate unique name for prefix $output_name" if (!defined $unique_output_name);
509

510
    $logger->debug("\"" . $unique_output_name . "\" will be used as fiji connector (output)");
511
    my $op = _add_port_to_hierarchy($mod, $unique_output_name, FIJI::VHDL->FIJI_PORTTYPE_ORIGINAL, $fiu_idx);
512

513
514
    # generate unique name for input port, return with error message if that fails
    my $unique_input_name = _unique_name($mod, $input_name);
515
    return "Could not generate unique name for prefix $input_name" if (!defined $unique_input_name);
516

517
    $logger->debug("\"" . $unique_input_name . "\" will be used as fiji connector (input)");
518
    my $ip = _add_port_to_hierarchy($mod, $unique_input_name, FIJI::VHDL->FIJI_PORTTYPE_MODIFIED, $fiu_idx);
519

520
    my %connections;
521
    my $rv = $self->_get_net_connections($net, \%connections, $msb, $driver_path, $driver_type);
522
    return $rv if (defined $rv);
523

524
    # connecting newly created output to driver
Christian Fibich's avatar
Christian Fibich committed
525
526
    foreach my $connection (@{$connections{'drivers'}}) {
        if (ref($connection) eq "Verilog::Netlist::Pin") {
527
528
529
530
531
532
533
            # FIXME: handle concatenations
            # For buses we introduce a dedicated temporary wire to re-route/inject single bits of it.
            # Therefore we can simply leave them alone here.
            if (defined($lsb) && defined($msb)) {
                $logger->warn("Ignoring Pin \"" . $connection->cell->name . HIERSEP . $connection->name . "\" because instrumented net \"" . $net->name . "\" is a bus.");
                next;
            }
534

535
            # If the driver is a pin of a cell, connect this pin to the newly created net
536
            $logger->debug("Original: Connecting (output) pin \"" . $connection->cell->name . HIERSEP . $connection->name . "\" to generated output \"" . $op->name . "\"");
537
            for my $netname (@{$connection->netnames}) {
Christian Fibich's avatar
Christian Fibich committed
538
539

                # @FIXME work to be done for Buses
540
541
542
543
544
545
546
547
                if (($netname->{'netname'} eq $net->name) && 
                     (!defined $netname->{lsb} || $netname->{lsb} eq $lsb) &&
                     (!defined $netname->{msb} || $netname->{msb} eq $msb)) {
                    $netname->{'netname'} = $op->net->name;
                    # there will never be an indexed newly created port (only single-bit FIUs)
                    $netname->{lsb} = undef;
                    $netname->{msb} = undef;
                }
548
            }
Christian Fibich's avatar
Christian Fibich committed
549

550
            #$connection->net(undef);     # resolved by link
551
            $connection->port(undef);    # resolved by link
552

Christian Fibich's avatar
Christian Fibich committed
553
        } elsif (ref($connection) eq "Verilog::Netlist::Port") {
554

555
                # @FIXME work to be done for Buses
556
            # if it is a port of a module, connect this port to the newly created net
557
            $logger->debug("Original: Connecting (input) port \"" . $connection->name . "\" to generated output \"" . $op->name . "\"");
Christian Fibich's avatar
Christian Fibich committed
558
            $connection->net($op->net);
559
            $mod->new_contassign(
560
561
                keyword => "assign",
                lhs     => $op->name,
562
                rhs     => $connection->name.$idx,
563
564
                module  => $mod,
                netlist => $mod->netlist
565
            );
566
        } elsif (ref($connection) eq "Verilog::Netlist::ContAssign") {
567
            # Retrieve net object of LHS of the assignment to determine if it is a bus and if the assignment is to the complete net or a single bit.
568
569
570
            my $lhs_elems = $self->_extract_netstring_elements($connection->lhs);
            my $lhs_net_name = $lhs_elems->{'net_name'};
            my $lhs_net = $mod->find_net($lhs_net_name);
571
            if (!defined($lhs_net)) {
572
573
574
575
576
577
578
                my $lhs_port = $mod->find_port($lhs_net_name);
                if (!defined($lhs_port)) {
                    return "Could not find net or port in module \"" . $mod->name . "\" matching LHS of assignment \"" . $connection->lhs . "\" = \"" . $connection->rhs . "\"";
                }
                # FIXME: so this is actually a port...
                $logger->fatal("Found port name in continuous assignment. This is not supported yet.");
                return "BORKED";
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
            }
            if (!defined($lhs_net->msb)) {
                # If the signal in LHS is not a vector at all we simply drive the new port instead, easy.
                $connection->lhs($op->name);
                $logger->debug("Original: Connecting to generated output \"" . $op->name . "\" continuous assignment of \"" . $connection->rhs . "\"");
            } else {
                # If LHS is a bus however we need more effort.
                # We need to extract the bit we want and drive the new port, but
                # also continue to drive the remaining bits of the vector just like before
                # e.g. when we want to tap [1] of \dumb.non.hierarchical_bus then we need to transform this:
                #   wire   [3:0] wirebus;
                #   wire   [3:0] \dumb.non.hierarchical_bus ;
                #   assign \dumb.non.hierarchical_bus = ~wirebus;
                # into this:
                #   wire   [3:0] wirebus;
                #   wire   [3:0] \dumb.non.hierarchical_bus ;
                #   wire   [3:0] tmp_hierarchical_bus;
                #   assign tmp_hierarchical_bus = ~wirebus;
                #   assign tmp_signal_o = tmp_hierarchical_bus[1];
                #   assign \dumb.non.hierarchical_bus[0] = tmp_hierarchical_bus[0];
                #   assign \dumb.non.hierarchical_bus[1] = tmp_signal_i;
                #   assign \dumb.non.hierarchical_bus[2] = tmp_hierarchical_bus[2];
                #   assign \dumb.non.hierarchical_bus[3] = tmp_hierarchical_bus[3];
                # However, we just need to create the temporary bus once even if more than one bit of it get instrumented...

                my ($op_rhs, $ip_lhs);
                # If the LHS is a bit range of a vector we have either
                # - generated the net earlier (in the else branch below) or,
                # - it was a bit-wise assignment in the original netlist as well.
                # In any case we only need to generate a temporary net if the assignment is not to a bit of a vector.
609
                if (defined($lhs_elems->{'lsb'})) {
610
611
612
                    $op_rhs = $connection->rhs;
                    $ip_lhs = $connection->lhs;
                } else {
613
                    my $tmp_name = FIJI_NAMESPACE_PREFIX . $lhs_net->name . "_tmp";
614
                    my $unique_tmp_name = _unique_name($mod, $tmp_name);
615
                    return "Could not generate unique name for prefix ".$tmp_name if (!defined $unique_tmp_name);
616
617
618

                    # Generate intermediate (tmp) bus and assign old RHS to it
                    $logger->debug("Generating intermediate bus to connect split up result of \"" . $connection->rhs . "\"");
619
                    my $tmp_bus = $mod->new_net(
620
                        name => _sanitize_identifier($unique_tmp_name),
621
622
623
                        msb => $lhs_net->msb,
                        lsb => $lhs_net->lsb,
                    );
624
                    generate_contassign($mod, $tmp_bus->name, $connection->rhs);
625
626
627
628
629

                    # Connect the individual bits of the tmp bus with the (previous) LHS that we don't want to instrument
                    my ($low, $high) = _extract_low_high($lhs_net->lsb, $lhs_net->msb);
                    for (my $i = $low ; $i <= $high ; $i++) {
                        if ($i != $msb) {
630
                            generate_contassign($mod, $connection->lhs."[".$i."]", $tmp_bus->name."[".$i."]");
631
632
633
634
635
636
637
                        }
                    }
                    $op_rhs = $tmp_bus->name . "[".$msb."]";
                    $ip_lhs = $connection->lhs."[".$msb."]";
                }
                # Connect requested bit of the tmp bus with the output port
                $logger->debug("Original: Adding assignment \"" . $op->name . " = " . $op_rhs . "\"");
638
                generate_contassign($mod, $op->name, $op_rhs);
639
640
641
642
643
644
645

                $logger->debug("Modified: Adding assignment \"" . $ip_lhs . " =  " . $ip->name . "\"");
                $connection->rhs($ip->name);
                $connection->lhs($ip_lhs);
            }
        } else {
            $logger->debug("Driver instance is neither pin, port nor contassign?");
646
        }
647

Christian Fibich's avatar
Christian Fibich committed
648
        # create interconnections for newly created port/pin
Christian Fibich's avatar
Christian Fibich committed
649
        # @TODO needed here or OK linking once after loop?
650
        # $mod->link;
651
652
    }

653
654
655
656
    # create interconnections for newly created port/pin
    # @TODO needed here or OK linking once after all loops?
    # $mod->link;
    
657
    # exactly the same for the input
658
    # connecting newly created input to driven cells
Christian Fibich's avatar
Christian Fibich committed
659
660
    foreach my $connection (@{$connections{'driven'}}) {
        if (ref($connection) eq "Verilog::Netlist::Pin") {
661
            for my $netname (@{$connection->netnames}) {
662
663
                if ($netname->{'netname'} eq $net->name) {
                    # FIXME: we'll ignore all indexed nets for now but that certainly is not right... or is it?
664
665
666
                    if (!defined($lsb) && !defined($msb)) {
                        $logger->warn("Modified: Connecting (input) pin \"" . $connection->cell->name . HIERSEP . $connection->name . "\" to generated input \"" . $ip->name . "\"");
                        $netname->{'netname'} = $ip->net->name;
Christian Fibich's avatar
Christian Fibich committed
667

668
669
670
671
672
673
                        #$connection->net(undef);     # resolved by link
                        $connection->port(undef);    # resolved by link

                    # } else {
                     # $netname->{lsb} eq $lsb) &&
                     # $netname->{msb} eq $msb)) {
674
                    # there will never be an indexed newly created port (only single-bit FIUs)
675
676
677
                    # $netname->{lsb} = undef;
                    # $netname->{msb} = undef;
                    }
678
                }
679
            }
Christian Fibich's avatar
Christian Fibich committed
680
        } elsif (ref($connection) eq "Verilog::Netlist::Port") {
681
                # @FIXME work to be done for Buses
682
            $logger->debug("Modified: Connecting (output) port \"" . $connection->module->name . HIERSEP . $connection->name . "\" to generated input \"" . $ip->name . "\"");
683
            $mod->new_contassign(
684
                keyword => "assign",
685
                lhs     => $connection->name.$idx,
686
                rhs     => $ip->name,
687
688
                module  => $mod,
                netlist => $mod->netlist
689
            );
690
        } elsif (ref($connection) eq "Verilog::Netlist::ContAssign") {
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
            # Retrieve net object of LHS of the assignment to determine if it is a bus and if the assignment is to the complete net or a single bit.
            my $lhs_elems = $self->_extract_netstring_elements($connection->lhs);
            my $lhs_net_name = $lhs_elems->{'net_name'};
            my $lhs_net = $mod->find_net($lhs_net_name);
            if (!defined($lhs_net)) {
                my $lhs_port = $mod->find_port($lhs_net_name);
                if (!defined($lhs_port)) {
                    return "Could not find net or port in module \"" . $mod->name . "\" matching LHS of assignment \"" . $connection->lhs . "\" = \"" . $connection->rhs . "\"";
                }
                # FIXME: so this is actually a port...
                $logger->fatal("Found port name in continuous assignment. This is not supported yet.");
                return "BORKED";
            }
            if (!defined($lhs_net->msb)) {
                # If the signal in LHS is not a vector at all we simply assign the injected net from the new port, easy.
706
707
708
709
710
                # However, we need to check for inversions on the RHS and conserve them
                $connection->rhs =~ /^[ \t]*(~)/;
                my $new_rhs = $1 . $ip->name;
                $connection->rhs($new_rhs);
                $logger->debug("Modified: Connecting to generated input \"$new_rhs\" in continuous assignment to \"" . $connection->lhs . "\"");
711
712
713
714
715
            } else {
                # FIXME: if LHS is a bus possibly containing one or more wires we need to instrument, we may need to use a temp wire to preserve the old values like for drivers above - I think.
                # $logger->warn("*Would* set RHS of \"" . $connection->lhs . " = " . $connection->rhs . "\" to \"$input_name\"");
                # $connection->rhs($input_name);
            }
716
717
        } else {
            $logger->debug("Driven instance is neither pin, port nor contassign?");
718
719
        }
    }
720
721

    # create interconnections for newly created ports/pins
Christian Fibich's avatar
Christian Fibich committed
722
    # @TODO OK linking once after loop?
723
    $mod->link;
724

725
    # Clean up "loose" wires:
726
    # If we instrument nets that are only wired through this module from and into others the need for the intermediate wire is removed by the introduction of our instrumentation pins
727
728
729
730
    my %instrumented_connections;
    $rv = $self->_get_net_connections($net, \%instrumented_connections, $msb, $driver_path, $driver_type);
    return $rv if (defined $rv);

731
    if (scalar(@{$instrumented_connections{'driven'}}) == 0 && scalar(@{$instrumented_connections{'drivers'}}) == 0 && scalar(@{$instrumented_connections{'connected'}}) == 0) {
732
        $logger->warn("Instrumenting \"" . $mod->name . "\", net \"" . $net->name.$idx . "\" has lead to a loose wire - removing.");
733
        $net->delete();
734
        $mod->link;
735
    }
736
737
738
    return undef;
}

739
740
741
## @method public validate_driver($net_path, $driver_path, $driver_type)
# @brief Check if the given driver is valid for the given net
#
742
743
# Check if the driver specified by $driver_type and $driver_path
# is actually connected to the net specified by $net_path
744
745
746
747
748
749
750
#
# @param net_path        The hierarchical path of the net, separeted by HIERSEP
# @param driver_path     The hierarchical path of the driver object, separated by HIERSEP
# @param driver_type     The type of the driver object, one of {PIN, PORT, ASSIGN}
#
# @returns STRING          if an error occurred
# @returns undef           if successfull
751
sub _validate_driver {
752
    my $logger = get_logger("");
Christian Fibich's avatar
Christian Fibich committed
753
    my ($self, $net_path, $driver_path, $driver_type) = @_;
754

Christian Fibich's avatar
Christian Fibich committed
755
    my $connection_object = $self->get_connection_object($driver_path, $driver_type);
756
    my $connections       = {};
757
    $self->_get_net_connections_from_path($net_path, $connections);
758

759
760
    goto FAIL if (!defined $connection_object);

Christian Fibich's avatar
Christian Fibich committed
761
762
    my @in_drivers     = grep { $_ == $connection_object } @{$connections->{'drivers'}};
    my @in_connections = grep { $_ == $connection_object } @{$connections->{'connected'}};
763

764
    goto FAIL if (@in_drivers == 0 && @in_connections == 0);
765
766

    return undef;
767
768
769
770
771

FAIL:
    my $msg = "No possible driver found";
    $logger->error($msg);
    return $msg;
772
773
}

774
775
776
777
778
779
780
781
782
## @function private _select_driver($connected,$net)
# @brief Prompt the user to select a driver for a net from a set of given cells/outputs
#
# @param connected       list reference containing connected Verilog::Perl instances
# @param net             the Verilog::Perl::Net instance to select the driver for
#
# @returns STRING          if an error occurred
# @returns Driver object   if successful
sub _select_driver {
Christian Fibich's avatar
Christian Fibich committed
783
    my ($connected, $net) = @_;
784

785
    print "Select driver for net " . $net->name . ": \n";
786
    my $di;
Christian Fibich's avatar
Christian Fibich committed
787
788
    for ($di = 0 ; $di < @{$connected} ; $di++) {
        printf("[%d] %s\n", $di, FIJI::Netlist->_connection_tostr(@{$connected}[$di]));
789
    }
Christian Fibich's avatar
Christian Fibich committed
790
    printf("[x] none of the above.\n", $di);
791
    my $sel;
792
    while (1) {
793
        $sel = <STDIN>;
Christian Fibich's avatar
Christian Fibich committed
794
        if ($sel =~ m/[0-9]+/ && defined @{$connected}[$sel]) {
795
            last;
Christian Fibich's avatar
Christian Fibich committed
796
        } elsif ($sel =~ m/[xX]/) {
797
            my $msg = "No driver selected for net " . $net->name;
798
            return $msg;
799
800
        } else {
            print "Invalid driver.\n";
801
802
803
        }
    }
    return @{$connected}[$sel];
804
805
}

806
807
808
## @method private _connection_tostr ($connection,$conn_str_list_ref)
# @brief Stringifies a connection information
#
Christian Fibich's avatar
Christian Fibich committed
809
# The string is in the format \<TYPE\>: \<PATH|TO|Netname\>
810
# Where '|' can be any HIERSEP and TYPE is one of {PIN, PORT, ASSIGN}
811
# and optionally pushes a hash {path=>...,type=>...,} onto the list @$conn_str_list_ref
812
#
813
814
815
# @param connection          the connection to print
# @param conn_str_list_ref   optional list where a hash describing the connection is pushed
#
Christian Fibich's avatar
Christian Fibich committed
816
# @returns STRING  in the format \<TYPE\>: \<PATH|TO|Netname\>
817
sub _connection_tostr {
Christian Fibich's avatar
Christian Fibich committed
818
    my ($self, $connection, $conn_str_list_ref) = @_;
819
820
    my $path;
    my $type;
821
    my $str;
822

Christian Fibich's avatar
Christian Fibich committed
823
    if (ref($connection) eq "Verilog::Netlist::Pin") {
824
        $path = $connection->cell->module->name . HIERSEP . $connection->cell->name . HIERSEP . $connection->name;
825
        $type = "PIN";
826
        $str = $type . ": " . $path
Christian Fibich's avatar
Christian Fibich committed
827
    } elsif (ref($connection) eq "Verilog::Netlist::Port") {
828
        $path = $connection->module->name . HIERSEP . $connection->name;
829
        $type = "PORT";
830
        $str = $type . ": " . $path
831
    } elsif (ref($connection) eq "Verilog::Netlist::ContAssign") {
832
        $path = $connection->module->name . HIERSEP . $connection->rhs;
833
        $type = "ASSIGN";
834
        $str = $type . ": " . $connection->rhs;
835
    }
836
837
    push @{$conn_str_list_ref}, {path => $path, type => $type} if defined $conn_str_list_ref;
    return $str
838
839
}

840
841
842
## @method public get_connection_object ($connection_path,$connection_type)
# @brief Retrieves the connection object specified by path and type
#
843
# Retrieves a reference to the Verilog::Pin, Verilog::Port or Verilog::ContAssign
844
845
846
847
848
# Object specified by the parameters
#
# @param connection_path     the hierarchichal PATH|To|the|object
# @param connection_type     the type of the object {PIN,PORT,ASSIGN}
#
849
# @returns the Verilog::Pin, Verilog::Port or Verilog::ContAssign Object specified by the parameters
850
sub get_connection_object {
851
    my $logger = get_logger("");
Christian Fibich's avatar
Christian Fibich committed
852
    my ($self, $connection_path, $connection_type) = @_;
853
854

    my $rv;
855
    my $SEP = HIERSEP;
856

Christian Fibich's avatar
Christian Fibich committed
857
    if ($connection_type eq "PIN") {
858
        if ($connection_path =~ /^(.+)\Q$SEP\E(.+)\Q$SEP\E(.+)$/) {
859

860
            $logger->debug("Looking for pin named \"$3\" in cell \"$2\" of module \"$1\"...");
861
862

            my $mod  = $self->{'nl'}->find_module($1);
Christian Fibich's avatar
Christian Fibich committed
863
864
            my $cell = $mod->find_cell($2) if (defined $mod);
            my $pin  = $cell->find_pin($3) if (defined $cell);
865
866
            $rv = $pin;
        }
Christian Fibich's avatar
Christian Fibich committed
867
    } elsif ($connection_type eq "PORT") {
868
        if ($connection_path =~ /^(.+)\Q$SEP\E(.+)$/) {
869

870
            $logger->debug("Looking for port named \"$2\" in module \"$1\"...");
871

872
            my $mod = $self->{'nl'}->find_module($1);
Christian Fibich's avatar
Christian Fibich committed
873
            my $port = $mod->find_port($2) if (defined $mod);
874
875
            $rv = $port;
        }
Christian Fibich's avatar
Christian Fibich committed
876
    } elsif ($connection_type eq "ASSIGN") {
877
        if ($connection_path =~ /^(.+)\Q$SEP\E(.+)$/) {
878
            my $lhs = $2;
879

880
            $logger->debug("Looking for assignment to/from \"$2\" in module \"$1\"...");
881
            my $mod = $self->{'nl'}->find_module($1);
882

Christian Fibich's avatar
Christian Fibich committed
883
            if (defined $mod) {
884
                my $assign;
885
886
                for my $a (grep { $_->isa("Verilog::Netlist::ContAssign") } $mod->statements) {
                    if ($a->lhs eq $lhs || $a->rhs =~ /\Q$lhs\E/) {
887
                        $assign = $a;
888
                        $logger->debug(sprintf("Constant assignment: \"%s\" = \"%s\"", $a->lhs, $a->rhs));
889
890
891
                        last;
                    }
                }
892
                $rv = $assign;
893