diff options
Diffstat (limited to 'passes')
-rw-r--r-- | passes/opt/opt_expr.cc | 30 | ||||
-rw-r--r-- | passes/pmgen/.gitignore | 2 | ||||
-rw-r--r-- | passes/pmgen/Makefile.inc | 29 | ||||
-rw-r--r-- | passes/pmgen/README.md | 162 | ||||
-rw-r--r-- | passes/pmgen/ice40_dsp.pmg | 1 | ||||
-rw-r--r-- | passes/pmgen/peepopt_muldiv.pmg | 2 | ||||
-rw-r--r-- | passes/pmgen/peepopt_shiftmul.pmg | 4 | ||||
-rw-r--r-- | passes/pmgen/pmgen.py | 359 | ||||
-rw-r--r-- | passes/pmgen/test_pmgen.cc | 379 | ||||
-rw-r--r-- | passes/pmgen/test_pmgen.pmg | 189 | ||||
-rw-r--r-- | passes/sat/async2sync.cc | 37 | ||||
-rw-r--r-- | passes/sat/sat.cc | 2 | ||||
-rw-r--r-- | passes/techmap/Makefile.inc | 1 | ||||
-rw-r--r-- | passes/techmap/abc9.cc | 123 | ||||
-rw-r--r-- | passes/techmap/clkbufmap.cc | 298 | ||||
-rw-r--r-- | passes/techmap/iopadmap.cc | 58 | ||||
-rw-r--r-- | passes/techmap/techmap.cc | 10 |
17 files changed, 1508 insertions, 178 deletions
diff --git a/passes/opt/opt_expr.cc b/passes/opt/opt_expr.cc index 858b3560c..00d7d6063 100644 --- a/passes/opt/opt_expr.cc +++ b/passes/opt/opt_expr.cc @@ -369,7 +369,7 @@ void replace_const_cells(RTLIL::Design *design, RTLIL::Module *module, bool cons for (auto cell : module->cells()) if (design->selected(module, cell) && cell->type[0] == '$') { if (cell->type.in(ID($_NOT_), ID($not), ID($logic_not)) && - cell->getPort(ID::A).size() == 1 && cell->getPort(ID::Y).size() == 1) + GetSize(cell->getPort(ID::A)) == 1 && GetSize(cell->getPort(ID::Y)) == 1) invert_map[assign_map(cell->getPort(ID::Y))] = assign_map(cell->getPort(ID::A)); if (cell->type.in(ID($mux), ID($_MUX_)) && cell->getPort(ID::A) == SigSpec(State::S1) && cell->getPort(ID::B) == SigSpec(State::S0)) @@ -740,12 +740,34 @@ void replace_const_cells(RTLIL::Design *design, RTLIL::Module *module, bool cons if (cell->type.in(ID($reduce_xor), ID($reduce_xnor), ID($lt), ID($le), ID($ge), ID($gt))) replace_cell(assign_map, module, cell, "x-bit in input", ID::Y, RTLIL::State::Sx); else - replace_cell(assign_map, module, cell, "x-bit in input", ID::Y, RTLIL::SigSpec(RTLIL::State::Sx, cell->getPort(ID::Y).size())); + replace_cell(assign_map, module, cell, "x-bit in input", ID::Y, RTLIL::SigSpec(RTLIL::State::Sx, GetSize(cell->getPort(ID::Y)))); goto next_cell; } } - if (cell->type.in(ID($_NOT_), ID($not), ID($logic_not)) && cell->getPort(ID::Y).size() == 1 && + if (cell->type.in(ID($shiftx), ID($shift))) { + SigSpec sig_a = assign_map(cell->getPort(ID::A)); + int width; + bool trim_x = cell->type == ID($shiftx) || !keepdc; + bool trim_0 = cell->type == ID($shift); + for (width = GetSize(sig_a); width > 1; width--) { + if ((trim_x && sig_a[width-1] == State::Sx) || + (trim_0 && sig_a[width-1] == State::S0)) + continue; + break; + } + + if (width < GetSize(sig_a)) { + cover_list("opt.opt_expr.trim", "$shiftx", "$shift", cell->type.str()); + sig_a.remove(width, GetSize(sig_a)-width); + cell->setPort(ID::A, sig_a); + cell->setParam(ID(A_WIDTH), width); + did_something = true; + goto next_cell; + } + } + + if (cell->type.in(ID($_NOT_), ID($not), ID($logic_not)) && GetSize(cell->getPort(ID::Y)) == 1 && invert_map.count(assign_map(cell->getPort(ID::A))) != 0) { cover_list("opt.opt_expr.invert.double", "$_NOT_", "$not", "$logic_not", cell->type.str()); replace_cell(assign_map, module, cell, "double_invert", ID::Y, invert_map.at(assign_map(cell->getPort(ID::A)))); @@ -1142,7 +1164,7 @@ void replace_const_cells(RTLIL::Design *design, RTLIL::Module *module, bool cons if (mux_undef && cell->type.in(ID($mux), ID($pmux))) { RTLIL::SigSpec new_a, new_b, new_s; - int width = cell->getPort(ID::A).size(); + int width = GetSize(cell->getPort(ID::A)); if ((cell->getPort(ID::A).is_fully_undef() && cell->getPort(ID::B).is_fully_undef()) || cell->getPort(ID(S)).is_fully_undef()) { cover_list("opt.opt_expr.mux_undef", "$mux", "$pmux", cell->type.str()); diff --git a/passes/pmgen/.gitignore b/passes/pmgen/.gitignore index e52f3282f..6b319b8c3 100644 --- a/passes/pmgen/.gitignore +++ b/passes/pmgen/.gitignore @@ -1 +1 @@ -/*_pm.h +/*_pm.h
\ No newline at end of file diff --git a/passes/pmgen/Makefile.inc b/passes/pmgen/Makefile.inc index c03606152..8e0cbdca8 100644 --- a/passes/pmgen/Makefile.inc +++ b/passes/pmgen/Makefile.inc @@ -1,30 +1,29 @@ -OBJS += passes/pmgen/ice40_dsp.o -OBJS += passes/pmgen/ice40_wrapcarry.o -OBJS += passes/pmgen/peepopt.o +%_pm.h: passes/pmgen/pmgen.py %.pmg + $(P) mkdir -p passes/pmgen && python3 $< -o $@ -p $(subst _pm.h,,$(notdir $@)) $(filter-out $<,$^) # -------------------------------------- -passes/pmgen/ice40_dsp.o: passes/pmgen/ice40_dsp_pm.h -EXTRA_OBJS += passes/pmgen/ice40_dsp_pm.h -.SECONDARY: passes/pmgen/ice40_dsp_pm.h +OBJS += passes/pmgen/test_pmgen.o +passes/pmgen/test_pmgen.o: passes/pmgen/test_pmgen_pm.h passes/pmgen/ice40_dsp_pm.h passes/pmgen/peepopt_pm.h +$(eval $(call add_extra_objs,passes/pmgen/test_pmgen_pm.h)) -passes/pmgen/ice40_dsp_pm.h: passes/pmgen/pmgen.py passes/pmgen/ice40_dsp.pmg - $(P) mkdir -p passes/pmgen && python3 $< -o $@ -p ice40_dsp $(filter-out $<,$^) +# -------------------------------------- + +OBJS += passes/pmgen/ice40_dsp.o +passes/pmgen/ice40_dsp.o: passes/pmgen/ice40_dsp_pm.h +$(eval $(call add_extra_objs,passes/pmgen/ice40_dsp_pm.h)) # -------------------------------------- +OBJS += passes/pmgen/ice40_wrapcarry.o passes/pmgen/ice40_wrapcarry.o: passes/pmgen/ice40_wrapcarry_pm.h -EXTRA_OBJS += passes/pmgen/ice40_wrapcarry_pm.h -.SECONDARY: passes/pmgen/ice40_wrapcarry_pm.h - -passes/pmgen/ice40_wrapcarry_pm.h: passes/pmgen/pmgen.py passes/pmgen/ice40_wrapcarry.pmg - $(P) mkdir -p passes/pmgen && python3 $< -o $@ -p ice40_wrapcarry $(filter-out $<,$^) +$(eval $(call add_extra_objs,passes/pmgen/ice40_wrapcarry_pm.h)) # -------------------------------------- +OBJS += passes/pmgen/peepopt.o passes/pmgen/peepopt.o: passes/pmgen/peepopt_pm.h -EXTRA_OBJS += passes/pmgen/peepopt_pm.h -.SECONDARY: passes/pmgen/peepopt_pm.h +$(eval $(call add_extra_objs,passes/pmgen/peepopt_pm.h)) PEEPOPT_PATTERN = passes/pmgen/peepopt_shiftmul.pmg PEEPOPT_PATTERN += passes/pmgen/peepopt_muldiv.pmg diff --git a/passes/pmgen/README.md b/passes/pmgen/README.md index 2f0b1fd5a..0856c9ba3 100644 --- a/passes/pmgen/README.md +++ b/passes/pmgen/README.md @@ -45,9 +45,9 @@ of type `foobar_pm::state_<pattern_name>_t`.) Similarly the `.pmg` file declares user data variables that become members of `.ud_<pattern_name>`, a struct of type `foobar_pm::udata_<pattern_name>_t`. -There are four versions of the `run_<pattern_name>()` method: Without callback, -callback without arguments, callback with reference to `pm`, and callback with -reference to `pm.st_<pattern_name>`. +There are three versions of the `run_<pattern_name>()` method: Without callback, +callback without arguments, and callback with reference to `pm`. All versions +of the `run_<pattern_name>()` method return the number of found matches. The .pmg File Format @@ -118,8 +118,8 @@ write matchers: connected to any of the given signal bits, plus one if any of the signal bits is also a primary input or primary output. -- In `code..endcode` blocks there exist `accept`, `reject`, and `branch` - statements. +- In `code..endcode` blocks there exist `accept`, `reject`, `branch`, + `finish`, and `subpattern` statements. - In `index` statements there is a special `===` operator for the index lookup. @@ -175,6 +175,48 @@ explore the case where `mul` is set to `nullptr`. Without the `optional` statement a match may only be assigned nullptr when one of the `if` expressions evaluates to `false`. +The `semioptional` statement marks matches that must match if at least one +matching cell exists, but if no matching cell exists it is set to `nullptr`. + +Slices and choices +------------------ + +Cell matches can contain "slices" and "choices". Slices can be used to +create matches for different sections of a cell. For example: + + state <int> pmux_slice + + match pmux + select pmux->type == $pmux + slice idx GetSize(port(pmux, \S)) + index <SigBit> port(pmux, \S)[idx] === port(eq, \Y) + set pmux_slice idx + endmatch + +The first argument to `slice` is the local variable name used to identify the +slice. The second argument is the number of slices that should be created for +this cell. The `set` statement can be used to copy that index into a state +variable so that later matches and/or code blocks can refer to it. + +A similar mechanism is "choices", where a list of options is given as +second argument, and the matcher will iterate over those options: + + state <SigSpec> foo bar + state <IdString> eq_ab eq_ba + + match eq + select eq->type == $eq + choice <IdString> AB {\A, \B} + define <IdString> BA (AB == \A ? \B : \A) + index <SigSpec> port(eq, AB) === foo + index <SigSpec> port(eq, BA) === bar + set eq_ab AB + set eq_ba BA + generate + +Notice how `define` can be used to define additional local variables similar +to the loop variables defined by `slice` and `choice`. + Additional code --------------- @@ -232,5 +274,111 @@ But in some cases it is more natural to utilize the implicit branch statement: portAB = \B; endcode -There is an implicit `code..endcode` block at the end of each `.pmg` file -that just accepts everything that gets all the way there. +There is an implicit `code..endcode` block at the end of each (sub)pattern +that just rejects. + +A `code..finally..endcode` block executes the code after `finally` during +back-tracking. This is useful for maintaining user data state or printing +debug messages. For example: + + udata <vector<Cell*>> stack + + code + stack.push_back(addAB); + ... + finally + stack.pop_back(); + endcode + +`accept` and `finish` statements can be used inside the `finally` section, +but not `reject`, `branch`, or `subpattern`. + +Declaring a subpattern +---------------------- + +A subpattern starts with a line containing the `subpattern` keyword followed +by the name of the subpattern. Subpatterns can be called from a `code` block +using a `subpattern(<subpattern_name>);` C statement. + +Arguments may be passed to subpattern via state variables. The `subpattern` +line must be followed by a `arg <arg1> <arg2> ...` line that lists the +state variables used to pass arguments. + + state <IdString> foobar_type + state <bool> foobar_state + + code foobar_type foobar_state + foobar_state = false; + foobar_type = $add; + subpattern(foo); + foobar_type = $sub; + subpattern(bar); + endcode + + subpattern foo + arg foobar_type foobar_state + + match addsub + index <IdString> addsub->type === foobar_type + ... + endmatch + + code + if (foobar_state) { + subpattern(tail); + } else { + foobar_state = true; + subpattern(bar); + } + endcode + + subpattern bar + arg foobar_type foobar_state + + match addsub + index <IdString> addsub->type === foobar_type + ... + endmatch + + code + if (foobar_state) { + subpattern(tail); + } else { + foobar_state = true; + subpattern(foo); + } + endcode + + subpattern tail + ... + +Subpatterns cann be called recursively. + +If a `subpattern` statement is preceded by a `fallthrough` statement, this is +equivalent to calling the subpattern at the end of the preceding block. + +Generate Blocks +--------------- + +Match blocks may contain an optional `generate` section that is used for automatic +test-case generation. For example: + + match mul + ... + generate 10 0 + SigSpec Y = port(ff, \D); + SigSpec A = module->addWire(NEW_ID, GetSize(Y) - rng(GetSize(Y)/2)); + SigSpec B = module->addWire(NEW_ID, GetSize(Y) - rng(GetSize(Y)/2)); + module->addMul(NEW_ID, A, B, Y, rng(2)); + endmatch + +The expression `rng(n)` returns a non-negative integer less than `n`. + +The first argument to `generate` is the chance of this generate block being +executed when the match block did not match anything, in percent. + +The second argument to `generate` is the chance of this generate block being +executed when the match block did match something, in percent. + +The special statement `finish` can be used within generate blocks to terminate +the current pattern matcher run. diff --git a/passes/pmgen/ice40_dsp.pmg b/passes/pmgen/ice40_dsp.pmg index 1f3590d4e..7003092bb 100644 --- a/passes/pmgen/ice40_dsp.pmg +++ b/passes/pmgen/ice40_dsp.pmg @@ -159,4 +159,5 @@ code clock clock_pol clock_vld clock_pol = cp; clock_vld = true; } + accept; endcode diff --git a/passes/pmgen/peepopt_muldiv.pmg b/passes/pmgen/peepopt_muldiv.pmg index 06c275834..7cad759d0 100644 --- a/passes/pmgen/peepopt_muldiv.pmg +++ b/passes/pmgen/peepopt_muldiv.pmg @@ -32,5 +32,5 @@ code log("muldiv pattern in %s: mul=%s, div=%s\n", log_id(module), log_id(mul), log_id(div)); module->connect(div_y, val_y); autoremove(div); - reject; + accept; endcode diff --git a/passes/pmgen/peepopt_shiftmul.pmg b/passes/pmgen/peepopt_shiftmul.pmg index 6adab4e5f..d4748ae19 100644 --- a/passes/pmgen/peepopt_shiftmul.pmg +++ b/passes/pmgen/peepopt_shiftmul.pmg @@ -34,6 +34,7 @@ match mul endmatch code +{ IdString const_factor_port = port(mul, \A).is_fully_const() ? \A : \B; IdString const_factor_signed = const_factor_port == \A ? \A_SIGNED : \B_SIGNED; Const const_factor_cnst = port(mul, const_factor_port).as_const(); @@ -90,5 +91,6 @@ code shift->setParam(\B_WIDTH, GetSize(new_b)); blacklist(shift); - reject; + accept; +} endcode diff --git a/passes/pmgen/pmgen.py b/passes/pmgen/pmgen.py index 81052afce..573722d68 100644 --- a/passes/pmgen/pmgen.py +++ b/passes/pmgen/pmgen.py @@ -38,7 +38,10 @@ for a in args: assert prefix is not None current_pattern = None +current_subpattern = None patterns = dict() +subpatterns = dict() +subpattern_args = dict() state_types = dict() udata_types = dict() blocks = list() @@ -104,9 +107,12 @@ def rewrite_cpp(s): return "".join(t) -def process_pmgfile(f): +def process_pmgfile(f, filename): + linenr = 0 global current_pattern + global current_subpattern while True: + linenr += 1 line = f.readline() if line == "": break line = line.strip() @@ -119,19 +125,52 @@ def process_pmgfile(f): if current_pattern is not None: block = dict() block["type"] = "final" - block["pattern"] = current_pattern + block["pattern"] = (current_pattern, current_subpattern) blocks.append(block) line = line.split() assert len(line) == 2 assert line[1] not in patterns current_pattern = line[1] + current_subpattern = "" patterns[current_pattern] = len(blocks) + subpatterns[(current_pattern, current_subpattern)] = len(blocks) + subpattern_args[(current_pattern, current_subpattern)] = list() state_types[current_pattern] = dict() udata_types[current_pattern] = dict() continue assert current_pattern is not None + if cmd == "fallthrough": + block = dict() + block["type"] = "fallthrough" + blocks.append(block) + line = line.split() + assert len(line) == 1 + continue + + if cmd == "subpattern": + if len(blocks) == 0 or blocks[-1]["type"] != "fallthrough": + block = dict() + block["type"] = "final" + block["pattern"] = (current_pattern, current_subpattern) + blocks.append(block) + elif len(blocks) and blocks[-1]["type"] == "fallthrough": + del blocks[-1] + line = line.split() + assert len(line) == 2 + current_subpattern = line[1] + subpattern_args[(current_pattern, current_subpattern)] = list() + assert (current_pattern, current_subpattern) not in subpatterns + subpatterns[(current_pattern, current_subpattern)] = len(blocks) + continue + + if cmd == "arg": + line = line.split() + assert len(line) > 1 + subpattern_args[(current_pattern, current_subpattern)] += line[1:] + continue + if cmd == "state": m = re.match(r"^state\s+<(.*?)>\s+(([A-Za-z_][A-Za-z_0-9]*\s+)*[A-Za-z_][A-Za-z_0-9]*)\s*$", line) assert m @@ -155,21 +194,28 @@ def process_pmgfile(f): if cmd == "match": block = dict() block["type"] = "match" - block["pattern"] = current_pattern + block["src"] = "%s:%d" % (filename, linenr) + block["pattern"] = (current_pattern, current_subpattern) + + block["genargs"] = None + block["gencode"] = None line = line.split() assert len(line) == 2 - assert line[1] not in state_types[current_pattern] + assert (line[1] not in state_types[current_pattern]) or (state_types[current_pattern][line[1]] == "Cell*") block["cell"] = line[1] state_types[current_pattern][line[1]] = "Cell*"; block["if"] = list() - block["select"] = list() + block["setup"] = list() block["index"] = list() block["filter"] = list() + block["sets"] = list() block["optional"] = False + block["semioptional"] = False while True: + linenr += 1 l = f.readline() assert l != "" a = l.split() @@ -183,7 +229,22 @@ def process_pmgfile(f): if a[0] == "select": b = l.lstrip()[6:] - block["select"].append(rewrite_cpp(b.strip())) + block["setup"].append(("select", rewrite_cpp(b.strip()))) + continue + + if a[0] == "slice": + m = re.match(r"^\s*slice\s+(\S+)\s+(.*?)\s*$", l) + block["setup"].append(("slice", m.group(1), rewrite_cpp(m.group(2)))) + continue + + if a[0] == "choice": + m = re.match(r"^\s*choice\s+<(.*?)>\s+(\S+)\s+(.*?)\s*$", l) + block["setup"].append(("choice", m.group(1), m.group(2), rewrite_cpp(m.group(3)))) + continue + + if a[0] == "define": + m = re.match(r"^\s*define\s+<(.*?)>\s+(\S+)\s+(.*?)\s*$", l) + block["setup"].append(("define", m.group(1), m.group(2), rewrite_cpp(m.group(3)))) continue if a[0] == "index": @@ -197,35 +258,71 @@ def process_pmgfile(f): block["filter"].append(rewrite_cpp(b.strip())) continue + if a[0] == "set": + m = re.match(r"^\s*set\s+(\S+)\s+(.*?)\s*$", l) + block["sets"].append((m.group(1), rewrite_cpp(m.group(2)))) + continue + if a[0] == "optional": block["optional"] = True continue + if a[0] == "semioptional": + block["semioptional"] = True + continue + + if a[0] == "generate": + block["genargs"] = list([int(s) for s in a[1:]]) + if len(block["genargs"]) == 0: block["genargs"].append(100) + if len(block["genargs"]) == 1: block["genargs"].append(0) + assert len(block["genargs"]) == 2 + block["gencode"] = list() + while True: + linenr += 1 + l = f.readline() + assert l != "" + a = l.split() + if len(a) == 1 and a[0] == "endmatch": break + block["gencode"].append(rewrite_cpp(l.rstrip())) + break + assert False + if block["optional"]: + assert not block["semioptional"] + blocks.append(block) continue if cmd == "code": block = dict() block["type"] = "code" - block["pattern"] = current_pattern + block["src"] = "%s:%d" % (filename, linenr) + block["pattern"] = (current_pattern, current_subpattern) block["code"] = list() + block["fcode"] = list() block["states"] = set() for s in line.split()[1:]: assert s in state_types[current_pattern] block["states"].add(s) + codetype = "code" + while True: + linenr += 1 l = f.readline() assert l != "" a = l.split() if len(a) == 0: continue if a[0] == "endcode": break - block["code"].append(rewrite_cpp(l.rstrip())) + if a[0] == "finally": + codetype = "fcode" + continue + + block[codetype].append(rewrite_cpp(l.rstrip())) blocks.append(block) continue @@ -234,15 +331,16 @@ def process_pmgfile(f): for fn in pmgfiles: with open(fn, "r") as f: - process_pmgfile(f) + process_pmgfile(f, fn) if current_pattern is not None: block = dict() block["type"] = "final" - block["pattern"] = current_pattern + block["pattern"] = (current_pattern, current_subpattern) blocks.append(block) current_pattern = None +current_subpattern = None if debug: pp.pprint(blocks) @@ -262,7 +360,18 @@ with open(outfile, "w") as f: print("struct {}_pm {{".format(prefix), file=f) print(" Module *module;", file=f) print(" SigMap sigmap;", file=f) - print(" std::function<void()> on_accept;".format(prefix), file=f) + print(" std::function<void()> on_accept;", file=f) + print(" bool generate_mode;", file=f) + print(" int accept_cnt;", file=f) + print("", file=f) + + print(" uint32_t rngseed;", file=f) + print(" int rng(unsigned int n) {", file=f) + print(" rngseed ^= rngseed << 13;", file=f) + print(" rngseed ^= rngseed >> 17;", file=f) + print(" rngseed ^= rngseed << 5;", file=f) + print(" return rngseed % n;", file=f) + print(" }", file=f) print("", file=f) for index in range(len(blocks)): @@ -271,12 +380,21 @@ with open(outfile, "w") as f: index_types = list() for entry in block["index"]: index_types.append(entry[0]) + value_types = ["Cell*"] + for entry in block["setup"]: + if entry[0] == "slice": + value_types.append("int") + if entry[0] == "choice": + value_types.append(entry[1]) + if entry[0] == "define": + value_types.append(entry[1]) print(" typedef std::tuple<{}> index_{}_key_type;".format(", ".join(index_types), index), file=f) - print(" dict<index_{}_key_type, vector<Cell*>> index_{};".format(index, index), file=f) + print(" typedef std::tuple<{}> index_{}_value_type;".format(", ".join(value_types), index), file=f) + print(" dict<index_{}_key_type, vector<index_{}_value_type>> index_{};".format(index, index, index), file=f) print(" dict<SigBit, pool<Cell*>> sigusers;", file=f) print(" pool<Cell*> blacklist_cells;", file=f) print(" pool<Cell*> autoremove_cells;", file=f) - print(" bool blacklist_dirty;", file=f) + print(" dict<Cell*,int> rollback_cache;", file=f) print(" int rollback;", file=f) print("", file=f) @@ -304,47 +422,30 @@ with open(outfile, "w") as f: print(" void add_siguser(const SigSpec &sig, Cell *cell) {", file=f) print(" for (auto bit : sigmap(sig)) {", file=f) print(" if (bit.wire == nullptr) continue;", file=f) - print(" if (sigusers.count(bit) == 0 && bit.wire->port_id)", file=f) - print(" sigusers[bit].insert(nullptr);", file=f) print(" sigusers[bit].insert(cell);", file=f) print(" }", file=f) print(" }", file=f) print("", file=f) print(" void blacklist(Cell *cell) {", file=f) - print(" if (cell != nullptr) {", file=f) - print(" if (blacklist_cells.insert(cell).second)", file=f) - print(" blacklist_dirty = true;", file=f) + print(" if (cell != nullptr && blacklist_cells.insert(cell).second) {", file=f) + print(" auto ptr = rollback_cache.find(cell);", file=f) + print(" if (ptr == rollback_cache.end()) return;", file=f) + print(" int rb = ptr->second;", file=f) + print(" if (rollback == 0 || rollback > rb)", file=f) + print(" rollback = rb;", file=f) print(" }", file=f) print(" }", file=f) print("", file=f) print(" void autoremove(Cell *cell) {", file=f) print(" if (cell != nullptr) {", file=f) - print(" if (blacklist_cells.insert(cell).second)", file=f) - print(" blacklist_dirty = true;", file=f) print(" autoremove_cells.insert(cell);", file=f) + print(" blacklist(cell);", file=f) print(" }", file=f) print(" }", file=f) print("", file=f) - for current_pattern in sorted(patterns.keys()): - print(" void check_blacklist_{}() {{".format(current_pattern), file=f) - print(" if (!blacklist_dirty)", file=f) - print(" return;", file=f) - print(" blacklist_dirty = false;", file=f) - for index in range(len(blocks)): - block = blocks[index] - if block["pattern"] != current_pattern: - continue - if block["type"] == "match": - print(" if (st_{}.{} != nullptr && blacklist_cells.count(st_{}.{})) {{".format(current_pattern, block["cell"], current_pattern, block["cell"]), file=f) - print(" rollback = {};".format(index+1), file=f) - print(" return;", file=f) - print(" }", file=f) - print(" rollback = 0;", file=f) - print(" }", file=f) - print("", file=f) current_pattern = None print(" SigSpec port(Cell *cell, IdString portname) {", file=f) @@ -367,7 +468,7 @@ with open(outfile, "w") as f: print("", file=f) print(" {}_pm(Module *module, const vector<Cell*> &cells) :".format(prefix), file=f) - print(" module(module), sigmap(module) {", file=f) + print(" module(module), sigmap(module), generate_mode(false), rngseed(12345678) {", file=f) for current_pattern in sorted(patterns.keys()): for s, t in sorted(udata_types[current_pattern].items()): if t.endswith("*"): @@ -375,10 +476,11 @@ with open(outfile, "w") as f: else: print(" ud_{}.{} = {}();".format(current_pattern, s, t), file=f) current_pattern = None - print(" for (auto cell : module->cells()) {", file=f) + print(" for (auto port : module->ports)", file=f) + print(" add_siguser(module->wire(port), nullptr);", file=f) + print(" for (auto cell : module->cells())", file=f) print(" for (auto &conn : cell->connections())", file=f) print(" add_siguser(conn.second, cell);", file=f) - print(" }", file=f) print(" for (auto cell : cells) {", file=f) for index in range(len(blocks)): @@ -386,12 +488,34 @@ with open(outfile, "w") as f: if block["type"] == "match": print(" do {", file=f) print(" Cell *{} = cell;".format(block["cell"]), file=f) - for expr in block["select"]: - print(" if (!({})) break;".format(expr), file=f) + print(" index_{}_value_type value;".format(index), file=f) + print(" std::get<0>(value) = cell;", file=f) + loopcnt = 0 + valueidx = 1 + for item in block["setup"]: + if item[0] == "select": + print(" if (!({})) continue;".format(item[1]), file=f) + if item[0] == "slice": + print(" int &{} = std::get<{}>(value);".format(item[1], valueidx), file=f) + print(" for ({} = 0; {} < {}; {}++) {{".format(item[1], item[1], item[2], item[1]), file=f) + valueidx += 1 + loopcnt += 1 + if item[0] == "choice": + print(" vector<{}> _pmg_choices_{} = {};".format(item[1], item[2], item[3]), file=f) + print(" for (const {} &{} : _pmg_choices_{}) {{".format(item[1], item[2], item[2]), file=f) + print(" std::get<{}>(value) = {};".format(valueidx, item[2]), file=f) + valueidx += 1 + loopcnt += 1 + if item[0] == "define": + print(" {} &{} = std::get<{}>(value);".format(item[1], item[2], valueidx), file=f) + print(" {} = {};".format(item[2], item[3]), file=f) + valueidx += 1 print(" index_{}_key_type key;".format(index), file=f) for field, entry in enumerate(block["index"]): print(" std::get<{}>(key) = {};".format(field, entry[1]), file=f) - print(" index_{}[key].push_back(cell);".format(index), file=f) + print(" index_{}[key].push_back(value);".format(index), file=f) + for i in range(loopcnt): + print(" }", file=f) print(" } while (0);", file=f) print(" }", file=f) @@ -405,41 +529,47 @@ with open(outfile, "w") as f: print("", file=f) for current_pattern in sorted(patterns.keys()): - print(" void run_{}(std::function<void()> on_accept_f) {{".format(current_pattern), file=f) + print(" int run_{}(std::function<void()> on_accept_f) {{".format(current_pattern), file=f) + print(" accept_cnt = 0;", file=f) print(" on_accept = on_accept_f;", file=f) print(" rollback = 0;", file=f) - print(" blacklist_dirty = false;", file=f) for s, t in sorted(state_types[current_pattern].items()): if t.endswith("*"): print(" st_{}.{} = nullptr;".format(current_pattern, s), file=f) else: print(" st_{}.{} = {}();".format(current_pattern, s, t), file=f) - print(" block_{}();".format(patterns[current_pattern]), file=f) + print(" block_{}(1);".format(patterns[current_pattern]), file=f) + print(" log_assert(rollback_cache.empty());", file=f) + print(" return accept_cnt;", file=f) print(" }", file=f) print("", file=f) - print(" void run_{}(std::function<void({}_pm&)> on_accept_f) {{".format(current_pattern, prefix), file=f) - print(" run_{}([&](){{on_accept_f(*this);}});".format(current_pattern), file=f) + print(" int run_{}(std::function<void({}_pm&)> on_accept_f) {{".format(current_pattern, prefix), file=f) + print(" return run_{}([&](){{on_accept_f(*this);}});".format(current_pattern), file=f) print(" }", file=f) print("", file=f) - print(" void run_{}(std::function<void(state_{}_t&)> on_accept_f) {{".format(current_pattern, current_pattern), file=f) - print(" run_{}([&](){{on_accept_f(st_{});}});".format(current_pattern, current_pattern), file=f) + print(" int run_{}() {{".format(current_pattern), file=f) + print(" return run_{}([](){{}});".format(current_pattern, current_pattern), file=f) print(" }", file=f) print("", file=f) - print(" void run_{}() {{".format(current_pattern), file=f) - print(" run_{}([](){{}});".format(current_pattern, current_pattern), file=f) - print(" }", file=f) + + if len(subpatterns): + for p, s in sorted(subpatterns.keys()): + print(" void block_subpattern_{}_{}(int recursion) {{ block_{}(recursion); }}".format(p, s, subpatterns[(p, s)]), file=f) print("", file=f) + current_pattern = None + current_subpattern = None for index in range(len(blocks)): block = blocks[index] - print(" void block_{}() {{".format(index), file=f) - current_pattern = block["pattern"] + if block["type"] in ("match", "code"): + print(" // {}".format(block["src"]), file=f) + + print(" void block_{}(int recursion YS_ATTRIBUTE(unused)) {{".format(index), file=f) + current_pattern, current_subpattern = block["pattern"] if block["type"] == "final": - print(" on_accept();", file=f) - print(" check_blacklist_{}();".format(current_pattern), file=f) print(" }", file=f) if index+1 != len(blocks): print("", file=f) @@ -449,12 +579,17 @@ with open(outfile, "w") as f: nonconst_st = set() restore_st = set() - for i in range(patterns[current_pattern], index): + for s in subpattern_args[(current_pattern, current_subpattern)]: + const_st.add(s) + + for i in range(subpatterns[(current_pattern, current_subpattern)], index): if blocks[i]["type"] == "code": for s in blocks[i]["states"]: const_st.add(s) elif blocks[i]["type"] == "match": const_st.add(blocks[i]["cell"]) + for item in blocks[i]["sets"]: + const_st.add(item[0]) else: assert False @@ -468,6 +603,10 @@ with open(outfile, "w") as f: s = block["cell"] assert s not in const_st nonconst_st.add(s) + for item in block["sets"]: + if item[0] in const_st: + const_st.remove(item[0]) + nonconst_st.add(item[0]) else: assert False @@ -482,37 +621,55 @@ with open(outfile, "w") as f: t = state_types[current_pattern][s] print(" {} &{} YS_ATTRIBUTE(unused) = st_{}.{};".format(t, s, current_pattern, s), file=f) + for u in sorted(udata_types[current_pattern].keys()): + t = udata_types[current_pattern][u] + print(" {} &{} YS_ATTRIBUTE(unused) = ud_{}.{};".format(t, u, current_pattern, u), file=f) + if len(restore_st): print("", file=f) for s in sorted(restore_st): t = state_types[current_pattern][s] - print(" {} backup_{} = {};".format(t, s, s), file=f) + print(" {} _pmg_backup_{} = {};".format(t, s, s), file=f) if block["type"] == "code": print("", file=f) - print(" do {", file=f) - print("#define reject do {{ check_blacklist_{}(); goto rollback_label; }} while(0)".format(current_pattern), file=f) - print("#define accept do {{ on_accept(); check_blacklist_{}(); if (rollback) goto rollback_label; }} while(0)".format(current_pattern), file=f) - print("#define branch do {{ block_{}(); if (rollback) goto rollback_label; }} while(0)".format(index+1), file=f) + print("#define reject do { goto rollback_label; } while(0)", file=f) + print("#define accept do { accept_cnt++; on_accept(); if (rollback) goto rollback_label; } while(0)", file=f) + print("#define finish do { rollback = -1; goto rollback_label; } while(0)", file=f) + print("#define branch do {{ block_{}(recursion+1); if (rollback) goto rollback_label; }} while(0)".format(index+1), file=f) + print("#define subpattern(pattern_name) do {{ block_subpattern_{}_ ## pattern_name (recursion+1); if (rollback) goto rollback_label; }} while(0)".format(current_pattern), file=f) for line in block["code"]: - print(" " + line, file=f) + print(" " + line, file=f) print("", file=f) - print(" block_{}();".format(index+1), file=f) + print(" block_{}(recursion+1);".format(index+1), file=f) + print("#undef reject", file=f) print("#undef accept", file=f) + print("#undef finish", file=f) print("#undef branch", file=f) - print(" } while (0);", file=f) + print("#undef subpattern", file=f) + print("", file=f) print("rollback_label:", file=f) print(" YS_ATTRIBUTE(unused);", file=f) + if len(block["fcode"]): + print("#define accept do { accept_cnt++; on_accept(); } while(0)", file=f) + print("#define finish do { rollback = -1; goto finish_label; } while(0)", file=f) + for line in block["fcode"]: + print(" " + line, file=f) + print("finish_label:", file=f) + print(" YS_ATTRIBUTE(unused);", file=f) + print("#undef accept", file=f) + print("#undef finish", file=f) + if len(restore_st) or len(nonconst_st): print("", file=f) for s in sorted(restore_st): t = state_types[current_pattern][s] - print(" {} = backup_{};".format(s, s), file=f) + print(" {} = _pmg_backup_{};".format(s, s), file=f) for s in sorted(nonconst_st): if s not in restore_st: t = state_types[current_pattern][s] @@ -524,12 +681,15 @@ with open(outfile, "w") as f: elif block["type"] == "match": assert len(restore_st) == 0 + print(" Cell* _pmg_backup_{} = {};".format(block["cell"], block["cell"]), file=f) + if len(block["if"]): for expr in block["if"]: print("", file=f) print(" if (!({})) {{".format(expr), file=f) print(" {} = nullptr;".format(block["cell"]), file=f) - print(" block_{}();".format(index+1), file=f) + print(" block_{}(recursion+1);".format(index+1), file=f) + print(" {} = _pmg_backup_{};".format(block["cell"], block["cell"]), file=f) print(" return;", file=f) print(" }", file=f) @@ -537,21 +697,48 @@ with open(outfile, "w") as f: print(" index_{}_key_type key;".format(index), file=f) for field, entry in enumerate(block["index"]): print(" std::get<{}>(key) = {};".format(field, entry[2]), file=f) - print(" const vector<Cell*> &cells = index_{}[key];".format(index), file=f) + print(" auto cells_ptr = index_{}.find(key);".format(index), file=f) + + if block["semioptional"] or block["genargs"] is not None: + print(" bool found_any_match = false;", file=f) print("", file=f) - print(" for (int idx = 0; idx < GetSize(cells); idx++) {", file=f) - print(" {} = cells[idx];".format(block["cell"]), file=f) - print(" if (blacklist_cells.count({})) continue;".format(block["cell"]), file=f) + print(" if (cells_ptr != index_{}.end()) {{".format(index), file=f) + print(" const vector<index_{}_value_type> &cells = cells_ptr->second;".format(index), file=f) + print(" for (int _pmg_idx = 0; _pmg_idx < GetSize(cells); _pmg_idx++) {", file=f) + print(" {} = std::get<0>(cells[_pmg_idx]);".format(block["cell"]), file=f) + valueidx = 1 + for item in block["setup"]: + if item[0] == "slice": + print(" const int &{} YS_ATTRIBUTE(unused) = std::get<{}>(cells[_pmg_idx]);".format(item[1], valueidx), file=f) + valueidx += 1 + if item[0] == "choice": + print(" const {} &{} YS_ATTRIBUTE(unused) = std::get<{}>(cells[_pmg_idx]);".format(item[1], item[2], valueidx), file=f) + valueidx += 1 + if item[0] == "define": + print(" const {} &{} YS_ATTRIBUTE(unused) = std::get<{}>(cells[_pmg_idx]);".format(item[1], item[2], valueidx), file=f) + valueidx += 1 + print(" if (blacklist_cells.count({})) continue;".format(block["cell"]), file=f) for expr in block["filter"]: - print(" if (!({})) continue;".format(expr), file=f) - print(" block_{}();".format(index+1), file=f) - print(" if (rollback) {", file=f) - print(" if (rollback != {}) {{".format(index+1), file=f) - print(" {} = nullptr;".format(block["cell"]), file=f) - print(" return;", file=f) + print(" if (!({})) continue;".format(expr), file=f) + if block["semioptional"] or block["genargs"] is not None: + print(" found_any_match = true;", file=f) + for item in block["sets"]: + print(" auto _pmg_backup_{} = {};".format(item[0], item[0]), file=f) + print(" {} = {};".format(item[0], item[1]), file=f) + print(" auto rollback_ptr = rollback_cache.insert(make_pair(std::get<0>(cells[_pmg_idx]), recursion));", file=f) + print(" block_{}(recursion+1);".format(index+1), file=f) + for item in block["sets"]: + print(" {} = _pmg_backup_{};".format(item[0], item[0]), file=f) + print(" if (rollback_ptr.second)", file=f) + print(" rollback_cache.erase(rollback_ptr.first);", file=f) + print(" if (rollback) {", file=f) + print(" if (rollback != recursion) {{".format(index+1), file=f) + print(" {} = _pmg_backup_{};".format(block["cell"], block["cell"]), file=f) + print(" return;", file=f) + print(" }", file=f) + print(" rollback = 0;", file=f) print(" }", file=f) - print(" rollback = 0;", file=f) print(" }", file=f) print(" }", file=f) @@ -559,8 +746,20 @@ with open(outfile, "w") as f: print(" {} = nullptr;".format(block["cell"]), file=f) if block["optional"]: - print(" block_{}();".format(index+1), file=f) + print(" block_{}(recursion+1);".format(index+1), file=f) + if block["semioptional"]: + print(" if (!found_any_match) block_{}(recursion+1);".format(index+1), file=f) + + print(" {} = _pmg_backup_{};".format(block["cell"], block["cell"]), file=f) + + if block["genargs"] is not None: + print("#define finish do { rollback = -1; return; } while(0)", file=f) + print(" if (generate_mode && rng(100) < (found_any_match ? {} : {})) {{".format(block["genargs"][1], block["genargs"][0]), file=f) + for line in block["gencode"]: + print(" " + line, file=f) + print(" }", file=f) + print("#undef finish", file=f) else: assert False diff --git a/passes/pmgen/test_pmgen.cc b/passes/pmgen/test_pmgen.cc new file mode 100644 index 000000000..0ad769dfd --- /dev/null +++ b/passes/pmgen/test_pmgen.cc @@ -0,0 +1,379 @@ +/* + * 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/sigtools.h" + +USING_YOSYS_NAMESPACE +PRIVATE_NAMESPACE_BEGIN + +// for peepopt_pm +bool did_something; + +#include "passes/pmgen/test_pmgen_pm.h" +#include "passes/pmgen/ice40_dsp_pm.h" +#include "passes/pmgen/peepopt_pm.h" + +void reduce_chain(test_pmgen_pm &pm) +{ + auto &st = pm.st_reduce; + auto &ud = pm.ud_reduce; + + if (ud.longest_chain.empty()) + return; + + log("Found chain of length %d (%s):\n", GetSize(ud.longest_chain), log_id(st.first->type)); + + SigSpec A; + SigSpec Y = ud.longest_chain.front().first->getPort(ID(Y)); + auto last_cell = ud.longest_chain.back().first; + + for (auto it : ud.longest_chain) { + auto cell = it.first; + if (cell == last_cell) { + A.append(cell->getPort(ID(A))); + A.append(cell->getPort(ID(B))); + } else { + A.append(cell->getPort(it.second == ID(A) ? ID(B) : ID(A))); + } + log(" %s\n", log_id(cell)); + pm.autoremove(cell); + } + + Cell *c; + + if (last_cell->type == ID($_AND_)) + c = pm.module->addReduceAnd(NEW_ID, A, Y); + else if (last_cell->type == ID($_OR_)) + c = pm.module->addReduceOr(NEW_ID, A, Y); + else if (last_cell->type == ID($_XOR_)) + c = pm.module->addReduceXor(NEW_ID, A, Y); + else + log_abort(); + + log(" -> %s (%s)\n", log_id(c), log_id(c->type)); +} + +void reduce_tree(test_pmgen_pm &pm) +{ + auto &st = pm.st_reduce; + auto &ud = pm.ud_reduce; + + if (ud.longest_chain.empty()) + return; + + SigSpec A = ud.leaves; + SigSpec Y = st.first->getPort(ID(Y)); + pm.autoremove(st.first); + + log("Found %s tree with %d leaves for %s (%s).\n", log_id(st.first->type), + GetSize(A), log_signal(Y), log_id(st.first)); + + Cell *c; + + if (st.first->type == ID($_AND_)) + c = pm.module->addReduceAnd(NEW_ID, A, Y); + else if (st.first->type == ID($_OR_)) + c = pm.module->addReduceOr(NEW_ID, A, Y); + else if (st.first->type == ID($_XOR_)) + c = pm.module->addReduceXor(NEW_ID, A, Y); + else + log_abort(); + + log(" -> %s (%s)\n", log_id(c), log_id(c->type)); +} + +void opt_eqpmux(test_pmgen_pm &pm) +{ + auto &st = pm.st_eqpmux; + + SigSpec Y = st.pmux->getPort(ID::Y); + int width = GetSize(Y); + + SigSpec EQ = st.pmux->getPort(ID::B).extract(st.pmux_slice_eq*width, width); + SigSpec NE = st.pmux->getPort(ID::B).extract(st.pmux_slice_ne*width, width); + + log("Found eqpmux circuit driving %s (eq=%s, ne=%s, pmux=%s).\n", + log_signal(Y), log_id(st.eq), log_id(st.ne), log_id(st.pmux)); + + pm.autoremove(st.pmux); + Cell *c = pm.module->addMux(NEW_ID, NE, EQ, st.eq->getPort(ID::Y), Y); + log(" -> %s (%s)\n", log_id(c), log_id(c->type)); +} + +#define GENERATE_PATTERN(pmclass, pattern) \ + generate_pattern<pmclass>([](pmclass &pm, std::function<void()> f){ return pm.run_ ## pattern(f); }, #pmclass, #pattern, design) + +void pmtest_addports(Module *module) +{ + pool<SigBit> driven_bits, used_bits; + SigMap sigmap(module); + int icnt = 0, ocnt = 0; + + for (auto cell : module->cells()) + for (auto conn : cell->connections()) + { + if (cell->input(conn.first)) + for (auto bit : sigmap(conn.second)) + used_bits.insert(bit); + if (cell->output(conn.first)) + for (auto bit : sigmap(conn.second)) + driven_bits.insert(bit); + } + + for (auto wire : vector<Wire*>(module->wires())) + { + SigSpec ibits, obits; + for (auto bit : sigmap(wire)) { + if (!used_bits.count(bit)) + obits.append(bit); + if (!driven_bits.count(bit)) + ibits.append(bit); + } + if (!ibits.empty()) { + Wire *w = module->addWire(stringf("\\i%d", icnt++), GetSize(ibits)); + w->port_input = true; + module->connect(ibits, w); + } + if (!obits.empty()) { + Wire *w = module->addWire(stringf("\\o%d", ocnt++), GetSize(obits)); + w->port_output = true; + module->connect(w, obits); + } + } + + module->fixup_ports(); +} + +template <class pm> +void generate_pattern(std::function<void(pm&,std::function<void()>)> run, const char *pmclass, const char *pattern, Design *design) +{ + log("Generating \"%s\" patterns for pattern matcher \"%s\".\n", pattern, pmclass); + + int modcnt = 0; + int maxmodcnt = 100; + int maxsubcnt = 4; + int timeout = 0; + vector<Module*> mods; + + while (modcnt < maxmodcnt) + { + int submodcnt = 0, itercnt = 0, cellcnt = 0; + Module *mod = design->addModule(NEW_ID); + + while (modcnt < maxmodcnt && submodcnt < maxsubcnt && itercnt++ < 1000) + { + if (timeout++ > 10000) + log_error("pmgen generator is stuck: 10000 iterations an no matching module generated.\n"); + + pm matcher(mod, mod->cells()); + + matcher.rng(1); + matcher.rngseed += modcnt; + matcher.rng(1); + matcher.rngseed += submodcnt; + matcher.rng(1); + matcher.rngseed += itercnt; + matcher.rng(1); + matcher.rngseed += cellcnt; + matcher.rng(1); + + if (GetSize(mod->cells()) != cellcnt) + { + bool found_match = false; + run(matcher, [&](){ found_match = true; }); + cellcnt = GetSize(mod->cells()); + + if (found_match) { + Module *m = design->addModule(stringf("\\pmtest_%s_%s_%05d", + pmclass, pattern, modcnt++)); + log("Creating module %s with %d cells.\n", log_id(m), cellcnt); + mod->cloneInto(m); + pmtest_addports(m); + mods.push_back(m); + submodcnt++; + timeout = 0; + } + } + + matcher.generate_mode = true; + run(matcher, [](){}); + } + + if (submodcnt) + maxsubcnt *= 2; + + design->remove(mod); + } + + Module *m = design->addModule(stringf("\\pmtest_%s_%s", pmclass, pattern)); + log("Creating module %s with %d cells.\n", log_id(m), GetSize(mods)); + for (auto mod : mods) { + Cell *c = m->addCell(mod->name, mod->name); + for (auto port : mod->ports) { + Wire *w = m->addWire(NEW_ID, GetSize(mod->wire(port))); + c->setPort(port, w); + } + } + pmtest_addports(m); +} + +struct TestPmgenPass : public Pass { + TestPmgenPass() : Pass("test_pmgen", "test pass for pmgen") { } + void help() YS_OVERRIDE + { + // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| + log("\n"); + log(" test_pmgen -reduce_chain [options] [selection]\n"); + log("\n"); + log("Demo for recursive pmgen patterns. Map chains of AND/OR/XOR to $reduce_*.\n"); + log("\n"); + + log("\n"); + log(" test_pmgen -reduce_tree [options] [selection]\n"); + log("\n"); + log("Demo for recursive pmgen patterns. Map trees of AND/OR/XOR to $reduce_*.\n"); + log("\n"); + + log("\n"); + log(" test_pmgen -eqpmux [options] [selection]\n"); + log("\n"); + log("Demo for recursive pmgen patterns. Optimize EQ/NE/PMUX circuits.\n"); + log("\n"); + + log("\n"); + log(" test_pmgen -generate [options] <pattern_name>\n"); + log("\n"); + log("Create modules that match the specified pattern.\n"); + log("\n"); + } + + void execute_reduce_chain(std::vector<std::string> args, RTLIL::Design *design) + { + log_header(design, "Executing TEST_PMGEN pass (-reduce_chain).\n"); + + size_t argidx; + for (argidx = 2; argidx < args.size(); argidx++) + { + // if (args[argidx] == "-singleton") { + // singleton_mode = true; + // continue; + // } + break; + } + extra_args(args, argidx, design); + + for (auto module : design->selected_modules()) + while (test_pmgen_pm(module, module->selected_cells()).run_reduce(reduce_chain)) {} + } + + void execute_reduce_tree(std::vector<std::string> args, RTLIL::Design *design) + { + log_header(design, "Executing TEST_PMGEN pass (-reduce_tree).\n"); + + size_t argidx; + for (argidx = 2; argidx < args.size(); argidx++) + { + // if (args[argidx] == "-singleton") { + // singleton_mode = true; + // continue; + // } + break; + } + extra_args(args, argidx, design); + + for (auto module : design->selected_modules()) + test_pmgen_pm(module, module->selected_cells()).run_reduce(reduce_tree); + } + + void execute_eqpmux(std::vector<std::string> args, RTLIL::Design *design) + { + log_header(design, "Executing TEST_PMGEN pass (-eqpmux).\n"); + + size_t argidx; + for (argidx = 2; argidx < args.size(); argidx++) + { + // if (args[argidx] == "-singleton") { + // singleton_mode = true; + // continue; + // } + break; + } + extra_args(args, argidx, design); + + for (auto module : design->selected_modules()) + test_pmgen_pm(module, module->selected_cells()).run_eqpmux(opt_eqpmux); + } + + void execute_generate(std::vector<std::string> args, RTLIL::Design *design) + { + log_header(design, "Executing TEST_PMGEN pass (-generate).\n"); + + size_t argidx; + for (argidx = 2; argidx < args.size(); argidx++) + { + // if (args[argidx] == "-singleton") { + // singleton_mode = true; + // continue; + // } + break; + } + + if (argidx+1 != args.size()) + log_cmd_error("Expected exactly one pattern.\n"); + + string pattern = args[argidx]; + + if (pattern == "reduce") + return GENERATE_PATTERN(test_pmgen_pm, reduce); + + if (pattern == "eqpmux") + return GENERATE_PATTERN(test_pmgen_pm, eqpmux); + + if (pattern == "ice40_dsp") + return GENERATE_PATTERN(ice40_dsp_pm, ice40_dsp); + + if (pattern == "peepopt-muldiv") + return GENERATE_PATTERN(peepopt_pm, muldiv); + + if (pattern == "peepopt-shiftmul") + return GENERATE_PATTERN(peepopt_pm, shiftmul); + + log_cmd_error("Unkown pattern: %s\n", pattern.c_str()); + } + + void execute(std::vector<std::string> args, RTLIL::Design *design) YS_OVERRIDE + { + if (GetSize(args) > 1) + { + if (args[1] == "-reduce_chain") + return execute_reduce_chain(args, design); + if (args[1] == "-reduce_tree") + return execute_reduce_tree(args, design); + if (args[1] == "-eqpmux") + return execute_eqpmux(args, design); + if (args[1] == "-generate") + return execute_generate(args, design); + } + help(); + log_cmd_error("Missing or unsupported mode parameter.\n"); + } +} TestPmgenPass; + +PRIVATE_NAMESPACE_END diff --git a/passes/pmgen/test_pmgen.pmg b/passes/pmgen/test_pmgen.pmg new file mode 100644 index 000000000..287ed97d8 --- /dev/null +++ b/passes/pmgen/test_pmgen.pmg @@ -0,0 +1,189 @@ +pattern reduce + +state <IdString> portname +udata <vector<pair<Cell*, IdString>>> chain longest_chain +udata <pool<Cell*>> non_first_cells +udata <SigSpec> leaves + +code + non_first_cells.clear(); + subpattern(setup); +endcode + +match first + select first->type.in($_AND_, $_OR_, $_XOR_) + filter !non_first_cells.count(first) +generate + SigSpec A = module->addWire(NEW_ID); + SigSpec B = module->addWire(NEW_ID); + SigSpec Y = module->addWire(NEW_ID); + switch (rng(3)) + { + case 0: + module->addAndGate(NEW_ID, A, B, Y); + break; + case 1: + module->addOrGate(NEW_ID, A, B, Y); + break; + case 2: + module->addXorGate(NEW_ID, A, B, Y); + break; + } +endmatch + +code + leaves = SigSpec(); + longest_chain.clear(); + chain.push_back(make_pair(first, \A)); + subpattern(tail); + chain.back().second = \B; + subpattern(tail); +finally + chain.pop_back(); + log_assert(chain.empty()); + if (GetSize(longest_chain) > 1) + accept; +endcode + +// ------------------------------------------------------------------ + +subpattern setup + +match first + select first->type.in($_AND_, $_OR_, $_XOR_) +endmatch + +code portname + portname = \A; + branch; + portname = \B; +endcode + +match next + select next->type.in($_AND_, $_OR_, $_XOR_) + select nusers(port(next, \Y)) == 2 + index <IdString> next->type === first->type + index <SigSpec> port(next, \Y) === port(first, portname) +endmatch + +code + non_first_cells.insert(next); +endcode + +// ------------------------------------------------------------------ + +subpattern tail +arg first + +match next + semioptional + select next->type.in($_AND_, $_OR_, $_XOR_) + select nusers(port(next, \Y)) == 2 + index <IdString> next->type === chain.back().first->type + index <SigSpec> port(next, \Y) === port(chain.back().first, chain.back().second) +generate 10 + SigSpec A = module->addWire(NEW_ID); + SigSpec B = module->addWire(NEW_ID); + SigSpec Y = port(chain.back().first, chain.back().second); + Cell *c = module->addAndGate(NEW_ID, A, B, Y); + c->type = chain.back().first->type; +endmatch + +code + if (next) { + chain.push_back(make_pair(next, \A)); + subpattern(tail); + chain.back().second = \B; + subpattern(tail); + } else { + if (GetSize(chain) > GetSize(longest_chain)) + longest_chain = chain; + leaves.append(port(chain.back().first, chain.back().second)); + } +finally + if (next) + chain.pop_back(); +endcode + +// ================================================================== + +pattern eqpmux + +state <bool> eq_ne_signed +state <SigSpec> eq_inA eq_inB +state <int> pmux_slice_eq pmux_slice_ne + +match eq + select eq->type == $eq + choice <IdString> AB {\A, \B} + define <IdString> BA AB == \A ? \B : \A + set eq_inA port(eq, \A) + set eq_inB port(eq, \B) + set eq_ne_signed param(eq, \A_SIGNED).as_bool() +generate 100 10 + SigSpec A = module->addWire(NEW_ID, rng(7)+1); + SigSpec B = module->addWire(NEW_ID, rng(7)+1); + SigSpec Y = module->addWire(NEW_ID); + module->addEq(NEW_ID, A, B, Y, rng(2)); +endmatch + +match pmux + select pmux->type == $pmux + slice idx GetSize(port(pmux, \S)) + index <SigBit> port(pmux, \S)[idx] === port(eq, \Y) + set pmux_slice_eq idx +generate 100 10 + int width = rng(7) + 1; + int numsel = rng(4) + 1; + int idx = rng(numsel); + + SigSpec A = module->addWire(NEW_ID, width); + SigSpec Y = module->addWire(NEW_ID, width); + + SigSpec B, S; + for (int i = 0; i < numsel; i++) { + B.append(module->addWire(NEW_ID, width)); + S.append(i == idx ? port(eq, \Y) : module->addWire(NEW_ID)); + } + + module->addPmux(NEW_ID, A, B, S, Y); +endmatch + +match ne + select ne->type == $ne + choice <IdString> AB {\A, \B} + define <IdString> BA (AB == \A ? \B : \A) + index <SigSpec> port(ne, AB) === eq_inA + index <SigSpec> port(ne, BA) === eq_inB + index <int> param(ne, \A_SIGNED).as_bool() === eq_ne_signed +generate 100 10 + SigSpec A = eq_inA, B = eq_inB, Y; + if (rng(2)) { + std::swap(A, B); + } + if (rng(2)) { + for (auto bit : port(pmux, \S)) { + if (nusers(bit) < 2) + Y.append(bit); + } + if (GetSize(Y)) + Y = Y[rng(GetSize(Y))]; + else + Y = module->addWire(NEW_ID); + } else { + Y = module->addWire(NEW_ID); + } + module->addNe(NEW_ID, A, B, Y, rng(2)); +endmatch + +match pmux2 + select pmux2->type == $pmux + slice idx GetSize(port(pmux2, \S)) + index <Cell*> pmux2 === pmux + index <SigBit> port(pmux2, \S)[idx] === port(ne, \Y) + set pmux_slice_ne idx +endmatch + +code + accept; +endcode diff --git a/passes/sat/async2sync.cc b/passes/sat/async2sync.cc index d045d0dcb..24ae6e448 100644 --- a/passes/sat/async2sync.cc +++ b/passes/sat/async2sync.cc @@ -39,7 +39,7 @@ struct Async2syncPass : public Pass { log("reset value in the next cycle regardless of the data-in value at the time of\n"); log("the clock edge.\n"); log("\n"); - log("Currently only $adff and $dffsr cells are supported by this pass.\n"); + log("Currently only $adff, $dffsr, and $dlatch cells are supported by this pass.\n"); log("\n"); } void execute(std::vector<std::string> args, RTLIL::Design *design) YS_OVERRIDE @@ -169,6 +169,41 @@ struct Async2syncPass : public Pass { cell->type = "$dff"; continue; } + + if (cell->type.in("$dlatch")) + { + bool en_pol = cell->parameters["\\EN_POLARITY"].as_bool(); + + SigSpec sig_en = cell->getPort("\\EN"); + SigSpec sig_d = cell->getPort("\\D"); + SigSpec sig_q = cell->getPort("\\Q"); + + log("Replacing %s.%s (%s): EN=%s, D=%s, Q=%s\n", + log_id(module), log_id(cell), log_id(cell->type), + log_signal(sig_en), log_signal(sig_d), log_signal(sig_q)); + + Const init_val; + for (int i = 0; i < GetSize(sig_q); i++) { + SigBit bit = sigmap(sig_q[i]); + init_val.bits.push_back(initbits.count(bit) ? initbits.at(bit) : State::Sx); + del_initbits.insert(bit); + } + + Wire *new_q = module->addWire(NEW_ID, GetSize(sig_q)); + new_q->attributes["\\init"] = init_val; + + if (en_pol) { + module->addMux(NEW_ID, new_q, sig_d, sig_en, sig_q); + } else { + module->addMux(NEW_ID, sig_d, new_q, sig_en, sig_q); + } + + cell->setPort("\\Q", new_q); + cell->unsetPort("\\EN"); + cell->unsetParam("\\EN_POLARITY"); + cell->type = "$ff"; + continue; + } } for (auto wire : module->wires()) diff --git a/passes/sat/sat.cc b/passes/sat/sat.cc index dd56d8c71..430bba1e8 100644 --- a/passes/sat/sat.cc +++ b/passes/sat/sat.cc @@ -268,7 +268,7 @@ struct SatHelper RTLIL::SigSpec removed_bits; for (int i = 0; i < lhs.size(); i++) { RTLIL::SigSpec bit = lhs.extract(i, 1); - if (!satgen.initial_state.check_all(bit)) { + if (rhs[i] == State::Sx || !satgen.initial_state.check_all(bit)) { removed_bits.append(bit); lhs.remove(i, 1); rhs.remove(i, 1); diff --git a/passes/techmap/Makefile.inc b/passes/techmap/Makefile.inc index 56f05eca4..631a80aa5 100644 --- a/passes/techmap/Makefile.inc +++ b/passes/techmap/Makefile.inc @@ -16,6 +16,7 @@ endif ifneq ($(SMALL),1) OBJS += passes/techmap/iopadmap.o +OBJS += passes/techmap/clkbufmap.o OBJS += passes/techmap/hilomap.o OBJS += passes/techmap/extract.o OBJS += passes/techmap/extract_fa.o diff --git a/passes/techmap/abc9.cc b/passes/techmap/abc9.cc index c1d4fff2d..84cb2c04f 100644 --- a/passes/techmap/abc9.cc +++ b/passes/techmap/abc9.cc @@ -76,12 +76,11 @@ inline std::string remap_name(RTLIL::IdString abc_name) return stringf("$abc$%d$%s", map_autoidx, abc_name.c_str()+1); } -void handle_loops(RTLIL::Design *design) +void handle_loops(RTLIL::Design *design, + const dict<IdString,pool<IdString>> &scc_break_inputs) { Pass::call(design, "scc -set_attr abc_scc_id {}"); - dict<IdString, vector<IdString>> abc_scc_break; - // For every unique SCC found, (arbitrarily) find the first // cell in the component, and select (and mark) all its output // wires @@ -116,44 +115,29 @@ void handle_loops(RTLIL::Design *design) cell->attributes.erase(it); } - auto jt = abc_scc_break.find(cell->type); - if (jt == abc_scc_break.end()) { - std::vector<IdString> ports; - RTLIL::Module* box_module = design->module(cell->type); - if (box_module) { - auto ports_csv = box_module->attributes.at(ID(abc_scc_break), RTLIL::Const::from_string("")).decode_string(); - for (const auto &port_name : split_tokens(ports_csv, ",")) { - auto port_id = RTLIL::escape_id(port_name); - auto kt = cell->connections_.find(port_id); - if (kt == cell->connections_.end()) - log_error("abc_scc_break attribute value '%s' does not exist as port on module '%s'\n", port_name.c_str(), log_id(box_module)); - ports.push_back(port_id); - } - } - jt = abc_scc_break.insert(std::make_pair(cell->type, std::move(ports))).first; - } - - for (auto port_name : jt->second) { - RTLIL::SigSpec sig; - auto &rhs = cell->connections_.at(port_name); - for (auto b : rhs) { - Wire *w = b.wire; - if (!w) continue; - w->port_output = true; - w->set_bool_attribute(ID(abc_scc_break)); - w = module->wire(stringf("%s.abci", w->name.c_str())); - if (!w) { - w = module->addWire(stringf("%s.abci", b.wire->name.c_str()), GetSize(b.wire)); - w->port_input = true; - } - else { - log_assert(b.offset < GetSize(w)); - log_assert(w->port_input); + auto jt = scc_break_inputs.find(cell->type); + if (jt != scc_break_inputs.end()) + for (auto port_name : jt->second) { + RTLIL::SigSpec sig; + auto &rhs = cell->connections_.at(port_name); + for (auto b : rhs) { + Wire *w = b.wire; + if (!w) continue; + w->port_output = true; + w->set_bool_attribute(ID(abc_scc_break)); + w = module->wire(stringf("%s.abci", w->name.c_str())); + if (!w) { + w = module->addWire(stringf("%s.abci", b.wire->name.c_str()), GetSize(b.wire)); + w->port_input = true; + } + else { + log_assert(b.offset < GetSize(w)); + log_assert(w->port_input); + } + sig.append(RTLIL::SigBit(w, b.offset)); } - sig.append(RTLIL::SigBit(w, b.offset)); + rhs = sig; } - rhs = sig; - } } module->fixup_ports(); @@ -288,7 +272,9 @@ void abc9_module(RTLIL::Design *design, RTLIL::Module *current_module, std::stri bool cleanup, vector<int> lut_costs, bool dff_mode, std::string clk_str, bool /*keepff*/, std::string delay_target, std::string /*lutin_shared*/, bool fast_mode, bool show_tempdir, std::string box_file, std::string lut_file, - std::string wire_delay, const dict<int,IdString> &box_lookup) + std::string wire_delay, const dict<int,IdString> &box_lookup, + const dict<IdString,pool<IdString>> &scc_break_inputs +) { module = current_module; map_autoidx = autoidx++; @@ -427,7 +413,7 @@ void abc9_module(RTLIL::Design *design, RTLIL::Module *current_module, std::stri RTLIL::Selection& sel = design->selection_stack.back(); sel.select(module); - handle_loops(design); + handle_loops(design, scc_break_inputs); Pass::call(design, "aigmap"); @@ -1081,6 +1067,7 @@ struct Abc9Pass : public Pass { extra_args(args, argidx, design); dict<int,IdString> box_lookup; + dict<IdString,pool<IdString>> scc_break_inputs; for (auto m : design->modules()) { auto it = m->attributes.find(ID(abc_box_id)); if (it == m->attributes.end()) @@ -1093,6 +1080,56 @@ struct Abc9Pass : public Pass { log_error("Module '%s' has the same abc_box_id = %d value as '%s'.\n", log_id(m), id, log_id(r.first->second)); log_assert(r.second); + + RTLIL::Wire *carry_in = nullptr, *carry_out = nullptr; + for (auto p : m->ports) { + auto w = m->wire(p); + log_assert(w); + if (w->port_input) { + if (w->attributes.count(ID(abc_scc_break))) + scc_break_inputs[m->name].insert(p); + if (w->attributes.count(ID(abc_carry))) { + if (carry_in) + log_error("Module '%s' contains more than one 'abc_carry' input port.\n", log_id(m)); + carry_in = w; + } + } + if (w->port_output) { + if (w->attributes.count(ID(abc_carry))) { + if (carry_out) + log_error("Module '%s' contains more than one 'abc_carry' input port.\n", log_id(m)); + carry_out = w; + } + } + } + if (carry_in || carry_out) { + if (carry_in && !carry_out) + log_error("Module '%s' contains an 'abc_carry' input port but no output port.\n", log_id(m)); + if (!carry_in && carry_out) + log_error("Module '%s' contains an 'abc_carry' output port but no input port.\n", log_id(m)); + // Make carry_in the last PI, and carry_out the last PO + // since ABC requires it this way + auto &ports = m->ports; + for (auto it = ports.begin(); it != ports.end(); ) { + RTLIL::Wire* w = m->wire(*it); + log_assert(w); + if (w == carry_in || w == carry_out) { + it = ports.erase(it); + continue; + } + if (w->port_id > carry_in->port_id) + --w->port_id; + if (w->port_id > carry_out->port_id) + --w->port_id; + log_assert(w->port_input || w->port_output); + log_assert(ports[w->port_id-1] == w->name); + ++it; + } + ports.push_back(carry_in->name); + carry_in->port_id = ports.size(); + ports.push_back(carry_out->name); + carry_out->port_id = ports.size(); + } } for (auto mod : design->selected_modules()) @@ -1110,7 +1147,7 @@ struct Abc9Pass : public Pass { if (!dff_mode || !clk_str.empty()) { abc9_module(design, mod, script_file, exe_file, cleanup, lut_costs, dff_mode, clk_str, keepff, delay_target, lutin_shared, fast_mode, show_tempdir, - box_file, lut_file, wire_delay, box_lookup); + box_file, lut_file, wire_delay, box_lookup, scc_break_inputs); continue; } @@ -1256,7 +1293,7 @@ struct Abc9Pass : public Pass { en_sig = assign_map(std::get<3>(it.first)); abc9_module(design, mod, script_file, exe_file, cleanup, lut_costs, !clk_sig.empty(), "$", keepff, delay_target, lutin_shared, fast_mode, show_tempdir, - box_file, lut_file, wire_delay, box_lookup); + box_file, lut_file, wire_delay, box_lookup, scc_break_inputs); assign_map.set(mod); } } diff --git a/passes/techmap/clkbufmap.cc b/passes/techmap/clkbufmap.cc new file mode 100644 index 000000000..246932d81 --- /dev/null +++ b/passes/techmap/clkbufmap.cc @@ -0,0 +1,298 @@ +/* + * yosys -- Yosys Open SYnthesis Suite + * + * Copyright (C) 2012 Clifford Wolf <clifford@clifford.at> + * Copyright (C) 2019 Marcin KoĆcielnicki <mwk@0x04.net> + * + * 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/sigtools.h" + +USING_YOSYS_NAMESPACE +PRIVATE_NAMESPACE_BEGIN + +void split_portname_pair(std::string &port1, std::string &port2) +{ + size_t pos = port1.find_first_of(':'); + if (pos != std::string::npos) { + port2 = port1.substr(pos+1); + port1 = port1.substr(0, pos); + } +} + +struct ClkbufmapPass : public Pass { + ClkbufmapPass() : Pass("clkbufmap", "insert global buffers on clock networks") { } + void help() YS_OVERRIDE + { + // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| + log("\n"); + log(" clkbufmap [options] [selection]\n"); + log("\n"); + log("Inserts global buffers between nets connected to clock inputs and their drivers.\n"); + log("\n"); + log("In the absence of any selection, all wires without the 'clkbuf_inhibit'\n"); + log("attribute will be considered for global buffer insertion.\n"); + log("Alternatively, to consider all wires without the 'buffer_type' attribute set to\n"); + log("'none' or 'bufr' one would specify:\n"); + log(" 'w:* a:buffer_type=none a:buffer_type=bufr %%u %%d'\n"); + log("as the selection.\n"); + log("\n"); + log(" -buf <celltype> <portname_out>:<portname_in>\n"); + log(" Specifies the cell type to use for the global buffers\n"); + log(" and its port names. The first port will be connected to\n"); + log(" the clock network sinks, and the second will be connected\n"); + log(" to the actual clock source. This option is required.\n"); + log("\n"); + log(" -inpad <celltype> <portname_out>:<portname_in>\n"); + log(" If specified, a PAD cell of the given type is inserted on\n"); + log(" clock nets that are also top module's inputs (in addition\n"); + log(" to the global buffer).\n"); + log("\n"); + } + + void module_queue(Design *design, Module *module, std::vector<Module *> &modules_sorted, pool<Module *> &modules_processed) { + if (modules_processed.count(module)) + return; + for (auto cell : module->cells()) { + Module *submodule = design->module(cell->type); + if (!submodule) + continue; + module_queue(design, submodule, modules_sorted, modules_processed); + } + modules_sorted.push_back(module); + modules_processed.insert(module); + } + + void execute(std::vector<std::string> args, RTLIL::Design *design) YS_OVERRIDE + { + log_header(design, "Executing CLKBUFMAP pass (inserting global clock buffers).\n"); + + std::string buf_celltype, buf_portname, buf_portname2; + std::string inpad_celltype, inpad_portname, inpad_portname2; + + size_t argidx; + for (argidx = 1; argidx < args.size(); argidx++) + { + std::string arg = args[argidx]; + if (arg == "-buf" && argidx+2 < args.size()) { + buf_celltype = args[++argidx]; + buf_portname = args[++argidx]; + split_portname_pair(buf_portname, buf_portname2); + continue; + } + if (arg == "-inpad" && argidx+2 < args.size()) { + inpad_celltype = args[++argidx]; + inpad_portname = args[++argidx]; + split_portname_pair(inpad_portname, inpad_portname2); + continue; + } + break; + } + + bool select = false; + if (argidx < args.size()) { + if (args[argidx].compare(0, 1, "-") != 0) + select = true; + extra_args(args, argidx, design); + } + + if (buf_celltype.empty()) + log_error("The -buf option is required.\n"); + + // Cell type, port name, bit index. + pool<pair<IdString, pair<IdString, int>>> sink_ports; + pool<pair<IdString, pair<IdString, int>>> buf_ports; + + // Process submodules before module using them. + std::vector<Module *> modules_sorted; + pool<Module *> modules_processed; + for (auto module : design->selected_modules()) + module_queue(design, module, modules_sorted, modules_processed); + + for (auto module : modules_sorted) + { + if (module->get_blackbox_attribute()) { + for (auto port : module->ports) { + auto wire = module->wire(port); + if (wire->get_bool_attribute("\\clkbuf_driver")) + for (int i = 0; i < GetSize(wire); i++) + buf_ports.insert(make_pair(module->name, make_pair(wire->name, i))); + if (wire->get_bool_attribute("\\clkbuf_sink")) + for (int i = 0; i < GetSize(wire); i++) + sink_ports.insert(make_pair(module->name, make_pair(wire->name, i))); + } + continue; + } + pool<SigBit> sink_wire_bits; + pool<SigBit> buf_wire_bits; + pool<SigBit> driven_wire_bits; + SigMap sigmap(module); + // bit -> (buffer, buffer's input) + dict<SigBit, pair<Cell *, Wire *>> buffered_bits; + + // First, collect nets that could use a clock buffer. + for (auto cell : module->cells()) + for (auto port : cell->connections()) + for (int i = 0; i < port.second.size(); i++) + if (sink_ports.count(make_pair(cell->type, make_pair(port.first, i)))) + sink_wire_bits.insert(sigmap(port.second[i])); + + // Second, collect ones that already have a clock buffer. + for (auto cell : module->cells()) + for (auto port : cell->connections()) + for (int i = 0; i < port.second.size(); i++) + if (buf_ports.count(make_pair(cell->type, make_pair(port.first, i)))) + buf_wire_bits.insert(sigmap(port.second[i])); + + // Collect all driven bits. + for (auto cell : module->cells()) + for (auto port : cell->connections()) + if (cell->output(port.first)) + for (int i = 0; i < port.second.size(); i++) + driven_wire_bits.insert(port.second[i]); + + // Insert buffers. + std::vector<pair<Wire *, Wire *>> input_queue; + // Copy current wire list, as we will be adding new ones during iteration. + std::vector<Wire *> wires(module->wires()); + for (auto wire : wires) + { + // Should not happen. + if (wire->port_input && wire->port_output) + continue; + bool process_wire = module->selected(wire); + if (!select && wire->get_bool_attribute("\\clkbuf_inhibit")) + process_wire = false; + if (!process_wire) { + // This wire is supposed to be bypassed, so make sure we don't buffer it in + // some buffer higher up in the hierarchy. + if (wire->port_output) + for (int i = 0; i < GetSize(wire); i++) + buf_ports.insert(make_pair(module->name, make_pair(wire->name, i))); + continue; + } + + pool<int> input_bits; + + for (int i = 0; i < GetSize(wire); i++) + { + SigBit wire_bit(wire, i); + SigBit mapped_wire_bit = sigmap(wire_bit); + if (buf_wire_bits.count(mapped_wire_bit)) { + // Already buffered downstream. If this is an output, mark it. + if (wire->port_output) + buf_ports.insert(make_pair(module->name, make_pair(wire->name, i))); + } else if (!sink_wire_bits.count(mapped_wire_bit)) { + // Nothing to do. + } else if (driven_wire_bits.count(wire_bit) || (wire->port_input && module->get_bool_attribute("\\top"))) { + // Clock network not yet buffered, driven by one of + // our cells or a top-level input -- buffer it. + + log("Inserting %s on %s.%s[%d].\n", buf_celltype.c_str(), log_id(module), log_id(wire), i); + RTLIL::Cell *cell = module->addCell(NEW_ID, RTLIL::escape_id(buf_celltype)); + Wire *iwire = module->addWire(NEW_ID); + cell->setPort(RTLIL::escape_id(buf_portname), mapped_wire_bit); + cell->setPort(RTLIL::escape_id(buf_portname2), iwire); + if (wire->port_input && !inpad_celltype.empty() && module->get_bool_attribute("\\top")) { + log("Inserting %s on %s.%s[%d].\n", inpad_celltype.c_str(), log_id(module), log_id(wire), i); + RTLIL::Cell *cell2 = module->addCell(NEW_ID, RTLIL::escape_id(inpad_celltype)); + cell2->setPort(RTLIL::escape_id(inpad_portname), iwire); + iwire = module->addWire(NEW_ID); + cell2->setPort(RTLIL::escape_id(inpad_portname2), iwire); + } + buffered_bits[mapped_wire_bit] = make_pair(cell, iwire); + + if (wire->port_input) { + input_bits.insert(i); + } + } else if (wire->port_input) { + // A clock input in a submodule -- mark it, let higher level + // worry about it. + if (wire->port_input) + sink_ports.insert(make_pair(module->name, make_pair(wire->name, i))); + } + } + if (!input_bits.empty()) { + // This is an input port and some buffers were inserted -- we need + // to create a new input wire and transfer attributes. + Wire *new_wire = module->addWire(NEW_ID, wire); + + for (int i = 0; i < wire->width; i++) { + SigBit wire_bit(wire, i); + SigBit mapped_wire_bit = sigmap(wire_bit); + auto it = buffered_bits.find(mapped_wire_bit); + if (it != buffered_bits.end()) { + + module->connect(it->second.second, SigSpec(new_wire, i)); + } else { + module->connect(SigSpec(wire, i), SigSpec(new_wire, i)); + } + } + input_queue.push_back(make_pair(wire, new_wire)); + } + } + + // Mark any newly-buffered output ports as such. + for (auto wire : module->selected_wires()) { + if (wire->port_input || !wire->port_output) + continue; + for (int i = 0; i < GetSize(wire); i++) + { + SigBit wire_bit(wire, i); + SigBit mapped_wire_bit = sigmap(wire_bit); + if (buffered_bits.count(mapped_wire_bit)) + buf_ports.insert(make_pair(module->name, make_pair(wire->name, i))); + } + } + + // Reconnect the drivers to buffer inputs. + for (auto cell : module->cells()) + for (auto port : cell->connections()) { + if (!cell->output(port.first)) + continue; + SigSpec sig = port.second; + bool newsig = false; + for (auto &bit : sig) { + const auto it = buffered_bits.find(sigmap(bit)); + if (it == buffered_bits.end()) + continue; + // Avoid substituting buffer's own output pin. + if (cell == it->second.first) + continue; + bit = it->second.second; + newsig = true; + } + if (newsig) + cell->setPort(port.first, sig); + } + + // This has to be done last, to avoid upsetting sigmap before the port reconnections. + for (auto &it : input_queue) { + Wire *wire = it.first; + Wire *new_wire = it.second; + module->swap_names(new_wire, wire); + wire->attributes.clear(); + wire->port_id = 0; + wire->port_input = false; + wire->port_output = false; + } + + module->fixup_ports(); + } + } +} ClkbufmapPass; + +PRIVATE_NAMESPACE_END diff --git a/passes/techmap/iopadmap.cc b/passes/techmap/iopadmap.cc index a2551316f..c868b9a87 100644 --- a/passes/techmap/iopadmap.cc +++ b/passes/techmap/iopadmap.cc @@ -64,6 +64,11 @@ struct IopadmapPass : public Pass { log(" of the tristate driver and the 2nd portname is the internal output\n"); log(" buffering the external signal.\n"); log("\n"); + log(" -ignore <celltype> <portname>[:<portname>]*\n"); + log(" Skips mapping inputs/outputs that are already connected to given\n"); + log(" ports of the given cell. Can be used multiple times. This is in\n"); + log(" addition to the cells specified as mapping targets.\n"); + log("\n"); log(" -widthparam <param_name>\n"); log(" Use the specified parameter name to set the port width.\n"); log("\n"); @@ -88,6 +93,7 @@ struct IopadmapPass : public Pass { std::string toutpad_celltype, toutpad_portname, toutpad_portname2, toutpad_portname3; std::string tinoutpad_celltype, tinoutpad_portname, tinoutpad_portname2, tinoutpad_portname3, tinoutpad_portname4; std::string widthparam, nameparam; + pool<pair<IdString, IdString>> ignore; bool flag_bits = false; size_t argidx; @@ -127,6 +133,18 @@ struct IopadmapPass : public Pass { split_portname_pair(tinoutpad_portname3, tinoutpad_portname4); continue; } + if (arg == "-ignore" && argidx+2 < args.size()) { + std::string ignore_celltype = args[++argidx]; + std::string ignore_portname = args[++argidx]; + std::string ignore_portname2; + while (!ignore_portname.empty()) { + split_portname_pair(ignore_portname, ignore_portname2); + ignore.insert(make_pair(RTLIL::escape_id(ignore_celltype), RTLIL::escape_id(ignore_portname))); + + ignore_portname = ignore_portname2; + } + continue; + } if (arg == "-widthparam" && argidx+1 < args.size()) { widthparam = args[++argidx]; continue; @@ -143,6 +161,23 @@ struct IopadmapPass : public Pass { } extra_args(args, argidx, design); + if (!inpad_portname2.empty()) + ignore.insert(make_pair(RTLIL::escape_id(inpad_celltype), RTLIL::escape_id(inpad_portname2))); + if (!outpad_portname2.empty()) + ignore.insert(make_pair(RTLIL::escape_id(outpad_celltype), RTLIL::escape_id(outpad_portname2))); + if (!inoutpad_portname2.empty()) + ignore.insert(make_pair(RTLIL::escape_id(inoutpad_celltype), RTLIL::escape_id(inoutpad_portname2))); + if (!toutpad_portname3.empty()) + ignore.insert(make_pair(RTLIL::escape_id(toutpad_celltype), RTLIL::escape_id(toutpad_portname3))); + if (!tinoutpad_portname4.empty()) + ignore.insert(make_pair(RTLIL::escape_id(tinoutpad_celltype), RTLIL::escape_id(tinoutpad_portname4))); + + for (auto module : design->modules()) + if (module->get_blackbox_attribute()) + for (auto wire : module->wires()) + if (wire->get_bool_attribute("\\iopad_external_pin")) + ignore.insert(make_pair(module->name, wire->name)); + for (auto module : design->selected_modules()) { dict<IdString, pool<int>> skip_wires; @@ -150,28 +185,11 @@ struct IopadmapPass : public Pass { SigMap sigmap(module); for (auto cell : module->cells()) - { - if (cell->type == RTLIL::escape_id(inpad_celltype) && cell->hasPort(RTLIL::escape_id(inpad_portname2))) - for (auto bit : sigmap(cell->getPort(RTLIL::escape_id(inpad_portname2)))) - skip_wire_bits.insert(bit); - - if (cell->type == RTLIL::escape_id(outpad_celltype) && cell->hasPort(RTLIL::escape_id(outpad_portname2))) - for (auto bit : sigmap(cell->getPort(RTLIL::escape_id(outpad_portname2)))) + for (auto port : cell->connections()) + if (ignore.count(make_pair(cell->type, port.first))) + for (auto bit : sigmap(port.second)) skip_wire_bits.insert(bit); - if (cell->type == RTLIL::escape_id(inoutpad_celltype) && cell->hasPort(RTLIL::escape_id(inoutpad_portname2))) - for (auto bit : sigmap(cell->getPort(RTLIL::escape_id(inoutpad_portname2)))) - skip_wire_bits.insert(bit); - - if (cell->type == RTLIL::escape_id(toutpad_celltype) && cell->hasPort(RTLIL::escape_id(toutpad_portname3))) - for (auto bit : sigmap(cell->getPort(RTLIL::escape_id(toutpad_portname3)))) - skip_wire_bits.insert(bit); - - if (cell->type == RTLIL::escape_id(tinoutpad_celltype) && cell->hasPort(RTLIL::escape_id(tinoutpad_portname4))) - for (auto bit : sigmap(cell->getPort(RTLIL::escape_id(tinoutpad_portname4)))) - skip_wire_bits.insert(bit); - } - if (!toutpad_celltype.empty() || !tinoutpad_celltype.empty()) { dict<SigBit, pair<IdString, pool<IdString>>> tbuf_bits; diff --git a/passes/techmap/techmap.cc b/passes/techmap/techmap.cc index b271c8781..c4496f76f 100644 --- a/passes/techmap/techmap.cc +++ b/passes/techmap/techmap.cc @@ -943,7 +943,8 @@ struct TechmapPass : public Pass { log(" instead of inlining them.\n"); log("\n"); log(" -max_iter <number>\n"); - log(" only run the specified number of iterations.\n"); + log(" only run the specified number of iterations on each module.\n"); + log(" default: unlimited\n"); log("\n"); log(" -recursive\n"); log(" instead of the iterative breadth-first algorithm use a recursive\n"); @@ -1157,15 +1158,16 @@ struct TechmapPass : public Pass { RTLIL::Module *module = *worker.module_queue.begin(); worker.module_queue.erase(module); + int module_max_iter = max_iter; bool did_something = true; std::set<RTLIL::Cell*> handled_cells; while (did_something) { did_something = false; - if (worker.techmap_module(design, module, map, handled_cells, celltypeMap, false)) - did_something = true; + if (worker.techmap_module(design, module, map, handled_cells, celltypeMap, false)) + did_something = true; if (did_something) module->check(); - if (max_iter > 0 && --max_iter == 0) + if (module_max_iter > 0 && --module_max_iter == 0) break; } } |