ioWriteAiger.c 13.6 KB
Newer Older
Alan Mishchenko committed
1 2
/**CFile****************************************************************

Alan Mishchenko committed
3
  FileName    [ioWriteAiger.c]
Alan Mishchenko committed
4 5 6 7 8 9 10 11 12 13 14 15 16 17

  SystemName  [ABC: Logic synthesis and verification system.]

  PackageName [Command processing package.]

  Synopsis    [Procedures to 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 - December 16, 2006.]

Alan Mishchenko committed
18
  Revision    [$Id: ioWriteAiger.c,v 1.00 2006/12/16 00:00:00 alanmi Exp $]
Alan Mishchenko committed
19 20 21

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

Alan Mishchenko committed
22
#include "io.h"
Alan Mishchenko committed
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 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 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127

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

/*
    The following is taken from the AIGER format description, 
    which can be found at http://fmv.jku.at/aiger
*/


/*
         The AIGER And-Inverter Graph (AIG) Format Version 20061129
         ----------------------------------------------------------
              Armin Biere, Johannes Kepler University, 2006

  This report describes the AIG file format as used by the AIGER library.
  The purpose of this report is not only to motivate and document the
  format, but also to allow independent implementations of writers and
  readers by giving precise and unambiguous definitions.

  ...

Introduction

  The name AIGER contains as one part the acronym AIG of And-Inverter
  Graphs and also if pronounced in German sounds like the name of the
  'Eiger', a mountain in the Swiss alps.  This choice should emphasize the
  origin of this format. It was first openly discussed at the Alpine
  Verification Meeting 2006 in Ascona as a way to provide a simple, compact
  file format for a model checking competition affiliated to CAV 2007.

  ...

Binary Format Definition

  The binary format is semantically a subset of the ASCII format with a
  slightly different syntax.  The binary format may need to reencode
  literals, but translating a file in binary format into ASCII format and
  then back in to binary format will result in the same file.

  The main differences of the binary format to the ASCII format are as
  follows.  After the header the list of input literals and all the
  current state literals of a latch can be omitted.  Furthermore the
  definitions of the AND gates are binary encoded.  However, the symbol
  table and the comment section are as in the ASCII format.

  The header of an AIGER file in binary format has 'aig' as format
  identifier, but otherwise is identical to the ASCII header.  The standard
  file extension for the binary format is therefore '.aig'. 
  
  A header for the binary format is still in ASCII encoding:

    aig M I L O A

  Constants, variables and literals are handled in the same way as in the
  ASCII format.  The first simplifying restriction is on the variable
  indices of inputs and latches.  The variable indices of inputs come first,
  followed by the pseudo-primary inputs of the latches and then the variable
  indices of all LHS of AND gates:

    input variable indices        1,          2,  ... ,  I
    latch variable indices      I+1,        I+2,  ... ,  (I+L)
    AND variable indices      I+L+1,      I+L+2,  ... ,  (I+L+A) == M

  The corresponding unsigned literals are

    input literals                2,          4,  ... ,  2*I
    latch literals            2*I+2,      2*I+4,  ... ,  2*(I+L)
    AND literals          2*(I+L)+2,  2*(I+L)+4,  ... ,  2*(I+L+A) == 2*M
                    
  All literals have to be defined, and therefore 'M = I + L + A'.  With this
  restriction it becomes possible that the inputs and the current state
  literals of the latches do not have to be listed explicitly.  Therefore,
  after the header only the list of 'L' next state literals follows, one per
  latch on a single line, and then the 'O' outputs, again one per line.

  In the binary format we assume that the AND gates are ordered and respect
  the child parent relation.  AND gates with smaller literals on the LHS
  come first.  Therefore we can assume that the literals on the right-hand
  side of a definition of an AND gate are smaller than the LHS literal.
  Furthermore we can sort the literals on the RHS, such that the larger
  literal comes first.  A definition thus consists of three literals
    
      lhs rhs0 rhs1

  with 'lhs' even and 'lhs > rhs0 >= rhs1'.  Also the variable indices are
  pairwise different to avoid combinational self loops.  Since the LHS
  indices of the definitions are all consecutive (as even integers),
  the binary format does not have to keep 'lhs'.  In addition, we can use
  the order restriction and only write the differences 'delta0' and 'delta1'
  instead of 'rhs0' and 'rhs1', with

      delta0 = lhs - rhs0,  delta1 = rhs0 - rhs1
  
  The differences will all be strictly positive, and in practice often very
  small.  We can take advantage of this fact by the simple little-endian
  encoding of unsigned integers of the next section.  After the binary delta
  encoding of the RHSs of all AND gates, the optional symbol table and
  optional comment section start in the same format as in the ASCII case.

  ...

*/

Alan Mishchenko committed
128 129 130
static unsigned Io_ObjMakeLit( int Var, int fCompl )                 { return (Var << 1) | fCompl;    }
static unsigned Io_ObjAigerNum( Abc_Obj_t * pObj )                   { return (unsigned)pObj->pCopy;  }
static void     Io_ObjSetAigerNum( Abc_Obj_t * pObj, unsigned Num )  { pObj->pCopy = (void *)Num;     }
Alan Mishchenko committed
131 132 133 134 135 136 137

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

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

Alan Mishchenko committed
138 139 140 141 142 143 144 145 146 147
  Synopsis    [Adds one unsigned AIG edge to the output buffer.]

  Description [This procedure is a slightly modified version of Armin Biere's
  procedure "void encode (FILE * file, unsigned x)" ]
  
  SideEffects [Returns the current writing position.]

  SeeAlso     []

***********************************************************************/
Alan Mishchenko committed
148
int Io_WriteAigerEncode( char * pBuffer, int Pos, unsigned x )
Alan Mishchenko committed
149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174
{
    unsigned char ch;
    while (x & ~0x7f)
    {
        ch = (x & 0x7f) | 0x80;
//        putc (ch, file);
        pBuffer[Pos++] = ch;
        x >>= 7;
    }
    ch = x;
//    putc (ch, file);
    pBuffer[Pos++] = ch;
    return Pos;
}

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

  Synopsis    [Create the array of literals to be written.]

  Description []
  
  SideEffects []

  SeeAlso     []

***********************************************************************/
Alan Mishchenko committed
175
Vec_Int_t * Io_WriteAigerLiterals( Abc_Ntk_t * pNtk )
Alan Mishchenko committed
176 177
{
    Vec_Int_t * vLits;
Alan Mishchenko committed
178
    Abc_Obj_t * pObj, * pDriver;
Alan Mishchenko committed
179
    int i;
Alan Mishchenko committed
180 181
    vLits = Vec_IntAlloc( Abc_NtkCoNum(pNtk) );
    Abc_NtkForEachLatchInput( pNtk, pObj, i )
Alan Mishchenko committed
182
    {
Alan Mishchenko committed
183 184
        pDriver = Abc_ObjFanin0(pObj);
        Vec_IntPush( vLits, Io_ObjMakeLit( Io_ObjAigerNum(pDriver), Abc_ObjFaninC0(pObj) ^ (Io_ObjAigerNum(pDriver) == 0) ) );
Alan Mishchenko committed
185
    }
Alan Mishchenko committed
186
    Abc_NtkForEachPo( pNtk, pObj, i )
Alan Mishchenko committed
187
    {
Alan Mishchenko committed
188 189
        pDriver = Abc_ObjFanin0(pObj);
        Vec_IntPush( vLits, Io_ObjMakeLit( Io_ObjAigerNum(pDriver), Abc_ObjFaninC0(pObj) ^ (Io_ObjAigerNum(pDriver) == 0) ) );
Alan Mishchenko committed
190 191 192 193 194 195 196 197 198 199 200 201 202 203 204
    }
    return vLits;
}

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

  Synopsis    [Creates the binary encoded array of literals.]

  Description []
  
  SideEffects []

  SeeAlso     []

***********************************************************************/
Alan Mishchenko committed
205
Vec_Str_t * Io_WriteEncodeLiterals( Vec_Int_t * vLits )
Alan Mishchenko committed
206 207 208 209 210
{
    Vec_Str_t * vBinary;
    int Pos = 0, Lit, LitPrev, Diff, i;
    vBinary = Vec_StrAlloc( 2 * Vec_IntSize(vLits) );
    LitPrev = Vec_IntEntry( vLits, 0 );
Alan Mishchenko committed
211
    Pos = Io_WriteAigerEncode( Vec_StrArray(vBinary), Pos, LitPrev ); 
Alan Mishchenko committed
212 213 214 215 216
    Vec_IntForEachEntryStart( vLits, Lit, i, 1 )
    {
        Diff = Lit - LitPrev;
        Diff = (Lit < LitPrev)? -Diff : Diff;
        Diff = (Diff << 1) | (int)(Lit < LitPrev);
Alan Mishchenko committed
217
        Pos = Io_WriteAigerEncode( Vec_StrArray(vBinary), Pos, Diff );
Alan Mishchenko committed
218 219 220 221 222 223 224 225
        LitPrev = Lit;
        if ( Pos + 10 > vBinary->nCap )
            Vec_StrGrow( vBinary, vBinary->nCap+1 );
    }
    vBinary->nSize = Pos;
/*
    // verify
    {
Alan Mishchenko committed
226
        extern Vec_Int_t * Io_WriteDecodeLiterals( char ** ppPos, int nEntries );
Alan Mishchenko committed
227
        char * pPos = Vec_StrArray( vBinary );
Alan Mishchenko committed
228
        Vec_Int_t * vTemp = Io_WriteDecodeLiterals( &pPos, Vec_IntSize(vLits) );
Alan Mishchenko committed
229 230 231 232 233 234 235 236 237 238 239 240 241
        for ( i = 0; i < Vec_IntSize(vLits); i++ )
        {
            int Entry1 = Vec_IntEntry(vLits,i);
            int Entry2 = Vec_IntEntry(vTemp,i);
            assert( Entry1 == Entry2 );
        }
    }
*/
    return vBinary;
}

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

Alan Mishchenko committed
242 243 244 245 246 247 248 249 250
  Synopsis    [Writes the AIG in the binary AIGER format.]

  Description []
  
  SideEffects []

  SeeAlso     []

***********************************************************************/
Alan Mishchenko committed
251
void Io_WriteAiger( Abc_Ntk_t * pNtk, char * pFileName, int fWriteSymbols, int fCompact )
Alan Mishchenko committed
252
{
Alan Mishchenko committed
253
    ProgressBar * pProgress;
Alan Mishchenko committed
254
    FILE * pFile;
Alan Mishchenko committed
255
    Abc_Obj_t * pObj, * pDriver;
Alan Mishchenko committed
256 257 258 259
    int i, nNodes, Pos, nBufferSize;
    unsigned char * pBuffer;
    unsigned uLit0, uLit1, uLit;

Alan Mishchenko committed
260
    assert( Abc_NtkIsStrash(pNtk) );
Alan Mishchenko committed
261 262 263 264
    // start the output stream
    pFile = fopen( pFileName, "wb" );
    if ( pFile == NULL )
    {
Alan Mishchenko committed
265
        fprintf( stdout, "Io_WriteAiger(): Cannot open the output file \"%s\".\n", pFileName );
Alan Mishchenko committed
266 267
        return;
    }
Alan Mishchenko committed
268 269
    Abc_NtkForEachLatch( pNtk, pObj, i )
        if ( !Abc_LatchIsInit0(pObj) )
Alan Mishchenko committed
270
        {
Alan Mishchenko committed
271
            fprintf( stdout, "Io_WriteAiger(): Cannot write AIGER format with non-0 latch init values. Run \"zero\".\n" );
Alan Mishchenko committed
272 273
            return;
        }
Alan Mishchenko committed
274

Alan Mishchenko committed
275 276
    // set the node numbers to be used in the output file
    nNodes = 0;
Alan Mishchenko committed
277 278 279 280 281
    Io_ObjSetAigerNum( Abc_AigConst1(pNtk), nNodes++ );
    Abc_NtkForEachCi( pNtk, pObj, i )
        Io_ObjSetAigerNum( pObj, nNodes++ );
    Abc_AigForEachAnd( pNtk, pObj, i )
        Io_ObjSetAigerNum( pObj, nNodes++ );
Alan Mishchenko committed
282 283

    // write the header "M I L O A" where M = I + L + A
Alan Mishchenko committed
284 285
    fprintf( pFile, "aig%s %u %u %u %u %u\n", 
        fCompact? "2" : "",
Alan Mishchenko committed
286 287 288 289 290
        Abc_NtkPiNum(pNtk) + Abc_NtkLatchNum(pNtk) + Abc_NtkNodeNum(pNtk), 
        Abc_NtkPiNum(pNtk),
        Abc_NtkLatchNum(pNtk),
        Abc_NtkPoNum(pNtk),
        Abc_NtkNodeNum(pNtk) );
Alan Mishchenko committed
291 292 293 294 295

    // if the driver node is a constant, we need to complement the literal below
    // because, in the AIGER format, literal 0/1 is represented as number 0/1
    // while, in ABC, constant 1 node has number 0 and so literal 0/1 will be 1/0

Alan Mishchenko committed
296
    if ( !fCompact ) 
Alan Mishchenko committed
297
    {
Alan Mishchenko committed
298
        // write latch drivers
Alan Mishchenko committed
299
        Abc_NtkForEachLatchInput( pNtk, pObj, i )
Alan Mishchenko committed
300
        {
Alan Mishchenko committed
301 302
            pDriver = Abc_ObjFanin0(pObj);
            fprintf( pFile, "%u\n", Io_ObjMakeLit( Io_ObjAigerNum(pDriver), Abc_ObjFaninC0(pObj) ^ (Io_ObjAigerNum(pDriver) == 0) ) );
Alan Mishchenko committed
303 304
        }
        // write PO drivers
Alan Mishchenko committed
305
        Abc_NtkForEachPo( pNtk, pObj, i )
Alan Mishchenko committed
306
        {
Alan Mishchenko committed
307 308
            pDriver = Abc_ObjFanin0(pObj);
            fprintf( pFile, "%u\n", Io_ObjMakeLit( Io_ObjAigerNum(pDriver), Abc_ObjFaninC0(pObj) ^ (Io_ObjAigerNum(pDriver) == 0) ) );
Alan Mishchenko committed
309 310 311
        }
    }
    else
Alan Mishchenko committed
312
    {
Alan Mishchenko committed
313 314
        Vec_Int_t * vLits = Io_WriteAigerLiterals( pNtk );
        Vec_Str_t * vBinary = Io_WriteEncodeLiterals( vLits );
Alan Mishchenko committed
315 316 317
        fwrite( Vec_StrArray(vBinary), 1, Vec_StrSize(vBinary), pFile );
        Vec_StrFree( vBinary );
        Vec_IntFree( vLits );
Alan Mishchenko committed
318 319 320 321
    }

    // write the nodes into the buffer
    Pos = 0;
Alan Mishchenko committed
322
    nBufferSize = 6 * Abc_NtkNodeNum(pNtk) + 100; // skeptically assuming 3 chars per one AIG edge
Alan Mishchenko committed
323
    pBuffer = ALLOC( unsigned char, nBufferSize );
Alan Mishchenko committed
324 325
    pProgress = Extra_ProgressBarStart( stdout, Abc_NtkObjNumMax(pNtk) );
    Abc_AigForEachAnd( pNtk, pObj, i )
Alan Mishchenko committed
326
    {
Alan Mishchenko committed
327 328 329 330
        Extra_ProgressBarUpdate( pProgress, i, NULL );
        uLit  = Io_ObjMakeLit( Io_ObjAigerNum(pObj), 0 );
        uLit0 = Io_ObjMakeLit( Io_ObjAigerNum(Abc_ObjFanin0(pObj)), Abc_ObjFaninC0(pObj) );
        uLit1 = Io_ObjMakeLit( Io_ObjAigerNum(Abc_ObjFanin1(pObj)), Abc_ObjFaninC1(pObj) );
Alan Mishchenko committed
331
        assert( uLit0 < uLit1 );
Alan Mishchenko committed
332 333
        Pos = Io_WriteAigerEncode( pBuffer, Pos, (unsigned)(uLit  - uLit1) );
        Pos = Io_WriteAigerEncode( pBuffer, Pos, (unsigned)(uLit1 - uLit0) );
Alan Mishchenko committed
334 335
        if ( Pos > nBufferSize - 10 )
        {
Alan Mishchenko committed
336
            printf( "Io_WriteAiger(): AIGER generation has failed because the allocated buffer is too small.\n" );
Alan Mishchenko committed
337 338 339 340 341
            fclose( pFile );
            return;
        }
    }
    assert( Pos < nBufferSize );
Alan Mishchenko committed
342
    Extra_ProgressBarStop( pProgress );
Alan Mishchenko committed
343 344 345 346

    // write the buffer
    fwrite( pBuffer, 1, Pos, pFile );
    free( pBuffer );
Alan Mishchenko committed
347

Alan Mishchenko committed
348 349 350 351
    // write the symbol table
    if ( fWriteSymbols )
    {
        // write PIs
Alan Mishchenko committed
352 353
        Abc_NtkForEachPi( pNtk, pObj, i )
            fprintf( pFile, "i%d %s\n", i, Abc_ObjName(pObj) );
Alan Mishchenko committed
354
        // write latches
Alan Mishchenko committed
355 356
        Abc_NtkForEachLatch( pNtk, pObj, i )
            fprintf( pFile, "l%d %s\n", i, Abc_ObjName(Abc_ObjFanout0(pObj)) );
Alan Mishchenko committed
357
        // write POs
Alan Mishchenko committed
358 359
        Abc_NtkForEachPo( pNtk, pObj, i )
            fprintf( pFile, "o%d %s\n", i, Abc_ObjName(pObj) );
Alan Mishchenko committed
360
    }
Alan Mishchenko committed
361

Alan Mishchenko committed
362 363
    // write the comment
    fprintf( pFile, "c\n" );
Alan Mishchenko committed
364 365 366
    if ( pNtk->pName && strlen(pNtk->pName) > 0 )
        fprintf( pFile, ".model %s\n", pNtk->pName );
    fprintf( pFile, "This file was produced by ABC on %s\n", Extra_TimeStamp() );
Alan Mishchenko committed
367 368 369 370 371 372 373 374 375
    fprintf( pFile, "For information about AIGER format, refer to %s\n", "http://fmv.jku.at/aiger" );
    fclose( pFile );
}

////////////////////////////////////////////////////////////////////////
///                       END OF FILE                                ///
////////////////////////////////////////////////////////////////////////