File size: 31,803 Bytes
107d124 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 | /*
* yosys -- Yosys Open SYnthesis Suite
*
* Copyright (C) 2012 Claire Xenia Wolf <claire@yosyshq.com>
*
* 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 "libparse.h"
#include <stdlib.h>
#include <string.h>
#include <istream>
#include <fstream>
#include <iostream>
#include <sstream>
#include <algorithm>
#ifdef FILTERLIB
#undef log_assert
void log_assert(bool cond) {
if (!cond)
fprintf(stderr, "Unspecified assertion failed\n");
}
void warn(std::string str) {
std::cerr << str;
}
#else
#include "kernel/log.h"
void warn(std::string str) {
Yosys::log_warning_noprefix("%s", str);
}
#endif
using namespace Yosys;
#ifndef FILTERLIB
LibertyAstCache LibertyAstCache::instance;
std::shared_ptr<const LibertyAst> LibertyAstCache::cached_ast(const std::string &fname, const LibertyFilter &filter)
{
auto it = cached.find(fname);
if (it == cached.end())
return nullptr;
if (!it->second.filter.covers(filter))
return nullptr;
if (verbose)
log("Using cached data for liberty file `%s'\n", fname);
return it->second.ast;
}
void LibertyAstCache::parsed_ast(const std::string &fname, const LibertyFilter &filter,
const std::shared_ptr<const LibertyAst> &ast)
{
auto it = cache_path.find(fname);
bool should_cache = it == cache_path.end() ? cache_by_default : it->second;
if (!should_cache)
return;
if (verbose)
log("Caching data for liberty file `%s'\n", fname);
cached[fname] = CacheEntry{filter, ast};
}
#endif
bool LibertyInputStream::extend_buffer_once()
{
if (eof)
return false;
// To support unget we leave the last already read character in the buffer
if (buf_pos > 1) {
size_t move_pos = buf_pos - 1;
memmove(buffer.data(), buffer.data() + move_pos, buf_end - move_pos);
buf_pos -= move_pos;
buf_end -= move_pos;
}
const size_t chunk_size = 4096;
if (buffer.size() < buf_end + chunk_size) {
buffer.resize(buf_end + chunk_size);
}
size_t read_size = f.rdbuf()->sgetn((char *)buffer.data() + buf_end, chunk_size);
buf_end += read_size;
if (read_size < chunk_size)
eof = true;
return read_size != 0;
}
bool LibertyInputStream::extend_buffer_at_least(size_t size) {
while (buffered_size() < size) {
if (!extend_buffer_once())
return false;
}
return true;
}
int LibertyInputStream::get_cold()
{
if (buf_pos == buf_end) {
if (!extend_buffer_at_least())
return EOF;
}
int c = buffer[buf_pos];
buf_pos += 1;
return c;
}
int LibertyInputStream::peek_cold(size_t offset)
{
if (buf_pos + offset >= buf_end) {
if (!extend_buffer_at_least(offset + 1))
return EOF;
}
#ifdef log_assert
log_assert(buf_pos + offset < buffer.size());
#endif
return buffer[buf_pos + offset];
}
LibertyAst::~LibertyAst()
{
for (auto child : children)
delete child;
children.clear();
}
const LibertyAst *LibertyAst::find(std::string name) const
{
log_assert(filter.allows(name));
for (auto child : children)
if (child->id == name)
return child;
return NULL;
}
void LibertyAst::dump(FILE *f, sieve &blacklist, sieve &whitelist, std::string indent, std::string path, bool path_ok) const
{
if (whitelist.count(path + "/*") > 0)
path_ok = true;
path += "/" + id;
if (blacklist.count(id) > 0 || blacklist.count(path) > 0)
return;
if (whitelist.size() > 0 && whitelist.count(id) == 0 && whitelist.count(path) == 0 && !path_ok) {
fprintf(stderr, "Automatically added to blacklist: %s\n", path.c_str());
blacklist.insert(id);
return;
}
fprintf(f, "%s%s", indent.c_str(), id.c_str());
if (!args.empty() || !children.empty()) {
fprintf(f, "(");
for (size_t i = 0; i < args.size(); i++)
fprintf(f, "%s%s", i > 0 ? ", " : "", args[i].c_str());
fprintf(f, ")");
}
if (!value.empty())
fprintf(f, " : %s", value.c_str());
if (!children.empty()) {
fprintf(f, " {\n");
for (size_t i = 0; i < children.size(); i++)
children[i]->dump(f, blacklist, whitelist, indent + " ", path, path_ok);
fprintf(f, "%s}\n", indent.c_str());
} else
fprintf(f, " ;\n");
}
// binary operators excluding ' '
bool LibertyExpression::char_is_nice_binop(char c) {
return c == '*' || c == '&' || c == '^' || c == '+' || c == '|';
}
bool LibertyExpression::is_binop() {
return kind == AND || kind == OR || kind == XOR;
}
// https://matklad.github.io/2020/04/13/simple-but-powerful-pratt-parsing.html
LibertyExpression LibertyExpression::parse(Lexer &s, int min_prio) {
if (s.empty())
return LibertyExpression{};
char c = s.peek();
auto lhs = LibertyExpression{};
while (isspace(c) || c == '"') {
if (s.empty())
return lhs;
s.next();
c = s.peek();
}
if (isalpha(c)) { // pin
lhs.kind = Kind::PIN;
lhs.name = s.pin();
} else if (c == '(') { // parens
s.next();
lhs = parse(s);
if (s.peek() != ')') {
std::stringstream ss;
ss << "expected ')' instead of " << s.peek() << " while parsing Liberty expression '" << s.full_expr() << "'\n";
warn(ss.str());
return lhs;
}
s.next();
} else if (c == '!') { // prefix NOT
s.next();
lhs.kind = Kind::NOT;
lhs.children.push_back(parse(s, 7));
} else {
std::stringstream ss;
ss << "unrecognised character " << c << " while parsing Liberty expression " << s.full_expr() << "\n";
warn(ss.str());
return lhs;
}
while (true) {
if (s.empty())
break;
c = s.peek();
if (c == '\'') { // postfix NOT
if (min_prio > 7)
break;
s.next();
auto n = LibertyExpression{};
n.kind = Kind::NOT;
n.children.push_back(lhs);
lhs = std::move(n);
continue;
} else if (c == '^') { // infix XOR
if (min_prio > 5)
break;
s.next();
auto rhs = parse(s, 6);
auto n = LibertyExpression{};
n.kind = Kind::XOR;
n.children.push_back(lhs);
n.children.push_back(rhs);
lhs = std::move(n);
continue;
} else if (c == '&' || c == '*' || isspace(c)) { // infix AND
if (min_prio > 3)
break;
if (isspace(c)) {
// Rewind past this space and any further spaces
while (isspace(c)) {
if (s.empty())
return lhs;
s.next();
c = s.peek();
}
if (char_is_nice_binop(c) || c == ')' || c == '\'' || c == '\"') {
// We found a real binop, so this space wasn't an AND
// and we just discard it as meaningless whitespace
// Tail operators also imply this isn't an AND
continue;
}
} else {
// Rewind past this op
s.next();
}
auto rhs = parse(s, 4);
if (rhs.kind == EMPTY)
continue;
auto n = LibertyExpression{};
n.kind = Kind::AND;
n.children.push_back(lhs);
n.children.push_back(rhs);
lhs = std::move(n);
continue;
} else if (c == '+' || c == '|') { // infix OR
if (min_prio > 1)
break;
s.next();
auto rhs = parse(s, 2);
auto n = LibertyExpression{};
n.kind = Kind::OR;
n.children.push_back(lhs);
n.children.push_back(rhs);
lhs = std::move(n);
continue;
}
break;
}
return lhs;
}
void LibertyExpression::get_pin_names(std::unordered_set<std::string>& names) {
if (kind == Kind::PIN) {
names.insert(name);
} else {
for (auto& child : children)
child.get_pin_names(names);
}
}
bool LibertyExpression::eval(std::unordered_map<std::string, bool>& values) {
bool result = false;
switch (kind) {
case Kind::AND:
result = true;
for (auto& child : children)
result &= child.eval(values);
return result;
case Kind::OR:
result = false;
for (auto& child : children)
result |= child.eval(values);
return result;
case Kind::NOT:
log_assert(children.size() == 1);
return !children[0].eval(values);
case Kind::XOR:
result = false;
for (auto& child : children)
result ^= child.eval(values);
return result;
case Kind::PIN:
return values.at(name);
case Kind::EMPTY:
log_assert(false);
}
return false;
}
std::string LibertyExpression::sexpr_str(int indent)
{
std::string prefix;
switch (kind) {
case AND:
prefix += "(and ";
break;
case OR:
prefix += "(or ";
break;
case NOT:
prefix += "(not ";
break;
case XOR:
prefix += "(xor ";
break;
case PIN:
prefix += "(pin \"" + name + "\"";
break;
case EMPTY:
prefix += "(";
break;
default:
log_assert(false);
}
size_t add_indent = prefix.length();
bool first = true;
for (auto child : children) {
if (!first) {
prefix += "\n" + std::string(indent + add_indent, ' ');
}
prefix += child.sexpr_str(indent + add_indent);
first = false;
}
prefix += ")";
return prefix;
}
std::string LibertyExpression::vlog_str()
{
std::string prefix;
if (kind != PIN)
prefix += "(";
if (is_binop()) {
log_assert(children.size() == 2);
prefix += children[0].vlog_str();
switch (kind) {
case AND:
prefix += "&";
break;
case OR:
prefix += "|";
break;
case XOR:
prefix += "^";
break;
default:
log_assert(false);
}
prefix += children[1].vlog_str();
} else {
switch (kind) {
case NOT:
log_assert(children.size() == 1);
prefix += "~";
prefix += children[0].vlog_str();
break;
case PIN:
prefix += name;
break;
default:
log_assert(false);
}
}
if (kind != PIN)
prefix += ")";
return prefix;
}
int LibertyParser::lexer_inner(std::string &str)
{
int c;
// eat whitespace
do {
c = f.get();
} while (c == ' ' || c == '\t' || c == '\r');
// search for identifiers, numbers, plus or minus.
if (('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') || ('0' <= c && c <= '9') || c == '_' || c == '-' || c == '+' || c == '.') {
f.unget();
size_t i = 1;
while (true) {
c = f.peek(i);
if (('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') || ('0' <= c && c <= '9') || c == '_' || c == '-' || c == '+' || c == '.')
i += 1;
else
break;
}
str.clear();
str.append(f.buffered_data(), f.buffered_data() + i);
f.consume(i);
if (str == "+" || str == "-") {
/* Single operator is not an identifier */
return str[0];
}
else {
return 'v';
}
}
// if it wasn't an identifer, number of array range,
// maybe it's a string?
if (c == '"') {
size_t i = 0;
while (true) {
c = f.peek(i);
line += (c == '\n');
if (c != '"' && c != EOF)
i += 1;
else
break;
}
str.clear();
str.append(f.buffered_data(), f.buffered_data() + i);
// Usage in filterlib is expected to retain quotes
// but yosys expects to get unquoted
#ifdef FILTERLIB
str = "\"" + str + "\"";
#endif
f.consume(i + 1);
return 'v';
}
// if it wasn't a string, perhaps it's a comment or a forward slash?
if (c == '/') {
c = f.get();
if (c == '*') { // start of '/*' block comment
int last_c = 0;
while (c > 0 && (last_c != '*' || c != '/')) {
last_c = c;
c = f.get();
if (c == '\n')
line++;
}
return lexer(str);
} else if (c == '/') { // start of '//' line comment
while (c > 0 && c != '\n')
c = f.get();
line++;
return lexer(str);
}
f.unget();
return '/'; // a single '/' charater.
}
// check for a backslash
if (c == '\\') {
c = f.get();
if (c == '\r')
c = f.get();
if (c == '\n') {
line++;
return lexer(str);
}
f.unget();
return '\\';
}
// check for a new line
if (c == '\n') {
line++;
return 'n';
}
// anything else, such as ';' will get passed
// through as literal items.
return c;
}
int LibertyParser::lexer(std::string &str)
{
int ret = lexer_inner(str);
// if (ret >= 32 && ret < 255) {
// fprintf(stdout, "LEX: ret >>%c<<\n", ret);
// } else if (ret == 'v') {
// fprintf(stdout, "LEX: ret v str %s\n", str.c_str());
// } else {
// fprintf(stdout, "LEX: ret %d\n", ret);
// }
return ret;
}
void LibertyParser::report_unexpected_token(int tok)
{
std::string eReport;
switch(tok)
{
case 'n':
error("Unexpected newline.");
break;
case '[':
case ']':
case '}':
case '{':
case '\"':
case ':':
eReport = "Unexpected '";
eReport += static_cast<char>(tok);
eReport += "'.";
error(eReport);
break;
case EOF:
error("Unexpected end of file");
break;
default:
eReport = "Unexpected token: ";
eReport += static_cast<char>(tok);
error(eReport);
}
}
// FIXME: the AST needs to be extended to store
// these vector ranges.
void LibertyParser::parse_vector_range(int tok)
{
// parse vector range [A] or [A:B]
std::string arg;
tok = lexer(arg);
if (tok != 'v')
{
// expected a vector array index
error("Expected a number.");
}
else
{
// fixme: check for number A
}
tok = lexer(arg);
// optionally check for : in case of [A:B]
// if it isn't we just expect ']'
// as we have [A]
if (tok == ':')
{
tok = lexer(arg);
if (tok != 'v')
{
// expected a vector array index
error("Expected a number.");
}
else
{
// fixme: check for number B
tok = lexer(arg);
}
}
// expect a closing bracket of array range
if (tok != ']')
{
error("Expected ']' on array range.");
}
}
// Consume into out_str any string-ish tokens, seperated with spaces
// to cope with abuse of the underdefined spec by real world PDKs
// enabled by proprietary implementations.
// Sorry.
int LibertyParser::consume_wrecked_str(int tok, std::string& out_str) {
std::string str = "";
while (tok != ';' && tok != EOF && tok != 'n') {
out_str += " ";
if (tok == 'v')
out_str += str;
else
out_str += tok;
tok = lexer(str);
}
if (tok == EOF)
error("wrecked string EOF");
return tok;
}
LibertyParser::ParseResult LibertyParser::try_parse(bool top_level, bool skip_all)
{
std::string str;
int tok = lexer(str);
// there are liberty files in the wild that
// have superfluous ';' at the end of
// a { ... }. We simply ignore a ';' here.
// and get to the next statement.
while ((tok == 'n') || (tok == ';'))
tok = lexer(str);
if (tok == EOF) {
if (top_level)
return ParseResult::closed();
report_unexpected_token(tok);
}
if (tok == '}')
return ParseResult::closed();
if (tok != 'v') {
report_unexpected_token(tok);
}
std::string id = str;
bool skip = skip_all || !filter.allows(id);
std::string value;
std::vector<std::string> args;
std::vector<LibertyAst *> children;
while (1)
{
tok = lexer(str);
// allow both ';' and new lines to
// terminate a statement.
if ((tok == ';') || (tok == 'n'))
break;
if (tok == ':' && value.empty()) {
tok = lexer(value);
if (tok == 'v') {
tok = lexer(str);
if (tok == '[') {
parse_vector_range(tok);
tok = lexer(str);
} else {
// Hack for when an expression string is unquoted
tok = consume_wrecked_str(tok, value);
}
} else if (tok == '(') {
// Hack for when an expression string is unquoted and starts with
// parentheses
tok = consume_wrecked_str(tok, value);
}
while (tok == '+' || tok == '-' || tok == '*' || tok == '/' || tok == '!') {
value += tok;
tok = lexer(str);
if (tok != 'v')
error();
value += str;
tok = lexer(str);
}
// In a liberty file, all key : value pairs should end in ';'
// However, there are some liberty files in the wild that
// just have a newline. We'll be kind and accept a newline
// instead of the ';' too..
if ((tok == ';') || (tok == 'n'))
break;
else
error();
continue;
}
if (tok == '(') {
while (1) {
std::string arg;
tok = lexer(arg);
if (tok == ',')
continue;
if (tok == ')')
break;
if (tok == '[')
{
parse_vector_range(tok);
continue;
}
if (tok == 'n')
continue;
if (tok != 'v') {
report_unexpected_token(tok);
}
args.push_back(std::move(arg));
}
continue;
}
if (tok == '{') {
bool terminated = false;
while (1) {
LibertyAst *child = parse(false, skip);
if (child == NULL) {
terminated = true;
break;
}
children.push_back(child);
}
if (!terminated) {
report_unexpected_token(EOF);
}
break;
}
report_unexpected_token(tok);
}
if (skip)
return ParseResult::skipped();
return ParseResult::node(new LibertyAst{std::move(id), std::move(value), std::move(args),
std::move(children), filter});
}
LibertyAst *LibertyParser::parse(bool top_level, bool skip_all)
{
while (1) {
ParseResult result = try_parse(top_level, skip_all);
// We got our statement, return it
if (result.kind == ParseResult::Node)
return result.ast;
// We didn't parse a statement, and there aren't any more, so we're done
if (result.kind == ParseResult::Closed)
return NULL;
// Otherwise, we skipped a node due to filtering, keep going
}
}
#ifndef FILTERLIB
void LibertyParser::error() const
{
log_error("Syntax error in liberty file on line %d.\n", line);
}
void LibertyParser::error(const std::string &str) const
{
std::stringstream ss;
ss << "Syntax error in liberty file on line " << line << ".\n";
ss << " " << str << "\n";
log_error("%s", ss.str());
}
#else
YS_ATTRIBUTE(weak)
void LibertyParser::error() const
{
fprintf(stderr, "Syntax error in liberty file on line %d.\n", line);
exit(1);
}
YS_ATTRIBUTE(weak)
void LibertyParser::error(const std::string &str) const
{
std::stringstream ss;
ss << "Syntax error in liberty file on line " << line << ".\n";
ss << " " << str << "\n";
printf("%s", ss.str().c_str());
exit(1);
}
/**** BEGIN: http://svn.clairexen.net/tools/trunk/examples/check.h ****/
#define CHECK_NV(result, check) \
do { \
auto _R = (result); \
if (!(_R check)) { \
fprintf(stderr, "Error from '%s' (%ld %s) in %s:%d.\n", \
#result, (long int)_R, #check, __FILE__, __LINE__); \
abort(); \
} \
} while(0)
#define CHECK_COND(result) \
do { \
if (!(result)) { \
fprintf(stderr, "Error from '%s' in %s:%d.\n", \
#result, __FILE__, __LINE__); \
abort(); \
} \
} while(0)
/**** END: http://svn.clairexen.net/tools/trunk/examples/check.h ****/
const LibertyAst *find_non_null(const LibertyAst *node, const char *name)
{
const LibertyAst *ret = node->find(name);
if (ret == NULL)
fprintf(stderr, "Error: expected to find `%s' node.\n", name);
return ret;
}
std::string func2vl(std::string str)
{
auto helper = LibertyExpression::Lexer(str);
return LibertyExpression::parse(helper).vlog_str();
}
std::string vlog_identifier(std::string str)
{
str.erase(std::remove(str.begin(), str.end(), '\"'), str.end());
return str;
}
void event2vl_wire(std::string &edge, LibertyExpression& parsed, const std::string& wire)
{
edge.clear();
if (parsed.kind == LibertyExpression::Kind::NOT) {
edge = "negedge " + wire;
// parsed = parsed.children[0];
} else {
edge = "posedge " + wire;
}
}
void event2vl(const LibertyAst *ast, std::string &edge, std::string &expr)
{
edge.clear();
expr.clear();
if (ast != NULL) {
auto helper = LibertyExpression::Lexer(ast->value);
auto parsed = LibertyExpression::parse(helper);
expr = parsed.vlog_str();
if (parsed.kind == LibertyExpression::Kind::NOT)
edge = "negedge " + parsed.children[0].vlog_str();
else
edge = "posedge " + parsed.vlog_str();
}
}
enum ClearPresetVar {
Error,
L,
H,
T,
X,
};
ClearPresetVar clear_preset_var(std::string type)
{
if (type.find('L') != std::string::npos) {
return ClearPresetVar::L;
}
if (type.find('H') != std::string::npos) {
return ClearPresetVar::H;
}
if (type.find('T') != std::string::npos) {
return ClearPresetVar::T;
}
if (type.find('X') != std::string::npos) {
return ClearPresetVar::X;
}
return ClearPresetVar::X;
}
void print_clear_preset_var(std::string var, ClearPresetVar type)
{
if (type == ClearPresetVar::L) {
printf(" %s <= 0;\n", var.c_str());
return;
}
if (type == ClearPresetVar::H) {
printf(" %s <= 1;\n", var.c_str());
return;
}
if (type == ClearPresetVar::T) {
printf(" %s <= ~%s;\n", var.c_str(), var.c_str());
return;
}
if (type == ClearPresetVar::X) {
printf(" %s <= 'bx;\n", var.c_str());
return;
}
}
struct FfEdge {
std::string edge;
std::string expr;
};
struct FfEdges {
FfEdge clock;
FfEdge clear;
FfEdge preset;
std::string edge;
void wired(FfEdge& edge, const LibertyAst* ast, const std::string& wire, const char* tag) {
auto* found = ast->find(tag);
if (!found)
return;
auto lexer = LibertyExpression::Lexer(found->value);
auto expr = LibertyExpression::parse(lexer);
event2vl_wire(edge.edge, expr, wire);
edge.expr = expr.vlog_str();
}
FfEdges(LibertyAst* child, const std::string& clear_wire, const std::string& preset_wire) {
wired(clear, child, clear_wire, "clear");
wired(preset, child, preset_wire, "preset");
event2vl(child->find("clocked_on"), clock.edge, clock.expr);
edge = "";
if (!clock.edge.empty())
edge += (edge.empty() ? "" : ", ") + clock.edge;
if (!clear.edge.empty())
edge += (edge.empty() ? "" : ", ") + clear.edge;
if (!preset.edge.empty())
edge += (edge.empty() ? "" : ", ") + preset.edge;
}
};
struct FfVar {
std::string var;
std::string edge;
FfEdge clear;
FfEdge preset;
// Value for both asserted
const char* clear_preset_var_name;
std::string next_state;
const char* else_prefix = "";
public:
void proc_header() {
printf(" always @(%s) begin\n", edge.c_str());
}
void proc_footer() {
if (*else_prefix)
printf(" end\n");
printf(" end\n");
}
void proc_cond(FfEdge& edge, const char* value) {
printf(" %sif (%s) begin\n", else_prefix, edge.expr.c_str());
printf(" %s <= %s;\n", var.c_str(), value);
printf(" end\n");
else_prefix = "else ";
}
void proc_cond_clear() { proc_cond(clear, "0"); }
void proc_cond_preset() { proc_cond(preset, "1"); }
void proc_next_state() {
if (*else_prefix)
printf(" %sbegin\n", else_prefix);
printf(" %s <= %s;\n", var.c_str(), next_state.c_str());
}
void proc(LibertyAst* child) {
else_prefix = "";
proc_header();
if (!clear.expr.empty() && !preset.expr.empty()) {
ClearPresetVar clear_preset = clear_preset_var(find_non_null(child, clear_preset_var_name)->value);
if (clear_preset == ClearPresetVar::L) {
proc_cond_clear();
proc_cond_preset();
proc_next_state();
proc_footer();
return;
} else if (clear_preset == ClearPresetVar::H) {
// Notice that preset and clear are swapped
proc_cond_preset();
proc_cond_clear();
proc_next_state();
proc_footer();
return;
} else {
// Boo, we have to emit non-synthesizable verilog
printf(" %sif ((%s) && (%s)) begin\n", else_prefix, clear.expr.c_str(), preset.expr.c_str());
print_clear_preset_var(var, clear_preset);
printf(" end\n");
else_prefix = "else ";
}
}
if (!clear.expr.empty()) {
proc_cond_clear();
}
if (!preset.expr.empty()) {
proc_cond_preset();
}
proc_next_state();
proc_footer();
}
};
void gen_verilogsim_cell(const LibertyAst *ast)
{
if (ast->find("statetable") != NULL)
return;
CHECK_NV(ast->args.size(), == 1);
auto module_name = vlog_identifier(ast->args[0]);
printf("module %s (", module_name.c_str());
bool first = true;
for (auto child : ast->children) {
if (child->id != "pin")
continue;
CHECK_NV(child->args.size(), == 1);
printf("%s%s", first ? "" : ", ", vlog_identifier(child->args[0]).c_str());
first = false;
}
printf(");\n");
for (auto child : ast->children) {
if (child->id != "ff" && child->id != "latch")
continue;
first = true;
std::string iq = "";
for (auto arg : child->args) {
if (first)
printf(" reg ");
printf("%s%s", first ? "" : ", ", vlog_identifier(arg).c_str());
if (first)
iq = vlog_identifier(arg);
first = false;
}
if (!first)
printf(";\n");
first = true;
for (auto gchild : child->children) {
if (gchild->id == "clear" || gchild->id == "preset") {
if (first)
printf(" wire ");
printf("%s%s_%s", first ? "" : ", ", iq.c_str(), gchild->id.c_str());
first = false;
}
}
if (!first)
printf(";\n");
}
for (auto child : ast->children) {
if (child->id != "pin")
continue;
CHECK_NV(child->args.size(), == 1);
const LibertyAst *dir = find_non_null(child, "direction");
const LibertyAst *func = child->find("function");
std::string var = vlog_identifier(child->args[0]);
printf(" %s %s;\n", dir->value.c_str(), var.c_str());
if (func != NULL)
printf(" assign %s = %s; // %s\n", var.c_str(), func2vl(func->value).c_str(), func->value.c_str());
}
for (auto child : ast->children)
{
if (child->id != "ff" || child->args.size() != 2)
continue;
auto iq_name = vlog_identifier(child->args[0]);
auto clear_wire = iq_name + "_clear";
auto preset_wire = iq_name + "_preset";
FfEdges edges(child, clear_wire, preset_wire);
if (edges.edge.empty())
continue;
std::string next_state = func2vl(find_non_null(child, "next_state")->value);
std::string not_next_state = std::string("~(") + next_state + ")";
if (edges.clear.expr.length())
std::swap(clear_wire, edges.clear.expr);
if (edges.preset.expr.length())
std::swap(preset_wire, edges.preset.expr);
auto iq = FfVar {
.var = vlog_identifier(child->args[0]),
.edge = edges.edge,
.clear = edges.clear,
.preset = edges.preset,
.clear_preset_var_name = "clear_preset_var1",
.next_state = next_state,
};
auto iqn = FfVar {
.var = vlog_identifier(child->args[1]),
.edge = edges.edge,
// Swapped clear and preset
.clear = edges.preset,
.preset = edges.clear,
.clear_preset_var_name = "clear_preset_var2",
.next_state = not_next_state,
};
iq.proc(child);
iqn.proc(child);
if (edges.clear.expr.length())
printf(" assign %s = %s;\n", edges.clear.expr.c_str(), clear_wire.c_str());
if (edges.preset.expr.length())
printf(" assign %s = %s;\n", edges.preset.expr.c_str(), preset_wire.c_str());
}
for (auto child : ast->children)
{
if (child->id != "latch" || child->args.size() != 2)
continue;
std::string iq_var = vlog_identifier(child->args[0]);
std::string iqn_var = vlog_identifier(child->args[1]);
std::string enable_edge, enable_expr;
event2vl(child->find("enable"), enable_edge, enable_expr);
std::string clear_edge, clear_expr;
event2vl(child->find("clear"), clear_edge, clear_expr);
std::string preset_edge, preset_expr;
event2vl(child->find("preset"), preset_edge, preset_expr);
printf(" always @* begin\n");
const char *else_prefix = "";
if (!clear_expr.empty() && !preset_expr.empty()) {
printf(" %sif ((%s) && (%s)) begin\n", else_prefix, clear_expr.c_str(), preset_expr.c_str());
print_clear_preset_var(iq_var, clear_preset_var(find_non_null(child, "clear_preset_var1")->value));
print_clear_preset_var(iqn_var, clear_preset_var(find_non_null(child, "clear_preset_var2")->value));
printf(" end\n");
else_prefix = "else ";
}
if (!clear_expr.empty()) {
printf(" %sif (%s) begin\n", else_prefix, clear_expr.c_str());
printf(" %s <= 0;\n", iq_var.c_str());
printf(" %s <= 1;\n", iqn_var.c_str());
printf(" end\n");
else_prefix = "else ";
}
if (!preset_expr.empty()) {
printf(" %sif (%s) begin\n", else_prefix, preset_expr.c_str());
printf(" %s <= 1;\n", iq_var.c_str());
printf(" %s <= 0;\n", iqn_var.c_str());
printf(" end\n");
else_prefix = "else ";
}
if (!enable_expr.empty()) {
printf(" %sif (%s) begin\n", else_prefix, enable_expr.c_str());
std::string expr = find_non_null(child, "data_in")->value;
printf(" %s <= %s;\n", iq_var.c_str(), func2vl(expr).c_str());
printf(" %s <= ~(%s);\n", iqn_var.c_str(), func2vl(expr).c_str());
printf(" end\n");
else_prefix = "else ";
}
printf(" end\n");
}
printf("endmodule\n");
}
void gen_verilogsim(const LibertyAst *ast)
{
CHECK_COND(ast->id == "library");
for (auto child : ast->children)
if (child->id == "cell" && !child->find("dont_use"))
gen_verilogsim_cell(child);
}
void usage()
{
fprintf(stderr, "Usage: filterlib [rules-file [liberty-file]]\n");
fprintf(stderr, " or: filterlib -verilogsim [liberty-file]\n");
exit(1);
}
int main(int argc, char **argv)
{
bool flag_verilogsim = false;
std::set<std::string> whitelist, blacklist;
if (argc > 3)
usage();
if (argc > 1)
{
if (!strcmp(argv[1], "-verilogsim"))
flag_verilogsim = true;
if (!strcmp(argv[1], "-") || !strcmp(argv[1], "-verilogsim"))
{
whitelist.insert("/library");
whitelist.insert("/library/cell");
whitelist.insert("/library/cell/area");
whitelist.insert("/library/cell/cell_footprint");
whitelist.insert("/library/cell/dont_touch");
whitelist.insert("/library/cell/dont_use");
whitelist.insert("/library/cell/ff");
whitelist.insert("/library/cell/ff/*");
whitelist.insert("/library/cell/latch");
whitelist.insert("/library/cell/latch/*");
whitelist.insert("/library/cell/pin");
whitelist.insert("/library/cell/pin/clock");
whitelist.insert("/library/cell/pin/direction");
whitelist.insert("/library/cell/pin/driver_type");
whitelist.insert("/library/cell/pin/function");
whitelist.insert("/library/cell/pin_opposite");
whitelist.insert("/library/cell/pin/state_function");
whitelist.insert("/library/cell/pin/three_state");
whitelist.insert("/library/cell/statetable");
whitelist.insert("/library/cell/statetable/*");
}
else
{
FILE *f = fopen(argv[1], "r");
if (f == NULL) {
fprintf(stderr, "Can't open rules file `%s'.\n", argv[1]);
usage();
}
char buffer[1024];
while (fgets(buffer, 1024, f) != NULL)
{
char mode = 0;
std::string id;
for (char *p = buffer; *p; p++)
{
if (*p == '-' || *p == '+') {
if (mode != 0)
goto syntax_error;
mode = *p;
continue;
}
if (*p == ' ' || *p == '\t' || *p == '\r' || *p == '\n' || *p == '#') {
if (!id.empty()) {
if (mode == '-')
blacklist.insert(id);
else
if (mode == '+')
whitelist.insert(id);
else
goto syntax_error;
}
id.clear();
if (*p == '#')
break;
continue;
}
id += *p;
continue;
syntax_error:
fprintf(stderr, "Syntax error in rules file:\n%s", buffer);
exit(1);
}
}
}
}
std::istream *f = &std::cin;
if (argc == 3) {
std::ifstream *ff = new std::ifstream;
ff->open(argv[2]);
if (ff->fail()) {
delete ff;
fprintf(stderr, "Can't open liberty file `%s'.\n", argv[2]);
usage();
}
f = ff;
}
LibertyParser parser(*f);
if (parser.ast) {
if (flag_verilogsim)
gen_verilogsim(parser.ast);
else
parser.ast->dump(stdout, blacklist, whitelist);
}
if (argc == 3)
delete f;
return 0;
}
#endif
|