cuddZddReord.c 49.3 KB
Newer Older
Alan Mishchenko committed
1 2 3 4 5 6 7 8 9
/**CFile***********************************************************************

  FileName    [cuddZddReord.c]

  PackageName [cudd]

  Synopsis    [Procedures for dynamic variable ordering of ZDDs.]

  Description [External procedures included in this module:
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
                    <ul>
                    <li> Cudd_zddReduceHeap()
                    <li> Cudd_zddShuffleHeap()
                    </ul>
               Internal procedures included in this module:
                    <ul>
                    <li> cuddZddAlignToBdd()
                    <li> cuddZddNextHigh()
                    <li> cuddZddNextLow()
                    <li> cuddZddUniqueCompare()
                    <li> cuddZddSwapInPlace()
                    <li> cuddZddSwapping()
                    <li> cuddZddSifting()
                    </ul>
               Static procedures included in this module:
                    <ul>
                    <li> zddSwapAny()
                    <li> cuddZddSiftingAux()
                    <li> cuddZddSiftingUp()
                    <li> cuddZddSiftingDown()
                    <li> cuddZddSiftingBackward()
                    <li> zddReorderPreprocess()
                    <li> zddReorderPostprocess()
                    <li> zddShuffle()
                    <li> zddSiftUp()
                    </ul>
              ]
Alan Mishchenko committed
37 38 39 40 41

  SeeAlso     []

  Author      [Hyong-Kyoon Shin, In-Ho Moon]

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
  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
73 74 75

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

76
#include "misc/util/util_hack.h"
77
#include "cuddInt.h"
Alan Mishchenko committed
78

79 80 81
ABC_NAMESPACE_IMPL_START


82

Alan Mishchenko committed
83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104
/*---------------------------------------------------------------------------*/
/* Constant declarations                                                     */
/*---------------------------------------------------------------------------*/

#define DD_MAX_SUBTABLE_SPARSITY 8
#define DD_SHRINK_FACTOR 2

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


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


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

#ifndef lint
105
static char rcsid[] DD_UNUSED = "$Id: cuddZddReord.c,v 1.47 2004/08/13 18:04:53 fabio Exp $";
Alan Mishchenko committed
106 107
#endif

108
int     *zdd_entry;
Alan Mishchenko committed
109

110
int     zddTotalNumberSwapping;
Alan Mishchenko committed
111

112
static  DdNode  *empty;
Alan Mishchenko committed
113 114 115 116 117 118 119 120 121 122 123 124 125


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


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

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

126 127 128 129 130 131 132 133 134 135
static Move * zddSwapAny (DdManager *table, int x, int y);
static int cuddZddSiftingAux (DdManager *table, int x, int x_low, int x_high);
static Move * cuddZddSiftingUp (DdManager *table, int x, int x_low, int initial_size);
static Move * cuddZddSiftingDown (DdManager *table, int x, int x_high, int initial_size);
static int cuddZddSiftingBackward (DdManager *table, Move *moves, int size);
static void zddReorderPreprocess (DdManager *table);
static int zddReorderPostprocess (DdManager *table);
static int zddShuffle (DdManager *table, int *permutation);
static int zddSiftUp (DdManager *table, int x, int xLow);
static void zddFixTree (DdManager *table, MtrNode *treenode);
Alan Mishchenko committed
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

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


/*---------------------------------------------------------------------------*/
/* Definition of exported functions                                          */
/*---------------------------------------------------------------------------*/


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

  Synopsis    [Main dynamic reordering routine for ZDDs.]

  Description [Main dynamic reordering routine for ZDDs.
  Calls one of the possible reordering procedures:
  <ul>
  <li>Swapping
  <li>Sifting
  <li>Symmetric Sifting
  </ul>

  For sifting and symmetric sifting it is possible to request reordering
  to convergence.<p>

  The core of all methods is the reordering procedure
  cuddZddSwapInPlace() which swaps two adjacent variables.
  Returns 1 in case of success; 0 otherwise. In the case of symmetric
  sifting (with and without convergence) returns 1 plus the number of
  symmetric variables, in case of success.]

  SideEffects [Changes the variable order for all ZDDs and clears
  the cache.]

******************************************************************************/
int
Cudd_zddReduceHeap(
  DdManager * table /* DD manager */,
  Cudd_ReorderingType heuristic /* method used for reordering */,
  int minsize /* bound below which no reordering occurs */)
{
176 177
    DdHook       *hook;
    int          result;
Alan Mishchenko committed
178 179 180 181 182
    unsigned int nextDyn;
#ifdef DD_STATS
    unsigned int initialSize;
    unsigned int finalSize;
#endif
183
    long         localTime;
Alan Mishchenko committed
184 185 186

    /* Don't reorder if there are too many dead nodes. */
    if (table->keysZ - table->deadZ < (unsigned) minsize)
187
        return(1);
Alan Mishchenko committed
188 189

    if (heuristic == CUDD_REORDER_SAME) {
190
        heuristic = table->autoMethodZ;
Alan Mishchenko committed
191 192
    }
    if (heuristic == CUDD_REORDER_NONE) {
193
        return(1);
Alan Mishchenko committed
194 195 196 197 198 199 200 201 202 203 204 205 206
    }

    /* This call to Cudd_zddReduceHeap does initiate reordering. Therefore
    ** we count it.
    */
    table->reorderings++;
    empty = table->zero;

    localTime = util_cpu_time();

    /* Run the hook functions. */
    hook = table->preReorderingHook;
    while (hook != NULL) {
207 208 209
        int res = (hook->f)(table, "ZDD", (void *)heuristic);
        if (res == 0) return(0);
        hook = hook->next;
Alan Mishchenko committed
210 211 212 213 214 215 216 217 218 219 220 221
    }

    /* Clear the cache and collect garbage. */
    zddReorderPreprocess(table);
    zddTotalNumberSwapping = 0;

#ifdef DD_STATS
    initialSize = table->keysZ;

    switch(heuristic) {
    case CUDD_REORDER_RANDOM:
    case CUDD_REORDER_RANDOM_PIVOT:
222 223
        (void) fprintf(table->out,"#:I_RANDOM  ");
        break;
Alan Mishchenko committed
224 225 226 227
    case CUDD_REORDER_SIFT:
    case CUDD_REORDER_SIFT_CONVERGE:
    case CUDD_REORDER_SYMM_SIFT:
    case CUDD_REORDER_SYMM_SIFT_CONV:
228 229
        (void) fprintf(table->out,"#:I_SIFTING ");
        break;
Alan Mishchenko committed
230 231
    case CUDD_REORDER_LINEAR:
    case CUDD_REORDER_LINEAR_CONVERGE:
232 233
        (void) fprintf(table->out,"#:I_LINSIFT ");
        break;
Alan Mishchenko committed
234
    default:
235 236
        (void) fprintf(table->err,"Unsupported ZDD reordering method\n");
        return(0);
Alan Mishchenko committed
237 238 239 240 241 242 243 244 245 246 247
    }
    (void) fprintf(table->out,"%8d: initial size",initialSize); 
#endif

    result = cuddZddTreeSifting(table,heuristic);

#ifdef DD_STATS
    (void) fprintf(table->out,"\n");
    finalSize = table->keysZ;
    (void) fprintf(table->out,"#:F_REORDER %8d: final size\n",finalSize); 
    (void) fprintf(table->out,"#:T_REORDER %8g: total time (sec)\n",
248
                   ((double)(util_cpu_time() - localTime)/1000.0)); 
Alan Mishchenko committed
249
    (void) fprintf(table->out,"#:N_REORDER %8d: total swaps\n",
250
                   zddTotalNumberSwapping);
Alan Mishchenko committed
251 252 253
#endif

    if (result == 0)
254
        return(0);
Alan Mishchenko committed
255 256

    if (!zddReorderPostprocess(table))
257
        return(0);
Alan Mishchenko committed
258 259

    if (table->realignZ) {
260 261
        if (!cuddBddAlignToZdd(table))
            return(0);
Alan Mishchenko committed
262 263 264 265
    }

    nextDyn = table->keysZ * DD_DYN_RATIO;
    if (table->reorderings < 20 || nextDyn > table->nextDyn)
266
        table->nextDyn = nextDyn;
Alan Mishchenko committed
267
    else
268
        table->nextDyn += 20;
Alan Mishchenko committed
269 270 271 272 273 274

    table->reordered = 1;

    /* Run hook functions. */
    hook = table->postReorderingHook;
    while (hook != NULL) {
275 276 277
        int res = (hook->f)(table, "ZDD", (void *)localTime);
        if (res == 0) return(0);
        hook = hook->next;
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
    }
    /* Update cumulative reordering time. */
    table->reordTime += util_cpu_time() - localTime;

    return(result);

} /* end of Cudd_zddReduceHeap */


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

  Synopsis    [Reorders ZDD variables according to given permutation.]

  Description [Reorders ZDD variables according to given permutation.
  The i-th entry of the permutation array contains the index of the variable
  that should be brought to the i-th level.  The size of the array should be
  equal or greater to the number of variables currently in use.
  Returns 1 in case of success; 0 otherwise.]

  SideEffects [Changes the ZDD variable order for all diagrams and clears
  the cache.]

  SeeAlso [Cudd_zddReduceHeap]

******************************************************************************/
int
Cudd_zddShuffleHeap(
  DdManager * table /* DD manager */,
  int * permutation /* required variable permutation */)
{

309
    int result;
Alan Mishchenko committed
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

    empty = table->zero;
    zddReorderPreprocess(table);

    result = zddShuffle(table,permutation);

    if (!zddReorderPostprocess(table)) return(0);

    return(result);

} /* end of Cudd_zddShuffleHeap */


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


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

  Synopsis    [Reorders ZDD variables according to the order of the BDD
  variables.]

  Description [Reorders ZDD variables according to the order of the
  BDD variables. This function can be called at the end of BDD
  reordering to insure that the order of the ZDD variables is
  consistent with the order of the BDD variables. The number of ZDD
  variables must be a multiple of the number of BDD variables. Let
  <code>M</code> be the ratio of the two numbers. cuddZddAlignToBdd
  then considers the ZDD variables from <code>M*i</code> to
  <code>(M+1)*i-1</code> as corresponding to BDD variable
  <code>i</code>.  This function should be normally called from
  Cudd_ReduceHeap, which clears the cache.  Returns 1 in case of
  success; 0 otherwise.]

  SideEffects [Changes the ZDD variable order for all diagrams and performs
  garbage collection of the ZDD unique table.]

  SeeAlso [Cudd_zddShuffleHeap Cudd_ReduceHeap]

******************************************************************************/
int
cuddZddAlignToBdd(
  DdManager * table /* DD manager */)
{
355 356 357 358
    int *invpermZ;              /* permutation array */
    int M;                      /* ratio of ZDD variables to BDD variables */
    int i,j;                    /* loop indices */
    int result;                 /* return value */
Alan Mishchenko committed
359 360 361

    /* We assume that a ratio of 0 is OK. */
    if (table->sizeZ == 0)
362
        return(1);
Alan Mishchenko committed
363 364 365 366 367 368 369

    empty = table->zero;
    M = table->sizeZ / table->size;
    /* Check whether the number of ZDD variables is a multiple of the
    ** number of BDD variables.
    */
    if (M * table->size != table->sizeZ)
370
        return(0);
Alan Mishchenko committed
371
    /* Create and initialize the inverse permutation array. */
Alan Mishchenko committed
372
    invpermZ = ABC_ALLOC(int,table->sizeZ);
Alan Mishchenko committed
373
    if (invpermZ == NULL) {
374 375
        table->errorCode = CUDD_MEMORY_OUT;
        return(0);
Alan Mishchenko committed
376 377
    }
    for (i = 0; i < table->size; i++) {
378 379 380 381 382 383 384
        int index = table->invperm[i];
        int indexZ = index * M;
        int levelZ = table->permZ[indexZ];
        levelZ = (levelZ / M) * M;
        for (j = 0; j < M; j++) {
            invpermZ[M * i + j] = table->invpermZ[levelZ + j];
        }
Alan Mishchenko committed
385 386 387 388
    }
    /* Eliminate dead nodes. Do not scan the cache again, because we
    ** assume that Cudd_ReduceHeap has already cleared it.
    */
389
    cuddGarbageCollect(table,0);
Alan Mishchenko committed
390 391

    result = zddShuffle(table, invpermZ);
Alan Mishchenko committed
392
    ABC_FREE(invpermZ);
Alan Mishchenko committed
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
    /* Fix the ZDD variable group tree. */
    zddFixTree(table,table->treeZ);
    return(result);
    
} /* end of cuddZddAlignToBdd */


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

  Synopsis    [Finds the next subtable with a larger index.]

  Description [Finds the next subtable with a larger index. Returns the
  index.]

  SideEffects [None]

  SeeAlso     []

******************************************************************************/
int
cuddZddNextHigh(
  DdManager * table,
  int  x)
{
    return(x + 1);

} /* end of cuddZddNextHigh */


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

  Synopsis    [Finds the next subtable with a smaller index.]

  Description [Finds the next subtable with a smaller index. Returns the
  index.]

  SideEffects [None]

  SeeAlso     []

******************************************************************************/
int
cuddZddNextLow(
  DdManager * table,
  int  x)
{
    return(x - 1);

} /* end of cuddZddNextLow */


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

  Synopsis [Comparison function used by qsort.]

  Description [Comparison function used by qsort to order the
  variables according to the number of keys in the subtables.
  Returns the difference in number of keys between the two
  variables being compared.]

  SideEffects [None]

  SeeAlso     []

******************************************************************************/
int
cuddZddUniqueCompare(
  int * ptr_x,
  int * ptr_y)
{
    return(zdd_entry[*ptr_y] - zdd_entry[*ptr_x]);

} /* end of cuddZddUniqueCompare */


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

  Synopsis    [Swaps two adjacent variables.]

  Description [Swaps two adjacent variables. It assumes that no dead
  nodes are present on entry to this procedure.  The procedure then
  guarantees that no dead nodes will be present when it terminates.
  cuddZddSwapInPlace assumes that x &lt; y.  Returns the number of keys in
  the table if successful; 0 otherwise.]

  SideEffects [None]

  SeeAlso     []

******************************************************************************/
int
cuddZddSwapInPlace(
  DdManager * table,
  int  x,
  int  y)
{
489 490 491 492
    DdNodePtr   *xlist, *ylist;
    int         xindex, yindex;
    int         xslots, yslots;
    int         xshift, yshift;
Alan Mishchenko committed
493 494
    int         oldxkeys, oldykeys;
    int         newxkeys, newykeys;
495 496 497
    int         i;
    int         posn;
    DdNode      *f, *f1, *f0, *f11, *f10, *f01, *f00;
498
    DdNode      *newf1=NULL, *newf0, *next;
499
    DdNodePtr   g, *lastP, *previousP;
Alan Mishchenko committed
500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535

#ifdef DD_DEBUG
    assert(x < y);
    assert(cuddZddNextHigh(table,x) == y);
    assert(table->subtableZ[x].keys != 0);
    assert(table->subtableZ[y].keys != 0);
    assert(table->subtableZ[x].dead == 0);
    assert(table->subtableZ[y].dead == 0);
#endif

    zddTotalNumberSwapping++;

    /* Get parameters of x subtable. */
    xindex   = table->invpermZ[x];
    xlist    = table->subtableZ[x].nodelist;
    oldxkeys = table->subtableZ[x].keys;
    xslots   = table->subtableZ[x].slots;
    xshift   = table->subtableZ[x].shift;
    newxkeys = 0;

    yindex   = table->invpermZ[y];
    ylist    = table->subtableZ[y].nodelist;
    oldykeys = table->subtableZ[y].keys;
    yslots   = table->subtableZ[y].slots;
    yshift   = table->subtableZ[y].shift;
    newykeys = oldykeys;

    /* The nodes in the x layer that don't depend on y directly
    ** will stay there; the others are put in a chain.
    ** The chain is handled as a FIFO; g points to the beginning and
    ** last points to the end.
    */

    g = NULL;
    lastP = &g;
    for (i = 0; i < xslots; i++) {
536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553
        previousP = &(xlist[i]);
        f = *previousP;
        while (f != NULL) {
            next = f->next;
            f1 = cuddT(f); f0 = cuddE(f);
            if ((f1->index != (DdHalfWord) yindex) &&
                (f0->index != (DdHalfWord) yindex)) { /* stays */
                newxkeys++;
                *previousP = f;
                previousP = &(f->next);
            } else {
                f->index = yindex;
                *lastP = f;
                lastP = &(f->next);
            }
            f = next;
        } /* while there are elements in the collision chain */
        *previousP = NULL;
Alan Mishchenko committed
554 555 556 557 558 559 560 561 562 563 564 565 566
    } /* for each slot of the x subtable */
    *lastP = NULL;


#ifdef DD_COUNT
    table->swapSteps += oldxkeys - newxkeys;
#endif
    /* Take care of the x nodes that must be re-expressed.
    ** They form a linked list pointed by g. Their index has been
    ** changed to yindex already.
    */
    f = g;
    while (f != NULL) {
567 568 569 570 571 572 573
        next = f->next;
        /* Find f1, f0, f11, f10, f01, f00. */
        f1 = cuddT(f);
        if ((int) f1->index == yindex) {
            f11 = cuddT(f1); f10 = cuddE(f1);
        } else {
            f11 = empty; f10 = f1;
Alan Mishchenko committed
574
        }
575 576 577 578 579
        f0 = cuddE(f);
        if ((int) f0->index == yindex) {
            f01 = cuddT(f0); f00 = cuddE(f0);
        } else {
            f01 = empty; f00 = f0;
Alan Mishchenko committed
580
        }
581 582 583 584 585 586 587 588 589 590 591 592 593 594

        /* Decrease ref count of f1. */
        cuddSatDec(f1->ref);
        /* Create the new T child. */
        if (f11 == empty) {
            if (f01 != empty) {
                newf1 = f01;
                cuddSatInc(newf1->ref);
            }
            /* else case was already handled when finding nodes
            ** with both children below level y
            */
        } else {
            /* Check xlist for triple (xindex, f11, f01). */
595
            posn = ddHash(cuddF2L(f11), cuddF2L(f01), xshift);
596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620
            /* For each element newf1 in collision list xlist[posn]. */
            newf1 = xlist[posn];
            while (newf1 != NULL) {
                if (cuddT(newf1) == f11 && cuddE(newf1) == f01) {
                    cuddSatInc(newf1->ref);
                    break; /* match */
                }
                newf1 = newf1->next;
            } /* while newf1 */
            if (newf1 == NULL) {        /* no match */
                newf1 = cuddDynamicAllocNode(table);
                if (newf1 == NULL)
                    goto zddSwapOutOfMem;
                newf1->index = xindex; newf1->ref = 1;
                cuddT(newf1) = f11;
                cuddE(newf1) = f01;
                /* Insert newf1 in the collision list xlist[pos];
                ** increase the ref counts of f11 and f01
                */
                newxkeys++;
                newf1->next = xlist[posn];
                xlist[posn] = newf1;
                cuddSatInc(f11->ref);
                cuddSatInc(f01->ref);
            }
Alan Mishchenko committed
621
        }
622 623 624 625 626 627 628 629
        cuddT(f) = newf1;

        /* Do the same for f0. */
        /* Decrease ref count of f0. */
        cuddSatDec(f0->ref);
        /* Create the new E child. */
        if (f10 == empty) {
            newf0 = f00;
Alan Mishchenko committed
630
            cuddSatInc(newf0->ref);
631 632
        } else {
            /* Check xlist for triple (xindex, f10, f00). */
633
            posn = ddHash(cuddF2L(f10), cuddF2L(f00), xshift);
634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657
            /* For each element newf0 in collision list xlist[posn]. */
            newf0 = xlist[posn];
            while (newf0 != NULL) {
                if (cuddT(newf0) == f10 && cuddE(newf0) == f00) {
                    cuddSatInc(newf0->ref);
                    break; /* match */
                }
                newf0 = newf0->next;
            } /* while newf0 */
            if (newf0 == NULL) {        /* no match */
                newf0 = cuddDynamicAllocNode(table);
                if (newf0 == NULL)
                    goto zddSwapOutOfMem;
                newf0->index = xindex; newf0->ref = 1;
                cuddT(newf0) = f10; cuddE(newf0) = f00;
                /* Insert newf0 in the collision list xlist[posn];
                ** increase the ref counts of f10 and f00.
                */
                newxkeys++;
                newf0->next = xlist[posn];
                xlist[posn] = newf0;
                cuddSatInc(f10->ref);
                cuddSatInc(f00->ref);
            }
Alan Mishchenko committed
658
        }
659
        cuddE(f) = newf0;
Alan Mishchenko committed
660

661 662 663 664
        /* Insert the modified f in ylist.
        ** The modified f does not already exists in ylist.
        ** (Because of the uniqueness of the cofactors.)
        */
665
        posn = ddHash(cuddF2L(newf1), cuddF2L(newf0), yshift);
666 667 668 669
        newykeys++;
        f->next = ylist[posn];
        ylist[posn] = f;
        f = next;
Alan Mishchenko committed
670 671 672 673 674 675
    } /* while f != NULL */

    /* GC the y layer. */

    /* For each node f in ylist. */
    for (i = 0; i < yslots; i++) {
676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691
        previousP = &(ylist[i]);
        f = *previousP;
        while (f != NULL) {
            next = f->next;
            if (f->ref == 0) {
                cuddSatDec(cuddT(f)->ref);
                cuddSatDec(cuddE(f)->ref);
                cuddDeallocNode(table, f);
                newykeys--;
            } else {
                *previousP = f;
                previousP = &(f->next);
            }
            f = next;
        } /* while f */
        *previousP = NULL;
Alan Mishchenko committed
692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751
    } /* for i */

    /* Set the appropriate fields in table. */
    table->subtableZ[x].nodelist = ylist;
    table->subtableZ[x].slots    = yslots;
    table->subtableZ[x].shift    = yshift;
    table->subtableZ[x].keys     = newykeys;
    table->subtableZ[x].maxKeys  = yslots * DD_MAX_SUBTABLE_DENSITY;

    table->subtableZ[y].nodelist = xlist;
    table->subtableZ[y].slots    = xslots;
    table->subtableZ[y].shift    = xshift;
    table->subtableZ[y].keys     = newxkeys;
    table->subtableZ[y].maxKeys  = xslots * DD_MAX_SUBTABLE_DENSITY;

    table->permZ[xindex] = y; table->permZ[yindex] = x;
    table->invpermZ[x] = yindex; table->invpermZ[y] = xindex;

    table->keysZ += newxkeys + newykeys - oldxkeys - oldykeys;

    /* Update univ section; univ[x] remains the same. */
    table->univ[y] = cuddT(table->univ[x]);

    return (table->keysZ);

zddSwapOutOfMem:
    (void) fprintf(table->err, "Error: cuddZddSwapInPlace out of memory\n");

    return (0);

} /* end of cuddZddSwapInPlace */


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

  Synopsis    [Reorders variables by a sequence of (non-adjacent) swaps.]

  Description [Implementation of Plessier's algorithm that reorders
  variables by a sequence of (non-adjacent) swaps.
    <ol>
    <li> Select two variables (RANDOM or HEURISTIC).
    <li> Permute these variables.
    <li> If the nodes have decreased accept the permutation.
    <li> Otherwise reconstruct the original heap.
    <li> Loop.
    </ol>
  Returns 1 in case of success; 0 otherwise.]

  SideEffects [None]

  SeeAlso     []

******************************************************************************/
int
cuddZddSwapping(
  DdManager * table,
  int lower,
  int upper,
  Cudd_ReorderingType heuristic)
{
752
    int i, j;
Alan Mishchenko committed
753 754
    int max, keys;
    int nvars;
755
    int x, y;
Alan Mishchenko committed
756 757 758
    int iterate;
    int previousSize;
    Move *moves, *move;
759
    int pivot = -1;
Alan Mishchenko committed
760 761 762 763 764 765 766 767 768 769 770 771
    int modulo;
    int result;

#ifdef DD_DEBUG
    /* Sanity check */
    assert(lower >= 0 && upper < table->sizeZ && lower <= upper);
#endif

    nvars = upper - lower + 1;
    iterate = nvars;

    for (i = 0; i < iterate; i++) {
772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798
        if (heuristic == CUDD_REORDER_RANDOM_PIVOT) {
            /* Find pivot <= id with maximum keys. */
            for (max = -1, j = lower; j <= upper; j++) {
                if ((keys = table->subtableZ[j].keys) > max) {
                    max = keys;
                    pivot = j;
                }
            }

            modulo = upper - pivot;
            if (modulo == 0) {
                y = pivot;      /* y = nvars-1 */
            } else {
                /* y = random # from {pivot+1 .. nvars-1} */
                y = pivot + 1 + (int) (Cudd_Random() % modulo);
            }

            modulo = pivot - lower - 1;
            if (modulo < 1) {   /* if pivot = 1 or 0 */
                x = lower;
            } else {
                do { /* x = random # from {0 .. pivot-2} */
                    x = (int) Cudd_Random() % modulo;
                } while (x == y);
                  /* Is this condition really needed, since x and y
                     are in regions separated by pivot? */
            }
Alan Mishchenko committed
799
        } else {
800 801 802 803
            x = (int) (Cudd_Random() % nvars) + lower;
            do {
                y = (int) (Cudd_Random() % nvars) + lower;
            } while (x == y);
Alan Mishchenko committed
804 805
        }

806 807 808 809
        previousSize = table->keysZ;
        moves = zddSwapAny(table, x, y);
        if (moves == NULL)
            goto cuddZddSwappingOutOfMem;
Alan Mishchenko committed
810

811 812 813
        result = cuddZddSiftingBackward(table, moves, previousSize);
        if (!result)
            goto cuddZddSwappingOutOfMem;
Alan Mishchenko committed
814

815 816 817 818 819
        while (moves != NULL) {
            move = moves->next;
            cuddDeallocMove(table, moves);
            moves = move;
        }
Alan Mishchenko committed
820
#ifdef DD_STATS
821 822 823 824 825 826 827 828
        if (table->keysZ < (unsigned) previousSize) {
            (void) fprintf(table->out,"-");
        } else if (table->keysZ > (unsigned) previousSize) {
            (void) fprintf(table->out,"+");     /* should never happen */
        } else {
            (void) fprintf(table->out,"=");
        }
        fflush(table->out);
Alan Mishchenko committed
829 830 831 832 833 834 835
#endif
    }

    return(1);

cuddZddSwappingOutOfMem:
    while (moves != NULL) {
836 837 838
        move = moves->next;
        cuddDeallocMove(table, moves);
        moves = move;
Alan Mishchenko committed
839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871
    }
    return(0);

} /* end of cuddZddSwapping */


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

  Synopsis    [Implementation of Rudell's sifting algorithm.]

  Description [Implementation of Rudell's sifting algorithm.
  Assumes that no dead nodes are present.
    <ol>
    <li> Order all the variables according to the number of entries
    in each unique table.
    <li> Sift the variable up and down, remembering each time the
    total size of the DD heap.
    <li> Select the best permutation.
    <li> Repeat 3 and 4 for all variables.
    </ol>
  Returns 1 if successful; 0 otherwise.]

  SideEffects [None]

  SeeAlso     []

******************************************************************************/
int
cuddZddSifting(
  DdManager * table,
  int  lower,
  int  upper)
{
872 873 874 875 876
    int i;
    int *var;
    int size;
    int x;
    int result;
Alan Mishchenko committed
877
#ifdef DD_STATS
878
    int previousSize;
Alan Mishchenko committed
879 880 881 882 883 884
#endif

    size = table->sizeZ;

    /* Find order in which to sift variables. */
    var = NULL;
Alan Mishchenko committed
885
    zdd_entry = ABC_ALLOC(int, size);
Alan Mishchenko committed
886
    if (zdd_entry == NULL) {
887 888
        table->errorCode = CUDD_MEMORY_OUT;
        goto cuddZddSiftingOutOfMem;
Alan Mishchenko committed
889
    }
Alan Mishchenko committed
890
    var = ABC_ALLOC(int, size);
Alan Mishchenko committed
891
    if (var == NULL) {
892 893
        table->errorCode = CUDD_MEMORY_OUT;
        goto cuddZddSiftingOutOfMem;
Alan Mishchenko committed
894 895 896
    }

    for (i = 0; i < size; i++) {
897 898 899
        x = table->permZ[i];
        zdd_entry[i] = table->subtableZ[x].keys;
        var[i] = i;
Alan Mishchenko committed
900 901
    }

902
    qsort((void *)var, (size_t)size, sizeof(int), (DD_QSFP)cuddZddUniqueCompare);
Alan Mishchenko committed
903 904 905

    /* Now sift. */
    for (i = 0; i < ddMin(table->siftMaxVar, size); i++) {
906 907 908 909
        if (zddTotalNumberSwapping >= table->siftMaxSwap)
            break;
        x = table->permZ[var[i]];
        if (x < lower || x > upper) continue;
Alan Mishchenko committed
910
#ifdef DD_STATS
911
        previousSize = table->keysZ;
Alan Mishchenko committed
912
#endif
913 914 915
        result = cuddZddSiftingAux(table, x, lower, upper);
        if (!result)
            goto cuddZddSiftingOutOfMem;
Alan Mishchenko committed
916
#ifdef DD_STATS
917 918 919 920 921 922 923 924 925
        if (table->keysZ < (unsigned) previousSize) {
            (void) fprintf(table->out,"-");
        } else if (table->keysZ > (unsigned) previousSize) {
            (void) fprintf(table->out,"+");     /* should never happen */
            (void) fprintf(table->out,"\nSize increased from %d to %d while sifting variable %d\n", previousSize, table->keysZ , var[i]);
        } else {
            (void) fprintf(table->out,"=");
        }
        fflush(table->out);
Alan Mishchenko committed
926 927 928
#endif
    }

Alan Mishchenko committed
929 930
    ABC_FREE(var);
    ABC_FREE(zdd_entry);
Alan Mishchenko committed
931 932 933 934 935

    return(1);

cuddZddSiftingOutOfMem:

Alan Mishchenko committed
936 937
    if (zdd_entry != NULL) ABC_FREE(zdd_entry);
    if (var != NULL) ABC_FREE(var);
Alan Mishchenko committed
938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965

    return(0);

} /* end of cuddZddSifting */


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


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

  Synopsis    [Swaps any two variables.]

  Description [Swaps any two variables. Returns the set of moves.]

  SideEffects [None]

  SeeAlso     []

******************************************************************************/
static Move *
zddSwapAny(
  DdManager * table,
  int  x,
  int  y)
{
966 967 968 969 970 971 972 973
    Move        *move, *moves;
    int         tmp, size;
    int         x_ref, y_ref;
    int         x_next, y_next;
    int         limit_size;

    if (x > y) {        /* make x precede y */
        tmp = x; x = y; y = tmp;
Alan Mishchenko committed
974 975 976 977 978 979 980 981 982 983
    }

    x_ref = x; y_ref = y;

    x_next = cuddZddNextHigh(table, x);
    y_next = cuddZddNextLow(table, y);
    moves = NULL;
    limit_size = table->keysZ;

    for (;;) {
984 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 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063
        if (x_next == y_next) { /* x < x_next = y_next < y */
            size = cuddZddSwapInPlace(table, x, x_next);
            if (size == 0)
                goto zddSwapAnyOutOfMem;
            move = (Move *) cuddDynamicAllocNode(table);
            if (move == NULL)
                goto zddSwapAnyOutOfMem;
            move->x = x;
            move->y = x_next;
            move->size = size;
            move->next = moves;
            moves = move;

            size = cuddZddSwapInPlace(table, y_next, y);
            if (size == 0)
                goto zddSwapAnyOutOfMem;
            move = (Move *)cuddDynamicAllocNode(table);
            if (move == NULL)
                goto zddSwapAnyOutOfMem;
            move->x = y_next;
            move->y = y;
            move->size = size;
            move->next = moves;
            moves = move;

            size = cuddZddSwapInPlace(table, x, x_next);
            if (size == 0)
                goto zddSwapAnyOutOfMem;
            move = (Move *)cuddDynamicAllocNode(table);
            if (move == NULL)
                goto zddSwapAnyOutOfMem;
            move->x = x;
            move->y = x_next;
            move->size = size;
            move->next = moves;
            moves = move;

            tmp = x; x = y; y = tmp;

        } else if (x == y_next) { /* x = y_next < y = x_next */
            size = cuddZddSwapInPlace(table, x, x_next);
            if (size == 0)
                goto zddSwapAnyOutOfMem;
            move = (Move *)cuddDynamicAllocNode(table);
            if (move == NULL)
                goto zddSwapAnyOutOfMem;
            move->x = x;
            move->y = x_next;
            move->size = size;
            move->next = moves;
            moves = move;

            tmp = x; x = y;  y = tmp;
        } else {
            size = cuddZddSwapInPlace(table, x, x_next);
            if (size == 0)
                goto zddSwapAnyOutOfMem;
            move = (Move *)cuddDynamicAllocNode(table);
            if (move == NULL)
                goto zddSwapAnyOutOfMem;
            move->x = x;
            move->y = x_next;
            move->size = size;
            move->next = moves;
            moves = move;

            size = cuddZddSwapInPlace(table, y_next, y);
            if (size == 0)
                goto zddSwapAnyOutOfMem;
            move = (Move *)cuddDynamicAllocNode(table);
            if (move == NULL)
                goto zddSwapAnyOutOfMem;
            move->x = y_next;
            move->y = y;
            move->size = size;
            move->next = moves;
            moves = move;

            x = x_next; y = y_next;
        }
Alan Mishchenko committed
1064

1065 1066 1067 1068
        x_next = cuddZddNextHigh(table, x);
        y_next = cuddZddNextLow(table, y);
        if (x_next > y_ref)
            break;      /* if x == y_ref */
Alan Mishchenko committed
1069

1070 1071 1072 1073 1074 1075
        if ((double) size > table->maxGrowth * (double) limit_size)
            break;
        if (size < limit_size)
            limit_size = size;
    }
    if (y_next >= x_ref) {
Alan Mishchenko committed
1076 1077
        size = cuddZddSwapInPlace(table, y_next, y);
        if (size == 0)
1078
            goto zddSwapAnyOutOfMem;
Alan Mishchenko committed
1079 1080
        move = (Move *)cuddDynamicAllocNode(table);
        if (move == NULL)
1081
            goto zddSwapAnyOutOfMem;
Alan Mishchenko committed
1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092
        move->x = y_next;
        move->y = y;
        move->size = size;
        move->next = moves;
        moves = move;
    }

    return(moves);

zddSwapAnyOutOfMem:
    while (moves != NULL) {
1093 1094 1095
        move = moves->next;
        cuddDeallocMove(table, moves);
        moves = move;
Alan Mishchenko committed
1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122
    }
    return(NULL);

} /* end of zddSwapAny */


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

  Synopsis    [Given xLow <= x <= xHigh moves x up and down between the
  boundaries.]

  Description [Given xLow <= x <= xHigh moves x up and down between the
  boundaries. Finds the best position and does the required changes.
  Returns 1 if successful; 0 otherwise.]

  SideEffects [None]

  SeeAlso     []

******************************************************************************/
static int
cuddZddSiftingAux(
  DdManager * table,
  int  x,
  int  x_low,
  int  x_high)
{
1123 1124 1125
    Move        *move;
    Move        *moveUp;        /* list of up move */
    Move        *moveDown;      /* list of down move */
Alan Mishchenko committed
1126

1127 1128
    int         initial_size;
    int         result;
Alan Mishchenko committed
1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139

    initial_size = table->keysZ;

#ifdef DD_DEBUG
    assert(table->subtableZ[x].keys > 0);
#endif

    moveDown = NULL;
    moveUp = NULL;

    if (x == x_low) {
1140 1141 1142 1143 1144 1145 1146 1147 1148
        moveDown = cuddZddSiftingDown(table, x, x_high, initial_size);
        /* after that point x --> x_high */
        if (moveDown == NULL)
            goto cuddZddSiftingAuxOutOfMem;
        result = cuddZddSiftingBackward(table, moveDown,
            initial_size);
        /* move backward and stop at best position */
        if (!result)
            goto cuddZddSiftingAuxOutOfMem;
Alan Mishchenko committed
1149 1150 1151

    }
    else if (x == x_high) {
1152 1153 1154 1155 1156 1157 1158 1159
        moveUp = cuddZddSiftingUp(table, x, x_low, initial_size);
        /* after that point x --> x_low */
        if (moveUp == NULL)
            goto cuddZddSiftingAuxOutOfMem;
        result = cuddZddSiftingBackward(table, moveUp, initial_size);
        /* move backward and stop at best position */
        if (!result)
            goto cuddZddSiftingAuxOutOfMem;
Alan Mishchenko committed
1160 1161
    }
    else if ((x - x_low) > (x_high - x)) {
1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174
        /* must go down first:shorter */
        moveDown = cuddZddSiftingDown(table, x, x_high, initial_size);
        /* after that point x --> x_high */
        if (moveDown == NULL)
            goto cuddZddSiftingAuxOutOfMem;
        moveUp = cuddZddSiftingUp(table, moveDown->y, x_low,
            initial_size);
        if (moveUp == NULL)
            goto cuddZddSiftingAuxOutOfMem;
        result = cuddZddSiftingBackward(table, moveUp, initial_size);
        /* move backward and stop at best position */
        if (!result)
            goto cuddZddSiftingAuxOutOfMem;
Alan Mishchenko committed
1175 1176
    }
    else {
1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190
        moveUp = cuddZddSiftingUp(table, x, x_low, initial_size);
        /* after that point x --> x_high */
        if (moveUp == NULL)
            goto cuddZddSiftingAuxOutOfMem;
        moveDown = cuddZddSiftingDown(table, moveUp->x, x_high,
            initial_size);
        /* then move up */
        if (moveDown == NULL)
            goto cuddZddSiftingAuxOutOfMem;
        result = cuddZddSiftingBackward(table, moveDown,
            initial_size);
        /* move backward and stop at best position */
        if (!result)
            goto cuddZddSiftingAuxOutOfMem;
Alan Mishchenko committed
1191 1192 1193
    }

    while (moveDown != NULL) {
1194 1195 1196
        move = moveDown->next;
        cuddDeallocMove(table, moveDown);
        moveDown = move;
Alan Mishchenko committed
1197 1198
    }
    while (moveUp != NULL) {
1199 1200 1201
        move = moveUp->next;
        cuddDeallocMove(table, moveUp);
        moveUp = move;
Alan Mishchenko committed
1202 1203 1204 1205 1206 1207
    }

    return(1);

cuddZddSiftingAuxOutOfMem:
    while (moveDown != NULL) {
1208 1209 1210
        move = moveDown->next;
        cuddDeallocMove(table, moveDown);
        moveDown = move;
Alan Mishchenko committed
1211 1212
    }
    while (moveUp != NULL) {
1213 1214 1215
        move = moveUp->next;
        cuddDeallocMove(table, moveUp);
        moveUp = move;
Alan Mishchenko committed
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
    }

    return(0);

} /* end of cuddZddSiftingAux */


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

  Synopsis    [Sifts a variable up.]

  Description [Sifts a variable up. Moves y up until either it reaches
  the bound (x_low) or the size of the ZDD heap increases too much.
  Returns the set of moves in case of success; NULL if memory is full.]

  SideEffects [None]

  SeeAlso     []

******************************************************************************/
static Move *
cuddZddSiftingUp(
  DdManager * table,
  int  x,
  int  x_low,
  int  initial_size)
{
1243 1244 1245 1246 1247
    Move        *moves;
    Move        *move;
    int         y;
    int         size;
    int         limit_size = initial_size;
Alan Mishchenko committed
1248 1249 1250 1251

    moves = NULL;
    y = cuddZddNextLow(table, x);
    while (y >= x_low) {
1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265
        size = cuddZddSwapInPlace(table, y, x);
        if (size == 0)
            goto cuddZddSiftingUpOutOfMem;
        move = (Move *)cuddDynamicAllocNode(table);
        if (move == NULL)
            goto cuddZddSiftingUpOutOfMem;
        move->x = y;
        move->y = x;
        move->size = size;
        move->next = moves;
        moves = move;

        if ((double)size > (double)limit_size * table->maxGrowth)
            break;
Alan Mishchenko committed
1266
        if (size < limit_size)
1267
            limit_size = size;
Alan Mishchenko committed
1268

1269 1270
        x = y;
        y = cuddZddNextLow(table, x);
Alan Mishchenko committed
1271 1272 1273 1274 1275
    }
    return(moves);

cuddZddSiftingUpOutOfMem:
    while (moves != NULL) {
1276 1277 1278
        move = moves->next;
        cuddDeallocMove(table, moves);
        moves = move;
Alan Mishchenko committed
1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305
    }
    return(NULL);

} /* end of cuddZddSiftingUp */


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

  Synopsis    [Sifts a variable down.]

  Description [Sifts a variable down. Moves x down until either it
  reaches the bound (x_high) or the size of the ZDD heap increases too
  much. Returns the set of moves in case of success; NULL if memory is
  full.]

  SideEffects [None]

  SeeAlso     []

******************************************************************************/
static Move *
cuddZddSiftingDown(
  DdManager * table,
  int  x,
  int  x_high,
  int  initial_size)
{
1306 1307 1308 1309 1310
    Move        *moves;
    Move        *move;
    int         y;
    int         size;
    int         limit_size = initial_size;
Alan Mishchenko committed
1311 1312 1313 1314

    moves = NULL;
    y = cuddZddNextHigh(table, x);
    while (y <= x_high) {
1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328
        size = cuddZddSwapInPlace(table, x, y);
        if (size == 0)
            goto cuddZddSiftingDownOutOfMem;
        move = (Move *)cuddDynamicAllocNode(table);
        if (move == NULL)
            goto cuddZddSiftingDownOutOfMem;
        move->x = x;
        move->y = y;
        move->size = size;
        move->next = moves;
        moves = move;

        if ((double)size > (double)limit_size * table->maxGrowth)
            break;
Alan Mishchenko committed
1329
        if (size < limit_size)
1330
            limit_size = size;
Alan Mishchenko committed
1331

1332 1333
        x = y;
        y = cuddZddNextHigh(table, x);
Alan Mishchenko committed
1334 1335 1336 1337 1338
    }
    return(moves);

cuddZddSiftingDownOutOfMem:
    while (moves != NULL) {
1339 1340 1341
        move = moves->next;
        cuddDeallocMove(table, moves);
        moves = move;
Alan Mishchenko committed
1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368
    }
    return(NULL);

} /* end of cuddZddSiftingDown */


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

  Synopsis    [Given a set of moves, returns the ZDD heap to the position
  giving the minimum size.]

  Description [Given a set of moves, returns the ZDD heap to the
  position giving the minimum size. In case of ties, returns to the
  closest position giving the minimum size. Returns 1 in case of
  success; 0 otherwise.]

  SideEffects [None]

  SeeAlso     []

******************************************************************************/
static int
cuddZddSiftingBackward(
  DdManager * table,
  Move * moves,
  int  size)
{
1369 1370 1371 1372
    int         i;
    int         i_best;
    Move        *move;
    int         res;
Alan Mishchenko committed
1373 1374 1375 1376

    /* Find the minimum size among moves. */
    i_best = -1;
    for (move = moves, i = 0; move != NULL; move = move->next, i++) {
1377 1378 1379 1380
        if (move->size < size) {
            i_best = i;
            size = move->size;
        }
Alan Mishchenko committed
1381 1382 1383
    }

    for (move = moves, i = 0; move != NULL; move = move->next, i++) {
1384 1385 1386 1387 1388 1389 1390
        if (i == i_best)
            break;
        res = cuddZddSwapInPlace(table, move->x, move->y);
        if (!res)
            return(0);
        if (i_best == -1 && res == size)
            break;
Alan Mishchenko committed
1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417
    }

    return(1);

} /* end of cuddZddSiftingBackward */


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

  Synopsis    [Prepares the ZDD heap for dynamic reordering.]

  Description [Prepares the ZDD heap for dynamic reordering. Does
  garbage collection, to guarantee that there are no dead nodes;
  and clears the cache, which is invalidated by dynamic reordering.]

  SideEffects [None]

******************************************************************************/
static void
zddReorderPreprocess(
  DdManager * table)
{

    /* Clear the cache. */
    cuddCacheFlush(table);

    /* Eliminate dead nodes. Do not scan the cache again. */
1418
    cuddGarbageCollect(table,0);
Alan Mishchenko committed
1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445

    return;

} /* end of ddReorderPreprocess */


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

  Synopsis    [Shrinks almost empty ZDD subtables at the end of reordering
  to guarantee that they have a reasonable load factor.]

  Description [Shrinks almost empty subtables at the end of reordering to
  guarantee that they have a reasonable load factor. However, if there many
  nodes are being reclaimed, then no resizing occurs. Returns 1 in case of
  success; 0 otherwise.]

  SideEffects [None]

******************************************************************************/
static int
zddReorderPostprocess(
  DdManager * table)
{
    int i, j, posn;
    DdNodePtr *nodelist, *oldnodelist;
    DdNode *node, *next;
    unsigned int slots, oldslots;
1446 1447
    extern DD_OOMFP MMoutOfMemory;
    DD_OOMFP saveHandler;
Alan Mishchenko committed
1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458

#ifdef DD_VERBOSE
    (void) fflush(table->out);
#endif

    /* If we have very many reclaimed nodes, we do not want to shrink
    ** the subtables, because this will lead to more garbage
    ** collections. More garbage collections mean shorter mean life for
    ** nodes with zero reference count; hence lower probability of finding
    ** a result in the cache.
    */
1459
    if (table->reclaimed > table->allocated / 2) return(1);
Alan Mishchenko committed
1460 1461 1462

    /* Resize subtables. */
    for (i = 0; i < table->sizeZ; i++) {
1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479
        int shift;
        oldslots = table->subtableZ[i].slots;
        if (oldslots < table->subtableZ[i].keys * DD_MAX_SUBTABLE_SPARSITY ||
            oldslots <= table->initSlots) continue;
        oldnodelist = table->subtableZ[i].nodelist;
        slots = oldslots >> 1;
        saveHandler = MMoutOfMemory;
        MMoutOfMemory = Cudd_OutOfMem;
        nodelist = ABC_ALLOC(DdNodePtr, slots);
        MMoutOfMemory = saveHandler;
        if (nodelist == NULL) {
            return(1);
        }
        table->subtableZ[i].nodelist = nodelist;
        table->subtableZ[i].slots = slots;
        table->subtableZ[i].shift++;
        table->subtableZ[i].maxKeys = slots * DD_MAX_SUBTABLE_DENSITY;
Alan Mishchenko committed
1480
#ifdef DD_VERBOSE
1481 1482 1483
        (void) fprintf(table->err,
                       "shrunk layer %d (%d keys) from %d to %d slots\n",
                       i, table->subtableZ[i].keys, oldslots, slots);
Alan Mishchenko committed
1484 1485
#endif

1486 1487
        for (j = 0; (unsigned) j < slots; j++) {
            nodelist[j] = NULL;
Alan Mishchenko committed
1488
        }
1489 1490 1491 1492 1493
        shift = table->subtableZ[i].shift;
        for (j = 0; (unsigned) j < oldslots; j++) {
            node = oldnodelist[j];
            while (node != NULL) {
                next = node->next;
1494
                posn = ddHash(cuddF2L(cuddT(node)), cuddF2L(cuddE(node)), shift);
1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507
                node->next = nodelist[posn];
                nodelist[posn] = node;
                node = next;
            }
        }
        ABC_FREE(oldnodelist);

        table->memused += (slots - oldslots) * sizeof(DdNode *);
        table->slots += slots - oldslots;
        table->minDead = (unsigned) (table->gcFrac * (double) table->slots);
        table->cacheSlack = (int) ddMin(table->maxCacheHard,
            DD_MAX_CACHE_TO_SLOTS_RATIO*table->slots) -
            2 * (int) table->cacheSlots;
Alan Mishchenko committed
1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537
    }
    /* We don't look at the constant subtable, because it is not
    ** affected by reordering.
    */

    return(1);

} /* end of zddReorderPostprocess */


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

  Synopsis    [Reorders ZDD variables according to a given permutation.]

  Description [Reorders ZDD variables according to a given permutation.
  The i-th permutation array contains the index of the variable that
  should be brought to the i-th level. zddShuffle assumes that no
  dead nodes are present.  The reordering is achieved by a series of
  upward sifts.  Returns 1 if successful; 0 otherwise.]

  SideEffects [None]

  SeeAlso []

******************************************************************************/
static int
zddShuffle(
  DdManager * table,
  int * permutation)
{
1538 1539 1540 1541 1542
    int         index;
    int         level;
    int         position;
    int         numvars;
    int         result;
Alan Mishchenko committed
1543
#ifdef DD_STATS
1544 1545 1546 1547
    long        localTime;
    int         initialSize;
    int         finalSize;
    int         previousSize;
Alan Mishchenko committed
1548 1549 1550 1551 1552 1553 1554
#endif

    zddTotalNumberSwapping = 0;
#ifdef DD_STATS
    localTime = util_cpu_time();
    initialSize = table->keysZ;
    (void) fprintf(table->out,"#:I_SHUFFLE %8d: initial size\n",
1555
                   initialSize); 
Alan Mishchenko committed
1556 1557 1558 1559 1560
#endif

    numvars = table->sizeZ;

    for (level = 0; level < numvars; level++) {
1561 1562
        index = permutation[level];
        position = table->permZ[index];
Alan Mishchenko committed
1563
#ifdef DD_STATS
1564
        previousSize = table->keysZ;
Alan Mishchenko committed
1565
#endif
1566 1567
        result = zddSiftUp(table,position,level);
        if (!result) return(0);
Alan Mishchenko committed
1568
#ifdef DD_STATS
1569 1570 1571 1572 1573 1574 1575 1576
        if (table->keysZ < (unsigned) previousSize) {
            (void) fprintf(table->out,"-");
        } else if (table->keysZ > (unsigned) previousSize) {
            (void) fprintf(table->out,"+");     /* should never happen */
        } else {
            (void) fprintf(table->out,"=");
        }
        fflush(table->out);
Alan Mishchenko committed
1577 1578 1579 1580 1581 1582 1583 1584
#endif
    }

#ifdef DD_STATS
    (void) fprintf(table->out,"\n");
    finalSize = table->keysZ;
    (void) fprintf(table->out,"#:F_SHUFFLE %8d: final size\n",finalSize); 
    (void) fprintf(table->out,"#:T_SHUFFLE %8g: total time (sec)\n",
1585
        ((double)(util_cpu_time() - localTime)/1000.0)); 
Alan Mishchenko committed
1586
    (void) fprintf(table->out,"#:N_SHUFFLE %8d: total swaps\n",
1587
                   zddTotalNumberSwapping);
Alan Mishchenko committed
1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618
#endif

    return(1);

} /* end of zddShuffle */


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

  Synopsis    [Moves one ZDD variable up.]

  Description [Takes a ZDD variable from position x and sifts it up to
  position xLow;  xLow should be less than or equal to x.
  Returns 1 if successful; 0 otherwise]

  SideEffects [None]

  SeeAlso     []

******************************************************************************/
static int
zddSiftUp(
  DdManager * table,
  int  x,
  int  xLow)
{
    int        y;
    int        size;

    y = cuddZddNextLow(table,x);
    while (y >= xLow) {
1619 1620 1621 1622 1623 1624
        size = cuddZddSwapInPlace(table,y,x);
        if (size == 0) {
            return(0);
        }
        x = y;
        y = cuddZddNextLow(table,x);
Alan Mishchenko committed
1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650
    }
    return(1);

} /* end of zddSiftUp */


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

  Synopsis    [Fixes the ZDD variable group tree after a shuffle.]

  Description [Fixes the ZDD variable group tree after a
  shuffle. Assumes that the order of the variables in a terminal node
  has not been changed.]

  SideEffects [Changes the ZDD variable group tree.]

  SeeAlso     []

******************************************************************************/
static void
zddFixTree(
  DdManager * table,
  MtrNode * treenode)
{
    if (treenode == NULL) return;
    treenode->low = ((int) treenode->index < table->sizeZ) ?
1651
        table->permZ[treenode->index] : treenode->index;
Alan Mishchenko committed
1652
    if (treenode->child != NULL) {
1653
        zddFixTree(table, treenode->child);
Alan Mishchenko committed
1654 1655
    }
    if (treenode->younger != NULL)
1656
        zddFixTree(table, treenode->younger);
Alan Mishchenko committed
1657
    if (treenode->parent != NULL && treenode->low < treenode->parent->low) {
1658 1659
        treenode->parent->low = treenode->low;
        treenode->parent->index = treenode->index;
Alan Mishchenko committed
1660 1661 1662 1663 1664
    }
    return;

} /* end of zddFixTree */

1665

1666 1667
ABC_NAMESPACE_IMPL_END

1668