giaAiger.c 47.8 KB
Newer Older
Alan Mishchenko committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
/**CFile****************************************************************

  FileName    [giaAiger.c]

  SystemName  [ABC: Logic synthesis and verification system.]

  PackageName [Scalable AIG package.]

  Synopsis    [Procedures to read/write binary AIGER format developed by
  Armin Biere, Johannes Kepler University (http://fmv.jku.at/)]

  Author      [Alan Mishchenko]
  
  Affiliation [UC Berkeley]

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

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

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

#include "gia.h"
23
#include "misc/tim/tim.h"
24
#include "base/main/main.h"
Alan Mishchenko committed
25

26 27
ABC_NAMESPACE_IMPL_START

28
#define XAIG_VERBOSE 0
29

Alan Mishchenko committed
30 31 32 33 34 35 36 37 38 39
////////////////////////////////////////////////////////////////////////
///                        DECLARATIONS                              ///
////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////
///                     FUNCTION DEFINITIONS                         ///
////////////////////////////////////////////////////////////////////////

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

40
  Synopsis    []
Alan Mishchenko committed
41 42 43 44 45 46 47 48

  Description []

  SideEffects []

  SeeAlso     []

***********************************************************************/
49
void Gia_FileFixName( char * pFileName )
Alan Mishchenko committed
50 51 52 53 54 55
{
    char * pName;
    for ( pName = pFileName; *pName; pName++ )
        if ( *pName == '>' )
            *pName = '\\';
}
56 57 58 59 60 61 62 63
char * Gia_FileNameGeneric( char * FileName )
{
    char * pDot, * pRes;
    pRes = Abc_UtilStrsav( FileName );
    if ( (pDot = strrchr( pRes, '.' )) )
        *pDot = 0;
    return pRes;
}
Alan Mishchenko committed
64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
int Gia_FileSize( char * pFileName )
{
    FILE * pFile;
    int nFileSize;
    pFile = fopen( pFileName, "r" );
    if ( pFile == NULL )
    {
        printf( "Gia_FileSize(): The file is unavailable (absent or open).\n" );
        return 0;
    }
    fseek( pFile, 0, SEEK_END );  
    nFileSize = ftell( pFile ); 
    fclose( pFile );
    return nFileSize;
}
79
void Gia_FileWriteBufferSize( FILE * pFile, int nSize )
Alan Mishchenko committed
80
{
81 82 83
    unsigned char Buffer[5];
    Gia_AigerWriteInt( Buffer, nSize );
    fwrite( Buffer, 1, 4, pFile );
Alan Mishchenko committed
84 85 86 87
}

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

88
  Synopsis    [Create the array of literals to be written.]
Alan Mishchenko committed
89 90 91 92 93 94 95 96

  Description []
  
  SideEffects []

  SeeAlso     []

***********************************************************************/
97
Vec_Int_t * Gia_AigerCollectLiterals( Gia_Man_t * p )
Alan Mishchenko committed
98
{
99 100 101 102 103 104 105 106 107
    Vec_Int_t * vLits;
    Gia_Obj_t * pObj;
    int i;
    vLits = Vec_IntAlloc( Gia_ManPoNum(p) );
    Gia_ManForEachRi( p, pObj, i )
        Vec_IntPush( vLits, Gia_ObjFaninLit0p(p, pObj) );
    Gia_ManForEachPo( p, pObj, i )
        Vec_IntPush( vLits, Gia_ObjFaninLit0p(p, pObj) );
    return vLits;
Alan Mishchenko committed
108
}
109
Vec_Int_t * Gia_AigerReadLiterals( unsigned char ** ppPos, int nEntries )
Alan Mishchenko committed
110
{
111 112 113 114 115 116
    Vec_Int_t * vLits;
    int Lit, LitPrev, Diff, i;
    vLits = Vec_IntAlloc( nEntries );
    LitPrev = Gia_AigerReadUnsigned( ppPos );
    Vec_IntPush( vLits, LitPrev );
    for ( i = 1; i < nEntries; i++ )
Alan Mishchenko committed
117
    {
118 119 120 121 122 123 124 125
//        Diff = Lit - LitPrev;
//        Diff = (Lit < LitPrev)? -Diff : Diff;
//        Diff = ((2 * Diff) << 1) | (int)(Lit < LitPrev);
        Diff = Gia_AigerReadUnsigned( ppPos );
        Diff = (Diff & 1)? -(Diff >> 1) : Diff >> 1;
        Lit  = Diff + LitPrev;
        Vec_IntPush( vLits, Lit );
        LitPrev = Lit;
Alan Mishchenko committed
126
    }
127
    return vLits;
Alan Mishchenko committed
128
}
129
Vec_Str_t * Gia_AigerWriteLiterals( Vec_Int_t * vLits )
Alan Mishchenko committed
130
{
131 132 133 134 135 136
    Vec_Str_t * vBinary;
    int Pos = 0, Lit, LitPrev, Diff, i;
    vBinary = Vec_StrAlloc( 2 * Vec_IntSize(vLits) );
    LitPrev = Vec_IntEntry( vLits, 0 );
    Pos = Gia_AigerWriteUnsignedBuffer( (unsigned char *)Vec_StrArray(vBinary), Pos, LitPrev ); 
    Vec_IntForEachEntryStart( vLits, Lit, i, 1 )
Alan Mishchenko committed
137
    {
138 139 140 141 142 143 144
        Diff = Lit - LitPrev;
        Diff = (Lit < LitPrev)? -Diff : Diff;
        Diff = (Diff << 1) | (int)(Lit < LitPrev);
        Pos = Gia_AigerWriteUnsignedBuffer( (unsigned char *)Vec_StrArray(vBinary), Pos, Diff );
        LitPrev = Lit;
        if ( Pos + 10 > vBinary->nCap )
            Vec_StrGrow( vBinary, vBinary->nCap+1 );
Alan Mishchenko committed
145
    }
146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162
    vBinary->nSize = Pos;
/*
    // verify
    {
        extern Vec_Int_t * Gia_AigerReadLiterals( char ** ppPos, int nEntries );
        char * pPos = Vec_StrArray( vBinary );
        Vec_Int_t * vTemp = Gia_AigerReadLiterals( &pPos, Vec_IntSize(vLits) );
        for ( i = 0; i < Vec_IntSize(vLits); i++ )
        {
            int Entry1 = Vec_IntEntry(vLits,i);
            int Entry2 = Vec_IntEntry(vTemp,i);
            assert( Entry1 == Entry2 );
        }
        Vec_IntFree( vTemp );
    }
*/
    return vBinary;
Alan Mishchenko committed
163 164 165 166
}

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

Alan Mishchenko committed
167 168 169 170 171 172 173 174 175
  Synopsis    [Reads the AIG in the binary AIGER format.]

  Description []
  
  SideEffects []

  SeeAlso     []

***********************************************************************/
176
Gia_Man_t * Gia_AigerReadFromMemory( char * pContents, int nFileSize, int fSkipStrash, int fCheck )
Alan Mishchenko committed
177
{
178 179
    Gia_Man_t * pNew, * pTemp;
    Vec_Int_t * vLits = NULL, * vPoTypes = NULL;
180
    Vec_Int_t * vNodes, * vDrivers, * vInits = NULL;
181
    int iObj, iNode0, iNode1, fHieOnly = 0;
182
    int nTotal, nInputs, nOutputs, nLatches, nAnds, i;
183
    int nBad = 0, nConstr = 0, nJust = 0, nFair = 0;
184
    unsigned char * pDrivers, * pSymbols, * pCur;
Alan Mishchenko committed
185 186
    unsigned uLit0, uLit1, uLit;

187 188
    // read the parameters (M I L O A + B C J F)
    pCur = (unsigned char *)pContents;         while ( *pCur != ' ' ) pCur++; pCur++;
Alan Mishchenko committed
189
    // read the number of objects
190
    nTotal = atoi( (const char *)pCur );    while ( *pCur != ' ' ) pCur++; pCur++;
Alan Mishchenko committed
191
    // read the number of inputs
192
    nInputs = atoi( (const char *)pCur );   while ( *pCur != ' ' ) pCur++; pCur++;
Alan Mishchenko committed
193
    // read the number of latches
194
    nLatches = atoi( (const char *)pCur );  while ( *pCur != ' ' ) pCur++; pCur++;
Alan Mishchenko committed
195
    // read the number of outputs
196
    nOutputs = atoi( (const char *)pCur );  while ( *pCur != ' ' ) pCur++; pCur++;
Alan Mishchenko committed
197
    // read the number of nodes
198
    nAnds = atoi( (const char *)pCur );     while ( *pCur != ' ' && *pCur != '\n' ) pCur++; 
199 200
    if ( *pCur == ' ' )
    {
201
//        assert( nOutputs == 0 );
202 203
        // read the number of properties
        pCur++;
204
        nBad = atoi( (const char *)pCur );     while ( *pCur != ' ' && *pCur != '\n' ) pCur++; 
205 206 207 208 209 210
        nOutputs += nBad;
    }
    if ( *pCur == ' ' )
    {
        // read the number of properties
        pCur++;
211
        nConstr = atoi( (const char *)pCur );     while ( *pCur != ' ' && *pCur != '\n' ) pCur++; 
212 213 214 215 216 217
        nOutputs += nConstr;
    }
    if ( *pCur == ' ' )
    {
        // read the number of properties
        pCur++;
218
        nJust = atoi( (const char *)pCur );     while ( *pCur != ' ' && *pCur != '\n' ) pCur++; 
219 220 221 222 223 224
        nOutputs += nJust;
    }
    if ( *pCur == ' ' )
    {
        // read the number of properties
        pCur++;
225
        nFair = atoi( (const char *)pCur );     while ( *pCur != ' ' && *pCur != '\n' ) pCur++; 
226 227 228 229 230 231 232 233 234
        nOutputs += nFair;
    }
    if ( *pCur != '\n' )
    {
        fprintf( stdout, "The parameter line is in a wrong format.\n" );
        return NULL;
    }
    pCur++;

Alan Mishchenko committed
235 236 237
    // check the parameters
    if ( nTotal != nInputs + nLatches + nAnds )
    {
238
        fprintf( stdout, "The number of objects does not match.\n" );
Alan Mishchenko committed
239 240
        return NULL;
    }
241 242
    if ( nJust || nFair )
    {
243
        fprintf( stdout, "Reading AIGER files with liveness properties is currently not supported.\n" );
244 245 246 247 248 249 250 251 252 253
        return NULL;
    }

    if ( nConstr )
    {
        if ( nConstr == 1 )
            fprintf( stdout, "Warning: The last output is interpreted as a constraint.\n" );
        else
            fprintf( stdout, "Warning: The last %d outputs are interpreted as constraints.\n", nConstr );
    }
Alan Mishchenko committed
254 255 256

    // allocate the empty AIG
    pNew = Gia_ManStart( nTotal + nLatches + nOutputs + 1 );
257
    pNew->nConstrs = nConstr;
Alan Mishchenko committed
258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280

    // prepare the array of nodes
    vNodes = Vec_IntAlloc( 1 + nTotal );
    Vec_IntPush( vNodes, 0 );

    // create the PIs
    for ( i = 0; i < nInputs + nLatches; i++ )
    {
        iObj = Gia_ManAppendCi(pNew);    
        Vec_IntPush( vNodes, iObj );
    }

    // remember the beginning of latch/PO literals
    pDrivers = pCur;
    if ( pContents[3] == ' ' ) // standard AIGER
    {
        // scroll to the beginning of the binary data
        for ( i = 0; i < nLatches + nOutputs; )
            if ( *pCur++ == '\n' )
                i++;
    }
    else // modified AIGER
    {
281
        vLits = Gia_AigerReadLiterals( &pCur, nLatches + nOutputs );
Alan Mishchenko committed
282 283 284
    }

    // create the AND gates
285 286
    if ( !fSkipStrash )
        Gia_ManHashAlloc( pNew );
Alan Mishchenko committed
287 288 289
    for ( i = 0; i < nAnds; i++ )
    {
        uLit = ((i + 1 + nInputs + nLatches) << 1);
290 291
        uLit1 = uLit  - Gia_AigerReadUnsigned( &pCur );
        uLit0 = uLit1 - Gia_AigerReadUnsigned( &pCur );
Alan Mishchenko committed
292
//        assert( uLit1 > uLit0 );
293 294
        iNode0 = Abc_LitNotCond( Vec_IntEntry(vNodes, uLit0 >> 1), uLit0 & 1 );
        iNode1 = Abc_LitNotCond( Vec_IntEntry(vNodes, uLit1 >> 1), uLit1 & 1 );
Alan Mishchenko committed
295
        assert( Vec_IntSize(vNodes) == i + 1 + nInputs + nLatches );
296
        if ( fSkipStrash )
297
            Vec_IntPush( vNodes, Gia_ManAppendAnd(pNew, iNode0, iNode1) );
298 299
        else
            Vec_IntPush( vNodes, Gia_ManHashAnd(pNew, iNode0, iNode1) );
Alan Mishchenko committed
300
    }
301 302
    if ( !fSkipStrash )
        Gia_ManHashStop( pNew );
Alan Mishchenko committed
303 304 305 306 307 308 309 310

    // remember the place where symbols begin
    pSymbols = pCur;

    // read the latch driver literals
    vDrivers = Vec_IntAlloc( nLatches + nOutputs );
    if ( pContents[3] == ' ' ) // standard AIGER
    {
311
        vInits = Vec_IntAlloc( nLatches );
Alan Mishchenko committed
312 313 314
        pCur = pDrivers;
        for ( i = 0; i < nLatches; i++ )
        {
315 316 317 318 319 320 321 322 323 324 325 326 327 328
            uLit0 = atoi( (char *)pCur );   
            while ( *pCur != ' ' && *pCur != '\n' ) 
                pCur++;
            if ( *pCur == ' ' )
            {
                pCur++;
                Vec_IntPush( vInits, atoi( (char *)pCur ) );
                while ( *pCur++ != '\n' );
            }
            else
            {
                pCur++;
                Vec_IntPush( vInits, 0 );
            }
329
            iNode0 = Abc_LitNotCond( Vec_IntEntry(vNodes, uLit0 >> 1), (uLit0 & 1) );
Alan Mishchenko committed
330 331 332 333 334
            Vec_IntPush( vDrivers, iNode0 );
        }
        // read the PO driver literals
        for ( i = 0; i < nOutputs; i++ )
        {
335
            uLit0 = atoi( (char *)pCur );   while ( *pCur++ != '\n' );
336
            iNode0 = Abc_LitNotCond( Vec_IntEntry(vNodes, uLit0 >> 1), (uLit0 & 1) );
Alan Mishchenko committed
337 338 339 340 341 342 343 344 345 346
            Vec_IntPush( vDrivers, iNode0 );
        }

    }
    else
    {
        // read the latch driver literals
        for ( i = 0; i < nLatches; i++ )
        {
            uLit0 = Vec_IntEntry( vLits, i );
347
            iNode0 = Abc_LitNotCond( Vec_IntEntry(vNodes, uLit0 >> 1), (uLit0 & 1) );
Alan Mishchenko committed
348 349 350 351 352 353
            Vec_IntPush( vDrivers, iNode0 );
        }
        // read the PO driver literals
        for ( i = 0; i < nOutputs; i++ )
        {
            uLit0 = Vec_IntEntry( vLits, i+nLatches );
354
            iNode0 = Abc_LitNotCond( Vec_IntEntry(vNodes, uLit0 >> 1), (uLit0 & 1) );
Alan Mishchenko committed
355 356 357 358 359 360 361 362 363 364 365 366 367 368 369
            Vec_IntPush( vDrivers, iNode0 );
        }
        Vec_IntFree( vLits );
    }

    // create the POs
    for ( i = 0; i < nOutputs; i++ )
        Gia_ManAppendCo( pNew, Vec_IntEntry(vDrivers, nLatches + i) );
    for ( i = 0; i < nLatches; i++ )
        Gia_ManAppendCo( pNew, Vec_IntEntry(vDrivers, i) );
    Vec_IntFree( vDrivers );

    // create the latches
    Gia_ManSetRegNum( pNew, nLatches );

370
    // read signal names if they are of the special type
Alan Mishchenko committed
371
    pCur = pSymbols;
372
    if ( *pCur != 'c' )
Alan Mishchenko committed
373
    {
374 375 376 377 378 379
        int fBreakUsed = 0;
        unsigned char * pCurOld = pCur;
        pNew->vUserPiIds = Vec_IntStartFull( nInputs );
        pNew->vUserPoIds = Vec_IntStartFull( nOutputs );
        pNew->vUserFfIds = Vec_IntStartFull( nLatches );
        while ( pCur < (unsigned char *)pContents + nFileSize && *pCur != 'c' )
380 381
        {
            int iTerm;
382
            char * pType = (char *)pCur;
383 384 385
            // check terminal type
            if ( *pCur != 'i' && *pCur != 'o' && *pCur != 'l'  )
            {
386
//                fprintf( stdout, "Wrong terminal type.\n" );
387 388 389 390
                fBreakUsed = 1;
                break;
            }
            // get terminal number
391
            iTerm = atoi( (char *)++pCur );  while ( *pCur++ != ' ' );
392
            // skip spaces
393 394
            while ( *pCur == ' ' )
                pCur++;
395 396 397 398 399 400 401 402 403 404
            // decode the user numbers:
            // flops are named: @l<num>
            // PIs are named: @i<num>
            // POs are named: @o<num>
            if ( *pCur++ != '@' )
            {
                fBreakUsed = 1;
                break;
            }
            if ( *pCur == 'i' && *pType == 'i' )
405
                Vec_IntWriteEntry( pNew->vUserPiIds, iTerm, atoi((char *)pCur+1) );
406
            else if ( *pCur == 'o' && *pType == 'o' )
407
                Vec_IntWriteEntry( pNew->vUserPoIds, iTerm, atoi((char *)pCur+1) );
408
            else if ( *pCur == 'l' && *pType == 'l' )
409
                Vec_IntWriteEntry( pNew->vUserFfIds, iTerm, atoi((char *)pCur+1) );
410 411 412 413 414 415 416 417 418 419 420 421
            else
            {
                fprintf( stdout, "Wrong name format.\n" );
                fBreakUsed = 1;
                break;
            }
            // skip digits
            while ( *pCur++ != '\n' );
        }
        // in case of abnormal termination, remove the arrays
        if ( fBreakUsed )
        {
422
            unsigned char * pName;
423 424 425 426
            int Entry, nInvars, nConstr, iTerm;

            Vec_Int_t * vPoNames = Vec_IntStartFull( nOutputs );

427 428 429
            Vec_IntFreeP( &pNew->vUserPiIds );
            Vec_IntFreeP( &pNew->vUserPoIds );
            Vec_IntFreeP( &pNew->vUserFfIds );
430 431 432

            // try to figure out signal names
            fBreakUsed = 0;
433 434
            pCur = (unsigned char *)pCurOld;
            while ( pCur < (unsigned char *)pContents + nFileSize && *pCur != 'c' )
435 436 437
            {
                // get the terminal type
                if ( *pCur == 'i' || *pCur == 'l' )
438 439 440 441
                {
                    // skip till the end of the line
                    while ( *pCur++ != '\n' );
                    *(pCur-1) = 0;
442
                    continue;
443
                }
444 445
                if ( *pCur != 'o' )
                {
446
//                    fprintf( stdout, "Wrong terminal type.\n" );
447 448 449 450
                    fBreakUsed = 1;
                    break;
                }
                // get the terminal number
451
                iTerm = atoi( (char *)++pCur );  while ( *pCur++ != ' ' );
452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469
                // get the node
                if ( iTerm < 0 || iTerm >= nOutputs )
                {
                    fprintf( stdout, "The output number (%d) is out of range.\n", iTerm );
                    fBreakUsed = 1;
                    break;
                }
                if ( Vec_IntEntry(vPoNames, iTerm) != ~0 )
                {
                    fprintf( stdout, "The output number (%d) is listed twice.\n", iTerm );
                    fBreakUsed = 1;
                    break;
                }

                // get the name
                pName = pCur;          while ( *pCur++ != '\n' );
                *(pCur-1) = 0;
                // assign the name
470
                Vec_IntWriteEntry( vPoNames, iTerm, pName - (unsigned char *)pContents );
471 472 473 474 475 476
            } 

            // check that all names are assigned
            if ( !fBreakUsed )
            {
                nInvars = nConstr = 0;
477
                vPoTypes = Vec_IntStart( Gia_ManPoNum(pNew) );
478 479 480 481 482
                Vec_IntForEachEntry( vPoNames, Entry, i )
                {
                    if ( Entry == ~0 )
                        continue;
                    if ( strncmp( pContents+Entry, "constraint:", 11 ) == 0 )
483 484
                    {
                        Vec_IntWriteEntry( vPoTypes, i, 1 );
485
                        nConstr++;
486
                    }
487
                    if ( strncmp( pContents+Entry, "invariant:", 10 ) == 0 )
488 489
                    {
                        Vec_IntWriteEntry( vPoTypes, i, 2 );
490
                        nInvars++;
491
                    }
492 493 494 495 496
                }
                if ( nConstr )
                    fprintf( stdout, "Recognized and added %d constraints.\n", nConstr );
                if ( nInvars )
                    fprintf( stdout, "Recognized and skipped %d invariants.\n", nInvars );
497 498
                if ( nConstr == 0 && nInvars == 0 )
                    Vec_IntFreeP( &vPoTypes );
499 500
            }
            Vec_IntFree( vPoNames );
501 502 503
        }
    }

504 505 506 507

    // check if there are other types of information to read
    if ( pCur + 1 < (unsigned char *)pContents + nFileSize && *pCur == 'c' )
    {
508
        int fVerbose = XAIG_VERBOSE;
509
        Vec_Str_t * vStr;
510
        unsigned char * pCurTemp;
511
        pCur++;
512
        // skip new line if present
513 514
//        if ( *pCur == '\n' )
//            pCur++;
515
        while ( pCur < (unsigned char *)pContents + nFileSize )
516
        {
517 518 519 520
            // read extra AIG
            if ( *pCur == 'a' )
            {
                pCur++;
521
                vStr = Vec_StrStart( Gia_AigerReadInt(pCur) );             pCur += 4;
522 523 524 525
                memcpy( Vec_StrArray(vStr), pCur, Vec_StrSize(vStr) );
                pCur += Vec_StrSize(vStr);
                pNew->pAigExtra = Gia_AigerReadFromMemory( Vec_StrArray(vStr), Vec_StrSize(vStr), 0, 0 );
                Vec_StrFree( vStr );
526
                if ( fVerbose ) printf( "Finished reading extension \"a\".\n" );
527 528 529 530 531
            }
            // read number of constraints
            else if ( *pCur == 'c' )
            {
                pCur++;
532 533
                assert( Gia_AigerReadInt(pCur) == 4 );                     pCur += 4;
                pNew->nConstrs = Gia_AigerReadInt( pCur );                 pCur += 4;
534
                if ( fVerbose ) printf( "Finished reading extension \"c\".\n" );
535 536
            }
            // read delay information
537 538 539 540 541 542 543
            else if ( *pCur == 'd' )
            {
                pCur++;
                assert( Gia_AigerReadInt(pCur) == 4 );                     pCur += 4;
                pNew->nAnd2Delay = Gia_AigerReadInt(pCur);                 pCur += 4;
                if ( fVerbose ) printf( "Finished reading extension \"d\".\n" );
            }
544
            else if ( *pCur == 'i' )
545 546
            {
                pCur++;
547 548 549
                nInputs = Gia_AigerReadInt(pCur)/4;                        pCur += 4;
                pNew->vInArrs  = Vec_FltStart( nInputs );
                memcpy( Vec_FltArray(pNew->vInArrs),  pCur, 4*nInputs );   pCur += 4*nInputs;
550
                if ( fVerbose ) printf( "Finished reading extension \"i\".\n" );
551 552 553 554 555 556 557
            }
            else if ( *pCur == 'o' )
            {
                pCur++;
                nOutputs = Gia_AigerReadInt(pCur)/4;                       pCur += 4;
                pNew->vOutReqs  = Vec_FltStart( nOutputs );
                memcpy( Vec_FltArray(pNew->vOutReqs),  pCur, 4*nOutputs ); pCur += 4*nOutputs;
558
                if ( fVerbose ) printf( "Finished reading extension \"o\".\n" );
559
            }
560
            // read equivalence classes
561 562 563 564
            else if ( *pCur == 'e' )
            {
                extern Gia_Rpr_t * Gia_AigerReadEquivClasses( unsigned char ** ppPos, int nSize );
                pCur++;
565
                pCurTemp = pCur + Gia_AigerReadInt(pCur) + 4;              pCur += 4;
566 567
                pNew->pReprs = Gia_AigerReadEquivClasses( &pCur, Gia_ManObjNum(pNew) );
                pNew->pNexts = Gia_ManDeriveNexts( pNew );
568
                assert( pCur == pCurTemp );
569
                if ( fVerbose ) printf( "Finished reading extension \"e\".\n" );
570
            }
571
            // read flop classes
572 573 574 575 576 577
            else if ( *pCur == 'f' )
            {
                pCur++;
                assert( Gia_AigerReadInt(pCur) == 4*Gia_ManRegNum(pNew) );   pCur += 4;
                pNew->vFlopClasses  = Vec_IntStart( Gia_ManRegNum(pNew) );
                memcpy( Vec_IntArray(pNew->vFlopClasses),  pCur, 4*Gia_ManRegNum(pNew) );   pCur += 4*Gia_ManRegNum(pNew);
578
                if ( fVerbose ) printf( "Finished reading extension \"f\".\n" );
579
            }
580
            // read gate classes
581 582 583 584 585 586
            else if ( *pCur == 'g' )
            {
                pCur++;
                assert( Gia_AigerReadInt(pCur) == 4*Gia_ManObjNum(pNew) );   pCur += 4;
                pNew->vGateClasses  = Vec_IntStart( Gia_ManObjNum(pNew) );
                memcpy( Vec_IntArray(pNew->vGateClasses),  pCur, 4*Gia_ManObjNum(pNew) );   pCur += 4*Gia_ManObjNum(pNew);
587
                if ( fVerbose ) printf( "Finished reading extension \"g\".\n" );
588 589 590 591 592 593 594 595 596 597
            }
            // read hierarchy information
            else if ( *pCur == 'h' )
            {
                pCur++;
                vStr = Vec_StrStart( Gia_AigerReadInt(pCur) );          pCur += 4;
                memcpy( Vec_StrArray(vStr), pCur, Vec_StrSize(vStr) );
                pCur += Vec_StrSize(vStr);
                pNew->pManTime = Tim_ManLoad( vStr, 1 );
                Vec_StrFree( vStr );
598
                fHieOnly = 1;
599
                if ( fVerbose ) printf( "Finished reading extension \"h\".\n" );
600 601 602 603 604
            }
            // read packing
            else if ( *pCur == 'k' )
            {
                extern Vec_Int_t * Gia_AigerReadPacking( unsigned char ** ppPos, int nSize );
605
                int nSize;
606
                pCur++;
607 608 609
                nSize = Gia_AigerReadInt(pCur);
                pCurTemp = pCur + nSize + 4;                            pCur += 4;
                pNew->vPacking = Gia_AigerReadPacking( &pCur, nSize ); 
610
                assert( pCur == pCurTemp );
611
                if ( fVerbose ) printf( "Finished reading extension \"k\".\n" );
612
            }
613
            // read mapping
614 615 616
            else if ( *pCur == 'm' )
            {
                extern int * Gia_AigerReadMapping( unsigned char ** ppPos, int nSize );
617
                extern int * Gia_AigerReadMappingSimple( unsigned char ** ppPos, int nSize );
618 619
                extern Vec_Int_t * Gia_AigerReadMappingDoc( unsigned char ** ppPos, int nObjs );
                int nSize;
620
                pCur++;
621 622
                nSize = Gia_AigerReadInt(pCur);
                pCurTemp = pCur + nSize + 4;           pCur += 4;
623
                pNew->vMapping = Gia_AigerReadMappingDoc( &pCur, Gia_ManObjNum(pNew) );
624
                assert( pCur == pCurTemp );
625
                if ( fVerbose ) printf( "Finished reading extension \"m\".\n" );
626 627 628 629 630 631 632 633 634 635 636
            }
            // read model name
            else if ( *pCur == 'n' )
            {
                pCur++;
                if ( (*pCur >= 'a' && *pCur <= 'z') || (*pCur >= 'A' && *pCur <= 'Z') || (*pCur >= '0' && *pCur <= '9') )
                {
                    pNew->pName = Abc_UtilStrsav( (char *)pCur );       pCur += strlen(pNew->pName) + 1;
                }
                else
                {
637
                    pCurTemp = pCur + Gia_AigerReadInt(pCur) + 4;       pCur += 4;
638 639 640 641 642
                    ABC_FREE( pNew->pName );
                    pNew->pName = Abc_UtilStrsav( (char *)pCur );       pCur += strlen(pNew->pName) + 1;
                    assert( pCur == pCurTemp );
                }
            }
643
            // read placement
644 645 646 647
            else if ( *pCur == 'p' )
            {
                Gia_Plc_t * pPlacement;
                pCur++;
648
                pCurTemp = pCur + Gia_AigerReadInt(pCur) + 4;           pCur += 4;
649 650 651
                pPlacement = ABC_ALLOC( Gia_Plc_t, Gia_ManObjNum(pNew) );
                memcpy( pPlacement, pCur, 4*Gia_ManObjNum(pNew) );      pCur += 4*Gia_ManObjNum(pNew);
                assert( pCur == pCurTemp );
652
                pNew->pPlacement = pPlacement;
653
                if ( fVerbose ) printf( "Finished reading extension \"p\".\n" );
654
            }
655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673
            // read choices
            else if ( *pCur == 'q' )
            {
                int i, nPairs, iRepr, iNode;
                assert( pNew->pSibls == NULL );
                pNew->pSibls = ABC_CALLOC( int, Gia_ManObjNum(pNew) );
                pCur++;
                pCurTemp = pCur + Gia_AigerReadInt(pCur) + 4;           pCur += 4;
                nPairs = Gia_AigerReadInt(pCur);                        pCur += 4;
                for ( i = 0; i < nPairs; i++ )
                {
                    iRepr = Gia_AigerReadInt(pCur);                     pCur += 4;
                    iNode = Gia_AigerReadInt(pCur);                     pCur += 4;
                    pNew->pSibls[iRepr] = iNode;
                    assert( iRepr > iNode );
                }
                assert( pCur == pCurTemp );
                if ( fVerbose ) printf( "Finished reading extension \"q\".\n" );
            }
674
            // read switching activity
675
            else if ( *pCur == 'u' )
676 677 678
            { 
                unsigned char * pSwitching;
                pCur++;
679
                pCurTemp = pCur + Gia_AigerReadInt(pCur) + 4;           pCur += 4;
680 681 682
                pSwitching = ABC_ALLOC( unsigned char, Gia_ManObjNum(pNew) );
                memcpy( pSwitching, pCur, Gia_ManObjNum(pNew) );        pCur += Gia_ManObjNum(pNew);
                assert( pCur == pCurTemp );
683
                if ( fVerbose ) printf( "Finished reading extension \"s\".\n" );
684
            }
685
            // read timing manager
686 687 688 689 690 691 692
            else if ( *pCur == 't' )
            {
                pCur++;
                vStr = Vec_StrStart( Gia_AigerReadInt(pCur) );          pCur += 4;
                memcpy( Vec_StrArray(vStr), pCur, Vec_StrSize(vStr) );  pCur += Vec_StrSize(vStr);
                pNew->pManTime = Tim_ManLoad( vStr, 0 );
                Vec_StrFree( vStr );
693
                if ( fVerbose ) printf( "Finished reading extension \"t\".\n" );
694 695 696 697 698 699 700 701
            }
            // read object classes
            else if ( *pCur == 'v' )
            {
                pCur++;
                pNew->vObjClasses = Vec_IntStart( Gia_AigerReadInt(pCur)/4 ); pCur += 4;
                memcpy( Vec_IntArray(pNew->vObjClasses), pCur, 4*Vec_IntSize(pNew->vObjClasses) );
                pCur += 4*Vec_IntSize(pNew->vObjClasses);
702
                if ( fVerbose ) printf( "Finished reading extension \"v\".\n" );
703 704
            }
            else break;
705 706 707
        }
    }

708 709
    // skipping the comments
    Vec_IntFree( vNodes );
710 711 712 713 714

    // update polarity of the additional outputs
    if ( nBad || nConstr || nJust || nFair )
        Gia_ManInvertConstraints( pNew );

715 716 717 718 719 720 721
    // clean the PO drivers
    if ( vPoTypes )
    {
        pNew = Gia_ManDupWithConstraints( pTemp = pNew, vPoTypes );
        Gia_ManStop( pTemp );
        Vec_IntFreeP( &vPoTypes );
    }
722

723
    if ( !fSkipStrash && Gia_ManHasDangling(pNew) )
724
    {
725
        Tim_Man_t * pManTime;
726
        Vec_Int_t * vFlopMap, * vGateMap, * vObjMap;
727
        vFlopMap = pNew->vFlopClasses; pNew->vFlopClasses = NULL;
728
        vGateMap = pNew->vGateClasses; pNew->vGateClasses = NULL;
729
        vObjMap  = pNew->vObjClasses;  pNew->vObjClasses  = NULL;
730
        pManTime = (Tim_Man_t *)pNew->pManTime; pNew->pManTime     = NULL;
731
        pNew = Gia_ManCleanup( pTemp = pNew );
732 733
        if ( (vGateMap || vObjMap) && (Gia_ManObjNum(pNew) < Gia_ManObjNum(pTemp)) )
            printf( "Cleanup removed objects after reading. Old gate/object abstraction maps are invalid!\n" );
734 735
        Gia_ManStop( pTemp );
        pNew->vFlopClasses = vFlopMap;
736
        pNew->vGateClasses = vGateMap;
737
        pNew->vObjClasses  = vObjMap;
738
        pNew->pManTime     = pManTime;
739
    }
740 741 742

    if ( fHieOnly )
    {
743
//        Tim_ManPrint( (Tim_Man_t *)pNew->pManTime );
744 745 746 747
        if ( Abc_FrameReadLibBox() == NULL )
            printf( "Cannot create TIM manager because box library is not available.\n" );
        else
            Tim_ManCreate( (Tim_Man_t *)pNew->pManTime, Abc_FrameReadLibBox(), pNew->vInArrs, pNew->vOutReqs );
748
    }
749 750
    Vec_FltFreeP( &pNew->vInArrs );
    Vec_FltFreeP( &pNew->vOutReqs );
751 752 753 754 755 756 757 758 759
/*
    // check the result
    if ( fCheck && !Gia_ManCheck( pNew ) )
    {
        printf( "Gia_AigerRead: The network check has failed.\n" );
        Gia_ManStop( pNew );
        return NULL;
    }
*/
760

761 762 763 764 765 766 767 768 769 770 771 772 773 774 775
    if ( vInits && Vec_IntSum(vInits) )
    {
        char * pInit = ABC_ALLOC( char, Vec_IntSize(vInits) + 1 );
        Gia_Obj_t * pObj;
        int i;
        assert( Vec_IntSize(vInits) == Gia_ManRegNum(pNew) );
        Gia_ManForEachRo( pNew, pObj, i )
        {
            if ( Vec_IntEntry(vInits, i) == 0 )
                pInit[i] = '0';
            else if ( Vec_IntEntry(vInits, i) == 1 )
                pInit[i] = '1';
            else 
            {
                assert( Vec_IntEntry(vInits, i) == Abc_Var2Lit(Gia_ObjId(pNew, pObj), 0) );
776
                // unitialized value of the latch is the latch literal according to http://fmv.jku.at/hwmcc11/beyond1.pdf
777 778 779 780 781 782 783 784 785 786
                pInit[i] = 'X';
            }
        }
        pInit[i] = 0;
        pNew = Gia_ManDupZeroUndc( pTemp = pNew, pInit, 1 );
        pNew->nConstrs = pTemp->nConstrs; pTemp->nConstrs = 0;
        Gia_ManStop( pTemp );
        ABC_FREE( pInit );
    }
    Vec_IntFreeP( &vInits );
787 788
    if ( !fSkipStrash && pNew->vMapping )
        Abc_Print( 0, "Structural hashing enabled while reading AIGER may have invalidated the mapping.  Consider using \"&r -s\".\n" );
789 790 791 792 793 794 795 796 797 798 799 800 801 802
    return pNew;
}

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

  Synopsis    [Reads the AIG in the binary AIGER format.]

  Description []
  
  SideEffects []

  SeeAlso     []

***********************************************************************/
803
Gia_Man_t * Gia_AigerRead( char * pFileName, int fSkipStrash, int fCheck )
804 805 806 807 808
{
    FILE * pFile;
    Gia_Man_t * pNew;
    char * pName, * pContents;
    int nFileSize;
809
    int RetValue;
810 811

    // read the file into the buffer
812
    Gia_FileFixName( pFileName );
813 814 815
    nFileSize = Gia_FileSize( pFileName );
    pFile = fopen( pFileName, "rb" );
    pContents = ABC_ALLOC( char, nFileSize );
816
    RetValue = fread( pContents, nFileSize, 1, pFile );
817 818
    fclose( pFile );

819
    pNew = Gia_AigerReadFromMemory( pContents, nFileSize, fSkipStrash, fCheck );
820 821 822
    ABC_FREE( pContents );
    if ( pNew )
    {
823
        ABC_FREE( pNew->pName );
824
        pName = Gia_FileNameGeneric( pFileName );
825
        pNew->pName = Abc_UtilStrsav( pName );
826
        ABC_FREE( pName );
827 828 829

        assert( pNew->pSpec == NULL );
        pNew->pSpec = Abc_UtilStrsav( pFileName );
830 831 832 833 834 835 836 837
    }
    return pNew;
}



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

838
  Synopsis    [Writes the AIG in into the memory buffer.]
Alan Mishchenko committed
839

840 841
  Description [The resulting buffer constains the AIG in AIGER format. 
  The resulting buffer should be deallocated by the user.]
Alan Mishchenko committed
842 843 844 845 846 847
  
  SideEffects []

  SeeAlso     []

***********************************************************************/
848
Vec_Str_t * Gia_AigerWriteIntoMemoryStr( Gia_Man_t * p )
Alan Mishchenko committed
849
{
850
    Vec_Str_t * vBuffer;
Alan Mishchenko committed
851
    Gia_Obj_t * pObj;
852 853 854 855 856 857 858
    int nNodes = 0, i, uLit, uLit0, uLit1; 
    // set the node numbers to be used in the output file
    Gia_ManConst0(p)->Value = nNodes++;
    Gia_ManForEachCi( p, pObj, i )
        pObj->Value = nNodes++;
    Gia_ManForEachAnd( p, pObj, i )
        pObj->Value = nNodes++;
Alan Mishchenko committed
859

860 861 862 863 864 865 866 867 868 869 870 871 872
    // write the header "M I L O A" where M = I + L + A
    vBuffer = Vec_StrAlloc( 3*Gia_ManObjNum(p) );
    Vec_StrPrintStr( vBuffer, "aig " );
    Vec_StrPrintNum( vBuffer, Gia_ManCandNum(p) );
    Vec_StrPrintStr( vBuffer, " " );
    Vec_StrPrintNum( vBuffer, Gia_ManPiNum(p) );
    Vec_StrPrintStr( vBuffer, " " );
    Vec_StrPrintNum( vBuffer, Gia_ManRegNum(p) );
    Vec_StrPrintStr( vBuffer, " " );
    Vec_StrPrintNum( vBuffer, Gia_ManPoNum(p) );
    Vec_StrPrintStr( vBuffer, " " );
    Vec_StrPrintNum( vBuffer, Gia_ManAndNum(p) );
    Vec_StrPrintStr( vBuffer, "\n" );
Alan Mishchenko committed
873

874 875 876 877 878 879 880
    // write latch drivers
    Gia_ManForEachRi( p, pObj, i )
    {
        uLit = Abc_Var2Lit( Gia_ObjValue(Gia_ObjFanin0(pObj)), Gia_ObjFaninC0(pObj) );
        Vec_StrPrintNum( vBuffer, uLit );
        Vec_StrPrintStr( vBuffer, "\n" );
    }
Alan Mishchenko committed
881

882 883
    // write PO drivers
    Gia_ManForEachPo( p, pObj, i )
Alan Mishchenko committed
884
    {
885 886 887
        uLit = Abc_Var2Lit( Gia_ObjValue(Gia_ObjFanin0(pObj)), Gia_ObjFaninC0(pObj) );
        Vec_StrPrintNum( vBuffer, uLit );
        Vec_StrPrintStr( vBuffer, "\n" );
Alan Mishchenko committed
888
    }
889 890
    // write the nodes into the buffer
    Gia_ManForEachAnd( p, pObj, i )
Alan Mishchenko committed
891
    {
892 893 894 895 896
        uLit  = Abc_Var2Lit( Gia_ObjValue(pObj), 0 );
        uLit0 = Abc_Var2Lit( Gia_ObjValue(Gia_ObjFanin0(pObj)), Gia_ObjFaninC0(pObj) );
        uLit1 = Abc_Var2Lit( Gia_ObjValue(Gia_ObjFanin1(pObj)), Gia_ObjFaninC1(pObj) );
        assert( uLit0 != uLit1 );
        if ( uLit0 > uLit1 )
Alan Mishchenko committed
897
        {
898 899 900
            int Temp = uLit0;
            uLit0 = uLit1;
            uLit1 = Temp;
Alan Mishchenko committed
901
        }
902 903
        Gia_AigerWriteUnsigned( vBuffer, uLit  - uLit1 );
        Gia_AigerWriteUnsigned( vBuffer, uLit1 - uLit0 );
Alan Mishchenko committed
904
    }
905 906
    Vec_StrPrintStr( vBuffer, "c" );
    return vBuffer;
Alan Mishchenko committed
907 908 909 910
}

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

911
  Synopsis    [Writes the AIG in into the memory buffer.]
Alan Mishchenko committed
912

913 914 915
  Description [The resulting buffer constains the AIG in AIGER format.
  The CI/CO/AND nodes are assumed to be ordered according to some rule.
  The resulting buffer should be deallocated by the user.]
Alan Mishchenko committed
916
  
917
  SideEffects [Note that in vCos, PIs are order first, followed by latches!]
Alan Mishchenko committed
918 919 920 921

  SeeAlso     []

***********************************************************************/
922
Vec_Str_t * Gia_AigerWriteIntoMemoryStrPart( Gia_Man_t * p, Vec_Int_t * vCis, Vec_Int_t * vAnds, Vec_Int_t * vCos, int nRegs )
Alan Mishchenko committed
923
{
924 925 926 927 928 929 930 931 932 933 934 935 936 937 938
    Vec_Str_t * vBuffer;
    Gia_Obj_t * pObj;
    int nNodes = 0, i, uLit, uLit0, uLit1; 
    // set the node numbers to be used in the output file
    Gia_ManConst0(p)->Value = nNodes++;
    Gia_ManForEachObjVec( vCis, p, pObj, i )
    {
        assert( Gia_ObjIsCi(pObj) );
        pObj->Value = nNodes++;
    }
    Gia_ManForEachObjVec( vAnds, p, pObj, i )
    {
        assert( Gia_ObjIsAnd(pObj) );
        pObj->Value = nNodes++;
    }
Alan Mishchenko committed
939

940 941 942 943 944 945 946 947 948 949 950 951 952
    // write the header "M I L O A" where M = I + L + A
    vBuffer = Vec_StrAlloc( 3*Gia_ManObjNum(p) );
    Vec_StrPrintStr( vBuffer, "aig " );
    Vec_StrPrintNum( vBuffer, Vec_IntSize(vCis) + Vec_IntSize(vAnds) );
    Vec_StrPrintStr( vBuffer, " " );
    Vec_StrPrintNum( vBuffer, Vec_IntSize(vCis) - nRegs );
    Vec_StrPrintStr( vBuffer, " " );
    Vec_StrPrintNum( vBuffer, nRegs );
    Vec_StrPrintStr( vBuffer, " " );
    Vec_StrPrintNum( vBuffer, Vec_IntSize(vCos) - nRegs );
    Vec_StrPrintStr( vBuffer, " " );
    Vec_StrPrintNum( vBuffer, Vec_IntSize(vAnds) );
    Vec_StrPrintStr( vBuffer, "\n" );
Alan Mishchenko committed
953

954 955
    // write latch drivers
    Gia_ManForEachObjVec( vCos, p, pObj, i )
Alan Mishchenko committed
956
    {
957 958
        assert( Gia_ObjIsCo(pObj) );
        if ( i < Vec_IntSize(vCos) - nRegs )
Alan Mishchenko committed
959
            continue;
960 961 962
        uLit = Abc_Var2Lit( Gia_ObjValue(Gia_ObjFanin0(pObj)), Gia_ObjFaninC0(pObj) );
        Vec_StrPrintNum( vBuffer, uLit );
        Vec_StrPrintStr( vBuffer, "\n" );
Alan Mishchenko committed
963
    }
964 965
    // write output drivers
    Gia_ManForEachObjVec( vCos, p, pObj, i )
Alan Mishchenko committed
966
    {
967 968 969 970 971 972
        assert( Gia_ObjIsCo(pObj) );
        if ( i >= Vec_IntSize(vCos) - nRegs )
            continue;
        uLit = Abc_Var2Lit( Gia_ObjValue(Gia_ObjFanin0(pObj)), Gia_ObjFaninC0(pObj) );
        Vec_StrPrintNum( vBuffer, uLit );
        Vec_StrPrintStr( vBuffer, "\n" );
Alan Mishchenko committed
973 974
    }

975 976
    // write the nodes into the buffer
    Gia_ManForEachObjVec( vAnds, p, pObj, i )
Alan Mishchenko committed
977
    {
978 979 980 981 982
        uLit  = Abc_Var2Lit( Gia_ObjValue(pObj), 0 );
        uLit0 = Abc_Var2Lit( Gia_ObjValue(Gia_ObjFanin0(pObj)), Gia_ObjFaninC0(pObj) );
        uLit1 = Abc_Var2Lit( Gia_ObjValue(Gia_ObjFanin1(pObj)), Gia_ObjFaninC1(pObj) );
        assert( uLit0 != uLit1 );
        if ( uLit0 > uLit1 )
Alan Mishchenko committed
983
        {
984 985 986
            int Temp = uLit0;
            uLit0 = uLit1;
            uLit1 = Temp;
Alan Mishchenko committed
987
        }
988 989
        Gia_AigerWriteUnsigned( vBuffer, uLit  - uLit1 );
        Gia_AigerWriteUnsigned( vBuffer, uLit1 - uLit0 );
Alan Mishchenko committed
990
    }
991 992
    Vec_StrPrintStr( vBuffer, "c" );
    return vBuffer;
Alan Mishchenko committed
993 994 995 996
}

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

Alan Mishchenko committed
997 998 999 1000 1001 1002 1003 1004 1005
  Synopsis    [Writes the AIG in the binary AIGER format.]

  Description []
  
  SideEffects []

  SeeAlso     []

***********************************************************************/
1006
void Gia_AigerWrite( Gia_Man_t * pInit, char * pFileName, int fWriteSymbols, int fCompact )
Alan Mishchenko committed
1007
{
1008
    int fVerbose = XAIG_VERBOSE;
Alan Mishchenko committed
1009 1010 1011
    FILE * pFile;
    Gia_Man_t * p;
    Gia_Obj_t * pObj;
1012
    Vec_Str_t * vStrExt;
Alan Mishchenko committed
1013 1014 1015
    int i, nBufferSize, Pos;
    unsigned char * pBuffer;
    unsigned uLit0, uLit1, uLit;
1016
//    assert( Gia_ManIsNormalized(pInit) );
1017
    assert( pInit->nXors == 0 && pInit->nMuxes == 0 );
Alan Mishchenko committed
1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028

    if ( Gia_ManCoNum(pInit) == 0 )
    {
        printf( "AIG cannot be written because it has no POs.\n" );
        return;
    }

    // start the output stream
    pFile = fopen( pFileName, "wb" );
    if ( pFile == NULL )
    {
1029
        fprintf( stdout, "Gia_AigerWrite(): Cannot open the output file \"%s\".\n", pFileName );
Alan Mishchenko committed
1030 1031 1032 1033 1034
        return;
    }

    // create normalized AIG
    if ( !Gia_ManIsNormalized(pInit) )
Alan Mishchenko committed
1035
    {
1036
//        printf( "Gia_AigerWrite(): Normalizing AIG for writing.\n" );
1037
        p = Gia_ManDupNormalize( pInit );
1038 1039 1040 1041 1042
        p->pManTime   = pInit->pManTime;   pInit->pManTime   = NULL;
        p->vNamesIn   = pInit->vNamesIn;   pInit->vNamesIn   = NULL;
        p->vNamesOut  = pInit->vNamesOut;  pInit->vNamesOut  = NULL;
        p->pAigExtra  = pInit->pAigExtra;  pInit->pAigExtra  = NULL;
        p->nAnd2Delay = pInit->nAnd2Delay; pInit->nAnd2Delay = 0;
1043
        p->nConstrs   = pInit->nConstrs;   pInit->nConstrs   = 0;
Alan Mishchenko committed
1044
    }
Alan Mishchenko committed
1045 1046 1047 1048
    else
        p = pInit;

    // write the header "M I L O A" where M = I + L + A
1049
    fprintf( pFile, "aig%s %u %u %u %u %u", 
Alan Mishchenko committed
1050 1051 1052 1053
        fCompact? "2" : "",
        Gia_ManCiNum(p) + Gia_ManAndNum(p), 
        Gia_ManPiNum(p),
        Gia_ManRegNum(p),
1054
        Gia_ManConstrNum(p) ? 0 : Gia_ManPoNum(p),
Alan Mishchenko committed
1055
        Gia_ManAndNum(p) );
1056 1057 1058 1059
    // write the extended header "B C J F"
    if ( Gia_ManConstrNum(p) )
        fprintf( pFile, " %u %u", Gia_ManPoNum(p) - Gia_ManConstrNum(p), Gia_ManConstrNum(p) );
    fprintf( pFile, "\n" ); 
Alan Mishchenko committed
1060

1061
    Gia_ManInvertConstraints( p );
Alan Mishchenko committed
1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072
    if ( !fCompact ) 
    {
        // write latch drivers
        Gia_ManForEachRi( p, pObj, i )
            fprintf( pFile, "%u\n", Gia_ObjFaninLit0p(p, pObj) );
        // write PO drivers
        Gia_ManForEachPo( p, pObj, i )
            fprintf( pFile, "%u\n", Gia_ObjFaninLit0p(p, pObj) );
    }
    else
    {
1073 1074
        Vec_Int_t * vLits = Gia_AigerCollectLiterals( p );
        Vec_Str_t * vBinary = Gia_AigerWriteLiterals( vLits );
Alan Mishchenko committed
1075 1076 1077 1078
        fwrite( Vec_StrArray(vBinary), 1, Vec_StrSize(vBinary), pFile );
        Vec_StrFree( vBinary );
        Vec_IntFree( vLits );
    }
1079
    Gia_ManInvertConstraints( p );
Alan Mishchenko committed
1080 1081 1082

    // write the nodes into the buffer
    Pos = 0;
1083
    nBufferSize = 8 * Gia_ManAndNum(p) + 100; // skeptically assuming 3 chars per one AIG edge
Alan Mishchenko committed
1084 1085 1086
    pBuffer = ABC_ALLOC( unsigned char, nBufferSize );
    Gia_ManForEachAnd( p, pObj, i )
    {
1087
        uLit  = Abc_Var2Lit( i, 0 );
Alan Mishchenko committed
1088 1089
        uLit0 = Gia_ObjFaninLit0( pObj, i );
        uLit1 = Gia_ObjFaninLit1( pObj, i );
1090
        assert( uLit0 < uLit1 );
1091 1092
        Pos = Gia_AigerWriteUnsignedBuffer( pBuffer, Pos, uLit  - uLit1 );
        Pos = Gia_AigerWriteUnsignedBuffer( pBuffer, Pos, uLit1 - uLit0 );
Alan Mishchenko committed
1093 1094
        if ( Pos > nBufferSize - 10 )
        {
1095
            printf( "Gia_AigerWrite(): AIGER generation has failed because the allocated buffer is too small.\n" );
Alan Mishchenko committed
1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107
            fclose( pFile );
            if ( p != pInit )
                Gia_ManStop( p );
            return;
        }
    }
    assert( Pos < nBufferSize );

    // write the buffer
    fwrite( pBuffer, 1, Pos, pFile );
    ABC_FREE( pBuffer );

1108 1109 1110 1111 1112 1113 1114
    // write the symbol table
    if ( p->vNamesIn && p->vNamesOut )
    {
        assert( Vec_PtrSize(p->vNamesIn)  == Gia_ManCiNum(p) );
        assert( Vec_PtrSize(p->vNamesOut) == Gia_ManCoNum(p) );
        // write PIs
        Gia_ManForEachPi( p, pObj, i )
1115
            fprintf( pFile, "i%d %s\n", i, (char *)Vec_PtrEntry(p->vNamesIn, i) );
1116 1117
        // write latches
        Gia_ManForEachRo( p, pObj, i )
1118
            fprintf( pFile, "l%d %s\n", i, (char *)Vec_PtrEntry(p->vNamesIn, Gia_ManPiNum(p) + i) );
1119 1120
        // write POs
        Gia_ManForEachPo( p, pObj, i )
1121
            fprintf( pFile, "o%d %s\n", i, (char *)Vec_PtrEntry(p->vNamesOut, i) );
1122 1123
    }

Alan Mishchenko committed
1124
    // write the comment
1125 1126
//    fprintf( pFile, "c\n" );
    fprintf( pFile, "c" );
1127 1128 1129 1130 1131 1132 1133 1134 1135

    // write additional AIG
    if ( p->pAigExtra )
    {
        fprintf( pFile, "a" );
        vStrExt = Gia_AigerWriteIntoMemoryStr( p->pAigExtra );
        Gia_FileWriteBufferSize( pFile, Vec_StrSize(vStrExt) );
        fwrite( Vec_StrArray(vStrExt), 1, Vec_StrSize(vStrExt), pFile );
        Vec_StrFree( vStrExt );
1136
        if ( fVerbose ) printf( "Finished writing extension \"a\".\n" );
1137 1138 1139 1140 1141 1142 1143 1144
    }
    // write constraints
    if ( p->nConstrs )
    {
        fprintf( pFile, "c" );
        Gia_FileWriteBufferSize( pFile, 4 );
        Gia_FileWriteBufferSize( pFile, p->nConstrs );
    }
1145 1146 1147 1148 1149 1150 1151
    // write timing information
    if ( p->nAnd2Delay )
    {
        fprintf( pFile, "d" );
        Gia_FileWriteBufferSize( pFile, 4 );
        Gia_FileWriteBufferSize( pFile, p->nAnd2Delay );
    }
1152
    if ( p->pManTime )
1153
    {
1154
        float * pTimes;
Alan Mishchenko committed
1155
        pTimes = Tim_ManGetArrTimes( (Tim_Man_t *)p->pManTime );
1156
        if ( pTimes )
1157 1158
        {
            fprintf( pFile, "i" );
1159
            Gia_FileWriteBufferSize( pFile, 4*Tim_ManPiNum((Tim_Man_t *)p->pManTime) );
1160 1161 1162 1163
            fwrite( pTimes, 1, 4*Tim_ManPiNum((Tim_Man_t *)p->pManTime), pFile );
            ABC_FREE( pTimes );
            if ( fVerbose ) printf( "Finished writing extension \"i\".\n" );
        }
Alan Mishchenko committed
1164
        pTimes = Tim_ManGetReqTimes( (Tim_Man_t *)p->pManTime );
1165 1166
        if ( pTimes )
        {
1167
            fprintf( pFile, "o" );
1168
            Gia_FileWriteBufferSize( pFile, 4*Tim_ManPoNum((Tim_Man_t *)p->pManTime) );
1169 1170
            fwrite( pTimes, 1, 4*Tim_ManPoNum((Tim_Man_t *)p->pManTime), pFile );
            ABC_FREE( pTimes );
1171
            if ( fVerbose ) printf( "Finished writing extension \"o\".\n" );
1172
        }
1173
    }
Alan Mishchenko committed
1174 1175 1176
    // write equivalences
    if ( p->pReprs && p->pNexts )
    {
1177
        extern Vec_Str_t * Gia_WriteEquivClasses( Gia_Man_t * p );
Alan Mishchenko committed
1178
        fprintf( pFile, "e" );
1179
        vStrExt = Gia_WriteEquivClasses( p );
1180
        Gia_FileWriteBufferSize( pFile, Vec_StrSize(vStrExt) );
1181 1182
        fwrite( Vec_StrArray(vStrExt), 1, Vec_StrSize(vStrExt), pFile );
        Vec_StrFree( vStrExt );
Alan Mishchenko committed
1183
    }
Alan Mishchenko committed
1184 1185 1186 1187
    // write flop classes
    if ( p->vFlopClasses )
    {
        fprintf( pFile, "f" );
1188 1189 1190
        Gia_FileWriteBufferSize( pFile, 4*Gia_ManRegNum(p) );
        assert( Vec_IntSize(p->vFlopClasses) == Gia_ManRegNum(p) );
        fwrite( Vec_IntArray(p->vFlopClasses), 1, 4*Gia_ManRegNum(p), pFile );
Alan Mishchenko committed
1191
    }
1192 1193 1194 1195
    // write gate classes
    if ( p->vGateClasses )
    {
        fprintf( pFile, "g" );
1196 1197 1198
        Gia_FileWriteBufferSize( pFile, 4*Gia_ManObjNum(p) );
        assert( Vec_IntSize(p->vGateClasses) == Gia_ManObjNum(p) );
        fwrite( Vec_IntArray(p->vGateClasses), 1, 4*Gia_ManObjNum(p), pFile );
1199
    }
1200 1201
    // write hierarchy info
    if ( p->pManTime )
1202
    {
1203 1204 1205 1206 1207
        fprintf( pFile, "h" );
        vStrExt = Tim_ManSave( (Tim_Man_t *)p->pManTime, 1 );
        Gia_FileWriteBufferSize( pFile, Vec_StrSize(vStrExt) );
        fwrite( Vec_StrArray(vStrExt), 1, Vec_StrSize(vStrExt), pFile );
        Vec_StrFree( vStrExt );
1208
        if ( fVerbose ) printf( "Finished writing extension \"h\".\n" );
1209 1210 1211 1212 1213 1214 1215 1216 1217 1218
    }
    // write packing
    if ( p->vPacking )
    {
        extern Vec_Str_t * Gia_WritePacking( Vec_Int_t * vPacking );
        fprintf( pFile, "k" );
        vStrExt = Gia_WritePacking( p->vPacking );
        Gia_FileWriteBufferSize( pFile, Vec_StrSize(vStrExt) );
        fwrite( Vec_StrArray(vStrExt), 1, Vec_StrSize(vStrExt), pFile );
        Vec_StrFree( vStrExt );
1219
        if ( fVerbose ) printf( "Finished writing extension \"k\".\n" );
1220
    }
Alan Mishchenko committed
1221
    // write mapping
1222
    if ( Gia_ManHasMapping(p) )
Alan Mishchenko committed
1223
    {
1224
        extern Vec_Str_t * Gia_AigerWriteMapping( Gia_Man_t * p );
1225
        extern Vec_Str_t * Gia_AigerWriteMappingSimple( Gia_Man_t * p );
1226
        extern Vec_Str_t * Gia_AigerWriteMappingDoc( Gia_Man_t * p );
Alan Mishchenko committed
1227
        fprintf( pFile, "m" );
1228
        vStrExt = Gia_AigerWriteMappingDoc( p );
1229 1230 1231
        Gia_FileWriteBufferSize( pFile, Vec_StrSize(vStrExt) );
        fwrite( Vec_StrArray(vStrExt), 1, Vec_StrSize(vStrExt), pFile );
        Vec_StrFree( vStrExt );
1232
        if ( fVerbose ) printf( "Finished writing extension \"m\".\n" );
1233
    }
Alan Mishchenko committed
1234
    // write placement
Alan Mishchenko committed
1235 1236 1237
    if ( p->pPlacement )
    {
        fprintf( pFile, "p" );
1238 1239
        Gia_FileWriteBufferSize( pFile, 4*Gia_ManObjNum(p) );
        fwrite( p->pPlacement, 1, 4*Gia_ManObjNum(p), pFile );
Alan Mishchenko committed
1240
    }
1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258
    // write choices
    if ( p->pSibls )
    {
        int i, nPairs = 0;
        fprintf( pFile, "q" );
        for ( i = 0; i < Gia_ManObjNum(p); i++ )
            nPairs += (Gia_ObjSibl(p, i) > 0);
        Gia_FileWriteBufferSize( pFile, 4*(nPairs * 2 + 1) );
        Gia_FileWriteBufferSize( pFile, nPairs );
        for ( i = 0; i < Gia_ManObjNum(p); i++ )
            if ( Gia_ObjSibl(p, i) )
            {
                assert( i > Gia_ObjSibl(p, i) );
                Gia_FileWriteBufferSize( pFile, i );
                Gia_FileWriteBufferSize( pFile, Gia_ObjSibl(p, i) );
            }
        if ( fVerbose ) printf( "Finished writing extension \"q\".\n" );
    }
1259
    // write switching activity
Alan Mishchenko committed
1260 1261
    if ( p->pSwitching )
    {
1262
        fprintf( pFile, "u" );
1263 1264
        Gia_FileWriteBufferSize( pFile, Gia_ManObjNum(p) );
        fwrite( p->pSwitching, 1, Gia_ManObjNum(p), pFile );
Alan Mishchenko committed
1265
    }
1266
/*
1267 1268 1269 1270
    // write timing information
    if ( p->pManTime )
    {
        fprintf( pFile, "t" );
1271 1272 1273 1274
        vStrExt = Tim_ManSave( (Tim_Man_t *)p->pManTime, 0 );
        Gia_FileWriteBufferSize( pFile, Vec_StrSize(vStrExt) );
        fwrite( Vec_StrArray(vStrExt), 1, Vec_StrSize(vStrExt), pFile );
        Vec_StrFree( vStrExt );
1275
    }
1276
*/
1277 1278
    // write object classes
    if ( p->vObjClasses )
1279
    {
1280 1281 1282 1283
        fprintf( pFile, "v" );
        Gia_FileWriteBufferSize( pFile, 4*Gia_ManObjNum(p) );
        assert( Vec_IntSize(p->vObjClasses) == Gia_ManObjNum(p) );
        fwrite( Vec_IntArray(p->vObjClasses), 1, 4*Gia_ManObjNum(p), pFile );
1284
    }
1285 1286 1287 1288 1289 1290 1291 1292
    // write name
    if ( p->pName )
    {
        fprintf( pFile, "n" );
        Gia_FileWriteBufferSize( pFile, strlen(p->pName)+1 );
        fwrite( p->pName, 1, strlen(p->pName), pFile );
        fprintf( pFile, "%c", '\0' );
    }
1293
    // write comments
Alan Mishchenko committed
1294
    fprintf( pFile, "\nThis file was produced by the GIA package in ABC on %s\n", Gia_TimeStamp() );
Alan Mishchenko committed
1295 1296 1297
    fprintf( pFile, "For information about AIGER format, refer to %s\n", "http://fmv.jku.at/aiger" );
    fclose( pFile );
    if ( p != pInit )
Alan Mishchenko committed
1298 1299 1300 1301
    {
        pInit->pManTime  = p->pManTime;  p->pManTime = NULL;
        pInit->vNamesIn  = p->vNamesIn;  p->vNamesIn = NULL;
        pInit->vNamesOut = p->vNamesOut; p->vNamesOut = NULL;
Alan Mishchenko committed
1302
        Gia_ManStop( p );
Alan Mishchenko committed
1303
    }
Alan Mishchenko committed
1304 1305
}

Alan Mishchenko committed
1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320
/**Function*************************************************************

  Synopsis    [Writes the AIG in the binary AIGER format.]

  Description []
  
  SideEffects []

  SeeAlso     []

***********************************************************************/
void Gia_DumpAiger( Gia_Man_t * p, char * pFilePrefix, int iFileNum, int nFileNumDigits )
{
    char Buffer[100];
    sprintf( Buffer, "%s%0*d.aig", pFilePrefix, nFileNumDigits, iFileNum );
1321
    Gia_AigerWrite( p, Buffer, 0, 0 );
1322 1323
}

1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334
/**Function*************************************************************

  Synopsis    [Writes the AIG in the binary AIGER format.]

  Description []
  
  SideEffects []

  SeeAlso     []

***********************************************************************/
1335
void Gia_AigerWriteSimple( Gia_Man_t * pInit, char * pFileName )
1336 1337 1338 1339 1340
{
    FILE * pFile;
    Vec_Str_t * vStr;
    if ( Gia_ManPoNum(pInit) == 0 )
    {
1341
        printf( "Gia_AigerWriteSimple(): AIG cannot be written because it has no POs.\n" );
1342 1343 1344 1345 1346 1347
        return;
    }
    // start the output stream
    pFile = fopen( pFileName, "wb" );
    if ( pFile == NULL )
    {
1348
        fprintf( stdout, "Gia_AigerWriteSimple(): Cannot open the output file \"%s\".\n", pFileName );
1349 1350 1351
        return;
    }
    // write the buffer
1352
    vStr = Gia_AigerWriteIntoMemoryStr( pInit );
1353 1354 1355 1356 1357
    fwrite( Vec_StrArray(vStr), 1, Vec_StrSize(vStr), pFile );
    Vec_StrFree( vStr );
    fclose( pFile );
}

Alan Mishchenko committed
1358 1359 1360 1361 1362
////////////////////////////////////////////////////////////////////////
///                       END OF FILE                                ///
////////////////////////////////////////////////////////////////////////


1363 1364
ABC_NAMESPACE_IMPL_END