aboutsummaryrefslogtreecommitdiffstats
path: root/kernel/rtlil.cc
blob: 1d380135b60af0307e0ecf08287595afeac05582 (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
pre { line-height: 125%; margin: 0; }
td.linenos pre { color: #000000; background-color: #f0f0f0; padding: 0 5px 0 5px; }
span.linenos { color: #000000; background-color: #f0f0f0; padding: 0 5px 0 5px; }
td.linenos pre.special { color: #000000; background-color: #ffffc0; padding: 0 5px 0 5px; }
span.linenos.special { color: #000000; background-color: #ffffc0; padding: 0 5px 0 5px; }
.highlight .hll { background-color: #ffffcc }
.highlight { background: #ffffff; }
.highlight .c { color: #888888 } /* Comment */
.highlight .err { color: #a61717; background-color: #e3d2d2 } /* Error */
.highlight .k { color: #008800; font-weight: bold } /* Keyword */
.highlight .ch { color: #888888 } /* Comment.Hashbang */
.highlight .cm { color: #888888 } /* Comment.Multiline */
.highlight .cp { color: #cc0000; font-weight: bold } /* Comment.Preproc */
.highlight .cpf { color: #888888 } /* Comment.PreprocFile */
.highlight .c1 { color: #888888 } /* Comment.Single */
.highlight .cs { color: #cc0000; font-weight: bold; background-color: #fff0f0 } /* Comment.Special */
.highlight .gd { color: #000000; background-color: #ffdddd } /* Generic.Deleted */
.highlight .ge { font-style: italic } /* Generic.Emph */
.highlight .gr { color: #aa0000 } /* Generic.Error */
.highlight .gh { color: #333333 } /* Generic.Heading */
.highlight .gi { color: #000000; background-color: #ddffdd } /* Generic.Inserted */
.highlight .go { color: #888888 } /* Generic.Output */
.highlight .gp { color: #555555 } /* Generic.Prompt */
.highlight .gs { font-weight: bold } /* Generic.Strong */
.highlight .gu { color: #666666 } /* Generic.Subheading */
.highlight .gt { color: #aa0000 } /* Generic.Traceback */
.highlight .kc { color: #008800; font-weight: bold } /* Keyword.Constant */
.highlight .kd { color: #008800; font-weight: bold } /* Keyword.Declaration */
.highlight .kn { color: #008800; font-weight: bold } /* Keyword.Namespace */
.highlight .kp { color: #008800 } /* Keyword.Pseudo */
.highlight .kr { color: #008800; font-weight: bold } /* Keyword.Reserved */
.highlight .kt { color: #888888; font-weight: bold } /* Keyword.Type */
.highlight .m { color: #0000DD; font-weight: bold } /* Literal.Number */
.highlight .s { color: #dd2200; background-color: #fff0f0 } /* Literal.String */
.highlight .na { color: #336699 } /* Name.Attribute */
.highlight .nb { color: #003388 } /* Name.Builtin */
.highlight .nc { color: #bb0066; font-weight: bold } /* Name.Class */
.highlight .no { color: #003366; font-weight: bold } /* Name.Constant */
.highlight .nd { color: #555555 } /* Name.Decorator */
.highlight .ne { color: #bb0066; font-weight: bold } /* Name.Exception */
.highlight .nf { color: #0066bb; font-weight: bold } /* Name.Function */
.highlight .nl { color: #336699; font-style: italic } /* Name.Label */
.highlight .nn { color: #bb0066; font-weight: bold } /* Name.Namespace */
.highlight .py { color: #336699; font-weight: bold } /* Name.Property */
.highlight .nt { color: #bb0066; font-weight: bold } /* Name.Tag */
.highlight .nv { color: #336699 } /* Name.Variable */
.highlight .ow { color: #008800 } /* Operator.Word */
.highlight .w { color: #bbbbbb } /* Text.Whitespace */
.highlight .mb { color: #0000DD; font-weight: bold } /* Literal.Number.Bin */
.highlight .mf { color: #0000DD; font-weight: bold } /* Literal.Number.Float */
.highlight .mh { color: #0000DD; font-weight: bold } /* Literal.Number.Hex */
.highlight .mi { color: #0000DD; font-weight: bold } /* Literal.Number.Integer */
.highlight .mo { color: #0000DD; font-weight: bold } /* Literal.Number.Oct */
.highlight .sa { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Affix */
.highlight .sb { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Backtick */
.highlight .sc { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Char */
.highlight .dl { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Delimiter */
.highlight .sd { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Doc */
.highlight .s2 { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Double */
.highlight .se { color: #0044dd; background-color: #fff0f0 } /* Literal.String.Escape */
.highlight .sh { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Heredoc */
.highlight .si { color: #3333bb; background-color: #fff0f0 } /* Literal.String.Interpol */
.highlight .sx { color: #22bb22; background-color: #f0fff0 } /* Literal.String.Other */
.highlight .sr { color: #008800; background-color: #fff0ff } /* Literal.String.Regex */
.highlight .s1 { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Single */
.highlight .ss { color: #aa6600; background-color: #fff0f0 } /* Literal.String.Symbol */
.highlight .bp { color: #003388 } /* Name.Builtin.Pseudo */
.highlight .fm { color: #0066bb; font-weight: bold } /* Name.Function.Magic */
.highlight .vc { color: #336699 } /* Name.Variable.Class */
.highlight .vg { color: #dd7700 } /* Name.Variable.Global */
.highlight .vi { color: #3333bb } /* Name.Variable.Instance */
.highlight .vm { color: #336699 } /* Name.Variable.Magic */
.highlight .il { color: #0000DD; font-weight: bold } /* Literal.Number.Integer.Long */
/******************************************************************************
 * memory.c
 * 
 * Copyright (c) 2002 K A Fraser
 * 
 * A description of the page table API:
 * 
 * Domains trap to process_page_updates with a list of update requests.
 * This is a list of (ptr, val) pairs, where the requested operation
 * is *ptr = val.
 * 
 * Reference counting of pages:
 * ----------------------------
 * Each page has two refcounts: tot_count and type_count.
 * 
 * TOT_COUNT is the obvious reference count. It counts all uses of a
 * physical page frame by a domain, including uses as a page directory,
 * a page table, or simple mappings via a PTE. This count prevents a
 * domain from releasing a frame back to the hypervisor's free pool when
 * it is still referencing it!
 * 
 * TYPE_COUNT is more subtle. A frame can be put to one of three
 * mutually-exclusive uses: it might be used as a page directory, or a
 * page table, or it may be mapped writeable by the domain [of course, a
 * frame may not be used in any of these three ways!].
 * So, type_count is a count of the number of times a frame is being 
 * referred to in its current incarnation. Therefore, a page can only
 * change its type when its type count is zero.
 * 
 * Pinning the page type:
 * ----------------------
 * The type of a page can be pinned/unpinned with the commands
 * PGEXT_[UN]PIN_L?_TABLE. Each page can be pinned exactly once (that is,
 * pinning is not reference counted, so it can't be nested).
 * This is useful to prevent a page's type count falling to zero, at which
 * point safety checks would need to be carried out next time the count
 * is increased again.
 * 
 * A further note on writeable page mappings:
 * ------------------------------------------
 * For simplicity, the count of writeable mappings for a page may not
 * correspond to reality. The 'writeable count' is incremented for every
 * PTE which maps the page with the _PAGE_RW flag set. However, for
 * write access to be possible the page directory entry must also have
 * its _PAGE_RW bit set. We do not check this as it complicates the 
 * reference counting considerably [consider the case of multiple
 * directory entries referencing a single page table, some with the RW
 * bit set, others not -- it starts getting a bit messy].
 * In normal use, this simplification shouldn't be a problem.
 * However, the logic can be added if required.
 * 
 * One more note on read-only page mappings:
 * -----------------------------------------
 * We want domains to be able to map pages for read-only access. The
 * main reason is that page tables and directories should be readable
 * by a domain, but it would not be safe for them to be writeable.
 * However, domains have free access to rings 1 & 2 of the Intel
 * privilege model. In terms of page protection, these are considered
 * to be part of 'supervisor mode'. The WP bit in CR0 controls whether
 * read-only restrictions are respected in supervisor mode -- if the 
 * bit is clear then any mapped page is writeable.
 * 
 * We get round this by always setting the WP bit and disallowing 
 * updates to it. This is very unlikely to cause a problem for guest
 * OS's, which will generally use the WP bit to simplify copy-on-write
 * implementation (in that case, OS wants a fault when it writes to
 * an application-supplied buffer).
 */


/*
 * THE FOLLOWING ARE ISSUES IF GUEST OPERATING SYSTEMS BECOME SMP-CAPABLE.
 * [THAT IS, THEY'RE NOT A PROBLEM NOW, AND MAY NOT EVER BE.]
 * -----------------------------------------------------------------------
 * 
 * *********
 * UPDATE 15/7/02: Interface has changed --updates now specify physical
 * address of page-table entry, rather than specifying a virtual address,
 * so hypervisor no longer "walks" the page tables. Therefore the 
 * solution below cannot work. Another possibility is to add a new entry
 * to our "struct page" which says to which top-level page table each
 * lower-level page table or writeable mapping belongs. If it belongs to more
 * than one, we'd probably just flush on all processors running the domain.
 * *********
 * 
 * ** 1 **
 * The problem involves creating new page tables which might be mapped 
 * writeable in the TLB of another processor. As an example, a domain might be 
 * running in two contexts (ie. on two processors) simultaneously, using the 
 * same top-level page table in both contexts. Now, if context 1 sends an 
 * update request [make page P read-only, add a reference to page P as a page 
 * table], that will succeed if there was only one writeable mapping of P. 
 * However, that mapping may persist in the TLB of context 2.
 * 
 * Solution: when installing a new page table, we must flush foreign TLBs as
 * necessary. Naive solution is to flush on any processor running our domain.
 * Cleverer solution is to flush on any processor running same top-level page
 * table, but this will sometimes fail (consider two different top-level page
 * tables which have a shared lower-level page table).
 * 
 * A better solution: when squashing a write reference, check how many times
 * that lowest-level table entry is referenced by ORing refcounts of tables
 * down the page-table hierarchy. If results is != 1, we require flushing all
 * instances of current domain if a new table is installed (because the
 * lowest-level entry may be referenced by many top-level page tables).
 * However, common case will be that result == 1, so we only need to flush
 * processors with the same top-level page table. Make choice at
 * table-installation time based on a `flush_level' flag, which is
 * FLUSH_NONE, FLUSH_PAGETABLE, FLUSH_DOMAIN. A flush reduces this
 * to FLUSH_NONE, while squashed write mappings can only promote up
 * to more aggressive flush types.
 * 
 * ** 2 **
 * Same problem occurs when removing a page table, at level 1 say, then
 * making it writeable. Need a TLB flush between otherwise another processor
 * might write an illegal mapping into the old table, while yet another
 * processor can use the illegal mapping because of a stale level-2 TLB
 * entry. So, removal of a table reference sets 'flush_level' appropriately,
 * and a flush occurs on next addition of a fresh write mapping.
 * 
 * BETTER SOLUTION FOR BOTH 1 AND 2:
 * When type_refcnt goes to zero, leave old type in place (don't set to
 * PGT_none). Then, only flush if making a page table of a page with
 * (cnt=0,type=PGT_writeable), or when adding a write mapping for a page
 * with (cnt=0, type=PGT_pagexxx). A TLB flush will cause all pages
 * with refcnt==0 to be reset to PGT_none. Need an array for the purpose,
 * added to when a type_refcnt goes to zero, and emptied on a TLB flush.
 * Either have per-domain table, or force TLB flush at end of each
 * call to 'process_page_updates'.
 * Most OSes will always keep a writeable reference hanging around, and
 * page table structure is fairly static, so this mechanism should be
 * fairly cheap.
 * 
 * MAYBE EVEN BETTER? [somewhat dubious: not for first cut of the code]:
 * If we need to force an intermediate flush, those other processors
 * spin until we complete, then do a single TLB flush. They can spin on
 * the lock protecting 'process_page_updates', and continue when that
 * is freed. Saves cost of setting up and servicing an IPI: later
 * communication is synchronous. Processors trying to install the domain
 * or domain&pagetable would also enter the spin.
 * 
 * ** 3 **
 * Indeed, this problem generalises to reusing page tables at different
 * levels of the hierarchy (conceptually, the guest OS can use the
 * hypervisor to introduce illegal table entries by proxy). Consider
 * unlinking a level-1 page table and reintroducing at level 2 with no
 * TLB flush. Hypervisor can add a reference to some other level-1 table
 * with the RW bit set. This is fine in the level-2 context, but some
 * other processor may still be using that table in level-1 context
 * (due to a stale TLB entry). At level 1 it may look like the
 * processor has write access to the other level-1 page table! Therefore
 * can add illegal values there with impunity :-(
 * 
 * Fortunately, the solution above generalises to this extended problem.
 */

/*
 * UPDATE 12.11.02.: We no longer have struct page and mem_map. These
 * have been replaced by struct pfn_info and frame_table respectively.
 * 
 * system_free_list is a list_head linking all system owned free pages.
 * it is initialized in init_frametable.
 *
 * Boris Dragovic.
 */
 
#include <xeno/config.h>
#include <xeno/init.h>
#include <xeno/lib.h>
#include <xeno/mm.h>
#include <xeno/sched.h>
#include <xeno/errno.h>
#include <asm/page.h>
#include <asm/io.h>
#include <asm/uaccess.h>
#include <asm/domain_page.h>

#if 0
#define MEM_LOG(_f, _a...) printk("DOM%d: (file=memory.c, line=%d) " _f "\n", current->domain, __LINE__, ## _a )
#else
#define MEM_LOG(_f, _a...) ((void)0)
#endif

/* Domain 0 is allowed to submit requests on behalf of others. */
#define DOMAIN_OKAY(_f) \
    ((((_f) & PG_domain_mask) == current->domain) || (current->domain == 0))

/* 'get' checks parameter for validity before inc'ing refcnt. */
static int get_l2_table(unsigned long page_nr);
static int get_l1_table(unsigned long page_nr);
static int get_page(unsigned long page_nr, int writeable);
static int inc_page_refcnt(unsigned long page_nr, unsigned int type);
/* 'put' does no checking because if refcnt not zero, entity must be valid. */
static void put_l2_table(unsigned long page_nr);
static void put_l1_table(unsigned long page_nr);
static void put_page(unsigned long page_nr, int writeable);
static int dec_page_refcnt(unsigned long page_nr, unsigned int type);

static int mod_l2_entry(unsigned long, l2_pgentry_t);
static int mod_l1_entry(unsigned long, l1_pgentry_t);

/* frame table size and its size in pages */
frame_table_t * frame_table;
unsigned long frame_table_size;
unsigned long max_page;

struct list_head free_list;
unsigned int free_pfns;

static int tlb_flush[NR_CPUS];

/*
 * init_frametable:
 * Initialise per-frame memory information. This goes directly after
 * MAX_MONITOR_ADDRESS in physical memory.
 */
void __init init_frametable(unsigned long nr_pages)
{
    struct pfn_info *pf;
    unsigned long page_index;

    memset(tlb_flush, 0, sizeof(tlb_flush));

    max_page = nr_pages;
    frame_table_size = nr_pages * sizeof(struct pfn_info);
    frame_table_size = (frame_table_size + PAGE_SIZE - 1) & PAGE_MASK;
    frame_table = (frame_table_t *)FRAMETABLE_VIRT_START;
    memset(frame_table, 0, frame_table_size);

    free_pfns = nr_pages - 
        ((__pa(frame_table) + frame_table_size) >> PAGE_SHIFT);

    /* Put all domain-allocatable memory on a free list. */
    INIT_LIST_HEAD(&free_list);
    for( page_index = (__pa(frame_table) + frame_table_size) >> PAGE_SHIFT; 
         page_index < nr_pages; 
         page_index++ )      
    {
        pf = list_entry(&frame_table[page_index].list, struct pfn_info, list);
        list_add_tail(&pf->list, &free_list);
    }
}


/* Return original refcnt, or -1 on error. */
static int inc_page_refcnt(unsigned long page_nr, unsigned int type)
{
    struct pfn_info *page;
    unsigned long flags;

    if ( page_nr >= max_page )
    {
        MEM_LOG("Page out of range (%08lx>%08lx)", page_nr, max_page);
        return -1;
    }
    page = frame_table + page_nr;
    flags = page->flags;
    if ( !DOMAIN_OKAY(flags) )
    {
        MEM_LOG("Bad page domain (%ld)", flags & PG_domain_mask);
        return -1;
    }
    if ( (flags & PG_type_mask) != type )
    {
        if ( page_type_count(page) != 0 )
        {
            MEM_LOG("Page %08lx bad type/count (%08lx!=%08x) cnt=%ld",
                    page_nr << PAGE_SHIFT,
                    flags & PG_type_mask, type, page_type_count(page));
            return -1;
        }

        page->flags |= type;
    }

    get_page_tot(page);
    return get_page_type(page);
}

/* Return new refcnt, or -1 on error. */
static int dec_page_refcnt(unsigned long page_nr, unsigned int type)
{
    struct pfn_info *page;
    int ret;

    if ( page_nr >= max_page )
    {
        MEM_LOG("Page out of range (%08lx>%08lx)", page_nr, max_page);
        return -1;
    }
    page = frame_table + page_nr;
    if ( !DOMAIN_OKAY(page->flags) || 
         ((page->flags & PG_type_mask) != type) ) 
    {
        MEM_LOG("Bad page type/domain (dom=%ld) (type %ld != expected %d)",
                page->flags & PG_domain_mask, page->flags & PG_type_mask,
                type);
        return -1;
    }
    ASSERT(page_type_count(page) != 0);
    if ( (ret = put_page_type(page)) == 0 ) page->flags &= ~PG_type_mask;
    put_page_tot(page);
    return ret;
}


/* We allow a L2 table to map itself, to achieve a linear pagetable. */
/* NB. There's no need for a put_twisted_l2_table() function!! */
static int get_twisted_l2_table(unsigned long entry_pfn, l2_pgentry_t l2e)
{
    unsigned long l2v = l2_pgentry_val(l2e);

    /* Clearly the mapping must be read-only :-) */
    if ( (l2v & _PAGE_RW) )
    {
        MEM_LOG("Attempt to install twisted L2 entry with write permissions");
        return -1;
    }

    /* This is a sufficient final check. */
    if ( (l2v >> PAGE_SHIFT) != entry_pfn )
    {
        MEM_LOG("L2 tables may not map _other_ L2 tables!\n");
        return -1;
    }
    
    /* We don't bump the reference counts. */
    return 0;
}


static int get_l2_table(unsigned long page_nr)
{
    l2_pgentry_t *p_l2_entry, l2_entry;
    int i, ret=0;
   
    ret = inc_page_refcnt(page_nr, PGT_l2_page_table);
    if ( ret != 0 ) return (ret < 0) ? ret : 0;
    
    /* NEW level-2 page table! Deal with every PDE in the table. */
    p_l2_entry = map_domain_mem(page_nr << PAGE_SHIFT);
    for ( i = 0; i < DOMAIN_ENTRIES_PER_L2_PAGETABLE; i++ )
    {
        l2_entry = *p_l2_entry++;
        if ( !(l2_pgentry_val(l2_entry) & _PAGE_PRESENT) ) continue;
        if ( (l2_pgentry_val(l2_entry) & (_PAGE_GLOBAL|_PAGE_PSE)) )
        {
            MEM_LOG("Bad L2 page type settings %04lx",
                    l2_pgentry_val(l2_entry) & (_PAGE_GLOBAL|_PAGE_PSE));
            ret = -1;
            goto out;
        }
        /* Assume we're mapping an L1 table, falling back to twisted L2. */
        ret = get_l1_table(l2_pgentry_to_pagenr(l2_entry));
        if ( ret ) ret = get_twisted_l2_table(page_nr, l2_entry);
        if ( ret ) goto out;
    }
    
    /* Now we simply slap in our high mapping. */
    memcpy(p_l2_entry, 
           idle_pg_table[smp_processor_id()] + DOMAIN_ENTRIES_PER_L2_PAGETABLE,
           HYPERVISOR_ENTRIES_PER_L2_PAGETABLE * sizeof(l2_pgentry_t));
    p_l2_entry[(PERDOMAIN_VIRT_START >> L2_PAGETABLE_SHIFT) -
              DOMAIN_ENTRIES_PER_L2_PAGETABLE] =
        mk_l2_pgentry(__pa(current->mm.perdomain_pt) | __PAGE_HYPERVISOR);

 out:
    unmap_domain_mem(p_l2_entry);
    return ret;
}

static int get_l1_table(unsigned long page_nr)
{
    l1_pgentry_t *p_l1_entry, l1_entry;
    int i, ret;

    /* Update ref count for page pointed at by PDE. */
    ret = inc_page_refcnt(page_nr, PGT_l1_page_table);
    if ( ret != 0 ) return (ret < 0) ? ret : 0;

    /* NEW level-1 page table! Deal with every PTE in the table. */
    p_l1_entry = map_domain_mem(page_nr << PAGE_SHIFT);
    for ( i = 0; i < ENTRIES_PER_L1_PAGETABLE; i++ )
    {
        l1_entry = *p_l1_entry++;
        if ( !(l1_pgentry_val(l1_entry) & _PAGE_PRESENT) ) continue;
        if ( (l1_pgentry_val(l1_entry) &
              (_PAGE_GLOBAL|_PAGE_PAT)) )
        {
            MEM_LOG("Bad L1 page type settings %04lx",
                    l1_pgentry_val(l1_entry) &
                    (_PAGE_GLOBAL|_PAGE_PAT));
            ret = -1;
            goto out;
        }
        ret = get_page(l1_pgentry_to_pagenr(l1_entry),
                       l1_pgentry_val(l1_entry) & _PAGE_RW);
        if ( ret ) goto out;
    }

 out:
    /* Make sure we unmap the right page! */
    unmap_domain_mem(p_l1_entry-1);
    return ret;
}

static int get_page(unsigned long page_nr, int writeable)
{
    struct pfn_info *page;
    unsigned long flags;

    /* Update ref count for page pointed at by PTE. */
    if ( page_nr >= max_page )
    {
        MEM_LOG("Page out of range (%08lx>%08lx)", page_nr, max_page);
        return(-1);
    }
    page = frame_table + page_nr;
    flags = page->flags;
    if ( !DOMAIN_OKAY(flags) )
    {
        MEM_LOG("Bad page domain (%ld)", flags & PG_domain_mask);
        return(-1);
    }

    if ( writeable )
    {
        if ( (flags & PG_type_mask) != PGT_writeable_page )
        {
            if ( page_type_count(page) != 0 )
            {
                MEM_LOG("Bad page type/count (%08lx!=%08x) cnt=%ld",
                        flags & PG_type_mask, PGT_writeable_page,
                        page_type_count(page));
                return(-1);
            }
            page->flags |= PGT_writeable_page;
        }
        get_page_type(page);
    }

    get_page_tot(page);
    
    return(0);
}

static void put_l2_table(unsigned long page_nr)
{
    l2_pgentry_t *p_l2_entry, l2_entry;
    int i;

    if ( dec_page_refcnt(page_nr, PGT_l2_page_table) ) return;

    /* We had last reference to level-2 page table. Free the PDEs. */
    p_l2_entry = map_domain_mem(page_nr << PAGE_SHIFT);
    for ( i = 0; i < DOMAIN_ENTRIES_PER_L2_PAGETABLE; i++ )
    {
        l2_entry = *p_l2_entry++;
        if ( (l2_pgentry_val(l2_entry) & _PAGE_PRESENT) )
            put_l1_table(l2_pgentry_to_pagenr(l2_entry));
    }

    unmap_domain_mem(p_l2_entry);
}

static void put_l1_table(unsigned long page_nr)
{
    l1_pgentry_t *p_l1_entry, l1_entry;
    int i;

    if ( dec_page_refcnt(page_nr, PGT_l1_page_table) ) return;

    /* We had last reference to level-1 page table. Free the PTEs. */
    p_l1_entry = map_domain_mem(page_nr << PAGE_SHIFT);
    for ( i = 0; i < ENTRIES_PER_L1_PAGETABLE; i++ )
    {
        l1_entry = *p_l1_entry++;
        if ( (l1_pgentry_val(l1_entry) & _PAGE_PRESENT) ) 
        {
            put_page(l1_pgentry_to_pagenr(l1_entry), 
                     l1_pgentry_val(l1_entry) & _PAGE_RW);
        }
    }

    /* Make sure we unmap the right page! */
    unmap_domain_mem(p_l1_entry-1);
}

static void put_page(unsigned long page_nr, int writeable)
{
    struct pfn_info *page;
    ASSERT(page_nr < max_page);
    page = frame_table + page_nr;
    ASSERT(DOMAIN_OKAY(page->flags));
    ASSERT((!writeable) || 
           ((page_type_count(page) != 0) && 
            ((page->flags & PG_type_mask) == PGT_writeable_page)));
    if ( writeable && (put_page_type(page) == 0) )
    {
        tlb_flush[smp_processor_id()] = 1;
        page->flags &= ~PG_type_mask;
    }
    put_page_tot(page);
}


static int mod_l2_entry(unsigned long pa, l2_pgentry_t new_l2_entry)
{
    l2_pgentry_t *p_l2_entry, old_l2_entry;

    p_l2_entry = map_domain_mem(pa);
    old_l2_entry = *p_l2_entry;

    if ( (((unsigned long)p_l2_entry & (PAGE_SIZE-1)) >> 2) >=
         DOMAIN_ENTRIES_PER_L2_PAGETABLE )
    {
        MEM_LOG("Illegal L2 update attempt in hypervisor area %p",
                p_l2_entry);
        goto fail;
    }

    if ( (l2_pgentry_val(new_l2_entry) & _PAGE_PRESENT) )
    {
        if ( (l2_pgentry_val(new_l2_entry) & (_PAGE_GLOBAL|_PAGE_PSE)) )
        {
            MEM_LOG("Bad L2 entry val %04lx",
                    l2_pgentry_val(new_l2_entry) & 
                    (_PAGE_GLOBAL|_PAGE_PSE));
            goto fail;
        }
        /* Differ in mapping (bits 12-31) or presence (bit 0)? */
        if ( ((l2_pgentry_val(old_l2_entry) ^ 
               l2_pgentry_val(new_l2_entry)) & 0xfffff001) != 0 )
        {
            if ( (l2_pgentry_val(old_l2_entry) & _PAGE_PRESENT) ) 
            {
                put_l1_table(l2_pgentry_to_pagenr(old_l2_entry));
            }
            
            /* Assume we're mapping an L1 table, falling back to twisted L2. */
            if ( get_l1_table(l2_pgentry_to_pagenr(new_l2_entry)) &&
                 get_twisted_l2_table(pa >> PAGE_SHIFT, new_l2_entry) )
                goto fail;
        } 
    }
    else if ( (l2_pgentry_val(old_l2_entry) & _PAGE_PRESENT) )
    {
        put_l1_table(l2_pgentry_to_pagenr(old_l2_entry));
    }
    
    *p_l2_entry = new_l2_entry;
    unmap_domain_mem(p_l2_entry);
    return 0;

 fail:
    unmap_domain_mem(p_l2_entry);
    return -1;
}


static int mod_l1_entry(unsigned long pa, l1_pgentry_t new_l1_entry)
{
    l1_pgentry_t *p_l1_entry, old_l1_entry;

    p_l1_entry = map_domain_mem(pa);
    old_l1_entry = *p_l1_entry;

    if ( (l1_pgentry_val(new_l1_entry) & _PAGE_PRESENT) )
    {
        if ( (l1_pgentry_val(new_l1_entry) &
              (_PAGE_GLOBAL|_PAGE_PAT)) ) 
        {

            MEM_LOG("Bad L1 entry val %04lx",
                    l1_pgentry_val(new_l1_entry) & 
                    (_PAGE_GLOBAL|_PAGE_PAT));
            goto fail;
        }
        /*
         * Differ in mapping (bits 12-31), writeable (bit 1), or
         * presence (bit 0)?
         */
        if ( ((l1_pgentry_val(old_l1_entry) ^
               l1_pgentry_val(new_l1_entry)) & 0xfffff003) != 0 )
        {
            if ( (l1_pgentry_val(old_l1_entry) & _PAGE_PRESENT) ) 
            {
                put_page(l1_pgentry_to_pagenr(old_l1_entry),
                         l1_pgentry_val(old_l1_entry) & _PAGE_RW);
            }
            
            if ( get_page(l1_pgentry_to_pagenr(new_l1_entry),
                          l1_pgentry_val(new_l1_entry) & _PAGE_RW) ){
                goto fail;
            }
        } 
    }
    else if ( (l1_pgentry_val(old_l1_entry) & _PAGE_PRESENT) )
    {
        put_page(l1_pgentry_to_pagenr(old_l1_entry),
                 l1_pgentry_val(old_l1_entry) & _PAGE_RW);
    }

    *p_l1_entry = new_l1_entry;
    unmap_domain_mem(p_l1_entry);
    return 0;

 fail:
    unmap_domain_mem(p_l1_entry);
    return -1;
}


static int do_extended_command(unsigned long ptr, unsigned long val)
{
    int err = 0;
    unsigned long pfn = ptr >> PAGE_SHIFT;
    struct pfn_info *page = frame_table + pfn;

    switch ( (val & PGEXT_CMD_MASK) )
    {
    case PGEXT_PIN_L1_TABLE:
        err = get_l1_table(pfn);
        goto mark_as_pinned;
    case PGEXT_PIN_L2_TABLE:
        err = get_l2_table(pfn);
    mark_as_pinned:
        if ( err )
        {
            MEM_LOG("Error while pinning pfn %08lx", pfn);
            break;
        }
        put_page_type(page);
        put_page_tot(page);
        if ( !(page->type_count & REFCNT_PIN_BIT) )
        {
            page->type_count |= REFCNT_PIN_BIT;
            page->tot_count  |= REFCNT_PIN_BIT;
        }
        else
        {
            MEM_LOG("Pfn %08lx already pinned", pfn);
            err = 1;
        }
        break;

    case PGEXT_UNPIN_TABLE:
        if ( !DOMAIN_OKAY(page->flags) )
        {
            err = 1;
            MEM_LOG("Page %08lx bad domain (dom=%ld)",
                    ptr, page->flags & PG_domain_mask);
        }
        else if ( (page->type_count & REFCNT_PIN_BIT) )
        {
            page->type_count &= ~REFCNT_PIN_BIT;
            page->tot_count  &= ~REFCNT_PIN_BIT;
            get_page_type(page);
            get_page_tot(page);
            ((page->flags & PG_type_mask) == PGT_l1_page_table) ?
                put_l1_table(pfn) : put_l2_table(pfn);
        }
        else
        {
            err = 1;
            MEM_LOG("Pfn %08lx not pinned", pfn);
        }
        break;

    case PGEXT_NEW_BASEPTR:
        err = get_l2_table(pfn);
        if ( !err )
        {
            put_l2_table(pagetable_val(current->mm.pagetable) >> PAGE_SHIFT);
            current->mm.pagetable = mk_pagetable(pfn << PAGE_SHIFT);
        }
        else
        {
            MEM_LOG("Error while installing new baseptr %08lx %d", ptr, err);
        }
        /* fall through */
        
    case PGEXT_TLB_FLUSH:
        tlb_flush[smp_processor_id()] = 1;
        break;
    
    case PGEXT_INVLPG:
        __flush_tlb_one(val & ~PGEXT_CMD_MASK);
        break;

    default:
        MEM_LOG("Invalid extended pt command 0x%08lx", val & PGEXT_CMD_MASK);
        err = 1;
        break;
    }

    return err;
}

/*
 * functions to handle page table updates: upper half is invoked in case pt
 * updates are requested by a domain and it invokes copy_from_user. bottom half
 * is invoked both in case of domain downcall and domain building by
 * hypervisor.
 */
page_update_request_t * do_process_page_updates_uh(page_update_request_t *updates,
    int count)
{
    page_update_request_t * ret = kmalloc(sizeof(page_update_request_t) * count, 
        GFP_KERNEL);

    if ( copy_from_user(ret, updates, sizeof(page_update_request_t) * count) )
    {
        kill_domain_with_errmsg("Cannot read page update request");
    }
    
    return ret;
}

/* Apply updates to page table @pagetable_id within the current domain. */
int do_process_page_updates_bh(page_update_request_t * cur, int count)
{
    unsigned long flags, pfn;
    struct pfn_info *page;
    int err = 0, i;

    for ( i = 0; i < count; i++ )
    {
        pfn = cur->ptr >> PAGE_SHIFT;
        if ( pfn >= max_page )
        {
            MEM_LOG("Page out of range (%08lx > %08lx)", pfn, max_page);
            kill_domain_with_errmsg("Page update request out of range");
        }

        err = 1;

        /* Least significant bits of 'ptr' demux the operation type. */
        switch ( cur->ptr & (sizeof(l1_pgentry_t)-1) )
        {
            /*
             * PGREQ_NORMAL: Normal update to any level of page table.
             */
        case PGREQ_NORMAL:
            page = frame_table + pfn;
            flags = page->flags;
            
            if ( DOMAIN_OKAY(flags) )
            {
                switch ( (flags & PG_type_mask) )
                {
                case PGT_l1_page_table: 
                    err = mod_l1_entry(cur->ptr, mk_l1_pgentry(cur->val)); 
                    break;
                case PGT_l2_page_table: 
                    err = mod_l2_entry(cur->ptr, mk_l2_pgentry(cur->val)); 
                    break;
                default:
                    MEM_LOG("Update to non-pt page %08lx", cur->ptr);
                    break;
                }
            }
            break;

        case PGREQ_MPT_UPDATE:
            page = frame_table + pfn;
            if ( DOMAIN_OKAY(page->flags) )
            {
                machine_to_phys_mapping[pfn] = cur->val;
            }
            break;

            /*
             * PGREQ_EXTENDED_COMMAND: Extended command is specified
             * in the least-siginificant bits of the 'value' field.
             */
        case PGREQ_EXTENDED_COMMAND:
            cur->ptr &= ~(sizeof(l1_pgentry_t) - 1);
            err = do_extended_command(cur->ptr, cur->val);
            break;

        default:
            MEM_LOG("Invalid page update command %08lx", cur->ptr);
            break;
        }

        if ( err )
        {
            kill_domain_with_errmsg("Illegal page update request");
        }

        cur++;
    }

    if ( tlb_flush[smp_processor_id()] )
    {
        tlb_flush[smp_processor_id()] = 0;
        __asm__ __volatile__ (
            "movl %%eax,%%cr3" : : 
            "a" (pagetable_val(current->mm.pagetable)));
    }

    return(0);
}

/* Apply updates to page table @pagetable_id within the current domain. */
int do_process_page_updates(page_update_request_t *updates, int count)
{
    page_update_request_t * pg_updates;
    int ret;

    pg_updates = do_process_page_updates_uh(updates, count);
    ret = do_process_page_updates_bh(pg_updates, count);
    kfree(pg_updates);

    return ret;
}
1' href='#n3481'>3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094
/*
 *  yosys -- Yosys Open SYnthesis Suite
 *
 *  Copyright (C) 2012  Clifford Wolf <clifford@clifford.at>
 *
 *  Permission to use, copy, modify, and/or distribute this software for any
 *  purpose with or without fee is hereby granted, provided that the above
 *  copyright notice and this permission notice appear in all copies.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 *  WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 *  MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 *  ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 *  WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 *  ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 *  OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 *
 */

#include "kernel/yosys.h"
#include "kernel/macc.h"
#include "kernel/celltypes.h"
#include "frontends/verilog/verilog_frontend.h"
#include "backends/ilang/ilang_backend.h"

#include <string.h>
#include <algorithm>

YOSYS_NAMESPACE_BEGIN

RTLIL::IdString::destruct_guard_t RTLIL::IdString::destruct_guard;
std::vector<char*> RTLIL::IdString::global_id_storage_;
dict<char*, int, hash_cstr_ops> RTLIL::IdString::global_id_index_;
#ifndef YOSYS_NO_IDS_REFCNT
std::vector<int> RTLIL::IdString::global_refcount_storage_;
std::vector<int> RTLIL::IdString::global_free_idx_list_;
#endif
#ifdef YOSYS_USE_STICKY_IDS
int RTLIL::IdString::last_created_idx_[8];
int RTLIL::IdString::last_created_idx_ptr_;
#endif

IdString RTLIL::ID::A;
IdString RTLIL::ID::B;
IdString RTLIL::ID::Y;
IdString RTLIL::ID::keep;
IdString RTLIL::ID::whitebox;
IdString RTLIL::ID::blackbox;

RTLIL::Const::Const()
{
	flags = RTLIL::CONST_FLAG_NONE;
}

RTLIL::Const::Const(std::string str)
{
	flags = RTLIL::CONST_FLAG_STRING;
	for (int i = str.size()-1; i >= 0; i--) {
		unsigned char ch = str[i];
		for (int j = 0; j < 8; j++) {
			bits.push_back((ch & 1) != 0 ? State::S1 : State::S0);
			ch = ch >> 1;
		}
	}
}

RTLIL::Const::Const(int val, int width)
{
	flags = RTLIL::CONST_FLAG_NONE;
	for (int i = 0; i < width; i++) {
		bits.push_back((val & 1) != 0 ? State::S1 : State::S0);
		val = val >> 1;
	}
}

RTLIL::Const::Const(RTLIL::State bit, int width)
{
	flags = RTLIL::CONST_FLAG_NONE;
	for (int i = 0; i < width; i++)
		bits.push_back(bit);
}

RTLIL::Const::Const(const std::vector<bool> &bits)
{
	flags = RTLIL::CONST_FLAG_NONE;
	for (auto b : bits)
		this->bits.push_back(b ? State::S1 : State::S0);
}

RTLIL::Const::Const(const RTLIL::Const &c)
{
	flags = c.flags;
	for (auto b : c.bits)
		this->bits.push_back(b);
}

bool RTLIL::Const::operator <(const RTLIL::Const &other) const
{
	if (bits.size() != other.bits.size())
		return bits.size() < other.bits.size();
	for (size_t i = 0; i < bits.size(); i++)
		if (bits[i] != other.bits[i])
			return bits[i] < other.bits[i];
	return false;
}

bool RTLIL::Const::operator ==(const RTLIL::Const &other) const
{
	return bits == other.bits;
}

bool RTLIL::Const::operator !=(const RTLIL::Const &other) const
{
	return bits != other.bits;
}

bool RTLIL::Const::as_bool() const
{
	for (size_t i = 0; i < bits.size(); i++)
		if (bits[i] == State::S1)
			return true;
	return false;
}

int RTLIL::Const::as_int(bool is_signed) const
{
	int32_t ret = 0;
	for (size_t i = 0; i < bits.size() && i < 32; i++)
		if (bits[i] == State::S1)
			ret |= 1 << i;
	if (is_signed && bits.back() == State::S1)
		for (size_t i = bits.size(); i < 32; i++)
			ret |= 1 << i;
	return ret;
}

std::string RTLIL::Const::as_string() const
{
	std::string ret;
	for (size_t i = bits.size(); i > 0; i--)
		switch (bits[i-1]) {
			case S0: ret += "0"; break;
			case S1: ret += "1"; break;
			case Sx: ret += "x"; break;
			case Sz: ret += "z"; break;
			case Sa: ret += "-"; break;
			case Sm: ret += "m"; break;
		}
	return ret;
}

RTLIL::Const RTLIL::Const::from_string(std::string str)
{
	Const c;
	for (auto it = str.rbegin(); it != str.rend(); it++)
		switch (*it) {
			case '0': c.bits.push_back(State::S0); break;
			case '1': c.bits.push_back(State::S1); break;
			case 'x': c.bits.push_back(State::Sx); break;
			case 'z': c.bits.push_back(State::Sz); break;
			case 'm': c.bits.push_back(State::Sm); break;
			default: c.bits.push_back(State::Sa);
		}
	return c;
}

std::string RTLIL::Const::decode_string() const
{
	std::string string;
	std::vector<char> string_chars;
	for (int i = 0; i < int (bits.size()); i += 8) {
		char ch = 0;
		for (int j = 0; j < 8 && i + j < int (bits.size()); j++)
			if (bits[i + j] == RTLIL::State::S1)
				ch |= 1 << j;
		if (ch != 0)
			string_chars.push_back(ch);
	}
	for (int i = int (string_chars.size()) - 1; i >= 0; i--)
		string += string_chars[i];
	return string;
}

bool RTLIL::Const::is_fully_zero() const
{
	cover("kernel.rtlil.const.is_fully_zero");

	for (auto bit : bits)
		if (bit != RTLIL::State::S0)
			return false;

	return true;
}

bool RTLIL::Const::is_fully_ones() const
{
	cover("kernel.rtlil.const.is_fully_ones");

	for (auto bit : bits)
		if (bit != RTLIL::State::S1)
			return false;

	return true;
}

bool RTLIL::Const::is_fully_def() const
{
	cover("kernel.rtlil.const.is_fully_def");

	for (auto bit : bits)
		if (bit != RTLIL::State::S0 && bit != RTLIL::State::S1)
			return false;

	return true;
}

bool RTLIL::Const::is_fully_undef() const
{
	cover("kernel.rtlil.const.is_fully_undef");

	for (auto bit : bits)
		if (bit != RTLIL::State::Sx && bit != RTLIL::State::Sz)
			return false;

	return true;
}

void RTLIL::AttrObject::set_bool_attribute(RTLIL::IdString id, bool value)
{
	if (value)
		attributes[id] = RTLIL::Const(1);
	else {
                const auto it = attributes.find(id);
                if (it != attributes.end())
			attributes.erase(it);
	}
}

bool RTLIL::AttrObject::get_bool_attribute(RTLIL::IdString id) const
{
	const auto it = attributes.find(id);
	if (it == attributes.end())
		return false;
	return it->second.as_bool();
}

void RTLIL::AttrObject::set_strpool_attribute(RTLIL::IdString id, const pool<string> &data)
{
	string attrval;
	for (auto &s : data) {
		if (!attrval.empty())
			attrval += "|";
		attrval += s;
	}
	attributes[id] = RTLIL::Const(attrval);
}

void RTLIL::AttrObject::add_strpool_attribute(RTLIL::IdString id, const pool<string> &data)
{
	pool<string> union_data = get_strpool_attribute(id);
	union_data.insert(data.begin(), data.end());
	if (!union_data.empty())
		set_strpool_attribute(id, union_data);
}

pool<string> RTLIL::AttrObject::get_strpool_attribute(RTLIL::IdString id) const
{
	pool<string> data;
	if (attributes.count(id) != 0)
		for (auto s : split_tokens(attributes.at(id).decode_string(), "|"))
			data.insert(s);
	return data;
}

void RTLIL::AttrObject::set_src_attribute(const std::string &src)
{
	if (src.empty())
		attributes.erase(ID(src));
	else
		attributes[ID(src)] = src;
}

std::string RTLIL::AttrObject::get_src_attribute() const
{
	std::string src;
	if (attributes.count(ID(src)))
		src = attributes.at(ID(src)).decode_string();
	return src;
}

bool RTLIL::Selection::selected_module(RTLIL::IdString mod_name) const
{
	if (full_selection)
		return true;
	if (selected_modules.count(mod_name) > 0)
		return true;
	if (selected_members.count(mod_name) > 0)
		return true;
	return false;
}

bool RTLIL::Selection::selected_whole_module(RTLIL::IdString mod_name) const
{
	if (full_selection)
		return true;
	if (selected_modules.count(mod_name) > 0)
		return true;
	return false;
}

bool RTLIL::Selection::selected_member(RTLIL::IdString mod_name, RTLIL::IdString memb_name) const
{
	if (full_selection)
		return true;
	if (selected_modules.count(mod_name) > 0)
		return true;
	if (selected_members.count(mod_name) > 0)
		if (selected_members.at(mod_name).count(memb_name) > 0)
			return true;
	return false;
}

void RTLIL::Selection::optimize(RTLIL::Design *design)
{
	if (full_selection) {
		selected_modules.clear();
		selected_members.clear();
		return;
	}

	std::vector<RTLIL::IdString> del_list, add_list;

	del_list.clear();
	for (auto mod_name : selected_modules) {
		if (design->modules_.count(mod_name) == 0)
			del_list.push_back(mod_name);
		selected_members.erase(mod_name);
	}
	for (auto mod_name : del_list)
		selected_modules.erase(mod_name);

	del_list.clear();
	for (auto &it : selected_members)
		if (design->modules_.count(it.first) == 0)
			del_list.push_back(it.first);
	for (auto mod_name : del_list)
		selected_members.erase(mod_name);

	for (auto &it : selected_members) {
		del_list.clear();
		for (auto memb_name : it.second)
			if (design->modules_[it.first]->count_id(memb_name) == 0)
				del_list.push_back(memb_name);
		for (auto memb_name : del_list)
			it.second.erase(memb_name);
	}

	del_list.clear();
	add_list.clear();
	for (auto &it : selected_members)
		if (it.second.size() == 0)
			del_list.push_back(it.first);
		else if (it.second.size() == design->modules_[it.first]->wires_.size() + design->modules_[it.first]->memories.size() +
				design->modules_[it.first]->cells_.size() + design->modules_[it.first]->processes.size())
			add_list.push_back(it.first);
	for (auto mod_name : del_list)
		selected_members.erase(mod_name);
	for (auto mod_name : add_list) {
		selected_members.erase(mod_name);
		selected_modules.insert(mod_name);
	}

	if (selected_modules.size() == design->modules_.size()) {
		full_selection = true;
		selected_modules.clear();
		selected_members.clear();
	}
}

RTLIL::Design::Design()
{
	static unsigned int hashidx_count = 123456789;
	hashidx_count = mkhash_xorshift(hashidx_count);
	hashidx_ = hashidx_count;

	refcount_modules_ = 0;
	selection_stack.push_back(RTLIL::Selection());

#ifdef WITH_PYTHON
	RTLIL::Design::get_all_designs()->insert(std::pair<unsigned int, RTLIL::Design*>(hashidx_, this));
#endif
}

RTLIL::Design::~Design()
{
	for (auto it = modules_.begin(); it != modules_.end(); ++it)
		delete it->second;
	for (auto n : verilog_packages)
		delete n;
	for (auto n : verilog_globals)
		delete n;
#ifdef WITH_PYTHON
	RTLIL::Design::get_all_designs()->erase(hashidx_);
#endif
}

#ifdef WITH_PYTHON
static std::map<unsigned int, RTLIL::Design*> all_designs;
std::map<unsigned int, RTLIL::Design*> *RTLIL::Design::get_all_designs(void)
{
	return &all_designs;
}
#endif

RTLIL::ObjRange<RTLIL::Module*> RTLIL::Design::modules()
{
	return RTLIL::ObjRange<RTLIL::Module*>(&modules_, &refcount_modules_);
}

RTLIL::Module *RTLIL::Design::module(RTLIL::IdString name)
{
	return modules_.count(name) ? modules_.at(name) : NULL;
}

RTLIL::Module *RTLIL::Design::top_module()
{
	RTLIL::Module *module = nullptr;
	int module_count = 0;

	for (auto mod : selected_modules()) {
		if (mod->get_bool_attribute(ID(top)))
			return mod;
		module_count++;
		module = mod;
	}

	return module_count == 1 ? module : nullptr;
}

void RTLIL::Design::add(RTLIL::Module *module)
{
	log_assert(modules_.count(module->name) == 0);
	log_assert(refcount_modules_ == 0);
	modules_[module->name] = module;
	module->design = this;

	for (auto mon : monitors)
		mon->notify_module_add(module);

	if (yosys_xtrace) {
		log("#X# New Module: %s\n", log_id(module));
		log_backtrace("-X- ", yosys_xtrace-1);
	}
}

RTLIL::Module *RTLIL::Design::addModule(RTLIL::IdString name)
{
	log_assert(modules_.count(name) == 0);
	log_assert(refcount_modules_ == 0);

	RTLIL::Module *module = new RTLIL::Module;
	modules_[name] = module;
	module->design = this;
	module->name = name;

	for (auto mon : monitors)
		mon->notify_module_add(module);

	if (yosys_xtrace) {
		log("#X# New Module: %s\n", log_id(module));
		log_backtrace("-X- ", yosys_xtrace-1);
	}

	return module;
}

void RTLIL::Design::scratchpad_unset(std::string varname)
{
	scratchpad.erase(varname);
}

void RTLIL::Design::scratchpad_set_int(std::string varname, int value)
{
	scratchpad[varname] = stringf("%d", value);
}

void RTLIL::Design::scratchpad_set_bool(std::string varname, bool value)
{
	scratchpad[varname] = value ? "true" : "false";
}

void RTLIL::Design::scratchpad_set_string(std::string varname, std::string value)
{
	scratchpad[varname] = value;
}

int RTLIL::Design::scratchpad_get_int(std::string varname, int default_value) const
{
	if (scratchpad.count(varname) == 0)
		return default_value;

	std::string str = scratchpad.at(varname);

	if (str == "0" || str == "false")
		return 0;

	if (str == "1" || str == "true")
		return 1;

	char *endptr = nullptr;
	long int parsed_value = strtol(str.c_str(), &endptr, 10);
	return *endptr ? default_value : parsed_value;
}

bool RTLIL::Design::scratchpad_get_bool(std::string varname, bool default_value) const
{
	if (scratchpad.count(varname) == 0)
		return default_value;

	std::string str = scratchpad.at(varname);

	if (str == "0" || str == "false")
		return false;

	if (str == "1" || str == "true")
		return true;

	return default_value;
}

std::string RTLIL::Design::scratchpad_get_string(std::string varname, std::string default_value) const
{
	if (scratchpad.count(varname) == 0)
		return default_value;
	return scratchpad.at(varname);
}

void RTLIL::Design::remove(RTLIL::Module *module)
{
	for (auto mon : monitors)
		mon->notify_module_del(module);

	if (yosys_xtrace) {
		log("#X# Remove Module: %s\n", log_id(module));
		log_backtrace("-X- ", yosys_xtrace-1);
	}

	log_assert(modules_.at(module->name) == module);
	modules_.erase(module->name);
	delete module;
}

void RTLIL::Design::rename(RTLIL::Module *module, RTLIL::IdString new_name)
{
	modules_.erase(module->name);
	module->name = new_name;
	add(module);
}

void RTLIL::Design::sort()
{
	scratchpad.sort();
	modules_.sort(sort_by_id_str());
	for (auto &it : modules_)
		it.second->sort();
}

void RTLIL::Design::check()
{
#ifndef NDEBUG
	for (auto &it : modules_) {
		log_assert(this == it.second->design);
		log_assert(it.first == it.second->name);
		log_assert(!it.first.empty());
		it.second->check();
	}
#endif
}

void RTLIL::Design::optimize()
{
	for (auto &it : modules_)
		it.second->optimize();
	for (auto &it : selection_stack)
		it.optimize(this);
	for (auto &it : selection_vars)
		it.second.optimize(this);
}

bool RTLIL::Design::selected_module(RTLIL::IdString mod_name) const
{
	if (!selected_active_module.empty() && mod_name != selected_active_module)
		return false;
	if (selection_stack.size() == 0)
		return true;
	return selection_stack.back().selected_module(mod_name);
}

bool RTLIL::Design::selected_whole_module(RTLIL::IdString mod_name) const
{
	if (!selected_active_module.empty() && mod_name != selected_active_module)
		return false;
	if (selection_stack.size() == 0)
		return true;
	return selection_stack.back().selected_whole_module(mod_name);
}

bool RTLIL::Design::selected_member(RTLIL::IdString mod_name, RTLIL::IdString memb_name) const
{
	if (!selected_active_module.empty() && mod_name != selected_active_module)
		return false;
	if (selection_stack.size() == 0)
		return true;
	return selection_stack.back().selected_member(mod_name, memb_name);
}

bool RTLIL::Design::selected_module(RTLIL::Module *mod) const
{
	return selected_module(mod->name);
}

bool RTLIL::Design::selected_whole_module(RTLIL::Module *mod) const
{
	return selected_whole_module(mod->name);
}

std::vector<RTLIL::Module*> RTLIL::Design::selected_modules() const
{
	std::vector<RTLIL::Module*> result;
	result.reserve(modules_.size());
	for (auto &it : modules_)
		if (selected_module(it.first) && !it.second->get_blackbox_attribute())
			result.push_back(it.second);
	return result;
}

std::vector<RTLIL::Module*> RTLIL::Design::selected_whole_modules() const
{
	std::vector<RTLIL::Module*> result;
	result.reserve(modules_.size());
	for (auto &it : modules_)
		if (selected_whole_module(it.first) && !it.second->get_blackbox_attribute())
			result.push_back(it.second);
	return result;
}

std::vector<RTLIL::Module*> RTLIL::Design::selected_whole_modules_warn() const
{
	std::vector<RTLIL::Module*> result;
	result.reserve(modules_.size());
	for (auto &it : modules_)
		if (it.second->get_blackbox_attribute())
			continue;
		else if (selected_whole_module(it.first))
			result.push_back(it.second);
		else if (selected_module(it.first))
			log_warning("Ignoring partially selected module %s.\n", log_id(it.first));
	return result;
}

RTLIL::Module::Module()
{
	static unsigned int hashidx_count = 123456789;
	hashidx_count = mkhash_xorshift(hashidx_count);
	hashidx_ = hashidx_count;

	design = nullptr;
	refcount_wires_ = 0;
	refcount_cells_ = 0;

#ifdef WITH_PYTHON
	RTLIL::Module::get_all_modules()->insert(std::pair<unsigned int, RTLIL::Module*>(hashidx_, this));
#endif
}

RTLIL::Module::~Module()
{
	for (auto it = wires_.begin(); it != wires_.end(); ++it)
		delete it->second;
	for (auto it = memories.begin(); it != memories.end(); ++it)
		delete it->second;
	for (auto it = cells_.begin(); it != cells_.end(); ++it)
		delete it->second;
	for (auto it = processes.begin(); it != processes.end(); ++it)
		delete it->second;
#ifdef WITH_PYTHON
	RTLIL::Module::get_all_modules()->erase(hashidx_);
#endif
}

#ifdef WITH_PYTHON
static std::map<unsigned int, RTLIL::Module*> all_modules;
std::map<unsigned int, RTLIL::Module*> *RTLIL::Module::get_all_modules(void)
{
	return &all_modules;
}
#endif

void RTLIL::Module::makeblackbox()
{
	pool<RTLIL::Wire*> delwires;

	for (auto it = wires_.begin(); it != wires_.end(); ++it)
		if (!it->second->port_input && !it->second->port_output)
			delwires.insert(it->second);

	for (auto it = memories.begin(); it != memories.end(); ++it)
		delete it->second;
	memories.clear();

	for (auto it = cells_.begin(); it != cells_.end(); ++it)
		delete it->second;
	cells_.clear();

	for (auto it = processes.begin(); it != processes.end(); ++it)
		delete it->second;
	processes.clear();

	remove(delwires);
	set_bool_attribute(ID::blackbox);
}

void RTLIL::Module::reprocess_module(RTLIL::Design *, dict<RTLIL::IdString, RTLIL::Module *>)
{
	log_error("Cannot reprocess_module module `%s' !\n", id2cstr(name));
}

RTLIL::IdString RTLIL::Module::derive(RTLIL::Design*, dict<RTLIL::IdString, RTLIL::Const>, bool mayfail)
{
	if (mayfail)
		return RTLIL::IdString();
	log_error("Module `%s' is used with parameters but is not parametric!\n", id2cstr(name));
}


RTLIL::IdString RTLIL::Module::derive(RTLIL::Design*, dict<RTLIL::IdString, RTLIL::Const>, dict<RTLIL::IdString, RTLIL::Module*>, dict<RTLIL::IdString, RTLIL::IdString>, bool mayfail)
{
	if (mayfail)
		return RTLIL::IdString();
	log_error("Module `%s' is used with parameters but is not parametric!\n", id2cstr(name));
}

size_t RTLIL::Module::count_id(RTLIL::IdString id)
{
	return wires_.count(id) + memories.count(id) + cells_.count(id) + processes.count(id);
}

#ifndef NDEBUG
namespace {
	struct InternalCellChecker
	{
		RTLIL::Module *module;
		RTLIL::Cell *cell;
		pool<RTLIL::IdString> expected_params, expected_ports;

		InternalCellChecker(RTLIL::Module *module, RTLIL::Cell *cell) : module(module), cell(cell) { }

		void error(int linenr)
		{
			std::stringstream buf;
			ILANG_BACKEND::dump_cell(buf, "  ", cell);

			log_error("Found error in internal cell %s%s%s (%s) at %s:%d:\n%s",
					module ? module->name.c_str() : "", module ? "." : "",
					cell->name.c_str(), cell->type.c_str(), __FILE__, linenr, buf.str().c_str());
		}

		int param(RTLIL::IdString name)
		{
			if (cell->parameters.count(name) == 0)
				error(__LINE__);
			expected_params.insert(name);
			return cell->parameters.at(name).as_int();
		}

		int param_bool(RTLIL::IdString name)
		{
			int v = param(name);
			if (cell->parameters.at(name).bits.size() > 32)
				error(__LINE__);
			if (v != 0 && v != 1)
				error(__LINE__);
			return v;
		}

		void param_bits(RTLIL::IdString name, int width)
		{
			param(name);
			if (int(cell->parameters.at(name).bits.size()) != width)
				error(__LINE__);
		}

		void port(RTLIL::IdString name, int width)
		{
			if (!cell->hasPort(name))
				error(__LINE__);
			if (cell->getPort(name).size() != width)
				error(__LINE__);
			expected_ports.insert(name);
		}

		void check_expected(bool check_matched_sign = true)
		{
			for (auto &para : cell->parameters)
				if (expected_params.count(para.first) == 0)
					error(__LINE__);
			for (auto &conn : cell->connections())
				if (expected_ports.count(conn.first) == 0)
					error(__LINE__);

			if (expected_params.count(ID(A_SIGNED)) != 0 && expected_params.count(ID(B_SIGNED)) && check_matched_sign) {
				bool a_is_signed = param(ID(A_SIGNED)) != 0;
				bool b_is_signed = param(ID(B_SIGNED)) != 0;
				if (a_is_signed != b_is_signed)
					error(__LINE__);
			}
		}

		void check_gate(const char *ports)
		{
			if (cell->parameters.size() != 0)
				error(__LINE__);

			for (const char *p = ports; *p; p++) {
				char portname[3] = { '\\', *p, 0 };
				if (!cell->hasPort(portname))
					error(__LINE__);
				if (cell->getPort(portname).size() != 1)
					error(__LINE__);
			}

			for (auto &conn : cell->connections()) {
				if (conn.first.size() != 2 || conn.first[0] != '\\')
					error(__LINE__);
				if (strchr(ports, conn.first[1]) == NULL)
					error(__LINE__);
			}
		}

		void check()
		{
			if (!cell->type.begins_with("$") || cell->type.begins_with("$__") || cell->type.begins_with("$paramod") || cell->type.begins_with("$fmcombine") ||
					cell->type.begins_with("$verific$") || cell->type.begins_with("$array:") || cell->type.begins_with("$extern:"))
				return;

			if (cell->type.in(ID($not), ID($pos), ID($neg))) {
				param_bool(ID(A_SIGNED));
				port(ID::A, param(ID(A_WIDTH)));
				port(ID::Y, param(ID(Y_WIDTH)));
				check_expected();
				return;
			}

			if (cell->type.in(ID($and), ID($or), ID($xor), ID($xnor))) {
				param_bool(ID(A_SIGNED));
				param_bool(ID(B_SIGNED));
				port(ID::A, param(ID(A_WIDTH)));
				port(ID::B, param(ID(B_WIDTH)));
				port(ID::Y, param(ID(Y_WIDTH)));
				check_expected();
				return;
			}

			if (cell->type.in(ID($reduce_and), ID($reduce_or), ID($reduce_xor), ID($reduce_xnor), ID($reduce_bool))) {
				param_bool(ID(A_SIGNED));
				port(ID::A, param(ID(A_WIDTH)));
				port(ID::Y, param(ID(Y_WIDTH)));
				check_expected();
				return;
			}

			if (cell->type.in(ID($shl), ID($shr), ID($sshl), ID($sshr), ID($shift), ID($shiftx))) {
				param_bool(ID(A_SIGNED));
				param_bool(ID(B_SIGNED));
				port(ID::A, param(ID(A_WIDTH)));
				port(ID::B, param(ID(B_WIDTH)));
				port(ID::Y, param(ID(Y_WIDTH)));
				check_expected(false);
				return;
			}

			if (cell->type.in(ID($lt), ID($le), ID($eq), ID($ne), ID($eqx), ID($nex), ID($ge), ID($gt))) {
				param_bool(ID(A_SIGNED));
				param_bool(ID(B_SIGNED));
				port(ID::A, param(ID(A_WIDTH)));
				port(ID::B, param(ID(B_WIDTH)));
				port(ID::Y, param(ID(Y_WIDTH)));
				check_expected();
				return;
			}

			if (cell->type.in(ID($add), ID($sub), ID($mul), ID($div), ID($mod), ID($pow))) {
				param_bool(ID(A_SIGNED));
				param_bool(ID(B_SIGNED));
				port(ID::A, param(ID(A_WIDTH)));
				port(ID::B, param(ID(B_WIDTH)));
				port(ID::Y, param(ID(Y_WIDTH)));
				check_expected(cell->type != ID($pow));
				return;
			}

			if (cell->type == ID($fa)) {
				port(ID::A, param(ID(WIDTH)));
				port(ID::B, param(ID(WIDTH)));
				port(ID(C), param(ID(WIDTH)));
				port(ID(X), param(ID(WIDTH)));
				port(ID::Y, param(ID(WIDTH)));
				check_expected();
				return;
			}

			if (cell->type == ID($lcu)) {
				port(ID(P), param(ID(WIDTH)));
				port(ID(G), param(ID(WIDTH)));
				port(ID(CI), 1);
				port(ID(CO), param(ID(WIDTH)));
				check_expected();
				return;
			}

			if (cell->type == ID($alu)) {
				param_bool(ID(A_SIGNED));
				param_bool(ID(B_SIGNED));
				port(ID::A, param(ID(A_WIDTH)));
				port(ID::B, param(ID(B_WIDTH)));
				port(ID(CI), 1);
				port(ID(BI), 1);
				port(ID(X), param(ID(Y_WIDTH)));
				port(ID::Y, param(ID(Y_WIDTH)));
				port(ID(CO), param(ID(Y_WIDTH)));
				check_expected();
				return;
			}

			if (cell->type == ID($macc)) {
				param(ID(CONFIG));
				param(ID(CONFIG_WIDTH));
				port(ID::A, param(ID(A_WIDTH)));
				port(ID::B, param(ID(B_WIDTH)));
				port(ID::Y, param(ID(Y_WIDTH)));
				check_expected();
				Macc().from_cell(cell);
				return;
			}

			if (cell->type == ID($logic_not)) {
				param_bool(ID(A_SIGNED));
				port(ID::A, param(ID(A_WIDTH)));
				port(ID::Y, param(ID(Y_WIDTH)));
				check_expected();
				return;
			}

			if (cell->type.in(ID($logic_and), ID($logic_or))) {
				param_bool(ID(A_SIGNED));
				param_bool(ID(B_SIGNED));
				port(ID::A, param(ID(A_WIDTH)));
				port(ID::B, param(ID(B_WIDTH)));
				port(ID::Y, param(ID(Y_WIDTH)));
				check_expected(false);
				return;
			}

			if (cell->type == ID($slice)) {
				param(ID(OFFSET));
				port(ID::A, param(ID(A_WIDTH)));
				port(ID::Y, param(ID(Y_WIDTH)));
				if (param(ID(OFFSET)) + param(ID(Y_WIDTH)) > param(ID(A_WIDTH)))
					error(__LINE__);
				check_expected();
				return;
			}

			if (cell->type == ID($concat)) {
				port(ID::A, param(ID(A_WIDTH)));
				port(ID::B, param(ID(B_WIDTH)));
				port(ID::Y, param(ID(A_WIDTH)) + param(ID(B_WIDTH)));
				check_expected();
				return;
			}

			if (cell->type == ID($mux)) {
				port(ID::A, param(ID(WIDTH)));
				port(ID::B, param(ID(WIDTH)));
				port(ID(S), 1);
				port(ID::Y, param(ID(WIDTH)));
				check_expected();
				return;
			}

			if (cell->type == ID($pmux)) {
				port(ID::A, param(ID(WIDTH)));
				port(ID::B, param(ID(WIDTH)) * param(ID(S_WIDTH)));
				port(ID(S), param(ID(S_WIDTH)));
				port(ID::Y, param(ID(WIDTH)));
				check_expected();
				return;
			}

			if (cell->type == ID($lut)) {
				param(ID(LUT));
				port(ID::A, param(ID(WIDTH)));
				port(ID::Y, 1);
				check_expected();
				return;
			}

			if (cell->type == ID($sop)) {
				param(ID(DEPTH));
				param(ID(TABLE));
				port(ID::A, param(ID(WIDTH)));
				port(ID::Y, 1);
				check_expected();
				return;
			}

			if (cell->type == ID($sr)) {
				param_bool(ID(SET_POLARITY));
				param_bool(ID(CLR_POLARITY));
				port(ID(SET), param(ID(WIDTH)));
				port(ID(CLR), param(ID(WIDTH)));
				port(ID(Q),   param(ID(WIDTH)));
				check_expected();
				return;
			}

			if (cell->type == ID($ff)) {
				port(ID(D), param(ID(WIDTH)));
				port(ID(Q), param(ID(WIDTH)));
				check_expected();
				return;
			}

			if (cell->type == ID($dff)) {
				param_bool(ID(CLK_POLARITY));
				port(ID(CLK), 1);
				port(ID(D), param(ID(WIDTH)));
				port(ID(Q), param(ID(WIDTH)));
				check_expected();
				return;
			}

			if (cell->type == ID($dffe)) {
				param_bool(ID(CLK_POLARITY));
				param_bool(ID(EN_POLARITY));
				port(ID(CLK), 1);
				port(ID(EN), 1);
				port(ID(D), param(ID(WIDTH)));
				port(ID(Q), param(ID(WIDTH)));
				check_expected();
				return;
			}

			if (cell->type == ID($dffsr)) {
				param_bool(ID(CLK_POLARITY));
				param_bool(ID(SET_POLARITY));
				param_bool(ID(CLR_POLARITY));
				port(ID(CLK), 1);
				port(ID(SET), param(ID(WIDTH)));
				port(ID(CLR), param(ID(WIDTH)));
				port(ID(D), param(ID(WIDTH)));
				port(ID(Q), param(ID(WIDTH)));
				check_expected();
				return;
			}

			if (cell->type == ID($adff)) {
				param_bool(ID(CLK_POLARITY));
				param_bool(ID(ARST_POLARITY));
				param_bits(ID(ARST_VALUE), param(ID(WIDTH)));
				port(ID(CLK), 1);
				port(ID(ARST), 1);
				port(ID(D), param(ID(WIDTH)));
				port(ID(Q), param(ID(WIDTH)));
				check_expected();
				return;
			}

			if (cell->type == ID($dlatch)) {
				param_bool(ID(EN_POLARITY));
				port(ID(EN), 1);
				port(ID(D), param(ID(WIDTH)));
				port(ID(Q), param(ID(WIDTH)));
				check_expected();
				return;
			}

			if (cell->type == ID($dlatchsr)) {
				param_bool(ID(EN_POLARITY));
				param_bool(ID(SET_POLARITY));
				param_bool(ID(CLR_POLARITY));
				port(ID(EN), 1);
				port(ID(SET), param(ID(WIDTH)));
				port(ID(CLR), param(ID(WIDTH)));
				port(ID(D), param(ID(WIDTH)));
				port(ID(Q), param(ID(WIDTH)));
				check_expected();
				return;
			}

			if (cell->type == ID($fsm)) {
				param(ID(NAME));
				param_bool(ID(CLK_POLARITY));
				param_bool(ID(ARST_POLARITY));
				param(ID(STATE_BITS));
				param(ID(STATE_NUM));
				param(ID(STATE_NUM_LOG2));
				param(ID(STATE_RST));
				param_bits(ID(STATE_TABLE), param(ID(STATE_BITS)) * param(ID(STATE_NUM)));
				param(ID(TRANS_NUM));
				param_bits(ID(TRANS_TABLE), param(ID(TRANS_NUM)) * (2*param(ID(STATE_NUM_LOG2)) + param(ID(CTRL_IN_WIDTH)) + param(ID(CTRL_OUT_WIDTH))));
				port(ID(CLK), 1);
				port(ID(ARST), 1);
				port(ID(CTRL_IN), param(ID(CTRL_IN_WIDTH)));
				port(ID(CTRL_OUT), param(ID(CTRL_OUT_WIDTH)));
				check_expected();
				return;
			}

			if (cell->type == ID($memrd)) {
				param(ID(MEMID));
				param_bool(ID(CLK_ENABLE));
				param_bool(ID(CLK_POLARITY));
				param_bool(ID(TRANSPARENT));
				port(ID(CLK), 1);
				port(ID(EN), 1);
				port(ID(ADDR), param(ID(ABITS)));
				port(ID(DATA), param(ID(WIDTH)));
				check_expected();
				return;
			}

			if (cell->type == ID($memwr)) {
				param(ID(MEMID));
				param_bool(ID(CLK_ENABLE));
				param_bool(ID(CLK_POLARITY));
				param(ID(PRIORITY));
				port(ID(CLK), 1);
				port(ID(EN), param(ID(WIDTH)));
				port(ID(ADDR), param(ID(ABITS)));
				port(ID(DATA), param(ID(WIDTH)));
				check_expected();
				return;
			}

			if (cell->type == ID($meminit)) {
				param(ID(MEMID));
				param(ID(PRIORITY));
				port(ID(ADDR), param(ID(ABITS)));
				port(ID(DATA), param(ID(WIDTH)) * param(ID(WORDS)));
				check_expected();
				return;
			}

			if (cell->type == ID($mem)) {
				param(ID(MEMID));
				param(ID(SIZE));
				param(ID(OFFSET));
				param(ID(INIT));
				param_bits(ID(RD_CLK_ENABLE), max(1, param(ID(RD_PORTS))));
				param_bits(ID(RD_CLK_POLARITY), max(1, param(ID(RD_PORTS))));
				param_bits(ID(RD_TRANSPARENT), max(1, param(ID(RD_PORTS))));
				param_bits(ID(WR_CLK_ENABLE), max(1, param(ID(WR_PORTS))));
				param_bits(ID(WR_CLK_POLARITY), max(1, param(ID(WR_PORTS))));
				port(ID(RD_CLK), param(ID(RD_PORTS)));
				port(ID(RD_EN), param(ID(RD_PORTS)));
				port(ID(RD_ADDR), param(ID(RD_PORTS)) * param(ID(ABITS)));
				port(ID(RD_DATA), param(ID(RD_PORTS)) * param(ID(WIDTH)));
				port(ID(WR_CLK), param(ID(WR_PORTS)));
				port(ID(WR_EN), param(ID(WR_PORTS)) * param(ID(WIDTH)));
				port(ID(WR_ADDR), param(ID(WR_PORTS)) * param(ID(ABITS)));
				port(ID(WR_DATA), param(ID(WR_PORTS)) * param(ID(WIDTH)));
				check_expected();
				return;
			}

			if (cell->type == ID($tribuf)) {
				port(ID::A, param(ID(WIDTH)));
				port(ID::Y, param(ID(WIDTH)));
				port(ID(EN), 1);
				check_expected();
				return;
			}

			if (cell->type.in(ID($assert), ID($assume), ID($live), ID($fair), ID($cover))) {
				port(ID::A, 1);
				port(ID(EN), 1);
				check_expected();
				return;
			}

			if (cell->type == ID($initstate)) {
				port(ID::Y, 1);
				check_expected();
				return;
			}

			if (cell->type.in(ID($anyconst), ID($anyseq), ID($allconst), ID($allseq))) {
				port(ID::Y, param(ID(WIDTH)));
				check_expected();
				return;
			}

			if (cell->type == ID($equiv)) {
				port(ID::A, 1);
				port(ID::B, 1);
				port(ID::Y, 1);
				check_expected();
				return;
			}

			if (cell->type.in(ID($specify2), ID($specify3))) {
				param_bool(ID(FULL));
				param_bool(ID(SRC_DST_PEN));
				param_bool(ID(SRC_DST_POL));
				param(ID(T_RISE_MIN));
				param(ID(T_RISE_TYP));
				param(ID(T_RISE_MAX));
				param(ID(T_FALL_MIN));
				param(ID(T_FALL_TYP));
				param(ID(T_FALL_MAX));
				port(ID(EN), 1);
				port(ID(SRC), param(ID(SRC_WIDTH)));
				port(ID(DST), param(ID(DST_WIDTH)));
				if (cell->type == ID($specify3)) {
					param_bool(ID(EDGE_EN));
					param_bool(ID(EDGE_POL));
					param_bool(ID(DAT_DST_PEN));
					param_bool(ID(DAT_DST_POL));
					port(ID(DAT), param(ID(DST_WIDTH)));
				}
				check_expected();
				return;
			}

			if (cell->type == ID($specrule)) {
				param(ID(TYPE));
				param_bool(ID(SRC_PEN));
				param_bool(ID(SRC_POL));
				param_bool(ID(DST_PEN));
				param_bool(ID(DST_POL));
				param(ID(T_LIMIT));
				param(ID(T_LIMIT2));
				port(ID(SRC_EN), 1);
				port(ID(DST_EN), 1);
				port(ID(SRC), param(ID(SRC_WIDTH)));
				port(ID(DST), param(ID(DST_WIDTH)));
				check_expected();
				return;
			}

			if (cell->type == ID($_BUF_))    { check_gate("AY"); return; }
			if (cell->type == ID($_NOT_))    { check_gate("AY"); return; }
			if (cell->type == ID($_AND_))    { check_gate("ABY"); return; }
			if (cell->type == ID($_NAND_))   { check_gate("ABY"); return; }
			if (cell->type == ID($_OR_))     { check_gate("ABY"); return; }
			if (cell->type == ID($_NOR_))    { check_gate("ABY"); return; }
			if (cell->type == ID($_XOR_))    { check_gate("ABY"); return; }
			if (cell->type == ID($_XNOR_))   { check_gate("ABY"); return; }
			if (cell->type == ID($_ANDNOT_)) { check_gate("ABY"); return; }
			if (cell->type == ID($_ORNOT_))  { check_gate("ABY"); return; }
			if (cell->type == ID($_MUX_))    { check_gate("ABSY"); return; }
			if (cell->type == ID($_NMUX_))   { check_gate("ABSY"); return; }
			if (cell->type == ID($_AOI3_))   { check_gate("ABCY"); return; }
			if (cell->type == ID($_OAI3_))   { check_gate("ABCY"); return; }
			if (cell->type == ID($_AOI4_))   { check_gate("ABCDY"); return; }
			if (cell->type == ID($_OAI4_))   { check_gate("ABCDY"); return; }

			if (cell->type == ID($_TBUF_))  { check_gate("AYE"); return; }

			if (cell->type == ID($_MUX4_))  { check_gate("ABCDSTY"); return; }
			if (cell->type == ID($_MUX8_))  { check_gate("ABCDEFGHSTUY"); return; }
			if (cell->type == ID($_MUX16_)) { check_gate("ABCDEFGHIJKLMNOPSTUVY"); return; }

			if (cell->type == ID($_SR_NN_)) { check_gate("SRQ"); return; }
			if (cell->type == ID($_SR_NP_)) { check_gate("SRQ"); return; }
			if (cell->type == ID($_SR_PN_)) { check_gate("SRQ"); return; }
			if (cell->type == ID($_SR_PP_)) { check_gate("SRQ"); return; }

			if (cell->type == ID($_FF_))    { check_gate("DQ");  return; }
			if (cell->type == ID($_DFF_N_)) { check_gate("DQC"); return; }
			if (cell->type == ID($_DFF_P_)) { check_gate("DQC"); return; }

			if (cell->type == ID($_DFFE_NN_)) { check_gate("DQCE"); return; }
			if (cell->type == ID($_DFFE_NP_)) { check_gate("DQCE"); return; }
			if (cell->type == ID($_DFFE_PN_)) { check_gate("DQCE"); return; }
			if (cell->type == ID($_DFFE_PP_)) { check_gate("DQCE"); return; }

			if (cell->type == ID($_DFF_NN0_)) { check_gate("DQCR"); return; }
			if (cell->type == ID($_DFF_NN1_)) { check_gate("DQCR"); return; }
			if (cell->type == ID($_DFF_NP0_)) { check_gate("DQCR"); return; }
			if (cell->type == ID($_DFF_NP1_)) { check_gate("DQCR"); return; }
			if (cell->type == ID($_DFF_PN0_)) { check_gate("DQCR"); return; }
			if (cell->type == ID($_DFF_PN1_)) { check_gate("DQCR"); return; }
			if (cell->type == ID($_DFF_PP0_)) { check_gate("DQCR"); return; }
			if (cell->type == ID($_DFF_PP1_)) { check_gate("DQCR"); return; }

			if (cell->type == ID($_DFFSR_NNN_)) { check_gate("CSRDQ"); return; }
			if (cell->type == ID($_DFFSR_NNP_)) { check_gate("CSRDQ"); return; }
			if (cell->type == ID($_DFFSR_NPN_)) { check_gate("CSRDQ"); return; }
			if (cell->type == ID($_DFFSR_NPP_)) { check_gate("CSRDQ"); return; }
			if (cell->type == ID($_DFFSR_PNN_)) { check_gate("CSRDQ"); return; }
			if (cell->type == ID($_DFFSR_PNP_)) { check_gate("CSRDQ"); return; }
			if (cell->type == ID($_DFFSR_PPN_)) { check_gate("CSRDQ"); return; }
			if (cell->type == ID($_DFFSR_PPP_)) { check_gate("CSRDQ"); return; }

			if (cell->type == ID($_DLATCH_N_)) { check_gate("EDQ"); return; }
			if (cell->type == ID($_DLATCH_P_)) { check_gate("EDQ"); return; }

			if (cell->type == ID($_DLATCHSR_NNN_)) { check_gate("ESRDQ"); return; }
			if (cell->type == ID($_DLATCHSR_NNP_)) { check_gate("ESRDQ"); return; }
			if (cell->type == ID($_DLATCHSR_NPN_)) { check_gate("ESRDQ"); return; }
			if (cell->type == ID($_DLATCHSR_NPP_)) { check_gate("ESRDQ"); return; }
			if (cell->type == ID($_DLATCHSR_PNN_)) { check_gate("ESRDQ"); return; }
			if (cell->type == ID($_DLATCHSR_PNP_)) { check_gate("ESRDQ"); return; }
			if (cell->type == ID($_DLATCHSR_PPN_)) { check_gate("ESRDQ"); return; }
			if (cell->type == ID($_DLATCHSR_PPP_)) { check_gate("ESRDQ"); return; }

			error(__LINE__);
		}
	};
}
#endif

void RTLIL::Module::sort()
{
	wires_.sort(sort_by_id_str());
	cells_.sort(sort_by_id_str());
	avail_parameters.sort(sort_by_id_str());
	memories.sort(sort_by_id_str());
	processes.sort(sort_by_id_str());
	for (auto &it : cells_)
		it.second->sort();
	for (auto &it : wires_)
		it.second->attributes.sort(sort_by_id_str());
	for (auto &it : memories)
		it.second->attributes.sort(sort_by_id_str());
}

void RTLIL::Module::check()
{
#ifndef NDEBUG
	std::vector<bool> ports_declared;
	for (auto &it : wires_) {
		log_assert(this == it.second->module);
		log_assert(it.first == it.second->name);
		log_assert(!it.first.empty());
		log_assert(it.second->width >= 0);
		log_assert(it.second->port_id >= 0);
		for (auto &it2 : it.second->attributes)
			log_assert(!it2.first.empty());
		if (it.second->port_id) {
			log_assert(GetSize(ports) >= it.second->port_id);
			log_assert(ports.at(it.second->port_id-1) == it.first);
			log_assert(it.second->port_input || it.second->port_output);
			if (GetSize(ports_declared) < it.second->port_id)
				ports_declared.resize(it.second->port_id);
			log_assert(ports_declared[it.second->port_id-1] == false);
			ports_declared[it.second->port_id-1] = true;
		} else
			log_assert(!it.second->port_input && !it.second->port_output);
	}
	for (auto port_declared : ports_declared)
		log_assert(port_declared == true);
	log_assert(GetSize(ports) == GetSize(ports_declared));

	for (auto &it : memories) {
		log_assert(it.first == it.second->name);
		log_assert(!it.first.empty());
		log_assert(it.second->width >= 0);
		log_assert(it.second->size >= 0);
		for (auto &it2 : it.second->attributes)
			log_assert(!it2.first.empty());
	}

	for (auto &it : cells_) {
		log_assert(this == it.second->module);
		log_assert(it.first == it.second->name);
		log_assert(!it.first.empty());
		log_assert(!it.second->type.empty());
		for (auto &it2 : it.second->connections()) {
			log_assert(!it2.first.empty());
			it2.second.check();
		}
		for (auto &it2 : it.second->attributes)
			log_assert(!it2.first.empty());
		for (auto &it2 : it.second->parameters)
			log_assert(!it2.first.empty());
		InternalCellChecker checker(this, it.second);
		checker.check();
	}

	for (auto &it : processes) {
		log_assert(it.first == it.second->name);
		log_assert(!it.first.empty());
		log_assert(it.second->root_case.compare.empty());
		std::vector<CaseRule*> all_cases = {&it.second->root_case};
		for (size_t i = 0; i < all_cases.size(); i++) {
			for (auto &switch_it : all_cases[i]->switches) {
				for (auto &case_it : switch_it->cases) {
					for (auto &compare_it : case_it->compare) {
						log_assert(switch_it->signal.size() == compare_it.size());
					}
					all_cases.push_back(case_it);
				}
			}
		}
		for (auto &sync_it : it.second->syncs) {
			switch (sync_it->type) {
				case SyncType::ST0:
				case SyncType::ST1:
				case SyncType::STp:
				case SyncType::STn:
				case SyncType::STe:
					log_assert(!sync_it->signal.empty());
					break;
				case SyncType::STa:
				case SyncType::STg:
				case SyncType::STi:
					log_assert(sync_it->signal.empty());
					break;
			}
		}
	}

	for (auto &it : connections_) {
		log_assert(it.first.size() == it.second.size());
		log_assert(!it.first.has_const());
		it.first.check();
		it.second.check();
	}

	for (auto &it : attributes)
		log_assert(!it.first.empty());
#endif
}

void RTLIL::Module::optimize()
{
}

void RTLIL::Module::cloneInto(RTLIL::Module *new_mod) const
{
	log_assert(new_mod->refcount_wires_ == 0);
	log_assert(new_mod->refcount_cells_ == 0);

	new_mod->avail_parameters = avail_parameters;

	for (auto &conn : connections_)
		new_mod->connect(conn);

	for (auto &attr : attributes)
		new_mod->attributes[attr.first] = attr.second;

	for (auto &it : wires_)
		new_mod->addWire(it.first, it.second);

	for (auto &it : memories)
		new_mod->memories[it.first] = new RTLIL::Memory(*it.second);

	for (auto &it : cells_)
		new_mod->addCell(it.first, it.second);

	for (auto &it : processes)
		new_mod->processes[it.first] = it.second->clone();

	struct RewriteSigSpecWorker
	{
		RTLIL::Module *mod;
		void operator()(RTLIL::SigSpec &sig)
		{
			std::vector<RTLIL::SigChunk> chunks = sig.chunks();
			for (auto &c : chunks)
				if (c.wire != NULL)
					c.wire = mod->wires_.at(c.wire->name);
			sig = chunks;
		}
	};

	RewriteSigSpecWorker rewriteSigSpecWorker;
	rewriteSigSpecWorker.mod = new_mod;
	new_mod->rewrite_sigspecs(rewriteSigSpecWorker);
	new_mod->fixup_ports();
}

RTLIL::Module *RTLIL::Module::clone() const
{
	RTLIL::Module *new_mod = new RTLIL::Module;
	new_mod->name = name;
	cloneInto(new_mod);
	return new_mod;
}

bool RTLIL::Module::has_memories() const
{
	return !memories.empty();
}

bool RTLIL::Module::has_processes() const
{
	return !processes.empty();
}

bool RTLIL::Module::has_memories_warn() const
{
	if (!memories.empty())
		log_warning("Ignoring module %s because it contains memories (run 'memory' command first).\n", log_id(this));
	return !memories.empty();
}

bool RTLIL::Module::has_processes_warn() const
{
	if (!processes.empty())
		log_warning("Ignoring module %s because it contains processes (run 'proc' command first).\n", log_id(this));
	return !processes.empty();
}

std::vector<RTLIL::Wire*> RTLIL::Module::selected_wires() const
{
	std::vector<RTLIL::Wire*> result;
	result.reserve(wires_.size());
	for (auto &it : wires_)
		if (design->selected(this, it.second))
			result.push_back(it.second);
	return result;
}

std::vector<RTLIL::Cell*> RTLIL::Module::selected_cells() const
{
	std::vector<RTLIL::Cell*> result;
	result.reserve(wires_.size());
	for (auto &it : cells_)
		if (design->selected(this, it.second))
			result.push_back(it.second);
	return result;
}

void RTLIL::Module::add(RTLIL::Wire *wire)
{
	log_assert(!wire->name.empty());
	log_assert(count_id(wire->name) == 0);
	log_assert(refcount_wires_ == 0);
	wires_[wire->name] = wire;
	wire->module = this;
}

void RTLIL::Module::add(RTLIL::Cell *cell)
{
	log_assert(!cell->name.empty());
	log_assert(count_id(cell->name) == 0);
	log_assert(refcount_cells_ == 0);
	cells_[cell->name] = cell;
	cell->module = this;
}

void RTLIL::Module::remove(const pool<RTLIL::Wire*> &wires)
{
	log_assert(refcount_wires_ == 0);

	struct DeleteWireWorker
	{
		RTLIL::Module *module;
		const pool<RTLIL::Wire*> *wires_p;

		void operator()(RTLIL::SigSpec &sig) {
			std::vector<RTLIL::SigChunk> chunks = sig;
			for (auto &c : chunks)
				if (c.wire != NULL && wires_p->count(c.wire)) {
					c.wire = module->addWire(NEW_ID, c.width);
					c.offset = 0;
				}
			sig = chunks;
		}

		void operator()(RTLIL::SigSpec &lhs, RTLIL::SigSpec &rhs) {
			log_assert(GetSize(lhs) == GetSize(rhs));
			RTLIL::SigSpec new_lhs, new_rhs;
			for (int i = 0; i < GetSize(lhs); i++) {
				RTLIL::SigBit lhs_bit = lhs[i];
				if (lhs_bit.wire != nullptr && wires_p->count(lhs_bit.wire))
					continue;
				RTLIL::SigBit rhs_bit = rhs[i];
				if (rhs_bit.wire != nullptr && wires_p->count(rhs_bit.wire))
					continue;
				new_lhs.append(lhs_bit);
				new_rhs.append(rhs_bit);
			}
			lhs = new_lhs;
			rhs = new_rhs;
		}
	};

	DeleteWireWorker delete_wire_worker;
	delete_wire_worker.module = this;
	delete_wire_worker.wires_p = &wires;
	rewrite_sigspecs2(delete_wire_worker);

	for (auto &it : wires) {
		log_assert(wires_.count(it->name) != 0);
		wires_.erase(it->name);
		delete it;
	}
}

void RTLIL::Module::remove(RTLIL::Cell *cell)
{
	while (!cell->connections_.empty())
		cell->unsetPort(cell->connections_.begin()->first);

	log_assert(cells_.count(cell->name) != 0);
	log_assert(refcount_cells_ == 0);
	cells_.erase(cell->name);
	delete cell;
}

void RTLIL::Module::rename(RTLIL::Wire *wire, RTLIL::IdString new_name)
{
	log_assert(wires_[wire->name] == wire);
	log_assert(refcount_wires_ == 0);
	wires_.erase(wire->name);
	wire->name = new_name;
	add(wire);
}

void RTLIL::Module::rename(RTLIL::Cell *cell, RTLIL::IdString new_name)
{
	log_assert(cells_[cell->name] == cell);
	log_assert(refcount_wires_ == 0);
	cells_.erase(cell->name);
	cell->name = new_name;
	add(cell);
}

void RTLIL::Module::rename(RTLIL::IdString old_name, RTLIL::IdString new_name)
{
	log_assert(count_id(old_name) != 0);
	if (wires_.count(old_name))
		rename(wires_.at(old_name), new_name);
	else if (cells_.count(old_name))
		rename(cells_.at(old_name), new_name);
	else
		log_abort();
}

void RTLIL::Module::swap_names(RTLIL::Wire *w1, RTLIL::Wire *w2)
{
	log_assert(wires_[w1->name] == w1);
	log_assert(wires_[w2->name] == w2);
	log_assert(refcount_wires_ == 0);

	wires_.erase(w1->name);
	wires_.erase(w2->name);

	std::swap(w1->name, w2->name);

	wires_[w1->name] = w1;
	wires_[w2->name] = w2;
}

void RTLIL::Module::swap_names(RTLIL::Cell *c1, RTLIL::Cell *c2)
{
	log_assert(cells_[c1->name] == c1);
	log_assert(cells_[c2->name] == c2);
	log_assert(refcount_cells_ == 0);

	cells_.erase(c1->name);
	cells_.erase(c2->name);

	std::swap(c1->name, c2->name);

	cells_[c1->name] = c1;
	cells_[c2->name] = c2;
}

RTLIL::IdString RTLIL::Module::uniquify(RTLIL::IdString name)
{
	int index = 0;
	return uniquify(name, index);
}

RTLIL::IdString RTLIL::Module::uniquify(RTLIL::IdString name, int &index)
{
	if (index == 0) {
		if (count_id(name) == 0)
			return name;
		index++;
	}

	while (1) {
		RTLIL::IdString new_name = stringf("%s_%d", name.c_str(), index);
		if (count_id(new_name) == 0)
			return new_name;
		index++;
	}
}

static bool fixup_ports_compare(const RTLIL::Wire *a, const RTLIL::Wire *b)
{
	if (a->port_id && !b->port_id)
		return true;
	if (!a->port_id && b->port_id)
		return false;

	if (a->port_id == b->port_id)
		return a->name < b->name;
	return a->port_id < b->port_id;
}

void RTLIL::Module::connect(const RTLIL::SigSig &conn)
{
	for (auto mon : monitors)
		mon->notify_connect(this, conn);

	if (design)
		for (auto mon : design->monitors)
			mon->notify_connect(this, conn);

	// ignore all attempts to assign constants to other constants
	if (conn.first.has_const()) {
		RTLIL::SigSig new_conn;
		for (int i = 0; i < GetSize(conn.first); i++)
			if (conn.first[i].wire) {
				new_conn.first.append(conn.first[i]);
				new_conn.second.append(conn.second[i]);
			}
		if (GetSize(new_conn.first))
			connect(new_conn);
		return;
	}

	if (yosys_xtrace) {
		log("#X# Connect (SigSig) in %s: %s = %s (%d bits)\n", log_id(this), log_signal(conn.first), log_signal(conn.second), GetSize(conn.first));
		log_backtrace("-X- ", yosys_xtrace-1);
	}

	log_assert(GetSize(conn.first) == GetSize(conn.second));
	connections_.push_back(conn);
}

void RTLIL::Module::connect(const RTLIL::SigSpec &lhs, const RTLIL::SigSpec &rhs)
{
	connect(RTLIL::SigSig(lhs, rhs));
}

void RTLIL::Module::new_connections(const std::vector<RTLIL::SigSig> &new_conn)
{
	for (auto mon : monitors)
		mon->notify_connect(this, new_conn);

	if (design)
		for (auto mon : design->monitors)
			mon->notify_connect(this, new_conn);

	if (yosys_xtrace) {
		log("#X# New connections vector in %s:\n", log_id(this));
		for (auto &conn: new_conn)
			log("#X#    %s = %s (%d bits)\n", log_signal(conn.first), log_signal(conn.second), GetSize(conn.first));
		log_backtrace("-X- ", yosys_xtrace-1);
	}

	connections_ = new_conn;
}

const std::vector<RTLIL::SigSig> &RTLIL::Module::connections() const
{
	return connections_;
}

void RTLIL::Module::fixup_ports()
{
	std::vector<RTLIL::Wire*> all_ports;

	for (auto &w : wires_)
		if (w.second->port_input || w.second->port_output)
			all_ports.push_back(w.second);
		else
			w.second->port_id = 0;

	std::sort(all_ports.begin(), all_ports.end(), fixup_ports_compare);

	ports.clear();
	for (size_t i = 0; i < all_ports.size(); i++) {
		ports.push_back(all_ports[i]->name);
		all_ports[i]->port_id = i+1;
	}
}

RTLIL::Wire *RTLIL::Module::addWire(RTLIL::IdString name, int width)
{
	RTLIL::Wire *wire = new RTLIL::Wire;
	wire->name = name;
	wire->width = width;
	add(wire);
	return wire;
}

RTLIL::Wire *RTLIL::Module::addWire(RTLIL::IdString name, const RTLIL::Wire *other)
{
	RTLIL::Wire *wire = addWire(name);
	wire->width = other->width;
	wire->start_offset = other->start_offset;
	wire->port_id = other->port_id;
	wire->port_input = other->port_input;
	wire->port_output = other->port_output;
	wire->upto = other->upto;
	wire->attributes = other->attributes;
	return wire;
}

RTLIL::Cell *RTLIL::Module::addCell(RTLIL::IdString name, RTLIL::IdString type)
{
	RTLIL::Cell *cell = new RTLIL::Cell;
	cell->name = name;
	cell->type = type;
	add(cell);
	return cell;
}

RTLIL::Cell *RTLIL::Module::addCell(RTLIL::IdString name, const RTLIL::Cell *other)
{
	RTLIL::Cell *cell = addCell(name, other->type);
	cell->connections_ = other->connections_;
	cell->parameters = other->parameters;
	cell->attributes = other->attributes;
	return cell;
}

#define DEF_METHOD(_func, _y_size, _type) \
	RTLIL::Cell* RTLIL::Module::add ## _func(RTLIL::IdString name, RTLIL::SigSpec sig_a, RTLIL::SigSpec sig_y, bool is_signed, const std::string &src) { \
		RTLIL::Cell *cell = addCell(name, _type);           \
		cell->parameters[ID(A_SIGNED)] = is_signed;         \
		cell->parameters[ID(A_WIDTH)] = sig_a.size();       \
		cell->parameters[ID(Y_WIDTH)] = sig_y.size();       \
		cell->setPort(ID::A, sig_a);                        \
		cell->setPort(ID::Y, sig_y);                        \
		cell->set_src_attribute(src);                       \
		return cell;                                        \
	} \
	RTLIL::SigSpec RTLIL::Module::_func(RTLIL::IdString name, RTLIL::SigSpec sig_a, bool is_signed, const std::string &src) { \
		RTLIL::SigSpec sig_y = addWire(NEW_ID, _y_size);    \
		add ## _func(name, sig_a, sig_y, is_signed, src);   \
		return sig_y;                                       \
	}
DEF_METHOD(Not,        sig_a.size(), ID($not))
DEF_METHOD(Pos,        sig_a.size(), ID($pos))
DEF_METHOD(Neg,        sig_a.size(), ID($neg))
DEF_METHOD(ReduceAnd,  1, ID($reduce_and))
DEF_METHOD(ReduceOr,   1, ID($reduce_or))
DEF_METHOD(ReduceXor,  1, ID($reduce_xor))
DEF_METHOD(ReduceXnor, 1, ID($reduce_xnor))
DEF_METHOD(ReduceBool, 1, ID($reduce_bool))
DEF_METHOD(LogicNot,   1, ID($logic_not))
#undef DEF_METHOD

#define DEF_METHOD(_func, _y_size, _type) \
	RTLIL::Cell* RTLIL::Module::add ## _func(RTLIL::IdString name, RTLIL::SigSpec sig_a, RTLIL::SigSpec sig_b, RTLIL::SigSpec sig_y, bool is_signed, const std::string &src) { \
		RTLIL::Cell *cell = addCell(name, _type);           \
		cell->parameters[ID(A_SIGNED)] = is_signed;         \
		cell->parameters[ID(B_SIGNED)] = is_signed;         \
		cell->parameters[ID(A_WIDTH)] = sig_a.size();       \
		cell->parameters[ID(B_WIDTH)] = sig_b.size();       \
		cell->parameters[ID(Y_WIDTH)] = sig_y.size();       \
		cell->setPort(ID::A, sig_a);                        \
		cell->setPort(ID::B, sig_b);                        \
		cell->setPort(ID::Y, sig_y);                        \
		cell->set_src_attribute(src);                       \
		return cell;                                        \
	} \
	RTLIL::SigSpec RTLIL::Module::_func(RTLIL::IdString name, RTLIL::SigSpec sig_a, RTLIL::SigSpec sig_b, bool is_signed, const std::string &src) { \
		RTLIL::SigSpec sig_y = addWire(NEW_ID, _y_size);         \
		add ## _func(name, sig_a, sig_b, sig_y, is_signed, src); \
		return sig_y;                                            \
	}
DEF_METHOD(And,      max(sig_a.size(), sig_b.size()), ID($and))
DEF_METHOD(Or,       max(sig_a.size(), sig_b.size()), ID($or))
DEF_METHOD(Xor,      max(sig_a.size(), sig_b.size()), ID($xor))
DEF_METHOD(Xnor,     max(sig_a.size(), sig_b.size()), ID($xnor))
DEF_METHOD(Shl,      sig_a.size(), ID($shl))
DEF_METHOD(Shr,      sig_a.size(), ID($shr))
DEF_METHOD(Sshl,     sig_a.size(), ID($sshl))
DEF_METHOD(Sshr,     sig_a.size(), ID($sshr))
DEF_METHOD(Shift,    sig_a.size(), ID($shift))
DEF_METHOD(Shiftx,   sig_a.size(), ID($shiftx))
DEF_METHOD(Lt,       1, ID($lt))
DEF_METHOD(Le,       1, ID($le))
DEF_METHOD(Eq,       1, ID($eq))
DEF_METHOD(Ne,       1, ID($ne))
DEF_METHOD(Eqx,      1, ID($eqx))
DEF_METHOD(Nex,      1, ID($nex))
DEF_METHOD(Ge,       1, ID($ge))
DEF_METHOD(Gt,       1, ID($gt))
DEF_METHOD(Add,      max(sig_a.size(), sig_b.size()), ID($add))
DEF_METHOD(Sub,      max(sig_a.size(), sig_b.size()), ID($sub))
DEF_METHOD(Mul,      max(sig_a.size(), sig_b.size()), ID($mul))
DEF_METHOD(Div,      max(sig_a.size(), sig_b.size()), ID($div))
DEF_METHOD(Mod,      max(sig_a.size(), sig_b.size()), ID($mod))
DEF_METHOD(LogicAnd, 1, ID($logic_and))
DEF_METHOD(LogicOr,  1, ID($logic_or))
#undef DEF_METHOD

#define DEF_METHOD(_func, _type, _pmux) \
	RTLIL::Cell* RTLIL::Module::add ## _func(RTLIL::IdString name, RTLIL::SigSpec sig_a, RTLIL::SigSpec sig_b, RTLIL::SigSpec sig_s, RTLIL::SigSpec sig_y, const std::string &src) { \
		RTLIL::Cell *cell = addCell(name, _type);                 \
		cell->parameters[ID(WIDTH)] = sig_a.size();               \
		if (_pmux) cell->parameters[ID(S_WIDTH)] = sig_s.size();  \
		cell->setPort(ID::A, sig_a);                              \
		cell->setPort(ID::B, sig_b);                              \
		cell->setPort(ID(S), sig_s);                              \
		cell->setPort(ID::Y, sig_y);                              \
		cell->set_src_attribute(src);                             \
		return cell;                                              \
	} \
	RTLIL::SigSpec RTLIL::Module::_func(RTLIL::IdString name, RTLIL::SigSpec sig_a, RTLIL::SigSpec sig_b, RTLIL::SigSpec sig_s, const std::string &src) { \
		RTLIL::SigSpec sig_y = addWire(NEW_ID, sig_a.size());     \
		add ## _func(name, sig_a, sig_b, sig_s, sig_y, src);      \
		return sig_y;                                             \
	}
DEF_METHOD(Mux,      ID($mux),        0)
DEF_METHOD(Pmux,     ID($pmux),       1)
#undef DEF_METHOD

#define DEF_METHOD_2(_func, _type, _P1, _P2) \
	RTLIL::Cell* RTLIL::Module::add ## _func(RTLIL::IdString name, RTLIL::SigBit sig1, RTLIL::SigBit sig2, const std::string &src) { \
		RTLIL::Cell *cell = addCell(name, _type);         \
		cell->setPort("\\" #_P1, sig1);                   \
		cell->setPort("\\" #_P2, sig2);                   \
		cell->set_src_attribute(src);                     \
		return cell;                                      \
	} \
	RTLIL::SigBit RTLIL::Module::_func(RTLIL::IdString name, RTLIL::SigBit sig1, const std::string &src) { \
		RTLIL::SigBit sig2 = addWire(NEW_ID);             \
		add ## _func(name, sig1, sig2, src);              \
		return sig2;                                      \
	}
#define DEF_METHOD_3(_func, _type, _P1, _P2, _P3) \
	RTLIL::Cell* RTLIL::Module::add ## _func(RTLIL::IdString name, RTLIL::SigBit sig1, RTLIL::SigBit sig2, RTLIL::SigBit sig3, const std::string &src) { \
		RTLIL::Cell *cell = addCell(name, _type);         \
		cell->setPort("\\" #_P1, sig1);                   \
		cell->setPort("\\" #_P2, sig2);                   \
		cell->setPort("\\" #_P3, sig3);                   \
		cell->set_src_attribute(src);                     \
		return cell;                                      \
	} \
	RTLIL::SigBit RTLIL::Module::_func(RTLIL::IdString name, RTLIL::SigBit sig1, RTLIL::SigBit sig2, const std::string &src) { \
		RTLIL::SigBit sig3 = addWire(NEW_ID);             \
		add ## _func(name, sig1, sig2, sig3, src);        \
		return sig3;                                      \
	}
#define DEF_METHOD_4(_func, _type, _P1, _P2, _P3, _P4) \
	RTLIL::Cell* RTLIL::Module::add ## _func(RTLIL::IdString name, RTLIL::SigBit sig1, RTLIL::SigBit sig2, RTLIL::SigBit sig3, RTLIL::SigBit sig4, const std::string &src) { \
		RTLIL::Cell *cell = addCell(name, _type);         \
		cell->setPort("\\" #_P1, sig1);                   \
		cell->setPort("\\" #_P2, sig2);                   \
		cell->setPort("\\" #_P3, sig3);                   \
		cell->setPort("\\" #_P4, sig4);                   \
		cell->set_src_attribute(src);                     \
		return cell;                                      \
	} \
	RTLIL::SigBit RTLIL::Module::_func(RTLIL::IdString name, RTLIL::SigBit sig1, RTLIL::SigBit sig2, RTLIL::SigBit sig3, const std::string &src) { \
		RTLIL::SigBit sig4 = addWire(NEW_ID);             \
		add ## _func(name, sig1, sig2, sig3, sig4, src);  \
		return sig4;                                      \
	}
#define DEF_METHOD_5(_func, _type, _P1, _P2, _P3, _P4, _P5) \
	RTLIL::Cell* RTLIL::Module::add ## _func(RTLIL::IdString name, RTLIL::SigBit sig1, RTLIL::SigBit sig2, RTLIL::SigBit sig3, RTLIL::SigBit sig4, RTLIL::SigBit sig5, const std::string &src) { \
		RTLIL::Cell *cell = addCell(name, _type);         \
		cell->setPort("\\" #_P1, sig1);                   \
		cell->setPort("\\" #_P2, sig2);                   \
		cell->setPort("\\" #_P3, sig3);                   \
		cell->setPort("\\" #_P4, sig4);                   \
		cell->setPort("\\" #_P5, sig5);                   \
		cell->set_src_attribute(src);                     \
		return cell;                                      \
	} \
	RTLIL::SigBit RTLIL::Module::_func(RTLIL::IdString name, RTLIL::SigBit sig1, RTLIL::SigBit sig2, RTLIL::SigBit sig3, RTLIL::SigBit sig4, const std::string &src) { \
		RTLIL::SigBit sig5 = addWire(NEW_ID);                  \
		add ## _func(name, sig1, sig2, sig3, sig4, sig5, src); \
		return sig5;                                           \
	}
DEF_METHOD_2(BufGate,    ID($_BUF_),    A, Y)
DEF_METHOD_2(NotGate,    ID($_NOT_),    A, Y)
DEF_METHOD_3(AndGate,    ID($_AND_),    A, B, Y)
DEF_METHOD_3(NandGate,   ID($_NAND_),   A, B, Y)
DEF_METHOD_3(OrGate,     ID($_OR_),     A, B, Y)
DEF_METHOD_3(NorGate,    ID($_NOR_),    A, B, Y)
DEF_METHOD_3(XorGate,    ID($_XOR_),    A, B, Y)
DEF_METHOD_3(XnorGate,   ID($_XNOR_),   A, B, Y)
DEF_METHOD_3(AndnotGate, ID($_ANDNOT_), A, B, Y)
DEF_METHOD_3(OrnotGate,  ID($_ORNOT_),  A, B, Y)
DEF_METHOD_4(MuxGate,    ID($_MUX_),    A, B, S, Y)
DEF_METHOD_4(NmuxGate,   ID($_NMUX_),   A, B, S, Y)
DEF_METHOD_4(Aoi3Gate,   ID($_AOI3_),   A, B, C, Y)
DEF_METHOD_4(Oai3Gate,   ID($_OAI3_),   A, B, C, Y)
DEF_METHOD_5(Aoi4Gate,   ID($_AOI4_),   A, B, C, D, Y)
DEF_METHOD_5(Oai4Gate,   ID($_OAI4_),   A, B, C, D, Y)
#undef DEF_METHOD_2
#undef DEF_METHOD_3
#undef DEF_METHOD_4
#undef DEF_METHOD_5

RTLIL::Cell* RTLIL::Module::addPow(RTLIL::IdString name, RTLIL::SigSpec sig_a, RTLIL::SigSpec sig_b, RTLIL::SigSpec sig_y, bool a_signed, bool b_signed, const std::string &src)
{
	RTLIL::Cell *cell = addCell(name, ID($pow));
	cell->parameters[ID(A_SIGNED)] = a_signed;
	cell->parameters[ID(B_SIGNED)] = b_signed;
	cell->parameters[ID(A_WIDTH)] = sig_a.size();
	cell->parameters[ID(B_WIDTH)] = sig_b.size();
	cell->parameters[ID(Y_WIDTH)] = sig_y.size();
	cell->setPort(ID::A, sig_a);
	cell->setPort(ID::B, sig_b);
	cell->setPort(ID::Y, sig_y);
	cell->set_src_attribute(src);
	return cell;
}

RTLIL::Cell* RTLIL::Module::addSlice(RTLIL::IdString name, RTLIL::SigSpec sig_a, RTLIL::SigSpec sig_y, RTLIL::Const offset, const std::string &src)
{
	RTLIL::Cell *cell = addCell(name, ID($slice));
	cell->parameters[ID(A_WIDTH)] = sig_a.size();
	cell->parameters[ID(Y_WIDTH)] = sig_y.size();
	cell->parameters[ID(OFFSET)] = offset;
	cell->setPort(ID::A, sig_a);
	cell->setPort(ID::Y, sig_y);
	cell->set_src_attribute(src);
	return cell;
}

RTLIL::Cell* RTLIL::Module::addConcat(RTLIL::IdString name, RTLIL::SigSpec sig_a, RTLIL::SigSpec sig_b, RTLIL::SigSpec sig_y, const std::string &src)
{
	RTLIL::Cell *cell = addCell(name, ID($concat));
	cell->parameters[ID(A_WIDTH)] = sig_a.size();
	cell->parameters[ID(B_WIDTH)] = sig_b.size();
	cell->setPort(ID::A, sig_a);
	cell->setPort(ID::B, sig_b);
	cell->setPort(ID::Y, sig_y);
	cell->set_src_attribute(src);
	return cell;
}

RTLIL::Cell* RTLIL::Module::addLut(RTLIL::IdString name, RTLIL::SigSpec sig_a, RTLIL::SigSpec sig_y, RTLIL::Const lut, const std::string &src)
{
	RTLIL::Cell *cell = addCell(name, ID($lut));
	cell->parameters[ID(LUT)] = lut;
	cell->parameters[ID(WIDTH)] = sig_a.size();
	cell->setPort(ID::A, sig_a);
	cell->setPort(ID::Y, sig_y);
	cell->set_src_attribute(src);
	return cell;
}

RTLIL::Cell* RTLIL::Module::addTribuf(RTLIL::IdString name, RTLIL::SigSpec sig_a, RTLIL::SigSpec sig_en, RTLIL::SigSpec sig_y, const std::string &src)
{
	RTLIL::Cell *cell = addCell(name, ID($tribuf));
	cell->parameters[ID(WIDTH)] = sig_a.size();
	cell->setPort(ID::A, sig_a);
	cell->setPort(ID(EN), sig_en);
	cell->setPort(ID::Y, sig_y);
	cell->set_src_attribute(src);
	return cell;
}

RTLIL::Cell* RTLIL::Module::addAssert(RTLIL::IdString name, RTLIL::SigSpec sig_a, RTLIL::SigSpec sig_en, const std::string &src)
{
	RTLIL::Cell *cell = addCell(name, ID($assert));
	cell->setPort(ID::A, sig_a);
	cell->setPort(ID(EN), sig_en);
	cell->set_src_attribute(src);
	return cell;
}

RTLIL::Cell* RTLIL::Module::addAssume(RTLIL::IdString name, RTLIL::SigSpec sig_a, RTLIL::SigSpec sig_en, const std::string &src)
{
	RTLIL::Cell *cell = addCell(name, ID($assume));
	cell->setPort(ID::A, sig_a);
	cell->setPort(ID(EN), sig_en);
	cell->set_src_attribute(src);
	return cell;
}

RTLIL::Cell* RTLIL::Module::addLive(RTLIL::IdString name, RTLIL::SigSpec sig_a, RTLIL::SigSpec sig_en, const std::string &src)
{
	RTLIL::Cell *cell = addCell(name, ID($live));
	cell->setPort(ID::A, sig_a);
	cell->setPort(ID(EN), sig_en);
	cell->set_src_attribute(src);
	return cell;
}

RTLIL::Cell* RTLIL::Module::addFair(RTLIL::IdString name, RTLIL::SigSpec sig_a, RTLIL::SigSpec sig_en, const std::string &src)
{
	RTLIL::Cell *cell = addCell(name, ID($fair));
	cell->setPort(ID::A, sig_a);
	cell->setPort(ID(EN), sig_en);
	cell->set_src_attribute(src);
	return cell;
}

RTLIL::Cell* RTLIL::Module::addCover(RTLIL::IdString name, RTLIL::SigSpec sig_a, RTLIL::SigSpec sig_en, const std::string &src)
{
	RTLIL::Cell *cell = addCell(name, ID($cover));
	cell->setPort(ID::A, sig_a);
	cell->setPort(ID(EN), sig_en);
	cell->set_src_attribute(src);
	return cell;
}

RTLIL::Cell* RTLIL::Module::addEquiv(RTLIL::IdString name, RTLIL::SigSpec sig_a, RTLIL::SigSpec sig_b, RTLIL::SigSpec sig_y, const std::string &src)
{
	RTLIL::Cell *cell = addCell(name, ID($equiv));
	cell->setPort(ID::A, sig_a);
	cell->setPort(ID::B, sig_b);
	cell->setPort(ID::Y, sig_y);
	cell->set_src_attribute(src);
	return cell;
}

RTLIL::Cell* RTLIL::Module::addSr(RTLIL::IdString name, RTLIL::SigSpec sig_set, RTLIL::SigSpec sig_clr, RTLIL::SigSpec sig_q, bool set_polarity, bool clr_polarity, const std::string &src)
{
	RTLIL::Cell *cell = addCell(name, ID($sr));
	cell->parameters[ID(SET_POLARITY)] = set_polarity;
	cell->parameters[ID(CLR_POLARITY)] = clr_polarity;
	cell->parameters[ID(WIDTH)] = sig_q.size();
	cell->setPort(ID(SET), sig_set);
	cell->setPort(ID(CLR), sig_clr);
	cell->setPort(ID(Q), sig_q);
	cell->set_src_attribute(src);
	return cell;
}

RTLIL::Cell* RTLIL::Module::addFf(RTLIL::IdString name, RTLIL::SigSpec sig_d, RTLIL::SigSpec sig_q, const std::string &src)
{
	RTLIL::Cell *cell = addCell(name, ID($ff));
	cell->parameters[ID(WIDTH)] = sig_q.size();
	cell->setPort(ID(D), sig_d);
	cell->setPort(ID(Q), sig_q);
	cell->set_src_attribute(src);
	return cell;
}

RTLIL::Cell* RTLIL::Module::addDff(RTLIL::IdString name, RTLIL::SigSpec sig_clk, RTLIL::SigSpec sig_d, RTLIL::SigSpec sig_q, bool clk_polarity, const std::string &src)
{
	RTLIL::Cell *cell = addCell(name, ID($dff));
	cell->parameters[ID(CLK_POLARITY)] = clk_polarity;
	cell->parameters[ID(WIDTH)] = sig_q.size();
	cell->setPort(ID(CLK), sig_clk);
	cell->setPort(ID(D), sig_d);
	cell->setPort(ID(Q), sig_q);
	cell->set_src_attribute(src);
	return cell;
}

RTLIL::Cell* RTLIL::Module::addDffe(RTLIL::IdString name, RTLIL::SigSpec sig_clk, RTLIL::SigSpec sig_en, RTLIL::SigSpec sig_d, RTLIL::SigSpec sig_q, bool clk_polarity, bool en_polarity, const std::string &src)
{
	RTLIL::Cell *cell = addCell(name, ID($dffe));
	cell->parameters[ID(CLK_POLARITY)] = clk_polarity;
	cell->parameters[ID(EN_POLARITY)] = en_polarity;
	cell->parameters[ID(WIDTH)] = sig_q.size();
	cell->setPort(ID(CLK), sig_clk);
	cell->setPort(ID(EN), sig_en);
	cell->setPort(ID(D), sig_d);
	cell->setPort(ID(Q), sig_q);
	cell->set_src_attribute(src);
	return cell;
}

RTLIL::Cell* RTLIL::Module::addDffsr(RTLIL::IdString name, RTLIL::SigSpec sig_clk, RTLIL::SigSpec sig_set, RTLIL::SigSpec sig_clr,
		RTLIL::SigSpec sig_d, RTLIL::SigSpec sig_q, bool clk_polarity, bool set_polarity, bool clr_polarity, const std::string &src)
{
	RTLIL::Cell *cell = addCell(name, ID($dffsr));
	cell->parameters[ID(CLK_POLARITY)] = clk_polarity;
	cell->parameters[ID(SET_POLARITY)] = set_polarity;
	cell->parameters[ID(CLR_POLARITY)] = clr_polarity;
	cell->parameters[ID(WIDTH)] = sig_q.size();
	cell->setPort(ID(CLK), sig_clk);
	cell->setPort(ID(SET), sig_set);
	cell->setPort(ID(CLR), sig_clr);
	cell->setPort(ID(D), sig_d);
	cell->setPort(ID(Q), sig_q);
	cell->set_src_attribute(src);
	return cell;
}

RTLIL::Cell* RTLIL::Module::addAdff(RTLIL::IdString name, RTLIL::SigSpec sig_clk, RTLIL::SigSpec sig_arst, RTLIL::SigSpec sig_d, RTLIL::SigSpec sig_q,
		RTLIL::Const arst_value, bool clk_polarity, bool arst_polarity, const std::string &src)
{
	RTLIL::Cell *cell = addCell(name, ID($adff));
	cell->parameters[ID(CLK_POLARITY)] = clk_polarity;
	cell->parameters[ID(ARST_POLARITY)] = arst_polarity;
	cell->parameters[ID(ARST_VALUE)] = arst_value;
	cell->parameters[ID(WIDTH)] = sig_q.size();
	cell->setPort(ID(CLK), sig_clk);
	cell->setPort(ID(ARST), sig_arst);
	cell->setPort(ID(D), sig_d);
	cell->setPort(ID(Q), sig_q);
	cell->set_src_attribute(src);
	return cell;
}

RTLIL::Cell* RTLIL::Module::addDlatch(RTLIL::IdString name, RTLIL::SigSpec sig_en, RTLIL::SigSpec sig_d, RTLIL::SigSpec sig_q, bool en_polarity, const std::string &src)
{
	RTLIL::Cell *cell = addCell(name, ID($dlatch));
	cell->parameters[ID(EN_POLARITY)] = en_polarity;
	cell->parameters[ID(WIDTH)] = sig_q.size();
	cell->setPort(ID(EN), sig_en);
	cell->setPort(ID(D), sig_d);
	cell->setPort(ID(Q), sig_q);
	cell->set_src_attribute(src);
	return cell;
}

RTLIL::Cell* RTLIL::Module::addDlatchsr(RTLIL::IdString name, RTLIL::SigSpec sig_en, RTLIL::SigSpec sig_set, RTLIL::SigSpec sig_clr,
		RTLIL::SigSpec sig_d, RTLIL::SigSpec sig_q, bool en_polarity, bool set_polarity, bool clr_polarity, const std::string &src)
{
	RTLIL::Cell *cell = addCell(name, ID($dlatchsr));
	cell->parameters[ID(EN_POLARITY)] = en_polarity;
	cell->parameters[ID(SET_POLARITY)] = set_polarity;
	cell->parameters[ID(CLR_POLARITY)] = clr_polarity;
	cell->parameters[ID(WIDTH)] = sig_q.size();
	cell->setPort(ID(EN), sig_en);
	cell->setPort(ID(SET), sig_set);
	cell->setPort(ID(CLR), sig_clr);
	cell->setPort(ID(D), sig_d);
	cell->setPort(ID(Q), sig_q);
	cell->set_src_attribute(src);
	return cell;
}

RTLIL::Cell* RTLIL::Module::addFfGate(RTLIL::IdString name, RTLIL::SigSpec sig_d, RTLIL::SigSpec sig_q, const std::string &src)
{
	RTLIL::Cell *cell = addCell(name, ID($_FF_));
	cell->setPort(ID(D), sig_d);
	cell->setPort(ID(Q), sig_q);
	cell->set_src_attribute(src);
	return cell;
}

RTLIL::Cell* RTLIL::Module::addDffGate(RTLIL::IdString name, RTLIL::SigSpec sig_clk, RTLIL::SigSpec sig_d, RTLIL::SigSpec sig_q, bool clk_polarity, const std::string &src)
{
	RTLIL::Cell *cell = addCell(name, stringf("$_DFF_%c_", clk_polarity ? 'P' : 'N'));
	cell->setPort(ID(C), sig_clk);
	cell->setPort(ID(D), sig_d);
	cell->setPort(ID(Q), sig_q);
	cell->set_src_attribute(src);
	return cell;
}

RTLIL::Cell* RTLIL::Module::addDffeGate(RTLIL::IdString name, RTLIL::SigSpec sig_clk, RTLIL::SigSpec sig_en, RTLIL::SigSpec sig_d, RTLIL::SigSpec sig_q, bool clk_polarity, bool en_polarity, const std::string &src)
{
	RTLIL::Cell *cell = addCell(name, stringf("$_DFFE_%c%c_", clk_polarity ? 'P' : 'N', en_polarity ? 'P' : 'N'));
	cell->setPort(ID(C), sig_clk);
	cell->setPort(ID(E), sig_en);
	cell->setPort(ID(D), sig_d);
	cell->setPort(ID(Q), sig_q);
	cell->set_src_attribute(src);
	return cell;
}

RTLIL::Cell* RTLIL::Module::addDffsrGate(RTLIL::IdString name, RTLIL::SigSpec sig_clk, RTLIL::SigSpec sig_set, RTLIL::SigSpec sig_clr,
		RTLIL::SigSpec sig_d, RTLIL::SigSpec sig_q, bool clk_polarity, bool set_polarity, bool clr_polarity, const std::string &src)
{
	RTLIL::Cell *cell = addCell(name, stringf("$_DFFSR_%c%c%c_", clk_polarity ? 'P' : 'N', set_polarity ? 'P' : 'N', clr_polarity ? 'P' : 'N'));
	cell->setPort(ID(C), sig_clk);
	cell->setPort(ID(S), sig_set);
	cell->setPort(ID(R), sig_clr);
	cell->setPort(ID(D), sig_d);
	cell->setPort(ID(Q), sig_q);
	cell->set_src_attribute(src);
	return cell;
}

RTLIL::Cell* RTLIL::Module::addAdffGate(RTLIL::IdString name, RTLIL::SigSpec sig_clk, RTLIL::SigSpec sig_arst, RTLIL::SigSpec sig_d, RTLIL::SigSpec sig_q,
		bool arst_value, bool clk_polarity, bool arst_polarity, const std::string &src)
{
	RTLIL::Cell *cell = addCell(name, stringf("$_DFF_%c%c%c_", clk_polarity ? 'P' : 'N', arst_polarity ? 'P' : 'N', arst_value ? '1' : '0'));
	cell->setPort(ID(C), sig_clk);
	cell->setPort(ID(R), sig_arst);
	cell->setPort(ID(D), sig_d);
	cell->setPort(ID(Q), sig_q);
	cell->set_src_attribute(src);
	return cell;
}

RTLIL::Cell* RTLIL::Module::addDlatchGate(RTLIL::IdString name, RTLIL::SigSpec sig_en, RTLIL::SigSpec sig_d, RTLIL::SigSpec sig_q, bool en_polarity, const std::string &src)
{
	RTLIL::Cell *cell = addCell(name, stringf("$_DLATCH_%c_", en_polarity ? 'P' : 'N'));
	cell->setPort(ID(E), sig_en);
	cell->setPort(ID(D), sig_d);
	cell->setPort(ID(Q), sig_q);
	cell->set_src_attribute(src);
	return cell;
}

RTLIL::Cell* RTLIL::Module::addDlatchsrGate(RTLIL::IdString name, RTLIL::SigSpec sig_en, RTLIL::SigSpec sig_set, RTLIL::SigSpec sig_clr,
		RTLIL::SigSpec sig_d, RTLIL::SigSpec sig_q, bool en_polarity, bool set_polarity, bool clr_polarity, const std::string &src)
{
	RTLIL::Cell *cell = addCell(name, stringf("$_DLATCHSR_%c%c%c_", en_polarity ? 'P' : 'N', set_polarity ? 'P' : 'N', clr_polarity ? 'P' : 'N'));
	cell->setPort(ID(E), sig_en);
	cell->setPort(ID(S), sig_set);
	cell->setPort(ID(R), sig_clr);
	cell->setPort(ID(D), sig_d);
	cell->setPort(ID(Q), sig_q);
	cell->set_src_attribute(src);
	return cell;
}

RTLIL::SigSpec RTLIL::Module::Anyconst(RTLIL::IdString name, int width, const std::string &src)
{
	RTLIL::SigSpec sig = addWire(NEW_ID, width);
	Cell *cell = addCell(name, ID($anyconst));
	cell->setParam(ID(WIDTH), width);
	cell->setPort(ID::Y, sig);
	cell->set_src_attribute(src);
	return sig;
}

RTLIL::SigSpec RTLIL::Module::Anyseq(RTLIL::IdString name, int width, const std::string &src)
{
	RTLIL::SigSpec sig = addWire(NEW_ID, width);
	Cell *cell = addCell(name, ID($anyseq));
	cell->setParam(ID(WIDTH), width);
	cell->setPort(ID::Y, sig);
	cell->set_src_attribute(src);
	return sig;
}

RTLIL::SigSpec RTLIL::Module::Allconst(RTLIL::IdString name, int width, const std::string &src)
{
	RTLIL::SigSpec sig = addWire(NEW_ID, width);
	Cell *cell = addCell(name, ID($allconst));
	cell->setParam(ID(WIDTH), width);
	cell->setPort(ID::Y, sig);
	cell->set_src_attribute(src);
	return sig;
}

RTLIL::SigSpec RTLIL::Module::Allseq(RTLIL::IdString name, int width, const std::string &src)
{
	RTLIL::SigSpec sig = addWire(NEW_ID, width);
	Cell *cell = addCell(name, ID($allseq));
	cell->setParam(ID(WIDTH), width);
	cell->setPort(ID::Y, sig);
	cell->set_src_attribute(src);
	return sig;
}

RTLIL::SigSpec RTLIL::Module::Initstate(RTLIL::IdString name, const std::string &src)
{
	RTLIL::SigSpec sig = addWire(NEW_ID);
	Cell *cell = addCell(name, ID($initstate));
	cell->setPort(ID::Y, sig);
	cell->set_src_attribute(src);
	return sig;
}

RTLIL::Wire::Wire()
{
	static unsigned int hashidx_count = 123456789;
	hashidx_count = mkhash_xorshift(hashidx_count);
	hashidx_ = hashidx_count;

	module = nullptr;
	width = 1;
	start_offset = 0;
	port_id = 0;
	port_input = false;
	port_output = false;
	upto = false;

#ifdef WITH_PYTHON
	RTLIL::Wire::get_all_wires()->insert(std::pair<unsigned int, RTLIL::Wire*>(hashidx_, this));
#endif
}

RTLIL::Wire::~Wire()
{
#ifdef WITH_PYTHON
	RTLIL::Wire::get_all_wires()->erase(hashidx_);
#endif
}

#ifdef WITH_PYTHON
static std::map<unsigned int, RTLIL::Wire*> all_wires;
std::map<unsigned int, RTLIL::Wire*> *RTLIL::Wire::get_all_wires(void)
{
	return &all_wires;
}
#endif

RTLIL::Memory::Memory()
{
	static unsigned int hashidx_count = 123456789;
	hashidx_count = mkhash_xorshift(hashidx_count);
	hashidx_ = hashidx_count;

	width = 1;
	start_offset = 0;
	size = 0;
#ifdef WITH_PYTHON
	RTLIL::Memory::get_all_memorys()->insert(std::pair<unsigned int, RTLIL::Memory*>(hashidx_, this));
#endif
}

RTLIL::Cell::Cell() : module(nullptr)
{
	static unsigned int hashidx_count = 123456789;
	hashidx_count = mkhash_xorshift(hashidx_count);
	hashidx_ = hashidx_count;

	// log("#memtrace# %p\n", this);
	memhasher();

#ifdef WITH_PYTHON
	RTLIL::Cell::get_all_cells()->insert(std::pair<unsigned int, RTLIL::Cell*>(hashidx_, this));
#endif
}

RTLIL::Cell::~Cell()
{
#ifdef WITH_PYTHON
	RTLIL::Cell::get_all_cells()->erase(hashidx_);
#endif
}

#ifdef WITH_PYTHON
static std::map<unsigned int, RTLIL::Cell*> all_cells;
std::map<unsigned int, RTLIL::Cell*> *RTLIL::Cell::get_all_cells(void)
{
	return &all_cells;
}
#endif

bool RTLIL::Cell::hasPort(RTLIL::IdString portname) const
{
	return connections_.count(portname) != 0;
}

void RTLIL::Cell::unsetPort(RTLIL::IdString portname)
{
	RTLIL::SigSpec signal;
	auto conn_it = connections_.find(portname);

	if (conn_it != connections_.end())
	{
		for (auto mon : module->monitors)
			mon->notify_connect(this, conn_it->first, conn_it->second, signal);

		if (module->design)
			for (auto mon : module->design->monitors)
				mon->notify_connect(this, conn_it->first, conn_it->second, signal);

		if (yosys_xtrace) {
			log("#X# Unconnect %s.%s.%s\n", log_id(this->module), log_id(this), log_id(portname));
			log_backtrace("-X- ", yosys_xtrace-1);
		}

		connections_.erase(conn_it);
	}
}

void RTLIL::Cell::setPort(RTLIL::IdString portname, RTLIL::SigSpec signal)
{
	auto conn_it = connections_.find(portname);

	if (conn_it == connections_.end()) {
		connections_[portname] = RTLIL::SigSpec();
		conn_it = connections_.find(portname);
		log_assert(conn_it != connections_.end());
	} else
	if (conn_it->second == signal)
		return;

	for (auto mon : module->monitors)
		mon->notify_connect(this, conn_it->first, conn_it->second, signal);

	if (module->design)
		for (auto mon : module->design->monitors)
			mon->notify_connect(this, conn_it->first, conn_it->second, signal);

	if (yosys_xtrace) {
		log("#X# Connect %s.%s.%s = %s (%d)\n", log_id(this->module), log_id(this), log_id(portname), log_signal(signal), GetSize(signal));
		log_backtrace("-X- ", yosys_xtrace-1);
	}

	conn_it->second = signal;
}

const RTLIL::SigSpec &RTLIL::Cell::getPort(RTLIL::IdString portname) const
{
	return connections_.at(portname);
}

const dict<RTLIL::IdString, RTLIL::SigSpec> &RTLIL::Cell::connections() const
{
	return connections_;
}

bool RTLIL::Cell::known() const
{
	if (yosys_celltypes.cell_known(type))
		return true;
	if (module && module->design && module->design->module(type))
		return true;
	return false;
}

bool RTLIL::Cell::input(RTLIL::IdString portname) const
{
	if (yosys_celltypes.cell_known(type))
		return yosys_celltypes.cell_input(type, portname);
	if (module && module->design) {
		RTLIL::Module *m = module->design->module(type);
		RTLIL::Wire *w = m ? m->wire(portname) : nullptr;
		return w && w->port_input;
	}
	return false;
}

bool RTLIL::Cell::output(RTLIL::IdString portname) const
{
	if (yosys_celltypes.cell_known(type))
		return yosys_celltypes.cell_output(type, portname);
	if (module && module->design) {
		RTLIL::Module *m = module->design->module(type);
		RTLIL::Wire *w = m ? m->wire(portname) : nullptr;
		return w && w->port_output;
	}
	return false;
}

bool RTLIL::Cell::hasParam(RTLIL::IdString paramname) const
{
	return parameters.count(paramname) != 0;
}

void RTLIL::Cell::unsetParam(RTLIL::IdString paramname)
{
	parameters.erase(paramname);
}

void RTLIL::Cell::setParam(RTLIL::IdString paramname, RTLIL::Const value)
{
	parameters[paramname] = value;
}

const RTLIL::Const &RTLIL::Cell::getParam(RTLIL::IdString paramname) const
{
	return parameters.at(paramname);
}

void RTLIL::Cell::sort()
{
	connections_.sort(sort_by_id_str());
	parameters.sort(sort_by_id_str());
	attributes.sort(sort_by_id_str());
}

void RTLIL::Cell::check()
{
#ifndef NDEBUG
	InternalCellChecker checker(NULL, this);
	checker.check();
#endif
}

void RTLIL::Cell::fixup_parameters(bool set_a_signed, bool set_b_signed)
{
	if (!type.begins_with("$") || type.begins_with("$_") || type.begins_with("$paramod") || type.begins_with("$fmcombine") ||
			type.begins_with("$verific$") || type.begins_with("$array:") || type.begins_with("$extern:"))
		return;

	if (type == ID($mux) || type == ID($pmux)) {
		parameters[ID(WIDTH)] = GetSize(connections_[ID::Y]);
		if (type == ID($pmux))
			parameters[ID(S_WIDTH)] = GetSize(connections_[ID(S)]);
		check();
		return;
	}

	if (type == ID($lut) || type == ID($sop)) {
		parameters[ID(WIDTH)] = GetSize(connections_[ID::A]);
		return;
	}

	if (type == ID($fa)) {
		parameters[ID(WIDTH)] = GetSize(connections_[ID::Y]);
		return;
	}

	if (type == ID($lcu)) {
		parameters[ID(WIDTH)] = GetSize(connections_[ID(CO)]);
		return;
	}

	bool signedness_ab = !type.in(ID($slice), ID($concat), ID($macc));

	if (connections_.count(ID::A)) {
		if (signedness_ab) {
			if (set_a_signed)
				parameters[ID(A_SIGNED)] = true;
			else if (parameters.count(ID(A_SIGNED)) == 0)
				parameters[ID(A_SIGNED)] = false;
		}
		parameters[ID(A_WIDTH)] = GetSize(connections_[ID::A]);
	}

	if (connections_.count(ID::B)) {
		if (signedness_ab) {
			if (set_b_signed)
				parameters[ID(B_SIGNED)] = true;
			else if (parameters.count(ID(B_SIGNED)) == 0)
				parameters[ID(B_SIGNED)] = false;
		}
		parameters[ID(B_WIDTH)] = GetSize(connections_[ID::B]);
	}

	if (connections_.count(ID::Y))
		parameters[ID(Y_WIDTH)] = GetSize(connections_[ID::Y]);

	if (connections_.count(ID(Q)))
		parameters[ID(WIDTH)] = GetSize(connections_[ID(Q)]);

	check();
}

RTLIL::SigChunk::SigChunk()
{
	wire = NULL;
	width = 0;
	offset = 0;
}

RTLIL::SigChunk::SigChunk(const RTLIL::Const &value)
{
	wire = NULL;
	data = value.bits;
	width = GetSize(data);
	offset = 0;
}

RTLIL::SigChunk::SigChunk(RTLIL::Wire *wire)
{
	log_assert(wire != nullptr);
	this->wire = wire;
	this->width = wire->width;
	this->offset = 0;
}

RTLIL::SigChunk::SigChunk(RTLIL::Wire *wire, int offset, int width)
{
	log_assert(wire != nullptr);
	this->wire = wire;
	this->width = width;
	this->offset = offset;
}

RTLIL::SigChunk::SigChunk(const std::string &str)
{
	wire = NULL;
	data = RTLIL::Const(str).bits;
	width = GetSize(data);
	offset = 0;
}

RTLIL::SigChunk::SigChunk(int val, int width)
{
	wire = NULL;
	data = RTLIL::Const(val, width).bits;
	this->width = GetSize(data);
	offset = 0;
}

RTLIL::SigChunk::SigChunk(RTLIL::State bit, int width)
{
	wire = NULL;
	data = RTLIL::Const(bit, width).bits;
	this->width = GetSize(data);
	offset = 0;
}

RTLIL::SigChunk::SigChunk(RTLIL::SigBit bit)
{
	wire = bit.wire;
	offset = 0;
	if (wire == NULL)
		data = RTLIL::Const(bit.data).bits;
	else
		offset = bit.offset;
	width = 1;
}

RTLIL::SigChunk::SigChunk(const RTLIL::SigChunk &sigchunk) : data(sigchunk.data)
{
	wire = sigchunk.wire;
	data = sigchunk.data;
	width = sigchunk.width;
	offset = sigchunk.offset;
}

RTLIL::SigChunk RTLIL::SigChunk::extract(int offset, int length) const
{
	RTLIL::SigChunk ret;
	if (wire) {
		ret.wire = wire;
		ret.offset = this->offset + offset;
		ret.width = length;
	} else {
		for (int i = 0; i < length; i++)
			ret.data.push_back(data[offset+i]);
		ret.width = length;
	}
	return ret;
}

bool RTLIL::SigChunk::operator <(const RTLIL::SigChunk &other) const
{
	if (wire && other.wire)
		if (wire->name != other.wire->name)
			return wire->name < other.wire->name;

	if (wire != other.wire)
		return wire < other.wire;

	if (offset != other.offset)
		return offset < other.offset;

	if (width != other.width)
		return width < other.width;

	return data < other.data;
}

bool RTLIL::SigChunk::operator ==(const RTLIL::SigChunk &other) const
{
	return wire == other.wire && width == other.width && offset == other.offset && data == other.data;
}

bool RTLIL::SigChunk::operator !=(const RTLIL::SigChunk &other) const
{
	if (*this == other)
		return false;
	return true;
}

RTLIL::SigSpec::SigSpec()
{
	width_ = 0;
	hash_ = 0;
}

RTLIL::SigSpec::SigSpec(const RTLIL::SigSpec &other)
{
	*this = other;
}

RTLIL::SigSpec::SigSpec(std::initializer_list<RTLIL::SigSpec> parts)
{
	cover("kernel.rtlil.sigspec.init.list");

	width_ = 0;
	hash_ = 0;

	std::vector<RTLIL::SigSpec> parts_vec(parts.begin(), parts.end());
	for (auto it = parts_vec.rbegin(); it != parts_vec.rend(); it++)
		append(*it);
}

const RTLIL::SigSpec &RTLIL::SigSpec::operator=(const RTLIL::SigSpec &other)
{
	cover("kernel.rtlil.sigspec.assign");

	width_ = other.width_;
	hash_ = other.hash_;
	chunks_ = other.chunks_;
	bits_.clear();

	if (!other.bits_.empty())
	{
		RTLIL::SigChunk *last = NULL;
		int last_end_offset = 0;

		for (auto &bit : other.bits_) {
			if (last && bit.wire == last->wire) {
				if (bit.wire == NULL) {
					last->data.push_back(bit.data);
					last->width++;
					continue;
				} else if (last_end_offset == bit.offset) {
					last_end_offset++;
					last->width++;
					continue;
				}
			}
			chunks_.push_back(bit);
			last = &chunks_.back();
			last_end_offset = bit.offset + 1;
		}

		check();
	}

	return *this;
}

RTLIL::SigSpec::SigSpec(const RTLIL::Const &value)
{
	cover("kernel.rtlil.sigspec.init.const");

	chunks_.push_back(RTLIL::SigChunk(value));
	width_ = chunks_.back().width;
	hash_ = 0;
	check();
}

RTLIL::SigSpec::SigSpec(const RTLIL::SigChunk &chunk)
{
	cover("kernel.rtlil.sigspec.init.chunk");

	chunks_.push_back(chunk);
	width_ = chunks_.back().width;
	hash_ = 0;
	check();
}

RTLIL::SigSpec::SigSpec(RTLIL::Wire *wire)
{
	cover("kernel.rtlil.sigspec.init.wire");

	chunks_.push_back(RTLIL::SigChunk(wire));
	width_ = chunks_.back().width;
	hash_ = 0;
	check();
}

RTLIL::SigSpec::SigSpec(RTLIL::Wire *wire, int offset, int width)
{
	cover("kernel.rtlil.sigspec.init.wire_part");

	chunks_.push_back(RTLIL::SigChunk(wire, offset, width));
	width_ = chunks_.back().width;
	hash_ = 0;
	check();
}

RTLIL::SigSpec::SigSpec(const std::string &str)
{
	cover("kernel.rtlil.sigspec.init.str");

	chunks_.push_back(RTLIL::SigChunk(str));
	width_ = chunks_.back().width;
	hash_ = 0;
	check();
}

RTLIL::SigSpec::SigSpec(int val, int width)
{
	cover("kernel.rtlil.sigspec.init.int");

	chunks_.push_back(RTLIL::SigChunk(val, width));
	width_ = width;
	hash_ = 0;
	check();
}

RTLIL::SigSpec::SigSpec(RTLIL::State bit, int width)
{
	cover("kernel.rtlil.sigspec.init.state");

	chunks_.push_back(RTLIL::SigChunk(bit, width));
	width_ = width;
	hash_ = 0;
	check();
}

RTLIL::SigSpec::SigSpec(RTLIL::SigBit bit, int width)
{
	cover("kernel.rtlil.sigspec.init.bit");

	if (bit.wire == NULL)
		chunks_.push_back(RTLIL::SigChunk(bit.data, width));
	else
		for (int i = 0; i < width; i++)
			chunks_.push_back(bit);
	width_ = width;
	hash_ = 0;
	check();
}

RTLIL::SigSpec::SigSpec(std::vector<RTLIL::SigChunk> chunks)
{
	cover("kernel.rtlil.sigspec.init.stdvec_chunks");

	width_ = 0;
	hash_ = 0;
	for (auto &c : chunks)
		append(c);
	check();
}

RTLIL::SigSpec::SigSpec(std::vector<RTLIL::SigBit> bits)
{
	cover("kernel.rtlil.sigspec.init.stdvec_bits");

	width_ = 0;
	hash_ = 0;
	for (auto &bit : bits)
		append_bit(bit);
	check();
}

RTLIL::SigSpec::SigSpec(pool<RTLIL::SigBit> bits)
{
	cover("kernel.rtlil.sigspec.init.pool_bits");

	width_ = 0;
	hash_ = 0;
	for (auto &bit : bits)
		append_bit(bit);
	check();
}

RTLIL::SigSpec::SigSpec(std::set<RTLIL::SigBit> bits)
{
	cover("kernel.rtlil.sigspec.init.stdset_bits");

	width_ = 0;
	hash_ = 0;
	for (auto &bit : bits)
		append_bit(bit);
	check();
}

RTLIL::SigSpec::SigSpec(bool bit)
{
	cover("kernel.rtlil.sigspec.init.bool");

	width_ = 0;
	hash_ = 0;
	append_bit(bit);
	check();
}

void RTLIL::SigSpec::pack() const
{
	RTLIL::SigSpec *that = (RTLIL::SigSpec*)this;

	if (that->bits_.empty())
		return;

	cover("kernel.rtlil.sigspec.convert.pack");
	log_assert(that->chunks_.empty());

	std::vector<RTLIL::SigBit> old_bits;
	old_bits.swap(that->bits_);

	RTLIL::SigChunk *last = NULL;
	int last_end_offset = 0;

	for (auto &bit : old_bits) {
		if (last && bit.wire == last->wire) {
			if (bit.wire == NULL) {
				last->data.push_back(bit.data);
				last->width++;
				continue;
			} else if (last_end_offset == bit.offset) {
				last_end_offset++;
				last->width++;
				continue;
			}
		}
		that->chunks_.push_back(bit);
		last = &that->chunks_.back();
		last_end_offset = bit.offset + 1;
	}

	check();
}

void RTLIL::SigSpec::unpack() const
{
	RTLIL::SigSpec *that = (RTLIL::SigSpec*)this;

	if (that->chunks_.empty())
		return;

	cover("kernel.rtlil.sigspec.convert.unpack");
	log_assert(that->bits_.empty());

	that->bits_.reserve(that->width_);
	for (auto &c : that->chunks_)
		for (int i = 0; i < c.width; i++)
			that->bits_.push_back(RTLIL::SigBit(c, i));

	that->chunks_.clear();
	that->hash_ = 0;
}

void RTLIL::SigSpec::updhash() const
{
	RTLIL::SigSpec *that = (RTLIL::SigSpec*)this;

	if (that->hash_ != 0)
		return;

	cover("kernel.rtlil.sigspec.hash");
	that->pack();

	that->hash_ = mkhash_init;
	for (auto &c : that->chunks_)
		if (c.wire == NULL) {
			for (auto &v : c.data)
				that->hash_ = mkhash(that->hash_, v);
		} else {
			that->hash_ = mkhash(that->hash_, c.wire->name.index_);
			that->hash_ = mkhash(that->hash_, c.offset);
			that->hash_ = mkhash(that->hash_, c.width);
		}

	if (that->hash_ == 0)
		that->hash_ = 1;
}

void RTLIL::SigSpec::sort()
{
	unpack();
	cover("kernel.rtlil.sigspec.sort");
	std::sort(bits_.begin(), bits_.end());
}

void RTLIL::SigSpec::sort_and_unify()
{
	unpack();
	cover("kernel.rtlil.sigspec.sort_and_unify");

	// A copy of the bits vector is used to prevent duplicating the logic from
	// SigSpec::SigSpec(std::vector<SigBit>).  This incurrs an extra copy but
	// that isn't showing up as significant in profiles.
	std::vector<SigBit> unique_bits = bits_;
	std::sort(unique_bits.begin(), unique_bits.end());
	auto last = std::unique(unique_bits.begin(), unique_bits.end());
	unique_bits.erase(last, unique_bits.end());

	*this = unique_bits;
}

void RTLIL::SigSpec::replace(const RTLIL::SigSpec &pattern, const RTLIL::SigSpec &with)
{
	replace(pattern, with, this);
}

void RTLIL::SigSpec::replace(const RTLIL::SigSpec &pattern, const RTLIL::SigSpec &with, RTLIL::SigSpec *other) const
{
	log_assert(other != NULL);
	log_assert(width_ == other->width_);
	log_assert(pattern.width_ == with.width_);

	pattern.unpack();
	with.unpack();
	unpack();
	other->unpack();

	for (int i = 0; i < GetSize(pattern.bits_); i++) {
		if (pattern.bits_[i].wire != NULL) {
			for (int j = 0; j < GetSize(bits_); j++) {
				if (bits_[j] == pattern.bits_[i]) {
					other->bits_[j] = with.bits_[i];
				}
			}
		}
	}

	other->check();
}

void RTLIL::SigSpec::replace(const dict<RTLIL::SigBit, RTLIL::SigBit> &rules)
{
	replace(rules, this);
}

void RTLIL::SigSpec::replace(const dict<RTLIL::SigBit, RTLIL::SigBit> &rules, RTLIL::SigSpec *other) const
{
	cover("kernel.rtlil.sigspec.replace_dict");

	log_assert(other != NULL);
	log_assert(width_ == other->width_);

	unpack();
	other->unpack();

	for (int i = 0; i < GetSize(bits_); i++) {
		auto it = rules.find(bits_[i]);
		if (it != rules.end())
			other->bits_[i] = it->second;
	}

	other->check();
}

void RTLIL::SigSpec::replace(const std::map<RTLIL::SigBit, RTLIL::SigBit> &rules)
{
	replace(rules, this);
}

void RTLIL::SigSpec::replace(const std::map<RTLIL::SigBit, RTLIL::SigBit> &rules, RTLIL::SigSpec *other) const
{
	cover("kernel.rtlil.sigspec.replace_map");

	log_assert(other != NULL);
	log_assert(width_ == other->width_);

	unpack();
	other->unpack();

	for (int i = 0; i < GetSize(bits_); i++) {
		auto it = rules.find(bits_[i]);
		if (it != rules.end())
			other->bits_[i] = it->second;
	}

	other->check();
}

void RTLIL::SigSpec::remove(const RTLIL::SigSpec &pattern)
{
	remove2(pattern, NULL);
}

void RTLIL::SigSpec::remove(const RTLIL::SigSpec &pattern, RTLIL::SigSpec *other) const
{
	RTLIL::SigSpec tmp = *this;
	tmp.remove2(pattern, other);
}

void RTLIL::SigSpec::remove2(const RTLIL::SigSpec &pattern, RTLIL::SigSpec *other)
{
	if (other)
		cover("kernel.rtlil.sigspec.remove_other");
	else
		cover("kernel.rtlil.sigspec.remove");

	unpack();
	if (other != NULL) {
		log_assert(width_ == other->width_);
		other->unpack();
	}

	for (int i = GetSize(bits_) - 1; i >= 0; i--)
	{
		if (bits_[i].wire == NULL) continue;

		for (auto &pattern_chunk : pattern.chunks())
			if (bits_[i].wire == pattern_chunk.wire &&
				bits_[i].offset >= pattern_chunk.offset &&
				bits_[i].offset < pattern_chunk.offset + pattern_chunk.width) {
				bits_.erase(bits_.begin() + i);
				width_--;
				if (other != NULL) {
					other->bits_.erase(other->bits_.begin() + i);
					other->width_--;
				}
				break;
			}
	}

	check();
}

void RTLIL::SigSpec::remove(const pool<RTLIL::SigBit> &pattern)
{
	remove2(pattern, NULL);
}

void RTLIL::SigSpec::remove(const pool<RTLIL::SigBit> &pattern, RTLIL::SigSpec *other) const
{
	RTLIL::SigSpec tmp = *this;
	tmp.remove2(pattern, other);
}

void RTLIL::SigSpec::remove2(const pool<RTLIL::SigBit> &pattern, RTLIL::SigSpec *other)
{
	if (other)
		cover("kernel.rtlil.sigspec.remove_other");
	else
		cover("kernel.rtlil.sigspec.remove");

	unpack();

	if (other != NULL) {
		log_assert(width_ == other->width_);
		other->unpack();
	}

	for (int i = GetSize(bits_) - 1; i >= 0; i--) {
		if (bits_[i].wire != NULL && pattern.count(bits_[i])) {
			bits_.erase(bits_.begin() + i);
			width_--;
			if (other != NULL) {
				other->bits_.erase(other->bits_.begin() + i);
				other->width_--;
			}
		}
	}

	check();
}

void RTLIL::SigSpec::remove2(const std::set<RTLIL::SigBit> &pattern, RTLIL::SigSpec *other)
{
	if (other)
		cover("kernel.rtlil.sigspec.remove_other");
	else
		cover("kernel.rtlil.sigspec.remove");

	unpack();

	if (other != NULL) {
		log_assert(width_ == other->width_);
		other->unpack();
	}

	for (int i = GetSize(bits_) - 1; i >= 0; i--) {
		if (bits_[i].wire != NULL && pattern.count(bits_[i])) {
			bits_.erase(bits_.begin() + i);
			width_--;
			if (other != NULL) {
				other->bits_.erase(other->bits_.begin() + i);
				other->width_--;
			}
		}
	}

	check();
}

RTLIL::SigSpec RTLIL::SigSpec::extract(const RTLIL::SigSpec &pattern, const RTLIL::SigSpec *other) const
{
	if (other)
		cover("kernel.rtlil.sigspec.extract_other");
	else
		cover("kernel.rtlil.sigspec.extract");

	log_assert(other == NULL || width_ == other->width_);

	RTLIL::SigSpec ret;
	std::vector<RTLIL::SigBit> bits_match = to_sigbit_vector();

	for (auto& pattern_chunk : pattern.chunks()) {
		if (other) {
			std::vector<RTLIL::SigBit> bits_other = other->to_sigbit_vector();
			for (int i = 0; i < width_; i++)
				if (bits_match[i].wire &&
					bits_match[i].wire == pattern_chunk.wire &&
					bits_match[i].offset >= pattern_chunk.offset &&
					bits_match[i].offset < pattern_chunk.offset + pattern_chunk.width)
					ret.append_bit(bits_other[i]);
		} else {
			for (int i = 0; i < width_; i++)
				if (bits_match[i].wire &&
					bits_match[i].wire == pattern_chunk.wire &&
					bits_match[i].offset >= pattern_chunk.offset &&
					bits_match[i].offset < pattern_chunk.offset + pattern_chunk.width)
					ret.append_bit(bits_match[i]);
		}
	}

	ret.check();
	return ret;
}

RTLIL::SigSpec RTLIL::SigSpec::extract(const pool<RTLIL::SigBit> &pattern, const RTLIL::SigSpec *other) const
{
	if (other)
		cover("kernel.rtlil.sigspec.extract_other");
	else
		cover("kernel.rtlil.sigspec.extract");

	log_assert(other == NULL || width_ == other->width_);

	std::vector<RTLIL::SigBit> bits_match = to_sigbit_vector();
	RTLIL::SigSpec ret;

	if (other) {
		std::vector<RTLIL::SigBit> bits_other = other->to_sigbit_vector();
		for (int i = 0; i < width_; i++)
			if (bits_match[i].wire && pattern.count(bits_match[i]))
				ret.append_bit(bits_other[i]);
	} else {
		for (int i = 0; i < width_; i++)
			if (bits_match[i].wire && pattern.count(bits_match[i]))
				ret.append_bit(bits_match[i]);
	}

	ret.check();
	return ret;
}

void RTLIL::SigSpec::replace(int offset, const RTLIL::SigSpec &with)
{
	cover("kernel.rtlil.sigspec.replace_pos");

	unpack();
	with.unpack();

	log_assert(offset >= 0);
	log_assert(with.width_ >= 0);
	log_assert(offset+with.width_ <= width_);

	for (int i = 0; i < with.width_; i++)
		bits_.at(offset + i) = with.bits_.at(i);

	check();
}

void RTLIL::SigSpec::remove_const()
{
	if (packed())
	{
		cover("kernel.rtlil.sigspec.remove_const.packed");

		std::vector<RTLIL::SigChunk> new_chunks;
		new_chunks.reserve(GetSize(chunks_));

		width_ = 0;
		for (auto &chunk : chunks_)
			if (chunk.wire != NULL) {
				new_chunks.push_back(chunk);
				width_ += chunk.width;
			}

		chunks_.swap(new_chunks);
	}
	else
	{
		cover("kernel.rtlil.sigspec.remove_const.unpacked");

		std::vector<RTLIL::SigBit> new_bits;
		new_bits.reserve(width_);

		for (auto &bit : bits_)
			if (bit.wire != NULL)
				new_bits.push_back(bit);

		bits_.swap(new_bits);
		width_ = bits_.size();
	}

	check();
}

void RTLIL::SigSpec::remove(int offset, int length)
{
	cover("kernel.rtlil.sigspec.remove_pos");

	unpack();

	log_assert(offset >= 0);
	log_assert(length >= 0);
	log_assert(offset + length <= width_);

	bits_.erase(bits_.begin() + offset, bits_.begin() + offset + length);
	width_ = bits_.size();

	check();
}

RTLIL::SigSpec RTLIL::SigSpec::extract(int offset, int length) const
{
	unpack();
	cover("kernel.rtlil.sigspec.extract_pos");
	return std::vector<RTLIL::SigBit>(bits_.begin() + offset, bits_.begin() + offset + length);
}

void RTLIL::SigSpec::append(const RTLIL::SigSpec &signal)
{
	if (signal.width_ == 0)
		return;

	if (width_ == 0) {
		*this = signal;
		return;
	}

	cover("kernel.rtlil.sigspec.append");

	if (packed() != signal.packed()) {
		pack();
		signal.pack();
	}

	if (packed())
		for (auto &other_c : signal.chunks_)
		{
			auto &my_last_c = chunks_.back();
			if (my_last_c.wire == NULL && other_c.wire == NULL) {
				auto &this_data = my_last_c.data;
				auto &other_data = other_c.data;
				this_data.insert(this_data.end(), other_data.begin(), other_data.end());
				my_last_c.width += other_c.width;
			} else
			if (my_last_c.wire == other_c.wire && my_last_c.offset + my_last_c.width == other_c.offset) {
				my_last_c.width += other_c.width;
			} else
				chunks_.push_back(other_c);
		}
	else
		bits_.insert(bits_.end(), signal.bits_.begin(), signal.bits_.end());

	width_ += signal.width_;
	check();
}

void RTLIL::SigSpec::append_bit(const RTLIL::SigBit &bit)
{
	if (packed())
	{
		cover("kernel.rtlil.sigspec.append_bit.packed");

		if (chunks_.size() == 0)
			chunks_.push_back(bit);
		else
			if (bit.wire == NULL)
				if (chunks_.back().wire == NULL) {
					chunks_.back().data.push_back(bit.data);
					chunks_.back().width++;
				} else
					chunks_.push_back(bit);
			else
				if (chunks_.back().wire == bit.wire && chunks_.back().offset + chunks_.back().width == bit.offset)
					chunks_.back().width++;
				else
					chunks_.push_back(bit);
	}
	else
	{
		cover("kernel.rtlil.sigspec.append_bit.unpacked");
		bits_.push_back(bit);
	}

	width_++;
	check();
}

void RTLIL::SigSpec::extend_u0(int width, bool is_signed)
{
	cover("kernel.rtlil.sigspec.extend_u0");

	pack();

	if (width_ > width)
		remove(width, width_ - width);

	if (width_ < width) {
		RTLIL::SigBit padding = width_ > 0 ? (*this)[width_ - 1] : RTLIL::State::Sx;
		if (!is_signed)
			padding = RTLIL::State::S0;
		while (width_ < width)
			append(padding);
	}

}

RTLIL::SigSpec RTLIL::SigSpec::repeat(int num) const
{
	cover("kernel.rtlil.sigspec.repeat");

	RTLIL::SigSpec sig;
	for (int i = 0; i < num; i++)
		sig.append(*this);
	return sig;
}

#ifndef NDEBUG
void RTLIL::SigSpec::check() const
{
	if (width_ > 64)
	{
		cover("kernel.rtlil.sigspec.check.skip");
	}
	else if (packed())
	{
		cover("kernel.rtlil.sigspec.check.packed");

		int w = 0;
		for (size_t i = 0; i < chunks_.size(); i++) {
			const RTLIL::SigChunk chunk = chunks_[i];
			if (chunk.wire == NULL) {
				if (i > 0)
					log_assert(chunks_[i-1].wire != NULL);
				log_assert(chunk.offset == 0);
				log_assert(chunk.data.size() == (size_t)chunk.width);
			} else {
				if (i > 0 && chunks_[i-1].wire == chunk.wire)
					log_assert(chunk.offset != chunks_[i-1].offset + chunks_[i-1].width);
				log_assert(chunk.offset >= 0);
				log_assert(chunk.width >= 0);
				log_assert(chunk.offset + chunk.width <= chunk.wire->width);
				log_assert(chunk.data.size() == 0);
			}
			w += chunk.width;
		}
		log_assert(w == width_);
		log_assert(bits_.empty());
	}
	else
	{
		cover("kernel.rtlil.sigspec.check.unpacked");

		log_assert(width_ == GetSize(bits_));
		log_assert(chunks_.empty());
	}
}
#endif

bool RTLIL::SigSpec::operator <(const RTLIL::SigSpec &other) const
{
	cover("kernel.rtlil.sigspec.comp_lt");

	if (this == &other)
		return false;

	if (width_ != other.width_)
		return width_ < other.width_;

	pack();
	other.pack();

	if (chunks_.size() != other.chunks_.size())
		return chunks_.size() < other.chunks_.size();

	updhash();
	other.updhash();

	if (hash_ != other.hash_)
		return hash_ < other.hash_;

	for (size_t i = 0; i < chunks_.size(); i++)
		if (chunks_[i] != other.chunks_[i]) {
			cover("kernel.rtlil.sigspec.comp_lt.hash_collision");
			return chunks_[i] < other.chunks_[i];
		}

	cover("kernel.rtlil.sigspec.comp_lt.equal");
	return false;
}

bool RTLIL::SigSpec::operator ==(const RTLIL::SigSpec &other) const
{
	cover("kernel.rtlil.sigspec.comp_eq");

	if (this == &other)
		return true;

	if (width_ != other.width_)
		return false;

	pack();
	other.pack();

	if (chunks_.size() != other.chunks_.size())
		return false;

	updhash();
	other.updhash();

	if (hash_ != other.hash_)
		return false;

	for (size_t i = 0; i < chunks_.size(); i++)
		if (chunks_[i] != other.chunks_[i]) {
			cover("kernel.rtlil.sigspec.comp_eq.hash_collision");
			return false;
		}

	cover("kernel.rtlil.sigspec.comp_eq.equal");
	return true;
}

bool RTLIL::SigSpec::is_wire() const
{
	cover("kernel.rtlil.sigspec.is_wire");

	pack();
	return GetSize(chunks_) == 1 && chunks_[0].wire && chunks_[0].wire->width == width_;
}

bool RTLIL::SigSpec::is_chunk() const
{
	cover("kernel.rtlil.sigspec.is_chunk");

	pack();
	return GetSize(chunks_) == 1;
}

bool RTLIL::SigSpec::is_fully_const() const
{
	cover("kernel.rtlil.sigspec.is_fully_const");

	pack();
	for (auto it = chunks_.begin(); it != chunks_.end(); it++)
		if (it->width > 0 && it->wire != NULL)
			return false;
	return true;
}

bool RTLIL::SigSpec::is_fully_zero() const
{
	cover("kernel.rtlil.sigspec.is_fully_zero");

	pack();
	for (auto it = chunks_.begin(); it != chunks_.end(); it++) {
		if (it->width > 0 && it->wire != NULL)
			return false;
		for (size_t i = 0; i < it->data.size(); i++)
			if (it->data[i] != RTLIL::State::S0)
				return false;
	}
	return true;
}

bool RTLIL::SigSpec::is_fully_ones() const
{
	cover("kernel.rtlil.sigspec.is_fully_ones");

	pack();
	for (auto it = chunks_.begin(); it != chunks_.end(); it++) {
		if (it->width > 0 && it->wire != NULL)
			return false;
		for (size_t i = 0; i < it->data.size(); i++)
			if (it->data[i] != RTLIL::State::S1)
				return false;
	}
	return true;
}

bool RTLIL::SigSpec::is_fully_def() const
{
	cover("kernel.rtlil.sigspec.is_fully_def");

	pack();
	for (auto it = chunks_.begin(); it != chunks_.end(); it++) {
		if (it->width > 0 && it->wire != NULL)
			return false;
		for (size_t i = 0; i < it->data.size(); i++)
			if (it->data[i] != RTLIL::State::S0 && it->data[i] != RTLIL::State::S1)
				return false;
	}
	return true;
}

bool RTLIL::SigSpec::is_fully_undef() const
{
	cover("kernel.rtlil.sigspec.is_fully_undef");

	pack();
	for (auto it = chunks_.begin(); it != chunks_.end(); it++) {
		if (it->width > 0 && it->wire != NULL)
			return false;
		for (size_t i = 0; i < it->data.size(); i++)
			if (it->data[i] != RTLIL::State::Sx && it->data[i] != RTLIL::State::Sz)
				return false;
	}
	return true;
}

bool RTLIL::SigSpec::has_const() const
{
	cover("kernel.rtlil.sigspec.has_const");

	pack();
	for (auto it = chunks_.begin(); it != chunks_.end(); it++)
		if (it->width > 0 && it->wire == NULL)
			return true;
	return false;
}

bool RTLIL::SigSpec::has_marked_bits() const
{
	cover("kernel.rtlil.sigspec.has_marked_bits");

	pack();
	for (auto it = chunks_.begin(); it != chunks_.end(); it++)
		if (it->width > 0 && it->wire == NULL) {
			for (size_t i = 0; i < it->data.size(); i++)
				if (it->data[i] == RTLIL::State::Sm)
					return true;
		}
	return false;
}

bool RTLIL::SigSpec::as_bool() const
{
	cover("kernel.rtlil.sigspec.as_bool");

	pack();
	log_assert(is_fully_const() && GetSize(chunks_) <= 1);
	if (width_)
		return RTLIL::Const(chunks_[0].data).as_bool();
	return false;
}

int RTLIL::SigSpec::as_int(bool is_signed) const
{
	cover("kernel.rtlil.sigspec.as_int");

	pack();
	log_assert(is_fully_const() && GetSize(chunks_) <= 1);
	if (width_)
		return RTLIL::Const(chunks_[0].data).as_int(is_signed);
	return 0;
}

std::string RTLIL::SigSpec::as_string() const
{
	cover("kernel.rtlil.sigspec.as_string");

	pack();
	std::string str;
	for (size_t i = chunks_.size(); i > 0; i--) {
		const RTLIL::SigChunk &chunk = chunks_[i-1];
		if (chunk.wire != NULL)
			for (int j = 0; j < chunk.width; j++)
				str += "?";
		else
			str += RTLIL::Const(chunk.data).as_string();
	}
	return str;
}

RTLIL::Const RTLIL::SigSpec::as_const() const
{
	cover("kernel.rtlil.sigspec.as_const");

	pack();
	log_assert(is_fully_const() && GetSize(chunks_) <= 1);
	if (width_)
		return chunks_[0].data;
	return RTLIL::Const();
}

RTLIL::Wire *RTLIL::SigSpec::as_wire() const
{
	cover("kernel.rtlil.sigspec.as_wire");

	pack();
	log_assert(is_wire());
	return chunks_[0].wire;
}

RTLIL::SigChunk RTLIL::SigSpec::as_chunk() const
{
	cover("kernel.rtlil.sigspec.as_chunk");

	pack();
	log_assert(is_chunk());
	return chunks_[0];
}

RTLIL::SigBit RTLIL::SigSpec::as_bit() const
{
	cover("kernel.rtlil.sigspec.as_bit");

	log_assert(width_ == 1);
	if (packed())
		return RTLIL::SigBit(*chunks_.begin());
	else
		return bits_[0];
}

bool RTLIL::SigSpec::match(std::string pattern) const
{
	cover("kernel.rtlil.sigspec.match");

	pack();
	std::string str = as_string();
	log_assert(pattern.size() == str.size());

	for (size_t i = 0; i < pattern.size(); i++) {
		if (pattern[i] == ' ')
			continue;
		if (pattern[i] == '*') {
			if (str[i] != 'z' && str[i] != 'x')
				return false;
			continue;
		}
		if (pattern[i] != str[i])
			return false;
	}

	return true;
}

std::set<RTLIL::SigBit> RTLIL::SigSpec::to_sigbit_set() const
{
	cover("kernel.rtlil.sigspec.to_sigbit_set");

	pack();
	std::set<RTLIL::SigBit> sigbits;
	for (auto &c : chunks_)
		for (int i = 0; i < c.width; i++)
			sigbits.insert(RTLIL::SigBit(c, i));
	return sigbits;
}

pool<RTLIL::SigBit> RTLIL::SigSpec::to_sigbit_pool() const
{
	cover("kernel.rtlil.sigspec.to_sigbit_pool");

	pack();
	pool<RTLIL::SigBit> sigbits;
	for (auto &c : chunks_)
		for (int i = 0; i < c.width; i++)
			sigbits.insert(RTLIL::SigBit(c, i));
	return sigbits;
}

std::vector<RTLIL::SigBit> RTLIL::SigSpec::to_sigbit_vector() const
{
	cover("kernel.rtlil.sigspec.to_sigbit_vector");

	unpack();
	return bits_;
}

std::map<RTLIL::SigBit, RTLIL::SigBit> RTLIL::SigSpec::to_sigbit_map(const RTLIL::SigSpec &other) const
{
	cover("kernel.rtlil.sigspec.to_sigbit_map");

	unpack();
	other.unpack();

	log_assert(width_ == other.width_);

	std::map<RTLIL::SigBit, RTLIL::SigBit> new_map;
	for (int i = 0; i < width_; i++)
		new_map[bits_[i]] = other.bits_[i];

	return new_map;
}

dict<RTLIL::SigBit, RTLIL::SigBit> RTLIL::SigSpec::to_sigbit_dict(const RTLIL::SigSpec &other) const
{
	cover("kernel.rtlil.sigspec.to_sigbit_dict");

	unpack();
	other.unpack();

	log_assert(width_ == other.width_);

	dict<RTLIL::SigBit, RTLIL::SigBit> new_map;
	for (int i = 0; i < width_; i++)
		new_map[bits_[i]] = other.bits_[i];

	return new_map;
}

static void sigspec_parse_split(std::vector<std::string> &tokens, const std::string &text, char sep)
{
	size_t start = 0, end = 0;
	while ((end = text.find(sep, start)) != std::string::npos) {
		tokens.push_back(text.substr(start, end - start));
		start = end + 1;
	}
	tokens.push_back(text.substr(start));
}

static int sigspec_parse_get_dummy_line_num()
{
	return 0;
}

bool RTLIL::SigSpec::parse(RTLIL::SigSpec &sig, RTLIL::Module *module, std::string str)
{
	cover("kernel.rtlil.sigspec.parse");

	AST::current_filename = "input";
	AST::use_internal_line_num();
	AST::set_line_num(0);

	std::vector<std::string> tokens;
	sigspec_parse_split(tokens, str, ',');

	sig = RTLIL::SigSpec();
	for (int tokidx = int(tokens.size())-1; tokidx >= 0; tokidx--)
	{
		std::string netname = tokens[tokidx];
		std::string indices;

		if (netname.size() == 0)
			continue;

		if (('0' <= netname[0] && netname[0] <= '9') || netname[0] == '\'') {
			cover("kernel.rtlil.sigspec.parse.const");
			AST::get_line_num = sigspec_parse_get_dummy_line_num;
			AST::AstNode *ast = VERILOG_FRONTEND::const2ast(netname);
			if (ast == NULL)
				return false;
			sig.append(RTLIL::Const(ast->bits));
			delete ast;
			continue;
		}

		if (module == NULL)
			return false;

		cover("kernel.rtlil.sigspec.parse.net");

		if (netname[0] != '$' && netname[0] != '\\')
			netname = "\\" + netname;

		if (module->wires_.count(netname) == 0) {
			size_t indices_pos = netname.size()-1;
			if (indices_pos > 2 && netname[indices_pos] == ']')
			{
				indices_pos--;
				while (indices_pos > 0 && ('0' <= netname[indices_pos] && netname[indices_pos] <= '9')) indices_pos--;
				if (indices_pos > 0 && netname[indices_pos] == ':') {
					indices_pos--;
					while (indices_pos > 0 && ('0' <= netname[indices_pos] && netname[indices_pos] <= '9')) indices_pos--;
				}
				if (indices_pos > 0 && netname[indices_pos] == '[') {
					indices = netname.substr(indices_pos);
					netname = netname.substr(0, indices_pos);
				}
			}
		}

		if (module->wires_.count(netname) == 0)
			return false;

		RTLIL::Wire *wire = module->wires_.at(netname);
		if (!indices.empty()) {
			std::vector<std::string> index_tokens;
			sigspec_parse_split(index_tokens, indices.substr(1, indices.size()-2), ':');
			if (index_tokens.size() == 1) {
				cover("kernel.rtlil.sigspec.parse.bit_sel");
				int a = atoi(index_tokens.at(0).c_str());
				if (a < 0 || a >= wire->width)
					return false;
				sig.append(RTLIL::SigSpec(wire, a));
			} else {
				cover("kernel.rtlil.sigspec.parse.part_sel");
				int a = atoi(index_tokens.at(0).c_str());
				int b = atoi(index_tokens.at(1).c_str());
				if (a > b) {
					int tmp = a;
					a = b, b = tmp;
				}
				if (a < 0 || a >= wire->width)
					return false;
				if (b < 0 || b >= wire->width)
					return false;
				sig.append(RTLIL::SigSpec(wire, a, b-a+1));
			}
		} else
			sig.append(wire);
	}

	return true;
}

bool RTLIL::SigSpec::parse_sel(RTLIL::SigSpec &sig, RTLIL::Design *design, RTLIL::Module *module, std::string str)
{
	if (str.empty() || str[0] != '@')
		return parse(sig, module, str);

	cover("kernel.rtlil.sigspec.parse.sel");

	str = RTLIL::escape_id(str.substr(1));
	if (design->selection_vars.count(str) == 0)
		return false;

	sig = RTLIL::SigSpec();
	RTLIL::Selection &sel = design->selection_vars.at(str);
	for (auto &it : module->wires_)
		if (sel.selected_member(module->name, it.first))
			sig.append(it.second);

	return true;
}

bool RTLIL::SigSpec::parse_rhs(const RTLIL::SigSpec &lhs, RTLIL::SigSpec &sig, RTLIL::Module *module, std::string str)
{
	if (str == "0") {
		cover("kernel.rtlil.sigspec.parse.rhs_zeros");
		sig = RTLIL::SigSpec(RTLIL::State::S0, lhs.width_);
		return true;
	}

	if (str == "~0") {
		cover("kernel.rtlil.sigspec.parse.rhs_ones");
		sig = RTLIL::SigSpec(RTLIL::State::S1, lhs.width_);
		return true;
	}

	if (lhs.chunks_.size() == 1) {
		char *p = (char*)str.c_str(), *endptr;
		long int val = strtol(p, &endptr, 10);
		if (endptr && endptr != p && *endptr == 0) {
			sig = RTLIL::SigSpec(val, lhs.width_);
			cover("kernel.rtlil.sigspec.parse.rhs_dec");
			return true;
		}
	}

	return parse(sig, module, str);
}

RTLIL::CaseRule::~CaseRule()
{
	for (auto it = switches.begin(); it != switches.end(); it++)
		delete *it;
}

bool RTLIL::CaseRule::empty() const
{
	return actions.empty() && switches.empty();
}

RTLIL::CaseRule *RTLIL::CaseRule::clone() const
{
	RTLIL::CaseRule *new_caserule = new RTLIL::CaseRule;
	new_caserule->compare = compare;
	new_caserule->actions = actions;
	for (auto &it : switches)
		new_caserule->switches.push_back(it->clone());
	return new_caserule;
}

RTLIL::SwitchRule::~SwitchRule()
{
	for (auto it = cases.begin(); it != cases.end(); it++)
		delete *it;
}

bool RTLIL::SwitchRule::empty() const
{
	return cases.empty();
}

RTLIL::SwitchRule *RTLIL::SwitchRule::clone() const
{
	RTLIL::SwitchRule *new_switchrule = new RTLIL::SwitchRule;
	new_switchrule->signal = signal;
	new_switchrule->attributes = attributes;
	for (auto &it : cases)
		new_switchrule->cases.push_back(it->clone());
	return new_switchrule;

}

RTLIL::SyncRule *RTLIL::SyncRule::clone() const
{
	RTLIL::SyncRule *new_syncrule = new RTLIL::SyncRule;
	new_syncrule->type = type;
	new_syncrule->signal = signal;
	new_syncrule->actions = actions;
	return new_syncrule;
}

RTLIL::Process::~Process()
{
	for (auto it = syncs.begin(); it != syncs.end(); it++)
		delete *it;
}

RTLIL::Process *RTLIL::Process::clone() const
{
	RTLIL::Process *new_proc = new RTLIL::Process;

	new_proc->name = name;
	new_proc->attributes = attributes;

	RTLIL::CaseRule *rc_ptr = root_case.clone();
	new_proc->root_case = *rc_ptr;
	rc_ptr->switches.clear();
	delete rc_ptr;

	for (auto &it : syncs)
		new_proc->syncs.push_back(it->clone());

	return new_proc;
}

#ifdef WITH_PYTHON
RTLIL::Memory::~Memory()
{
	RTLIL::Memory::get_all_memorys()->erase(hashidx_);
}
static std::map<unsigned int, RTLIL::Memory*> all_memorys;
std::map<unsigned int, RTLIL::Memory*> *RTLIL::Memory::get_all_memorys(void)
{
	return &all_memorys;
}
#endif
YOSYS_NAMESPACE_END