giaBalAig.c 39.8 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
/**CFile****************************************************************

  FileName    [giaBalance.c]

  SystemName  [ABC: Logic synthesis and verification system.]

  PackageName [Scalable AIG package.]

  Synopsis    [AIG balancing.]

  Author      [Alan Mishchenko]
  
  Affiliation [UC Berkeley]

  Date        [Ver. 1.0. Started - June 20, 2005.]

  Revision    [$Id: giaBalance.c,v 1.00 2005/06/20 00:00:00 alanmi Exp $]

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

#include "gia.h"
22 23
#include "misc/vec/vecHash.h"
#include "misc/vec/vecQue.h"
24
#include "opt/dau/dau.h"
25 26 27 28 29 30 31 32

ABC_NAMESPACE_IMPL_START


////////////////////////////////////////////////////////////////////////
///                        DECLARATIONS                              ///
////////////////////////////////////////////////////////////////////////

33 34 35 36 37 38
// operation manager
typedef struct Dam_Man_t_ Dam_Man_t;
struct Dam_Man_t_
{
    Gia_Man_t *      pGia;      // user's AIG
    Vec_Int_t *      vNod2Set;  // node ID into fanin set
39 40 41
    Vec_Int_t *      vDiv2Nod;  // div ID into root node set
    Vec_Int_t *      vSetStore; // fanin set storage
    Vec_Int_t *      vNodStore; // root node set storage
42
    Vec_Flt_t *      vCounts;   // occur counts
43 44
    Vec_Int_t *      vNodLevR;  // node reverse level
    Vec_Int_t *      vDivLevR;  // divisor reverse level
45 46
    Vec_Int_t *      vVisit;    // visited MUXes
    Vec_Que_t *      vQue;      // pairs by their weight
47 48
    Hash_IntMan_t *  vHash;     // pair hash table
    abctime          clkStart;  // starting the clock
49
    int              nLevelMax; // maximum level
50 51 52 53 54 55 56 57 58 59 60 61 62
    int              nDivs;     // extracted divisor count
    int              nAnds;     // total AND node count
    int              nGain;     // total gain in AND nodes
    int              nGainX;    // gain from XOR nodes
};

static inline int    Dam_ObjHand( Dam_Man_t * p, int i )     { return i < Vec_IntSize(p->vNod2Set) ? Vec_IntEntry(p->vNod2Set, i) : 0;                      }
static inline int *  Dam_ObjSet( Dam_Man_t * p, int i )      { int h = Dam_ObjHand(p, i); if ( h == 0 ) return NULL; return Vec_IntEntryP(p->vSetStore, h); }

static inline int    Dam_DivHand( Dam_Man_t * p, int d )     { return d < Vec_IntSize(p->vDiv2Nod) ? Vec_IntEntry(p->vDiv2Nod, d) : 0;                      }
static inline int *  Dam_DivSet( Dam_Man_t * p, int d )      { int h = Dam_DivHand(p, d); if ( h == 0 ) return NULL; return Vec_IntEntryP(p->vNodStore, h); }


63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
////////////////////////////////////////////////////////////////////////
///                     FUNCTION DEFINITIONS                         ///
////////////////////////////////////////////////////////////////////////

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

  Synopsis    [Simplify multi-input AND/XOR.]

  Description []
               
  SideEffects []

  SeeAlso     []

***********************************************************************/
void Gia_ManSimplifyXor( Vec_Int_t * vSuper )
{
    int i, k = 0, Prev = -1, This, fCompl = 0;
    Vec_IntForEachEntry( vSuper, This, i )
    {
        if ( This == 0 )
            continue;
        if ( This == 1 )
            fCompl ^= 1; 
        else if ( Prev != This )
            Vec_IntWriteEntry( vSuper, k++, This ), Prev = This;
        else
            Prev = -1, k--;
    }
    Vec_IntShrink( vSuper, k );
    if ( Vec_IntSize( vSuper ) == 0 )
94 95
        Vec_IntPush( vSuper, fCompl );
    else if ( fCompl )
96 97 98 99 100 101 102 103
        Vec_IntWriteEntry( vSuper, 0, Abc_LitNot(Vec_IntEntry(vSuper, 0)) );
}
void Gia_ManSimplifyAnd( Vec_Int_t * vSuper )
{
    int i, k = 0, Prev = -1, This;
    Vec_IntForEachEntry( vSuper, This, i )
    {
        if ( This == 0 )
104
            { Vec_IntFill(vSuper, 1, 0); return; }
105 106 107 108 109
        if ( This == 1 )
            continue;
        if ( Prev == -1 || Abc_Lit2Var(Prev) != Abc_Lit2Var(This) )
            Vec_IntWriteEntry( vSuper, k++, This ), Prev = This;
        else if ( Prev != This )
110
            { Vec_IntFill(vSuper, 1, 0); return; }
111 112
    }
    Vec_IntShrink( vSuper, k );
113 114
    if ( Vec_IntSize( vSuper ) == 0 )
        Vec_IntPush( vSuper, 1 );
115 116 117 118 119 120 121 122 123 124 125 126 127
}

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

  Synopsis    [Collect multi-input AND/XOR.]

  Description []
               
  SideEffects []

  SeeAlso     []

***********************************************************************/
128
void Gia_ManSuperCollectXor_rec( Gia_Man_t * p, Gia_Obj_t * pObj, int fStrict )
129 130
{
    assert( !Gia_IsComplement(pObj) );
131
    if ( !Gia_ObjIsXor(pObj) ||     
132
        (fStrict && Gia_ObjRefNum(p, pObj) > 1) || 
133 134
        Gia_ObjRefNum(p, pObj) > 2 || 
        (Gia_ObjRefNum(p, pObj) == 2 && (Gia_ObjRefNum(p, Gia_ObjFanin0(pObj)) == 1 || Gia_ObjRefNum(p, Gia_ObjFanin1(pObj)) == 1)) || 
135
        Vec_IntSize(p->vSuper) > 50 )
136 137 138 139 140
    {
        Vec_IntPush( p->vSuper, Gia_ObjToLit(p, pObj) );
        return;
    }
    assert( !Gia_ObjFaninC0(pObj) && !Gia_ObjFaninC1(pObj) );
141 142
    Gia_ManSuperCollectXor_rec( p, Gia_ObjFanin0(pObj), fStrict );
    Gia_ManSuperCollectXor_rec( p, Gia_ObjFanin1(pObj), fStrict );
143
}
144
void Gia_ManSuperCollectAnd_rec( Gia_Man_t * p, Gia_Obj_t * pObj, int fStrict )
145
{
146 147
    if ( Gia_IsComplement(pObj) || 
        !Gia_ObjIsAndReal(p, pObj) || 
148
        (fStrict && Gia_ObjRefNum(p, pObj) > 1) || 
149 150
        Gia_ObjRefNum(p, pObj) > 2 || 
        (Gia_ObjRefNum(p, pObj) == 2 && (Gia_ObjRefNum(p, Gia_ObjFanin0(pObj)) == 1 || Gia_ObjRefNum(p, Gia_ObjFanin1(pObj)) == 1)) || 
151
        Vec_IntSize(p->vSuper) > 50 )
152 153 154 155
    {
        Vec_IntPush( p->vSuper, Gia_ObjToLit(p, pObj) );
        return;
    }
156 157
    Gia_ManSuperCollectAnd_rec( p, Gia_ObjChild0(pObj), fStrict );
    Gia_ManSuperCollectAnd_rec( p, Gia_ObjChild1(pObj), fStrict );
158
}
159
void Gia_ManSuperCollect( Gia_Man_t * p, Gia_Obj_t * pObj, int fStrict )
160
{
161 162 163 164 165
//    int nSize;
    if ( p->vSuper == NULL )
        p->vSuper = Vec_IntAlloc( 1000 );
    else
        Vec_IntClear( p->vSuper );
166 167 168
    if ( Gia_ObjIsXor(pObj) )
    {
        assert( !Gia_ObjFaninC0(pObj) && !Gia_ObjFaninC1(pObj) );
169 170
        Gia_ManSuperCollectXor_rec( p, Gia_ObjFanin0(pObj), fStrict );
        Gia_ManSuperCollectXor_rec( p, Gia_ObjFanin1(pObj), fStrict );
171
//        nSize = Vec_IntSize(vSuper);
172 173
        Vec_IntSort( p->vSuper, 0 );
        Gia_ManSimplifyXor( p->vSuper );
174 175
//        if ( nSize != Vec_IntSize(vSuper) )
//            printf( "X %d->%d  ", nSize, Vec_IntSize(vSuper) );
176 177 178
    }
    else if ( Gia_ObjIsAndReal(p, pObj) )
    {
179 180
        Gia_ManSuperCollectAnd_rec( p, Gia_ObjChild0(pObj), fStrict );
        Gia_ManSuperCollectAnd_rec( p, Gia_ObjChild1(pObj), fStrict );
181
//        nSize = Vec_IntSize(vSuper);
182 183
        Vec_IntSort( p->vSuper, 0 );
        Gia_ManSimplifyAnd( p->vSuper );
184 185
//        if ( nSize != Vec_IntSize(vSuper) )
//            printf( "A %d->%d  ", nSize, Vec_IntSize(vSuper) );
186 187
    }
    else assert( 0 );
188 189 190
//    if ( nSize > 10 )
//        printf( "%d ", nSize );
    assert( Vec_IntSize(p->vSuper) > 0 );
191 192 193 194 195 196 197 198 199 200 201 202 203
}

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

  Synopsis    []

  Description []
               
  SideEffects []

  SeeAlso     []

***********************************************************************/
204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259
int Gia_ManFindSharedNode( Gia_Man_t * pNew, Vec_Int_t * vSuper, int iLit0 )
{
    int i, iLit1 = Vec_IntEntryLast(vSuper);
    // iterate through the nodes whose level is equal to that of the last one
    int iLit1Level = Gia_ObjLevelId(pNew, Abc_Lit2Var(iLit1));
    for ( i = Vec_IntSize(vSuper)-1; i >= 0; i-- )
    {
        int iLit2 = Vec_IntEntry(vSuper, i);
        if ( iLit1Level != Gia_ObjLevelId(pNew, Abc_Lit2Var(iLit2)) )
            break;
        if ( Abc_Lit2Var(iLit0) != Abc_Lit2Var(iLit2) && !Gia_ManHashLookupInt(pNew, iLit0, iLit2) ) // new node
            continue;
        // swap iLit2 and iLit1
        if ( iLit2 != iLit1 )
        {
            Vec_IntWriteEntry( vSuper, i, iLit1 );
            Vec_IntWriteEntry( vSuper, Vec_IntSize(vSuper)-1, iLit2 );
        }
        break;
    }
    return Vec_IntPop(vSuper);    
}
void Gia_ManPrepareLastTwo( Gia_Man_t * pNew, Vec_Int_t * vSuper )
{
    int i, k, Stop, Lit1, Lit2, Level1, Level2, * pArray;
    int nSize = Vec_IntSize(vSuper);
    if ( nSize == 2 )
        return;
    assert( nSize > 2 );
    Level1 = Gia_ObjLevelId( pNew, Abc_Lit2Var(Vec_IntEntry(vSuper, nSize-2)) );
    // find the first one with Level1
    for ( Stop = nSize-3; Stop >= 0; Stop-- )
    {
        Level2 = Gia_ObjLevelId( pNew, Abc_Lit2Var(Vec_IntEntry(vSuper, Stop)) );
        if ( Level1 != Level2 )
            break;
    }
    if ( Stop == nSize-3 )
        return;
    // avoid worst-case quadratic behavior by looking at the last 8 nodes
    Stop = Abc_MaxInt( Stop, nSize - 9 );
    for ( i = nSize - 1; i > Stop; i-- )
        for ( k = i - 1; k > Stop; k-- )
        {
            Lit1 = Vec_IntEntry(vSuper, i);
            Lit2 = Vec_IntEntry(vSuper, k);
            if ( Abc_Lit2Var(Lit1) != Abc_Lit2Var(Lit2) && !Gia_ManHashLookupInt(pNew, Lit1, Lit2) ) // new node
                continue;
            // move Lit1 to be last and Lit2 to be the one before
            pArray = Vec_IntArray( vSuper );
            if ( i != nSize-1 )
                ABC_SWAP( int, pArray[i], pArray[nSize-1] );
            if ( k != nSize-2 )
                ABC_SWAP( int, pArray[k], pArray[nSize-2] );
        }
}
260
void Gia_ManCreateGate( Gia_Man_t * pNew, Gia_Obj_t * pObj, Vec_Int_t * vSuper )
261 262 263
{
    int iLit0 = Vec_IntPop(vSuper);
    int iLit1 = Vec_IntPop(vSuper);
264
//    int iLit1 = Gia_ManFindSharedNode(pNew, vSuper, iLit0);
265
    int iLit, i;
266
    if ( !Gia_ObjIsXor(pObj) )
267
        iLit = Gia_ManHashAnd( pNew, iLit0, iLit1 );
268 269 270 271
    else if ( pNew->pMuxes )
        iLit = Gia_ManHashXorReal( pNew, iLit0, iLit1 );
    else 
        iLit = Gia_ManHashXor( pNew, iLit0, iLit1 );
272 273 274 275 276 277 278
    Vec_IntPush( vSuper, iLit );
    Gia_ObjSetGateLevel( pNew, Gia_ManObj(pNew, Abc_Lit2Var(iLit)) );
    // shift to the corrent location
    for ( i = Vec_IntSize(vSuper)-1; i > 0; i-- )
    {
        int iLit1 = Vec_IntEntry(vSuper, i);
        int iLit2 = Vec_IntEntry(vSuper, i-1);
279
        if ( Gia_ObjLevelId(pNew, Abc_Lit2Var(iLit1)) <= Gia_ObjLevelId(pNew, Abc_Lit2Var(iLit2)) )
280 281 282 283 284
            break;
        Vec_IntWriteEntry( vSuper, i,   iLit2 );
        Vec_IntWriteEntry( vSuper, i-1, iLit1 );
    }
}
285 286
int Gia_ManBalanceGate( Gia_Man_t * pNew, Gia_Obj_t * pObj, Vec_Int_t * vSuper, int * pLits, int nLits )
{
287
    assert( !Gia_ObjIsBuf(pObj) );
288 289 290 291
    Vec_IntClear( vSuper );
    if ( nLits == 1 )
        Vec_IntPush( vSuper, pLits[0] );
    else if ( nLits == 2 )
292 293 294 295 296 297 298 299
    {
        Vec_IntPush( vSuper, pLits[0] );
        Vec_IntPush( vSuper, pLits[1] );
        Gia_ManCreateGate( pNew, pObj, vSuper );
    }
    else if ( nLits > 2 )
    {
        // collect levels
300
        int i, * pArray, * pPerm; //int iLit;
301 302 303 304 305 306 307 308 309 310 311
        for ( i = 0; i < nLits; i++ )
            Vec_IntPush( vSuper, Gia_ObjLevelId(pNew, Abc_Lit2Var(pLits[i])) );
        // sort by level
        Vec_IntGrow( vSuper, 4 * nLits );        
        pArray = Vec_IntArray( vSuper );
        pPerm = pArray + nLits;
        Abc_QuickSortCostData( pArray, nLits, 1, (word *)(pArray + 2 * nLits), pPerm );
        // collect in the increasing order of level
        for ( i = 0; i < nLits; i++ )
            Vec_IntWriteEntry( vSuper, i, pLits[pPerm[i]] );
        Vec_IntShrink( vSuper, nLits );
312 313 314 315 316
/*            
        Vec_IntForEachEntry( vSuper, iLit, i )
            printf( "%d ", Gia_ObjLevel(pNew, Gia_ManObj( pNew, Abc_Lit2Var(iLit) )) );
        printf( "\n" );
*/
317 318
        // perform incremental extraction
        while ( Vec_IntSize(vSuper) > 1 )
319 320 321
        {
            if ( !Gia_ObjIsXor(pObj) )
                Gia_ManPrepareLastTwo( pNew, vSuper );
322
            Gia_ManCreateGate( pNew, pObj, vSuper );
323
        }
324 325 326 327 328
    }
    // consider trivial case
    assert( Vec_IntSize(vSuper) == 1 );
    return Vec_IntEntry(vSuper, 0);
}
329 330 331 332 333 334 335 336 337 338 339 340

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

  Synopsis    []

  Description []
               
  SideEffects []

  SeeAlso     []

***********************************************************************/
341
void Gia_ManBalance_rec( Gia_Man_t * pNew, Gia_Man_t * p, Gia_Obj_t * pObj, int fStrict )
342 343 344 345 346
{
    int i, iLit, iBeg, iEnd;
    if ( ~pObj->Value )
        return;
    assert( Gia_ObjIsAnd(pObj) );
347
    assert( !Gia_ObjIsBuf(pObj) );
348 349 350
    // handle MUX
    if ( Gia_ObjIsMux(p, pObj) )
    {
351 352 353
        Gia_ManBalance_rec( pNew, p, Gia_ObjFanin0(pObj), fStrict );
        Gia_ManBalance_rec( pNew, p, Gia_ObjFanin1(pObj), fStrict );
        Gia_ManBalance_rec( pNew, p, Gia_ObjFanin2(p, pObj), fStrict );
354 355 356 357 358
        pObj->Value = Gia_ManHashMuxReal( pNew, Gia_ObjFanin2Copy(p, pObj), Gia_ObjFanin1Copy(pObj), Gia_ObjFanin0Copy(pObj) );
        Gia_ObjSetGateLevel( pNew, Gia_ManObj(pNew, Abc_Lit2Var(pObj->Value)) );
        return;
    }
    // find supergate
359
    Gia_ManSuperCollect( p, pObj, fStrict );
360
    // save entries
361 362
    if ( p->vStore == NULL )
        p->vStore = Vec_IntAlloc( 1000 );
363 364 365 366 367 368 369
    iBeg = Vec_IntSize( p->vStore );
    Vec_IntAppend( p->vStore, p->vSuper );
    iEnd = Vec_IntSize( p->vStore );
    // call recursively
    Vec_IntForEachEntryStartStop( p->vStore, iLit, i, iBeg, iEnd )
    {
        Gia_Obj_t * pTemp = Gia_ManObj( p, Abc_Lit2Var(iLit) );
370
        Gia_ManBalance_rec( pNew, p, pTemp, fStrict );
371 372 373 374
        Vec_IntWriteEntry( p->vStore, i, Abc_LitNotCond(pTemp->Value, Abc_LitIsCompl(iLit)) );
    }
    assert( Vec_IntSize(p->vStore) == iEnd );
    // consider general case
375
    pObj->Value = Gia_ManBalanceGate( pNew, pObj, p->vSuper, Vec_IntEntryP(p->vStore, iBeg), iEnd-iBeg );
376 377
    Vec_IntShrink( p->vStore, iBeg );
}
378
Gia_Man_t * Gia_ManBalanceInt( Gia_Man_t * p, int fStrict )
379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394
{
    Gia_Man_t * pNew, * pTemp;
    Gia_Obj_t * pObj;
    int i;
    Gia_ManFillValue( p );
    Gia_ManCreateRefs( p ); 
    // start the new manager
    pNew = Gia_ManStart( Gia_ManObjNum(p) );
    pNew->pName = Abc_UtilStrsav( p->pName );
    pNew->pSpec = Abc_UtilStrsav( p->pSpec );
    pNew->pMuxes = ABC_CALLOC( unsigned, pNew->nObjsAlloc );
    pNew->vLevels = Vec_IntStart( pNew->nObjsAlloc );
    // create constant and inputs
    Gia_ManConst0(p)->Value = 0;
    Gia_ManForEachCi( p, pObj, i )
        pObj->Value = Gia_ManAppendCi( pNew );
395 396 397 398 399 400 401
    // set arrival times for the input of the new AIG
    if ( p->vCiArrs )
    {
        int Id, And2Delay = p->And2Delay ? p->And2Delay : 1;
        Gia_ManForEachCiId( pNew, Id, i )
            Vec_IntWriteEntry( pNew->vLevels, Id, Vec_IntEntry(p->vCiArrs, i)/And2Delay );
    }
402 403 404 405 406 407
    else if ( p->vInArrs )
    {
        int Id, And2Delay = p->And2Delay ? p->And2Delay : 1;
        Gia_ManForEachCiId( pNew, Id, i )
            Vec_IntWriteEntry( pNew->vLevels, Id, (int)(Vec_FltEntry(p->vInArrs, i)/And2Delay) );
    }
408 409
    // create internal nodes
    Gia_ManHashStart( pNew );
410 411
    Gia_ManForEachBuf( p, pObj, i )
    {
412
        Gia_ManBalance_rec( pNew, p, Gia_ObjFanin0(pObj), fStrict );
413 414 415
        pObj->Value = Gia_ManAppendBuf( pNew, Gia_ObjFanin0Copy(pObj) );
        Gia_ObjSetGateLevel( pNew, Gia_ManObj(pNew, Abc_Lit2Var(pObj->Value)) );
    }
416 417
    Gia_ManForEachCo( p, pObj, i )
    {
418
        Gia_ManBalance_rec( pNew, p, Gia_ObjFanin0(pObj), fStrict );
419 420
        pObj->Value = Gia_ManAppendCo( pNew, Gia_ObjFanin0Copy(pObj) );
    }
421
    assert( !fStrict || Gia_ManObjNum(pNew) <= Gia_ManObjNum(p) );
422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440
    Gia_ManHashStop( pNew );
    Gia_ManSetRegNum( pNew, Gia_ManRegNum(p) );
    // perform cleanup
    pNew = Gia_ManCleanup( pTemp = pNew );
    Gia_ManStop( pTemp );
    return pNew;
}

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

  Synopsis    []

  Description []
               
  SideEffects []

  SeeAlso     []

***********************************************************************/
441
Gia_Man_t * Gia_ManBalance( Gia_Man_t * p, int fSimpleAnd, int fStrict, int fVerbose )
442 443 444
{
    Gia_Man_t * pNew, * pNew1, * pNew2;
    if ( fVerbose )      Gia_ManPrintStats( p, NULL );
Alan Mishchenko committed
445
    pNew = fSimpleAnd ? Gia_ManDup( p ) : Gia_ManDupMuxes( p, 2 );
446
    Gia_ManTransferTiming( pNew, p );
447
    if ( fVerbose )      Gia_ManPrintStats( pNew, NULL );
448
    pNew1 = Gia_ManBalanceInt( pNew, fStrict );
449
    Gia_ManTransferTiming( pNew1, pNew );
450 451
    if ( fVerbose )      Gia_ManPrintStats( pNew1, NULL );
    Gia_ManStop( pNew );
Alan Mishchenko committed
452
    pNew2 = Gia_ManDupNoMuxes( pNew1, 0 );
453
    Gia_ManTransferTiming( pNew2, pNew1 );
454 455 456 457 458
    if ( fVerbose )      Gia_ManPrintStats( pNew2, NULL );
    Gia_ManStop( pNew1 );
    return pNew2;
}

459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478




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

  Synopsis    []

  Description []

  SideEffects []

  SeeAlso     []

***********************************************************************/
Dam_Man_t * Dam_ManAlloc( Gia_Man_t * pGia )
{
    Dam_Man_t * p;
    p = ABC_CALLOC( Dam_Man_t, 1 );
    p->clkStart = Abc_Clock();
479
    p->vVisit = Vec_IntAlloc( 1000 );
480 481 482 483 484
    p->pGia = pGia;
    return p;
}
void Dam_ManFree( Dam_Man_t * p )
{   
485
    Vec_IntFreeP( &p->vVisit );
486 487
    Vec_IntFreeP( &p->vDivLevR );
    Vec_IntFreeP( &p->vNodLevR );
488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517
    Vec_IntFreeP( &p->vNod2Set );
    Vec_IntFreeP( &p->vDiv2Nod );
    Vec_IntFreeP( &p->vSetStore );
    Vec_IntFreeP( &p->vNodStore );
    Vec_FltFreeP( &p->vCounts );
    Vec_QueFreeP( &p->vQue );
    Hash_IntManStop( p->vHash );
    ABC_FREE( p );
}

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

  Synopsis    [Collect initial multi-input gates.]

  Description []
               
  SideEffects []

  SeeAlso     []

***********************************************************************/
void Dam_ManCollectSets_rec( Dam_Man_t * p, int Id )
{
    Gia_Obj_t * pObj;
    int i, iBeg, iEnd, iLit;
    if ( Dam_ObjHand(p, Id) || Id == 0 )
        return;
    pObj = Gia_ManObj(p->pGia, Id);
    if ( Gia_ObjIsCi(pObj) )
        return;
518 519 520 521 522
    if ( Gia_ObjIsBuf(pObj) )
    {
        Dam_ManCollectSets_rec( p, Gia_ObjFaninId0(pObj, Id) );
        return;
    }
523 524
    if ( Gia_ObjIsMux(p->pGia, pObj) )
    {
525 526 527 528
        if ( pObj->fMark0 )
            return;
        pObj->fMark0 = 1;
        Vec_IntPush( p->vVisit, Id );
529 530 531 532 533 534
        Dam_ManCollectSets_rec( p, Gia_ObjFaninId0(pObj, Id) );
        Dam_ManCollectSets_rec( p, Gia_ObjFaninId1(pObj, Id) );
        Dam_ManCollectSets_rec( p, Gia_ObjFaninId2(p->pGia, Id) );
        p->nAnds += 3;
        return;
    }
535
    Gia_ManSuperCollect( p->pGia, pObj, 0 );
536 537 538 539 540 541 542 543 544 545 546 547 548 549 550
    Vec_IntWriteEntry( p->vNod2Set, Id, Vec_IntSize(p->vSetStore) );
    Vec_IntPush( p->vSetStore, Vec_IntSize(p->pGia->vSuper) );
    p->nAnds += (1 + 2 * Gia_ObjIsXor(pObj)) * (Vec_IntSize(p->pGia->vSuper) - 1);
    // save entries
    iBeg = Vec_IntSize( p->vSetStore );
    Vec_IntAppend( p->vSetStore, p->pGia->vSuper );
    iEnd = Vec_IntSize( p->vSetStore );
    // call recursively
    Vec_IntForEachEntryStartStop( p->vSetStore, iLit, i, iBeg, iEnd )
        Dam_ManCollectSets_rec( p, Abc_Lit2Var(iLit) );
}
void Dam_ManCollectSets( Dam_Man_t * p )
{
    Gia_Obj_t * pObj;
    int i;
551
    Gia_ManCreateRefs( p->pGia );
552 553 554
    p->vNod2Set  = Vec_IntStart( Gia_ManObjNum(p->pGia) );
    p->vSetStore = Vec_IntAlloc( Gia_ManObjNum(p->pGia) );
    Vec_IntPush( p->vSetStore, -1 );
555
    Vec_IntClear( p->vVisit );
556 557 558
    Gia_ManForEachCo( p->pGia, pObj, i )
        Dam_ManCollectSets_rec( p, Gia_ObjFaninId0p(p->pGia, pObj) );
    ABC_FREE( p->pGia->pRefs );
559 560
    Gia_ManForEachObjVec( p->vVisit, p->pGia, pObj, i )
        pObj->fMark0 = 0;
561 562 563 564 565 566 567 568 569 570 571 572 573
}

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

  Synopsis    [Create divisors.]

  Description []
               
  SideEffects []

  SeeAlso     []

***********************************************************************/
574
int Dam_ManDivSlack( Dam_Man_t * p, int iLit0, int iLit1, int LevR )
575
{
576 577
    int Lev0 = Gia_ObjLevel(p->pGia, Gia_ManObj(p->pGia, Abc_Lit2Var(iLit0)));
    int Lev1 = Gia_ObjLevel(p->pGia, Gia_ManObj(p->pGia, Abc_Lit2Var(iLit1)));
578 579
    int Slack = p->nLevelMax - LevR - Abc_MaxInt(Lev0, Lev1) - 1 - (int)(iLit0 > iLit1);
    return Abc_MinInt( Slack, 100 );
580
}
581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606
void Dam_ManCreateMultiRefs( Dam_Man_t * p, Vec_Int_t ** pvRefsAnd, Vec_Int_t ** pvRefsXor )  
{
    Vec_Int_t * vRefsAnd, * vRefsXor;
    Gia_Obj_t * pObj;
    int i, k, * pSet;
    vRefsAnd = Vec_IntStart( 2 * Gia_ManObjNum(p->pGia) );
    vRefsXor = Vec_IntStart( Gia_ManObjNum(p->pGia) );
    Gia_ManForEachAnd( p->pGia, pObj, i )
    {
        if ( !Dam_ObjHand(p, i) )
            continue;
        pSet = Dam_ObjSet(p, i);
        if ( Gia_ObjIsXor(pObj) )
            for ( k = 1; k <= pSet[0]; k++ )
            {
                assert( !Abc_LitIsCompl(pSet[k]) );
                Vec_IntAddToEntry( vRefsXor, Abc_Lit2Var(pSet[k]), 1 );
            }
        else if ( Gia_ObjIsAndReal(p->pGia, pObj) )
            for ( k = 1; k <= pSet[0]; k++ )
                Vec_IntAddToEntry( vRefsAnd, pSet[k], 1 );
        else assert( 0 );
    }
    *pvRefsAnd = vRefsAnd;
    *pvRefsXor = vRefsXor;
}
607
void Dam_ManCreatePairs( Dam_Man_t * p, int fVerbose )
608 609 610
{
    Gia_Obj_t * pObj;
    Hash_IntMan_t * vHash;
611
    Vec_Int_t * vRefsAnd, * vRefsXor, * vSuper, * vDivs, * vRemap, * vLevRMax;
612 613 614 615 616 617
    int i, j, k, Num, FanK, FanJ, nRefs, iNode, iDiv, * pSet;
    int nPairsAll = 0, nPairsTried = 0, nPairsUsed = 0, nPairsXor = 0;
    int nDivsAll = 0, nDivsUsed = 0, nDivsXor = 0;
    Dam_ManCollectSets( p );
    vSuper = p->pGia->vSuper;
    vDivs  = Vec_IntAlloc( Gia_ManObjNum(p->pGia) );
618
    vHash  = Hash_IntManStart( Gia_ManObjNum(p->pGia)/2 );
619
    vLevRMax = Vec_IntStart( 1000 );
620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658
    Dam_ManCreateMultiRefs( p, &vRefsAnd, &vRefsXor );
    Gia_ManForEachAnd( p->pGia, pObj, i )
    {
        if ( !Dam_ObjHand(p, i) )
            continue;
        pSet = Dam_ObjSet(p, i);
        nPairsAll += pSet[0] * (pSet[0] - 1) / 2;
        Vec_IntClear(vSuper);
        if ( Gia_ObjIsXor(pObj) )
        {
            for ( k = 1; k <= pSet[0]; k++ )
                if ( Vec_IntEntry(vRefsXor, Abc_Lit2Var(pSet[k])) > 1 )
                    Vec_IntPush( vSuper, pSet[k] );
        }
        else if ( Gia_ObjIsAndReal(p->pGia, pObj) )
        {
            for ( k = 1; k <= pSet[0]; k++ )
                if ( Vec_IntEntry(vRefsAnd, pSet[k]) > 1 )
                    Vec_IntPush( vSuper, pSet[k] );
        }
        else assert( 0 );
        if ( Vec_IntSize(vSuper) < 2 )
            continue;
        // enumerate pairs
        nPairsTried += Vec_IntSize(vSuper) * (Vec_IntSize(vSuper) - 1) / 2;
        Vec_IntPush( vDivs, -i ); // remember node
        Vec_IntForEachEntry( vSuper, FanK, k )
        Vec_IntForEachEntryStart( vSuper, FanJ, j, k+1 )
        {
            if ( (FanK > FanJ) ^ Gia_ObjIsXor(pObj) )
                Num = Hash_Int2ManInsert( vHash, FanJ, FanK, 0 );
            else
                Num = Hash_Int2ManInsert( vHash, FanK, FanJ, 0 );
            if ( Hash_Int2ObjInc( vHash, Num ) == 1 )
            {
                nDivsUsed++;
                nDivsXor += Gia_ObjIsXor(pObj);
            }
            Vec_IntPush( vDivs, Num ); // remember devisor
659 660 661 662
            // update reverse level
            if ( Num >= Vec_IntSize(vLevRMax) )
                Vec_IntFillExtra( vLevRMax, 3 * Vec_IntSize(vLevRMax) / 2, 0 );
            Vec_IntUpdateEntry( vLevRMax, Num, Vec_IntEntry(p->vNodLevR, i) );
663 664 665 666
        }
    }
    Vec_IntFree( vRefsAnd );
    Vec_IntFree( vRefsXor );
667
//    Hash_IntManProfile( vHash );
668
    // remove entries that appear only once
669
    p->vHash     = Hash_IntManStart( 3 * nDivsUsed /2 );
670 671
    p->vCounts   = Vec_FltAlloc( 2 * nDivsUsed );           Vec_FltPush( p->vCounts, ABC_INFINITY );
    p->vQue      = Vec_QueAlloc( Vec_FltCap(p->vCounts) );
672
    Vec_QueSetPriority( p->vQue, Vec_FltArrayP(p->vCounts) );
673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688
    // mapping div to node
    p->vDiv2Nod  = Vec_IntAlloc( 2 * nDivsUsed );           Vec_IntPush( p->vDiv2Nod, ABC_INFINITY );
    p->vNodStore = Vec_IntAlloc( Gia_ManObjNum(p->pGia) );  Vec_IntPush( p->vNodStore, -1 );
    nDivsAll     = Hash_IntManEntryNum(vHash);
    vRemap       = Vec_IntStartFull( nDivsAll+1 );
    for ( i = 1; i <= nDivsAll; i++ )
    {
        nRefs = Hash_IntObjData2(vHash, i);
        if ( nRefs < 2 )
            continue;
        nPairsUsed += nRefs;
        if ( Hash_IntObjData0(vHash, i) > Hash_IntObjData1(vHash, i) )
            nPairsXor += nRefs; 
        Num = Hash_Int2ManInsert( p->vHash, Hash_IntObjData0(vHash, i), Hash_IntObjData1(vHash, i), 0 );
        assert( Num == Hash_IntManEntryNum(p->vHash) );
        assert( Num == Vec_FltSize(p->vCounts) );
689
        Vec_FltPush( p->vCounts, nRefs + 0.005*Dam_ManDivSlack(p, Hash_IntObjData0(vHash, i), Hash_IntObjData1(vHash, i), Vec_IntEntry(vLevRMax, i)) );
690 691 692 693 694 695 696 697 698 699 700 701
        Vec_QuePush( p->vQue, Num );
        // remember divisors
        assert( Num == Vec_IntSize(p->vDiv2Nod) );
        Vec_IntPush( p->vDiv2Nod, Vec_IntSize(p->vNodStore) );
        Vec_IntPush( p->vNodStore, 0 );
        Vec_IntFillExtra( p->vNodStore, Vec_IntSize(p->vNodStore) + nRefs, -1 );
        // remember entry
        Vec_IntWriteEntry( vRemap, i, Num );
    }
    assert( Vec_FltSize(p->vCounts) == Hash_IntManEntryNum(p->vHash)+1 );
    assert( Vec_IntSize(p->vDiv2Nod) == nDivsUsed+1 );
    Hash_IntManStop( vHash );
702
    Vec_IntFree( vLevRMax );
703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719
    // fill in the divisors
    iNode = -1;
    Vec_IntForEachEntry( vDivs, iDiv, i )
    {
        if ( iDiv < 0 )
        {
            iNode = -iDiv;
            continue;
        }
        Num = Vec_IntEntry( vRemap, iDiv );
        if ( Num == -1 )
            continue;
        pSet = Dam_DivSet( p, Num );
        pSet[++pSet[0]] = iNode;
    }
    Vec_IntFree( vRemap );
    Vec_IntFree( vDivs );
720 721
    // create storage for reverse level of divisor during update
    p->vDivLevR = Vec_IntStart( 2 * nDivsUsed );
722
    // make sure divisors are added correctly
723 724
//    for ( i = 1; i <= nDivsUsed; i++ )
//        assert( Dam_DivSet(p, i)[0] == Vec_FltEntry(p->vCounts, i)+1 );
725 726
    if ( !fVerbose )
        return;
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 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793
    // print stats
    printf( "Pairs:" );
    printf( "  Total =%9d (%6.2f %%)", nPairsAll,   100.0 * nPairsAll   / Abc_MaxInt(nPairsAll, 1) );
    printf( "  Tried =%9d (%6.2f %%)", nPairsTried, 100.0 * nPairsTried / Abc_MaxInt(nPairsAll, 1) );
    printf( "  Used =%9d (%6.2f %%)",  nPairsUsed,  100.0 * nPairsUsed  / Abc_MaxInt(nPairsAll, 1) );
    printf( "  Xor =%9d (%6.2f %%)",   nPairsXor,   100.0 * nPairsXor   / Abc_MaxInt(nPairsAll, 1) );
    printf( "\n" );
    printf( "Div:  " );
    printf( "  Total =%9d (%6.2f %%)", nDivsAll,    100.0 * nDivsAll    / Abc_MaxInt(nDivsAll, 1) );
    printf( "  Tried =%9d (%6.2f %%)", nDivsAll,    100.0 * nDivsAll    / Abc_MaxInt(nDivsAll, 1) );
    printf( "  Used =%9d (%6.2f %%)",  nDivsUsed,   100.0 * nDivsUsed   / Abc_MaxInt(nDivsAll, 1) );
    printf( "  Xor =%9d (%6.2f %%)",   nDivsXor,    100.0 * nDivsXor    / Abc_MaxInt(nDivsAll, 1) );
    printf( "\n" );
}

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

  Synopsis    [Derives new AIG.]

  Description []
               
  SideEffects []

  SeeAlso     []

***********************************************************************/
void Dam_ManMultiAig_rec( Dam_Man_t * pMan, Gia_Man_t * pNew, Gia_Man_t * p, Gia_Obj_t * pObj )
{
    int i, * pSet;
    if ( ~pObj->Value )
        return;
    assert( Gia_ObjIsAnd(pObj) );
    pSet = Dam_ObjSet(pMan, Gia_ObjId(p, pObj));
    if ( pSet == NULL )
    {
        Dam_ManMultiAig_rec( pMan, pNew, p, Gia_ObjFanin0(pObj) );
        Dam_ManMultiAig_rec( pMan, pNew, p, Gia_ObjFanin1(pObj) );
        if ( Gia_ObjIsMux(p, pObj) )
        {
            Dam_ManMultiAig_rec( pMan, pNew, p, Gia_ObjFanin2(p, pObj) );
            pObj->Value = Gia_ManHashMuxReal( pNew, Gia_ObjFanin2Copy(p, pObj), Gia_ObjFanin1Copy(pObj), Gia_ObjFanin0Copy(pObj) );
        }
        else if ( Gia_ObjIsXor(pObj) )
            pObj->Value = Gia_ManHashXorReal( pNew, Gia_ObjFanin0Copy(pObj), Gia_ObjFanin1Copy(pObj) );
        else 
            pObj->Value = Gia_ManHashAnd( pNew, Gia_ObjFanin0Copy(pObj), Gia_ObjFanin1Copy(pObj) );
        Gia_ObjSetGateLevel( pNew, Gia_ManObj(pNew, Abc_Lit2Var(pObj->Value)) );
        return;
    }
    assert( Gia_ObjIsXor(pObj) || Gia_ObjIsAndReal(p, pObj) );
    // call recursively
    for ( i = 1; i <= pSet[0]; i++ )
    {
        Gia_Obj_t * pTemp = Gia_ManObj( p, Abc_Lit2Var(pSet[i]) );
        Dam_ManMultiAig_rec( pMan, pNew, p, pTemp );
        pSet[i] = Abc_LitNotCond( pTemp->Value, Abc_LitIsCompl(pSet[i]) );
    }
    // create balanced gate
    pObj->Value = Gia_ManBalanceGate( pNew, pObj, p->vSuper, pSet + 1, pSet[0] );
}
Gia_Man_t * Dam_ManMultiAig( Dam_Man_t * pMan )
{
    Gia_Man_t * p = pMan->pGia;
    Gia_Man_t * pNew, * pTemp;
    Gia_Obj_t * pObj;
    int i;
    // start the new manager
794
    pNew = Gia_ManStart( 2*Gia_ManObjNum(p) );
795 796 797 798 799 800 801 802
    pNew->pName = Abc_UtilStrsav( p->pName );
    pNew->pSpec = Abc_UtilStrsav( p->pSpec );
    pNew->pMuxes = ABC_CALLOC( unsigned, pNew->nObjsAlloc );
    pNew->vLevels = Vec_IntStart( pNew->nObjsAlloc );
    // create constant and inputs
    Gia_ManFillValue( p );
    Gia_ManConst0(p)->Value = 0;
    Gia_ManForEachCi( p, pObj, i )
803
    {
804
        pObj->Value = Gia_ManAppendCi( pNew );
805 806
        Vec_IntWriteEntry( pNew->vLevels, Abc_Lit2Var(pObj->Value), Gia_ObjLevel(p, pObj) );
    }
807 808
    // create internal nodes
    Gia_ManHashStart( pNew );
809 810 811 812 813 814
    Gia_ManForEachBuf( p, pObj, i )
    {
        Dam_ManMultiAig_rec( pMan, pNew, p, Gia_ObjFanin0(pObj) );
        pObj->Value = Gia_ManAppendBuf( pNew, Gia_ObjFanin0Copy(pObj) );
        Gia_ObjSetGateLevel( pNew, Gia_ManObj(pNew, Abc_Lit2Var(pObj->Value)) );
    }
815 816 817 818 819
    Gia_ManForEachCo( p, pObj, i )
    {
        Dam_ManMultiAig_rec( pMan, pNew, p, Gia_ObjFanin0(pObj) );
        pObj->Value = Gia_ManAppendCo( pNew, Gia_ObjFanin0Copy(pObj) );
    }
Alan Mishchenko committed
820
//    assert( Gia_ManObjNum(pNew) <= Gia_ManObjNum(p) );
821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842
    Gia_ManHashStop( pNew );
    Gia_ManSetRegNum( pNew, Gia_ManRegNum(p) );
    // perform cleanup
    pNew = Gia_ManCleanup( pTemp = pNew );
    Gia_ManStop( pTemp );
    return pNew;
}

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

  Synopsis    [Updates the data-structure after extracting one divisor.]

  Description []
               
  SideEffects []

  SeeAlso     []

***********************************************************************/
void Dam_PrintDiv( Dam_Man_t * p, int iDiv )
{
    if ( iDiv == 0 )
843
        printf( "Final statistics after extracting %6d divisors:          ", p->nDivs );
844 845
    else
    {
846
        char Buffer[100];
847 848
        int iData0 = Hash_IntObjData0(p->vHash, iDiv);
        int iData1 = Hash_IntObjData1(p->vHash, iDiv);
849 850 851 852 853 854 855
        printf( "Div%5d : ",  p->nDivs+1 );
        printf( "D%-8d = ",   iDiv );
        sprintf( Buffer, "%c%d", Abc_LitIsCompl(iData0)? '!':' ', Abc_Lit2Var(iData0) );
        printf( "%8s ",   Buffer );
        printf( "%c  ",     (iData0 < iData1) ? '*' : '+' );
        sprintf( Buffer, "%c%d", Abc_LitIsCompl(iData1)? '!':' ', Abc_Lit2Var(iData1) );
        printf( "%8s   ", Buffer );
856
        printf( "Weight %9.2f  ", Vec_FltEntry(p->vCounts, iDiv) );
857 858
    }
    printf( "Divs =%8d  ",  Hash_IntManEntryNum(p->vHash) );
859
    printf( "Ands =%8d  ",  p->nAnds - p->nGain );
860 861 862 863 864 865 866 867 868 869
    Abc_PrintTime( 1, "Time", Abc_Clock() - p->clkStart );
}
void Dam_PrintQue( Dam_Man_t * p )
{
    int i;
    printf( "Divisor queue: \n" );
    for ( i = 1; i <= Hash_IntManEntryNum(p->vHash); i++ )
    {
        int iLit0 = Hash_IntObjData0(p->vHash, i);
        int iLit1 = Hash_IntObjData1(p->vHash, i);
870 871 872 873 874
        printf( "Div %7d : ",     i );
        printf( "Weight %9.2f  ", Vec_FltEntry(p->vCounts, i) );
        printf( "F = %c%c ",      Abc_LitIsCompl(iLit0) ? '!': ' ', 'a' + Abc_Lit2Var(iLit0)-1 );
        printf( "%c ",            (Hash_IntObjData0(p->vHash, i) < Hash_IntObjData1(p->vHash, i)) ? '*':'+' );
        printf( "%c%c   ",        Abc_LitIsCompl(iLit1) ? '!': ' ', 'a' + Abc_Lit2Var(iLit1)-1 );
875 876 877
        printf( "\n" );
    }
}
878
int Dam_ManUpdateNode( Dam_Man_t * p, int iObj, int iLit0, int iLit1, int iLitNew, Vec_Int_t * vDivs )
879 880
{
    int * pSet = Dam_ObjSet( p, iObj );
881
    int i, k, c, Num, iLit, iLit2, fPres;
882 883 884 885 886 887 888 889 890 891 892 893 894
    // check if literal can be found
    for ( i = 1; i <= pSet[0]; i++ )
        if ( pSet[i] == iLit0 )
            break;
    if ( i > pSet[0] )
        return 0;
    // check if literal can be found
    for ( i = 1; i <= pSet[0]; i++ )
        if ( pSet[i] == iLit1 )
            break;
    if ( i > pSet[0] )
        return 0;
    // compact literals
895
    Vec_IntPush( vDivs, -iObj );
896 897 898 899 900 901
    for ( k = i = 1; i <= pSet[0]; i++ )
    {
        if ( iLit0 == pSet[i] || iLit1 == pSet[i] )
            continue;
        pSet[k++] = iLit = pSet[i];
        // reduce weights of the divisors
902
        fPres = 0;
903 904 905 906 907 908 909 910 911 912
        for ( c = 0; c < 2; c++ )
        {
            iLit2 = c ? iLit1 : iLit0;
            if ( (iLit > iLit2) ^ (iLit0 > iLit1) )
                Num = *Hash_Int2ManLookup( p->vHash, iLit2, iLit );
            else
                Num = *Hash_Int2ManLookup( p->vHash, iLit, iLit2 );
            if ( Num > 0 )
            {
                Vec_FltAddToEntry( p->vCounts, Num, -1 );
913
                if ( Vec_QueIsMember(p->vQue, Num) )
914
                {
915
                    Vec_QueUpdate( p->vQue, Num );
916 917
                    fPres |= (1 << c);
                }
918 919
            }
        }
920 921 922 923 924 925 926 927
        if ( fPres != 3 )
            continue;
        if ( (iLit > iLitNew) ^ (iLit0 > iLit1) )
            Num = Hash_Int2ManInsert( p->vHash, iLitNew, iLit, 0 );
        else
            Num = Hash_Int2ManInsert( p->vHash, iLit, iLitNew, 0 );
        Hash_Int2ObjInc( p->vHash, Num );
        Vec_IntPush( vDivs, Num );
928 929 930 931
        // update reverse level
        if ( Num >= Vec_IntSize(p->vDivLevR) )
            Vec_IntFillExtra( p->vDivLevR, 3 * Vec_IntSize(p->vDivLevR) / 2, 0 );
        Vec_IntUpdateEntry( p->vDivLevR, Num, Vec_IntEntry(p->vNodLevR, iObj) );
932 933 934
    }
    pSet[k] = iLitNew;
    pSet[0] = k;
935
    return 1;
936 937 938
}
void Dam_ManUpdate( Dam_Man_t * p, int iDiv )
{
939
    Vec_Int_t * vDivs = p->pGia->vSuper;
940 941
    int iLit0 = Hash_IntObjData0(p->vHash, iDiv);
    int iLit1 = Hash_IntObjData1(p->vHash, iDiv);
942 943 944
    int i, iLitNew, * pSet, * pNods = Dam_DivSet( p, iDiv );
    int nPresent = 0, nPairsStart, nPairsStop, pPairsNew, nRefs;
    int fThisIsXor = (iLit0 > iLit1), iDivTemp, iNode;
945 946 947 948 949
//    Dam_PrintQue( p );
    if ( fThisIsXor )
        iLitNew = Gia_ManAppendXorReal( p->pGia, iLit0, iLit1 );
    else
        iLitNew = Gia_ManAppendAnd( p->pGia, iLit0, iLit1 );
950 951
    Gia_ObjSetGateLevel( p->pGia, Gia_ManObj(p->pGia, Abc_Lit2Var(iLitNew)) );
//    printf( "%d ", Gia_ObjLevel(p->pGia, Gia_ManObj(p->pGia, Abc_Lit2Var(iLitNew))) );
952 953
    // replace entries
    assert( pNods[0] >= 2 );
954 955
    nPairsStart = Hash_IntManEntryNum(p->vHash) + 1;
    Vec_IntClear( vDivs );
956
    for ( i = 1; i <= pNods[0]; i++ )
957 958 959 960 961 962 963 964 965 966 967
        nPresent += Dam_ManUpdateNode( p, pNods[i], iLit0, iLit1, iLitNew, vDivs );
    nPairsStop = Hash_IntManEntryNum(p->vHash) + 1;
    // extend arrayvs
    pPairsNew = 0;
    Vec_FltFillExtra( p->vCounts, nPairsStop, 0 );
    Vec_IntFillExtra( p->vDiv2Nod, nPairsStop, -1 );
    for ( i = nPairsStart; i < nPairsStop; i++ )
    {
        nRefs = Hash_IntObjData2(p->vHash, i);
        if ( nRefs < 2 )
            continue;
968
        Vec_FltWriteEntry( p->vCounts, i, nRefs + 0.001*Dam_ManDivSlack(p, Hash_IntObjData0(p->vHash, i), Hash_IntObjData1(p->vHash, i), Vec_IntEntry(p->vDivLevR, i)) );
969 970 971 972 973 974 975
        Vec_QuePush( p->vQue, i );
        // remember divisors
        Vec_IntWriteEntry( p->vDiv2Nod, i, Vec_IntSize(p->vNodStore) );
        Vec_IntPush( p->vNodStore, 0 );
        Vec_IntFillExtra( p->vNodStore, Vec_IntSize(p->vNodStore) + nRefs, -1 );
        pPairsNew++;
    }
976
//    printf( "Added %d new pairs\n", pPairsNew );
977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993
    // fill in the divisors
    iNode = -1;
    Vec_IntForEachEntry( vDivs, iDivTemp, i )
    {
        if ( iDivTemp < 0 )
        {
            iNode = -iDivTemp;
            continue;
        }
        if ( Vec_IntEntry(p->vDiv2Nod, iDivTemp) == -1 )
            continue;
        pSet = Dam_DivSet( p, iDivTemp );
        pSet[++pSet[0]] = iNode;
    }
    // make sure divisors are added correctly
    for ( i = nPairsStart; i < nPairsStop; i++ )
        if ( Vec_IntEntry(p->vDiv2Nod, i) > 0 )
994
            assert( Dam_DivSet(p, i)[0] == Hash_IntObjData2(p->vHash, i) );
995 996
    // update costs
    Vec_FltWriteEntry( p->vCounts, iDiv, 0 );
997 998
    p->nGain += (1 + 2 * fThisIsXor) * (nPresent - 1);
    p->nGainX += 3 * fThisIsXor * (nPresent - 1);
999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012
    p->nDivs++;
}

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

  Synopsis    [Perform extraction for multi-input AND/XOR.]

  Description []
               
  SideEffects []

  SeeAlso     []

***********************************************************************/
1013
Gia_Man_t * Dam_ManAreaBalanceInt( Gia_Man_t * pGia, Vec_Int_t * vCiLevels, int nNewNodesMax, int fVerbose, int fVeryVerbose )
1014 1015
{
    Gia_Man_t * pNew;
1016
    Dam_Man_t * p;
1017
    int i, iDiv;
1018
    p = Dam_ManAlloc( pGia );
1019 1020 1021
    p->nLevelMax = Gia_ManSetLevels( p->pGia, vCiLevels );
    p->vNodLevR = Gia_ManReverseLevel( p->pGia );
    Vec_IntFillExtra( p->pGia->vLevels, 3*Gia_ManObjNum(p->pGia)/2, 0 );
1022
    Dam_ManCreatePairs( p, fVerbose );
1023
    for ( i = 0; i < nNewNodesMax && Vec_QueTopPriority(p->vQue) >= 2; i++ )
1024
    {
1025 1026 1027 1028
        iDiv = Vec_QuePop(p->vQue);
        if ( fVeryVerbose )
            Dam_PrintDiv( p, iDiv );
        Dam_ManUpdate( p, iDiv );
1029
    }
1030 1031 1032
    if ( fVeryVerbose )
        Dam_PrintDiv( p, 0 );
    pNew = Dam_ManMultiAig( p );
1033
    if ( fVerbose )
1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044
    {
        int nDivsAll = Hash_IntManEntryNum(p->vHash);
        int nDivsUsed = p->nDivs;
        printf( "Div:  " );
        printf( "  Total =%9d (%6.2f %%) ",   nDivsAll,   100.0 * nDivsAll    / Abc_MaxInt(nDivsAll, 1) );
        printf( "  Used =%9d (%6.2f %%)",     nDivsUsed,  100.0 * nDivsUsed   / Abc_MaxInt(nDivsAll, 1) );
        printf( "  Gain =%6d (%6.2f %%)",     p->nGain,   100.0 * p->nGain / Abc_MaxInt(p->nAnds, 1) );
        printf( "  GainX = %d  ",             p->nGainX  );
        Abc_PrintTime( 1, "Time", Abc_Clock() - p->clkStart );
    }
    Dam_ManFree( p );
1045 1046
    return pNew;
}
1047
Gia_Man_t * Gia_ManAreaBalance( Gia_Man_t * p, int fSimpleAnd, int nNewNodesMax, int fVerbose, int fVeryVerbose )
1048
{
1049
    Gia_Man_t * pNew0, * pNew, * pNew1, * pNew2;
1050
    Vec_Int_t * vCiLevels;
1051 1052 1053 1054 1055 1056 1057 1058 1059
    // set arrival times for the input of the new AIG
    if ( p->vCiArrs )
    {
        int i, Id, And2Delay = p->And2Delay ? p->And2Delay : 1;
        Vec_IntFreeP( &p->vLevels );
        p->vLevels = Vec_IntStart( Gia_ManObjNum(p) );
        Gia_ManForEachCiId( p, Id, i )
            Vec_IntWriteEntry( p->vLevels, Id, Vec_IntEntry(p->vCiArrs, i)/And2Delay );
    }
1060 1061 1062 1063 1064 1065
    else if ( p->vInArrs )
    {
        int i, Id, And2Delay = p->And2Delay ? p->And2Delay : 1;
        Gia_ManForEachCiId( p, Id, i )
            Vec_IntWriteEntry( p->vLevels, Id, (int)(Vec_FltEntry(p->vInArrs, i)/And2Delay) );
    }
1066 1067 1068 1069
    // determine CI levels
    if ( p->pManTime && p->vLevels == NULL )
        Gia_ManLevelWithBoxes( p );
    vCiLevels = Gia_ManGetCiLevels( p );
1070
    // get the starting manager
1071 1072
    pNew0 = Gia_ManHasMapping(p) ? (Gia_Man_t *)Dsm_ManDeriveGia(p, 0) : Gia_ManDup(p);
    Gia_ManTransferTiming( pNew0, p );
1073 1074
    if ( fVerbose )     Gia_ManPrintStats( pNew0, NULL );
    // derive internal manager
Alan Mishchenko committed
1075
    pNew = fSimpleAnd ? Gia_ManDup( pNew0 ) : Gia_ManDupMuxes( pNew0, 2 );
1076
    Gia_ManTransferTiming( pNew, pNew0 );
1077
    if ( fVerbose )     Gia_ManPrintStats( pNew, NULL );
1078 1079
    if ( pNew0 != p ) Gia_ManStop( pNew0 );
    // perform the operation
1080
    pNew1 = Dam_ManAreaBalanceInt( pNew, vCiLevels, nNewNodesMax, fVerbose, fVeryVerbose );
1081
    Gia_ManTransferTiming( pNew1, pNew );
1082 1083
    if ( fVerbose )     Gia_ManPrintStats( pNew1, NULL );
    Gia_ManStop( pNew );
1084
    Vec_IntFreeP( &vCiLevels );
1085
    // derive the final result
Alan Mishchenko committed
1086
    pNew2 = Gia_ManDupNoMuxes( pNew1, 0 );
1087
    Gia_ManTransferTiming( pNew2, pNew1 );
1088 1089
    if ( fVerbose )     Gia_ManPrintStats( pNew2, NULL );
    Gia_ManStop( pNew1 );
1090 1091 1092
    // normalize if needed
    if ( !Gia_ManIsNormalized(pNew2) )
    {
1093
        pNew2 = Gia_ManDupNormalize( pNew1 = pNew2, 0 );
1094
        Gia_ManTransferTiming( pNew2, pNew1 );
1095 1096
        Gia_ManStop( pNew1 );
    }
1097
    //Gia_ManTransferTiming( pNew2, p );
1098 1099 1100
    return pNew2;
}

1101 1102 1103 1104 1105 1106 1107
////////////////////////////////////////////////////////////////////////
///                       END OF FILE                                ///
////////////////////////////////////////////////////////////////////////


ABC_NAMESPACE_IMPL_END