1 /*
2  *  yosys -- Yosys Open SYnthesis Suite
3  *
4  *  Copyright (C) 2012  Claire Xenia Wolf <claire@yosyshq.com>
5  *
6  *  Permission to use, copy, modify, and/or distribute this software for any
7  *  purpose with or without fee is hereby granted, provided that the above
8  *  copyright notice and this permission notice appear in all copies.
9  *
10  *  THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11  *  WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12  *  MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13  *  ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14  *  WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15  *  ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16  *  OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17  *
18  */
19 
20 #include "kernel/yosys.h"
21 #include "kernel/utils.h"
22 #include "kernel/sigtools.h"
23 
24 #include <stdlib.h>
25 #include <stdio.h>
26 #include <string.h>
27 
28 USING_YOSYS_NAMESPACE
29 PRIVATE_NAMESPACE_BEGIN
30 
concat_name(RTLIL::Cell * cell,IdString object_name)31 IdString concat_name(RTLIL::Cell *cell, IdString object_name)
32 {
33 	if (object_name[0] == '\\')
34 		return stringf("%s.%s", cell->name.c_str(), object_name.c_str() + 1);
35 	else {
36 		std::string object_name_str = object_name.str();
37 		if (object_name_str.substr(0, 8) == "$flatten")
38 			object_name_str.erase(0, 8);
39 		return stringf("$flatten%s.%s", cell->name.c_str(), object_name_str.c_str());
40 	}
41 }
42 
43 template<class T>
map_name(RTLIL::Cell * cell,T * object)44 IdString map_name(RTLIL::Cell *cell, T *object)
45 {
46 	return cell->module->uniquify(concat_name(cell, object->name));
47 }
48 
49 template<class T>
map_attributes(RTLIL::Cell * cell,T * object,IdString orig_object_name)50 void map_attributes(RTLIL::Cell *cell, T *object, IdString orig_object_name)
51 {
52 	if (object->has_attribute(ID::src))
53 		object->add_strpool_attribute(ID::src, cell->get_strpool_attribute(ID::src));
54 
55 	// Preserve original names via the hdlname attribute, but only for objects with a fully public name.
56 	if (cell->name[0] == '\\' && (object->has_attribute(ID::hdlname) || orig_object_name[0] == '\\')) {
57 		std::vector<std::string> hierarchy;
58 		if (object->has_attribute(ID::hdlname))
59 			hierarchy = object->get_hdlname_attribute();
60 		else
61 			hierarchy.push_back(orig_object_name.str().substr(1));
62 		hierarchy.insert(hierarchy.begin(), cell->name.str().substr(1));
63 		object->set_hdlname_attribute(hierarchy);
64 	}
65 }
66 
map_sigspec(const dict<RTLIL::Wire *,RTLIL::Wire * > & map,RTLIL::SigSpec & sig,RTLIL::Module * into=nullptr)67 void map_sigspec(const dict<RTLIL::Wire*, RTLIL::Wire*> &map, RTLIL::SigSpec &sig, RTLIL::Module *into = nullptr)
68 {
69 	vector<SigChunk> chunks = sig;
70 	for (auto &chunk : chunks)
71 		if (chunk.wire != nullptr && chunk.wire->module != into)
72 			chunk.wire = map.at(chunk.wire);
73 	sig = chunks;
74 }
75 
76 struct FlattenWorker
77 {
78 	bool ignore_wb = false;
79 
flatten_cellFlattenWorker80 	void flatten_cell(RTLIL::Design *design, RTLIL::Module *module, RTLIL::Cell *cell, RTLIL::Module *tpl, SigMap &sigmap, std::vector<RTLIL::Cell*> &new_cells)
81 	{
82 		// Copy the contents of the flattened cell
83 
84 		dict<IdString, IdString> memory_map;
85 		for (auto &tpl_memory_it : tpl->memories) {
86 			RTLIL::Memory *new_memory = module->addMemory(map_name(cell, tpl_memory_it.second), tpl_memory_it.second);
87 			map_attributes(cell, new_memory, tpl_memory_it.second->name);
88 			memory_map[tpl_memory_it.first] = new_memory->name;
89 			design->select(module, new_memory);
90 		}
91 
92 		dict<RTLIL::Wire*, RTLIL::Wire*> wire_map;
93 		dict<IdString, IdString> positional_ports;
94 		for (auto tpl_wire : tpl->wires()) {
95 			if (tpl_wire->port_id > 0)
96 				positional_ports.emplace(stringf("$%d", tpl_wire->port_id), tpl_wire->name);
97 
98 			RTLIL::Wire *new_wire = nullptr;
99 			if (tpl_wire->name[0] == '\\') {
100 				RTLIL::Wire *hier_wire = module->wire(concat_name(cell, tpl_wire->name));
101 				if (hier_wire != nullptr && hier_wire->get_bool_attribute(ID::hierconn)) {
102 					hier_wire->attributes.erase(ID::hierconn);
103 					if (GetSize(hier_wire) < GetSize(tpl_wire)) {
104 						log_warning("Widening signal %s.%s to match size of %s.%s (via %s.%s).\n",
105 							log_id(module), log_id(hier_wire), log_id(tpl), log_id(tpl_wire), log_id(module), log_id(cell));
106 						hier_wire->width = GetSize(tpl_wire);
107 					}
108 					new_wire = hier_wire;
109 				}
110 			}
111 			if (new_wire == nullptr) {
112 				new_wire = module->addWire(map_name(cell, tpl_wire), tpl_wire);
113 				new_wire->port_input = new_wire->port_output = false;
114 				new_wire->port_id = false;
115 			}
116 
117 			map_attributes(cell, new_wire, tpl_wire->name);
118 			wire_map[tpl_wire] = new_wire;
119 			design->select(module, new_wire);
120 		}
121 
122 		for (auto &tpl_proc_it : tpl->processes) {
123 			RTLIL::Process *new_proc = module->addProcess(map_name(cell, tpl_proc_it.second), tpl_proc_it.second);
124 			map_attributes(cell, new_proc, tpl_proc_it.second->name);
125 			for (auto new_proc_sync : new_proc->syncs)
126 				for (auto &memwr_action : new_proc_sync->mem_write_actions)
127 					memwr_action.memid = memory_map.at(memwr_action.memid).str();
128 			auto rewriter = [&](RTLIL::SigSpec &sig) { map_sigspec(wire_map, sig); };
129 			new_proc->rewrite_sigspecs(rewriter);
130 			design->select(module, new_proc);
131 		}
132 
133 		for (auto tpl_cell : tpl->cells()) {
134 			RTLIL::Cell *new_cell = module->addCell(map_name(cell, tpl_cell), tpl_cell);
135 			map_attributes(cell, new_cell, tpl_cell->name);
136 			if (new_cell->has_memid()) {
137 				IdString memid = new_cell->getParam(ID::MEMID).decode_string();
138 				new_cell->setParam(ID::MEMID, Const(memory_map.at(memid).str()));
139 			} else if (new_cell->is_mem_cell()) {
140 				IdString memid = new_cell->getParam(ID::MEMID).decode_string();
141 				new_cell->setParam(ID::MEMID, Const(concat_name(cell, memid).str()));
142 			}
143 			auto rewriter = [&](RTLIL::SigSpec &sig) { map_sigspec(wire_map, sig); };
144 			new_cell->rewrite_sigspecs(rewriter);
145 			design->select(module, new_cell);
146 			new_cells.push_back(new_cell);
147 		}
148 
149 		for (auto &tpl_conn_it : tpl->connections()) {
150 			RTLIL::SigSig new_conn = tpl_conn_it;
151 			map_sigspec(wire_map, new_conn.first);
152 			map_sigspec(wire_map, new_conn.second);
153 			module->connect(new_conn);
154 		}
155 
156 		// Attach port connections of the flattened cell
157 
158 		pool<SigBit> tpl_driven;
159 		for (auto tpl_cell : tpl->cells())
160 			for (auto &tpl_conn : tpl_cell->connections())
161 				if (tpl_cell->output(tpl_conn.first))
162 					for (auto bit : tpl_conn.second)
163 						tpl_driven.insert(bit);
164 		for (auto &tpl_conn : tpl->connections())
165 			for (auto bit : tpl_conn.first)
166 				tpl_driven.insert(bit);
167 
168 		for (auto &port_it : cell->connections())
169 		{
170 			IdString port_name = port_it.first;
171 			if (positional_ports.count(port_name) > 0)
172 				port_name = positional_ports.at(port_name);
173 			if (tpl->wire(port_name) == nullptr || tpl->wire(port_name)->port_id == 0) {
174 				if (port_name.begins_with("$"))
175 					log_error("Can't map port `%s' of cell `%s' to template `%s'!\n",
176 						port_name.c_str(), cell->name.c_str(), tpl->name.c_str());
177 				continue;
178 			}
179 
180 			if (GetSize(port_it.second) == 0)
181 				continue;
182 
183 			RTLIL::Wire *tpl_wire = tpl->wire(port_name);
184 			RTLIL::SigSig new_conn;
185 			bool is_signed = false;
186 			if (tpl_wire->port_output && !tpl_wire->port_input) {
187 				new_conn.first = port_it.second;
188 				new_conn.second = tpl_wire;
189 				is_signed = tpl_wire->is_signed;
190 			} else if (!tpl_wire->port_output && tpl_wire->port_input) {
191 				new_conn.first = tpl_wire;
192 				new_conn.second = port_it.second;
193 				is_signed = new_conn.second.is_wire() && new_conn.second.as_wire()->is_signed;
194 			} else {
195 				SigSpec sig_tpl = tpl_wire, sig_mod = port_it.second;
196 				for (int i = 0; i < GetSize(sig_tpl) && i < GetSize(sig_mod); i++) {
197 					if (tpl_driven.count(sig_tpl[i])) {
198 						new_conn.first.append(sig_mod[i]);
199 						new_conn.second.append(sig_tpl[i]);
200 					} else {
201 						new_conn.first.append(sig_tpl[i]);
202 						new_conn.second.append(sig_mod[i]);
203 					}
204 				}
205 			}
206 			map_sigspec(wire_map, new_conn.first, module);
207 			map_sigspec(wire_map, new_conn.second, module);
208 
209 			if (new_conn.second.size() > new_conn.first.size())
210 				new_conn.second.remove(new_conn.first.size(), new_conn.second.size() - new_conn.first.size());
211 			if (new_conn.second.size() < new_conn.first.size())
212 				new_conn.second.extend_u0(new_conn.first.size(), is_signed);
213 			log_assert(new_conn.first.size() == new_conn.second.size());
214 
215 			if (sigmap(new_conn.first).has_const())
216 				log_error("Cell port %s.%s.%s is driving constant bits: %s <= %s\n",
217 					log_id(module), log_id(cell), log_id(port_it.first), log_signal(new_conn.first), log_signal(new_conn.second));
218 
219 			module->connect(new_conn);
220 			sigmap.add(new_conn.first, new_conn.second);
221 		}
222 
223 		module->remove(cell);
224 	}
225 
flatten_moduleFlattenWorker226 	void flatten_module(RTLIL::Design *design, RTLIL::Module *module, pool<RTLIL::Module*> &used_modules)
227 	{
228 		if (!design->selected(module) || module->get_blackbox_attribute(ignore_wb))
229 			return;
230 
231 		SigMap sigmap(module);
232 		std::vector<RTLIL::Cell*> worklist = module->selected_cells();
233 		while (!worklist.empty())
234 		{
235 			RTLIL::Cell *cell = worklist.back();
236 			worklist.pop_back();
237 
238 			if (!design->has(cell->type))
239 				continue;
240 
241 			RTLIL::Module *tpl = design->module(cell->type);
242 			if (tpl->get_blackbox_attribute(ignore_wb))
243 				continue;
244 
245 			if (cell->get_bool_attribute(ID::keep_hierarchy) || tpl->get_bool_attribute(ID::keep_hierarchy)) {
246 				log("Keeping %s.%s (found keep_hierarchy attribute).\n", log_id(module), log_id(cell));
247 				used_modules.insert(tpl);
248 				continue;
249 			}
250 
251 			log_debug("Flattening %s.%s (%s).\n", log_id(module), log_id(cell), log_id(cell->type));
252 			// If a design is fully selected and has a top module defined, topological sorting ensures that all cells
253 			// added during flattening are black boxes, and flattening is finished in one pass. However, when flattening
254 			// individual modules, this isn't the case, and the newly added cells might have to be flattened further.
255 			flatten_cell(design, module, cell, tpl, sigmap, worklist);
256 		}
257 	}
258 };
259 
260 struct FlattenPass : public Pass {
FlattenPassFlattenPass261 	FlattenPass() : Pass("flatten", "flatten design") { }
helpFlattenPass262 	void help() override
263 	{
264 		//   |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
265 		log("\n");
266 		log("    flatten [options] [selection]\n");
267 		log("\n");
268 		log("This pass flattens the design by replacing cells by their implementation. This\n");
269 		log("pass is very similar to the 'techmap' pass. The only difference is that this\n");
270 		log("pass is using the current design as mapping library.\n");
271 		log("\n");
272 		log("Cells and/or modules with the 'keep_hierarchy' attribute set will not be\n");
273 		log("flattened by this command.\n");
274 		log("\n");
275 		log("    -wb\n");
276 		log("        Ignore the 'whitebox' attribute on cell implementations.\n");
277 		log("\n");
278 	}
executeFlattenPass279 	void execute(std::vector<std::string> args, RTLIL::Design *design) override
280 	{
281 		log_header(design, "Executing FLATTEN pass (flatten design).\n");
282 		log_push();
283 
284 		FlattenWorker worker;
285 
286 		size_t argidx;
287 		for (argidx = 1; argidx < args.size(); argidx++) {
288 			if (args[argidx] == "-wb") {
289 				worker.ignore_wb = true;
290 				continue;
291 			}
292 			break;
293 		}
294 		extra_args(args, argidx, design);
295 
296 		RTLIL::Module *top = nullptr;
297 		if (design->full_selection())
298 			for (auto module : design->modules())
299 				if (module->get_bool_attribute(ID::top))
300 					top = module;
301 
302 		pool<RTLIL::Module*> used_modules;
303 		if (top == nullptr)
304 			used_modules = design->modules();
305 		else
306 			used_modules.insert(top);
307 
308 		TopoSort<RTLIL::Module*, IdString::compare_ptr_by_name<RTLIL::Module>> topo_modules;
309 		pool<RTLIL::Module*> worklist = used_modules;
310 		while (!worklist.empty()) {
311 			RTLIL::Module *module = worklist.pop();
312 			for (auto cell : module->selected_cells()) {
313 				RTLIL::Module *tpl = design->module(cell->type);
314 				if (tpl != nullptr) {
315 					if (topo_modules.database.count(tpl) == 0)
316 						worklist.insert(tpl);
317 					topo_modules.edge(tpl, module);
318 				}
319 			}
320 		}
321 
322 		if (!topo_modules.sort())
323 			log_error("Cannot flatten a design containing recursive instantiations.\n");
324 
325 		for (auto module : topo_modules.sorted)
326 			worker.flatten_module(design, module, used_modules);
327 
328 		if (top != nullptr)
329 			for (auto module : design->modules().to_vector())
330 				if (!used_modules[module] && !module->get_blackbox_attribute(worker.ignore_wb)) {
331 					log("Deleting now unused module %s.\n", log_id(module));
332 					design->remove(module);
333 				}
334 
335 		log_pop();
336 	}
337 } FlattenPass;
338 
339 PRIVATE_NAMESPACE_END
340