summaryrefslogtreecommitdiffstats
path: root/src/proof/cec/cecSplit.c
blob: 24c1e15c6448f77abf1323550a41a99ddddcb913 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
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
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
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
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
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
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
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
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
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
706
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
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
/**CFile****************************************************************

  FileName    [cecSplit.c]

  SystemName  [ABC: Logic synthesis and verification system.]

  PackageName [Combinational equivalence checking.]

  Synopsis    [Cofactoring for combinational miters.]

  Author      [Alan Mishchenko]
  
  Affiliation [UC Berkeley]

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

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

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

#include <math.h>
#include "aig/gia/gia.h"
#include "aig/gia/giaAig.h"
#include "sat/cnf/cnf.h"
#include "sat/bsat/satSolver.h"
#include "misc/util/utilTruth.h"
//#include "bdd/cudd/cuddInt.h"

#ifdef ABC_USE_PTHREADS

#ifdef _WIN32
#include "../lib/pthread.h"
#else
#include <pthread.h>
#include <unistd.h>
#endif

#endif

ABC_NAMESPACE_IMPL_START


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

#ifndef ABC_USE_PTHREADS

int Cec_GiaSplitTest( Gia_Man_t * p, int nProcs, int nTimeOut, int nIterMax, int LookAhead, int fVerbose, int fVeryVerbose, int fSilent ) { return -1; }

#else // pthreads are used

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

#if 0 // BDD code

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

  Synopsis    [Permute primary inputs.]

  Description []
               
  SideEffects []

  SeeAlso     []

***********************************************************************/
DdManager * Gia_ManBuildBdd( Gia_Man_t * p, Vec_Ptr_t ** pvNodes, int nSkip )
{
    abctime clk = Abc_Clock();
    DdManager * dd;
    DdNode * bBdd, * bBdd0, * bBdd1;
    Vec_Ptr_t * vNodes;
    Gia_Obj_t * pObj;
    int i;
    vNodes = Vec_PtrStart( Gia_ManObjNum(p) );
    dd = Cudd_Init( Gia_ManPiNum(p), 0, CUDD_UNIQUE_SLOTS, CUDD_CACHE_SLOTS, 0 );
//    Cudd_AutodynEnable( dd,  CUDD_REORDER_SYMM_SIFT );
    bBdd = Cudd_ReadLogicZero(dd); Cudd_Ref( bBdd );
    Vec_PtrWriteEntry( vNodes, 0, bBdd );  
    Gia_ManForEachPi( p, pObj, i )
    {
        bBdd = i > nSkip ? Cudd_bddIthVar(dd, i) : Cudd_ReadLogicZero(dd); Cudd_Ref( bBdd );
        Vec_PtrWriteEntry( vNodes, Gia_ObjId(p, pObj), bBdd );
    }
    Gia_ManForEachAnd( p, pObj, i )
    {
        bBdd0 = Cudd_NotCond( (DdNode *)Vec_PtrEntry(vNodes, Gia_ObjFaninId0(pObj, i)), Gia_ObjFaninC0(pObj) );
        bBdd1 = Cudd_NotCond( (DdNode *)Vec_PtrEntry(vNodes, Gia_ObjFaninId1(pObj, i)), Gia_ObjFaninC1(pObj) );
        bBdd = Cudd_bddAnd( dd, bBdd0, bBdd1 ); Cudd_Ref( bBdd );
        Vec_PtrWriteEntry( vNodes, Gia_ObjId(p, pObj), bBdd );
        if ( i % 10 == 0 )
            printf( "%d ", i );
//        if ( i == 3000 )
//            break;
    }
    printf( "\n" );
    Gia_ManForEachPo( p, pObj, i )
    {
        bBdd = Cudd_NotCond( (DdNode *)Vec_PtrEntry(vNodes, Gia_ObjFaninId0(pObj, Gia_ObjId(p, pObj))), Gia_ObjFaninC0(pObj) );  Cudd_Ref( bBdd );
        Vec_PtrWriteEntry( vNodes, Gia_ObjId(p, pObj), bBdd );
    }
    if ( bBdd == Cudd_ReadLogicZero(dd) )
        printf( "Equivalent!\n" );
    else
        printf( "Not tquivalent!\n" );
    if ( pvNodes )
        *pvNodes = vNodes;
    Abc_PrintTime( 1, "Time", Abc_Clock() - clk );
    return dd;
}
void Gia_ManDerefBdd( DdManager * dd, Vec_Ptr_t * vNodes )
{
    DdNode * bBdd;
    int i;
    Vec_PtrForEachEntry( DdNode *, vNodes, bBdd, i )
        if ( bBdd )
            Cudd_RecursiveDeref( dd, bBdd );
    if ( Cudd_CheckZeroRef(dd) > 0 )
        printf( "The number of referenced nodes = %d\n", Cudd_CheckZeroRef(dd) );
    Cudd_PrintInfo( dd, stdout );
    Cudd_Quit( dd );
}
void Gia_ManBuildBddTest( Gia_Man_t * p )
{
    Vec_Ptr_t * vNodes;
    DdManager * dd = Gia_ManBuildBdd( p, &vNodes, 50 );
    Gia_ManDerefBdd( dd, vNodes );
}

#endif // BDD code

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

  Synopsis    []

  Description []
               
  SideEffects []

  SeeAlso     []

***********************************************************************/
void Cec_GiaSplitExplore( Gia_Man_t * p )
{
    Gia_Obj_t * pObj, * pFan0, * pFan1;
    int i, Counter = 0;
    assert( p->pMuxes == NULL );
    ABC_FREE( p->pRefs );
    Gia_ManCreateRefs( p ); 
    Gia_ManForEachAnd( p, pObj, i )
    {
        if ( !Gia_ObjRecognizeExor(pObj, &pFan0, &pFan1) )
            continue;
        if ( Gia_ObjRefNum(p, Gia_ObjFanin0(pObj)) > 1 && 
             Gia_ObjRefNum(p, Gia_ObjFanin1(pObj)) > 1 )
             continue;
        printf( "%5d : ", Counter++ );
        printf( "%2d %2d    ", Gia_ObjRefNum(p, Gia_Regular(pFan0)),  Gia_ObjRefNum(p, Gia_Regular(pFan1)) );
        printf( "%2d %2d  \n", Gia_ObjRefNum(p, Gia_ObjFanin0(pObj)), Gia_ObjRefNum(p, Gia_ObjFanin1(pObj)) );
    }
}

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

  Synopsis    [Find cofactoring variable.]

  Description []
               
  SideEffects []

  SeeAlso     []

***********************************************************************/
int * Gia_PermuteSpecialOrder( Gia_Man_t * p )
{
    Vec_Int_t * vPerm;
    Gia_Obj_t * pObj;
    int i, * pOrder;
    Gia_ManCreateRefs( p );
    vPerm = Vec_IntAlloc( Gia_ManPiNum(p) );
    Gia_ManForEachPi( p, pObj, i )
        Vec_IntPush( vPerm, Gia_ObjRefNum(p, pObj) );
    pOrder = Abc_QuickSortCost( Vec_IntArray(vPerm), Vec_IntSize(vPerm), 1 );
    Vec_IntFree( vPerm );
    return pOrder;
}
Gia_Man_t * Gia_PermuteSpecial( Gia_Man_t * p )
{
    Gia_Man_t * pNew;
    Vec_Int_t * vPerm;
    int * pOrder = Gia_PermuteSpecialOrder( p );
    vPerm = Vec_IntAllocArray( pOrder, Gia_ManPiNum(p) );
    pNew = Gia_ManDupPerm( p, vPerm );
    Vec_IntFree( vPerm );
    return pNew;
}

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

  Synopsis    [Find cofactoring variable.]

  Description []
               
  SideEffects []

  SeeAlso     []

***********************************************************************/
int Gia_SplitCofVar2( Gia_Man_t * p, int * pnFanouts, int * pnCost )
{
    Gia_Obj_t * pObj;
    int i, iBest = -1, CostBest = -1;
    if ( p->pRefs == NULL )
        Gia_ManCreateRefs( p );
    Gia_ManForEachPi( p, pObj, i )
        if ( CostBest < Gia_ObjRefNum(p, pObj) )
            iBest = i, CostBest = Gia_ObjRefNum(p, pObj);
    assert( iBest >= 0 );
    *pnFanouts = Gia_ObjRefNum(p, Gia_ManPi(p, iBest));
    *pnCost = -1;
    return iBest;
}
int Gia_SplitCofVar( Gia_Man_t * p, int LookAhead, int * pnFanouts, int * pnCost )
{
    Gia_Man_t * pPart;
    int Cost0, Cost1, CostBest = ABC_INFINITY;
    int * pOrder, i, iBest = -1;
    if ( LookAhead == 1 )
        return Gia_SplitCofVar2( p, pnFanouts, pnCost );
    pOrder = Gia_PermuteSpecialOrder( p );
    LookAhead = Abc_MinInt( LookAhead, Gia_ManPiNum(p) );
    for ( i = 0; i < LookAhead; i++ )
    {
        pPart = Gia_ManDupCofactorVar( p, pOrder[i], 0 );
        Cost0 = Gia_ManAndNum(pPart);
        Gia_ManStop( pPart );

        pPart = Gia_ManDupCofactorVar( p, pOrder[i], 1 );
        Cost1 = Gia_ManAndNum(pPart);
        Gia_ManStop( pPart );

        if ( CostBest > Cost0 + Cost1 )
            CostBest = Cost0 + Cost1, iBest = pOrder[i];

/*
        pPart = Gia_ManDupExist( p, pOrder[i] );
        printf( "%2d : Var = %4d  Refs = %3d  %6d %6d -> %6d    %6d -> %6d\n", 
            i, pOrder[i], Gia_ObjRefNum(p, Gia_ManPi(p, pOrder[i])), 
            Cost0, Cost1, Cost0+Cost1, Gia_ManAndNum(p), Gia_ManAndNum(pPart) );
        Gia_ManStop( pPart );

        printf( "%2d : Var = %4d  Refs = %3d  %6d %6d -> %6d\n", 
            i, pOrder[i], Gia_ObjRefNum(p, Gia_ManPi(p, pOrder[i])), 
            Cost0, Cost1, Cost0+Cost1 );
*/
    }
    ABC_FREE( pOrder );
    assert( iBest >= 0 );
    *pnFanouts = Gia_ObjRefNum(p, Gia_ManPi(p, iBest));
    *pnCost = CostBest;
    return iBest;
}

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

  Synopsis    []

  Description []
               
  SideEffects []

  SeeAlso     []

***********************************************************************/
Abc_Cex_t * Cec_SplitDeriveModel( Gia_Man_t * p, Cnf_Dat_t * pCnf, sat_solver * pSat )
{
    Abc_Cex_t * pCex;
    Gia_Obj_t * pObj;
    int i, iLit, * pModel;
    pModel = ABC_CALLOC( int, Gia_ManPiNum(p) );
    Gia_ManForEachPi( p, pObj, i )
        pModel[i] = sat_solver_var_value(pSat, pCnf->pVarNums[Gia_ObjId(p, pObj)]);
    if ( p->vCofVars )
        Vec_IntForEachEntry( p->vCofVars, iLit, i )
            pModel[Abc_Lit2Var(iLit)] = !Abc_LitIsCompl(iLit);
    pCex = Abc_CexCreate( 0, Gia_ManPiNum(p), pModel, 0, 0, 0 );
    ABC_FREE( pModel );
    return pCex;
}

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

  Synopsis    []

  Description []
               
  SideEffects []

  SeeAlso     []

***********************************************************************/
static inline Cnf_Dat_t * Cec_GiaDeriveGiaRemapped( Gia_Man_t * p )
{
    Cnf_Dat_t * pCnf;
    Aig_Man_t * pAig = Gia_ManToAigSimple( p );
    pAig->nRegs = 0;
    pCnf = Cnf_Derive( pAig, 0 );//Aig_ManCoNum(pAig) );
    Aig_ManStop( pAig );
    return pCnf;
}
static inline sat_solver * Cec_GiaDeriveSolver( Gia_Man_t * p, Cnf_Dat_t * pCnf, int nTimeOut )
{
    sat_solver * pSat;
    int i;
    pSat = sat_solver_new();
    sat_solver_setnvars( pSat, pCnf->nVars );
    for ( i = 0; i < pCnf->nClauses; i++ )
        if ( !sat_solver_addclause( pSat, pCnf->pClauses[i], pCnf->pClauses[i+1] ) )
        {
            // the problem is UNSAT
            sat_solver_delete( pSat );
            return NULL;
        }
    sat_solver_set_runtime_limit( pSat, nTimeOut ? nTimeOut * CLOCKS_PER_SEC + Abc_Clock(): 0 );
    return pSat;
}
static inline int Cnf_GiaSolveOne( Gia_Man_t * p, Cnf_Dat_t * pCnf, int nTimeOut, int * pnVars, int * pnConfs )
{
    int status;
    sat_solver * pSat = Cec_GiaDeriveSolver( p, pCnf, nTimeOut );
    if ( pSat == NULL )
    {
        *pnVars = 0;
        *pnConfs = 0;
        return 1;
    }
    status   = sat_solver_solve( pSat, NULL, NULL, (ABC_INT64_T)0, (ABC_INT64_T)0, (ABC_INT64_T)0, (ABC_INT64_T)0 );
    *pnVars  = sat_solver_nvars( pSat );
    *pnConfs = sat_solver_nconflicts( pSat );
    if ( status == l_True )
        p->pCexComb = Cec_SplitDeriveModel( p, pCnf, pSat );
    sat_solver_delete( pSat );
    if ( status == l_Undef )
        return -1;
    if ( status == l_False )
        return 1;
    return 0;
}
static inline void Cec_GiaSplitClean( Vec_Ptr_t * vStack )
{
    Gia_Man_t * pNew;
    int i;
    Vec_PtrForEachEntry( Gia_Man_t *, vStack, pNew, i )
        Gia_ManStop( pNew );
    Vec_PtrFree( vStack );
}

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

  Synopsis    []

  Description []
               
  SideEffects []

  SeeAlso     []

***********************************************************************/
void Cec_GiaSplitPrint( int nIter, int Depth, int nVars, int nConfs, int fStatus, double Prog, abctime clk )
{
    printf( "%4d : ",             nIter );
    printf( "Depth =%3d  ",       Depth );
    printf( "SatVar =%7d  ",      nVars );
    printf( "SatConf =%7d   ",    nConfs );
    printf( "%s   ",              fStatus ? (fStatus == 1 ? "UNSAT    " : "UNDECIDED") : "SAT      " );
    printf( "Solved %8.4f %%   ", 100*Prog );
    Abc_PrintTime( 1, "Time", clk );
    //ABC_PRTr( "Time", Abc_Clock()-clk );
    fflush( stdout );
}
void Cec_GiaSplitPrintRefs( Gia_Man_t * p )
{
    Gia_Obj_t * pObj;
    int i;
    if ( p->pRefs == NULL )
        Gia_ManCreateRefs( p ); 
    Gia_ManForEachPi( p, pObj, i )
        printf( "%d ", Gia_ObjRefNum(p, pObj) );
    printf( "\n" );
}

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

  Synopsis    []

  Description []
               
  SideEffects []

  SeeAlso     []

***********************************************************************/
int Cec_GiaSplitTest2( Gia_Man_t * p, int nProcs, int nTimeOut, int nIterMax, int LookAhead, int fVerbose, int fVeryVerbose, int fSilent )
{
    abctime clkTotal = Abc_Clock();
    Vec_Ptr_t * vStack;
    Cnf_Dat_t * pCnf;
    int nSatVars, nSatConfs;
    int nIter, status, RetValue = -1;
    double Progress = 0;
    // check the problem
    pCnf = Cec_GiaDeriveGiaRemapped( p );
    status = Cnf_GiaSolveOne( p, pCnf, nTimeOut, &nSatVars, &nSatConfs );
    Cnf_DataFree( pCnf );
    if ( fVerbose )
        Cec_GiaSplitPrint( 0, 0, nSatVars, nSatConfs, status, Progress, Abc_Clock() - clkTotal );
    if ( status == 0 )
    {
        if ( !fSilent )
        printf( "The problem is SAT without cofactoring.\n" );
        return 0;
    }
    if ( status == 1 )
    {
        if ( !fSilent )
        printf( "The problem is UNSAT without cofactoring.\n" );
        return 1;
    }
    assert( status == -1 );
    // create local copy
    vStack = Vec_PtrAlloc( 1000 );
    Vec_PtrPush( vStack, Gia_ManDup(p) );
    // start with the current problem
    for ( nIter = 1; Vec_PtrSize(vStack) > 0; nIter++ )
    {
        // get the last AIG
        Gia_Man_t * pLast = (Gia_Man_t *)Vec_PtrPop( vStack );
        // determine cofactoring variable
        int Depth = 1 + (pLast->vCofVars ? Vec_IntSize(pLast->vCofVars) : 0);
        int nFanouts, Cost, iVar  = Gia_SplitCofVar( pLast, LookAhead, &nFanouts, &Cost );
        // cofactor
        Gia_Man_t * pPart = Gia_ManDupCofactorVar( pLast, iVar, 0 );
        if ( pLast->vCofVars == NULL )
            pLast->vCofVars = Vec_IntAlloc( 100 );
        // print results
        if ( fVeryVerbose )
        {
//            Cec_GiaSplitPrintRefs( pLast );
            printf( "Var = %5d. Fanouts = %5d. Cost = %8d.  AndBefore = %6d.  AndAfter = %6d.\n", 
                iVar, nFanouts, Cost, Gia_ManAndNum(pLast), Gia_ManAndNum(pPart) );
//            Cec_GiaSplitPrintRefs( pPart );
        }
        // create variable
        pPart->vCofVars = Vec_IntAlloc( Vec_IntSize(pLast->vCofVars) + 1 );
        Vec_IntAppend( pPart->vCofVars, pLast->vCofVars );
        Vec_IntPush( pPart->vCofVars, Abc_Var2Lit(iVar, 1) );
        // solve the problem
        pCnf = Cec_GiaDeriveGiaRemapped( pPart );
        status = Cnf_GiaSolveOne( pPart, pCnf, nTimeOut, &nSatVars, &nSatConfs );
        Cnf_DataFree( pCnf );
        if ( status == 1 )
            Progress += 1.0 / pow(2, Depth);
        if ( fVerbose ) 
            Cec_GiaSplitPrint( nIter, Depth, nSatVars, nSatConfs, status, Progress, Abc_Clock() - clkTotal );
        if ( status == 0 ) // SAT
        {
            p->pCexComb = pPart->pCexComb;  pPart->pCexComb = NULL;
            Gia_ManStop( pLast );
            Gia_ManStop( pPart );
            RetValue = 0;
            break;
        }
        if ( status == 1 ) // UNSAT
            Gia_ManStop( pPart );
        else               // UNDEC
            Vec_PtrPush( vStack, pPart );
        // cofactor
        pPart = Gia_ManDupCofactorVar( pLast, iVar, 1 );
        // create variable
        pPart->vCofVars = Vec_IntAlloc( Vec_IntSize(pLast->vCofVars) + 1 );
        Vec_IntAppend( pPart->vCofVars, pLast->vCofVars );
        Vec_IntPush( pPart->vCofVars, Abc_Var2Lit(iVar, 0) );
        Gia_ManStop( pLast );
        // solve the problem
        pCnf = Cec_GiaDeriveGiaRemapped( pPart );
        status = Cnf_GiaSolveOne( pPart, pCnf, nTimeOut, &nSatVars, &nSatConfs );
        Cnf_DataFree( pCnf );
        if ( status == 1 )
            Progress += 1.0 / pow(2, Depth);
        if ( fVerbose )
            Cec_GiaSplitPrint( nIter, Depth, nSatVars, nSatConfs, status, Progress, Abc_Clock() - clkTotal );
        if ( status == 0 ) // SAT
        {
            p->pCexComb = pPart->pCexComb;  pPart->pCexComb = NULL;
            Gia_ManStop( pPart );
            RetValue = 0;
            break;
        }
        if ( status == 1 ) // UNSAT
            Gia_ManStop( pPart );
        else               // UNDEC
            Vec_PtrPush( vStack, pPart );
        if ( nIterMax && nIter >= nIterMax )
            break;
    }
    if ( Vec_PtrSize(vStack) == 0 )
        RetValue = 1;
    // finish
    Cec_GiaSplitClean( vStack );
    if ( !fSilent )
    {
        if ( RetValue == 0 )
            printf( "Problem is SAT " );
        else if ( RetValue == 1 )
            printf( "Problem is UNSAT " );
        else if ( RetValue == -1 )
            printf( "Problem is UNDECIDED " );
        else assert( 0 );
        printf( "after %d case-splits.  ", nIter );
        Abc_PrintTime( 1, "Time", Abc_Clock() - clkTotal );
        fflush( stdout );
    }
    return RetValue;
}

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

  Synopsis    []

  Description []
               
  SideEffects []

  SeeAlso     []

***********************************************************************/
#define PAR_THR_MAX 100
typedef struct Par_ThData_t_
{
    Gia_Man_t * p;
    Cnf_Dat_t * pCnf;
    int         iThread;
    int         nTimeOut;
    int         fWorking;
    int         Result;
    int         nVars;
    int         nConfs;
} Par_ThData_t;
void * Cec_GiaSplitWorkerThread( void * pArg )
{
    Par_ThData_t * pThData = (Par_ThData_t *)pArg;
    volatile int * pPlace = &pThData->fWorking;
    while ( 1 )
    {
        while ( *pPlace == 0 );
        assert( pThData->fWorking );
        if ( pThData->p == NULL )
        {
            pthread_exit( NULL );
            assert( 0 );
            return NULL;
        }
        pThData->Result = Cnf_GiaSolveOne( pThData->p, pThData->pCnf, pThData->nTimeOut, &pThData->nVars, &pThData->nConfs );
        pThData->fWorking = 0;
    }
    assert( 0 );
    return NULL;
}
int Cec_GiaSplitTestInt( Gia_Man_t * p, int nProcs, int nTimeOut, int nIterMax, int LookAhead, int fVerbose, int fVeryVerbose, int fSilent )
{
    abctime clkTotal = Abc_Clock();
    Par_ThData_t ThData[PAR_THR_MAX];
    pthread_t WorkerThread[PAR_THR_MAX];
    Vec_Ptr_t * vStack;
    Cnf_Dat_t * pCnf;
    double Progress = 0;
    int i, status, nSatVars, nSatConfs;
    int nIter = 0, RetValue = -1, fWorkToDo = 1;
    Abc_CexFreeP( &p->pCexComb );
    if ( fVerbose )
        printf( "Solving CEC problem by cofactoring with the following parameters:\n" );
    if ( fVerbose )
        printf( "Processes = %d   TimeOut = %d sec   MaxIter = %d   LookAhead = %d   Verbose = %d.\n", nProcs, nTimeOut, nIterMax, LookAhead, fVerbose );
    fflush( stdout );
    if ( nProcs == 1 )
        return Cec_GiaSplitTest2( p, nProcs, nTimeOut, nIterMax, LookAhead, fVerbose, fVeryVerbose, fSilent );
    // subtract manager thread
    nProcs--;
    assert( nProcs >= 1 && nProcs <= PAR_THR_MAX );
    // check the problem
    pCnf = Cec_GiaDeriveGiaRemapped( p );
    status = Cnf_GiaSolveOne( p, pCnf, nTimeOut, &nSatVars, &nSatConfs );
    Cnf_DataFree( pCnf );
    if ( fVerbose && status != -1 )
        Cec_GiaSplitPrint( 0, 0, nSatVars, nSatConfs, status, Progress, Abc_Clock() - clkTotal );
    if ( status == 0 )
    {
        if ( !fSilent )
        printf( "The problem is SAT without cofactoring.\n" );
        return 0;
    }
    if ( status == 1 )
    {
        if ( !fSilent )
        printf( "The problem is UNSAT without cofactoring.\n" );
        return 1;
    }
    assert( status == -1 );
    // create local copy
    vStack = Vec_PtrAlloc( 1000 );
    Vec_PtrPush( vStack, Gia_ManDup(p) );
    // start threads
    for ( i = 0; i < nProcs; i++ )
    {
        ThData[i].p        = NULL;
        ThData[i].pCnf     = NULL;
        ThData[i].iThread  = i;
        ThData[i].nTimeOut = nTimeOut;
        ThData[i].fWorking = 0;
        ThData[i].Result   = -1;
        ThData[i].nVars    = -1;
        ThData[i].nConfs   = -1;
        status = pthread_create( WorkerThread + i, NULL,Cec_GiaSplitWorkerThread, (void *)(ThData + i) );  assert( status == 0 );
    }
    // look at the threads
    while ( fWorkToDo )
    {
        fWorkToDo = (int)(Vec_PtrSize(vStack) > 0);
        for ( i = 0; i < nProcs; i++ )
        {
            // check if this thread is working
            if ( ThData[i].fWorking )
            {
                fWorkToDo = 1;
                continue;
            }
            // check if this thread has recently finished
            if ( ThData[i].p != NULL )
            {
                Gia_Man_t * pLast = ThData[i].p;
                int Depth = pLast->vCofVars ? Vec_IntSize(pLast->vCofVars) : 0;
                if ( pLast->vCofVars == NULL )
                    pLast->vCofVars = Vec_IntAlloc( 100 );
                if ( fVerbose )
                    Cec_GiaSplitPrint( i+1, Depth, ThData[i].nVars, ThData[i].nConfs, ThData[i].Result, Progress, Abc_Clock() - clkTotal );
                if ( ThData[i].Result == 0 ) // SAT
                {
                    p->pCexComb = pLast->pCexComb;  pLast->pCexComb = NULL;
                    RetValue = 0;
                    goto finish;
                }
                if ( ThData[i].Result == -1 ) // UNDEC
                {
                    // determine cofactoring variable
                    int nFanouts, Cost, iVar = Gia_SplitCofVar( pLast, LookAhead, &nFanouts, &Cost );
                    // cofactor
                    Gia_Man_t * pPart = Gia_ManDupCofactorVar( pLast, iVar, 0 );
                    pPart->vCofVars = Vec_IntAlloc( Vec_IntSize(pLast->vCofVars) + 1 );
                    Vec_IntAppend( pPart->vCofVars, pLast->vCofVars );
                    Vec_IntPush( pPart->vCofVars, Abc_Var2Lit(iVar, 1) );
                    Vec_PtrPush( vStack, pPart );
                    // print results
                    if ( fVeryVerbose )
                    {
//                        Cec_GiaSplitPrintRefs( pLast );
                        printf( "Var = %5d. Fanouts = %5d. Cost = %8d.  AndBefore = %6d.  AndAfter = %6d.\n", 
                            iVar, nFanouts, Cost, Gia_ManAndNum(pLast), Gia_ManAndNum(pPart) );
//                        Cec_GiaSplitPrintRefs( pPart );
                    }
                    // cofactor
                    pPart = Gia_ManDupCofactorVar( pLast, iVar, 1 );
                    pPart->vCofVars = Vec_IntAlloc( Vec_IntSize(pLast->vCofVars) + 1 );
                    Vec_IntAppend( pPart->vCofVars, pLast->vCofVars );
                    Vec_IntPush( pPart->vCofVars, Abc_Var2Lit(iVar, 1) );
                    Vec_PtrPush( vStack, pPart );
                    // keep working
                    fWorkToDo = 1;
                    nIter++;
                }
                else
                    Progress += 1.0 / pow(2, Depth);
                Gia_ManStopP( &ThData[i].p );
                if ( ThData[i].pCnf == NULL )
                    continue;
                Cnf_DataFree( ThData[i].pCnf );
                ThData[i].pCnf = NULL;
            }
            if ( Vec_PtrSize(vStack) == 0 )
                continue;
            // start a new thread
            assert( ThData[i].p == NULL );
            ThData[i].p = (Gia_Man_t*)Vec_PtrPop( vStack );
            ThData[i].pCnf = Cec_GiaDeriveGiaRemapped( ThData[i].p );
            ThData[i].fWorking = 1;
        }
        if ( nIterMax && nIter >= nIterMax )
            break;
    }
    if ( !fWorkToDo )
        RetValue = 1;
finish:
    // wait till threads finish
    for ( i = 0; i < nProcs; i++ )
        if ( ThData[i].fWorking )
            i = 0;
    // stop threads
    for ( i = 0; i < nProcs; i++ )
    {
        assert( !ThData[i].fWorking );
        // cleanup
        Gia_ManStopP( &ThData[i].p );
        if ( ThData[i].pCnf == NULL )
            continue;
        Cnf_DataFree( ThData[i].pCnf );
        ThData[i].pCnf = NULL;
        // stop
        ThData[i].p = NULL;
        ThData[i].fWorking = 1;
    }
    // finish
    Cec_GiaSplitClean( vStack );
    if ( !fSilent )
    {
        if ( RetValue == 0 )
            printf( "Problem is SAT " );
        else if ( RetValue == 1 )
            printf( "Problem is UNSAT " );
        else if ( RetValue == -1 )
            printf( "Problem is UNDECIDED " );
        else assert( 0 );
        printf( "after %d case-splits.  ", nIter );
        Abc_PrintTime( 1, "Time", Abc_Clock() - clkTotal );
        fflush( stdout );
    }
    return RetValue;
}
int Cec_GiaSplitTest( Gia_Man_t * p, int nProcs, int nTimeOut, int nIterMax, int LookAhead, int fVerbose, int fVeryVerbose, int fSilent )
{
    Abc_Cex_t * pCex = NULL;
    Gia_Man_t * pOne;
    Gia_Obj_t * pObj;
    int i, RetValue1, fOneUndef = 0, RetValue = -1;
    Abc_CexFreeP( &p->pCexComb );
    Gia_ManForEachPo( p, pObj, i )
    {
        pOne = Gia_ManDupOutputGroup( p, i, i+1 );
        if ( fVerbose )
            printf( "\nSolving output %d:\n", i );
        RetValue1 = Cec_GiaSplitTestInt( pOne, nProcs, nTimeOut, nIterMax, LookAhead,  fVerbose, fVeryVerbose, fSilent );
        Gia_ManStop( pOne );
        // collect the result
        if ( RetValue1 == 0 && RetValue == -1 )
        {
            pCex = pOne->pCexComb; pOne->pCexComb = NULL;
            pCex->iPo = i;
            RetValue = 0;
        }
        if ( RetValue1 == -1 )
            fOneUndef = 1;
    }
    if ( RetValue == -1 )
        RetValue = fOneUndef ? -1 : 1;
    else
        p->pCexComb = pCex;
    return RetValue;
}

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

  Synopsis    [Print stats about cofactoring variables.]

  Description []
               
  SideEffects []

  SeeAlso     []

***********************************************************************/
void Cec_GiaPrintCofStats( Gia_Man_t * p )
{
    Gia_Man_t * pCof0, * pCof1;
    Gia_Obj_t * pObj, * pFan0, * pFan1, * pCtrl;
    Vec_Int_t * vMarks;
    int i, Count = 0;
    vMarks = Vec_IntStart( Gia_ManObjNum(p) );
    Gia_ManForEachAnd( p, pObj, i )
    {
        if ( !Gia_ObjIsMuxType(pObj) )
            continue;
        if ( Gia_ObjRecognizeExor(pObj, &pFan0, &pFan1) )
            continue;
        pCtrl = Gia_ObjRecognizeMux( pObj, &pFan1, &pFan0 );
        pCtrl = Gia_Regular(pCtrl);
        Vec_IntAddToEntry( vMarks, Gia_ObjId(p, pCtrl), 1 );
    }
    printf( "The AIG with %d candidate nodes (PI+AND) has %d unique MUX control drivers:\n", 
        Gia_ManCandNum(p), Vec_IntCountPositive(vMarks) );
    Gia_ManLevelNum( p );
    Gia_ManForEachCand( p, pObj, i )
    {
        if ( !Vec_IntEntry(vMarks, i) )
            continue;
        pCof0 = Gia_ManDupCofactorObj( p, i, 0 );
        pCof1 = Gia_ManDupCofactorObj( p, i, 1 );
        printf( "%6d :   ",          Count++ );
        printf( "Obj = %6d   ",      i );
        printf( "MUX refs = %5d   ", Vec_IntEntry(vMarks, i) );
        printf( "Level = %5d   ",    Gia_ObjLevelId(p, i) );
        printf( "Cof0 = %7d   ",     Gia_ManAndNum(pCof0) );
        printf( "Cof1 = %7d   ",     Gia_ManAndNum(pCof1) );
        printf( "\n" );
        Gia_ManStop( pCof0 );
        Gia_ManStop( pCof1 );
    }
    Vec_IntFree( vMarks );
}
void Cec_GiaPrintCofStats2( Gia_Man_t * p )
{
    Gia_Man_t * pCof0, * pCof1;
    Gia_Obj_t * pObj;
    int i;
    Gia_ManLevelNum( p );
    Gia_ManCreateRefs( p );
    Gia_ManForEachPi( p, pObj, i )
    {
        pCof0 = Gia_ManDupCofactorVar( p, i, 0 );
        pCof1 = Gia_ManDupCofactorVar( p, i, 1 );
        printf( "PI %5d :   ",   i );
        printf( "Refs = %5d   ", Gia_ObjRefNum(p, pObj) );
        printf( "Cof0 = %7d   ", Gia_ManAndNum(pCof0) );
        printf( "Cof1 = %7d   ", Gia_ManAndNum(pCof1) );
        printf( "\n" );
        Gia_ManStop( pCof0 );
        Gia_ManStop( pCof1 );
    }
}

#endif // pthreads are used

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


ABC_NAMESPACE_IMPL_END
i">1, m); EXPECT_EQ(2, n); EXPECT_EQ('a', a); EXPECT_EQ('b', b); EXPECT_EQ('c', c); EXPECT_EQ('d', d); } // Tests DoAll(a1, a2, ..., a8). TEST(DoAllTest, EightActions) { int m = 0, n = 0; char a = '\0', b = '\0', c = '\0', d = '\0', e = '\0'; Action<int(int*, int*, char*, char*, char*, char*, // NOLINT char*)> action = DoAll(SetArgPointee<0>(1), SetArgPointee<1>(2), SetArgPointee<2>('a'), SetArgPointee<3>('b'), SetArgPointee<4>('c'), SetArgPointee<5>('d'), SetArgPointee<6>('e'), Return(3)); EXPECT_EQ(3, action.Perform(make_tuple(&m, &n, &a, &b, &c, &d, &e))); EXPECT_EQ(1, m); EXPECT_EQ(2, n); EXPECT_EQ('a', a); EXPECT_EQ('b', b); EXPECT_EQ('c', c); EXPECT_EQ('d', d); EXPECT_EQ('e', e); } // Tests DoAll(a1, a2, ..., a9). TEST(DoAllTest, NineActions) { int m = 0, n = 0; char a = '\0', b = '\0', c = '\0', d = '\0', e = '\0', f = '\0'; Action<int(int*, int*, char*, char*, char*, char*, // NOLINT char*, char*)> action = DoAll(SetArgPointee<0>(1), SetArgPointee<1>(2), SetArgPointee<2>('a'), SetArgPointee<3>('b'), SetArgPointee<4>('c'), SetArgPointee<5>('d'), SetArgPointee<6>('e'), SetArgPointee<7>('f'), Return(3)); EXPECT_EQ(3, action.Perform(make_tuple(&m, &n, &a, &b, &c, &d, &e, &f))); EXPECT_EQ(1, m); EXPECT_EQ(2, n); EXPECT_EQ('a', a); EXPECT_EQ('b', b); EXPECT_EQ('c', c); EXPECT_EQ('d', d); EXPECT_EQ('e', e); EXPECT_EQ('f', f); } // Tests DoAll(a1, a2, ..., a10). TEST(DoAllTest, TenActions) { int m = 0, n = 0; char a = '\0', b = '\0', c = '\0', d = '\0'; char e = '\0', f = '\0', g = '\0'; Action<int(int*, int*, char*, char*, char*, char*, // NOLINT char*, char*, char*)> action = DoAll(SetArgPointee<0>(1), SetArgPointee<1>(2), SetArgPointee<2>('a'), SetArgPointee<3>('b'), SetArgPointee<4>('c'), SetArgPointee<5>('d'), SetArgPointee<6>('e'), SetArgPointee<7>('f'), SetArgPointee<8>('g'), Return(3)); EXPECT_EQ(3, action.Perform(make_tuple(&m, &n, &a, &b, &c, &d, &e, &f, &g))); EXPECT_EQ(1, m); EXPECT_EQ(2, n); EXPECT_EQ('a', a); EXPECT_EQ('b', b); EXPECT_EQ('c', c); EXPECT_EQ('d', d); EXPECT_EQ('e', e); EXPECT_EQ('f', f); EXPECT_EQ('g', g); } // The ACTION*() macros trigger warning C4100 (unreferenced formal // parameter) in MSVC with -W4. Unfortunately they cannot be fixed in // the macro definition, as the warnings are generated when the macro // is expanded and macro expansion cannot contain #pragma. Therefore // we suppress them here. #ifdef _MSC_VER # pragma warning(push) # pragma warning(disable:4100) #endif // Tests the ACTION*() macro family. // Tests that ACTION() can define an action that doesn't reference the // mock function arguments. ACTION(Return5) { return 5; } TEST(ActionMacroTest, WorksWhenNotReferencingArguments) { Action<double()> a1 = Return5(); EXPECT_DOUBLE_EQ(5, a1.Perform(make_tuple())); Action<int(double, bool)> a2 = Return5(); EXPECT_EQ(5, a2.Perform(make_tuple(1, true))); } // Tests that ACTION() can define an action that returns void. ACTION(IncrementArg1) { (*arg1)++; } TEST(ActionMacroTest, WorksWhenReturningVoid) { Action<void(int, int*)> a1 = IncrementArg1(); int n = 0; a1.Perform(make_tuple(5, &n)); EXPECT_EQ(1, n); } // Tests that the body of ACTION() can reference the type of the // argument. ACTION(IncrementArg2) { StaticAssertTypeEq<int*, arg2_type>(); arg2_type temp = arg2; (*temp)++; } TEST(ActionMacroTest, CanReferenceArgumentType) { Action<void(int, bool, int*)> a1 = IncrementArg2(); int n = 0; a1.Perform(make_tuple(5, false, &n)); EXPECT_EQ(1, n); } // Tests that the body of ACTION() can reference the argument tuple // via args_type and args. ACTION(Sum2) { StaticAssertTypeEq<tuple<int, char, int*>, args_type>(); args_type args_copy = args; return get<0>(args_copy) + get<1>(args_copy); } TEST(ActionMacroTest, CanReferenceArgumentTuple) { Action<int(int, char, int*)> a1 = Sum2(); int dummy = 0; EXPECT_EQ(11, a1.Perform(make_tuple(5, Char(6), &dummy))); } // Tests that the body of ACTION() can reference the mock function // type. int Dummy(bool flag) { return flag? 1 : 0; } ACTION(InvokeDummy) { StaticAssertTypeEq<int(bool), function_type>(); function_type* fp = &Dummy; return (*fp)(true); } TEST(ActionMacroTest, CanReferenceMockFunctionType) { Action<int(bool)> a1 = InvokeDummy(); EXPECT_EQ(1, a1.Perform(make_tuple(true))); EXPECT_EQ(1, a1.Perform(make_tuple(false))); } // Tests that the body of ACTION() can reference the mock function's // return type. ACTION(InvokeDummy2) { StaticAssertTypeEq<int, return_type>(); return_type result = Dummy(true); return result; } TEST(ActionMacroTest, CanReferenceMockFunctionReturnType) { Action<int(bool)> a1 = InvokeDummy2(); EXPECT_EQ(1, a1.Perform(make_tuple(true))); EXPECT_EQ(1, a1.Perform(make_tuple(false))); } // Tests that ACTION() works for arguments passed by const reference. ACTION(ReturnAddrOfConstBoolReferenceArg) { StaticAssertTypeEq<const bool&, arg1_type>(); return &arg1; } TEST(ActionMacroTest, WorksForConstReferenceArg) { Action<const bool*(int, const bool&)> a = ReturnAddrOfConstBoolReferenceArg(); const bool b = false; EXPECT_EQ(&b, a.Perform(tuple<int, const bool&>(0, b))); } // Tests that ACTION() works for arguments passed by non-const reference. ACTION(ReturnAddrOfIntReferenceArg) { StaticAssertTypeEq<int&, arg0_type>(); return &arg0; } TEST(ActionMacroTest, WorksForNonConstReferenceArg) { Action<int*(int&, bool, int)> a = ReturnAddrOfIntReferenceArg(); int n = 0; EXPECT_EQ(&n, a.Perform(tuple<int&, bool, int>(n, true, 1))); } // Tests that ACTION() can be used in a namespace. namespace action_test { ACTION(Sum) { return arg0 + arg1; } } // namespace action_test TEST(ActionMacroTest, WorksInNamespace) { Action<int(int, int)> a1 = action_test::Sum(); EXPECT_EQ(3, a1.Perform(make_tuple(1, 2))); } // Tests that the same ACTION definition works for mock functions with // different argument numbers. ACTION(PlusTwo) { return arg0 + 2; } TEST(ActionMacroTest, WorksForDifferentArgumentNumbers) { Action<int(int)> a1 = PlusTwo(); EXPECT_EQ(4, a1.Perform(make_tuple(2))); Action<double(float, void*)> a2 = PlusTwo(); int dummy; EXPECT_DOUBLE_EQ(6, a2.Perform(make_tuple(4.0f, &dummy))); } // Tests that ACTION_P can define a parameterized action. ACTION_P(Plus, n) { return arg0 + n; } TEST(ActionPMacroTest, DefinesParameterizedAction) { Action<int(int m, bool t)> a1 = Plus(9); EXPECT_EQ(10, a1.Perform(make_tuple(1, true))); } // Tests that the body of ACTION_P can reference the argument types // and the parameter type. ACTION_P(TypedPlus, n) { arg0_type t1 = arg0; n_type t2 = n; return t1 + t2; } TEST(ActionPMacroTest, CanReferenceArgumentAndParameterTypes) { Action<int(char m, bool t)> a1 = TypedPlus(9); EXPECT_EQ(10, a1.Perform(make_tuple(Char(1), true))); } // Tests that a parameterized action can be used in any mock function // whose type is compatible. TEST(ActionPMacroTest, WorksInCompatibleMockFunction) { Action<std::string(const std::string& s)> a1 = Plus("tail"); const std::string re = "re"; EXPECT_EQ("retail", a1.Perform(tuple<const std::string&>(re))); } // Tests that we can use ACTION*() to define actions overloaded on the // number of parameters. ACTION(OverloadedAction) { return arg0 ? arg1 : "hello"; } ACTION_P(OverloadedAction, default_value) { return arg0 ? arg1 : default_value; } ACTION_P2(OverloadedAction, true_value, false_value) { return arg0 ? true_value : false_value; } TEST(ActionMacroTest, CanDefineOverloadedActions) { typedef Action<const char*(bool, const char*)> MyAction; const MyAction a1 = OverloadedAction(); EXPECT_STREQ("hello", a1.Perform(make_tuple(false, CharPtr("world")))); EXPECT_STREQ("world", a1.Perform(make_tuple(true, CharPtr("world")))); const MyAction a2 = OverloadedAction("hi"); EXPECT_STREQ("hi", a2.Perform(make_tuple(false, CharPtr("world")))); EXPECT_STREQ("world", a2.Perform(make_tuple(true, CharPtr("world")))); const MyAction a3 = OverloadedAction("hi", "you"); EXPECT_STREQ("hi", a3.Perform(make_tuple(true, CharPtr("world")))); EXPECT_STREQ("you", a3.Perform(make_tuple(false, CharPtr("world")))); } // Tests ACTION_Pn where n >= 3. ACTION_P3(Plus, m, n, k) { return arg0 + m + n + k; } TEST(ActionPnMacroTest, WorksFor3Parameters) { Action<double(int m, bool t)> a1 = Plus(100, 20, 3.4); EXPECT_DOUBLE_EQ(3123.4, a1.Perform(make_tuple(3000, true))); Action<std::string(const std::string& s)> a2 = Plus("tail", "-", ">"); const std::string re = "re"; EXPECT_EQ("retail->", a2.Perform(tuple<const std::string&>(re))); } ACTION_P4(Plus, p0, p1, p2, p3) { return arg0 + p0 + p1 + p2 + p3; } TEST(ActionPnMacroTest, WorksFor4Parameters) { Action<int(int)> a1 = Plus(1, 2, 3, 4); EXPECT_EQ(10 + 1 + 2 + 3 + 4, a1.Perform(make_tuple(10))); } ACTION_P5(Plus, p0, p1, p2, p3, p4) { return arg0 + p0 + p1 + p2 + p3 + p4; } TEST(ActionPnMacroTest, WorksFor5Parameters) { Action<int(int)> a1 = Plus(1, 2, 3, 4, 5); EXPECT_EQ(10 + 1 + 2 + 3 + 4 + 5, a1.Perform(make_tuple(10))); } ACTION_P6(Plus, p0, p1, p2, p3, p4, p5) { return arg0 + p0 + p1 + p2 + p3 + p4 + p5; } TEST(ActionPnMacroTest, WorksFor6Parameters) { Action<int(int)> a1 = Plus(1, 2, 3, 4, 5, 6); EXPECT_EQ(10 + 1 + 2 + 3 + 4 + 5 + 6, a1.Perform(make_tuple(10))); } ACTION_P7(Plus, p0, p1, p2, p3, p4, p5, p6) { return arg0 + p0 + p1 + p2 + p3 + p4 + p5 + p6; } TEST(ActionPnMacroTest, WorksFor7Parameters) { Action<int(int)> a1 = Plus(1, 2, 3, 4, 5, 6, 7); EXPECT_EQ(10 + 1 + 2 + 3 + 4 + 5 + 6 + 7, a1.Perform(make_tuple(10))); } ACTION_P8(Plus, p0, p1, p2, p3, p4, p5, p6, p7) { return arg0 + p0 + p1 + p2 + p3 + p4 + p5 + p6 + p7; } TEST(ActionPnMacroTest, WorksFor8Parameters) { Action<int(int)> a1 = Plus(1, 2, 3, 4, 5, 6, 7, 8); EXPECT_EQ(10 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8, a1.Perform(make_tuple(10))); } ACTION_P9(Plus, p0, p1, p2, p3, p4, p5, p6, p7, p8) { return arg0 + p0 + p1 + p2 + p3 + p4 + p5 + p6 + p7 + p8; } TEST(ActionPnMacroTest, WorksFor9Parameters) { Action<int(int)> a1 = Plus(1, 2, 3, 4, 5, 6, 7, 8, 9); EXPECT_EQ(10 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9, a1.Perform(make_tuple(10))); } ACTION_P10(Plus, p0, p1, p2, p3, p4, p5, p6, p7, p8, last_param) { arg0_type t0 = arg0; last_param_type t9 = last_param; return t0 + p0 + p1 + p2 + p3 + p4 + p5 + p6 + p7 + p8 + t9; } TEST(ActionPnMacroTest, WorksFor10Parameters) { Action<int(int)> a1 = Plus(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); EXPECT_EQ(10 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10, a1.Perform(make_tuple(10))); } // Tests that the action body can promote the parameter types. ACTION_P2(PadArgument, prefix, suffix) { // The following lines promote the two parameters to desired types. std::string prefix_str(prefix); char suffix_char = static_cast<char>(suffix); return prefix_str + arg0 + suffix_char; } TEST(ActionPnMacroTest, SimpleTypePromotion) { Action<std::string(const char*)> no_promo = PadArgument(std::string("foo"), 'r'); Action<std::string(const char*)> promo = PadArgument("foo", static_cast<int>('r')); EXPECT_EQ("foobar", no_promo.Perform(make_tuple(CharPtr("ba")))); EXPECT_EQ("foobar", promo.Perform(make_tuple(CharPtr("ba")))); } // Tests that we can partially restrict parameter types using a // straight-forward pattern. // Defines a generic action that doesn't restrict the types of its // parameters. ACTION_P3(ConcatImpl, a, b, c) { std::stringstream ss; ss << a << b << c; return ss.str(); } // Next, we try to restrict that either the first parameter is a // string, or the second parameter is an int. // Defines a partially specialized wrapper that restricts the first // parameter to std::string. template <typename T1, typename T2> // ConcatImplActionP3 is the class template ACTION_P3 uses to // implement ConcatImpl. We shouldn't change the name as this // pattern requires the user to use it directly. ConcatImplActionP3<std::string, T1, T2> Concat(const std::string& a, T1 b, T2 c) { GTEST_INTENTIONAL_CONST_COND_PUSH_() if (true) { GTEST_INTENTIONAL_CONST_COND_POP_() // This branch verifies that ConcatImpl() can be invoked without // explicit template arguments. return ConcatImpl(a, b, c); } else { // This branch verifies that ConcatImpl() can also be invoked with // explicit template arguments. It doesn't really need to be // executed as this is a compile-time verification. return ConcatImpl<std::string, T1, T2>(a, b, c); } } // Defines another partially specialized wrapper that restricts the // second parameter to int. template <typename T1, typename T2> ConcatImplActionP3<T1, int, T2> Concat(T1 a, int b, T2 c) { return ConcatImpl(a, b, c); } TEST(ActionPnMacroTest, CanPartiallyRestrictParameterTypes) { Action<const std::string()> a1 = Concat("Hello", "1", 2); EXPECT_EQ("Hello12", a1.Perform(make_tuple())); a1 = Concat(1, 2, 3); EXPECT_EQ("123", a1.Perform(make_tuple())); } // Verifies the type of an ACTION*. ACTION(DoFoo) {} ACTION_P(DoFoo, p) {} ACTION_P2(DoFoo, p0, p1) {} TEST(ActionPnMacroTest, TypesAreCorrect) { // DoFoo() must be assignable to a DoFooAction variable. DoFooAction a0 = DoFoo(); // DoFoo(1) must be assignable to a DoFooActionP variable. DoFooActionP<int> a1 = DoFoo(1); // DoFoo(p1, ..., pk) must be assignable to a DoFooActionPk // variable, and so on. DoFooActionP2<int, char> a2 = DoFoo(1, '2'); PlusActionP3<int, int, char> a3 = Plus(1, 2, '3'); PlusActionP4<int, int, int, char> a4 = Plus(1, 2, 3, '4'); PlusActionP5<int, int, int, int, char> a5 = Plus(1, 2, 3, 4, '5'); PlusActionP6<int, int, int, int, int, char> a6 = Plus(1, 2, 3, 4, 5, '6'); PlusActionP7<int, int, int, int, int, int, char> a7 = Plus(1, 2, 3, 4, 5, 6, '7'); PlusActionP8<int, int, int, int, int, int, int, char> a8 = Plus(1, 2, 3, 4, 5, 6, 7, '8'); PlusActionP9<int, int, int, int, int, int, int, int, char> a9 = Plus(1, 2, 3, 4, 5, 6, 7, 8, '9'); PlusActionP10<int, int, int, int, int, int, int, int, int, char> a10 = Plus(1, 2, 3, 4, 5, 6, 7, 8, 9, '0'); // Avoid "unused variable" warnings. (void)a0; (void)a1; (void)a2; (void)a3; (void)a4; (void)a5; (void)a6; (void)a7; (void)a8; (void)a9; (void)a10; } // Tests that an ACTION_P*() action can be explicitly instantiated // with reference-typed parameters. ACTION_P(Plus1, x) { return x; } ACTION_P2(Plus2, x, y) { return x + y; } ACTION_P3(Plus3, x, y, z) { return x + y + z; } ACTION_P10(Plus10, a0, a1, a2, a3, a4, a5, a6, a7, a8, a9) { return a0 + a1 + a2 + a3 + a4 + a5 + a6 + a7 + a8 + a9; } TEST(ActionPnMacroTest, CanExplicitlyInstantiateWithReferenceTypes) { int x = 1, y = 2, z = 3; const tuple<> empty = make_tuple(); Action<int()> a = Plus1<int&>(x); EXPECT_EQ(1, a.Perform(empty)); a = Plus2<const int&, int&>(x, y); EXPECT_EQ(3, a.Perform(empty)); a = Plus3<int&, const int&, int&>(x, y, z); EXPECT_EQ(6, a.Perform(empty)); int n[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; a = Plus10<const int&, int&, const int&, int&, const int&, int&, const int&, int&, const int&, int&>(n[0], n[1], n[2], n[3], n[4], n[5], n[6], n[7], n[8], n[9]); EXPECT_EQ(55, a.Perform(empty)); } class NullaryConstructorClass { public: NullaryConstructorClass() : value_(123) {} int value_; }; // Tests using ReturnNew() with a nullary constructor. TEST(ReturnNewTest, NoArgs) { Action<NullaryConstructorClass*()> a = ReturnNew<NullaryConstructorClass>(); NullaryConstructorClass* c = a.Perform(make_tuple()); EXPECT_EQ(123, c->value_); delete c; } class UnaryConstructorClass { public: explicit UnaryConstructorClass(int value) : value_(value) {} int value_; }; // Tests using ReturnNew() with a unary constructor. TEST(ReturnNewTest, Unary) { Action<UnaryConstructorClass*()> a = ReturnNew<UnaryConstructorClass>(4000); UnaryConstructorClass* c = a.Perform(make_tuple()); EXPECT_EQ(4000, c->value_); delete c; } TEST(ReturnNewTest, UnaryWorksWhenMockMethodHasArgs) { Action<UnaryConstructorClass*(bool, int)> a = ReturnNew<UnaryConstructorClass>(4000); UnaryConstructorClass* c = a.Perform(make_tuple(false, 5)); EXPECT_EQ(4000, c->value_); delete c; } TEST(ReturnNewTest, UnaryWorksWhenMockMethodReturnsPointerToConst) { Action<const UnaryConstructorClass*()> a = ReturnNew<UnaryConstructorClass>(4000); const UnaryConstructorClass* c = a.Perform(make_tuple()); EXPECT_EQ(4000, c->value_); delete c; } class TenArgConstructorClass { public: TenArgConstructorClass(int a1, int a2, int a3, int a4, int a5, int a6, int a7, int a8, int a9, int a10) : value_(a1 + a2 + a3 + a4 + a5 + a6 + a7 + a8 + a9 + a10) { } int value_; }; // Tests using ReturnNew() with a 10-argument constructor. TEST(ReturnNewTest, ConstructorThatTakes10Arguments) { Action<TenArgConstructorClass*()> a = ReturnNew<TenArgConstructorClass>(1000000000, 200000000, 30000000, 4000000, 500000, 60000, 7000, 800, 90, 0); TenArgConstructorClass* c = a.Perform(make_tuple()); EXPECT_EQ(1234567890, c->value_); delete c; } // Tests that ACTION_TEMPLATE works when there is no value parameter. ACTION_TEMPLATE(CreateNew, HAS_1_TEMPLATE_PARAMS(typename, T), AND_0_VALUE_PARAMS()) { return new T; } TEST(ActionTemplateTest, WorksWithoutValueParam) { const Action<int*()> a = CreateNew<int>(); int* p = a.Perform(make_tuple()); delete p; } // Tests that ACTION_TEMPLATE works when there are value parameters. ACTION_TEMPLATE(CreateNew, HAS_1_TEMPLATE_PARAMS(typename, T), AND_1_VALUE_PARAMS(a0)) { return new T(a0); } TEST(ActionTemplateTest, WorksWithValueParams) { const Action<int*()> a = CreateNew<int>(42); int* p = a.Perform(make_tuple()); EXPECT_EQ(42, *p); delete p; } // Tests that ACTION_TEMPLATE works for integral template parameters. ACTION_TEMPLATE(MyDeleteArg, HAS_1_TEMPLATE_PARAMS(int, k), AND_0_VALUE_PARAMS()) { delete get<k>(args); } // Resets a bool variable in the destructor. class BoolResetter { public: explicit BoolResetter(bool* value) : value_(value) {} ~BoolResetter() { *value_ = false; } private: bool* value_; }; TEST(ActionTemplateTest, WorksForIntegralTemplateParams) { const Action<void(int*, BoolResetter*)> a = MyDeleteArg<1>(); int n = 0; bool b = true; BoolResetter* resetter = new BoolResetter(&b); a.Perform(make_tuple(&n, resetter)); EXPECT_FALSE(b); // Verifies that resetter is deleted. } // Tests that ACTION_TEMPLATES works for template template parameters. ACTION_TEMPLATE(ReturnSmartPointer, HAS_1_TEMPLATE_PARAMS(template <typename Pointee> class, Pointer), AND_1_VALUE_PARAMS(pointee)) { return Pointer<pointee_type>(new pointee_type(pointee)); } TEST(ActionTemplateTest, WorksForTemplateTemplateParameters) { using ::testing::internal::linked_ptr; const Action<linked_ptr<int>()> a = ReturnSmartPointer<linked_ptr>(42); linked_ptr<int> p = a.Perform(make_tuple()); EXPECT_EQ(42, *p); } // Tests that ACTION_TEMPLATE works for 10 template parameters. template <typename T1, typename T2, typename T3, int k4, bool k5, unsigned int k6, typename T7, typename T8, typename T9> struct GiantTemplate { public: explicit GiantTemplate(int a_value) : value(a_value) {} int value; }; ACTION_TEMPLATE(ReturnGiant, HAS_10_TEMPLATE_PARAMS( typename, T1, typename, T2, typename, T3, int, k4, bool, k5, unsigned int, k6, class, T7, class, T8, class, T9, template <typename T> class, T10), AND_1_VALUE_PARAMS(value)) { return GiantTemplate<T10<T1>, T2, T3, k4, k5, k6, T7, T8, T9>(value); } TEST(ActionTemplateTest, WorksFor10TemplateParameters) { using ::testing::internal::linked_ptr; typedef GiantTemplate<linked_ptr<int>, bool, double, 5, true, 6, char, unsigned, int> Giant; const Action<Giant()> a = ReturnGiant< int, bool, double, 5, true, 6, char, unsigned, int, linked_ptr>(42); Giant giant = a.Perform(make_tuple()); EXPECT_EQ(42, giant.value); } // Tests that ACTION_TEMPLATE works for 10 value parameters. ACTION_TEMPLATE(ReturnSum, HAS_1_TEMPLATE_PARAMS(typename, Number), AND_10_VALUE_PARAMS(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10)) { return static_cast<Number>(v1) + v2 + v3 + v4 + v5 + v6 + v7 + v8 + v9 + v10; } TEST(ActionTemplateTest, WorksFor10ValueParameters) { const Action<int()> a = ReturnSum<int>(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); EXPECT_EQ(55, a.Perform(make_tuple())); } // Tests that ACTION_TEMPLATE and ACTION/ACTION_P* can be overloaded // on the number of value parameters. ACTION(ReturnSum) { return 0; } ACTION_P(ReturnSum, x) { return x; } ACTION_TEMPLATE(ReturnSum, HAS_1_TEMPLATE_PARAMS(typename, Number), AND_2_VALUE_PARAMS(v1, v2)) { return static_cast<Number>(v1) + v2; } ACTION_TEMPLATE(ReturnSum, HAS_1_TEMPLATE_PARAMS(typename, Number), AND_3_VALUE_PARAMS(v1, v2, v3)) { return static_cast<Number>(v1) + v2 + v3; } ACTION_TEMPLATE(ReturnSum, HAS_2_TEMPLATE_PARAMS(typename, Number, int, k), AND_4_VALUE_PARAMS(v1, v2, v3, v4)) { return static_cast<Number>(v1) + v2 + v3 + v4 + k; } TEST(ActionTemplateTest, CanBeOverloadedOnNumberOfValueParameters) { const Action<int()> a0 = ReturnSum(); const Action<int()> a1 = ReturnSum(1); const Action<int()> a2 = ReturnSum<int>(1, 2); const Action<int()> a3 = ReturnSum<int>(1, 2, 3); const Action<int()> a4 = ReturnSum<int, 10000>(2000, 300, 40, 5); EXPECT_EQ(0, a0.Perform(make_tuple())); EXPECT_EQ(1, a1.Perform(make_tuple())); EXPECT_EQ(3, a2.Perform(make_tuple())); EXPECT_EQ(6, a3.Perform(make_tuple())); EXPECT_EQ(12345, a4.Perform(make_tuple())); } #ifdef _MSC_VER # pragma warning(pop) #endif } // namespace gmock_generated_actions_test } // namespace testing