acecFadds.c 45.4 KB
Newer Older
1 2
/**CFile****************************************************************

3
  FileName    [acecFadds.c]
4 5 6

  SystemName  [ABC: Logic synthesis and verification system.]

7
  PackageName [CEC for arithmetic circuits.]
8

9
  Synopsis    [Detecting half-adders and full-adders.]
10 11 12 13 14 15 16

  Author      [Alan Mishchenko]
  
  Affiliation [UC Berkeley]

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

17
  Revision    [$Id: acecFadds.c,v 1.00 2005/06/20 00:00:00 alanmi Exp $]
18 19 20

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

21
#include "acecInt.h"
22 23
#include "misc/vec/vecWec.h"
#include "misc/tim/tim.h"
24 25 26 27 28 29 30 31

ABC_NAMESPACE_IMPL_START


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

32 33 34
#define Dtc_ForEachCut( pList, pCut, i ) for ( i = 0, pCut = pList + 1; i < pList[0]; i++, pCut += pCut[0] + 1 )
#define Dtc_ForEachFadd( vFadds, i )     for ( i = 0; i < Vec_IntSize(vFadds)/5; i++ )

35 36 37 38
////////////////////////////////////////////////////////////////////////
///                     FUNCTION DEFINITIONS                         ///
////////////////////////////////////////////////////////////////////////

39 40
/**Function*************************************************************

41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
  Synopsis    [Detecting HADDs in the AIG.]

  Description []
               
  SideEffects []

  SeeAlso     []

***********************************************************************/
Vec_Int_t * Gia_ManDetectHalfAdders( Gia_Man_t * p, int fVerbose )
{
    Vec_Int_t * vHadds = Vec_IntAlloc( 1000 );
    Gia_Obj_t * pObj, * pFan0, * pFan1; 
    int i, iLit, iFan0, iFan1, fComplDiff, Count, Counts[5] = {0};
    Gia_ManHashStart( p );
56
    if ( p->nXors )
57
    {
58
        Gia_ManForEachAnd( p, pObj, i )
59
        {
60 61
            if ( !Gia_ObjIsXor(pObj) )
                continue;
62
            Count = 0;
63 64
            iFan0 = Gia_ObjFaninId0(pObj, i);
            iFan1 = Gia_ObjFaninId1(pObj, i);
65 66 67 68 69 70 71 72
            if ( (iLit = Gia_ManHashLookupInt(p, Abc_Var2Lit(iFan0, 0), Abc_Var2Lit(iFan1, 0))) )
                Vec_IntPushTwo( vHadds, i, Abc_Lit2Var(iLit) ), Count++;
            if ( (iLit = Gia_ManHashLookupInt(p, Abc_Var2Lit(iFan0, 1), Abc_Var2Lit(iFan1, 1))) )
                Vec_IntPushTwo( vHadds, i, Abc_Lit2Var(iLit) ), Count++;
            if ( (iLit = Gia_ManHashLookupInt(p, Abc_Var2Lit(iFan0, 0), Abc_Var2Lit(iFan1, 1))) )
                Vec_IntPushTwo( vHadds, i, Abc_Lit2Var(iLit) ), Count++;
            if ( (iLit = Gia_ManHashLookupInt(p, Abc_Var2Lit(iFan0, 1), Abc_Var2Lit(iFan1, 0))) )
                Vec_IntPushTwo( vHadds, i, Abc_Lit2Var(iLit) ), Count++;
73
            Counts[Count]++;
74
        }
75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109
    }
    else
    {
        ABC_FREE( p->pRefs );
        Gia_ManCreateRefs( p );
        Gia_ManForEachAnd( p, pObj, i )
        {
            if ( !Gia_ObjRecognizeExor(pObj, &pFan0, &pFan1) )
                continue;
            Count = 0;
            if ( Gia_ObjRefNumId(p, Gia_ObjFaninId0(pObj, i)) > 1 )
                Vec_IntPushTwo( vHadds, i, Gia_ObjFaninId0(pObj, i) ), Count++;
            if ( Gia_ObjRefNumId(p, Gia_ObjFaninId1(pObj, i)) > 1 )
                Vec_IntPushTwo( vHadds, i, Gia_ObjFaninId1(pObj, i) ), Count++;
            iFan0 = Gia_ObjId( p, pFan0 );
            iFan1 = Gia_ObjId( p, pFan1 );
            fComplDiff =          (Gia_ObjFaninC0(Gia_ObjFanin0(pObj)) ^ Gia_ObjFaninC1(Gia_ObjFanin0(pObj)));
            assert( fComplDiff == (Gia_ObjFaninC0(Gia_ObjFanin1(pObj)) ^ Gia_ObjFaninC1(Gia_ObjFanin1(pObj))) );
            if ( fComplDiff )
            {
                if ( (iLit = Gia_ManHashLookupInt(p, Abc_Var2Lit(iFan0, 0), Abc_Var2Lit(iFan1, 0))) )
                    Vec_IntPushTwo( vHadds, i, Abc_Lit2Var(iLit) ), Count++;
                if ( (iLit = Gia_ManHashLookupInt(p, Abc_Var2Lit(iFan0, 1), Abc_Var2Lit(iFan1, 1))) )
                    Vec_IntPushTwo( vHadds, i, Abc_Lit2Var(iLit) ), Count++;
            }
            else
            {
                if ( (iLit = Gia_ManHashLookupInt(p, Abc_Var2Lit(iFan0, 0), Abc_Var2Lit(iFan1, 1))) )
                    Vec_IntPushTwo( vHadds, i, Abc_Lit2Var(iLit) ), Count++;
                if ( (iLit = Gia_ManHashLookupInt(p, Abc_Var2Lit(iFan0, 1), Abc_Var2Lit(iFan1, 0))) )
                    Vec_IntPushTwo( vHadds, i, Abc_Lit2Var(iLit) ), Count++;
            }
            Counts[Count]++;
        }
        ABC_FREE( p->pRefs );
110 111 112 113 114 115 116 117 118 119 120
    }
    Gia_ManHashStop( p );
    if ( fVerbose )
    {
        int iXor, iAnd;
        printf( "Found %d half-adders with XOR gates: ", Vec_IntSize(vHadds)/2 );
        for ( i = 0; i <= 4; i++ )
            printf( "%d=%d ", i, Counts[i] );
        printf( "\n" );

        Vec_IntForEachEntryDouble( vHadds, iXor, iAnd, i )
121 122 123 124
        {
            pObj = Gia_ManObj( p, iXor );
            printf( "%3d : %5d %5d -> %5d %5d\n", i, Gia_ObjFaninId0(pObj, iXor), Gia_ObjFaninId1(pObj, iXor), iXor, iAnd );
        }
125 126 127 128 129 130
    }
    return vHadds;
}

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

131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148
  Synopsis    [Derive GIA with boxes containing adder-chains.]

  Description []
               
  SideEffects []

  SeeAlso     []

***********************************************************************/
void Gia_ManIllustrateBoxes( Gia_Man_t * p )
{
    Tim_Man_t * pManTime = (Tim_Man_t *)p->pManTime;
    int nBoxes = Tim_ManBoxNum( pManTime );
    int i, k, curCi, curCo, nBoxIns, nBoxOuts;
    Gia_Obj_t * pObj;
    // walk through the boxes
    curCi = Tim_ManPiNum(pManTime);
    curCo = 0;
149
    for ( i = 0; i < nBoxes; i++ )
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
    {
        nBoxIns = Tim_ManBoxInputNum(pManTime, i);
        nBoxOuts = Tim_ManBoxOutputNum(pManTime, i);
        printf( "Box %4d  [%d x %d] :   ", i, nBoxIns, nBoxOuts );
        printf( "Input obj IDs = " );
        for ( k = 0; k < nBoxIns; k++ )
        {
            pObj = Gia_ManCo( p, curCo + k );
            printf( "%d ", Gia_ObjId(p, pObj) );
        }
        printf( "  Output obj IDs = " );
        for ( k = 0; k < nBoxOuts; k++ )
        {
            pObj = Gia_ManCi( p, curCi + k );
            printf( "%d ", Gia_ObjId(p, pObj) );
        }
        curCo += nBoxIns;
        curCi += nBoxOuts;
        printf( "\n" );
    }
    curCo += Tim_ManPoNum(pManTime);
    // verify counts
    assert( curCi == Gia_ManCiNum(p) );
    assert( curCo == Gia_ManCoNum(p) );
}
175 176 177

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

178
  Synopsis    [Detecting FADDs in the AIG.]
179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238

  Description []
               
  SideEffects []

  SeeAlso     []

***********************************************************************/
int Dtc_ManCutMergeOne( int * pCut0, int * pCut1, int * pCut )
{
    int i, k;
    for ( k = 0; k <= pCut1[0]; k++ )
        pCut[k] = pCut1[k];
    for ( i = 1; i <= pCut0[0]; i++ )
    {
        for ( k = 1; k <= pCut1[0]; k++ )
            if ( pCut0[i] == pCut1[k] )
                break;
        if ( k <= pCut1[0] )
            continue;
        if ( pCut[0] == 3 )
            return 0;
        pCut[1+pCut[0]++] = pCut0[i];
    }
    assert( pCut[0] == 2 || pCut[0] == 3 );
    if ( pCut[1] > pCut[2] )
        ABC_SWAP( int, pCut[1], pCut[2] );
    assert( pCut[1] < pCut[2] );
    if ( pCut[0] == 2 )
        return 1;
    if ( pCut[2] > pCut[3] )
        ABC_SWAP( int, pCut[2], pCut[3] );
    if ( pCut[1] > pCut[2] )
        ABC_SWAP( int, pCut[1], pCut[2] );
    assert( pCut[1] < pCut[2] );
    assert( pCut[2] < pCut[3] );
    return 1;
}
int Dtc_ManCutCheckEqual( Vec_Int_t * vCuts, int * pCutNew )
{
    int * pList = Vec_IntArray( vCuts );
    int i, k, * pCut;
    Dtc_ForEachCut( pList, pCut, i )
    {
        for ( k = 0; k <= pCut[0]; k++ )
            if ( pCut[k] != pCutNew[k] )
                break;
        if ( k > pCut[0] )
            return 1;
    }
    return 0;
}
int Dtc_ObjComputeTruth_rec( Gia_Obj_t * pObj )
{
    int Truth0, Truth1;
    if ( pObj->Value )
        return pObj->Value;
    assert( Gia_ObjIsAnd(pObj) );
    Truth0 = Dtc_ObjComputeTruth_rec( Gia_ObjFanin0(pObj) );
    Truth1 = Dtc_ObjComputeTruth_rec( Gia_ObjFanin1(pObj) );
239 240 241 242
    if ( Gia_ObjIsXor(pObj) )
        return (pObj->Value = (Gia_ObjFaninC0(pObj) ? ~Truth0 : Truth0) ^ (Gia_ObjFaninC1(pObj) ? ~Truth1 : Truth1));
    else
        return (pObj->Value = (Gia_ObjFaninC0(pObj) ? ~Truth0 : Truth0) & (Gia_ObjFaninC1(pObj) ? ~Truth1 : Truth1));
243 244 245 246 247 248 249 250 251 252 253
}
void Dtc_ObjCleanTruth_rec( Gia_Obj_t * pObj )
{
    if ( !pObj->Value )
        return;
    pObj->Value = 0;
    if ( !Gia_ObjIsAnd(pObj) )
        return;
    Dtc_ObjCleanTruth_rec( Gia_ObjFanin0(pObj) );
    Dtc_ObjCleanTruth_rec( Gia_ObjFanin1(pObj) );
}
254
int Dtc_ObjComputeTruth( Gia_Man_t * p, int iObj, int * pCut, int * pTruth )
255 256 257 258 259 260
{
    unsigned Truth, Truths[3] = { 0xAA, 0xCC, 0xF0 }; int i;
    for ( i = 1; i <= pCut[0]; i++ )
        Gia_ManObj(p, pCut[i])->Value = Truths[i-1];
    Truth = 0xFF & Dtc_ObjComputeTruth_rec( Gia_ManObj(p, iObj) );
    Dtc_ObjCleanTruth_rec( Gia_ManObj(p, iObj) );
261 262
    if ( pTruth ) 
        *pTruth = Truth;
263 264
    if ( Truth == 0x66 || Truth == 0x99 )
        return 3;
265
    if ( Truth == 0x96 || Truth == 0x69 )
266
        return 1;
267 268
    if ( Truth == 0xE8 || Truth == 0xD4 || Truth == 0xB2 || Truth == 0x71 ||
         Truth == 0x17 || Truth == 0x2B || Truth == 0x4D || Truth == 0x8E )
269 270 271
        return 2;
    return 0;
}
272
void Dtc_ManCutMerge( Gia_Man_t * p, int iObj, int * pList0, int * pList1, Vec_Int_t * vCuts, Vec_Int_t * vCutsXor2, Vec_Int_t * vCutsXor, Vec_Int_t * vCutsMaj )
273
{
274
    int fVerbose = 0;
275 276
    Vec_Int_t * vTemp;
    int i, k, c, Type, * pCut0, * pCut1, pCut[4];
277 278
    if ( fVerbose )
        printf( "Object %d = :\n", iObj );
279 280 281 282 283 284 285 286 287 288
    Vec_IntFill( vCuts, 2, 1 );
    Vec_IntPush( vCuts, iObj );
    Dtc_ForEachCut( pList0, pCut0, i )
    Dtc_ForEachCut( pList1, pCut1, k )
    {
        if ( !Dtc_ManCutMergeOne(pCut0, pCut1, pCut) )
            continue;
        if ( Dtc_ManCutCheckEqual(vCuts, pCut) )
            continue;
        Vec_IntAddToEntry( vCuts, 0, 1 );  
289 290
        if ( fVerbose )
            printf( "%d : ", pCut[0] );
291
        for ( c = 0; c <= pCut[0]; c++ )
292
        {
293
            Vec_IntPush( vCuts, pCut[c] );
294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310
            if ( fVerbose && c )
                printf( "%d ", pCut[c] );
        }
        if ( fVerbose )
            printf( "\n" );
        if ( pCut[0] == 2 )
        {
            int Value = Dtc_ObjComputeTruth( p, iObj, pCut, NULL );
            assert( Value == 3 || Value == 0 );
            if ( Value == 3 )
            {
                Vec_IntPush( vCutsXor2, pCut[1] );
                Vec_IntPush( vCutsXor2, pCut[2] );
                Vec_IntPush( vCutsXor2, iObj );
            }
            continue;
        }
311 312
        if ( pCut[0] != 3 )
            continue;
313
        Type = Dtc_ObjComputeTruth( p, iObj, pCut, NULL );
314 315 316
        if ( Type == 0 )
            continue;
        vTemp = Type == 1 ? vCutsXor : vCutsMaj;
317 318
        if ( fVerbose )
            printf( "%d = %s(", iObj, Type == 1 ? "XOR" : "MAJ" );
319
        for ( c = 1; c <= pCut[0]; c++ )
320 321 322
        {
            if ( fVerbose )
                printf( " %d", pCut[c] );
323
            Vec_IntPush( vTemp, pCut[c] );
324 325 326
        }
        if ( fVerbose )
            printf( " )\n" );
327 328 329
        Vec_IntPush( vTemp, iObj );
    }
}
330
void Dtc_ManComputeCuts( Gia_Man_t * p, Vec_Int_t ** pvCutsXor2, Vec_Int_t ** pvCutsXor, Vec_Int_t ** pvCutsMaj, int fVerbose )
331 332 333 334
{
    Gia_Obj_t * pObj; 
    int * pList0, * pList1, i, nCuts = 0;
    Vec_Int_t * vTemp = Vec_IntAlloc( 1000 );
335
    Vec_Int_t * vCutsXor2 = Vec_IntAlloc( Gia_ManAndNum(p) );
336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351
    Vec_Int_t * vCutsXor = Vec_IntAlloc( Gia_ManAndNum(p) );
    Vec_Int_t * vCutsMaj = Vec_IntAlloc( Gia_ManAndNum(p) );
    Vec_Int_t * vCuts = Vec_IntAlloc( 30 * Gia_ManAndNum(p) );
    Vec_IntFill( vCuts, Gia_ManObjNum(p), 0 );
    Gia_ManCleanValue( p );
    Gia_ManForEachCi( p, pObj, i )
    {
        Vec_IntWriteEntry( vCuts, Gia_ObjId(p, pObj), Vec_IntSize(vCuts) );
        Vec_IntPush( vCuts, 1 );
        Vec_IntPush( vCuts, 1 );
        Vec_IntPush( vCuts, Gia_ObjId(p, pObj) );
    }
    Gia_ManForEachAnd( p, pObj, i )
    {
        pList0 = Vec_IntEntryP( vCuts, Vec_IntEntry(vCuts, Gia_ObjFaninId0(pObj, i)) );
        pList1 = Vec_IntEntryP( vCuts, Vec_IntEntry(vCuts, Gia_ObjFaninId1(pObj, i)) );
352
        Dtc_ManCutMerge( p, i, pList0, pList1, vTemp, vCutsXor2, vCutsXor, vCutsMaj );
353 354
        Vec_IntWriteEntry( vCuts, i, Vec_IntSize(vCuts) );
        Vec_IntAppend( vCuts, vTemp );
355
        nCuts += Vec_IntEntry( vTemp, 0 );
356
    }
357 358 359
    if ( fVerbose )
        printf( "Nodes = %d.  Cuts = %d.  Cuts/Node = %.2f.  Ints/Node = %.2f.\n", 
            Gia_ManAndNum(p), nCuts, 1.0*nCuts/Gia_ManAndNum(p), 1.0*Vec_IntSize(vCuts)/Gia_ManAndNum(p) );
360 361
    Vec_IntFree( vTemp );
    Vec_IntFree( vCuts );
362 363 364 365
    if ( pvCutsXor2 )
        *pvCutsXor2 = vCutsXor2;
    else
        Vec_IntFree( vCutsXor2 );
366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395
    *pvCutsXor = vCutsXor;
    *pvCutsMaj = vCutsMaj;
}
Vec_Int_t * Dtc_ManFindCommonCuts( Gia_Man_t * p, Vec_Int_t * vCutsXor, Vec_Int_t * vCutsMaj )
{
    int * pCuts0 = Vec_IntArray(vCutsXor);
    int * pCuts1 = Vec_IntArray(vCutsMaj);
    int * pLimit0 = Vec_IntLimit(vCutsXor);
    int * pLimit1 = Vec_IntLimit(vCutsMaj);   int i;
    Vec_Int_t * vFadds = Vec_IntAlloc( 1000 );
    assert( Vec_IntSize(vCutsXor) % 4 == 0 );
    assert( Vec_IntSize(vCutsMaj) % 4 == 0 );
    while ( pCuts0 < pLimit0 && pCuts1 < pLimit1 )
    {
        for ( i = 0; i < 3; i++ )
            if ( pCuts0[i] != pCuts1[i] )
                break;
        if ( i == 3 )
        {
            for ( i = 0; i < 4; i++ )
                Vec_IntPush( vFadds, pCuts0[i] );
            Vec_IntPush( vFadds, pCuts1[3] );
            pCuts0 += 4;
            pCuts1 += 4;
        }
        else if ( pCuts0[i] < pCuts1[i] )
            pCuts0 += 4;
        else if ( pCuts0[i] > pCuts1[i] )
            pCuts1 += 4;
    }
396
    assert( Vec_IntSize(vFadds) % 5 == 0 );
397 398 399 400
    return vFadds;
}
void Dtc_ManPrintFadds( Vec_Int_t * vFadds )
{
401 402
    int i;
    Dtc_ForEachFadd( vFadds, i )
403 404 405 406 407 408 409 410 411
    {
        printf( "%6d : ", i );
        printf( "%6d ", Vec_IntEntry(vFadds, 5*i+0) );
        printf( "%6d ", Vec_IntEntry(vFadds, 5*i+1) );
        printf( "%6d ", Vec_IntEntry(vFadds, 5*i+2) );
        printf( " ->  " );
        printf( "%6d ", Vec_IntEntry(vFadds, 5*i+3) );
        printf( "%6d ", Vec_IntEntry(vFadds, 5*i+4) );
        printf( "\n" );
412 413 414 415 416 417

        if ( i == 100 )
        {
            printf( "Skipping other FADDs.\n" );
            break;
        }
418 419
    }
}
420
int Dtc_ManCompare( int * pCut0, int * pCut1 )
421
{
422 423 424 425 426 427 428 429 430 431 432 433 434 435 436
    if ( pCut0[0] < pCut1[0] ) return -1;
    if ( pCut0[0] > pCut1[0] ) return  1;
    if ( pCut0[1] < pCut1[1] ) return -1;
    if ( pCut0[1] > pCut1[1] ) return  1;
    if ( pCut0[2] < pCut1[2] ) return -1;
    if ( pCut0[2] > pCut1[2] ) return  1;
    return 0;
}
int Dtc_ManCompare2( int * pCut0, int * pCut1 )
{
    if ( pCut0[4] < pCut1[4] ) return -1;
    if ( pCut0[4] > pCut1[4] ) return  1;
    return 0;
}
// returns array of 5-tuples containing inputs/sum/cout of each full adder
437
Vec_Int_t * Gia_ManDetectFullAdders( Gia_Man_t * p, int fVerbose, Vec_Int_t ** pvCutsXor2 )
438 439
{
    Vec_Int_t * vCutsXor, * vCutsMaj, * vFadds;
440
    Dtc_ManComputeCuts( p, pvCutsXor2, &vCutsXor, &vCutsMaj, fVerbose );
441 442 443 444 445
    qsort( Vec_IntArray(vCutsXor), Vec_IntSize(vCutsXor)/4, 16, (int (*)(const void *, const void *))Dtc_ManCompare );
    qsort( Vec_IntArray(vCutsMaj), Vec_IntSize(vCutsMaj)/4, 16, (int (*)(const void *, const void *))Dtc_ManCompare );
    vFadds = Dtc_ManFindCommonCuts( p, vCutsXor, vCutsMaj );
    qsort( Vec_IntArray(vFadds), Vec_IntSize(vFadds)/5, 20, (int (*)(const void *, const void *))Dtc_ManCompare2 );
    if ( fVerbose )
446
        printf( "XOR3 cuts = %d.  MAJ cuts = %d.  Full-adders = %d.\n", Vec_IntSize(vCutsXor)/4, Vec_IntSize(vCutsMaj)/4, Vec_IntSize(vFadds)/5 );
447 448
    if ( fVerbose )
        Dtc_ManPrintFadds( vFadds );
449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469
    Vec_IntFree( vCutsXor );
    Vec_IntFree( vCutsMaj );
    return vFadds;
}

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

  Synopsis    [Map each MAJ into the topmost MAJ of its chain.]

  Description []
               
  SideEffects []

  SeeAlso     []

***********************************************************************/
// maps MAJ nodes into FADD indexes
Vec_Int_t * Gia_ManCreateMap( Gia_Man_t * p, Vec_Int_t * vFadds )
{
    Vec_Int_t * vMap = Vec_IntStartFull( Gia_ManObjNum(p) );  int i;
    Dtc_ForEachFadd( vFadds, i )
470
        Vec_IntWriteEntry( vMap, Vec_IntEntry(vFadds, 5*i+4), i );
471 472 473 474 475 476 477 478 479
    return vMap;
}
// find chain length (for each MAJ, how many FADDs are rooted in its first input)
int Gia_ManFindChains_rec( Gia_Man_t * p, int iMaj, Vec_Int_t * vFadds, Vec_Int_t * vMap, Vec_Int_t * vLength )
{
    assert( Vec_IntEntry(vMap, iMaj) >= 0 ); // MAJ
    if ( Vec_IntEntry(vLength, iMaj) >= 0 )
        return Vec_IntEntry(vLength, iMaj);
    assert( Gia_ObjIsAnd(Gia_ManObj(p, iMaj)) );
480
    {
481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595
        int iFadd = Vec_IntEntry( vMap, iMaj );
        int iXor0 = Vec_IntEntry( vFadds, 5*iFadd+0 );
        int iXor1 = Vec_IntEntry( vFadds, 5*iFadd+1 );
        int iXor2 = Vec_IntEntry( vFadds, 5*iFadd+2 );
        int iLen0 = Vec_IntEntry( vMap, iXor0 ) == -1 ? 0 : Gia_ManFindChains_rec( p, iXor0, vFadds, vMap, vLength );
        int iLen1 = Vec_IntEntry( vMap, iXor1 ) == -1 ? 0 : Gia_ManFindChains_rec( p, iXor1, vFadds, vMap, vLength );
        int iLen2 = Vec_IntEntry( vMap, iXor2 ) == -1 ? 0 : Gia_ManFindChains_rec( p, iXor2, vFadds, vMap, vLength );
        int iLen = Abc_MaxInt( iLen0, Abc_MaxInt(iLen1, iLen2) );
        if ( iLen0 < iLen )
        {
            if ( iLen == iLen1 )
            {
                ABC_SWAP( int, Vec_IntArray(vFadds)[5*iFadd+0], Vec_IntArray(vFadds)[5*iFadd+1] );
            }
            else if ( iLen == iLen2 )
            {
                ABC_SWAP( int, Vec_IntArray(vFadds)[5*iFadd+0], Vec_IntArray(vFadds)[5*iFadd+2] );
            }
        }
        Vec_IntWriteEntry( vLength, iMaj, iLen + 1 );
        return iLen + 1;
    }
}
// for each FADD find the longest chain and reorder its inputs
void Gia_ManFindChains( Gia_Man_t * p, Vec_Int_t * vFadds, Vec_Int_t * vMap )
{
    int i;
    // for each FADD find the longest chain rooted in it
    Vec_Int_t * vLength = Vec_IntStartFull( Gia_ManObjNum(p) );
    Dtc_ForEachFadd( vFadds, i )
        Gia_ManFindChains_rec( p, Vec_IntEntry(vFadds, 5*i+4), vFadds, vMap, vLength );
    Vec_IntFree( vLength );
}
// collect one carry-chain
void Gia_ManCollectOneChain( Gia_Man_t * p, Vec_Int_t * vFadds, int iFaddTop, Vec_Int_t * vMap, Vec_Int_t * vChain )
{
    int iFadd;
    Vec_IntClear( vChain );
    for ( iFadd = iFaddTop; iFadd >= 0 && 
          !Gia_ObjIsTravIdCurrentId(p, Vec_IntEntry(vFadds, 5*iFadd+3)) && 
          !Gia_ObjIsTravIdCurrentId(p, Vec_IntEntry(vFadds, 5*iFadd+4)); 
          iFadd = Vec_IntEntry(vMap, Vec_IntEntry(vFadds, 5*iFadd+0)) )
          {
                Vec_IntPush( vChain, iFadd );
          }
    Vec_IntReverseOrder( vChain );
}
void Gia_ManMarkWithTravId_rec( Gia_Man_t * p, int Id )
{
    Gia_Obj_t * pObj;
    if ( Gia_ObjIsTravIdCurrentId(p, Id) )
        return;
    Gia_ObjSetTravIdCurrentId(p, Id);
    pObj = Gia_ManObj( p, Id );
    if ( Gia_ObjIsAnd(pObj) )
        Gia_ManMarkWithTravId_rec( p, Gia_ObjFaninId0(pObj, Id) );
    if ( Gia_ObjIsAnd(pObj) )
        Gia_ManMarkWithTravId_rec( p, Gia_ObjFaninId1(pObj, Id) );
}
// returns mapping of each MAJ into the topmost elements of its chain
Vec_Wec_t * Gia_ManCollectTopmost( Gia_Man_t * p, Vec_Int_t * vFadds, Vec_Int_t * vMap, int nFaddMin )
{
    int i, j, iFadd;
    Vec_Int_t * vChain  = Vec_IntAlloc( 100 );
    Vec_Wec_t * vChains = Vec_WecAlloc( Vec_IntSize(vFadds)/5 );
    // erase elements appearing as FADD inputs
    Vec_Bit_t * vMarksTop = Vec_BitStart( Vec_IntSize(vFadds)/5 );
    Dtc_ForEachFadd( vFadds, i )
        if ( (iFadd = Vec_IntEntry(vMap, Vec_IntEntry(vFadds, 5*i+0))) >= 0 )
            Vec_BitWriteEntry( vMarksTop, iFadd, 1 );
    // compress the remaining ones
    Gia_ManIncrementTravId( p );
    Dtc_ForEachFadd( vFadds, i )
    {
        if ( Vec_BitEntry(vMarksTop, i) )
            continue;
        Gia_ManCollectOneChain( p, vFadds, i, vMap, vChain );
        if ( Vec_IntSize(vChain) < nFaddMin )
            continue;
        Vec_IntAppend( Vec_WecPushLevel(vChains), vChain );
        Vec_IntForEachEntry( vChain, iFadd, j )
        {
            assert( !Gia_ObjIsTravIdCurrentId(p, Vec_IntEntry(vFadds, 5*iFadd+3)) );
            assert( !Gia_ObjIsTravIdCurrentId(p, Vec_IntEntry(vFadds, 5*iFadd+4)) );
            Gia_ManMarkWithTravId_rec( p, Vec_IntEntry(vFadds, 5*iFadd+3) );
            Gia_ManMarkWithTravId_rec( p, Vec_IntEntry(vFadds, 5*iFadd+4) );
        }
    }
    // cleanup
    Vec_BitFree( vMarksTop );
    Vec_IntFree( vChain );
    return vChains;
}
// prints chains beginning in majority nodes contained in vTops
void Gia_ManPrintChains( Gia_Man_t * p, Vec_Int_t * vFadds, Vec_Int_t * vMap, Vec_Wec_t * vChains )
{
    Vec_Int_t * vChain;
    int i, k, iFadd, Count = 0;
    Vec_WecForEachLevel( vChains, vChain, i )
    {
        Count += Vec_IntSize(vChain);
        if ( i < 10 )
        {
            printf( "Chain %4d : %4d    ", i, Vec_IntSize(vChain) );
            Vec_IntForEachEntry( vChain, iFadd, k )
            {
                printf( "%d(%d) ", iFadd, Vec_IntEntry(vFadds, 5*iFadd+4) );
                if ( k != Vec_IntSize(vChain) - 1 )
                    printf( "-> " );
                if ( k > 6 )
                {
                    printf( "..." );
                    break;
                }
            }
596
            printf( "\n" );
597 598 599 600
        }
        else if ( i == 10 )
            printf( "...\n" );

601
    }
602 603 604 605 606 607
    printf( "Total chains = %d. Total full-adders = %d.\n", Vec_WecSize(vChains), Count );
}
// map SUM bits and topmost MAJ into topmost FADD number
Vec_Int_t * Gia_ManFindMapping( Gia_Man_t * p, Vec_Int_t * vFadds, Vec_Int_t * vMap, Vec_Wec_t * vChains )
{
    Vec_Int_t * vChain;
608
    int i, k, iFadd = -1;
609 610 611
    Vec_Int_t * vMap2Chain = Vec_IntStartFull( Gia_ManObjNum(p) );
    Vec_WecForEachLevel( vChains, vChain, i )
    {
612
        assert( Vec_IntSize(vChain) > 0 );
613 614 615 616 617 618 619 620 621 622 623
        Vec_IntForEachEntry( vChain, iFadd, k )
        {
            //printf( "Chain %d: setting SUM %d (obj %d)\n", i, k, Vec_IntEntry(vFadds, 5*iFadd+3) );
            assert( Vec_IntEntry(vMap2Chain, Vec_IntEntry(vFadds, 5*iFadd+3)) == -1 );
            Vec_IntWriteEntry( vMap2Chain, Vec_IntEntry(vFadds, 5*iFadd+3), i );
        }
        //printf( "Chain %d: setting CARRY (obj %d)\n", i, Vec_IntEntry(vFadds, 5*iFadd+4) );
        assert( Vec_IntEntry(vMap2Chain, Vec_IntEntry(vFadds, 5*iFadd+4)) == -1 );
        Vec_IntWriteEntry( vMap2Chain, Vec_IntEntry(vFadds, 5*iFadd+4), i );
    }
    return vMap2Chain;
624 625 626 627
}

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

628
  Synopsis    [Derive GIA with boxes containing adder-chains.]
629 630 631 632 633 634 635 636

  Description []
               
  SideEffects []

  SeeAlso     []

***********************************************************************/
637
Vec_Int_t * Gia_ManCollectTruthTables( Gia_Man_t * p, Vec_Int_t * vFadds )
638
{
639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678
    int i, k, Type, Truth, pCut[4] = {3};
    Vec_Int_t * vTruths = Vec_IntAlloc( 2*Vec_IntSize(vFadds)/5 );
    Gia_ManCleanValue( p );
    Dtc_ForEachFadd( vFadds, i )
    {
        for ( k = 0; k < 3; k++ )
            pCut[k+1] = Vec_IntEntry( vFadds, 5*i+k );
        Type = Dtc_ObjComputeTruth( p, Vec_IntEntry(vFadds, 5*i+3), pCut, &Truth );
        assert( Type == 1 );
        Vec_IntPush( vTruths, Truth );
        Type = Dtc_ObjComputeTruth( p, Vec_IntEntry(vFadds, 5*i+4), pCut, &Truth );
        assert( Type == 2 );
        Vec_IntPush( vTruths, Truth );
    }
    return vTruths;
}
float * Gia_ManGenerateDelayTableFloat( int nIns, int nOuts )
{
    int i, Total = nIns * nOuts;
    float * pDelayTable = ABC_ALLOC( float, Total + 3 );
    pDelayTable[0] = 0;
    pDelayTable[1] = nIns;
    pDelayTable[2] = nOuts;
    for ( i = 0; i < Total; i++ )
        pDelayTable[i+3] = 1;
    pDelayTable[i+3 - nIns] = -ABC_INFINITY;
    return pDelayTable;
}
Tim_Man_t * Gia_ManGenerateTim( int nPis, int nPos, int nBoxes, int nIns, int nOuts )
{
    Tim_Man_t * pMan;
    int i, curPi, curPo;
    Vec_Ptr_t * vDelayTables = Vec_PtrAlloc( 1 );
    Vec_PtrPush( vDelayTables, Gia_ManGenerateDelayTableFloat(nIns, nOuts) );
    pMan = Tim_ManStart( nPis + nOuts * nBoxes, nPos + nIns * nBoxes );
    Tim_ManSetDelayTables( pMan, vDelayTables );
    curPi = nPis;
    curPo = 0;
    for ( i = 0; i < nBoxes; i++ )
    {
679
        Tim_ManCreateBox( pMan, curPo, nIns, curPi, nOuts, 0, 0 );
680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705
        curPi += nOuts;
        curPo += nIns;
    }
    curPo += nPos;
    assert( curPi == Tim_ManCiNum(pMan) );
    assert( curPo == Tim_ManCoNum(pMan) );
    //Tim_ManPrint( pMan );
    return pMan;
}
Gia_Man_t * Gia_ManGenerateExtraAig( int nBoxes, int nIns, int nOuts )
{
    Gia_Man_t * pNew = Gia_ManStart( nBoxes * 20 );
    int i, k, pInLits[16], pOutLits[16];
    assert( nIns < 16 && nOuts < 16 );
    for ( i = 0; i < nIns; i++ )
        pInLits[i] = Gia_ManAppendCi( pNew );
    pOutLits[0] = Gia_ManAppendXor( pNew, Gia_ManAppendXor(pNew, pInLits[0], pInLits[1]), pInLits[2] );
    pOutLits[1] = Gia_ManAppendMaj( pNew, pInLits[0], pInLits[1], pInLits[2] );
    for ( i = 0; i < nBoxes; i++ )
        for ( k = 0; k < nOuts; k++ )
            Gia_ManAppendCo( pNew, pOutLits[k] );
    return pNew;
}
void Gia_ManDupFadd( Gia_Man_t * pNew, Gia_Man_t * p, Vec_Int_t * vChain, Vec_Int_t * vFadds, Vec_Int_t * vMap, Vec_Wec_t * vChains, Vec_Int_t * vMap2Chain, Vec_Int_t * vTruths )
{
    extern void Gia_ManDupWithFaddBoxes_rec( Gia_Man_t * pNew, Gia_Man_t * p, Gia_Obj_t * pObj, Vec_Int_t * vFadds, Vec_Int_t * vMap, Vec_Wec_t * vChains, Vec_Int_t * vMap2Chain, Vec_Int_t * vTruths );
706
    int i, k, iFadd = -1, iCiLit, pLits[3];
707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 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
    Gia_Obj_t * pObj;
    // construct FADD inputs
    Vec_IntForEachEntry( vChain, iFadd, i )
        for ( k = 0; k < 3; k++ )
        {
            if ( i && !k ) continue;
            pObj = Gia_ManObj( p, Vec_IntEntry(vFadds, 5*iFadd+k) );
            Gia_ManDupWithFaddBoxes_rec( pNew, p, pObj, vFadds, vMap, vChains, vMap2Chain, vTruths );
        }
    // construct boxes
    iCiLit = 0;
    Vec_IntForEachEntry( vChain, iFadd, i )
    {
        int iXorTruth = Vec_IntEntry( vTruths, 2*iFadd+0 );
        int iMajTruth = Vec_IntEntry( vTruths, 2*iFadd+1 );
        for ( k = 0; k < 3; k++ )
        {
            pObj = Gia_ManObj( p, Vec_IntEntry(vFadds, 5*iFadd+k) );
            pLits[k] = (!k && iCiLit) ? iCiLit : pObj->Value;
            assert( pLits[k] >= 0 );
        }
        // normalize truth table
        //    if ( Truth == 0xE8 || Truth == 0xD4 || Truth == 0xB2 || Truth == 0x71 ||
        //         Truth == 0x17 || Truth == 0x2B || Truth == 0x4D || Truth == 0x8E )
        if ( iMajTruth == 0x4D )
            pLits[0] = Abc_LitNot(pLits[0]), iMajTruth = 0x8E, iXorTruth = 0xFF & ~iXorTruth;
        else if ( iMajTruth == 0xD4 )
            pLits[0] = Abc_LitNot(pLits[0]), iMajTruth = 0xE8, iXorTruth = 0xFF & ~iXorTruth;
        else if ( iMajTruth == 0x2B )
            pLits[1] = Abc_LitNot(pLits[1]), iMajTruth = 0x8E, iXorTruth = 0xFF & ~iXorTruth;
        else if ( iMajTruth == 0xB2 )
            pLits[1] = Abc_LitNot(pLits[1]), iMajTruth = 0xE8, iXorTruth = 0xFF & ~iXorTruth;
        if ( iMajTruth == 0x8E )
            pLits[2] = Abc_LitNot(pLits[2]), iMajTruth = 0xE8, iXorTruth = 0xFF & ~iXorTruth;
        else if ( iMajTruth == 0x71 )
            pLits[2] = Abc_LitNot(pLits[2]), iMajTruth = 0x17, iXorTruth = 0xFF & ~iXorTruth;
        else assert( iMajTruth == 0xE8 || iMajTruth == 0x17 );
        // normalize carry-in
        if ( Abc_LitIsCompl(pLits[0]) )
        {
            for ( k = 0; k < 3; k++ )
                pLits[k] = Abc_LitNot(pLits[k]);
            iXorTruth = 0xFF & ~iXorTruth;
            iMajTruth = 0xFF & ~iMajTruth;
        }
        // add COs
        assert( !Abc_LitIsCompl(pLits[0]) );
        for ( k = 0; k < 3; k++ )
            Gia_ManAppendCo( pNew, pLits[k] );
        // create CI
        assert( iXorTruth == 0x96 || iXorTruth == 0x69 );
        pObj = Gia_ManObj( p, Vec_IntEntry(vFadds, 5*iFadd+3) );
        pObj->Value = Abc_LitNotCond( Gia_ManAppendCi(pNew), (int)(iXorTruth == 0x69) );
        // create CI
        assert( iMajTruth == 0xE8 || iMajTruth == 0x17 );
        iCiLit = Abc_LitNotCond( Gia_ManAppendCi(pNew), (int)(iMajTruth == 0x17) );
    }   
    // assign carry out
    assert( iFadd == Vec_IntEntryLast(vChain) );
    pObj = Gia_ManObj( p, Vec_IntEntry(vFadds, 5*iFadd+4) );
    pObj->Value = iCiLit;
}
void Gia_ManDupWithFaddBoxes_rec( Gia_Man_t * pNew, Gia_Man_t * p, Gia_Obj_t * pObj, Vec_Int_t * vFadds, Vec_Int_t * vMap, Vec_Wec_t * vChains, Vec_Int_t * vMap2Chain, Vec_Int_t * vTruths )
{
    int iChain;
    if ( ~pObj->Value )
        return;
    assert( Gia_ObjIsAnd(pObj) );
    iChain = Vec_IntEntry( vMap2Chain, Gia_ObjId(p, pObj) );
/*
    assert( iChain == -1 );
    if ( iChain >= 0 )
    {
        Gia_ManDupFadd( pNew, p, Vec_WecEntry(vChains, iChain), vFadds, vMap, vChains, vMap2Chain, vTruths );
        assert( ~pObj->Value );
        return;
    }
*/
    Gia_ManDupWithFaddBoxes_rec( pNew, p, Gia_ObjFanin0(pObj), vFadds, vMap, vChains, vMap2Chain, vTruths );
    Gia_ManDupWithFaddBoxes_rec( pNew, p, Gia_ObjFanin1(pObj), vFadds, vMap, vChains, vMap2Chain, vTruths );
    pObj->Value = Gia_ManAppendAnd( pNew, Gia_ObjFanin0Copy(pObj), Gia_ObjFanin1Copy(pObj) );
}
789
Gia_Man_t * Gia_ManDupWithNaturalBoxes( Gia_Man_t * p, int nFaddMin, int fVerbose )
790
{
791
    abctime clk = Abc_Clock();
792
    Gia_Man_t * pNew;//, * pTemp;
793 794 795 796
    Vec_Int_t * vFadds, * vMap, * vMap2Chain, * vTruths, * vChain;
    Vec_Wec_t * vChains;
    Gia_Obj_t * pObj;  
    int i, nBoxes;
797 798 799 800 801
    if ( Gia_ManBoxNum(p) > 0 )
    {
        printf( "Currently natural carry-chains cannot be detected when boxes are present.\n" );
        return NULL;
    }
802
    assert( Gia_ManBoxNum(p) == 0 );
803 804

    // detect FADDs
805
    vFadds = Gia_ManDetectFullAdders( p, fVerbose, NULL );
806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825
    assert( Vec_IntSize(vFadds) % 5 == 0 );
    // map MAJ into its FADD
    vMap = Gia_ManCreateMap( p, vFadds );
    // for each FADD, find the longest chain and reorder its inputs
    Gia_ManFindChains( p, vFadds, vMap );
    // returns the set of topmost MAJ nodes
    vChains = Gia_ManCollectTopmost( p, vFadds, vMap, nFaddMin );
    if ( fVerbose )
        Gia_ManPrintChains( p, vFadds, vMap, vChains );
    if ( Vec_WecSize(vChains) == 0 )
    {
        Vec_IntFree( vFadds );
        Vec_IntFree( vMap );
        Vec_WecFree( vChains );
        return Gia_ManDup( p );
    }
    // returns mapping of each MAJ into the topmost elements of its chain
    vMap2Chain = Gia_ManFindMapping( p, vFadds, vMap, vChains );
    // compute truth tables for FADDs
    vTruths = Gia_ManCollectTruthTables( p, vFadds );
826 827
    if ( fVerbose )
        Abc_PrintTime( 1, "Carry-chain detection time", Abc_Clock() - clk );
828 829

    // duplicate
830
    clk = Abc_Clock();
831 832 833 834 835 836 837 838 839 840 841 842 843
    Gia_ManFillValue( p );
    pNew = Gia_ManStart( Gia_ManObjNum(p) );
    pNew->pName = Abc_UtilStrsav( p->pName );
    pNew->pSpec = Abc_UtilStrsav( p->pSpec );
    Gia_ManConst0(p)->Value = 0;
    Gia_ManForEachCi( p, pObj, i )
        pObj->Value = Gia_ManAppendCi( pNew );
    Vec_WecForEachLevel( vChains, vChain, i )
        Gia_ManDupFadd( pNew, p, vChain, vFadds, vMap, vChains, vMap2Chain, vTruths );
    Gia_ManForEachCo( p, pObj, i )
        Gia_ManDupWithFaddBoxes_rec( pNew, p, Gia_ObjFanin0(pObj), vFadds, vMap, vChains, vMap2Chain, vTruths );
    Gia_ManForEachCo( p, pObj, i )
        Gia_ManAppendCo( pNew, Gia_ObjFanin0Copy(pObj) );
844
    Gia_ManSetRegNum( pNew, Gia_ManRegNum(p) );
845 846 847 848
    if ( Gia_ManRegNum(p) )
    {
        if ( fVerbose )
            printf( "Warning: Sequential design is coverted into combinational one by adding white boxes.\n" );
849
        pNew->nRegs = 0;
850
    }
851 852 853
    assert( !Gia_ManHasDangling(pNew) );

    // cleanup
854
    Vec_IntFree( vFadds );
855 856 857 858 859 860 861 862 863 864
    Vec_IntFree( vMap );
    Vec_WecFree( vChains );
    Vec_IntFree( vMap2Chain );
    Vec_IntFree( vTruths );
    
    // other information
    nBoxes = (Gia_ManCiNum(pNew) - Gia_ManCiNum(p)) / 2;
    assert( nBoxes == (Gia_ManCoNum(pNew) - Gia_ManCoNum(p)) / 3 );
    pNew->pManTime  = Gia_ManGenerateTim( Gia_ManCiNum(p), Gia_ManCoNum(p), nBoxes, 3, 2 );
    pNew->pAigExtra = Gia_ManGenerateExtraAig( nBoxes, 3, 2 );
865
/*
866
    // normalize
867
    pNew = Gia_ManDupNormalize( pTemp = pNew, 0 );
868 869 870
    pNew->pManTime  = pTemp->pManTime;  pTemp->pManTime  = NULL;
    pNew->pAigExtra = pTemp->pAigExtra; pTemp->pAigExtra = NULL;
    Gia_ManStop( pTemp );
871
*/
872 873 874 875
    //pNew = Gia_ManDupCollapse( pTemp = pNew, pNew->pAigExtra, NULL );
    //Gia_ManStop( pTemp );

    //Gia_ManIllustrateBoxes( pNew );
876 877
    if ( fVerbose )
        Abc_PrintTime( 1, "AIG with boxes construction time", Abc_Clock() - clk );
878
    return pNew;
879 880
}

881 882 883 884 885 886 887 888 889 890 891 892 893
/**Function*************************************************************

  Synopsis    [Converting AIG with annotated carry-chains into AIG with boxes.]

  Description [Assumes that annotations are pObj->fMark0 or pObj->fMark1.
  Only one of these can be set to 1.  If fMark0 (fMark1) is set to 1, 
  the first (second) input of an AND-gate is chained.]
               
  SideEffects []

  SeeAlso     []

***********************************************************************/
894 895 896 897 898 899 900 901 902 903 904 905
int Gia_ObjFanin0CopyCarry( Vec_Int_t * vCarries, Gia_Obj_t * pObj, int Id )
{
    if ( vCarries == NULL || Vec_IntEntry(vCarries, Gia_ObjFaninId0(pObj, Id)) == -1 )
        return Gia_ObjFanin0Copy(pObj);
    return Abc_LitNotCond( Vec_IntEntry(vCarries, Gia_ObjFaninId0(pObj, Id)), Gia_ObjFaninC0(pObj) );
}
int Gia_ObjFanin1CopyCarry( Vec_Int_t * vCarries, Gia_Obj_t * pObj, int Id )
{
    if ( vCarries == NULL || Vec_IntEntry(vCarries, Gia_ObjFaninId1(pObj, Id)) == -1 )
        return Gia_ObjFanin1Copy(pObj);
    return Abc_LitNotCond( Vec_IntEntry(vCarries, Gia_ObjFaninId1(pObj, Id)), Gia_ObjFaninC1(pObj) );
}
906
Gia_Man_t * Gia_ManDupWithArtificalFaddBoxes( Gia_Man_t * p, int fUseFanout, int fXorTrick )
907 908 909
{
    Gia_Man_t * pNew;
    Gia_Obj_t * pObj;  
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 945
    int nBoxes = Gia_ManBoxNum(p);
    int i, nRealPis, nRealPos;
    Vec_Int_t * vCarries = NULL;
    // make sure two chains do not overlap
    Gia_ManCleanPhase( p );
    Gia_ManForEachCi( p, pObj, i )
        assert( !pObj->fMark0 && !pObj->fMark1 );
    Gia_ManForEachCo( p, pObj, i )
        assert( !pObj->fMark0 && !pObj->fMark1 );
    Gia_ManForEachAnd( p, pObj, i )
    {
        assert( !pObj->fMark0 || !pObj->fMark1 );
        if ( pObj->fMark0 )
        {
            assert( Gia_ObjFanin0(pObj)->fPhase == 0 );
            Gia_ObjFanin0(pObj)->fPhase = 1;
        }
        if ( pObj->fMark1 )
        {
            assert( Gia_ObjFanin1(pObj)->fPhase == 0 );
            Gia_ObjFanin1(pObj)->fPhase = 1;
        }
    }
    // create mapping for carry-chains
    if ( !fUseFanout )
        vCarries = Vec_IntStartFull( Gia_ManObjNum(p) );
    // create references and discount carries
    if ( vCarries )
    {
        Gia_ManCreateRefs( p );
        Gia_ManForEachAnd( p, pObj, i )
            if ( pObj->fMark0 )
                Gia_ObjRefFanin0Dec( p, pObj );
            else if ( pObj->fMark1 )
                Gia_ObjRefFanin1Dec( p, pObj );
    }
946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961
    // if AIG already has (natural) FADD boxes, it should not un-normalized
    Gia_ManFillValue( p );
    pNew = Gia_ManStart( Gia_ManObjNum(p) );
    pNew->pName = Abc_UtilStrsav( p->pName );
    pNew->pSpec = Abc_UtilStrsav( p->pSpec );
    Gia_ManConst0(p)->Value = 0;
    Gia_ManForEachObj1( p, pObj, i )
    {
        if ( Gia_ObjIsCi(pObj) )
            pObj->Value = Gia_ManAppendCi( pNew );
        else if ( Gia_ObjIsCo(pObj) )
            pObj->Value = Gia_ManAppendCo( pNew, Gia_ObjFanin0Copy(pObj) );
        else if ( !pObj->fMark0 && !pObj->fMark1 ) // AND-gate
            pObj->Value = Gia_ManAppendAnd( pNew, Gia_ObjFanin0Copy(pObj), Gia_ObjFanin1Copy(pObj) );
        else // AND-gate with chain
        {
962
            int iCiLit, iOtherLit, iLit0, iLit1, iLit2, iXorLit;
963
            assert( pObj->fMark0 != pObj->fMark1 );
964
            iCiLit    = pObj->fMark0 ? Gia_ObjFanin0CopyCarry(vCarries, pObj, i) : Gia_ObjFanin1CopyCarry(vCarries, pObj, i);
965
            iOtherLit = pObj->fMark0 ? Gia_ObjFanin1Copy(pObj) : Gia_ObjFanin0Copy(pObj);
966
            assert( iCiLit >= 0 && iOtherLit >= 0 );
967 968 969 970
            iLit0 = Abc_LitNotCond( iCiLit,    Abc_LitIsCompl(iCiLit) );
            iLit1 = Abc_LitNotCond( iOtherLit, Abc_LitIsCompl(iCiLit) );
            iLit2 = Abc_LitNotCond( 0,         Abc_LitIsCompl(iCiLit) );
            // add COs
971
            assert( !Abc_LitIsCompl(iLit0) );
972 973 974 975
            Gia_ManAppendCo( pNew, iLit0 );
            Gia_ManAppendCo( pNew, iLit1 );
            Gia_ManAppendCo( pNew, iLit2 );
            // add CI (unused sum bit)
976
            iXorLit = Gia_ManAppendCi(pNew);
977 978
            // add CI (carry bit)
            pObj->Value = Abc_LitNotCond( Gia_ManAppendCi(pNew), Abc_LitIsCompl(iCiLit) );
979 980 981 982
            if ( vCarries && pObj->fPhase )
            {
                Vec_IntWriteEntry( vCarries, i, pObj->Value );
                if ( Gia_ObjRefNum(p, pObj) > 0 )
983 984 985 986 987 988
                {
                    if ( fXorTrick )
                        pObj->Value = Gia_ManAppendAnd( pNew, Abc_LitNotCond(iXorLit, !Abc_LitIsCompl(iCiLit)), iOtherLit );
                    else
                        pObj->Value = Gia_ManAppendAnd( pNew, Gia_ObjFanin0Copy(pObj), Gia_ObjFanin1Copy(pObj) );
                }
989
            }
990 991 992
            nBoxes++;
        }
    }
993 994 995 996
    Gia_ManCleanPhase( p );
    Vec_IntFreeP( &vCarries );
    ABC_FREE( p->pRefs );
    assert( !Gia_ManHasDangling(pNew) );
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
    // other information
//    nBoxes += (Gia_ManCiNum(pNew) - Gia_ManCiNum(p)) / 2;
//    assert( nBoxes == Gia_ManBoxNum(p) + (Gia_ManCoNum(pNew) - Gia_ManCoNum(p)) / 3 );
    nRealPis = Gia_ManBoxNum(p) ? Tim_ManPiNum((Tim_Man_t *)p->pManTime) : Gia_ManCiNum(p);
    nRealPos = Gia_ManBoxNum(p) ? Tim_ManPoNum((Tim_Man_t *)p->pManTime) : Gia_ManCoNum(p);
    pNew->pManTime  = Gia_ManGenerateTim( nRealPis, nRealPos, nBoxes, 3, 2 );
    pNew->pAigExtra = Gia_ManGenerateExtraAig( nBoxes, 3, 2 );
    // optionally normalize the AIG
    return pNew;
}
Gia_Man_t * Gia_ManDupWithArtificalFaddBoxesTest( Gia_Man_t * p )
{
    Gia_Man_t * pNew;
    Gia_Obj_t * pObj;
    int i;
    // label some and-gates
    Gia_ManCleanMark01( p );
    Gia_ManForEachAnd( p, pObj, i )
    {
        pObj->fMark0 = i % 5;
        pObj->fMark1 = i % 7;
        if ( pObj->fMark0 && pObj->fMark1 )
            pObj->fMark0 = pObj->fMark1 = 0;
    }

    // output new AIG
1023
    pNew = Gia_ManDupWithArtificalFaddBoxes( p, 0, 0 );
1024 1025 1026 1027 1028 1029
    Gia_ManCleanMark01( p );
    return pNew;
}

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

1030
  Synopsis    [Adds artificial carry chains to the manager.]
1031 1032 1033 1034 1035 1036 1037 1038

  Description []
               
  SideEffects []

  SeeAlso     []

***********************************************************************/
1039 1040
// computes AIG delay information when boxes are used
int Gia_ManFindAnnotatedDelay( Gia_Man_t * p, int DelayC, int * pnBoxes, int fIgnoreBoxDelays )
1041 1042
{
    Gia_Obj_t * pObj;
1043
    int nRealPis = Gia_ManBoxNum(p) ? Tim_ManPiNum((Tim_Man_t *)p->pManTime) : Gia_ManCiNum(p);
1044
    int * pDelays = Vec_IntArray(p->vLevels);
1045
    int i, k, iBox, iBoxOutId, Delay, Delay0, Delay1, DelayMax = 0, nBoxes = 0;
1046 1047 1048 1049
    Vec_IntFill( p->vLevels, Gia_ManObjNum(p), 0 );
    Gia_ManForEachObj1( p, pObj, i )
    {
        if ( Gia_ObjIsCi(pObj) )
1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073
        {
            if ( fIgnoreBoxDelays )
                continue;
            // check if it is real PI
            iBoxOutId = Gia_ObjCioId(pObj) - nRealPis;
            if ( iBoxOutId < 0 )
                continue;
            // if it is a box output, find box number
            iBox = iBoxOutId / 2;
            assert( iBox < Gia_ManBoxNum(p) );
            // check find the maximum delay of the box inputs
            Delay = 0;
            for ( k = 0; k < 3; k++ )
            {
                int Id = Gia_ObjId( p, Gia_ManCo(p, iBox*3+k) );
                assert( Id < i );
                Delay = Abc_MaxInt( Delay, pDelays[Id] );
            }
            // consider outputs
            if ( iBoxOutId & 1 ) // carry output
                Delay += DelayC;
            else // sum output
                Delay += 100;
            pDelays[i] = Delay;
1074
            continue;
1075
        }
1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102
        if ( Gia_ObjIsCo(pObj) )
        {
            pDelays[i] = pDelays[Gia_ObjFaninId0(pObj, i)];
            DelayMax = Abc_MaxInt( DelayMax, pDelays[i] );
            continue;
        }
        assert( !pObj->fMark0 || !pObj->fMark1 );
        Delay0 = pDelays[Gia_ObjFaninId0(pObj, i)];
        Delay1 = pDelays[Gia_ObjFaninId1(pObj, i)];
        if ( pObj->fMark0 )
        {
            Delay = Abc_MaxInt( Delay0 + DelayC, Delay1 + 100 );
            nBoxes++;
        }
        else if ( pObj->fMark1 )
        {
            Delay = Abc_MaxInt( Delay1 + DelayC, Delay0 + 100 );
            nBoxes++;
        }
        else
            Delay = Abc_MaxInt( Delay0 + 100, Delay1 + 100 );
        pDelays[i] = Delay;
    }
    if ( pnBoxes )
        *pnBoxes = nBoxes;
    return DelayMax;
}
1103 1104 1105 1106 1107 1108 1109
// check if the object is already used in some chain
static inline int Gia_ObjIsUsed( Gia_Obj_t * pObj )
{
    return pObj->fMark0 || pObj->fMark1 || pObj->fPhase;
}
// finds internal node that can begin a new chain
int Gia_ManFindChainStart( Gia_Man_t * p )
1110 1111 1112 1113 1114 1115
{
    Gia_Obj_t * pObj;
    int * pDelays = Vec_IntArray(p->vLevels);
    int i, iMax = -1, DelayMax = 0;
    Gia_ManForEachAnd( p, pObj, i )
    {
1116
        if ( Gia_ObjIsUsed(pObj) )
1117 1118 1119 1120 1121 1122 1123 1124
            continue;
        if ( DelayMax > pDelays[i] )
            continue;
        DelayMax = pDelays[i];
        iMax = i;
    }
    return iMax;
}
1125
// finds a sequence of internal nodes that creates a new chain
1126 1127 1128 1129
int Gia_ManFindPath( Gia_Man_t * p, int DelayC, int nPathMin, int nPathMax, Vec_Int_t * vPath )
{
    Gia_Obj_t * pObj, * pFanin0, * pFanin1;
    int * pDelays = Vec_IntArray(p->vLevels);
1130
    int i, iLit, iMax = Gia_ManFindChainStart( p );
1131 1132 1133 1134 1135 1136 1137
    if ( iMax == -1 )
        return -1;
    Vec_IntClear( vPath );
    pObj = Gia_ManObj(p, iMax);
    assert( Gia_ObjIsAnd(pObj) );
    while ( Gia_ObjIsAnd(pObj) )
    {
1138
        assert( !Gia_ObjIsUsed(pObj) );
1139 1140
        pFanin0 = Gia_ObjFanin0(pObj);
        pFanin1 = Gia_ObjFanin1(pObj);
1141
        if ( Gia_ObjIsUsed(pFanin0) && Gia_ObjIsUsed(pFanin1) )
1142
            break;
1143
        if ( Gia_ObjIsUsed(pFanin0) )
1144 1145 1146 1147
        {
            Vec_IntPush( vPath, Abc_Var2Lit(Gia_ObjId(p, pObj), 1) );
            pObj = pFanin1;
        }
1148
        else if ( Gia_ObjIsUsed(pFanin1) )
1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175
        {
            Vec_IntPush( vPath, Abc_Var2Lit(Gia_ObjId(p, pObj), 0) );
            pObj = pFanin0;
        }
        else
        {
            if ( pDelays[Gia_ObjId(p, pFanin1)] > pDelays[Gia_ObjId(p, pFanin0)] )
            {
                Vec_IntPush( vPath, Abc_Var2Lit(Gia_ObjId(p, pObj), 1) );
                pObj = pFanin1;
            }
            else
            {
                Vec_IntPush( vPath, Abc_Var2Lit(Gia_ObjId(p, pObj), 0) );
                pObj = pFanin0;
            }
        }
    }
    if ( Vec_IntSize(vPath) < nPathMin )
    {
        Gia_ManObj(p, iMax)->fPhase = 1;
        return 0;
    }
    // label nodes
    if ( Vec_IntSize(vPath) > nPathMax )
        Vec_IntShrink( vPath, nPathMax );
    Vec_IntForEachEntry( vPath, iLit, i )
1176 1177
    {
        pObj = Gia_ManObj( p, Abc_Lit2Var(iLit) );
1178
        if ( Abc_LitIsCompl(iLit) )
1179 1180 1181 1182 1183 1184
        {
            assert( pObj->fMark1 == 0 );
            pObj->fMark1 = 1;
            assert( Gia_ObjFanin1(pObj)->fPhase == 0 );
            Gia_ObjFanin1(pObj)->fPhase = 1;
        }
1185
        else
1186 1187 1188 1189 1190 1191 1192
        {
            assert( pObj->fMark0 == 0 );
            pObj->fMark0 = 1;
            assert( Gia_ObjFanin0(pObj)->fPhase == 0 );
            Gia_ObjFanin0(pObj)->fPhase = 1;
        }
    }
1193 1194
    return Vec_IntSize(vPath);
}
1195 1196
// iteratively create the given number of chains
int Gia_ManIteratePaths( Gia_Man_t * p, int DelayC, int nPathMin, int nPathMax, int nPathLimit, int fIgnoreBoxDelays, int fVerbose )
1197
{
1198
    Gia_Obj_t * pObj;
1199 1200 1201 1202 1203 1204
    Vec_Int_t * vPath = Vec_IntAlloc( 100 );
    int i, RetValue, nBoxes, MaxDelay, nPaths = 0;
    assert( p->vLevels == NULL );
    p->vLevels = Vec_IntStart( Gia_ManObjNum(p) );
    Gia_ManCleanMark01( p );
    Gia_ManCleanPhase( p );
1205 1206
    Gia_ManForEachCi( p, pObj, i )
        pObj->fPhase = 1;
1207 1208 1209 1210
    if ( fVerbose )
        printf( "Running path detection: BoxDelay = %d, PathMin = %d, PathMax = %d, PathLimit = %d.\n", DelayC, nPathMin, nPathMax, nPathLimit );
    for ( i = 0; i < nPathLimit; i++ )
    {
1211
        MaxDelay = Gia_ManFindAnnotatedDelay( p, DelayC, &nBoxes, fIgnoreBoxDelays );
1212 1213 1214 1215 1216 1217 1218 1219 1220
        RetValue = Gia_ManFindPath( p, DelayC, nPathMin, nPathMax, vPath );
        if ( RetValue == -1 )
            break;
        nPaths += (RetValue > 0);
        if ( fVerbose )
            printf( "Iter %5d : Paths = %2d. Boxes = %2d. Total boxes = %6d.  Max delay = %5d.\n", i, nPaths, RetValue, nBoxes, MaxDelay );
    }
    Vec_IntFree( vPath );
    Vec_IntFreeP( &p->vLevels );
1221
    Gia_ManCleanPhase( p );
1222 1223
    return 1;
}
1224
// annotate artificial chains and then put them into boxes
1225
Gia_Man_t * Gia_ManDupWithArtificialBoxes( Gia_Man_t * p, int DelayC, int nPathMin, int nPathMax, int nPathLimit, int fUseFanout, int fXorTrick, int fIgnoreBoxDelays, int fVerbose )
1226 1227
{
    Gia_Man_t * pNew;
1228
/*
1229 1230 1231 1232 1233
    if ( Gia_ManBoxNum(p) > 0 )
    {
        printf( "Currently artifical carry-chains cannot be detected when natural ones are present.\n" );
        return NULL;
    }
1234 1235
*/
    Gia_ManIteratePaths( p, DelayC, nPathMin, nPathMax, nPathLimit, fIgnoreBoxDelays, fVerbose );
1236
    pNew = Gia_ManDupWithArtificalFaddBoxes( p, fUseFanout, fXorTrick );
1237
    Gia_ManCleanMark01( p );
1238 1239 1240
    return pNew;
}

1241 1242 1243 1244 1245 1246 1247
////////////////////////////////////////////////////////////////////////
///                       END OF FILE                                ///
////////////////////////////////////////////////////////////////////////


ABC_NAMESPACE_IMPL_END