Skip to content

Commit 19c6aa2

Browse files
committed
add generic writer class with formatting function to FunctionalTools
1 parent f21bde0 commit 19c6aa2

File tree

4 files changed

+203
-160
lines changed

4 files changed

+203
-160
lines changed

backends/functional/cxx.cc

+74-106
Original file line numberDiff line numberDiff line change
@@ -56,129 +56,93 @@ struct CxxType {
5656
}
5757
};
5858

59-
struct CxxWriter {
60-
std::ostream &f;
61-
CxxWriter(std::ostream &out) : f(out) {}
62-
void printf(const char *fmt, ...)
63-
{
64-
va_list va;
65-
va_start(va, fmt);
66-
f << vstringf(fmt, va);
67-
va_end(va);
68-
}
69-
};
59+
using CxxWriter = FunctionalTools::Writer;
7060

7161
struct CxxStruct {
7262
std::string name;
7363
dict<IdString, CxxType> types;
7464
FunctionalTools::Scope scope;
7565
CxxStruct(std::string name)
7666
: name(name), scope(illegal_characters, reserved_keywords) {
77-
scope.reserve("out");
78-
scope.reserve("dump");
67+
scope.reserve("fn");
68+
scope.reserve("visit");
7969
}
8070
void insert(IdString name, CxxType type) {
8171
scope(name);
8272
types.insert({name, type});
8373
}
8474
void print(CxxWriter &f) {
85-
f.printf("\tstruct %s {\n", name.c_str());
75+
f.print("\tstruct {} {{\n", name);
8676
for (auto p : types) {
87-
f.printf("\t\t%s %s;\n", p.second.to_string().c_str(), scope(p.first).c_str());
77+
f.print("\t\t{} {};\n", p.second.to_string(), scope(p.first));
8878
}
89-
f.printf("\n\t\ttemplate <typename T> void visit(T &&fn) {\n");
79+
f.print("\n\t\ttemplate <typename T> void visit(T &&fn) {{\n");
9080
for (auto p : types) {
91-
f.printf("\t\t\tfn(\"%s\", %s);\n", RTLIL::unescape_id(p.first).c_str(), scope(p.first).c_str());
81+
f.print("\t\t\tfn(\"{}\", {});\n", RTLIL::unescape_id(p.first), scope(p.first));
9282
}
93-
f.printf("\t\t}\n");
94-
f.printf("\t};\n\n");
83+
f.print("\t\t}}\n");
84+
f.print("\t}};\n\n");
9585
};
9686
std::string operator[](IdString field) {
9787
return scope(field);
9888
}
9989
};
10090

101-
struct CxxTemplate {
102-
vector<std::variant<std::string, int>> _v;
103-
public:
104-
CxxTemplate(std::string fmt) {
105-
std::string buf;
106-
for(auto it = fmt.begin(); it != fmt.end(); it++){
107-
if(*it == '%'){
108-
it++;
109-
log_assert(it != fmt.end());
110-
if(*it == '%')
111-
buf += *it;
112-
else {
113-
log_assert(*it >= '0' && *it <= '9');
114-
_v.emplace_back(std::move(buf));
115-
_v.emplace_back((int)(*it - '0'));
116-
}
117-
}else
118-
buf += *it;
119-
}
120-
if(!buf.empty())
121-
_v.emplace_back(std::move(buf));
122-
}
123-
template<typename... Args> static std::string format(CxxTemplate fmt, Args&&... args) {
124-
vector<std::string> strs = {args...};
125-
std::string result;
126-
for(auto &v : fmt._v){
127-
if(std::string *s = std::get_if<std::string>(&v))
128-
result += *s;
129-
else if(int *i = std::get_if<int>(&v))
130-
result += strs[*i];
131-
else
132-
log_error("missing case");
133-
}
134-
return result;
135-
}
136-
};
137-
138-
template<class NodeNames> struct CxxPrintVisitor {
91+
template<class NodePrinter> struct CxxPrintVisitor {
13992
using Node = FunctionalIR::Node;
140-
NodeNames np;
93+
CxxWriter &f;
94+
NodePrinter np;
14195
CxxStruct &input_struct;
14296
CxxStruct &state_struct;
143-
CxxPrintVisitor(NodeNames np, CxxStruct &input_struct, CxxStruct &state_struct) : np(np), input_struct(input_struct), state_struct(state_struct) { }
144-
template<class T> std::string arg_to_string(T n) { return std::to_string(n); }
145-
std::string arg_to_string(std::string n) { return n; }
146-
std::string arg_to_string(Node n) { return np(n); }
147-
template<typename... Args> std::string format(std::string fmt, Args&&... args) {
148-
return CxxTemplate::format(fmt, arg_to_string(args)...);
97+
CxxPrintVisitor(CxxWriter &f, NodePrinter np, CxxStruct &input_struct, CxxStruct &state_struct) : f(f), np(np), input_struct(input_struct), state_struct(state_struct) { }
98+
template<typename... Args> void print(const char *fmt, Args&&... args) {
99+
f.print_with(np, fmt, std::forward<Args>(args)...);
149100
}
150-
std::string buf(Node, Node n) { return np(n); }
151-
std::string slice(Node, Node a, int, int offset, int out_width) { return format("%0.slice<%2>(%1)", a, offset, out_width); }
152-
std::string zero_extend(Node, Node a, int, int out_width) { return format("%0.zero_extend<%1>()", a, out_width); }
153-
std::string sign_extend(Node, Node a, int, int out_width) { return format("%0.sign_extend<%1>()", a, out_width); }
154-
std::string concat(Node, Node a, int, Node b, int) { return format("%0.concat(%1)", a, b); }
155-
std::string add(Node, Node a, Node b, int) { return format("%0 + %1", a, b); }
156-
std::string sub(Node, Node a, Node b, int) { return format("%0 - %1", a, b); }
157-
std::string bitwise_and(Node, Node a, Node b, int) { return format("%0 & %1", a, b); }
158-
std::string bitwise_or(Node, Node a, Node b, int) { return format("%0 | %1", a, b); }
159-
std::string bitwise_xor(Node, Node a, Node b, int) { return format("%0 ^ %1", a, b); }
160-
std::string bitwise_not(Node, Node a, int) { return format("~%0", a); }
161-
std::string unary_minus(Node, Node a, int) { return format("-%0", a); }
162-
std::string reduce_and(Node, Node a, int) { return format("%0.all()", a); }
163-
std::string reduce_or(Node, Node a, int) { return format("%0.any()", a); }
164-
std::string reduce_xor(Node, Node a, int) { return format("%0.parity()", a); }
165-
std::string equal(Node, Node a, Node b, int) { return format("%0 == %1", a, b); }
166-
std::string not_equal(Node, Node a, Node b, int) { return format("%0 != %1", a, b); }
167-
std::string signed_greater_than(Node, Node a, Node b, int) { return format("%0.signed_greater_than(%1)", a, b); }
168-
std::string signed_greater_equal(Node, Node a, Node b, int) { return format("%0.signed_greater_equal(%1)", a, b); }
169-
std::string unsigned_greater_than(Node, Node a, Node b, int) { return format("%0 > %1", a, b); }
170-
std::string unsigned_greater_equal(Node, Node a, Node b, int) { return format("%0 >= %1", a, b); }
171-
std::string logical_shift_left(Node, Node a, Node b, int, int) { return format("%0 << %1", a, b); }
172-
std::string logical_shift_right(Node, Node a, Node b, int, int) { return format("%0 >> %1", a, b); }
173-
std::string arithmetic_shift_right(Node, Node a, Node b, int, int) { return format("%0.arithmetic_shift_right(%1)", a, b); }
174-
std::string mux(Node, Node a, Node b, Node s, int) { return format("%2.any() ? %1 : %0", a, b, s); }
175-
std::string pmux(Node, Node a, Node b, Node s, int, int) { return format("%0.pmux(%1, %2)", a, b, s); }
176-
std::string constant(Node, RTLIL::Const value) { return format("Signal<%0>(%1)", value.size(), value.as_int()); }
177-
std::string input(Node, IdString name) { return format("input.%0", input_struct[name]); }
178-
std::string state(Node, IdString name) { return format("current_state.%0", state_struct[name]); }
179-
std::string memory_read(Node, Node mem, Node addr, int, int) { return format("%0.read(%1)", mem, addr); }
180-
std::string memory_write(Node, Node mem, Node addr, Node data, int, int) { return format("%0.write(%1, %2)", mem, addr, data); }
181-
std::string undriven(Node, int width) { return format("Signal<%0>(0)", width); }
101+
void buf(Node, Node n) { print("{}", n); }
102+
void slice(Node, Node a, int, int offset, int out_width) { print("{0}.slice<{2}>({1})", a, offset, out_width); }
103+
void zero_extend(Node, Node a, int, int out_width) { print("{}.zero_extend<{}>()", a, out_width); }
104+
void sign_extend(Node, Node a, int, int out_width) { print("{}.sign_extend<{}>()", a, out_width); }
105+
void concat(Node, Node a, int, Node b, int) { print("{}.concat({})", a, b); }
106+
void add(Node, Node a, Node b, int) { print("{} + {}", a, b); }
107+
void sub(Node, Node a, Node b, int) { print("{} - {}", a, b); }
108+
void bitwise_and(Node, Node a, Node b, int) { print("{} & {}", a, b); }
109+
void bitwise_or(Node, Node a, Node b, int) { print("{} | {}", a, b); }
110+
void bitwise_xor(Node, Node a, Node b, int) { print("{} ^ {}", a, b); }
111+
void bitwise_not(Node, Node a, int) { print("~{}", a); }
112+
void unary_minus(Node, Node a, int) { print("-{}", a); }
113+
void reduce_and(Node, Node a, int) { print("{}.all()", a); }
114+
void reduce_or(Node, Node a, int) { print("{}.any()", a); }
115+
void reduce_xor(Node, Node a, int) { print("{}.parity()", a); }
116+
void equal(Node, Node a, Node b, int) { print("{} == {}", a, b); }
117+
void not_equal(Node, Node a, Node b, int) { print("{} != {}", a, b); }
118+
void signed_greater_than(Node, Node a, Node b, int) { print("{}.signed_greater_than({})", a, b); }
119+
void signed_greater_equal(Node, Node a, Node b, int) { print("{}.signed_greater_equal({})", a, b); }
120+
void unsigned_greater_than(Node, Node a, Node b, int) { print("{} > {}", a, b); }
121+
void unsigned_greater_equal(Node, Node a, Node b, int) { print("{} >= {}", a, b); }
122+
void logical_shift_left(Node, Node a, Node b, int, int) { print("{} << {}", a, b); }
123+
void logical_shift_right(Node, Node a, Node b, int, int) { print("{} >> {}", a, b); }
124+
void arithmetic_shift_right(Node, Node a, Node b, int, int) { print("{}.arithmetic_shift_right{})", a, b); }
125+
void mux(Node, Node a, Node b, Node s, int) { print("{2}.any() ? {1} : {0}", a, b, s); }
126+
void pmux(Node, Node a, Node b, Node s, int, int) { print("{0}.pmux({1}, {2})", a, b, s); }
127+
void constant(Node, RTLIL::Const value) {
128+
std::stringstream ss;
129+
bool multiple = value.size() > 32;
130+
ss << "Signal<" << value.size() << ">(" << std::hex << std::showbase;
131+
if(multiple) ss << "{";
132+
while(value.size() > 32) {
133+
ss << value.as_int() << ", ";
134+
value = value.extract(32, value.size() - 32);
135+
}
136+
ss << value.as_int();
137+
if(multiple) ss << "}";
138+
ss << ")";
139+
print("{}", ss.str());
140+
}
141+
void input(Node, IdString name) { print("input.{}", input_struct[name]); }
142+
void state(Node, IdString name) { print("current_state.{}", state_struct[name]); }
143+
void memory_read(Node, Node mem, Node addr, int, int) { print("{}.read({})", mem, addr); }
144+
void memory_write(Node, Node mem, Node addr, Node data, int, int) { print("{}.write({}, {})", mem, addr, data); }
145+
void undriven(Node, int width) { print("Signal<{}>(0)", width); }
182146
};
183147

184148
struct CxxModule {
@@ -201,31 +165,35 @@ struct CxxModule {
201165
module_name = FunctionalTools::Scope(illegal_characters, reserved_keywords)(module->name);
202166
}
203167
void write_header(CxxWriter &f) {
204-
f.printf("#include \"sim.h\"\n\n");
168+
f.print("#include \"sim.h\"\n\n");
205169
}
206170
void write_struct_def(CxxWriter &f) {
207-
f.printf("struct %s {\n", module_name.c_str());
171+
f.print("struct {} {{\n", module_name);
208172
input_struct.print(f);
209173
output_struct.print(f);
210174
state_struct.print(f);
211-
f.printf("\tstatic void eval(Inputs const &, Outputs &, State const &, State &);\n");
212-
f.printf("};\n\n");
175+
f.print("\tstatic void eval(Inputs const &, Outputs &, State const &, State &);\n");
176+
f.print("}};\n\n");
213177
}
214178
void write_eval_def(CxxWriter &f) {
215-
f.printf("void %s::eval(%s::Inputs const &input, %s::Outputs &output, %s::State const &current_state, %s::State &next_state)\n{\n", module_name.c_str(), module_name.c_str(), module_name.c_str(), module_name.c_str(), module_name.c_str());
179+
f.print("void {0}::eval({0}::Inputs const &input, {0}::Outputs &output, {0}::State const &current_state, {0}::State &next_state)\n{{\n", module_name);
216180
FunctionalTools::Scope locals(illegal_characters, reserved_keywords);
217181
locals.reserve("input");
218182
locals.reserve("output");
219183
locals.reserve("current_state");
220184
locals.reserve("next_state");
221185
auto node_name = [&](FunctionalIR::Node n) { return locals(n.id(), n.name()); };
222-
for (auto node : ir)
223-
f.printf("\t%s %s = %s;\n", CxxType(node.sort()).to_string().c_str(), node_name(node).c_str(), node.visit(CxxPrintVisitor(node_name, input_struct, state_struct)).c_str());
186+
CxxPrintVisitor printVisitor(f, node_name, input_struct, state_struct);
187+
for (auto node : ir) {
188+
f.print("\t{} {} = ", CxxType(node.sort()).to_string(), node_name(node));
189+
node.visit(printVisitor);
190+
f.print(";\n");
191+
}
224192
for (auto [name, sort] : ir.state())
225-
f.printf("\tnext_state.%s = %s;\n", state_struct[name].c_str(), node_name(ir.get_state_next_node(name)).c_str());
193+
f.print("\tnext_state.{} = {};\n", state_struct[name], node_name(ir.get_state_next_node(name)));
226194
for (auto [name, sort] : ir.outputs())
227-
f.printf("\toutput.%s = %s;\n", output_struct[name].c_str(), node_name(ir.get_output_node(name)).c_str());
228-
f.printf("}\n");
195+
f.print("\toutput.{} = {};\n", output_struct[name], node_name(ir.get_output_node(name)));
196+
f.print("}}\n");
229197
}
230198
};
231199

backends/functional/cxx_runtime/sim.h

+2-2
Original file line numberDiff line numberDiff line change
@@ -143,11 +143,11 @@ class Signal {
143143
{
144144
for(size_t i = sizeof(T) * 8; i < n; i++)
145145
if(_bits[i])
146-
return ~0;
146+
return ~((T)0);
147147
return as_numeric<T>();
148148
}
149149

150-
uint32_t as_int() { return as_numeric<uint32_t>(); }
150+
uint32_t as_int() const { return as_numeric<uint32_t>(); }
151151

152152
Signal<n> operator ~() const
153153
{

kernel/functionalir.cc

+51
Original file line numberDiff line numberDiff line change
@@ -443,4 +443,55 @@ void FunctionalIR::forward_buf() {
443443
_graph.permute(perm, alias);
444444
}
445445

446+
static std::string quote_fmt(const char *fmt)
447+
{
448+
std::string r;
449+
for(const char *p = fmt; *p != 0; p++) {
450+
switch(*p) {
451+
case '\n': r += "\\n"; break;
452+
case '\t': r += "\\t"; break;
453+
case '"': r += "\\\""; break;
454+
case '\\': r += "\\\\"; break;
455+
default: r += *p; break;
456+
}
457+
}
458+
return r;
459+
}
460+
461+
void FunctionalTools::Writer::print_impl(const char *fmt, vector<std::function<void()>> &fns)
462+
{
463+
size_t next_index = 0;
464+
for(const char *p = fmt; *p != 0; p++)
465+
switch(*p) {
466+
case '{':
467+
if(*++p == '{') {
468+
*os << '{';
469+
} else {
470+
char *pe;
471+
size_t index = strtoul(p, &pe, 10);
472+
if(*pe != '}')
473+
log_error("invalid format string: expected {<number>}, {} or {{, got \"%s\": \"%s\"\n",
474+
quote_fmt(std::string(p - 1, pe - p + 2).c_str()).c_str(),
475+
quote_fmt(fmt).c_str());
476+
if(p == pe)
477+
index = next_index;
478+
else
479+
p = pe;
480+
if(index >= fns.size())
481+
log_error("invalid format string: index %zu out of bounds (%zu): \"%s\"\n", index, fns.size(), quote_fmt(fmt).c_str());
482+
fns[index]();
483+
next_index = index + 1;
484+
}
485+
break;
486+
case '}':
487+
p++;
488+
if(*p != '}')
489+
log_error("invalid format string: unescaped }: \"%s\"\n", quote_fmt(fmt).c_str());
490+
*os << '}';
491+
break;
492+
default:
493+
*os << *p;
494+
}
495+
}
496+
446497
YOSYS_NAMESPACE_END

0 commit comments

Comments
 (0)