cuddSubsetSP.c 61.3 KB
Newer Older
Alan Mishchenko committed
1 2 3 4 5 6 7 8 9 10 11
/**CFile***********************************************************************

  FileName    [cuddSubsetSP.c]

  PackageName [cudd]

  Synopsis [Procedure to subset the given BDD choosing the shortest paths
            (largest cubes) in the BDD.]


  Description  [External procedures included in this module:
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
                <ul>
                <li> Cudd_SubsetShortPaths()
                <li> Cudd_SupersetShortPaths()
                </ul>
                Internal procedures included in this module:
                <ul>
                <li> cuddSubsetShortPaths()
                </ul>
                Static procedures included in this module:
                <ul>
                <li> BuildSubsetBdd()
                <li> CreatePathTable()
                <li> AssessPathLength()
                <li> CreateTopDist()
                <li> CreateBotDist()
                <li> ResizeNodeDistPages()
                <li> ResizeQueuePages()
                <li> stPathTableDdFree()
                </ul>
                ]
Alan Mishchenko committed
32 33 34 35 36

  SeeAlso     [cuddSubsetHB.c]

  Author      [Kavita Ravi]

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
  Copyright   [Copyright (c) 1995-2004, Regents of the University of Colorado

  All rights reserved.

  Redistribution and use in source and binary forms, with or without
  modification, are permitted provided that the following conditions
  are met:

  Redistributions of source code must retain the above copyright
  notice, this list of conditions and the following disclaimer.

  Redistributions in binary form must reproduce the above copyright
  notice, this list of conditions and the following disclaimer in the
  documentation and/or other materials provided with the distribution.

  Neither the name of the University of Colorado nor the names of its
  contributors may be used to endorse or promote products derived from
  this software without specific prior written permission.

  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  POSSIBILITY OF SUCH DAMAGE.]
Alan Mishchenko committed
68 69 70

******************************************************************************/

71
#include "misc/util/util_hack.h"
Alan Mishchenko committed
72 73
#include "cuddInt.h"

74 75 76
ABC_NAMESPACE_IMPL_START


77

Alan Mishchenko committed
78 79 80 81 82 83
/*---------------------------------------------------------------------------*/
/* Constant declarations                                                     */
/*---------------------------------------------------------------------------*/

#define DEFAULT_PAGE_SIZE 2048 /* page size to store the BFS queue element type */
#define DEFAULT_NODE_DIST_PAGE_SIZE 2048 /*  page sizesto store NodeDist_t type */
84 85 86 87 88
#define MAXSHORTINT     ((DdHalfWord) ~0) /* constant defined to store
                                           * maximum distance of a node
                                           * from the root or the
                                           * constant
                                           */
Alan Mishchenko committed
89
#define INITIAL_PAGES 128 /* number of initial pages for the
90
                           * queue/NodeDist_t type */
Alan Mishchenko committed
91 92 93 94 95

/*---------------------------------------------------------------------------*/
/* Stucture declarations                                                     */
/*---------------------------------------------------------------------------*/

96
/* structure created to store subset results for each node and distances with
Alan Mishchenko committed
97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
 * odd and even parity of the node from the root and sink. Main data structure
 * in this procedure.
 */
struct NodeDist{
    DdHalfWord oddTopDist;
    DdHalfWord evenTopDist;
    DdHalfWord oddBotDist;
    DdHalfWord evenBotDist;
    DdNode *regResult;
    DdNode *compResult;
};

/* assorted information needed by the BuildSubsetBdd procedure. */
struct AssortedInfo {
    unsigned int maxpath;
    int findShortestPath;
    int thresholdReached;
114
    st__table *maxpathTable;
Alan Mishchenko committed
115 116 117 118 119 120 121 122 123 124 125 126 127 128
    int threshold;
};

/*---------------------------------------------------------------------------*/
/* Type declarations                                                         */
/*---------------------------------------------------------------------------*/

typedef struct NodeDist NodeDist_t;

/*---------------------------------------------------------------------------*/
/* Variable declarations                                                     */
/*---------------------------------------------------------------------------*/

#ifndef lint
129
static char rcsid[] DD_UNUSED = "$Id: cuddSubsetSP.c,v 1.34 2009/02/19 16:23:19 fabio Exp $";
Alan Mishchenko committed
130 131 132 133 134 135 136 137 138
#endif

#ifdef DD_DEBUG
static int numCalls;
static int hits;
static int thishit;
#endif


139
static  int             memOut; /* flag to indicate out of memory */
Alan Mishchenko committed
140 141 142
static  DdNode          *zero, *one; /* constant functions */

static  NodeDist_t      **nodeDistPages; /* pointers to the pages */
143 144 145 146
static  int             nodeDistPageIndex; /* index to next element */
static  int             nodeDistPage; /* index to current page */
static  int             nodeDistPageSize = DEFAULT_NODE_DIST_PAGE_SIZE; /* page size */
static  int             maxNodeDistPages; /* number of page pointers */
Alan Mishchenko committed
147 148 149
static  NodeDist_t      *currentNodeDistPage; /* current page */

static  DdNode          ***queuePages; /* pointers to the pages */
150 151 152 153
static  int             queuePageIndex; /* index to next element */
static  int             queuePage; /* index to current page */
static  int             queuePageSize = DEFAULT_PAGE_SIZE; /* page size */
static  int             maxQueuePages; /* number of page pointers */
Alan Mishchenko committed
154 155 156 157 158 159 160 161 162 163 164 165 166
static  DdNode          **currentQueuePage; /* current page */


/*---------------------------------------------------------------------------*/
/* Macro declarations                                                        */
/*---------------------------------------------------------------------------*/

/**AutomaticStart*************************************************************/

/*---------------------------------------------------------------------------*/
/* Static function prototypes                                                */
/*---------------------------------------------------------------------------*/

167 168
static void ResizeNodeDistPages (void);
static void ResizeQueuePages (void);
169 170 171
static void CreateTopDist ( st__table *pathTable, int parentPage, int parentQueueIndex, int topLen, DdNode **childPage, int childQueueIndex, int numParents, FILE *fp);
static int CreateBotDist (DdNode *node, st__table *pathTable, unsigned int *pathLengthArray, FILE *fp);
static st__table * CreatePathTable (DdNode *node, unsigned int *pathLengthArray, FILE *fp);
172
static unsigned int AssessPathLength (unsigned int *pathLengthArray, int threshold, int numVars, unsigned int *excess, FILE *fp);
173 174
static DdNode * BuildSubsetBdd (DdManager *dd, st__table *pathTable, DdNode *node, struct AssortedInfo *info, st__table *subsetNodeTable);
static enum st__retval stPathTableDdFree (char *key, char *value, char *arg);
Alan Mishchenko committed
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

/**AutomaticEnd***************************************************************/

/*---------------------------------------------------------------------------*/
/* Definition of Exported functions                                          */
/*---------------------------------------------------------------------------*/


/**Function********************************************************************

  Synopsis    [Extracts a dense subset from a BDD with the shortest paths
  heuristic.]

  Description [Extracts a dense subset from a BDD.  This procedure
  tries to preserve the shortest paths of the input BDD, because they
  give many minterms and contribute few nodes.  This procedure may
  increase the number of nodes in trying to create the subset or
  reduce the number of nodes due to recombination as compared to the
  original BDD. Hence the threshold may not be strictly adhered to. In
  practice, recombination overshadows the increase in the number of
  nodes and results in small BDDs as compared to the threshold. The
  hardlimit specifies whether threshold needs to be strictly adhered
  to. If it is set to 1, the procedure ensures that result is never
  larger than the specified limit but may be considerably less than
  the threshold.  Returns a pointer to the BDD for the subset if
  successful; NULL otherwise.  The value for numVars should be as
  close as possible to the size of the support of f for better
  efficiency. However, it is safe to pass the value returned by
  Cudd_ReadSize for numVars. If 0 is passed, then the value returned
  by Cudd_ReadSize is used.]

  SideEffects [None]

  SeeAlso     [Cudd_SupersetShortPaths Cudd_SubsetHeavyBranch Cudd_ReadSize]

******************************************************************************/
DdNode *
Cudd_SubsetShortPaths(
  DdManager * dd /* manager */,
  DdNode * f /* function to be subset */,
  int  numVars /* number of variables in the support of f */,
  int  threshold /* maximum number of nodes in the subset */,
  int  hardlimit /* flag: 1 if threshold is a hard limit */)
{
    DdNode *subset;

    memOut = 0;
    do {
223 224
        dd->reordered = 0;
        subset = cuddSubsetShortPaths(dd, f, numVars, threshold, hardlimit);
Alan Mishchenko committed
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
    } while((dd->reordered ==1) && (!memOut));

    return(subset);

} /* end of Cudd_SubsetShortPaths */


/**Function********************************************************************

  Synopsis    [Extracts a dense superset from a BDD with the shortest paths
  heuristic.]

  Description [Extracts a dense superset from a BDD.  The procedure is
  identical to the subset procedure except for the fact that it
  receives the complement of the given function. Extracting the subset
  of the complement function is equivalent to extracting the superset
  of the function.  This procedure tries to preserve the shortest
  paths of the complement BDD, because they give many minterms and
  contribute few nodes.  This procedure may increase the number of
  nodes in trying to create the superset or reduce the number of nodes
  due to recombination as compared to the original BDD. Hence the
  threshold may not be strictly adhered to. In practice, recombination
  overshadows the increase in the number of nodes and results in small
  BDDs as compared to the threshold.  The hardlimit specifies whether
  threshold needs to be strictly adhered to. If it is set to 1, the
  procedure ensures that result is never larger than the specified
  limit but may be considerably less than the threshold. Returns a
  pointer to the BDD for the superset if successful; NULL
  otherwise. The value for numVars should be as close as possible to
  the size of the support of f for better efficiency.  However, it is
  safe to pass the value returned by Cudd_ReadSize for numVar.  If 0
  is passed, then the value returned by Cudd_ReadSize is used.]

  SideEffects [None]

  SeeAlso     [Cudd_SubsetShortPaths Cudd_SupersetHeavyBranch Cudd_ReadSize]

******************************************************************************/
DdNode *
Cudd_SupersetShortPaths(
  DdManager * dd /* manager */,
  DdNode * f /* function to be superset */,
  int  numVars /* number of variables in the support of f */,
  int  threshold /* maximum number of nodes in the subset */,
  int  hardlimit /* flag: 1 if threshold is a hard limit */)
{
    DdNode *subset, *g;

    g = Cudd_Not(f);
    memOut = 0;
    do {
276 277
        dd->reordered = 0;
        subset = cuddSubsetShortPaths(dd, g, numVars, threshold, hardlimit);
Alan Mishchenko committed
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
    } while((dd->reordered ==1) && (!memOut));

    return(Cudd_NotCond(subset, (subset != NULL)));

} /* end of Cudd_SupersetShortPaths */


/*---------------------------------------------------------------------------*/
/* Definition of internal functions                                          */
/*---------------------------------------------------------------------------*/


/**Function********************************************************************

  Synopsis    [The outermost procedure to return a subset of the given BDD
  with the shortest path lengths.]

  Description [The outermost procedure to return a subset of the given
  BDD with the largest cubes. The path lengths are calculated, the maximum
  allowable path length is determined and the number of nodes of this
  path length that can be used to build a subset. If the threshold is
  larger than the size of the original BDD, the original BDD is
  returned. ]

  SideEffects [None]

  SeeAlso     [Cudd_SubsetShortPaths]

******************************************************************************/
DdNode *
cuddSubsetShortPaths(
  DdManager * dd /* DD manager */,
  DdNode * f /* function to be subset */,
  int  numVars /* total number of variables in consideration */,
  int  threshold /* maximum number of nodes allowed in the subset */,
  int  hardlimit /* flag determining whether thershold should be respected strictly */)
{
315
    st__table *pathTable;
Alan Mishchenko committed
316 317 318 319 320
    DdNode *N, *subset;

    unsigned int  *pathLengthArray;
    unsigned int maxpath, oddLen, evenLen, pathLength, *excess;
    int i;
321
    NodeDist_t  *nodeStat;
Alan Mishchenko committed
322
    struct AssortedInfo *info;
323
    st__table *subsetNodeTable;
Alan Mishchenko committed
324 325 326 327 328 329 330 331

    one = DD_ONE(dd);
    zero = Cudd_Not(one);

    if (numVars == 0) {
      /* set default value */
      numVars = Cudd_ReadSize(dd);
    }
332

Alan Mishchenko committed
333
    if (threshold > numVars) {
334
        threshold = threshold - numVars;
Alan Mishchenko committed
335 336
    }
    if (f == NULL) {
337 338 339
        fprintf(dd->err, "Cannot partition, nil object\n");
        dd->errorCode = CUDD_INVALID_ARG;
        return(NULL);
Alan Mishchenko committed
340 341
    }
    if (Cudd_IsConstant(f))
342
        return (f);
Alan Mishchenko committed
343

Alan Mishchenko committed
344
    pathLengthArray = ABC_ALLOC(unsigned int, numVars+1);
Alan Mishchenko committed
345 346 347 348 349 350 351 352 353 354
    for (i = 0; i < numVars+1; i++) pathLengthArray[i] = 0;


#ifdef DD_DEBUG
    numCalls = 0;
#endif

    pathTable = CreatePathTable(f, pathLengthArray, dd->err);

    if ((pathTable == NULL) || (memOut)) {
355
        if (pathTable != NULL)
356
            st__free_table(pathTable);
357 358
        ABC_FREE(pathLengthArray);
        return (NIL(DdNode));
Alan Mishchenko committed
359 360
    }

Alan Mishchenko committed
361
    excess = ABC_ALLOC(unsigned int, 1);
Alan Mishchenko committed
362 363
    *excess = 0;
    maxpath = AssessPathLength(pathLengthArray, threshold, numVars, excess,
364
                               dd->err);
Alan Mishchenko committed
365 366 367

    if (maxpath != (unsigned) (numVars + 1)) {

368 369 370 371
        info = ABC_ALLOC(struct AssortedInfo, 1);
        info->maxpath = maxpath;
        info->findShortestPath = 0;
        info->thresholdReached = *excess;
372
        info->maxpathTable = st__init_table( st__ptrcmp, st__ptrhash);
373
        info->threshold = threshold;
Alan Mishchenko committed
374 375

#ifdef DD_DEBUG
376 377 378 379 380 381 382 383 384 385 386 387 388
        (void) fprintf(dd->out, "Path length array\n");
        for (i = 0; i < (numVars+1); i++) {
            if (pathLengthArray[i])
                (void) fprintf(dd->out, "%d ",i);
        }
        (void) fprintf(dd->out, "\n");
        for (i = 0; i < (numVars+1); i++) {
            if (pathLengthArray[i])
                (void) fprintf(dd->out, "%d ",pathLengthArray[i]);
        }
        (void) fprintf(dd->out, "\n");
        (void) fprintf(dd->out, "Maxpath  = %d, Thresholdreached = %d\n",
                       maxpath, info->thresholdReached);
Alan Mishchenko committed
389 390
#endif

391
        N = Cudd_Regular(f);
392
        if (! st__lookup(pathTable, (const char *)N, (char **)&nodeStat)) {
393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416
            fprintf(dd->err, "Something wrong, root node must be in table\n");
            dd->errorCode = CUDD_INTERNAL_ERROR;
            ABC_FREE(excess);
            ABC_FREE(info);
            return(NULL);
        } else {
            if ((nodeStat->oddTopDist != MAXSHORTINT) &&
                (nodeStat->oddBotDist != MAXSHORTINT))
                oddLen = (nodeStat->oddTopDist + nodeStat->oddBotDist);
            else
                oddLen = MAXSHORTINT;

            if ((nodeStat->evenTopDist != MAXSHORTINT) &&
                (nodeStat->evenBotDist != MAXSHORTINT))
                evenLen = (nodeStat->evenTopDist +nodeStat->evenBotDist);
            else
                evenLen = MAXSHORTINT;

            pathLength = (oddLen <= evenLen) ? oddLen : evenLen;
            if (pathLength > maxpath) {
                (void) fprintf(dd->err, "All computations are bogus, since root has path length greater than max path length within threshold %u, %u\n", maxpath, pathLength);
                dd->errorCode = CUDD_INTERNAL_ERROR;
                return(NULL);
            }
Alan Mishchenko committed
417 418 419
        }

#ifdef DD_DEBUG
420 421 422
        numCalls = 0;
        hits = 0;
        thishit = 0;
Alan Mishchenko committed
423
#endif
424 425
        /* initialize a table to store computed nodes */
        if (hardlimit) {
426
            subsetNodeTable = st__init_table( st__ptrcmp, st__ptrhash);
427
        } else {
428
            subsetNodeTable = NIL( st__table);
429 430 431 432 433 434
        }
        subset = BuildSubsetBdd(dd, pathTable, f, info, subsetNodeTable);
        if (subset != NULL) {
            cuddRef(subset);
        }
        /* record the number of times a computed result for a node is hit */
Alan Mishchenko committed
435 436

#ifdef DD_DEBUG
437 438
        (void) fprintf(dd->out, "Hits = %d, New==Node = %d, NumCalls = %d\n",
                hits, thishit, numCalls);
Alan Mishchenko committed
439 440
#endif

441 442
        if (subsetNodeTable != NIL( st__table)) {
            st__free_table(subsetNodeTable);
443
        }
444 445
        st__free_table(info->maxpathTable);
        st__foreach(pathTable, stPathTableDdFree, (char *)dd);
Alan Mishchenko committed
446

447
        ABC_FREE(info);
Alan Mishchenko committed
448 449

    } else {/* if threshold larger than size of dd */
450 451
        subset = f;
        cuddRef(subset);
Alan Mishchenko committed
452
    }
Alan Mishchenko committed
453
    ABC_FREE(excess);
454
    st__free_table(pathTable);
Alan Mishchenko committed
455 456 457
    ABC_FREE(pathLengthArray);
    for (i = 0; i <= nodeDistPage; i++) ABC_FREE(nodeDistPages[i]);
    ABC_FREE(nodeDistPages);
Alan Mishchenko committed
458 459 460 461

#ifdef DD_DEBUG
    /* check containment of subset in f */
    if (subset != NULL) {
462 463 464 465 466 467 468
        DdNode *check;
        check = Cudd_bddIteConstant(dd, subset, f, one);
        if (check != one) {
            (void) fprintf(dd->err, "Wrong partition\n");
            dd->errorCode = CUDD_INTERNAL_ERROR;
            return(NULL);
        }
Alan Mishchenko committed
469 470 471 472
    }
#endif

    if (subset != NULL) {
473 474
        cuddDeref(subset);
        return(subset);
Alan Mishchenko committed
475
    } else {
476
        return(NULL);
Alan Mishchenko committed
477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496
    }

} /* end of cuddSubsetShortPaths */


/*---------------------------------------------------------------------------*/
/* Definition of static functions                                            */
/*---------------------------------------------------------------------------*/


/**Function********************************************************************

  Synopsis    [Resize the number of pages allocated to store the distances
  related to each node.]

  Description [Resize the number of pages allocated to store the distances
  related to each node. The procedure  moves the counter to the
  next page when the end of the page is reached and allocates new
  pages when necessary. ]

497
  SideEffects [Changes the size of  pages, page, page index, maximum
Alan Mishchenko committed
498 499 500 501 502 503
  number of pages freeing stuff in case of memory out. ]

  SeeAlso     []

******************************************************************************/
static void
504
ResizeNodeDistPages(void)
Alan Mishchenko committed
505 506 507 508 509 510 511 512
{
    int i;
    NodeDist_t **newNodeDistPages;

    /* move to next page */
    nodeDistPage++;

    /* If the current page index is larger than the number of pages
513
     * allocated, allocate a new page array. Page numbers are incremented by
Alan Mishchenko committed
514 515 516
     * INITIAL_PAGES
     */
    if (nodeDistPage == maxNodeDistPages) {
517 518 519 520 521 522 523 524 525 526 527 528 529 530
        newNodeDistPages = ABC_ALLOC(NodeDist_t *,maxNodeDistPages + INITIAL_PAGES);
        if (newNodeDistPages == NULL) {
            for (i = 0; i < nodeDistPage; i++) ABC_FREE(nodeDistPages[i]);
            ABC_FREE(nodeDistPages);
            memOut = 1;
            return;
        } else {
            for (i = 0; i < maxNodeDistPages; i++) {
                newNodeDistPages[i] = nodeDistPages[i];
            }
            /* Increase total page count */
            maxNodeDistPages += INITIAL_PAGES;
            ABC_FREE(nodeDistPages);
            nodeDistPages = newNodeDistPages;
Alan Mishchenko committed
531 532 533
        }
    }
    /* Allocate a new page */
Alan Mishchenko committed
534
    currentNodeDistPage = nodeDistPages[nodeDistPage] = ABC_ALLOC(NodeDist_t,
535
                                                              nodeDistPageSize);
Alan Mishchenko committed
536
    if (currentNodeDistPage == NULL) {
537 538 539 540
        for (i = 0; i < nodeDistPage; i++) ABC_FREE(nodeDistPages[i]);
        ABC_FREE(nodeDistPages);
        memOut = 1;
        return;
Alan Mishchenko committed
541 542 543 544 545 546 547 548 549 550
    }
    /* reset page index */
    nodeDistPageIndex = 0;
    return;

} /* end of ResizeNodeDistPages */


/**Function********************************************************************

551
  Synopsis    [Resize the number of pages allocated to store nodes in the BFS
Alan Mishchenko committed
552 553
  traversal of the Bdd  .]

554
  Description [Resize the number of pages allocated to store nodes in the BFS
Alan Mishchenko committed
555 556 557 558
  traversal of the Bdd. The procedure  moves the counter to the
  next page when the end of the page is reached and allocates new
  pages when necessary.]

559
  SideEffects [Changes the size of pages, page, page index, maximum
Alan Mishchenko committed
560 561 562 563 564 565
  number of pages freeing stuff in case of memory out. ]

  SeeAlso     []

******************************************************************************/
static void
566
ResizeQueuePages(void)
Alan Mishchenko committed
567 568 569 570 571 572
{
    int i;
    DdNode ***newQueuePages;

    queuePage++;
    /* If the current page index is larger than the number of pages
573
     * allocated, allocate a new page array. Page numbers are incremented by
Alan Mishchenko committed
574 575 576
     * INITIAL_PAGES
     */
    if (queuePage == maxQueuePages) {
577 578 579 580 581 582 583 584 585 586 587 588 589 590
        newQueuePages = ABC_ALLOC(DdNode **,maxQueuePages + INITIAL_PAGES);
        if (newQueuePages == NULL) {
            for (i = 0; i < queuePage; i++) ABC_FREE(queuePages[i]);
            ABC_FREE(queuePages);
            memOut = 1;
            return;
        } else {
            for (i = 0; i < maxQueuePages; i++) {
                newQueuePages[i] = queuePages[i];
            }
            /* Increase total page count */
            maxQueuePages += INITIAL_PAGES;
            ABC_FREE(queuePages);
            queuePages = newQueuePages;
Alan Mishchenko committed
591 592 593
        }
    }
    /* Allocate a new page */
Alan Mishchenko committed
594
    currentQueuePage = queuePages[queuePage] = ABC_ALLOC(DdNode *,queuePageSize);
Alan Mishchenko committed
595
    if (currentQueuePage == NULL) {
596 597 598 599
        for (i = 0; i < queuePage; i++) ABC_FREE(queuePages[i]);
        ABC_FREE(queuePages);
        memOut = 1;
        return;
Alan Mishchenko committed
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
    }
    /* reset page index */
    queuePageIndex = 0;
    return;

} /* end of ResizeQueuePages */


/**Function********************************************************************

  Synopsis    [ Labels each node with its shortest distance from the root]

  Description [ Labels each node with its shortest distance from the root.
  This is done in a BFS search of the BDD. The nodes are processed
  in a queue implemented as pages(array) to reduce memory fragmentation.
  An entry is created for each node visited. The distance from the root
  to the node with the corresponding  parity is updated. The procedure
  is called recursively each recusion level handling nodes at a given
  level from the root.]


  SideEffects [Creates entries in the pathTable]

  SeeAlso     [CreatePathTable CreateBotDist]

******************************************************************************/
static void
CreateTopDist(
628
  st__table * pathTable /* hast table to store path lengths */,
Alan Mishchenko committed
629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648
  int  parentPage /* the pointer to the page on which the first parent in the queue is to be found. */,
  int  parentQueueIndex /* pointer to the first parent on the page */,
  int  topLen /* current distance from the root */,
  DdNode ** childPage /* pointer to the page on which the first child is to be added. */,
  int  childQueueIndex /* pointer to the first child */,
  int  numParents /* number of parents to process in this recursive call */,
  FILE *fp /* where to write messages */)
{
    NodeDist_t *nodeStat;
    DdNode *N, *Nv, *Nnv, *node, *child, *regChild;
    int  i;
    int processingDone, childrenCount;

#ifdef DD_DEBUG
    numCalls++;

    /* assume this procedure comes in with only the root node*/
    /* set queue index to the next available entry for addition */
    /* set queue page to page of addition */
    if ((queuePages[parentPage] == childPage) && (parentQueueIndex ==
649 650
                                                  childQueueIndex)) {
        fprintf(fp, "Should not happen that they are equal\n");
Alan Mishchenko committed
651 652 653 654 655
    }
    assert(queuePageIndex == childQueueIndex);
    assert(currentQueuePage == childPage);
#endif
    /* number children added to queue is initialized , needed for
656
     * numParents in the next call
Alan Mishchenko committed
657 658 659 660
     */
    childrenCount = 0;
    /* process all the nodes in this level */
    while (numParents) {
661 662 663 664
        numParents--;
        if (parentQueueIndex == queuePageSize) {
            parentPage++;
            parentQueueIndex = 0;
Alan Mishchenko committed
665
        }
666 667 668 669 670 671 672 673 674 675 676 677 678 679 680
        /* a parent to process */
        node = *(queuePages[parentPage] + parentQueueIndex);
        parentQueueIndex++;
        /* get its children */
        N = Cudd_Regular(node);
        Nv = Cudd_T(N);
        Nnv = Cudd_E(N);

        Nv = Cudd_NotCond(Nv, Cudd_IsComplement(node));
        Nnv = Cudd_NotCond(Nnv, Cudd_IsComplement(node));

        processingDone = 2;
        while (processingDone) {
            /* processing the THEN and the ELSE children, the THEN
             * child first
Alan Mishchenko committed
681
             */
682 683
            if (processingDone == 2) {
                child = Nv;
Alan Mishchenko committed
684
            } else {
685
                child = Nnv;
Alan Mishchenko committed
686 687
            }

688 689 690 691 692 693
            regChild = Cudd_Regular(child);
            /* dont process if the child is a constant */
            if (!Cudd_IsConstant(child)) {
                /* check is already visited, if not add a new entry in
                 * the path Table
                 */
694
                if (! st__lookup(pathTable, (const char *)regChild, (char **)&nodeStat)) {
695 696 697 698 699 700 701
                    /* if not in table, has never been visited */
                    /* create entry for table */
                    if (nodeDistPageIndex == nodeDistPageSize)
                        ResizeNodeDistPages();
                    if (memOut) {
                        for (i = 0; i <= queuePage; i++) ABC_FREE(queuePages[i]);
                        ABC_FREE(queuePages);
702
                        st__free_table(pathTable);
703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725
                        return;
                    }
                    /* New entry for child in path Table is created here */
                    nodeStat = currentNodeDistPage + nodeDistPageIndex;
                    nodeDistPageIndex++;

                    /* Initialize fields of the node data */
                    nodeStat->oddTopDist = MAXSHORTINT;
                    nodeStat->evenTopDist = MAXSHORTINT;
                    nodeStat->evenBotDist = MAXSHORTINT;
                    nodeStat->oddBotDist = MAXSHORTINT;
                    nodeStat->regResult = NULL;
                    nodeStat->compResult = NULL;
                    /* update the table entry element, the distance keeps
                     * track of the parity of the path from the root
                     */
                    if (Cudd_IsComplement(child)) {
                        nodeStat->oddTopDist = (DdHalfWord) topLen + 1;
                    } else {
                        nodeStat->evenTopDist = (DdHalfWord) topLen + 1;
                    }

                    /* insert entry element for  child in the table */
726 727
                    if ( st__insert(pathTable, (char *)regChild,
                                  (char *)nodeStat) == st__OUT_OF_MEM) {
728 729 730 731 732 733
                        memOut = 1;
                        for (i = 0; i <= nodeDistPage; i++)
                            ABC_FREE(nodeDistPages[i]);
                        ABC_FREE(nodeDistPages);
                        for (i = 0; i <= queuePage; i++) ABC_FREE(queuePages[i]);
                        ABC_FREE(queuePages);
734
                        st__free_table(pathTable);
735 736 737 738 739 740 741 742 743 744 745 746 747 748
                        return;
                    }

                    /* Create list element for this child to process its children.
                     * If this node has been processed already, then it appears
                     * in the path table and hence is never added to the list
                     * again.
                     */

                    if (queuePageIndex == queuePageSize) ResizeQueuePages();
                    if (memOut) {
                        for (i = 0; i <= nodeDistPage; i++)
                            ABC_FREE(nodeDistPages[i]);
                        ABC_FREE(nodeDistPages);
749
                        st__free_table(pathTable);
750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767
                        return;
                    }
                    *(currentQueuePage + queuePageIndex) = child;
                    queuePageIndex++;

                    childrenCount++;
                } else {
                    /* if not been met in a path with this parity before */
                    /* put in list */
                    if (((Cudd_IsComplement(child)) && (nodeStat->oddTopDist ==
                          MAXSHORTINT)) || ((!Cudd_IsComplement(child)) &&
                                  (nodeStat->evenTopDist == MAXSHORTINT))) {

                        if (queuePageIndex == queuePageSize) ResizeQueuePages();
                        if (memOut) {
                            for (i = 0; i <= nodeDistPage; i++)
                                ABC_FREE(nodeDistPages[i]);
                            ABC_FREE(nodeDistPages);
768
                            st__free_table(pathTable);
769 770 771 772 773 774 775 776 777 778 779 780 781 782 783
                            return;

                        }
                        *(currentQueuePage + queuePageIndex) = child;
                        queuePageIndex++;

                        /* update the distance with the appropriate parity */
                        if (Cudd_IsComplement(child)) {
                            nodeStat->oddTopDist = (DdHalfWord) topLen + 1;
                        } else {
                            nodeStat->evenTopDist = (DdHalfWord) topLen + 1;
                        }
                        childrenCount++;
                    }

784
                } /* end of else (not found in st__table) */
785 786 787
            } /*end of if Not constant child */
            processingDone--;
        } /*end of while processing Nv, Nnv */
Alan Mishchenko committed
788 789 790 791 792 793 794 795
    }  /*end of while numParents */

#ifdef DD_DEBUG
    assert(queuePages[parentPage] == childPage);
    assert(parentQueueIndex == childQueueIndex);
#endif

    if (childrenCount != 0) {
796 797 798 799 800
        topLen++;
        childPage = currentQueuePage;
        childQueueIndex = queuePageIndex;
        CreateTopDist(pathTable, parentPage, parentQueueIndex, topLen,
                      childPage, childQueueIndex, childrenCount, fp);
Alan Mishchenko committed
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
    }

    return;

} /* end of CreateTopDist */


/**Function********************************************************************

  Synopsis    [ Labels each node with the shortest distance from the constant.]

  Description [Labels each node with the shortest distance from the constant.
  This is done in a DFS search of the BDD. Each node has an odd
  and even parity distance from the sink (since there exists paths to both
  zero and one) which is less than MAXSHORTINT. At each node these distances
  are updated using the minimum distance of its children from the constant.
  SInce now both the length from the root and child is known, the minimum path
  length(length of the shortest path between the root and the constant that
  this node lies on) of this node can be calculated and used to update the
  pathLengthArray]

  SideEffects [Updates Path Table and path length array]

  SeeAlso     [CreatePathTable CreateTopDist AssessPathLength]

******************************************************************************/
static int
CreateBotDist(
  DdNode * node /* current node */,
830
  st__table * pathTable /* path table with path lengths */,
Alan Mishchenko committed
831 832 833 834 835 836 837 838 839 840 841 842
  unsigned int * pathLengthArray /* array that stores number of nodes belonging to a particular path length. */,
  FILE *fp /* where to write messages */)
{
    DdNode *N, *Nv, *Nnv;
    DdNode *realChild;
    DdNode *child, *regChild;
    NodeDist_t *nodeStat, *nodeStatChild;
    unsigned int  oddLen, evenLen, pathLength;
    DdHalfWord botDist;
    int processingDone;

    if (Cudd_IsConstant(node))
843
        return(1);
Alan Mishchenko committed
844 845 846 847
    N = Cudd_Regular(node);
    /* each node has one table entry */
    /* update as you go down the min dist of each node from
       the root in each (odd and even) parity */
848
    if (! st__lookup(pathTable, (const char *)N, (char **)&nodeStat)) {
849 850
        fprintf(fp, "Something wrong, the entry doesn't exist\n");
        return(0);
Alan Mishchenko committed
851 852 853 854
    }

    /* compute length of odd parity distances */
    if ((nodeStat->oddTopDist != MAXSHORTINT) &&
855 856
        (nodeStat->oddBotDist != MAXSHORTINT))
        oddLen = (nodeStat->oddTopDist + nodeStat->oddBotDist);
Alan Mishchenko committed
857
    else
858
        oddLen = MAXSHORTINT;
Alan Mishchenko committed
859 860 861

    /* compute length of even parity distances */
    if (!((nodeStat->evenTopDist == MAXSHORTINT) ||
862 863
          (nodeStat->evenBotDist == MAXSHORTINT)))
        evenLen = (nodeStat->evenTopDist +nodeStat->evenBotDist);
Alan Mishchenko committed
864
    else
865
        evenLen = MAXSHORTINT;
Alan Mishchenko committed
866 867 868 869 870 871 872 873 874 875

    /* assign pathlength to minimum of the two */
    pathLength = (oddLen <= evenLen) ? oddLen : evenLen;

    Nv = Cudd_T(N);
    Nnv = Cudd_E(N);

    /* process each child */
    processingDone = 0;
    while (processingDone != 2) {
876 877 878 879
        if (!processingDone) {
            child = Nv;
        } else {
            child = Nnv;
Alan Mishchenko committed
880 881
        }

882 883 884 885 886 887 888 889 890 891
        realChild = Cudd_NotCond(child, Cudd_IsComplement(node));
        regChild = Cudd_Regular(child);
        if (Cudd_IsConstant(realChild)) {
            /* Found a minterm; count parity and shortest distance
            ** from the constant.
            */
            if (Cudd_IsComplement(child))
                nodeStat->oddBotDist = 1;
            else
                nodeStat->evenBotDist = 1;
Alan Mishchenko committed
892
        } else {
893
            /* If node not in table, recur. */
894
            if (! st__lookup(pathTable, (const char *)regChild, (char **)&nodeStatChild)) {
895 896 897 898 899 900 901 902 903 904 905 906 907
                fprintf(fp, "Something wrong, node in table should have been created in top dist proc.\n");
                return(0);
            }

            if (nodeStatChild->oddBotDist == MAXSHORTINT) {
                if (nodeStatChild->evenBotDist == MAXSHORTINT) {
                    if (!CreateBotDist(realChild, pathTable, pathLengthArray, fp))
                        return(0);
                } else {
                    fprintf(fp, "Something wrong, both bot nodeStats should be there\n");
                    return(0);
                }
            }
Alan Mishchenko committed
908

909 910
            /* Update shortest distance from the constant depending on
            **  parity. */
Alan Mishchenko committed
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
            if (Cudd_IsComplement(child)) {
                /* If parity on the edge then add 1 to even distance
                ** of child to get odd parity distance and add 1 to
                ** odd distance of child to get even parity
                ** distance. Change distance of current node only if
                ** the calculated distance is less than existing
                ** distance. */
                if (nodeStatChild->oddBotDist != MAXSHORTINT)
                    botDist = nodeStatChild->oddBotDist + 1;
                else
                    botDist = MAXSHORTINT;
                if (nodeStat->evenBotDist > botDist )
                    nodeStat->evenBotDist = botDist;

                if (nodeStatChild->evenBotDist != MAXSHORTINT)
                    botDist = nodeStatChild->evenBotDist + 1;
                else
                    botDist = MAXSHORTINT;
                if (nodeStat->oddBotDist > botDist)
                    nodeStat->oddBotDist = botDist;

            } else {
                /* If parity on the edge then add 1 to even distance
                ** of child to get even parity distance and add 1 to
                ** odd distance of child to get odd parity distance.
                ** Change distance of current node only if the
                ** calculated distance is lesser than existing
                ** distance. */
                if (nodeStatChild->evenBotDist != MAXSHORTINT)
                    botDist = nodeStatChild->evenBotDist + 1;
                else
                    botDist = MAXSHORTINT;
                if (nodeStat->evenBotDist > botDist)
                    nodeStat->evenBotDist = botDist;

                if (nodeStatChild->oddBotDist != MAXSHORTINT)
                    botDist = nodeStatChild->oddBotDist + 1;
                else
                    botDist = MAXSHORTINT;
                if (nodeStat->oddBotDist > botDist)
                    nodeStat->oddBotDist = botDist;
            }
        } /* end of else (if not constant child ) */
        processingDone++;
Alan Mishchenko committed
956 957 958 959
    } /* end of while processing Nv, Nnv */

    /* Compute shortest path length on the fly. */
    if ((nodeStat->oddTopDist != MAXSHORTINT) &&
960 961
        (nodeStat->oddBotDist != MAXSHORTINT))
        oddLen = (nodeStat->oddTopDist + nodeStat->oddBotDist);
Alan Mishchenko committed
962
    else
963
        oddLen = MAXSHORTINT;
Alan Mishchenko committed
964 965

    if ((nodeStat->evenTopDist != MAXSHORTINT) &&
966 967
        (nodeStat->evenBotDist != MAXSHORTINT))
        evenLen = (nodeStat->evenTopDist +nodeStat->evenBotDist);
Alan Mishchenko committed
968
    else
969
        evenLen = MAXSHORTINT;
Alan Mishchenko committed
970 971 972 973

    /* Update path length array that has number of nodes of a particular
    ** path length. */
    if (oddLen < pathLength ) {
974 975 976 977 978
        if (pathLength != MAXSHORTINT)
            pathLengthArray[pathLength]--;
        if (oddLen != MAXSHORTINT)
            pathLengthArray[oddLen]++;
        pathLength = oddLen;
Alan Mishchenko committed
979 980
    }
    if (evenLen < pathLength ) {
981 982 983 984
        if (pathLength != MAXSHORTINT)
            pathLengthArray[pathLength]--;
        if (evenLen != MAXSHORTINT)
            pathLengthArray[evenLen]++;
Alan Mishchenko committed
985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009
    }

    return(1);

} /*end of CreateBotDist */


/**Function********************************************************************

  Synopsis    [ The outer procedure to label each node with its shortest
  distance from the root and constant]

  Description [ The outer procedure to label each node with its shortest
  distance from the root and constant. Calls CreateTopDist and CreateBotDist.
  The basis for computing the distance between root and constant is that
  the distance may be the sum of even distances from the node to the root
  and constant or the sum of odd distances from the node to the root and
  constant.  Both CreateTopDist and CreateBotDist create the odd and
  even parity distances from the root and constant respectively.]

  SideEffects [None]

  SeeAlso     [CreateTopDist CreateBotDist]

******************************************************************************/
1010
static st__table *
Alan Mishchenko committed
1011 1012 1013 1014 1015 1016
CreatePathTable(
  DdNode * node /* root of function */,
  unsigned int * pathLengthArray /* array of path lengths to store nodes labeled with the various path lengths */,
  FILE *fp /* where to write messages */)
{

1017
    st__table *pathTable;
Alan Mishchenko committed
1018 1019 1020 1021 1022 1023 1024 1025 1026 1027
    NodeDist_t *nodeStat;
    DdHalfWord topLen;
    DdNode *N;
    int i, numParents;
    int insertValue;
    DdNode **childPage;
    int parentPage;
    int childQueueIndex, parentQueueIndex;

    /* Creating path Table for storing data about nodes */
1028
    pathTable = st__init_table( st__ptrcmp, st__ptrhash);
Alan Mishchenko committed
1029 1030 1031

    /* initializing pages for info about each node */
    maxNodeDistPages = INITIAL_PAGES;
Alan Mishchenko committed
1032
    nodeDistPages = ABC_ALLOC(NodeDist_t *, maxNodeDistPages);
Alan Mishchenko committed
1033
    if (nodeDistPages == NULL) {
1034
        goto OUT_OF_MEM;
Alan Mishchenko committed
1035 1036 1037
    }
    nodeDistPage = 0;
    currentNodeDistPage = nodeDistPages[nodeDistPage] =
1038
        ABC_ALLOC(NodeDist_t, nodeDistPageSize);
Alan Mishchenko committed
1039
    if (currentNodeDistPage == NULL) {
1040 1041 1042
        for (i = 0; i <= nodeDistPage; i++) ABC_FREE(nodeDistPages[i]);
        ABC_FREE(nodeDistPages);
        goto OUT_OF_MEM;
Alan Mishchenko committed
1043 1044 1045 1046 1047
    }
    nodeDistPageIndex = 0;

    /* Initializing pages for the BFS search queue, implemented as an array. */
    maxQueuePages = INITIAL_PAGES;
Alan Mishchenko committed
1048
    queuePages = ABC_ALLOC(DdNode **, maxQueuePages);
Alan Mishchenko committed
1049
    if (queuePages == NULL) {
1050
        goto OUT_OF_MEM;
Alan Mishchenko committed
1051 1052
    }
    queuePage = 0;
Alan Mishchenko committed
1053
    currentQueuePage  = queuePages[queuePage] = ABC_ALLOC(DdNode *, queuePageSize);
Alan Mishchenko committed
1054
    if (currentQueuePage == NULL) {
1055 1056 1057
        for (i = 0; i <= queuePage; i++) ABC_FREE(queuePages[i]);
        ABC_FREE(queuePages);
        goto OUT_OF_MEM;
Alan Mishchenko committed
1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073
    }
    queuePageIndex = 0;

    /* Enter the root node into the queue to start with. */
    parentPage = queuePage;
    parentQueueIndex = queuePageIndex;
    topLen = 0;
    *(currentQueuePage + queuePageIndex) = node;
    queuePageIndex++;
    childPage = currentQueuePage;
    childQueueIndex = queuePageIndex;

    N = Cudd_Regular(node);

    if (nodeDistPageIndex == nodeDistPageSize) ResizeNodeDistPages();
    if (memOut) {
1074 1075 1076 1077
        for (i = 0; i <= nodeDistPage; i++) ABC_FREE(nodeDistPages[i]);
        ABC_FREE(nodeDistPages);
        for (i = 0; i <= queuePage; i++) ABC_FREE(queuePages[i]);
        ABC_FREE(queuePages);
1078
        st__free_table(pathTable);
1079
        goto OUT_OF_MEM;
Alan Mishchenko committed
1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091
    }

    nodeStat = currentNodeDistPage + nodeDistPageIndex;
    nodeDistPageIndex++;

    nodeStat->oddTopDist = MAXSHORTINT;
    nodeStat->evenTopDist = MAXSHORTINT;
    nodeStat->evenBotDist = MAXSHORTINT;
    nodeStat->oddBotDist = MAXSHORTINT;
    nodeStat->regResult = NULL;
    nodeStat->compResult = NULL;

1092 1093
    insertValue = st__insert(pathTable, (char *)N, (char *)nodeStat);
    if (insertValue == st__OUT_OF_MEM) {
1094 1095 1096 1097 1098
        memOut = 1;
        for (i = 0; i <= nodeDistPage; i++) ABC_FREE(nodeDistPages[i]);
        ABC_FREE(nodeDistPages);
        for (i = 0; i <= queuePage; i++) ABC_FREE(queuePages[i]);
        ABC_FREE(queuePages);
1099
        st__free_table(pathTable);
1100
        goto OUT_OF_MEM;
Alan Mishchenko committed
1101
    } else if (insertValue == 1) {
1102
        fprintf(fp, "Something wrong, the entry exists but didnt show up in st__lookup\n");
1103
        return(NULL);
Alan Mishchenko committed
1104 1105 1106
    }

    if (Cudd_IsComplement(node)) {
1107
        nodeStat->oddTopDist = 0;
Alan Mishchenko committed
1108
    } else {
1109
        nodeStat->evenTopDist = 0;
Alan Mishchenko committed
1110 1111 1112 1113 1114 1115 1116 1117 1118
    }
    numParents = 1;
    /* call the function that counts the distance of each node from the
     * root
     */
#ifdef DD_DEBUG
    numCalls = 0;
#endif
    CreateTopDist(pathTable, parentPage, parentQueueIndex, (int) topLen,
1119
                  childPage, childQueueIndex, numParents, fp);
Alan Mishchenko committed
1120
    if (memOut) {
1121 1122
        fprintf(fp, "Out of Memory and cant count path lengths\n");
        goto OUT_OF_MEM;
Alan Mishchenko committed
1123 1124 1125 1126 1127 1128 1129 1130 1131 1132
    }

#ifdef DD_DEBUG
    numCalls = 0;
#endif
    /* call the function that counts the distance of each node from the
     * constant
     */
    if (!CreateBotDist(node, pathTable, pathLengthArray, fp)) return(NULL);

1133
    /* free BFS queue pages as no longer required */
Alan Mishchenko committed
1134 1135
    for (i = 0; i <= queuePage; i++) ABC_FREE(queuePages[i]);
    ABC_FREE(queuePages);
Alan Mishchenko committed
1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179
    return(pathTable);

OUT_OF_MEM:
    (void) fprintf(fp, "Out of Memory, cannot allocate pages\n");
    memOut = 1;
    return(NULL);

} /*end of CreatePathTable */


/**Function********************************************************************

  Synopsis    [Chooses the maximum allowable path length of nodes under the
  threshold.]

  Description [Chooses the maximum allowable path length under each node.
  The corner cases are when the threshold is larger than the number
  of nodes in the BDD iself, in which case 'numVars + 1' is returned.
  If all nodes of a particular path length are needed, then the
  maxpath returned is the next one with excess nodes = 0;]

  SideEffects [None]

  SeeAlso     []

******************************************************************************/
static unsigned int
AssessPathLength(
  unsigned int * pathLengthArray /* array determining number of nodes belonging to the different path lengths */,
  int  threshold /* threshold to determine maximum allowable nodes in the subset */,
  int  numVars /* maximum number of variables */,
  unsigned int * excess /* number of nodes labeled maxpath required in the subset */,
  FILE *fp /* where to write messages */)
{
    unsigned int i, maxpath;
    int temp;

    temp = threshold;
    i = 0;
    maxpath = 0;
    /* quit loop if i reaches max number of variables or if temp reaches
     * below zero
     */
    while ((i < (unsigned) numVars+1) && (temp > 0)) {
1180 1181 1182 1183 1184
        if (pathLengthArray[i] > 0) {
            maxpath = i;
            temp = temp - pathLengthArray[i];
        }
        i++;
Alan Mishchenko committed
1185 1186 1187
    }
    /* if all nodes of max path are needed */
    if (temp >= 0) {
1188 1189 1190
        maxpath++; /* now maxpath  becomes the next maxppath or max number
                      of variables */
        *excess = 0;
Alan Mishchenko committed
1191
    } else { /* normal case when subset required is less than size of
1192 1193
                original BDD */
        *excess = temp + pathLengthArray[maxpath];
Alan Mishchenko committed
1194 1195 1196
    }

    if (maxpath == 0) {
1197
        fprintf(fp, "Path Length array seems to be all zeroes, check\n");
Alan Mishchenko committed
1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248
    }
    return(maxpath);

} /* end of AssessPathLength */


/**Function********************************************************************

  Synopsis    [Builds the BDD with nodes labeled with path length less than or equal to maxpath]

  Description [Builds the BDD with nodes labeled with path length
  under maxpath and as many nodes labeled maxpath as determined by the
  threshold. The procedure uses the path table to determine which nodes
  in the original bdd need to be retained. This procedure picks a
  shortest path (tie break decided by taking the child with the shortest
  distance to the constant) and recurs down the path till it reaches the
  constant. the procedure then starts building the subset upward from
  the constant. All nodes labeled by path lengths less than the given
  maxpath are used to build the subset.  However, in the case of nodes
  that have label equal to maxpath, as many are chosen as required by
  the threshold. This number is stored in the info structure in the
  field thresholdReached. This field is decremented whenever a node
  labeled maxpath is encountered and the nodes labeled maxpath are
  aggregated in a maxpath table. As soon as the thresholdReached count
  goes to 0, the shortest path from this node to the constant is found.
  The extraction of nodes with the above labeling is based on the fact
  that each node, labeled with a path length, P, has at least one child
  labeled P or less. So extracting all nodes labeled a given path length
  P ensures complete paths between the root and the constant. Extraction
  of a partial number of nodes with a given path length may result in
  incomplete paths and hence the additional number of nodes are grabbed
  to complete the path. Since the Bdd is built bottom-up, other nodes
  labeled maxpath do lie on complete paths.  The procedure may cause the
  subset to have a larger or smaller number of nodes than the specified
  threshold. The increase in the number of nodes is caused by the
  building of a subset and the reduction by recombination. However in
  most cases, the recombination overshadows the increase and the
  procedure returns a result with lower number of nodes than specified.
  The subsetNodeTable is NIL when there is no hard limit on the number
  of nodes. Further efforts towards keeping the subset closer to the
  threshold number were abandoned in favour of keeping the procedure
  simple and fast.]

  SideEffects [SubsetNodeTable is changed if it is not NIL.]

  SeeAlso     []

******************************************************************************/
static DdNode *
BuildSubsetBdd(
  DdManager * dd /* DD manager */,
1249
  st__table * pathTable /* path table with path lengths and computed results */,
Alan Mishchenko committed
1250 1251
  DdNode * node /* current node */,
  struct AssortedInfo * info /* assorted information structure */,
1252
  st__table * subsetNodeTable /* table storing computed results */)
Alan Mishchenko committed
1253 1254 1255
{
    DdNode *N, *Nv, *Nnv;
    DdNode *ThenBranch, *ElseBranch, *childBranch;
1256
    DdNode *child, *regChild, *regNnv = NULL, *regNv = NULL;
Alan Mishchenko committed
1257 1258 1259 1260
    NodeDist_t *nodeStatNv, *nodeStat, *nodeStatNnv;
    DdNode *neW, *topv, *regNew;
    char *entry;
    unsigned int topid;
1261
    unsigned int childPathLength, oddLen, evenLen, NnvPathLength = 0, NvPathLength = 0;
Alan Mishchenko committed
1262 1263 1264 1265 1266 1267 1268 1269 1270
    unsigned int NvBotDist, NnvBotDist;
    int tiebreakChild;
    int  processingDone, thenDone, elseDone;


#ifdef DD_DEBUG
    numCalls++;
#endif
    if (Cudd_IsConstant(node))
1271
        return(node);
Alan Mishchenko committed
1272 1273 1274

    N = Cudd_Regular(node);
    /* Find node in table. */
1275
    if (! st__lookup(pathTable, (const char *)N, (char **)&nodeStat)) {
1276 1277 1278
        (void) fprintf(dd->err, "Something wrong, node must be in table \n");
        dd->errorCode = CUDD_INTERNAL_ERROR;
        return(NULL);
Alan Mishchenko committed
1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289
    }
    /* If the node in the table has been visited, then return the corresponding
    ** Dd. Since a node can become a subset of itself, its
    ** complement (that is te same node reached by a different parity) will
    ** become a superset of the original node and result in some minterms
    ** that were not in the original set. Hence two different results are
    ** maintained, corresponding to the odd and even parities.
    */

    /* If this node is reached with an odd parity, get odd parity results. */
    if (Cudd_IsComplement(node)) {
1290
        if  (nodeStat->compResult != NULL) {
Alan Mishchenko committed
1291
#ifdef DD_DEBUG
1292
            hits++;
Alan Mishchenko committed
1293
#endif
1294 1295
            return(nodeStat->compResult);
        }
Alan Mishchenko committed
1296
    } else {
1297 1298 1299 1300
        /* if this node is reached with an even parity, get even parity
         * results
         */
        if (nodeStat->regResult != NULL) {
Alan Mishchenko committed
1301
#ifdef DD_DEBUG
1302
            hits++;
Alan Mishchenko committed
1303
#endif
1304 1305
            return(nodeStat->regResult);
        }
Alan Mishchenko committed
1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325
    }


    /* get children */
    Nv = Cudd_T(N);
    Nnv = Cudd_E(N);

    Nv = Cudd_NotCond(Nv, Cudd_IsComplement(node));
    Nnv = Cudd_NotCond(Nnv, Cudd_IsComplement(node));

    /* no child processed */
    processingDone = 0;
    /* then child not processed */
    thenDone = 0;
    ThenBranch = NULL;
    /* else child not processed */
    elseDone = 0;
    ElseBranch = NULL;
    /* if then child constant, branch is the child */
    if (Cudd_IsConstant(Nv)) {
1326 1327 1328 1329
        /*shortest path found */
        if ((Nv == DD_ONE(dd)) && (info->findShortestPath)) {
            info->findShortestPath = 0;
        }
Alan Mishchenko committed
1330

1331 1332 1333 1334 1335
        ThenBranch = Nv;
        cuddRef(ThenBranch);
        if (ThenBranch == NULL) {
            return(NULL);
        }
Alan Mishchenko committed
1336

1337 1338 1339
        thenDone++;
        processingDone++;
        NvBotDist = MAXSHORTINT;
Alan Mishchenko committed
1340
    } else {
1341 1342 1343
        /* Derive regular child for table lookup. */
        regNv = Cudd_Regular(Nv);
        /* Get node data for shortest path length. */
1344
        if (! st__lookup(pathTable, (const char *)regNv, (char **)&nodeStatNv) ) {
1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355
            (void) fprintf(dd->err, "Something wrong, node must be in table\n");
            dd->errorCode = CUDD_INTERNAL_ERROR;
            return(NULL);
        }
        /* Derive shortest path length for child. */
        if ((nodeStatNv->oddTopDist != MAXSHORTINT) &&
            (nodeStatNv->oddBotDist != MAXSHORTINT)) {
            oddLen = (nodeStatNv->oddTopDist + nodeStatNv->oddBotDist);
        } else {
            oddLen = MAXSHORTINT;
        }
Alan Mishchenko committed
1356

1357 1358 1359 1360 1361 1362
        if ((nodeStatNv->evenTopDist != MAXSHORTINT) &&
            (nodeStatNv->evenBotDist != MAXSHORTINT)) {
            evenLen = (nodeStatNv->evenTopDist +nodeStatNv->evenBotDist);
        } else {
            evenLen = MAXSHORTINT;
        }
Alan Mishchenko committed
1363

1364 1365 1366
        NvPathLength = (oddLen <= evenLen) ? oddLen : evenLen;
        NvBotDist = (oddLen <= evenLen) ? nodeStatNv->oddBotDist:
                                                   nodeStatNv->evenBotDist;
Alan Mishchenko committed
1367 1368 1369
    }
    /* if else child constant, branch is the child */
    if (Cudd_IsConstant(Nnv)) {
1370 1371 1372 1373
        /*shortest path found */
        if ((Nnv == DD_ONE(dd)) && (info->findShortestPath)) {
            info->findShortestPath = 0;
        }
Alan Mishchenko committed
1374

1375 1376 1377 1378 1379
        ElseBranch = Nnv;
        cuddRef(ElseBranch);
        if (ElseBranch == NULL) {
            return(NULL);
        }
Alan Mishchenko committed
1380

1381 1382 1383
        elseDone++;
        processingDone++;
        NnvBotDist = MAXSHORTINT;
Alan Mishchenko committed
1384
    } else {
1385 1386 1387
        /* Derive regular child for table lookup. */
        regNnv = Cudd_Regular(Nnv);
        /* Get node data for shortest path length. */
1388
        if (! st__lookup(pathTable, (const char *)regNnv, (char **)&nodeStatNnv) ) {
1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399
            (void) fprintf(dd->err, "Something wrong, node must be in table\n");
            dd->errorCode = CUDD_INTERNAL_ERROR;
            return(NULL);
        }
        /* Derive shortest path length for child. */
        if ((nodeStatNnv->oddTopDist != MAXSHORTINT) &&
            (nodeStatNnv->oddBotDist != MAXSHORTINT)) {
            oddLen = (nodeStatNnv->oddTopDist + nodeStatNnv->oddBotDist);
        } else {
            oddLen = MAXSHORTINT;
        }
Alan Mishchenko committed
1400

1401 1402 1403 1404 1405 1406
        if ((nodeStatNnv->evenTopDist != MAXSHORTINT) &&
            (nodeStatNnv->evenBotDist != MAXSHORTINT)) {
            evenLen = (nodeStatNnv->evenTopDist +nodeStatNnv->evenBotDist);
        } else {
            evenLen = MAXSHORTINT;
        }
Alan Mishchenko committed
1407

1408 1409 1410
        NnvPathLength = (oddLen <= evenLen) ? oddLen : evenLen;
        NnvBotDist = (oddLen <= evenLen) ? nodeStatNnv->oddBotDist :
                                                   nodeStatNnv->evenBotDist;
Alan Mishchenko committed
1411 1412 1413 1414 1415
    }

    tiebreakChild = (NvBotDist <= NnvBotDist) ? 1 : 0;
    /* while both children not processed */
    while (processingDone != 2) {
1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432
        if (!processingDone) {
            /* if no child processed */
            /* pick the child with shortest path length and record which one
             * picked
             */
            if ((NvPathLength < NnvPathLength) ||
                ((NvPathLength == NnvPathLength) && (tiebreakChild == 1))) {
                child = Nv;
                regChild = regNv;
                thenDone = 1;
                childPathLength = NvPathLength;
            } else {
                child = Nnv;
                regChild = regNnv;
                elseDone = 1;
                childPathLength = NnvPathLength;
            } /* then path length less than else path length */
Alan Mishchenko committed
1433
        } else {
1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453
            /* if one child processed, process the other */
            if (thenDone) {
                child = Nnv;
                regChild = regNnv;
                elseDone = 1;
                childPathLength = NnvPathLength;
            } else {
                child = Nv;
                regChild = regNv;
                thenDone = 1;
                childPathLength = NvPathLength;
            } /* end of else pick the Then child if ELSE child processed */
        } /* end of else one child has been processed */

        /* ignore (replace with constant 0) all nodes which lie on paths larger
         * than the maximum length of the path required
         */
        if (childPathLength > info->maxpath) {
            /* record nodes visited */
            childBranch = zero;
Alan Mishchenko committed
1454
        } else {
1455 1456 1457
            if (childPathLength < info->maxpath) {
                if (info->findShortestPath) {
                    info->findShortestPath = 0;
Alan Mishchenko committed
1458
                }
1459 1460 1461 1462 1463 1464
                childBranch = BuildSubsetBdd(dd, pathTable, child, info,
                                             subsetNodeTable);

            } else { /* Case: path length of node = maxpath */
                /* If the node labeled with maxpath is found in the
                ** maxpathTable, use it to build the subset BDD.  */
1465
                if ( st__lookup(info->maxpathTable, (char *)regChild,
1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480
                              (char **)&entry)) {
                    /* When a node that is already been chosen is hit,
                    ** the quest for a complete path is over.  */
                    if (info->findShortestPath) {
                        info->findShortestPath = 0;
                    }
                    childBranch = BuildSubsetBdd(dd, pathTable, child, info,
                                                 subsetNodeTable);
                } else {
                    /* If node is not found in the maxpathTable and
                    ** the threshold has been reached, then if the
                    ** path needs to be completed, continue. Else
                    ** replace the node with a zero.  */
                    if (info->thresholdReached <= 0) {
                        if (info->findShortestPath) {
1481 1482
                            if ( st__insert(info->maxpathTable, (char *)regChild,
                                          (char *)NIL(char)) == st__OUT_OF_MEM) {
1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497
                                memOut = 1;
                                (void) fprintf(dd->err, "OUT of memory\n");
                                info->thresholdReached = 0;
                                childBranch = zero;
                            } else {
                                info->thresholdReached--;
                                childBranch = BuildSubsetBdd(dd, pathTable,
                                                    child, info,subsetNodeTable);
                            }
                        } else { /* not find shortest path, we dont need this
                                    node */
                            childBranch = zero;
                        }
                    } else { /* Threshold hasn't been reached,
                             ** need the node. */
1498 1499
                        if ( st__insert(info->maxpathTable, (char *)regChild,
                                      (char *)NIL(char)) == st__OUT_OF_MEM) {
1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511
                            memOut = 1;
                            (void) fprintf(dd->err, "OUT of memory\n");
                            info->thresholdReached = 0;
                            childBranch = zero;
                        } else {
                            info->thresholdReached--;
                            if (info->thresholdReached <= 0) {
                                info->findShortestPath = 1;
                            }
                            childBranch = BuildSubsetBdd(dd, pathTable,
                                                 child, info, subsetNodeTable);

1512
                        } /* end of st__insert successful */
1513 1514 1515 1516 1517 1518 1519 1520 1521
                    } /* end of threshold hasnt been reached yet */
                } /* end of else node not found in maxpath table */
            } /* end of if (path length of node = maxpath) */
        } /* end if !(childPathLength > maxpath) */
        if (childBranch == NULL) {
            /* deref other stuff incase reordering has taken place */
            if (ThenBranch != NULL) {
                Cudd_RecursiveDeref(dd, ThenBranch);
                ThenBranch = NULL;
Alan Mishchenko committed
1522
            }
1523 1524 1525 1526 1527
            if (ElseBranch != NULL) {
                Cudd_RecursiveDeref(dd, ElseBranch);
                ElseBranch = NULL;
            }
            return(NULL);
Alan Mishchenko committed
1528 1529
        }

1530
        cuddRef(childBranch);
Alan Mishchenko committed
1531

1532 1533 1534 1535 1536 1537
        if (child == Nv) {
            ThenBranch = childBranch;
        } else {
            ElseBranch = childBranch;
        }
        processingDone++;
Alan Mishchenko committed
1538

1539
    } /*end of while processing Nv, Nnv */
Alan Mishchenko committed
1540 1541 1542 1543 1544 1545 1546

    info->findShortestPath = 0;
    topid = Cudd_NodeReadIndex(N);
    topv = Cudd_ReadVars(dd, topid);
    cuddRef(topv);
    neW = cuddBddIteRecur(dd, topv, ThenBranch, ElseBranch);
    if (neW != NULL) {
1547
        cuddRef(neW);
Alan Mishchenko committed
1548 1549 1550 1551 1552 1553 1554
    }
    Cudd_RecursiveDeref(dd, topv);
    Cudd_RecursiveDeref(dd, ThenBranch);
    Cudd_RecursiveDeref(dd, ElseBranch);


    /* Hard Limit of threshold has been imposed */
1555
    if (subsetNodeTable != NIL( st__table)) {
1556 1557 1558 1559 1560
        /* check if a new node is created */
        regNew = Cudd_Regular(neW);
        /* subset node table keeps all new nodes that have been created to keep
         * a running count of how many nodes have been built in the subset.
         */
1561
        if (! st__lookup(subsetNodeTable, (char *)regNew, (char **)&entry)) {
1562
            if (!Cudd_IsConstant(regNew)) {
1563 1564
                if ( st__insert(subsetNodeTable, (char *)regNew,
                              (char *)NULL) == st__OUT_OF_MEM) {
1565 1566 1567
                    (void) fprintf(dd->err, "Out of memory\n");
                    return (NULL);
                }
1568
                if ( st__count(subsetNodeTable) > info->threshold) {
1569 1570 1571
                    info->thresholdReached = 0;
                }
            }
Alan Mishchenko committed
1572 1573 1574 1575 1576
        }
    }


    if (neW == NULL) {
1577
        return(NULL);
Alan Mishchenko committed
1578
    } else {
1579 1580 1581 1582 1583 1584 1585 1586 1587
        /*store computed result in regular form*/
        if (Cudd_IsComplement(node)) {
            nodeStat->compResult = neW;
            cuddRef(nodeStat->compResult);
            /* if the new node is the same as the corresponding node in the
             * original bdd then its complement need not be computed as it
             * cannot be larger than the node itself
             */
            if (neW == node) {
Alan Mishchenko committed
1588
#ifdef DD_DEBUG
1589
                thishit++;
Alan Mishchenko committed
1590
#endif
1591 1592 1593 1594 1595 1596 1597 1598 1599 1600
                /* if a result for the node has already been computed, then
                 * it can only be smaller than teh node itself. hence store
                 * the node result in order not to break recombination
                 */
                if (nodeStat->regResult != NULL) {
                    Cudd_RecursiveDeref(dd, nodeStat->regResult);
                }
                nodeStat->regResult = Cudd_Not(neW);
                cuddRef(nodeStat->regResult);
            }
Alan Mishchenko committed
1601

1602 1603 1604 1605
        } else {
            nodeStat->regResult = neW;
            cuddRef(nodeStat->regResult);
            if (neW == node) {
Alan Mishchenko committed
1606
#ifdef DD_DEBUG
1607
                thishit++;
Alan Mishchenko committed
1608
#endif
1609 1610 1611 1612 1613 1614
                if (nodeStat->compResult != NULL) {
                    Cudd_RecursiveDeref(dd, nodeStat->compResult);
                }
                nodeStat->compResult = Cudd_Not(neW);
                cuddRef(nodeStat->compResult);
            }
Alan Mishchenko committed
1615 1616
        }

1617 1618
        cuddDeref(neW);
        return(neW);
Alan Mishchenko committed
1619 1620 1621 1622 1623 1624
    } /* end of else i.e. Subset != NULL */
} /* end of BuildSubsetBdd */


/**Function********************************************************************

1625
  Synopsis     [Procedure to free te result dds stored in the NodeDist pages.]
Alan Mishchenko committed
1626 1627 1628 1629 1630 1631 1632 1633

  Description [None]

  SideEffects [None]

  SeeAlso     []

******************************************************************************/
1634
static enum st__retval
Alan Mishchenko committed
1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645
stPathTableDdFree(
  char * key,
  char * value,
  char * arg)
{
    NodeDist_t *nodeStat;
    DdManager *dd;

    nodeStat = (NodeDist_t *)value;
    dd = (DdManager *)arg;
    if (nodeStat->regResult != NULL) {
1646
        Cudd_RecursiveDeref(dd, nodeStat->regResult);
Alan Mishchenko committed
1647 1648
    }
    if (nodeStat->compResult != NULL) {
1649
        Cudd_RecursiveDeref(dd, nodeStat->compResult);
Alan Mishchenko committed
1650
    }
1651
    return( st__CONTINUE);
Alan Mishchenko committed
1652 1653

} /* end of stPathTableFree */
1654 1655


1656 1657
ABC_NAMESPACE_IMPL_END