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

  FileName    [cuddReorder.c]

  PackageName [cudd]

  Synopsis    [Functions for dynamic variable reordering.]

  Description [External procedures included in this file:
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
                <ul>
                <li> Cudd_ReduceHeap()
                <li> Cudd_ShuffleHeap()
                </ul>
        Internal procedures included in this module:
                <ul>
                <li> cuddDynamicAllocNode()
                <li> cuddSifting()
                <li> cuddSwapping()
                <li> cuddNextHigh()
                <li> cuddNextLow()
                <li> cuddSwapInPlace()
                <li> cuddBddAlignToZdd()
                </ul>
        Static procedures included in this module:
                <ul>
                <li> ddUniqueCompare()
                <li> ddSwapAny()
                <li> ddSiftingAux()
                <li> ddSiftingUp()
                <li> ddSiftingDown()
                <li> ddSiftingBackward()
                <li> ddReorderPreprocess()
                <li> ddReorderPostprocess()
                <li> ddShuffle()
                <li> ddSiftUp()
                <li> bddFixTree()
                </ul>]
Alan Mishchenko committed
38 39 40

  Author      [Shipra Panda, Bernard Plessier, Fabio Somenzi]

41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
  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
72 73 74

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

Alan Mishchenko committed
75
#include "util_hack.h"
Alan Mishchenko committed
76 77
#include "cuddInt.h"

78 79 80
ABC_NAMESPACE_IMPL_START


81

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

#define DD_MAX_SUBTABLE_SPARSITY 8
#define DD_SHRINK_FACTOR 2

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

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

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

#ifndef lint
102
static char rcsid[] DD_UNUSED = "$Id: cuddReorder.c,v 1.69 2009/02/21 18:24:10 fabio Exp $";
Alan Mishchenko committed
103 104
#endif

105
static  int     *entry;
Alan Mishchenko committed
106

107
int     ddTotalNumberSwapping;
Alan Mishchenko committed
108
#ifdef DD_STATS
109
int     ddTotalNISwaps;
Alan Mishchenko committed
110 111 112 113 114 115 116 117 118 119 120 121
#endif

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

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

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

122 123 124 125 126 127 128 129 130 131 132 133 134
static int ddUniqueCompare (int *ptrX, int *ptrY);
static Move * ddSwapAny (DdManager *table, int x, int y);
static int ddSiftingAux (DdManager *table, int x, int xLow, int xHigh);
static Move * ddSiftingUp (DdManager *table, int y, int xLow);
static Move * ddSiftingDown (DdManager *table, int x, int xHigh);
static int ddSiftingBackward (DdManager *table, int size, Move *moves);
static int ddReorderPreprocess (DdManager *table);
static int ddReorderPostprocess (DdManager *table);
static int ddShuffle (DdManager *table, int *permutation);
static int ddSiftUp (DdManager *table, int x, int xLow);
static void bddFixTree (DdManager *table, MtrNode *treenode);
static int ddUpdateMtrTree (DdManager *table, MtrNode *treenode, int *perm, int *invperm);
static int ddCheckPermuation (DdManager *table, MtrNode *treenode, int *perm, int *invperm);
Alan Mishchenko committed
135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181

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


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


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

  Synopsis    [Main dynamic reordering routine.]

  Description [Main dynamic reordering routine.
  Calls one of the possible reordering procedures:
  <ul>
  <li>Swapping
  <li>Sifting
  <li>Symmetric Sifting
  <li>Group Sifting
  <li>Window Permutation
  <li>Simulated Annealing
  <li>Genetic Algorithm
  <li>Dynamic Programming (exact)
  </ul>

  For sifting, symmetric sifting, group sifting, and window
  permutation it is possible to request reordering to convergence.<p>

  The core of all methods is the reordering procedure
  cuddSwapInPlace() which swaps two adjacent variables and is based
  on Rudell's paper.
  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 diagrams and clears
  the cache.]

******************************************************************************/
int
Cudd_ReduceHeap(
  DdManager * table /* DD manager */,
  Cudd_ReorderingType heuristic /* method used for reordering */,
  int  minsize /* bound below which no reordering occurs */)
{
    DdHook *hook;
182
    int result;
Alan Mishchenko committed
183 184 185 186 187 188 189 190 191
    unsigned int nextDyn;
#ifdef DD_STATS
    unsigned int initialSize;
    unsigned int finalSize;
#endif
    long localTime;

    /* Don't reorder if there are too many dead nodes. */
    if (table->keys - table->dead < (unsigned) minsize)
192
        return(1);
Alan Mishchenko committed
193 194

    if (heuristic == CUDD_REORDER_SAME) {
195
        heuristic = table->autoMethod;
Alan Mishchenko committed
196 197
    }
    if (heuristic == CUDD_REORDER_NONE) {
198
        return(1);
Alan Mishchenko committed
199 200 201 202 203 204 205 206 207 208 209 210
    }

    /* This call to Cudd_ReduceHeap does initiate reordering. Therefore
    ** we count it.
    */
    table->reorderings++;

    localTime = util_cpu_time();

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

    if (!ddReorderPreprocess(table)) return(0);
    ddTotalNumberSwapping = 0;
218

Alan Mishchenko committed
219
    if (table->keys > table->peakLiveNodes) {
220
        table->peakLiveNodes = table->keys;
Alan Mishchenko committed
221 222 223 224 225 226 227 228
    }
#ifdef DD_STATS
    initialSize = table->keys - table->isolated;
    ddTotalNISwaps = 0;

    switch(heuristic) {
    case CUDD_REORDER_RANDOM:
    case CUDD_REORDER_RANDOM_PIVOT:
229 230
        (void) fprintf(table->out,"#:I_RANDOM  ");
        break;
Alan Mishchenko committed
231 232 233 234 235 236
    case CUDD_REORDER_SIFT:
    case CUDD_REORDER_SIFT_CONVERGE:
    case CUDD_REORDER_SYMM_SIFT:
    case CUDD_REORDER_SYMM_SIFT_CONV:
    case CUDD_REORDER_GROUP_SIFT:
    case CUDD_REORDER_GROUP_SIFT_CONV:
237 238
        (void) fprintf(table->out,"#:I_SIFTING ");
        break;
Alan Mishchenko committed
239 240 241 242 243 244
    case CUDD_REORDER_WINDOW2:
    case CUDD_REORDER_WINDOW3:
    case CUDD_REORDER_WINDOW4:
    case CUDD_REORDER_WINDOW2_CONV:
    case CUDD_REORDER_WINDOW3_CONV:
    case CUDD_REORDER_WINDOW4_CONV:
245 246
        (void) fprintf(table->out,"#:I_WINDOW  ");
        break;
Alan Mishchenko committed
247
    case CUDD_REORDER_ANNEALING:
248 249
        (void) fprintf(table->out,"#:I_ANNEAL  ");
        break;
Alan Mishchenko committed
250
    case CUDD_REORDER_GENETIC:
251 252
        (void) fprintf(table->out,"#:I_GENETIC ");
        break;
Alan Mishchenko committed
253 254
    case CUDD_REORDER_LINEAR:
    case CUDD_REORDER_LINEAR_CONVERGE:
255 256
        (void) fprintf(table->out,"#:I_LINSIFT ");
        break;
Alan Mishchenko committed
257
    case CUDD_REORDER_EXACT:
258 259
        (void) fprintf(table->out,"#:I_EXACT   ");
        break;
Alan Mishchenko committed
260
    default:
261
        return(0);
Alan Mishchenko committed
262
    }
263
    (void) fprintf(table->out,"%8d: initial size",initialSize);
Alan Mishchenko committed
264 265 266 267
#endif

    /* See if we should use alternate threshold for maximum growth. */
    if (table->reordCycle && table->reorderings % table->reordCycle == 0) {
268 269 270 271
        double saveGrowth = table->maxGrowth;
        table->maxGrowth = table->maxGrowthAlt;
        result = cuddTreeSifting(table,heuristic);
        table->maxGrowth = saveGrowth;
Alan Mishchenko committed
272
    } else {
273
        result = cuddTreeSifting(table,heuristic);
Alan Mishchenko committed
274 275 276 277 278
    }

#ifdef DD_STATS
    (void) fprintf(table->out,"\n");
    finalSize = table->keys - table->isolated;
279
    (void) fprintf(table->out,"#:F_REORDER %8d: final size\n",finalSize);
Alan Mishchenko committed
280
    (void) fprintf(table->out,"#:T_REORDER %8g: total time (sec)\n",
281
                   ((double)(util_cpu_time() - localTime)/1000.0));
Alan Mishchenko committed
282
    (void) fprintf(table->out,"#:N_REORDER %8d: total swaps\n",
283
                   ddTotalNumberSwapping);
Alan Mishchenko committed
284 285 286 287
    (void) fprintf(table->out,"#:M_REORDER %8d: NI swaps\n",ddTotalNISwaps);
#endif

    if (result == 0)
288
        return(0);
Alan Mishchenko committed
289 290

    if (!ddReorderPostprocess(table))
291
        return(0);
Alan Mishchenko committed
292 293

    if (table->realign) {
294 295
        if (!cuddZddAlignToBdd(table))
            return(0);
Alan Mishchenko committed
296 297 298
    }

    nextDyn = (table->keys - table->constants.keys + 1) *
299
              DD_DYN_RATIO + table->constants.keys;
Alan Mishchenko committed
300
    if (table->reorderings < 20 || nextDyn > table->nextDyn)
301
        table->nextDyn = nextDyn;
Alan Mishchenko committed
302
    else
303
        table->nextDyn += 20;
Alan Mishchenko committed
304 305 306 307 308
    table->reordered = 1;

    /* Run hook functions. */
    hook = table->postReorderingHook;
    while (hook != NULL) {
309 310 311
        int res = (hook->f)(table, "BDD", (void *)localTime);
        if (res == 0) return(0);
        hook = hook->next;
Alan Mishchenko committed
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
    }
    /* Update cumulative reordering time. */
    table->reordTime += util_cpu_time() - localTime;

    return(result);

} /* end of Cudd_ReduceHeap */


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

  Synopsis    [Reorders variables according to given permutation.]

  Description [Reorders 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 variable order for all diagrams and clears
  the cache.]

  SeeAlso [Cudd_ReduceHeap]

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

343
    int result;
Alan Mishchenko committed
344 345 346 347 348 349
    int i;
    int identity = 1;
    int *perm;

    /* Don't waste time in case of identity permutation. */
    for (i = 0; i < table->size; i++) {
350 351 352 353
        if (permutation[i] != table->invperm[i]) {
            identity = 0;
            break;
        }
Alan Mishchenko committed
354 355
    }
    if (identity == 1) {
356
        return(1);
Alan Mishchenko committed
357 358 359
    }
    if (!ddReorderPreprocess(table)) return(0);
    if (table->keys > table->peakLiveNodes) {
360
        table->peakLiveNodes = table->keys;
Alan Mishchenko committed
361 362
    }

Alan Mishchenko committed
363
    perm = ABC_ALLOC(int, table->size);
Alan Mishchenko committed
364
    for (i = 0; i < table->size; i++)
365
        perm[permutation[i]] = i;
Alan Mishchenko committed
366
    if (!ddCheckPermuation(table,table->tree,perm,permutation)) {
367 368
        ABC_FREE(perm);
        return(0);
Alan Mishchenko committed
369 370
    }
    if (!ddUpdateMtrTree(table,table->tree,perm,permutation)) {
371 372
        ABC_FREE(perm);
        return(0);
Alan Mishchenko committed
373
    }
Alan Mishchenko committed
374
    ABC_FREE(perm);
Alan Mishchenko committed
375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411

    result = ddShuffle(table,permutation);

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

    return(result);

} /* end of Cudd_ShuffleHeap */


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


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

  Synopsis    [Dynamically allocates a Node.]

  Description [Dynamically allocates a Node. This procedure is similar
  to cuddAllocNode in Cudd_Table.c, but it does not attempt garbage
  collection, because during reordering there are no dead nodes.
  Returns a pointer to a new node if successful; NULL is memory is
  full.]

  SideEffects [None]

  SeeAlso     [cuddAllocNode]

******************************************************************************/
DdNode *
cuddDynamicAllocNode(
  DdManager * table)
{
    int     i;
    DdNodePtr *mem;
    DdNode *list, *node;
412 413
    extern DD_OOMFP MMoutOfMemory;
    DD_OOMFP saveHandler;
Alan Mishchenko committed
414

415
    if (table->nextFree == NULL) {        /* free list is empty */
416 417 418 419 420 421 422 423 424 425 426 427 428 429 430
        /* Try to allocate a new block. */
        saveHandler = MMoutOfMemory;
        MMoutOfMemory = Cudd_OutOfMem;
        mem = (DdNodePtr *) ABC_ALLOC(DdNode, DD_MEM_CHUNK + 1);
        MMoutOfMemory = saveHandler;
        if (mem == NULL && table->stash != NULL) {
            ABC_FREE(table->stash);
            table->stash = NULL;
            /* Inhibit resizing of tables. */
            table->maxCacheHard = table->cacheSlots - 1;
            table->cacheSlack = - (int) (table->cacheSlots + 1);
            for (i = 0; i < table->size; i++) {
                table->subtables[i].maxKeys <<= 2;
            }
            mem = (DdNodePtr *) ABC_ALLOC(DdNode,DD_MEM_CHUNK + 1);
Alan Mishchenko committed
431
        }
432 433 434 435 436 437 438
        if (mem == NULL) {
            /* Out of luck. Call the default handler to do
            ** whatever it specifies for a failed malloc.  If this
            ** handler returns, then set error code, print
            ** warning, and return. */
            (*MMoutOfMemory)(sizeof(DdNode)*(DD_MEM_CHUNK + 1));
            table->errorCode = CUDD_MEMORY_OUT;
Alan Mishchenko committed
439
#ifdef DD_VERBOSE
440 441 442 443
            (void) fprintf(table->err,
                           "cuddDynamicAllocNode: out of memory");
            (void) fprintf(table->err,"Memory in use = %lu\n",
                           table->memused);
Alan Mishchenko committed
444
#endif
445 446 447 448 449 450 451 452 453 454 455 456 457
            return(NULL);
        } else {        /* successful allocation; slice memory */
            unsigned long offset;
            table->memused += (DD_MEM_CHUNK + 1) * sizeof(DdNode);
            mem[0] = (DdNode *) table->memoryList;
            table->memoryList = mem;

            /* Here we rely on the fact that the size of a DdNode is a
            ** power of 2 and a multiple of the size of a pointer.
            ** If we align one node, all the others will be aligned
            ** as well. */
            offset = (unsigned long) mem & (sizeof(DdNode) - 1);
            mem += (sizeof(DdNode) - offset) / sizeof(DdNodePtr);
Alan Mishchenko committed
458
#ifdef DD_DEBUG
459
            assert(((unsigned long) mem & (sizeof(DdNode) - 1)) == 0);
Alan Mishchenko committed
460
#endif
461
            list = (DdNode *) mem;
Alan Mishchenko committed
462

463 464 465 466 467
            i = 1;
            do {
                list[i - 1].ref = 0;
                list[i - 1].next = &list[i];
            } while (++i < DD_MEM_CHUNK);
Alan Mishchenko committed
468

469 470
            list[DD_MEM_CHUNK-1].ref = 0;
            list[DD_MEM_CHUNK - 1].next = NULL;
Alan Mishchenko committed
471

472 473
            table->nextFree = &list[0];
        }
474
    } /* if free list empty */
Alan Mishchenko committed
475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507

    node = table->nextFree;
    table->nextFree = node->next;
    return (node);

} /* end of cuddDynamicAllocNode */


/**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]

******************************************************************************/
int
cuddSifting(
  DdManager * table,
  int  lower,
  int  upper)
{
508 509 510 511 512
    int i;
    int *var;
    int size;
    int x;
    int result;
Alan Mishchenko committed
513
#ifdef DD_STATS
514
    int previousSize;
Alan Mishchenko committed
515 516 517 518 519 520
#endif

    size = table->size;

    /* Find order in which to sift variables. */
    var = NULL;
Alan Mishchenko committed
521
    entry = ABC_ALLOC(int,size);
Alan Mishchenko committed
522
    if (entry == NULL) {
523 524
        table->errorCode = CUDD_MEMORY_OUT;
        goto cuddSiftingOutOfMem;
Alan Mishchenko committed
525
    }
Alan Mishchenko committed
526
    var = ABC_ALLOC(int,size);
Alan Mishchenko committed
527
    if (var == NULL) {
528 529
        table->errorCode = CUDD_MEMORY_OUT;
        goto cuddSiftingOutOfMem;
Alan Mishchenko committed
530 531 532
    }

    for (i = 0; i < size; i++) {
533 534 535
        x = table->perm[i];
        entry[i] = table->subtables[x].keys;
        var[i] = i;
Alan Mishchenko committed
536 537
    }

538
    qsort((void *)var,size,sizeof(int),(DD_QSFP)ddUniqueCompare);
Alan Mishchenko committed
539 540 541

    /* Now sift. */
    for (i = 0; i < ddMin(table->siftMaxVar,size); i++) {
542 543 544 545 546 547
        if (ddTotalNumberSwapping >= table->siftMaxSwap)
            break;
        x = table->perm[var[i]];

        if (x < lower || x > upper || table->subtables[x].bindVar == 1)
            continue;
Alan Mishchenko committed
548
#ifdef DD_STATS
549
        previousSize = table->keys - table->isolated;
Alan Mishchenko committed
550
#endif
551 552
        result = ddSiftingAux(table, x, lower, upper);
        if (!result) goto cuddSiftingOutOfMem;
Alan Mishchenko committed
553
#ifdef DD_STATS
554 555 556 557 558 559 560 561 562
        if (table->keys < (unsigned) previousSize + table->isolated) {
            (void) fprintf(table->out,"-");
        } else if (table->keys > (unsigned) previousSize + table->isolated) {
            (void) fprintf(table->out,"+");     /* should never happen */
            (void) fprintf(table->err,"\nSize increased from %d to %d while sifting variable %d\n", previousSize, table->keys - table->isolated, var[i]);
        } else {
            (void) fprintf(table->out,"=");
        }
        fflush(table->out);
Alan Mishchenko committed
563 564 565
#endif
    }

Alan Mishchenko committed
566 567
    ABC_FREE(var);
    ABC_FREE(entry);
Alan Mishchenko committed
568 569 570 571 572

    return(1);

cuddSiftingOutOfMem:

Alan Mishchenko committed
573 574
    if (entry != NULL) ABC_FREE(entry);
    if (var != NULL) ABC_FREE(var);
Alan Mishchenko committed
575

576
    return(0);
Alan Mishchenko committed
577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605

} /* end of cuddSifting */


/**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]

******************************************************************************/
int
cuddSwapping(
  DdManager * table,
  int lower,
  int upper,
  Cudd_ReorderingType heuristic)
{
606 607 608 609 610
    int i, j;
    int max, keys;
    int nvars;
    int x, y;
    int iterate;
Alan Mishchenko committed
611 612
    int previousSize;
    Move *moves, *move;
613 614
    int pivot;
    int modulo;
Alan Mishchenko committed
615 616 617 618 619 620 621 622 623 624 625
    int result;

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

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

    for (i = 0; i < iterate; i++) {
626 627 628 629 630 631 632 633 634 635
        if (ddTotalNumberSwapping >= table->siftMaxSwap)
            break;
        if (heuristic == CUDD_REORDER_RANDOM_PIVOT) {
            max = -1;
            for (j = lower; j <= upper; j++) {
                if ((keys = table->subtables[j].keys) > max) {
                    max = keys;
                    pivot = j;
                }
            }
Alan Mishchenko committed
636

637 638 639 640 641 642
            modulo = upper - pivot;
            if (modulo == 0) {
                y = pivot;
            } else{
                y = pivot + 1 + ((int) Cudd_Random() % modulo);
            }
Alan Mishchenko committed
643

644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666
            modulo = pivot - lower - 1;
            if (modulo < 1) {
                x = lower;
            } else{
                do {
                    x = (int) Cudd_Random() % modulo;
                } while (x == y);
            }
        } else {
            x = ((int) Cudd_Random() % nvars) + lower;
            do {
                y = ((int) Cudd_Random() % nvars) + lower;
            } while (x == y);
        }
        previousSize = table->keys - table->isolated;
        moves = ddSwapAny(table,x,y);
        if (moves == NULL) goto cuddSwappingOutOfMem;
        result = ddSiftingBackward(table,previousSize,moves);
        if (!result) goto cuddSwappingOutOfMem;
        while (moves != NULL) {
            move = moves->next;
            cuddDeallocMove(table, moves);
            moves = move;
Alan Mishchenko committed
667 668
        }
#ifdef DD_STATS
669 670 671 672 673 674 675 676
        if (table->keys < (unsigned) previousSize + table->isolated) {
            (void) fprintf(table->out,"-");
        } else if (table->keys > (unsigned) previousSize + table->isolated) {
            (void) fprintf(table->out,"+");     /* should never happen */
        } else {
            (void) fprintf(table->out,"=");
        }
        fflush(table->out);
Alan Mishchenko committed
677 678
#endif
#if 0
679 680
        (void) fprintf(table->out,"#:t_SWAPPING %8d: tmp size\n",
                       table->keys - table->isolated);
Alan Mishchenko committed
681 682 683 684 685 686 687
#endif
    }

    return(1);

cuddSwappingOutOfMem:
    while (moves != NULL) {
688 689 690
        move = moves->next;
        cuddDeallocMove(table, moves);
        moves = move;
Alan Mishchenko committed
691 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
    }

    return(0);

} /* end of cuddSwapping */


/**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     [cuddNextLow]

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

} /* end of cuddNextHigh */
718

Alan Mishchenko committed
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 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777

/**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     [cuddNextHigh]

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

} /* end of cuddNextLow */


/**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.
  cuddSwapInPlace assumes that x &lt; y.  Returns the number of keys in
  the table if successful; 0 otherwise.]

  SideEffects [None]

******************************************************************************/
int
cuddSwapInPlace(
  DdManager * table,
  int  x,
  int  y)
{
    DdNodePtr *xlist, *ylist;
    int    xindex, yindex;
    int    xslots, yslots;
    int    xshift, yshift;
    int    oldxkeys, oldykeys;
    int    newxkeys, newykeys;
    int    comple, newcomplement;
    int    i;
    Cudd_VariableType varType;
    Cudd_LazyGroupType groupType;
    int    posn;
    int    isolated;
    DdNode *f,*f0,*f1,*f01,*f00,*f11,*f10,*newf1,*newf0;
    DdNode *g,*next;
    DdNodePtr *previousP;
    DdNode *tmp;
    DdNode *sentinel = &(table->sentinel);
778 779
    extern DD_OOMFP MMoutOfMemory;
    DD_OOMFP saveHandler;
Alan Mishchenko committed
780

781
#ifdef DD_DEBUG
Alan Mishchenko committed
782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797
    int    count,idcheck;
#endif

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

    ddTotalNumberSwapping++;

    /* Get parameters of x subtable. */
    xindex = table->invperm[x];
798
    xlist = table->subtables[x].nodelist;
Alan Mishchenko committed
799 800 801 802 803 804 805 806 807 808 809 810 811
    oldxkeys = table->subtables[x].keys;
    xslots = table->subtables[x].slots;
    xshift = table->subtables[x].shift;

    /* Get parameters of y subtable. */
    yindex = table->invperm[y];
    ylist = table->subtables[y].nodelist;
    oldykeys = table->subtables[y].keys;
    yslots = table->subtables[y].slots;
    yshift = table->subtables[y].shift;

    if (!cuddTestInteract(table,xindex,yindex)) {
#ifdef DD_STATS
812
        ddTotalNISwaps++;
Alan Mishchenko committed
813
#endif
814 815
        newxkeys = oldxkeys;
        newykeys = oldykeys;
Alan Mishchenko committed
816
    } else {
817 818 819 820 821 822 823 824 825 826 827
        newxkeys = 0;
        newykeys = oldykeys;

        /* Check whether the two projection functions involved in this
        ** swap are isolated. At the end, we'll be able to tell how many
        ** isolated projection functions are there by checking only these
        ** two functions again. This is done to eliminate the isolated
        ** projection functions from the node count.
        */
        isolated = - ((table->vars[xindex]->ref == 1) +
                     (table->vars[yindex]->ref == 1));
Alan Mishchenko committed
828

829 830 831 832 833 834 835 836 837 838 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 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888
        /* The nodes in the x layer that do not depend on
        ** y will stay there; the others are put in a chain.
        ** The chain is handled as a LIFO; g points to the beginning.
        */
        g = NULL;
        if ((oldxkeys >= xslots || (unsigned) xslots == table->initSlots) &&
            oldxkeys <= DD_MAX_SUBTABLE_DENSITY * xslots) {
            for (i = 0; i < xslots; i++) {
                previousP = &(xlist[i]);
                f = *previousP;
                while (f != sentinel) {
                    next = f->next;
                    f1 = cuddT(f); f0 = cuddE(f);
                    if (f1->index != (DdHalfWord) yindex &&
                        Cudd_Regular(f0)->index != (DdHalfWord) yindex) {
                        /* stays */
                        newxkeys++;
                        *previousP = f;
                        previousP = &(f->next);
                    } else {
                        f->index = yindex;
                        f->next = g;
                        g = f;
                    }
                    f = next;
                } /* while there are elements in the collision chain */
                *previousP = sentinel;
            } /* for each slot of the x subtable */
        } else {                /* resize xlist */
            DdNode *h = NULL;
            DdNodePtr *newxlist;
            unsigned int newxslots;
            int newxshift;
            /* Empty current xlist. Nodes that stay go to list h;
            ** nodes that move go to list g. */
            for (i = 0; i < xslots; i++) {
                f = xlist[i];
                while (f != sentinel) {
                    next = f->next;
                    f1 = cuddT(f); f0 = cuddE(f);
                    if (f1->index != (DdHalfWord) yindex &&
                        Cudd_Regular(f0)->index != (DdHalfWord) yindex) {
                        /* stays */
                        f->next = h;
                        h = f;
                        newxkeys++;
                    } else {
                        f->index = yindex;
                        f->next = g;
                        g = f;
                    }
                    f = next;
                } /* while there are elements in the collision chain */
            } /* for each slot of the x subtable */
            /* Decide size of new subtable. */
            newxshift = xshift;
            newxslots = xslots;
            while ((unsigned) oldxkeys > DD_MAX_SUBTABLE_DENSITY * newxslots) {
                newxshift--;
                newxslots <<= 1;
Alan Mishchenko committed
889
            }
890 891 892 893 894 895 896 897 898 899 900 901 902 903 904
            while ((unsigned) oldxkeys < newxslots &&
                   newxslots > table->initSlots) {
                newxshift++;
                newxslots >>= 1;
            }
            /* Try to allocate new table. Be ready to back off. */
            saveHandler = MMoutOfMemory;
            MMoutOfMemory = Cudd_OutOfMem;
            newxlist = ABC_ALLOC(DdNodePtr, newxslots);
            MMoutOfMemory = saveHandler;
            if (newxlist == NULL) {
                (void) fprintf(table->err, "Unable to resize subtable %d for lack of memory\n", i);
                newxlist = xlist;
                newxslots = xslots;
                newxshift = xshift;
Alan Mishchenko committed
905
            } else {
906 907 908 909 910 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
                table->slots += ((int) newxslots - xslots);
                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;
                table->memused +=
                    ((int) newxslots - xslots) * sizeof(DdNodePtr);
                ABC_FREE(xlist);
                xslots =  newxslots;
                xshift = newxshift;
                xlist = newxlist;
            }
            /* Initialize new subtable. */
            for (i = 0; i < xslots; i++) {
                xlist[i] = sentinel;
            }
            /* Move nodes that were parked in list h to their new home. */
            f = h;
            while (f != NULL) {
                next = f->next;
                f1 = cuddT(f);
                f0 = cuddE(f);
                /* Check xlist for pair (f11,f01). */
                posn = ddHash(f1, f0, xshift);
                /* For each element tmp in collision list xlist[posn]. */
                previousP = &(xlist[posn]);
                tmp = *previousP;
                while (f1 < cuddT(tmp)) {
                    previousP = &(tmp->next);
                    tmp = *previousP;
                }
                while (f1 == cuddT(tmp) && f0 < cuddE(tmp)) {
                    previousP = &(tmp->next);
                    tmp = *previousP;
                }
                f->next = *previousP;
                *previousP = f;
                f = next;
Alan Mishchenko committed
945 946 947 948
            }
        }

#ifdef DD_COUNT
949
        table->swapSteps += oldxkeys - newxkeys;
Alan Mishchenko committed
950
#endif
951 952 953 954 955 956 957 958 959
        /* Take care of the x nodes that must be re-expressed.
        ** They form a linked list pointed by g. Their index has been
        ** already changed to yindex.
        */
        f = g;
        while (f != NULL) {
            next = f->next;
            /* Find f1, f0, f11, f10, f01, f00. */
            f1 = cuddT(f);
Alan Mishchenko committed
960
#ifdef DD_DEBUG
961
            assert(!(Cudd_IsComplement(f1)));
Alan Mishchenko committed
962
#endif
963 964 965 966 967
            if ((int) f1->index == yindex) {
                f11 = cuddT(f1); f10 = cuddE(f1);
            } else {
                f11 = f10 = f1;
            }
Alan Mishchenko committed
968
#ifdef DD_DEBUG
969
            assert(!(Cudd_IsComplement(f11)));
Alan Mishchenko committed
970
#endif
971 972 973 974 975 976 977 978 979 980 981 982 983 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
            f0 = cuddE(f);
            comple = Cudd_IsComplement(f0);
            f0 = Cudd_Regular(f0);
            if ((int) f0->index == yindex) {
                f01 = cuddT(f0); f00 = cuddE(f0);
            } else {
                f01 = f00 = f0;
            }
            if (comple) {
                f01 = Cudd_Not(f01);
                f00 = Cudd_Not(f00);
            }
            /* Decrease ref count of f1. */
            cuddSatDec(f1->ref);
            /* Create the new T child. */
            if (f11 == f01) {
                newf1 = f11;
                cuddSatInc(newf1->ref);
            } else {
                /* Check xlist for triple (xindex,f11,f01). */
                posn = ddHash(f11, f01, xshift);
                /* For each element newf1 in collision list xlist[posn]. */
                previousP = &(xlist[posn]);
                newf1 = *previousP;
                while (f11 < cuddT(newf1)) {
                    previousP = &(newf1->next);
                    newf1 = *previousP;
                }
                while (f11 == cuddT(newf1) && f01 < cuddE(newf1)) {
                    previousP = &(newf1->next);
                    newf1 = *previousP;
                }
                if (cuddT(newf1) == f11 && cuddE(newf1) == f01) {
                    cuddSatInc(newf1->ref);
                } else { /* no match */
                    newf1 = cuddDynamicAllocNode(table);
                    if (newf1 == NULL)
                        goto cuddSwapOutOfMem;
                    newf1->index = xindex; newf1->ref = 1;
                    cuddT(newf1) = f11;
                    cuddE(newf1) = f01;
                    /* Insert newf1 in the collision list xlist[posn];
                    ** increase the ref counts of f11 and f01.
                    */
                    newxkeys++;
                    newf1->next = *previousP;
                    *previousP = newf1;
                    cuddSatInc(f11->ref);
                    tmp = Cudd_Regular(f01);
                    cuddSatInc(tmp->ref);
                }
            }
            cuddT(f) = newf1;
Alan Mishchenko committed
1024
#ifdef DD_DEBUG
1025
            assert(!(Cudd_IsComplement(newf1)));
Alan Mishchenko committed
1026 1027
#endif

1028 1029 1030
            /* Do the same for f0, keeping complement dots into account. */
            /* Decrease ref count of f0. */
            tmp = Cudd_Regular(f0);
Alan Mishchenko committed
1031
            cuddSatDec(tmp->ref);
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 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098
            /* Create the new E child. */
            if (f10 == f00) {
                newf0 = f00;
                tmp = Cudd_Regular(newf0);
                cuddSatInc(tmp->ref);
            } else {
                /* make sure f10 is regular */
                newcomplement = Cudd_IsComplement(f10);
                if (newcomplement) {
                    f10 = Cudd_Not(f10);
                    f00 = Cudd_Not(f00);
                }
                /* Check xlist for triple (xindex,f10,f00). */
                posn = ddHash(f10, f00, xshift);
                /* For each element newf0 in collision list xlist[posn]. */
                previousP = &(xlist[posn]);
                newf0 = *previousP;
                while (f10 < cuddT(newf0)) {
                    previousP = &(newf0->next);
                    newf0 = *previousP;
                }
                while (f10 == cuddT(newf0) && f00 < cuddE(newf0)) {
                    previousP = &(newf0->next);
                    newf0 = *previousP;
                }
                if (cuddT(newf0) == f10 && cuddE(newf0) == f00) {
                    cuddSatInc(newf0->ref);
                } else { /* no match */
                    newf0 = cuddDynamicAllocNode(table);
                    if (newf0 == NULL)
                        goto cuddSwapOutOfMem;
                    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 = *previousP;
                    *previousP = newf0;
                    cuddSatInc(f10->ref);
                    tmp = Cudd_Regular(f00);
                    cuddSatInc(tmp->ref);
                }
                if (newcomplement) {
                    newf0 = Cudd_Not(newf0);
                }
            }
            cuddE(f) = newf0;

            /* Insert the modified f in ylist.
            ** The modified f does not already exists in ylist.
            ** (Because of the uniqueness of the cofactors.)
            */
            posn = ddHash(newf1, newf0, yshift);
            newykeys++;
            previousP = &(ylist[posn]);
            tmp = *previousP;
            while (newf1 < cuddT(tmp)) {
                previousP = &(tmp->next);
                tmp = *previousP;
            }
            while (newf1 == cuddT(tmp) && newf0 < cuddE(tmp)) {
                previousP = &(tmp->next);
                tmp = *previousP;
            }
            f->next = *previousP;
Alan Mishchenko committed
1099
            *previousP = f;
1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125
            f = next;
        } /* while f != NULL */

        /* GC the y layer. */

        /* For each node f in ylist. */
        for (i = 0; i < yslots; i++) {
            previousP = &(ylist[i]);
            f = *previousP;
            while (f != sentinel) {
                next = f->next;
                if (f->ref == 0) {
                    tmp = cuddT(f);
                    cuddSatDec(tmp->ref);
                    tmp = Cudd_Regular(cuddE(f));
                    cuddSatDec(tmp->ref);
                    cuddDeallocNode(table,f);
                    newykeys--;
                } else {
                    *previousP = f;
                    previousP = &(f->next);
                }
                f = next;
            } /* while f */
            *previousP = sentinel;
        } /* for i */
Alan Mishchenko committed
1126

1127
#ifdef DD_DEBUG
Alan Mishchenko committed
1128
#if 0
1129
        (void) fprintf(table->out,"Swapping %d and %d\n",x,y);
Alan Mishchenko committed
1130
#endif
1131 1132 1133 1134 1135 1136 1137 1138 1139 1140
        count = 0;
        idcheck = 0;
        for (i = 0; i < yslots; i++) {
            f = ylist[i];
            while (f != sentinel) {
                count++;
                if (f->index != (DdHalfWord) yindex)
                    idcheck++;
                f = f->next;
            }
Alan Mishchenko committed
1141
        }
1142 1143 1144 1145
        if (count != newykeys) {
            (void) fprintf(table->out,
                           "Error in finding newykeys\toldykeys = %d\tnewykeys = %d\tactual = %d\n",
                           oldykeys,newykeys,count);
Alan Mishchenko committed
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
        if (idcheck != 0)
            (void) fprintf(table->out,
                           "Error in id's of ylist\twrong id's = %d\n",
                           idcheck);
        count = 0;
        idcheck = 0;
        for (i = 0; i < xslots; i++) {
            f = xlist[i];
            while (f != sentinel) {
                count++;
                if (f->index != (DdHalfWord) xindex)
                    idcheck++;
                f = f->next;
            }
        }
        if (count != newxkeys) {
            (void) fprintf(table->out,
                           "Error in finding newxkeys\toldxkeys = %d \tnewxkeys = %d \tactual = %d\n",
                           oldxkeys,newxkeys,count);
        }
        if (idcheck != 0)
            (void) fprintf(table->out,
                           "Error in id's of xlist\twrong id's = %d\n",
                           idcheck);
Alan Mishchenko committed
1171 1172
#endif

1173 1174 1175
        isolated += (table->vars[xindex]->ref == 1) +
                    (table->vars[yindex]->ref == 1);
        table->isolated += isolated;
Alan Mishchenko committed
1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 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
    }

    /* Set the appropriate fields in table. */
    table->subtables[x].nodelist = ylist;
    table->subtables[x].slots = yslots;
    table->subtables[x].shift = yshift;
    table->subtables[x].keys = newykeys;
    table->subtables[x].maxKeys = yslots * DD_MAX_SUBTABLE_DENSITY;
    i = table->subtables[x].bindVar;
    table->subtables[x].bindVar = table->subtables[y].bindVar;
    table->subtables[y].bindVar = i;
    /* Adjust filds for lazy sifting. */
    varType = table->subtables[x].varType;
    table->subtables[x].varType = table->subtables[y].varType;
    table->subtables[y].varType = varType;
    i = table->subtables[x].pairIndex;
    table->subtables[x].pairIndex = table->subtables[y].pairIndex;
    table->subtables[y].pairIndex = i;
    i = table->subtables[x].varHandled;
    table->subtables[x].varHandled = table->subtables[y].varHandled;
    table->subtables[y].varHandled = i;
    groupType = table->subtables[x].varToBeGrouped;
    table->subtables[x].varToBeGrouped = table->subtables[y].varToBeGrouped;
    table->subtables[y].varToBeGrouped = groupType;

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

    table->perm[xindex] = y; table->perm[yindex] = x;
    table->invperm[x] = yindex; table->invperm[y] = xindex;

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

    return(table->keys - table->isolated);

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

    return (0);

} /* end of cuddSwapInPlace */


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

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

  Description [Reorders BDD variables according to the order of the
  ZDD variables. This function can be called at the end of ZDD
  reordering to insure that the order of the BDD variables is
  consistent with the order of the ZDD 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. cuddBddAlignToZdd
  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_zddReduceHeap, which clears the cache.  Returns 1 in case of
  success; 0 otherwise.]

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

  SeeAlso [Cudd_ShuffleHeap Cudd_zddReduceHeap]

******************************************************************************/
int
cuddBddAlignToZdd(
  DdManager * table /* DD manager */)
{
1249 1250 1251 1252
    int *invperm;               /* permutation array */
    int M;                      /* ratio of ZDD variables to BDD variables */
    int i;                      /* loop index */
    int result;                 /* return value */
Alan Mishchenko committed
1253 1254 1255

    /* We assume that a ratio of 0 is OK. */
    if (table->size == 0)
1256
        return(1);
Alan Mishchenko committed
1257 1258 1259 1260 1261 1262

    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)
1263
        return(0);
Alan Mishchenko committed
1264
    /* Create and initialize the inverse permutation array. */
Alan Mishchenko committed
1265
    invperm = ABC_ALLOC(int,table->size);
Alan Mishchenko committed
1266
    if (invperm == NULL) {
1267 1268
        table->errorCode = CUDD_MEMORY_OUT;
        return(0);
Alan Mishchenko committed
1269 1270
    }
    for (i = 0; i < table->sizeZ; i += M) {
1271 1272 1273
        int indexZ = table->invpermZ[i];
        int index  = indexZ / M;
        invperm[i / M] = index;
Alan Mishchenko committed
1274 1275 1276 1277 1278 1279 1280 1281 1282
    }
    /* Eliminate dead nodes. Do not scan the cache again, because we
    ** assume that Cudd_zddReduceHeap has already cleared it.
    */
    cuddGarbageCollect(table,0);

    /* Initialize number of isolated projection functions. */
    table->isolated = 0;
    for (i = 0; i < table->size; i++) {
1283
        if (table->vars[i]->ref == 1) table->isolated++;
Alan Mishchenko committed
1284 1285 1286 1287 1288 1289 1290
    }

    /* Initialize the interaction matrix. */
    result = cuddInitInteract(table);
    if (result == 0) return(0);

    result = ddShuffle(table, invperm);
Alan Mishchenko committed
1291
    ABC_FREE(invperm);
Alan Mishchenko committed
1292
    /* Free interaction matrix. */
Alan Mishchenko committed
1293
    ABC_FREE(table->interact);
Alan Mishchenko committed
1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323
    /* Fix the BDD variable group tree. */
    bddFixTree(table,table->tree);
    return(result);

} /* end of cuddBddAlignToZdd */

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


/**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]

******************************************************************************/
static int
ddUniqueCompare(
  int * ptrX,
  int * ptrY)
{
#if 0
    if (entry[*ptrY] == entry[*ptrX]) {
1324
        return((*ptrX) - (*ptrY));
Alan Mishchenko committed
1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346
    }
#endif
    return(entry[*ptrY] - entry[*ptrX]);

} /* end of ddUniqueCompare */


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

  Synopsis    [Swaps any two variables.]

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

  SideEffects [None]

******************************************************************************/
static Move *
ddSwapAny(
  DdManager * table,
  int  x,
  int  y)
{
1347 1348 1349 1350 1351 1352
    Move        *move, *moves;
    int         xRef,yRef;
    int         xNext,yNext;
    int         size;
    int         limitSize;
    int         tmp;
Alan Mishchenko committed
1353 1354

    if (x >y) {
1355
        tmp = x; x = y; y = tmp;
Alan Mishchenko committed
1356 1357 1358 1359 1360 1361 1362 1363 1364 1365
    }

    xRef = x; yRef = y;

    xNext = cuddNextHigh(table,x);
    yNext = cuddNextLow(table,y);
    moves = NULL;
    limitSize = table->keys - table->isolated;

    for (;;) {
1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411
        if ( xNext == yNext) {
            size = cuddSwapInPlace(table,x,xNext);
            if (size == 0) goto ddSwapAnyOutOfMem;
            move = (Move *) cuddDynamicAllocNode(table);
            if (move == NULL) goto ddSwapAnyOutOfMem;
            move->x = x;
            move->y = xNext;
            move->size = size;
            move->next = moves;
            moves = move;

            size = cuddSwapInPlace(table,yNext,y);
            if (size == 0) goto ddSwapAnyOutOfMem;
            move = (Move *) cuddDynamicAllocNode(table);
            if (move == NULL) goto ddSwapAnyOutOfMem;
            move->x = yNext;
            move->y = y;
            move->size = size;
            move->next = moves;
            moves = move;

            size = cuddSwapInPlace(table,x,xNext);
            if (size == 0) goto ddSwapAnyOutOfMem;
            move = (Move *) cuddDynamicAllocNode(table);
            if (move == NULL) goto ddSwapAnyOutOfMem;
            move->x = x;
            move->y = xNext;
            move->size = size;
            move->next = moves;
            moves = move;

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

        } else if (x == yNext) {

            size = cuddSwapInPlace(table,x,xNext);
            if (size == 0) goto ddSwapAnyOutOfMem;
            move = (Move *) cuddDynamicAllocNode(table);
            if (move == NULL) goto ddSwapAnyOutOfMem;
            move->x = x;
            move->y = xNext;
            move->size = size;
            move->next = moves;
            moves = move;

            tmp = x; x = y; y = tmp;
Alan Mishchenko committed
1412

1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436
        } else {
            size = cuddSwapInPlace(table,x,xNext);
            if (size == 0) goto ddSwapAnyOutOfMem;
            move = (Move *) cuddDynamicAllocNode(table);
            if (move == NULL) goto ddSwapAnyOutOfMem;
            move->x = x;
            move->y = xNext;
            move->size = size;
            move->next = moves;
            moves = move;

            size = cuddSwapInPlace(table,yNext,y);
            if (size == 0) goto ddSwapAnyOutOfMem;
            move = (Move *) cuddDynamicAllocNode(table);
            if (move == NULL) goto ddSwapAnyOutOfMem;
            move->x = yNext;
            move->y = y;
            move->size = size;
            move->next = moves;
            moves = move;

            x = xNext;
            y = yNext;
        }
Alan Mishchenko committed
1437

1438 1439 1440
        xNext = cuddNextHigh(table,x);
        yNext = cuddNextLow(table,y);
        if (xNext > yRef) break;
Alan Mishchenko committed
1441

1442 1443 1444 1445
        if ((double) size > table->maxGrowth * (double) limitSize) break;
        if (size < limitSize) limitSize = size;
    }
    if (yNext>=xRef) {
Alan Mishchenko committed
1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457
        size = cuddSwapInPlace(table,yNext,y);
        if (size == 0) goto ddSwapAnyOutOfMem;
        move = (Move *) cuddDynamicAllocNode(table);
        if (move == NULL) goto ddSwapAnyOutOfMem;
        move->x = yNext;
        move->y = y;
        move->size = size;
        move->next = moves;
        moves = move;
    }

    return(moves);
1458

Alan Mishchenko committed
1459 1460
ddSwapAnyOutOfMem:
    while (moves != NULL) {
1461 1462 1463
        move = moves->next;
        cuddDeallocMove(table, moves);
        moves = move;
Alan Mishchenko committed
1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489
    }
    return(NULL);

} /* end of ddSwapAny */


/**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]

******************************************************************************/
static int
ddSiftingAux(
  DdManager * table,
  int  x,
  int  xLow,
  int  xHigh)
{

1490 1491 1492 1493 1494
    Move        *move;
    Move        *moveUp;                /* list of up moves */
    Move        *moveDown;              /* list of down moves */
    int         initialSize;
    int         result;
Alan Mishchenko committed
1495 1496 1497 1498 1499 1500 1501

    initialSize = table->keys - table->isolated;

    moveDown = NULL;
    moveUp = NULL;

    if (x == xLow) {
1502 1503 1504 1505 1506 1507
        moveDown = ddSiftingDown(table,x,xHigh);
        /* At this point x --> xHigh unless bounding occurred. */
        if (moveDown == (Move *) CUDD_OUT_OF_MEM) goto ddSiftingAuxOutOfMem;
        /* Move backward and stop at best position. */
        result = ddSiftingBackward(table,initialSize,moveDown);
        if (!result) goto ddSiftingAuxOutOfMem;
Alan Mishchenko committed
1508 1509

    } else if (x == xHigh) {
1510 1511 1512 1513 1514 1515
        moveUp = ddSiftingUp(table,x,xLow);
        /* At this point x --> xLow unless bounding occurred. */
        if (moveUp == (Move *) CUDD_OUT_OF_MEM) goto ddSiftingAuxOutOfMem;
        /* Move backward and stop at best position. */
        result = ddSiftingBackward(table,initialSize,moveUp);
        if (!result) goto ddSiftingAuxOutOfMem;
Alan Mishchenko committed
1516 1517

    } else if ((x - xLow) > (xHigh - x)) { /* must go down first: shorter */
1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528
        moveDown = ddSiftingDown(table,x,xHigh);
        /* At this point x --> xHigh unless bounding occurred. */
        if (moveDown == (Move *) CUDD_OUT_OF_MEM) goto ddSiftingAuxOutOfMem;
        if (moveDown != NULL) {
            x = moveDown->y;
        }
        moveUp = ddSiftingUp(table,x,xLow);
        if (moveUp == (Move *) CUDD_OUT_OF_MEM) goto ddSiftingAuxOutOfMem;
        /* Move backward and stop at best position */
        result = ddSiftingBackward(table,initialSize,moveUp);
        if (!result) goto ddSiftingAuxOutOfMem;
Alan Mishchenko committed
1529 1530

    } else { /* must go up first: shorter */
1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541
        moveUp = ddSiftingUp(table,x,xLow);
        /* At this point x --> xLow unless bounding occurred. */
        if (moveUp == (Move *) CUDD_OUT_OF_MEM) goto ddSiftingAuxOutOfMem;
        if (moveUp != NULL) {
            x = moveUp->x;
        }
        moveDown = ddSiftingDown(table,x,xHigh);
        if (moveDown == (Move *) CUDD_OUT_OF_MEM) goto ddSiftingAuxOutOfMem;
        /* Move backward and stop at best position. */
        result = ddSiftingBackward(table,initialSize,moveDown);
        if (!result) goto ddSiftingAuxOutOfMem;
Alan Mishchenko committed
1542 1543 1544
    }

    while (moveDown != NULL) {
1545 1546 1547
        move = moveDown->next;
        cuddDeallocMove(table, moveDown);
        moveDown = move;
Alan Mishchenko committed
1548 1549
    }
    while (moveUp != NULL) {
1550 1551 1552
        move = moveUp->next;
        cuddDeallocMove(table, moveUp);
        moveUp = move;
Alan Mishchenko committed
1553 1554 1555 1556 1557 1558
    }

    return(1);

ddSiftingAuxOutOfMem:
    if (moveDown != (Move *) CUDD_OUT_OF_MEM) {
1559 1560 1561 1562 1563
        while (moveDown != NULL) {
            move = moveDown->next;
            cuddDeallocMove(table, moveDown);
            moveDown = move;
        }
Alan Mishchenko committed
1564 1565
    }
    if (moveUp != (Move *) CUDD_OUT_OF_MEM) {
1566 1567 1568 1569 1570
        while (moveUp != NULL) {
            move = moveUp->next;
            cuddDeallocMove(table, moveUp);
            moveUp = move;
        }
Alan Mishchenko committed
1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594
    }

    return(0);

} /* end of ddSiftingAux */


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

  Synopsis    [Sifts a variable up.]

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

  SideEffects [None]

******************************************************************************/
static Move *
ddSiftingUp(
  DdManager * table,
  int  y,
  int  xLow)
{
1595 1596 1597 1598 1599 1600 1601 1602
    Move        *moves;
    Move        *move;
    int         x;
    int         size;
    int         limitSize;
    int         xindex, yindex;
    int         isolated;
    int         L;      /* lower bound on DD size */
Alan Mishchenko committed
1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619
#ifdef DD_DEBUG
    int checkL;
    int z;
    int zindex;
#endif

    moves = NULL;
    yindex = table->invperm[y];

    /* Initialize the lower bound.
    ** The part of the DD below y will not change.
    ** The part of the DD above y that does not interact with y will not
    ** change. The rest may vanish in the best case, except for
    ** the nodes at level xLow, which will not vanish, regardless.
    */
    limitSize = L = table->keys - table->isolated;
    for (x = xLow + 1; x < y; x++) {
1620 1621 1622 1623 1624
        xindex = table->invperm[x];
        if (cuddTestInteract(table,xindex,yindex)) {
            isolated = table->vars[xindex]->ref == 1;
            L -= table->subtables[x].keys - isolated;
        }
Alan Mishchenko committed
1625 1626 1627 1628 1629 1630
    }
    isolated = table->vars[yindex]->ref == 1;
    L -= table->subtables[y].keys - isolated;

    x = cuddNextLow(table,y);
    while (x >= xLow && L <= limitSize) {
1631
        xindex = table->invperm[x];
Alan Mishchenko committed
1632
#ifdef DD_DEBUG
1633 1634 1635 1636 1637 1638 1639
        checkL = table->keys - table->isolated;
        for (z = xLow + 1; z < y; z++) {
            zindex = table->invperm[z];
            if (cuddTestInteract(table,zindex,yindex)) {
                isolated = table->vars[zindex]->ref == 1;
                checkL -= table->subtables[z].keys - isolated;
            }
Alan Mishchenko committed
1640
        }
1641 1642 1643
        isolated = table->vars[yindex]->ref == 1;
        checkL -= table->subtables[y].keys - isolated;
        assert(L == checkL);
Alan Mishchenko committed
1644
#endif
1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662
        size = cuddSwapInPlace(table,x,y);
        if (size == 0) goto ddSiftingUpOutOfMem;
        /* Update the lower bound. */
        if (cuddTestInteract(table,xindex,yindex)) {
            isolated = table->vars[xindex]->ref == 1;
            L += table->subtables[y].keys - isolated;
        }
        move = (Move *) cuddDynamicAllocNode(table);
        if (move == NULL) goto ddSiftingUpOutOfMem;
        move->x = x;
        move->y = y;
        move->size = size;
        move->next = moves;
        moves = move;
        if ((double) size > (double) limitSize * table->maxGrowth) break;
        if (size < limitSize) limitSize = size;
        y = x;
        x = cuddNextLow(table,y);
Alan Mishchenko committed
1663 1664 1665 1666 1667
    }
    return(moves);

ddSiftingUpOutOfMem:
    while (moves != NULL) {
1668 1669 1670
        move = moves->next;
        cuddDeallocMove(table, moves);
        moves = move;
Alan Mishchenko committed
1671 1672 1673 1674
    }
    return((Move *) CUDD_OUT_OF_MEM);

} /* end of ddSiftingUp */
1675

Alan Mishchenko committed
1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694

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

  Synopsis    [Sifts a variable down.]

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

  SideEffects [None]

******************************************************************************/
static Move *
ddSiftingDown(
  DdManager * table,
  int  x,
  int  xHigh)
{
1695 1696 1697 1698 1699 1700 1701 1702
    Move        *moves;
    Move        *move;
    int         y;
    int         size;
    int         R;      /* upper bound on node decrease */
    int         limitSize;
    int         xindex, yindex;
    int         isolated;
Alan Mishchenko committed
1703
#ifdef DD_DEBUG
1704 1705 1706
    int         checkR;
    int         z;
    int         zindex;
Alan Mishchenko committed
1707 1708 1709 1710 1711 1712 1713 1714
#endif

    moves = NULL;
    /* Initialize R */
    xindex = table->invperm[x];
    limitSize = size = table->keys - table->isolated;
    R = 0;
    for (y = xHigh; y > x; y--) {
1715 1716 1717 1718 1719
        yindex = table->invperm[y];
        if (cuddTestInteract(table,xindex,yindex)) {
            isolated = table->vars[yindex]->ref == 1;
            R += table->subtables[y].keys - isolated;
        }
Alan Mishchenko committed
1720 1721 1722 1723 1724
    }

    y = cuddNextHigh(table,x);
    while (y <= xHigh && size - R < limitSize) {
#ifdef DD_DEBUG
1725 1726 1727 1728 1729 1730 1731
        checkR = 0;
        for (z = xHigh; z > x; z--) {
            zindex = table->invperm[z];
            if (cuddTestInteract(table,xindex,zindex)) {
                isolated = table->vars[zindex]->ref == 1;
                checkR += table->subtables[z].keys - isolated;
            }
Alan Mishchenko committed
1732
        }
1733
        assert(R == checkR);
Alan Mishchenko committed
1734
#endif
1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753
        /* Update upper bound on node decrease. */
        yindex = table->invperm[y];
        if (cuddTestInteract(table,xindex,yindex)) {
            isolated = table->vars[yindex]->ref == 1;
            R -= table->subtables[y].keys - isolated;
        }
        size = cuddSwapInPlace(table,x,y);
        if (size == 0) goto ddSiftingDownOutOfMem;
        move = (Move *) cuddDynamicAllocNode(table);
        if (move == NULL) goto ddSiftingDownOutOfMem;
        move->x = x;
        move->y = y;
        move->size = size;
        move->next = moves;
        moves = move;
        if ((double) size > (double) limitSize * table->maxGrowth) break;
        if (size < limitSize) limitSize = size;
        x = y;
        y = cuddNextHigh(table,x);
Alan Mishchenko committed
1754 1755 1756 1757 1758
    }
    return(moves);

ddSiftingDownOutOfMem:
    while (moves != NULL) {
1759 1760 1761
        move = moves->next;
        cuddDeallocMove(table, moves);
        moves = move;
Alan Mishchenko committed
1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787
    }
    return((Move *) CUDD_OUT_OF_MEM);

} /* end of ddSiftingDown */


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

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

  Description [Given a set of moves, returns the DD 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]

******************************************************************************/
static int
ddSiftingBackward(
  DdManager * table,
  int  size,
  Move * moves)
{
    Move *move;
1788
    int res;
Alan Mishchenko committed
1789 1790

    for (move = moves; move != NULL; move = move->next) {
1791 1792 1793
        if (move->size < size) {
            size = move->size;
        }
Alan Mishchenko committed
1794 1795 1796
    }

    for (move = moves; move != NULL; move = move->next) {
1797 1798 1799
        if (move->size == size) return(1);
        res = cuddSwapInPlace(table,(int)move->x,(int)move->y);
        if (!res) return(0);
Alan Mishchenko committed
1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836
    }

    return(1);

} /* end of ddSiftingBackward */


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

  Synopsis    [Prepares the DD heap for dynamic reordering.]

  Description [Prepares the DD heap for dynamic reordering. Does
  garbage collection, to guarantee that there are no dead nodes;
  clears the cache, which is invalidated by dynamic reordering; initializes
  the number of isolated projection functions; and initializes the
  interaction matrix.  Returns 1 in case of success; 0 otherwise.]

  SideEffects [None]

******************************************************************************/
static int
ddReorderPreprocess(
  DdManager * table)
{
    int i;
    int res;

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

    /* Eliminate dead nodes. Do not scan the cache again. */
    cuddGarbageCollect(table,0);

    /* Initialize number of isolated projection functions. */
    table->isolated = 0;
    for (i = 0; i < table->size; i++) {
1837
        if (table->vars[i]->ref == 1) table->isolated++;
Alan Mishchenko committed
1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867
    }

    /* Initialize the interaction matrix. */
    res = cuddInitInteract(table);
    if (res == 0) return(0);

    return(1);

} /* end of ddReorderPreprocess */


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

  Synopsis    [Cleans up at the end of reordering.]

  Description []

  SideEffects [None]

******************************************************************************/
static int
ddReorderPostprocess(
  DdManager * table)
{

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

    /* Free interaction matrix. */
Alan Mishchenko committed
1868
    ABC_FREE(table->interact);
Alan Mishchenko committed
1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895

    return(1);

} /* end of ddReorderPostprocess */


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

  Synopsis    [Reorders variables according to a given permutation.]

  Description [Reorders 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. ddShuffle assumes that no
  dead nodes are present and that the interaction matrix is properly
  initialized.  The reordering is achieved by a series of upward sifts.
  Returns 1 if successful; 0 otherwise.]

  SideEffects [None]

  SeeAlso []

******************************************************************************/
static int
ddShuffle(
  DdManager * table,
  int * permutation)
{
1896 1897 1898 1899 1900
    int         index;
    int         level;
    int         position;
    int         numvars;
    int         result;
Alan Mishchenko committed
1901
#ifdef DD_STATS
1902 1903 1904 1905
    long        localTime;
    int         initialSize;
    int         finalSize;
    int         previousSize;
Alan Mishchenko committed
1906 1907 1908 1909 1910 1911 1912
#endif

    ddTotalNumberSwapping = 0;
#ifdef DD_STATS
    localTime = util_cpu_time();
    initialSize = table->keys - table->isolated;
    (void) fprintf(table->out,"#:I_SHUFFLE %8d: initial size\n",
1913
                   initialSize);
Alan Mishchenko committed
1914 1915 1916 1917 1918 1919
    ddTotalNISwaps = 0;
#endif

    numvars = table->size;

    for (level = 0; level < numvars; level++) {
1920 1921
        index = permutation[level];
        position = table->perm[index];
Alan Mishchenko committed
1922
#ifdef DD_STATS
1923
        previousSize = table->keys - table->isolated;
Alan Mishchenko committed
1924
#endif
1925 1926
        result = ddSiftUp(table,position,level);
        if (!result) return(0);
Alan Mishchenko committed
1927
#ifdef DD_STATS
1928 1929 1930 1931 1932 1933 1934 1935
        if (table->keys < (unsigned) previousSize + table->isolated) {
            (void) fprintf(table->out,"-");
        } else if (table->keys > (unsigned) previousSize + table->isolated) {
            (void) fprintf(table->out,"+");     /* should never happen */
        } else {
            (void) fprintf(table->out,"=");
        }
        fflush(table->out);
Alan Mishchenko committed
1936 1937 1938 1939 1940 1941
#endif
    }

#ifdef DD_STATS
    (void) fprintf(table->out,"\n");
    finalSize = table->keys - table->isolated;
1942
    (void) fprintf(table->out,"#:F_SHUFFLE %8d: final size\n",finalSize);
Alan Mishchenko committed
1943
    (void) fprintf(table->out,"#:T_SHUFFLE %8g: total time (sec)\n",
1944
        ((double)(util_cpu_time() - localTime)/1000.0));
Alan Mishchenko committed
1945
    (void) fprintf(table->out,"#:N_SHUFFLE %8d: total swaps\n",
1946
                   ddTotalNumberSwapping);
Alan Mishchenko committed
1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978
    (void) fprintf(table->out,"#:M_SHUFFLE %8d: NI swaps\n",ddTotalNISwaps);
#endif

    return(1);

} /* end of ddShuffle */


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

  Synopsis    [Moves one variable up.]

  Description [Takes a 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
ddSiftUp(
  DdManager * table,
  int  x,
  int  xLow)
{
    int        y;
    int        size;

    y = cuddNextLow(table,x);
    while (y >= xLow) {
1979 1980 1981 1982 1983 1984
        size = cuddSwapInPlace(table,y,x);
        if (size == 0) {
            return(0);
        }
        x = y;
        y = cuddNextLow(table,x);
Alan Mishchenko committed
1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010
    }
    return(1);

} /* end of ddSiftUp */


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

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

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

  SideEffects [Changes the BDD variable group tree.]

  SeeAlso     []

******************************************************************************/
static void
bddFixTree(
  DdManager * table,
  MtrNode * treenode)
{
    if (treenode == NULL) return;
    treenode->low = ((int) treenode->index < table->size) ?
2011
        table->perm[treenode->index] : treenode->index;
Alan Mishchenko committed
2012
    if (treenode->child != NULL) {
2013
        bddFixTree(table, treenode->child);
Alan Mishchenko committed
2014 2015
    }
    if (treenode->younger != NULL)
2016
        bddFixTree(table, treenode->younger);
Alan Mishchenko committed
2017
    if (treenode->parent != NULL && treenode->low < treenode->parent->low) {
2018 2019
        treenode->parent->low = treenode->low;
        treenode->parent->index = treenode->index;
Alan Mishchenko committed
2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044
    }
    return;

} /* end of bddFixTree */


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

  Synopsis    [Updates the BDD variable group tree before a shuffle.]

  Description [Updates the BDD variable group tree before a shuffle.
  Returns 1 if successful; 0 otherwise.]

  SideEffects [Changes the BDD variable group tree.]

  SeeAlso     []

******************************************************************************/
static int
ddUpdateMtrTree(
  DdManager * table,
  MtrNode * treenode,
  int * perm,
  int * invperm)
{
2045 2046
    int i, size;
    int index, level, minLevel, maxLevel, minIndex;
Alan Mishchenko committed
2047 2048 2049

    if (treenode == NULL) return(1);

2050 2051 2052
    minLevel = CUDD_MAXINDEX;
    maxLevel = 0;
    minIndex = -1;
Alan Mishchenko committed
2053 2054
    /* i : level */
    for (i = treenode->low; i < treenode->low + treenode->size; i++) {
2055 2056 2057 2058 2059 2060 2061 2062
        index = table->invperm[i];
        level = perm[index];
        if (level < minLevel) {
            minLevel = level;
            minIndex = index;
        }
        if (level > maxLevel)
            maxLevel = level;
Alan Mishchenko committed
2063 2064
    }
    size = maxLevel - minLevel + 1;
2065
    if (minIndex == -1) return(0);
Alan Mishchenko committed
2066
    if (size == treenode->size) {
2067 2068 2069 2070 2071
        treenode->low = minLevel;
        treenode->index = minIndex;
    } else {
        return(0);
    }
Alan Mishchenko committed
2072 2073

    if (treenode->child != NULL) {
2074 2075
        if (!ddUpdateMtrTree(table, treenode->child, perm, invperm))
            return(0);
Alan Mishchenko committed
2076 2077
    }
    if (treenode->younger != NULL) {
2078 2079
        if (!ddUpdateMtrTree(table, treenode->younger, perm, invperm))
            return(0);
Alan Mishchenko committed
2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103
    }
    return(1);
}


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

  Synopsis    [Checks the BDD variable group tree before a shuffle.]

  Description [Checks the BDD variable group tree before a shuffle.
  Returns 1 if successful; 0 otherwise.]

  SideEffects [Changes the BDD variable group tree.]

  SeeAlso     []

******************************************************************************/
static int
ddCheckPermuation(
  DdManager * table,
  MtrNode * treenode,
  int * perm,
  int * invperm)
{
2104 2105
    int i, size;
    int index, level, minLevel, maxLevel;
Alan Mishchenko committed
2106 2107 2108 2109 2110 2111 2112

    if (treenode == NULL) return(1);

    minLevel = table->size;
    maxLevel = 0;
    /* i : level */
    for (i = treenode->low; i < treenode->low + treenode->size; i++) {
2113 2114 2115 2116 2117 2118
        index = table->invperm[i];
        level = perm[index];
        if (level < minLevel)
            minLevel = level;
        if (level > maxLevel)
            maxLevel = level;
Alan Mishchenko committed
2119 2120 2121
    }
    size = maxLevel - minLevel + 1;
    if (size != treenode->size)
2122
        return(0);
Alan Mishchenko committed
2123 2124

    if (treenode->child != NULL) {
2125 2126
        if (!ddCheckPermuation(table, treenode->child, perm, invperm))
            return(0);
Alan Mishchenko committed
2127 2128
    }
    if (treenode->younger != NULL) {
2129 2130
        if (!ddCheckPermuation(table, treenode->younger, perm, invperm))
            return(0);
Alan Mishchenko committed
2131 2132 2133
    }
    return(1);
}
2134 2135


2136 2137
ABC_NAMESPACE_IMPL_END