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
###############################################################################
# Copyright (c) 2011-2024 by Altair Engineering, Inc.
# All rights reserved.
#
# Altair Engineering, Inc. makes this software available as part of the Vision
# tool platform.  As long as you are a licensee of the Vision tool platform
# you may make copies of the software and modify it to be used within the
# Vision tool platform, but you must include all of this notice on any copy.
# Redistribution without written permission to any third party, with or
# without modification, is not permitted.
# Altair Engineering, Inc. does not warrant that this software is error free
# or fit for any purpose.  Altair Engineering, Inc. disclaims any liability for
# all claims, expenses, losses, damages and costs any user may incur as a
# result of using, copying or modifying the software.
# =============================================================================
#   @plugin
#       Calculate Area
#   @namespace
#       CalculateArea
#   @section
#       Analyze the Loaded Database
#   @description
#       Add a main menu entry to calculate the estimated chip area.
#
#       Add a comment to the top module with the total area.
#
#       A text report with details about the chip area consumption can be
#       created.
#   @configuration
#   @license
#       permit spice
#   @files
#       calculateArea.tcl
#   @example
#       demo/spice/alu8bit.sp
#   @cmdline
#       -hspice @example[0]
#       -userware @files[0]
#   @tag
#       spice dspf parasitic spf
###############################################################################


# =============================================================================
# Init - Initialize the plugin.
# =============================================================================
#
proc CalculateArea:Init {} {
    gui plugin addConfig CalculateArea wName "w" text \
        "Name of the width attribute."
    gui plugin addConfig CalculateArea mName "m" text \
        "Name of the multiplier attribute."
    gui plugin addConfig CalculateArea lName "l" text \
        "Name of the length attribute."
    gui plugin addConfig CalculateArea laName "p_la" text \
        "Name of the length adder attribute."

    ##
    # Add a menu entry.
    #
    gui menu command {"Userware" "Calculate Area"} \
        [list CalculateArea:Start true]
    gui menu command {"Userware" "Write Area Report"} \
        [list CalculateArea:WriteAreaReport]
}


# =============================================================================
# Finit - Finalize the plugin.
# =============================================================================
#
proc CalculateArea:Finit {} {
    ##
    # Undo modifications of the GUI.
    #
    gui menu removeEntry {"Userware" "Calculate Area"}
    gui menu removeEntry {"Userware" "Write Area Report"}
}


# =============================================================================
# Start - This procedure loops over all NMOS and PMOS instances of all top
#         modules and calculates the estimated chip area.
# =============================================================================
#
proc CalculateArea:Start {interactive} {
    ##
    # Return if the database is empty.
    #
    set db [gui database get]
    if {$db == {}} {
        return
    }

    ##
    # Flag all cells in the database that should be included in the area
    # calculation.
    #
    CalculateArea:_flagDatabase $db

    ##
    # Get the top module OID of the loaded design.
    #
    set top [CalculateArea:_getTop $db]

    ##
    # Calculate the p-area:
    #   Loop over all PMOS instances (the cell is flagged red) and count
    #   the area of each pmos transistor.
    #
    set pArea 0
    $db flat foreach instOfCell red $top inst {
        set pArea [expr {$pArea + [CalculateArea:_area $db $inst]}]
    }

    ##
    # Calculate the n-area:
    #   Loop over all NMOS instances (the cell is flagged blue) and count
    #   the area of each nmos transistor.
    #
    set nArea 0
    $db flat foreach instOfCell blue $top inst {
        set nArea [expr {$nArea + [CalculateArea:_area $db $inst]}]
    }

    ##
    # Calculate the RC-area:
    #   Loop over all Res and Cap instances (the cell is flagged green)
    #   and count the area of each R/C device.
    #
    set rcArea 0
    $db flat foreach instOfCell green $top inst {
        set rcArea [expr {$rcArea + [CalculateArea:_area $db $inst]}]
    }

    ##
    # Calculate the total area.
    #
    set totalArea [expr {($pArea + $nArea) + $rcArea}]

    ##
    # If running interactive (e.g. invoked from the main menu), then
    # show the result in a dialog window. Otherwise print the calculated area
    # to the Console (and Message) window.
    #
    if {$interactive} {
        set t [toplevel .calculateAreaResult]
        ttk::label $t.label -text "Total Area = $totalArea"
        ttk::button $t.ok -text "OK" -command [list destroy $t]
        pack $t.label -side top -padx 5 -pady 2
        pack $t.ok    -side top -padx 5 -pady 2
        gui window modelessDialog $t "Total Area" \
            -place "MOUSE" \
            -onTop \
            -closeCallback "destroy $t"
    } else {
        gui console print "totalArea=$totalArea"
    }

    ##
    # Add an @comment attribute to store the calculated area somewhere.
    #
    set    comment "pArea=$pArea\n"
    append comment "nArea=$nArea\n"
    append comment "rcArea=$rcArea\n"
    append comment "totalArea=$totalArea"
    $db attr $top set "@comment=$comment"

    ##
    # Inform the GUI that the attributes (@comment) have changed.
    #
    gui attribute changed
}


# =============================================================================
# WriteAreaReport - Write a detailed report of the area consumption.
# =============================================================================
#
proc CalculateArea:WriteAreaReport {} {
    ##
    # Return if the database is empty.
    #
    set db [gui database get]
    if {$db == {}} {
        return
    }

    ##
    # Get the output file name.
    #
    set fname [gui window fileDialog saveFile \
        "Save Area Report" {{"Text Files" .txt}}]
    if {$fname == ""} {
        return
    }

    ##
    # Flag all cells in the database that should be included in the area
    # calculation.
    #
    CalculateArea:_flagDatabase $db

    ##
    # Get the top module OID of the loaded design.
    #
    set top [CalculateArea:_getTop $db]

    array set _total {}

    ##
    # Loop over all instances with the 'yellow' flag set and calculate the
    # total width for all instances of the same model and length.
    #
    set colWidth 0
    $db flat foreach instOfCell "yellow" $top inst {
        ##
        # Get the model name of this device.
        #
        set cell [$db oid cname $inst]

        ##
        # Calculate the column width of the first column.
        #
        set len  [string length $cell]
        if {$len > $colWidth} {
            set colWidth $len
        }

        ##
        # Get the width and the length for this device.
        #
        set width  [CalculateArea:_getWidth  $db $inst]
        set length [CalculateArea:_getLength $db $inst]

        ##
        # Initialize the variable holding the total width for this
        # cell type and length.
        #
        if {![info exists _total($cell:$length)]} {
            set _total($cell:$length) 0
        }

        ##
        # Update the total width for this cell type and length.
        #
        set _total($cell:$length) [expr {$_total($cell:$length) + $width}]
    }

    ##
    # Open the output file for writing.
    #
    set out [open $fname "w"]

    ##
    # Print the header of the result table.
    #
    if {$colWidth < 12} {
        set colWidth 12
    }
    puts $out [format "%*s %20s %20s %20s" $colWidth \
                      "<Cell Type>" "<Length>" "<Total Width>" "<Total Area>"]

    ##
    # Loop over the result hash table sorted by the key.
    #
    foreach key [lsort [array names _total]] {
        ##
        # The key is the cell type and the length separated by a colon.
        # Extract the cell type and the length from the key.
        #
        set colPos   [string last ":" $key]
        set cellType [string range $key 0 $colPos-1]
        set length   [string range $key $colPos+1 end]

        ##
        # The width is the value for this key.
        #
        set width $_total($key)

        ##
        # The consumed area is the product of the length and the width.
        #
        set totalArea [expr {$length * $width}]

        ##
        # Print a formatted row showing the values for this entry.
        #
        puts $out [format "%*s %20e %20e %20e" $colWidth \
                          $cellType $length $width $totalArea]
    }

    ##
    # close the output file.
    #
    close $out
}


# -----------------------------------------------------------------------------
# _area - Get the W, L and M values of the given instance. Calculate the
#         estimated chip area by multiplying: ((M * W) * L).
# -----------------------------------------------------------------------------
#
proc CalculateArea:_area {db inst} {
    ##
    # Get the width and the length for this device.
    #
    set width  [CalculateArea:_getWidth  $db $inst]
    set length [CalculateArea:_getLength $db $inst]

    ##
    # Return the calculated area.
    #
    return [expr {$width * $length}]
}


# -----------------------------------------------------------------------------
# _getWidth - Return the width for the given device.
# -----------------------------------------------------------------------------
#
proc CalculateArea:_getWidth {db inst} {
    ##
    # Get the width and the multiplier attribute name.
    #
    set wName [gui plugin getConfigValue CalculateArea wName]
    set mName [gui plugin getConfigValue CalculateArea mName]

    ##
    # Get the width and the multiplier factor of this device.
    #
    set width      [CalculateArea:_getAttrValue $db $inst $wName 0]
    set multiplier [CalculateArea:_getAttrValue $db $inst $mName 1]

    return [expr {$multiplier * $width}]
}


# -----------------------------------------------------------------------------
# _getLength - Return the length for the given device.
# -----------------------------------------------------------------------------
#
proc CalculateArea:_getLength {db inst} {
    ##
    # Get the length and the length adder attribute name.
    #
    set lName  [gui plugin getConfigValue CalculateArea lName]
    set laName [gui plugin getConfigValue CalculateArea laName]

    ##
    # Get the length and the length adder of this device.
    #
    set length      [CalculateArea:_getAttrValue $db $inst $lName  0]
    set lengthAdder [CalculateArea:_getAttrValue $db $inst $laName 0]

    ##
    # Return the length of this device.
    #
    return [expr {$length + $lengthAdder}]
}


# -----------------------------------------------------------------------------
# _getAttrValue - Get the value for the given attribute name at the given
#                 instance. If the requested attribute is not set at the
#                 instance then the default value is returned.
# -----------------------------------------------------------------------------
#
proc CalculateArea:_getAttrValue {db inst attrName defaultValue} {
    ##
    # First try to get the value for the attribute name as given to this
    # procedure without any modifications.
    #
    set val [$db flatattr $inst getMergedValue $attrName]

    ##
    # If no value was found then try to find a value for the attribute name
    # using lower case characters.
    #
    if {$val == ""} {
        set val [$db flatattr $inst getMergedValue [string tolower $attrName]]
    }

    ##
    # If still no value was found then try to find a value for the attribute
    # name using upper case characters.
    #
    if {$val == ""} {
        set val [$db flatattr $inst getMergedValue [string toupper $attrName]]
    }

    ##
    # If still no value could be found then return the default value for this
    # attribute.
    #
    if {$val == ""} {
        set    msg "Cannot find $attrName @instance '$inst'; "
        append msg "using the default value: '$defaultValue'."
        zmessage print WAR $msg
        return $defaultValue
    }

    ##
    # Check that the attribute value is a double.
    #
    set val [zdb formatvalue fromspice $val]
    if {![string is double -strict $val]} {
        set    msg "Value of the '$attrName' attribute @instance '$inst': $val "
        append msg "is not a double; "
        append msg "using the default value: '$defaultValue'."
        zmessage print WAR $msg
        return $defaultValue
    }

    ##
    # Return the value for this attribute.
    #
    return $val
}


# -----------------------------------------------------------------------------
# _flagDatabase - Loop over all cells and set the 'blue' flag at all cells
#                 with the NMOS function and the flag 'red' at all cells with
#                 the PMOS function.
#                 Res and Caps are flagged with the green flag.
# -----------------------------------------------------------------------------
#
proc CalculateArea:_flagDatabase {db} {
    ##
    # Loop over all cells in the given database.
    #
    $db foreach cell cell {
        ##
        # Clear the given flag at each cell.
        #
        $db flag $cell clear blue
        $db flag $cell clear red
        $db flag $cell clear green

        ##
        # Set the given flag at all cells that should be included in the
        # area calculation.
        #
        switch [$db primFuncOf $cell] {
            "NMOS" {
                $db flag $cell set blue
                $db flag $cell set yellow
            }
            "PMOS" {
                $db flag $cell set red
                $db flag $cell set yellow
            }
            "RES"  -
            "CAP"  {
                $db flag $cell set green
                $db flag $cell set yellow
            }
            default {}
        }
    }
}


# -----------------------------------------------------------------------------
# _getTop - All unused sub-circuits in the loaded design are treated as a
#           top module. This procedure can be used to find the top module
#           with the most content. We assume that this is the real top module.
# -----------------------------------------------------------------------------
#
proc CalculateArea:_getTop {db} {
    ##
    # Initialize the local variables 'topModule' and 'maxSize'.
    #
    set topModule {}
    set maxSize   0

    ##
    # Loop over all top modules to find the largest module.
    #
    #
    $db foreach top top {
        ##
        # Calculate the size (instance count + port count + net count) of this
        # top module.
        #
        set size 0
        foreach v [$db report sizeOf $top] {incr size $v}

        ##
        # Check if the size of this module is larger then the size of any
        # previous top modules.
        #
        if {$size > $maxSize} {
            ##
            # Set the new maxSize to the size of this module and set the top
            # module OID to this module.
            #
            set maxSize   $size
            set topModule $top
        }
    }

    ##
    # Return the top module OID.
    #
    return $topModule
}


# =============================================================================
# Call the initialization procedure.
# =============================================================================
#
CalculateArea:Init