-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbdd14.w
3280 lines (2918 loc) · 112 KB
/
bdd14.w
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
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
\datethis
@*Intro. This program is the fourteenth in a series of exploratory studies by
which I'm attempting to gain first-hand experience with OBDD structures, as I
prepare Section 7.1.4 of {\sl The Art of Computer Programming}.
It's basically the same as {\mc BDD11}, but extended to include some
rudimentary methods for changing and ``sifting'' the order of variables.
In this program I try to implement simplified versions of the basic routines
that are needed in a ``large'' BDD package.
\def\<#1>{\hbox{$\langle\,$#1$\,\rangle$}}
\chardef\ttv='174 % vertical line
\chardef\tta='046 % ampersand
\chardef\tth='136 % hat
\chardef\ttt='176 % tilde
The computation is governed by primitive commands in a language called BDDL;
these commands can either be
read from a file or typed online (or both).
@^BDDL, a primitive language for BDD calculations@>
BDDL commands have the following simple syntax, where \<number> denotes
a nonnegative decimal integer:
$$\eqalign{
&\<const>\gets\.{c0}\mid\.{c1}\cr
&\<var>\gets\.x\<number>\cr
&\<func>\gets\.f\<number>\cr
&\<atom>\gets\<const>\mid\<var>\mid\<func>\cr
&\<expr>\gets\<unop>\<atom>\mid
\<atom>\<binop>\<atom>\mid
\<atom>\.{[y]}\mid\cr
&\hskip15em \<atom>\<ternop>\<atom>\<ternop>\<atom>\cr
&\<command>\gets\<special>\mid\<func>\.=\<expr>\mid\<func>\.{=.}\mid
\.y\<number>\.=\<atom>\mid\.y\<number>\.{=.}\cr}$$
The special commands \<special>,
@^Special commands@>
@^Commands@>
the unary operators \<unop>, the binary operators \<binop>, and the
ternary operators \<ternop> are explained below. One short example
will give the general flavor: After the commands
$$\halign{\qquad\tt#\hfil\cr
f1=x1{\tth}x2\cr
f2=x3{\ttv}x4\cr
f1=f1{\tta}f2\cr
f2={\ttt}f1\cr}$$
the function $f_1$ will be
$(x_1\oplus x_2)\land(x_3\lor x_4)$,
and $f_2$ will be $\lnot f_1$.
Then `\.{f1=.}' will undefine~$f_1$.
If the command line specifies an input file, all commands are taken
from that file and standard input is ignored. Otherwise the user is
prompted for commands.
For simplicity, I do my own memory allocation in a big array
called |mem|. The bottom part of that array is devoted to
BDD nodes, which each occupy two octabytes. The upper part
is divided into dynamically allocated pages of a fixed size
(usually 4096 bytes). The cache of computed results, and
the hash tables for each variable, are kept in arrays whose elements
appear in the upper pages. These elements
need not be consecutive, because the $k$th byte of each dynamic array
is kept in location |mem[b[k>>12]+(k&0xfff)]|, for some array~|b| of base
addresses.
Each node of the BDD base is responsible for roughly 28 bytes in |mem|,
assuming 16 bytes for the node itself, plus about 8 for its entry in
a hash table, plus about 4 for its entry in a cache. (I could reduce
the storage cost from 28 to 21 by choosing algorithms that run slower; but I
decided to give up some space in the interests of time. For example,
I'm devoting four bytes to each reference count, so that there's no
need to consider saturation. And this program uses linear probing for
its hash tables, at the expense of about 3 bytes per node, because
I like the sequential memory accesses of linear probing.)
Many compile-time parameters affect the sizes of various tables and the
heuristic strategies of various methods adopted here.
To browse through them all, see the entry ``Tweakable parameters''
in the index at the end.
@^Tweakable parameters@>
@ Here's the overall program structure:
@c
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include "gb_flip.h" /* random number generator */
#define verbose Verbose /* because `|verbose|' is |long| in libgb */
@<Type definitions@>@;
@<Global variables@>@;
@<Templates for subroutines@>@;
@<Subroutines@>@;
@#
main (int argc, char *argv[])
{
@<Local variables@>;@#
@<Check the command line@>;
@<Initialize everything@>;
while (1) @<Read a command and obey it; |goto alldone| if done@>;
alldone: @<Print statistics about this run@>;
exit(0); /* normal termination */
}
@ @d file_given (argc==2)
@<Check the command...@>=
if (argc>2 || (file_given && !(infile=fopen(argv[1],"r")))) {
fprintf(stderr,"Usage: %s [commandfile]\n",argv[0]);
exit(-1);
}
@ @<Glob...@>=
FILE *infile; /* input file containing commands */
int verbose=-1; /* master control for debugging output; $-1$ gives all */
@ @<Initialize everything@>=
gb_init_rand(0); /* initialize the random number generator */
@ One of the main things I hope to learn with this program is the total
number of |mems| that the computation needs, namely the total number of
memory references to octabytes.
I'm not sure how many mems to charge for recursion overhead. A machine
like \.{MMIX} needs to use memory only when the depth gets sufficiently
deep that 256 registers aren't enough; then it needs two mems for
each saved item (one to push it and another to pop it). Most
of \.{MMIX}'s recursive activity takes place in the deepest levels, whose
parameters never need to descend to memory. So I'm making a separate
count of |rmems|, the number of entries to recursive subroutines.
Some of the mems are classified as |zmems|, because they arise only when
zeroing out pages of memory during initializations.
@d o mems++ /* a convenient macro for instrumenting a memory access */
@d oo mems+=2
@d ooo mems+=3
@d oooo mems+=4
@<Print statistics about this run@>=
printf("Job stats:\n");
printf(" %llu mems plus %llu rmems plus %llu zmems\n",mems,rmems,zmems);
@<Print total memory usage@>;
@ @<Sub...@>=
void show_stats(void) {
printf("stats: %d/%d nodes, %d dead, %d pages,",
totalnodes,nodeptr-botsink,deadnodes,topofmem-pageptr);
printf(" %llu mems, %llu rmems, %llu zmems\n",mems,rmems,zmems);
}
@ This program uses `|long long|' to refer to 64-bit integers,
because a single `|long|' isn't treated consistently by the
\CEE/~compilers available to me. (When I first learned~\CEE/,
`|int|' was traditionally `|short|', so I was obliged
to say `|long|' when I wanted 32-bit integers. Consequently
the programs of the Stanford GraphBase, written in the 90s,
now get 64-bit integers---contrary to my original intent.
C'est tragique; c'est la vie.)
@<Glob...@>=
unsigned long long mems, rmems, zmems; /* mem counters */
@ @<Initialize everything@>+=
if (sizeof(long long)!=8) {
fprintf(stderr,"Sorry, I assume that sizeof(long long) is 8!\n");
exit(-2);
}
@ Speaking of compilers, the one I use at present insists that
pointers occupy 64 bits. As a result, I need to pack and unpack
pointer data, in all the key data structures of this program;
otherwise I would basically be giving up half of my memory and half
of the hardware cache.
I could solve this problem by using arrays with integer subscripts.
Indeed, that approach would be simple and clean.
But I anticipate doing some fairly long calculations, and
speed is also important to me. So I've chosen a slightly more
complex (and slightly dirtier) approach, equivalent to using
short pointers; I wrap such pointers up with syntax that doesn't
offend my compiler. The use of this scheme allows me to use
the convenient syntax of~\CEE/ for fields within structures.
Namely, data is stored here with a type called |addr|, which is simply
an unsigned 32-bit integer. An |addr| contains
all the information of a pointer, since I'm not planning to use
this program with more than $2^{32}$ bytes of memory.
It has a special name only to indicate its pointerly nature.
With this approach the program goes fast, as with usual pointers,
because it doesn't have to shift left by 4~bits and add the base
address of~|mem| whenever addressing the memory. But I do limit
myself to BDD bases of at most about 30 million nodes.
(At the cost of shift-left-four each time, I could extend this
scheme to handling a 35-bit address space, if I ever get a
computer with 32 gigabytes of RAM. I~still would want to keep
32-bit pointers in memory, in order to double the effective cache size.)
The |addr_| macro converts an arbitrary pointer to an |addr|.
@d addr_(p) ((addr)(size_t)(p))
@<Type def...@>=
typedef unsigned int addr;
@*Dynamic arrays. Before I get into the BDD stuff, I might as well
give myself some infrastructure to work with.
The giant |mem| array mentioned earlier has nodes at the bottom,
in locations |mem| through |nodeptr-1|. It has pages at the top,
in locations |pageptr| through |mem+memsize-1|. We must therefore keep
|nodeptr<=pageptr|.
A node has four fields, called |lo|, |hi|, |xref|, and |index|.
I shall explain their significance eventually,
when I {\it do\/} ``get into the BDD stuff.''
A page is basically unstructured, although we will eventually fill
it either with hash-table data or cache memos.
The |node_| and |page_| macros are provided to make pointers
from stored items of type |addr|.
@s node int
@s page int
@^Tweakable parameters@>
@d logpagesize 12 /* must be at least 4 */
@d memsize (1<<29) /* bytes in |mem|, must be a multiple of |pagesize| */
@#
@d pagesize (1<<logpagesize) /* the number of bytes per page */
@d pagemask (pagesize-1)
@d pageints (pagesize/sizeof(int))
@d node_(a) ((node*)(size_t)(a))
@d page_(a) ((page*)(size_t)(a))
@<Type...@>=
typedef struct node_struct {
addr lo,hi;
int xref; /* reference count minus one */
unsigned int index; /* variable ID followed by random bits */
} node;
typedef struct page_struct {
addr dat[pageints];
} page;
@ Here's how we launch the dynamic memory setup.
Incidentally, I tried to initialize |mem| by declaring it to be
a variable of type |void*|, then saying `|mem=malloc(memsize)|'.
But that failed spectacularly, because the geniuses who developed
the standard library for my 64-bit version of Linux decided in their
great wisdom to make |malloc| return a huge pointer like
|0x2adaf3739010|, even when the program could fit comfortably in
a 30-bit address space. D'oh.
@d topofmem ((page*)&mem[memsize])
@<Initialize everything@>+=
botsink=(node*)mem; /* this is the sink node for the all-zero function */
topsink=botsink+1; /* this is the sink node for the all-one function */
o,botsink->lo=botsink->hi=addr_(botsink);
o,topsink->lo=topsink->hi=addr_(topsink);
oo,botsink->xref=topsink->xref=0;
oooo,botsink->index=gb_next_rand();
oooo,topsink->index=gb_next_rand();
totalnodes=2;
nodeptr=topsink+1;
pageptr=topofmem;
@ @<Glob...@>=
char mem[memsize]; /* where we store most of the stuff */
node *nodeptr; /* the smallest unused node in |mem| */
page *pageptr; /* the smallest used page in |mem| */
node *nodeavail; /* stack of nodes available for reuse */
page *pageavail; /* stack of pages available for reuse */
node *botsink, *topsink; /* the sink nodes, which never go away */
int totalnodes; /* this many nodes are currently in use */
int deadnodes; /* and this many of them currently have |xref<0| */
int leasesonlife=10;
@ Here's how we get a fresh (but uninitialized) node.
The |nodeavail| stack is linked by its |xref| fields.
If memory is completely full, |NULL| is returned. In such cases
we need not abandon all hope; a garbage collection may be able
to reclaim enough memory to continue. (I've tried to write this
entire program in such a way that such temporary failures are harmless.)
@<Sub...@>=
node* reserve_node(void) {
register node *r=nodeavail;
if (r) o,nodeavail=node_(nodeavail->xref);
else {
r=nodeptr;
if (r<(node*)pageptr) nodeptr++;
else {
leasesonlife--;
fprintf(stderr,"NULL node forced (%d pages, %d nodes, %d dead)\n",
topofmem-pageptr,nodeptr-botsink,deadnodes);
fprintf(stderr,"(I will try %d more times)\n",leasesonlife);
if (leasesonlife==0) {
show_stats();@+exit(-98); /* sigh */
}
return NULL;
}
}
totalnodes++;
return r;
}
@ Conversely, nodes can always be recycled. In such cases, there
had better not be any other nodes pointing to them.
@<Sub...@>=
void free_node(register node *p) {
o,p->xref=addr_(nodeavail);
nodeavail=p;
totalnodes--;
}
@ Occupation and liberation of pages is similar, but it takes place
at the top of |mem|.
@<Sub...@>=
page* reserve_page(void) {
register page *r=pageavail;
if (r) o,pageavail=page_(pageavail->dat[0]);
else {
r=pageptr-1;
if ((node*)r>=nodeptr) pageptr=r;
else {
leasesonlife--;
fprintf(stderr,"NULL page forced (%d pages, %d nodes, %d dead)\n",
topofmem-pageptr,nodeptr-botsink,deadnodes);
fprintf(stderr,"(I will try %d more times)\n",leasesonlife);
if (leasesonlife==0) {
show_stats();@+exit(-97); /* sigh */
}
return NULL;
}
}
return r;
}
@#
void free_page(register page *p) {
o,p->dat[0]=addr_(pageavail);
pageavail=p;
}
@ @<If there are at least three free pages...@>=
j=(node*)(pageptr-3)-nodeptr;
if (j>=0) {
for (p=nodeavail;p&&j<3;o,p=(node_(p->xref))) j++;
if (j>=3) break;
}
@ @<Print total memory usage@>=
j=nodeptr-(node*)mem; k=topofmem-pageptr;
printf(" %llu bytes of memory (%d nodes, %d pages)\n",
((long long)j)*sizeof(node)+((long long)k)*sizeof(page),j,k);
@ @<Local variables@>=
register int j,k;
@*Variables and hash tables. Our BDD base represents functions
on the variables $x_v$ for $0\le v<|varsize|$, where |varsize|
is a power of~2.
When $x_v$ is first mentioned, we create a |var| record for it,
from which it is possible to find all the nodes that branch on
this variable. The list of all such nodes is implicitly present
in a hash table, which contains a pointer to node $(v,l,h)$
near the hash address of the pair $(l,h)$. This hash table is
called the {\it unique table\/} for~$v$, because of the BDD property
that no two nodes have the same triple of values $(v,l,h)$.
When there are $n$ nodes that branch on $x_v$, the unique table
for~$v$ has size $m$, where $m$ is a power of~2 such that
$n$ lies between $m/8$ and $3m/4$, inclusive. Thus at least
one of every eight table slots is occupied, and
at least one of every four is unoccupied, on the average.
If $n=25$, for example, we might have $m=64$ or $m=128$; but $m=256$ would make
the table too sparse.
Each unique table has a maximum size, which must be small enough
that we don't need too many base addresses for its pages, yet large
enough that we can accommodate big BDDs. If, for example,
|logmaxhashsize=19| and |logpagesize=12|, a unique table might contain as
many as $2^{19}$ |addr|s, filling $2^9$ pages. Then we must make room for
512 base addresses in each |var| record, and we can handle up to
$2^{19}-2^{17}=393216$ nodes that branch on any particular variable.
@^Tweakable parameters@>
@d logmaxhashsize 21
@d slotsperpage (pagesize/sizeof(addr))
@d maxhashpages (((1<<logmaxhashsize)+slotsperpage-1)/slotsperpage)
@<Type def...@>=
typedef struct var_struct {
addr proj; /* address of the projection function $x_v$ */
addr repl; /* address of the replacement function $y_v$ */
int free; /* the number of unused slots in the unique table for $v$ */
int mask; /* the number of slots in that unique table, times 4, minus 1 */
addr base[maxhashpages]; /* base addresses for its pages */
int name; /* the user's name (subscript) for this variable */
unsigned int timestamp; /* time stamp for composition */
int aux; /* flag used by |math_print| or the sifting algorithm */
struct var_struct *up,*down; /* the neighboring active variables */
} var;
@ Every node |p| that branches on $x_v$ in the BDD has a field |p->index|,
whose leftmost |logvarsize| bits contain the index~$v$. The rightmost
|32-logvarsize| bits of |p->index| are chosen randomly, in order to
provide convenient hash coding.
The SGB random-number generator used here makes four memory references
per number generated.
N.B.: The hashing scheme will fail dramatically unless
|logvarsize+logmaxhashsize<=32|.
@^Tweakable parameters@>
@d logvarsize 10
@d varsize (1<<logvarsize) /* the number of permissible variables */
@d varpart(x) ((x)>>(32-logvarsize))
@d initnewnode(p,v,l,h) oo,p->lo=addr_(l),p->hi=addr_(h),p->xref=0,@|
oooo,p->index=((v)<<(32-logvarsize))+(gb_next_rand()>>(logvarsize-1))
@ Variable $x_v$ in this documentation means the variable whose information
record is |varhead[v]|. But the user's variable `\.{x5}' might not be
represented by |varhead[5]|, because the ordering of variables can change
as a program runs. If \.{x5} is really the variable in |varhead[13]|, say, we
will have |varmap[5]=13| and |varhead[13].name=5|.
@d topofvars &varhead[varsize]
@<Glob...@>=
var varhead[varsize]; /* basic info about each variable */
var *tvar=topofvars; /* threshold for verbose printouts */
int varmap[varsize]; /* the variable that has a given name */
@ @<Init...@>=
for (k=0;k<varsize;k++) varmap[k]=k;
@ The simplest nonconstant Boolean expression is a projection function, $x_v$.
We access it with the following subroutine, creating it from scratch
if necessary.
(The calling routine will have ensured that at least one free page
and at least one free node exist when |projection| is invoked.)
Beware: Garbage collection might occur when |unique_find| is called here.
@<Sub...@>=
node* projection(int v) {
register node *p;
register var *hv=&varhead[v];
o,p=node_(hv->proj);
if (p) return p; /* the projection function has already been created */
o,hv->base[0]=addr_(reserve_page()); /* it won't be |NULL| */
@<Create a unique table for variable |hv| with size 2@>;
p=unique_find(&varhead[v],botsink,topsink); /* see below */
oooo,botsink->xref++,topsink->xref++;
o,hv->proj=addr_(p); /* |p| won't be |NULL| either */
if (verbose&2) printf(" %x=x%d\n",id(p),v);
o,hv->name=v;
return p;
}
@ I sometimes like to use a subroutine before I'm in the mood to write
its innards. In such cases, a pre-specification
like the one given here allows me to procrastinate.
@<Templates for subroutines@>=
node* unique_find(var *v, node *l, node *h);
@ Now, however, I'm ready to tackle the subroutine just named, |unique_find|,
which is one of the most crucial in the entire program.
Given a variable~|v|, together with node pointers |l| and~|h|, we often
want to see if the BDD base contains a node $(v,l,h)$---namely, a branch
on~$x_v$ with {\mc LO} pointer~|l| and {\mc HI} pointer~|h|.
If no such node exists, we want to create it. The subroutine should return a
pointer to that (unique) node. Furthermore,
the reference counts of |l| and |h| should be decreased afterwards.
To do this task, we look for $(l,h)$ in the unique table for $v$,
using the hash code
$$\hbox{|(l->index<<3)^(h->index<<2)|}.$$
(This hash code is a multiple of~4,
the size of each entry in the unique table.)
Several technicalities should be noted. First, no branch is needed
when $l=h$. Second, we consider that a
new reference is being made to the node returned, as well as to nodes
|l| and~|h| if a new node is created;
the |xref| fields (reference counts) must be adjusted accordingly.
Third, we might discover that the node exists, but it is dead;
in other words, all prior links to it might have gone away, but we haven't
discarded it yet. In such a case we should bring it back to life.
Fourth, |l| and |h| will not become dead
when their reference counts decrease, because the calling routine knows them.
And finally, in the worst case we won't have room for a new node, so we'll
have to return |NULL|. The calling routine must be prepared to cope with
such failures (which we hope are only temporary).
The following inscrutable macros try to make my homegrown dynamic array
addressing palatable. I have to admit that I didn't get them right
the first time. Or even the second time. Or even \dots~.
@d hashcode(l,h) ((addr*)(size_t)(oo,((l)->index<<3)^((h)->index<<2)))
@d hashedcode(p) hashcode(node_(p->lo),node_(p->hi))
@d addr__(x) (*((addr*)(size_t)(x)))
@d fetchnode(v,k) node_(addr__(v->base[(k)>>logpagesize]+((k)&pagemask)))
@d storenode(v,k,p) o,addr__(v->base[(k)>>logpagesize]+((k)&pagemask))=addr_(p)
@<Sub...@>=
node* unique_find(var *v, node *l, node *h) {
register int j,k,mask,free;
register addr *hash;
register node *p,*r;
if (l==h) { /* easy case */
return oo,l->xref--,l; /* |l->xref| will still be $\ge0$ */
}
restart: o,mask=v->mask,free=v->free;
for (hash=hashcode(l,h);;hash++) { /* ye olde linear probing */
k=addr_(hash)&mask;
oo,p=fetchnode(v,k);
if (!p) goto newnode;
if (node_(p->lo)==l && node_(p->hi)==h) break;
}
if (o,p->xref<0) {
deadnodes--,o,p->xref=0; /* a lucky hit; its children are alive */
return p;
}
oooo,l->xref--,h->xref--;
return o,p->xref++,p;
newnode: @<Periodically try to conserve space@>;
@<Create a new node and return it@>;
}
@ @<Templates for subroutines@>=
void recursively_revive(node *p); /* recursive resuscitation */
void recursively_kill(node *p); /* recursive euthanization */
void collect_garbage(int level); /* invocation of the recycler */
@ Before we can call |unique_find|, we need a hash table to work with.
We start small.
@d storenulls(k) *(long long*)(size_t)(k)=0LL;
@<Create a unique table for variable |hv| with size 2@>=
o,hv->free=2,hv->mask=7;
storenulls(hv->base[0]); /* both slots start out |NULL| */
zmems++;
@ A little timer starts ticking at the beginning of this program,
and it advances whenever we reach the present point.
Whenever the timer reaches a multiple of |timerinterval|, we pause to
examine the memory situation, in an attempt to keep node growth under
control.
Memory can be conserved in two ways. First, we can recycle all the dead
nodes. That's a somewhat expensive proposition; but it's worthwhile
if the number of such nodes is more than, say, 1/8 of the total
number of nodes allocated. Second, we can try to change the ordering
of the variables. The present program includes Rudell's
@^Rudell, Richard Lyle@>
``sifting algorithm'' for dynamically improving the variable order; but
it invokes that algorithm only under user control. Perhaps I will have
time someday to make reordering more automatic.
@^Tweakable parameters@>
@d timerinterval 1024
@d deadfraction 8
@<Periodically try to conserve space@>=
if ((++timer%timerinterval)==0) {
if (deadnodes>totalnodes/deadfraction) {
collect_garbage(0);
goto restart; /* the hash table might now be different */
}
}
@ @<Glob...@>=
unsigned long long timer;
@ Brand-new nodes enter the fray here.
@<Create a new node and return it@>=
p=reserve_node();
if (!p) goto cramped; /* sorry, there ain't no more room */
if (--free<=mask>>4) {
free_node(p);
@<Double the table size and |goto restart|@>;
}
storenode(v,k,p);@+o,v->free=free;
initnewnode(p,v-varhead,l,h);
return p;
cramped: /* after failure, we need to keep the xrefs tidy */
deref(l); /* decrease |l->xref|, and recurse if it becomes dead */
deref(h); /* ditto for |h| */
return NULL;
@ We get to this part of the code when the table has become too dense.
The density will now decrease from 3/4 to 3/8.
@<Double the table size and |goto restart|@>=
{
register int newmask=mask+mask+1,kk=newmask>>logpagesize;
if (verbose&256)
printf("doubling the hash table for level %d(x%d) (%d slots)\n",
v-varhead,v->name,(newmask+1)/sizeof(addr));
if (kk) @<Reserve new all-|NULL| pages for the bigger table@>@;
else {
for (k=v->base[0]+mask+1;k<v->base[0]+newmask;k+=sizeof(long long))
storenulls(k);
zmems+=(newmask-mask)/sizeof(long long);
}
@<Rehash everything in the low half@>;
v->mask=newmask; /* mems are counted after restarting */
v->free=free+1+(newmask-mask)/sizeof(addr);
goto restart;
}
@ @d maxmask ((1<<logmaxhashsize)*sizeof(addr)-1)
/* the biggest possible |mask| */
@<Reserve new all-|NULL| pages for the bigger table@>=
{
if (newmask>maxmask) { /* too big: can't go there */
if (verbose&(2+256+512))
printf("profile limit reached for level %d(x%d)\n",v-varhead,v->name);
goto cramped;
}
for (k=(mask>>logpagesize)+1;k<=kk;k++) {
o,v->base[k]=addr_(reserve_page());
if (!v->base[k]) { /* oops, we're out of space */
for (k--;k>mask>>logpagesize;k--) {
o,free_page(page_(v->base[k]));
}
goto cramped;
}
for (j=v->base[k];j<v->base[k]+pagesize;j+=sizeof(long long))
storenulls(j);
zmems+=pagesize/sizeof(long long);
}
}
@ Some subtle cases can arise at this point.
For example, consider the hash table
{\let\\=\Lambda $(a,\\,\\,b)$, with hash$(a)=3$ and hash$(b)=7$; when
doubling the size, we need to rehash $a$ twice, going from
the doubled-up table
$(a,\\,\\,b,\\,\\,\\,\\)$ to
$(\\,\\,\\,b,a,\\,\\,\\)$ to
$(\\,\\,\\,\\,a,\\,\\,b)$ to
$(\\,\\,\\,a,\\,\\,\\,b)$.}
I learned this interesting algorithm from Rick Rudell.
@^Rudell, Richard Lyle@>
@<Rehash everything in the low half@>=
for (k=0;k<newmask;k+=sizeof(addr)) {
oo,r=fetchnode(v,k);
if (r) {
storenode(v,k,NULL); /* prevent propagation past this slot */
for (o,hash=hashedcode(r);;hash++) {
j=addr_(hash)&newmask;
oo,p=fetchnode(v,j);
if (!p) break;
}
storenode(v,j,r);
}@+else if (k>mask) break; /* see the example above */
}
@ While I've got linear probing firmly in mind, I might as well
write a subroutine that will be needed later for garbage collection.
The |table_purge| routine deletes all dead nodes that branch
on a given variable~$x_v$.
@<Sub...@>=
void table_purge(var *v) {
register int free,i,j,jj,k,kk,mask,newmask,oldtotal;
register node *p, *r;
register addr *hash;
o,mask=v->mask,free=v->free;
if (o,v->proj) { /* |v->proj!=0| if and only if $x_v$ exists */
oldtotal=totalnodes;
for (k=0;k<mask;k+=sizeof(addr)) {
oo,p=fetchnode(v,k);
if (p && p->xref<0) {
free_node(p);
@<Remove entry |k| from the hash table@>;
}
}
deadnodes-=oldtotal-totalnodes, free+=oldtotal-totalnodes;
@<Downsize the table if only a few entries are left@>;
o,v->free=free;
}
}
@ Deletion from a linearly probed hash table is tricky, as noted in
Algorithm 6.4R of TAOCP. Here I can speed that algorithm up slightly,
because there's no need to move dead entries that will be deleted later.
Furthermore, if I do meet a dead entry, I can take a slightly tricky
shortcut and continue the removals.
@<Remove entry |k|...@>=
do {
for (kk=k,j=k+sizeof(addr),k=0;;j+=sizeof(addr)) {
jj=j&mask;
oo,p=fetchnode(v,jj);
if (!p) break;
if (p->xref>=0) {
o,i=addr_(hashedcode(p))&mask;
if ((i<=kk)+(jj<i)+(kk<jj)>1) storenode(v,kk,p),kk=jj;
}@+else if (!k)
k=j,free_node(p); /* shortcut */
}
storenode(v,kk,NULL);
} while (k);
k=j; /* the last run through that loop saw no dead nodes */
@ At least one node, |v->proj|, branches on $x_v$ at this point.
@<Downsize the table if only a few entries are left@>=
k=(mask>>2)+1-free; /* this many nodes still branch on $x_v$ */
for (newmask=mask;(newmask>>5)>=k;newmask>>=1);
if (newmask!=mask) {
if (verbose&256)
printf("downsizing the hash table for level %d(x%d) (%d slots)\n",
v-varhead,v->name,(newmask+1)/sizeof(addr));
free-=(mask-newmask)>>2;
@<Rehash everything in the upper half@>;
for (k=mask>>logpagesize;k>newmask>>logpagesize;k--)
o,free_page(page_(v->base[k]));
v->mask=newmask;
}
@ Finally, another algorithm learned from Rudell. To prove its correctness,
one can verify the following fact:
Any entries that wrapped around from the upper half to
the bottom in the original table will still wrap around in the smaller table.
@^Rudell, Richard Lyle@>
@<Rehash everything in the upper half@>=
for (k=newmask+1;k<mask;k+=sizeof(addr)) {
oo,r=fetchnode(v,k);
if (r) {
for (o,hash=hashedcode(r);;hash++) {
j=addr_(hash)&newmask;
oo,p=fetchnode(v,j);
if (!p) break;
}
storenode(v,j,r);
}
}
@*The cache. The other principal data structure we need, besides the BDD base
itself, is a software cache that helps us avoid repeating the calculations
that we've already done. If, for example, $f$ and $g$ are nodes of the BDD for
which we've already computed $h=f\land g$, the cache should contain the
information that $f\land g$ is known to be node~$h$.
But that description is only approximately correct, because
the cost of forgetting the value of $f\land g$ is less than the cost of
building a fancy data structure that is able to remember every result.
(If we forget only a few things, we need to do only a few recomputations.)
Therefore we adopt a simple scheme that is designed to be reliable most of
the time, yet not perfect: We look for $f\land g$ in only one position
within the cache, based on a hash code. If two or more results happen
to hash to the same cache slot, we remember only the most recent one.
Every entry of the cache consists of four tetrabytes, called
$f$, $g$, $h$, and~$r$. The last of these, $r$, is nonzero if and only if the
cache entry is meaningful; in that case $r$ points to a BDD node, the result
of an operation encoded by $f$, $g$, and~$h$.
This $(f,g,h)$ encoding has several variants:
\smallskip\textindent{$\bullet$} If $h$ is 0, then $g$ is
a ``time stamp,'' and $f$ points to a BDD node. This case is used for
functional composition, when we want to
invalidate a block of cache entries quickly by simply changing an
external time stamp; items with a stale time stamp won't match any further
cache lookups.
\smallskip\textindent{$\bullet$} If $0<h\le|maxbinop|$, then $h$
denotes a binary operation on the BDD nodes $f$ and~$g$.
For example, $h=1$ stands for $\land$. The binary operations currently
implemented are:
and~(1),
but-not~(2),
not-but~(4),
xor~(6),
or~(7),
constrain~(8),
all-quantifier~(9),
no-quantifier~(10),
yes-quantifier~(12),
diff-quantifier~(14),
exists-quantifier~(15).
@^Binary operations@>
\smallskip\textindent{$\bullet$} Otherwise $(f,g,h)$ encodes a ternary
operation on the three BDD nodes $f$, $g$, |h&-16|. The four least-significant
bits of~$h$ are used to identify the ternary operation involved:
if-then-else~(0),
median~(1),
and-and~(2),
and-exist~(3),
not-yet-implemented~(4--15).
@^Ternary operations@>
@s memo int
@d memo_(a) ((memo*)(size_t)(a))
@<Type def...@>=
typedef struct memo_struct {
addr f; /* first operand */
addr g; /* second operand, or time stamp */
addr h; /* third operand and/or operation code */
addr r; /* result */
} memo;
@ The cache always occupies $2^e$ pages of the dynamic memory,
for some integer $e\ge0$. If we have leisure to choose this size, we pick
the smallest $e\ge0$ such that the cache has at least $\max(4m,n/4)$ slots,
where $m$ is the number of nonempty items in the cache and $n$ is
the number of live nodes in the BDD. Furthermore, the cache size
will double whenever the number of cache insertions reaches a
given threshold.
@^Tweakable parameters@>
@d logmaxcachepages 15 /* shouldn't be large if |logvarsize| is large */
@d maxcachepages (1<<logmaxcachepages)
@d cacheslotsperpage (pagesize/sizeof(memo))
@d maxbinop 15
@<Glob...@>=
addr cachepage[maxcachepages]; /* base addresses for the cache */
int cachepages; /* the current number of pages in the cache */
int cacheinserts; /* the number of times we've inserted a memo */
int threshold; /* the number of inserts that trigger cache doubling */
int cachemask; /* index of the first slot following the cache, minus 1 */
@ The following subroutines, useful for debugging, print out the
cache contents in symbolic form.
If |p| points to a node, |id(p)| is |p-botsink|.
@d id(a) (((size_t)(a)-(size_t)mem)/sizeof(node)) /* node number in |mem| */
@<Sub...@>=
void print_memo(memo *m) {
printf("%x",id(m->f));
if (m->h==0) printf("[%d]",m->g); /* time stamp */
else if (m->h<=maxbinop) printf("%s%x",binopname[m->h],id(m->g));
else printf("%s%x%s%x",
ternopname1[m->h&0xf],id(m->g),ternopname2[m->h&0xf],id(m->h));
printf("=%x\n",id(m->r));
}
@#
void print_cache(void) {
register int k;
register memo* m;
for (k=0;k<cachepages;k++)
for (m=memo_(cachepage[k]);m<memo_(cachepage[k])+cacheslotsperpage;m++)
if (m->r) print_memo(m);
}
@ Many of the symbolic names here are presently unused. I've filled them
in just to facilitate extensions to this program.
@<Glob...@>=
char *binopname[]=
{"","&",">","!","<","@@","^","|","_","A","N","#","Y","$","D","E"};
char *ternopname1[]=
{"?",".","&","&","@@","#","$","%","*","<","-","+","|","/","\\","~"};
char *ternopname2[]=
{":",".","&","E","@@","#","$","%","*","<","-","+","|","/","\\","~"};
@ The threshold is set to half the total number of cache slots,
because this many random insertions will keep about $e^{-1/2}\approx
61$\% of the cache slots unclobbered. (If $p$ denotes this probability,
a random large binary tree will need about $E$ steps to recalculate a
lost result, where $E=p\cdot1+(1-p)\cdot(1+2E)$; hence we want
$p>1/2$ to avoid blowup, and $E=1/(2p-1)$.)
@<Sub...@>=
int choose_cache_size(int items) {
register int k,slots;
k=1,slots=cacheslotsperpage;
while (4*slots<totalnodes-deadnodes && k<maxcachepages) k<<=1,slots<<=1;
while (slots<4*items && k<maxcachepages) k<<=1,slots<<=1;
return k;
}
@#
void cache_init(void) {
register int k;
register memo *m;
cachepages=choose_cache_size(0);
if (verbose&(8+16+32+512))
printf("initializing the cache (%d page%s)\n",
cachepages,cachepages==1?"":"s");
for (k=0;k<cachepages;k++) {
o,cachepage[k]=addr_(reserve_page());
if (!cachepage[k]) {
fprintf(stderr,"(trouble allocating cache pages!)\n");
for (k--;(k+1)&k;k--) o,free_page(page_(cachepage[k]));
cachepages=k+1;
break;
}
for (m=memo_(cachepage[k]);m<memo_(cachepage[k])+cacheslotsperpage;m++)
m->r=0;
zmems+=cacheslotsperpage;
}
cachemask=(cachepages<<logpagesize)-1;
cacheinserts=0;
threshold=1+(cachepages*cacheslotsperpage)/2;
}
@ @<Initialize ev...@>=
cache_init();
@ Here's how we look for a memo in the cache. Memos might point to dead
nodes, as long as those nodes still exist.
A simple hash function is adequate for caching, because no clustering
can occur.
No mems are charged for computing |cachehash|, because we assume that
the calling routine has taken responsibility for accessing |f->index|
and |g->index|.
@d cachehash(f,g,h)
((f)->index<<4)^(((h)?(g)->index:addr_(g))<<5)^(addr_(h)<<6)
@d thememo(s) memo_(cachepage[((s)&cachemask)>>logpagesize]+((s)&pagemask))
@<Sub...@>=
node* cache_lookup(node *f,node *g,node *h) {
register node *r;
register memo *m;
register addr slot=cachehash(f,g,h);
o,m=thememo(slot);
o,r=node_(m->r);
if (!r) return NULL;
if (o,node_(m->f)==f && node_(m->g)==g && node_(m->h)==h) {
if (verbose&8) {
printf("hit %x: ",(slot&cachemask)/sizeof(memo));
print_memo(m);
}
if (o,r->xref<0) {
recursively_revive(r);
return r;
}
return o,r->xref++,r;
}
return NULL;
}
@ Insertion into the cache is even easier, except that we might
want to double the cache size while we're at it.
@<Sub...@>=
void cache_insert(node *f,node *g,node *h,node *r) {
register memo *m,*mm;
register int k;
register int slot=cachehash(f,g,h);
if (h) oo;@+else o; /* mems for computing |cachehash| */
if (++cacheinserts>=threshold) @<Double the cache size@>;
o,m=thememo(slot);
if ((verbose&16) && m->r) {
printf("lose %x: ",(slot&cachemask)/sizeof(memo));
print_memo(m);
}
oo,m->f=addr_(f),m->g=addr_(g),m->h=addr_(h),m->r=addr_(r);
if (verbose&32) {
printf("set %x: ",(slot&cachemask)/sizeof(memo));
print_memo(m);
}
}
@ @<Double the cache size@>=
if (cachepages<maxcachepages) {
if (verbose&(8+16+32+512))
printf("doubling the cache (%d pages)\n",cachepages<<1);
for (k=cachepages;k<cachepages+cachepages;k++) {
o,cachepage[k]=addr_(reserve_page());
if (!cachepage[k]) { /* sorry, we can't double the cache after all */
fprintf(stderr,"(trouble doubling cache pages!)\n");
for (k--;k>=cachepages;k--) o,free_page(page_(cachepage[k]));
goto done;
}
for (m=memo_(cachepage[k]);m<memo_(cachepage[k])+cacheslotsperpage;m++)
m->r=0;
zmems+=cacheslotsperpage;
}
cachepages<<=1;