CIRCT  20.0.0git
HWAttributes.cpp
Go to the documentation of this file.
1 //===- HWAttributes.cpp - Implement HW attributes -------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
11 #include "circt/Dialect/HW/HWOps.h"
13 #include "circt/Support/LLVM.h"
14 #include "mlir/IR/Diagnostics.h"
15 #include "mlir/IR/DialectImplementation.h"
16 #include "llvm/ADT/SmallString.h"
17 #include "llvm/ADT/StringExtras.h"
18 #include "llvm/ADT/TypeSwitch.h"
19 #include "llvm/Support/FileSystem.h"
20 #include "llvm/Support/Path.h"
21 
22 using namespace circt;
23 using namespace circt::hw;
24 using mlir::TypedAttr;
25 
26 // Internal method used for .mlir file parsing, defined below.
27 static Attribute parseParamExprWithOpcode(StringRef opcode, DialectAsmParser &p,
28  Type type);
29 
30 //===----------------------------------------------------------------------===//
31 // ODS Boilerplate
32 //===----------------------------------------------------------------------===//
33 
34 #define GET_ATTRDEF_CLASSES
35 #include "circt/Dialect/HW/HWAttributes.cpp.inc"
36 
37 void HWDialect::registerAttributes() {
38  addAttributes<
39 #define GET_ATTRDEF_LIST
40 #include "circt/Dialect/HW/HWAttributes.cpp.inc"
41  >();
42 }
43 
44 Attribute HWDialect::parseAttribute(DialectAsmParser &p, Type type) const {
45  StringRef attrName;
46  Attribute attr;
47  auto parseResult = generatedAttributeParser(p, &attrName, type, attr);
48  if (parseResult.has_value())
49  return attr;
50 
51  // Parse "#hw.param.expr.add" as ParamExprAttr.
52  if (attrName.starts_with(ParamExprAttr::getMnemonic())) {
53  auto string = attrName.drop_front(ParamExprAttr::getMnemonic().size());
54  if (string.front() == '.')
55  return parseParamExprWithOpcode(string.drop_front(), p, type);
56  }
57 
58  p.emitError(p.getNameLoc(), "Unexpected hw attribute '" + attrName + "'");
59  return {};
60 }
61 
62 void HWDialect::printAttribute(Attribute attr, DialectAsmPrinter &p) const {
63  if (succeeded(generatedAttributePrinter(attr, p)))
64  return;
65  llvm_unreachable("Unexpected attribute");
66 }
67 
68 //===----------------------------------------------------------------------===//
69 // OutputFileAttr
70 //===----------------------------------------------------------------------===//
71 
72 static std::string canonicalizeFilename(const Twine &directory,
73  const Twine &filename) {
74 
75  // Convert the filename to a native style path.
76  SmallString<128> nativeFilename;
77  llvm::sys::path::native(filename, nativeFilename);
78 
79  // If the filename is an absolute path, ignore the directory.
80  // e.g. `directory/` + `/etc/filename` -> `/etc/filename`.
81  if (llvm::sys::path::is_absolute(nativeFilename))
82  return std::string(nativeFilename);
83 
84  // Convert the directory to a native style path.
85  SmallString<128> nativeDirectory;
86  llvm::sys::path::native(directory, nativeDirectory);
87 
88  // If the filename component is empty, then ensure that the path ends in a
89  // separator and return it.
90  // e.g. `directory` + `` -> `directory/`.
91  auto separator = llvm::sys::path::get_separator();
92  if (nativeFilename.empty() && !nativeDirectory.ends_with(separator)) {
93  nativeDirectory += separator;
94  return std::string(nativeDirectory);
95  }
96 
97  // Append the directory and filename together.
98  // e.g. `/tmp/` + `out/filename` -> `/tmp/out/filename`.
99  SmallString<128> fullPath;
100  llvm::sys::path::append(fullPath, nativeDirectory, nativeFilename);
101  return std::string(fullPath);
102 }
103 
104 OutputFileAttr OutputFileAttr::getFromFilename(MLIRContext *context,
105  const Twine &filename,
106  bool excludeFromFileList,
107  bool includeReplicatedOps) {
108  return OutputFileAttr::getFromDirectoryAndFilename(
109  context, "", filename, excludeFromFileList, includeReplicatedOps);
110 }
111 
112 OutputFileAttr OutputFileAttr::getFromDirectoryAndFilename(
113  MLIRContext *context, const Twine &directory, const Twine &filename,
114  bool excludeFromFileList, bool includeReplicatedOps) {
115  auto canonicalized = canonicalizeFilename(directory, filename);
116  return OutputFileAttr::get(StringAttr::get(context, canonicalized),
117  BoolAttr::get(context, excludeFromFileList),
118  BoolAttr::get(context, includeReplicatedOps));
119 }
120 
121 OutputFileAttr OutputFileAttr::getAsDirectory(MLIRContext *context,
122  const Twine &directory,
123  bool excludeFromFileList,
124  bool includeReplicatedOps) {
125  return getFromDirectoryAndFilename(context, directory, "",
126  excludeFromFileList, includeReplicatedOps);
127 }
128 
129 bool OutputFileAttr::isDirectory() {
130  return getFilename().getValue().ends_with(llvm::sys::path::get_separator());
131 }
132 
133 StringRef OutputFileAttr::getDirectory() {
134  auto dir = getFilename().getValue();
135  for (unsigned i = 0, e = dir.size(); i < e; ++i) {
136  if (dir.ends_with(llvm::sys::path::get_separator()))
137  break;
138  dir = dir.drop_back();
139  }
140  return dir;
141 }
142 
143 /// Option ::= 'excludeFromFileList' | 'includeReplicatedOp'
144 /// OutputFileAttr ::= 'output_file<' directory ',' name (',' Option)* '>'
145 Attribute OutputFileAttr::parse(AsmParser &p, Type type) {
146  StringAttr filename;
147  if (p.parseLess() || p.parseAttribute<StringAttr>(filename))
148  return Attribute();
149 
150  // Parse the additional keyword attributes. Its easier to let people specify
151  // these more than once than to detect the problem and do something about it.
152  bool excludeFromFileList = false;
153  bool includeReplicatedOps = false;
154  while (true) {
155  if (p.parseOptionalComma())
156  break;
157  if (!p.parseOptionalKeyword("excludeFromFileList"))
158  excludeFromFileList = true;
159  else if (!p.parseKeyword("includeReplicatedOps",
160  "or 'excludeFromFileList'"))
161  includeReplicatedOps = true;
162  else
163  return Attribute();
164  }
165 
166  if (p.parseGreater())
167  return Attribute();
168 
169  return OutputFileAttr::getFromFilename(p.getContext(), filename.getValue(),
170  excludeFromFileList,
171  includeReplicatedOps);
172 }
173 
174 void OutputFileAttr::print(AsmPrinter &p) const {
175  p << "<" << getFilename();
176  if (getExcludeFromFilelist().getValue())
177  p << ", excludeFromFileList";
178  if (getIncludeReplicatedOps().getValue())
179  p << ", includeReplicatedOps";
180  p << ">";
181 }
182 
183 //===----------------------------------------------------------------------===//
184 // EnumFieldAttr
185 //===----------------------------------------------------------------------===//
186 
187 Attribute EnumFieldAttr::parse(AsmParser &p, Type) {
188  StringRef field;
189  Type type;
190  if (p.parseLess() || p.parseKeyword(&field) || p.parseComma() ||
191  p.parseType(type) || p.parseGreater())
192  return Attribute();
193  return EnumFieldAttr::get(p.getEncodedSourceLoc(p.getCurrentLocation()),
194  StringAttr::get(p.getContext(), field), type);
195 }
196 
197 void EnumFieldAttr::print(AsmPrinter &p) const {
198  p << "<" << getField().getValue() << ", ";
199  p.printType(getType().getValue());
200  p << ">";
201 }
202 
203 EnumFieldAttr EnumFieldAttr::get(Location loc, StringAttr value,
204  mlir::Type type) {
205  if (!hw::isHWEnumType(type))
206  emitError(loc) << "expected enum type";
207 
208  // Check whether the provided value is a member of the enum type.
209  EnumType enumType = llvm::cast<EnumType>(getCanonicalType(type));
210  if (!enumType.contains(value.getValue())) {
211  emitError(loc) << "enum value '" << value.getValue()
212  << "' is not a member of enum type " << enumType;
213  return nullptr;
214  }
215 
216  return Base::get(value.getContext(), value, TypeAttr::get(type));
217 }
218 
219 //===----------------------------------------------------------------------===//
220 // InnerRefAttr
221 //===----------------------------------------------------------------------===//
222 
223 Attribute InnerRefAttr::parse(AsmParser &p, Type type) {
224  SymbolRefAttr attr;
225  if (p.parseLess() || p.parseAttribute<SymbolRefAttr>(attr) ||
226  p.parseGreater())
227  return Attribute();
228  if (attr.getNestedReferences().size() != 1)
229  return Attribute();
230  return InnerRefAttr::get(attr.getRootReference(), attr.getLeafReference());
231 }
232 
233 static void printSymbolName(AsmPrinter &p, StringAttr sym) {
234  if (sym)
235  p.printSymbolName(sym.getValue());
236  else
237  p.printSymbolName({});
238 }
239 
240 void InnerRefAttr::print(AsmPrinter &p) const {
241  p << "<";
242  printSymbolName(p, getModule());
243  p << "::";
244  printSymbolName(p, getName());
245  p << ">";
246 }
247 
248 //===----------------------------------------------------------------------===//
249 // InnerSymAttr and InnerSymPropertiesAttr
250 //===----------------------------------------------------------------------===//
251 
252 Attribute InnerSymPropertiesAttr::parse(AsmParser &parser, Type type) {
253  StringAttr name;
254  NamedAttrList dummyList;
255  int64_t fieldId = 0;
256  if (parser.parseLess() || parser.parseSymbolName(name, "name", dummyList) ||
257  parser.parseComma() || parser.parseInteger(fieldId) ||
258  parser.parseComma())
259  return Attribute();
260 
261  StringRef visibility;
262  auto loc = parser.getCurrentLocation();
263  if (parser.parseOptionalKeyword(&visibility,
264  {"public", "private", "nested"})) {
265  parser.emitError(loc, "expected 'public', 'private', or 'nested'");
266  return Attribute();
267  }
268  auto visibilityAttr = parser.getBuilder().getStringAttr(visibility);
269 
270  if (parser.parseGreater())
271  return Attribute();
272 
273  return parser.getChecked<InnerSymPropertiesAttr>(parser.getContext(), name,
274  fieldId, visibilityAttr);
275 }
276 
277 void InnerSymPropertiesAttr::print(AsmPrinter &odsPrinter) const {
278  odsPrinter << "<@" << getName().getValue() << "," << getFieldID() << ","
279  << getSymVisibility().getValue() << ">";
280 }
281 
282 LogicalResult InnerSymPropertiesAttr::verify(
283  ::llvm::function_ref<::mlir::InFlightDiagnostic()> emitError,
284  ::mlir::StringAttr name, uint64_t fieldID,
285  ::mlir::StringAttr symVisibility) {
286  if (!name || name.getValue().empty())
287  return emitError() << "inner symbol cannot have empty name";
288  return success();
289 }
290 
291 StringAttr InnerSymAttr::getSymIfExists(uint64_t fieldId) const {
292  const auto *it =
293  llvm::find_if(getImpl()->props, [&](const InnerSymPropertiesAttr &p) {
294  return p.getFieldID() == fieldId;
295  });
296  if (it != getProps().end())
297  return it->getName();
298  return {};
299 }
300 
301 InnerSymAttr InnerSymAttr::erase(uint64_t fieldID) const {
302  SmallVector<InnerSymPropertiesAttr> syms(getProps());
303  const auto *it = llvm::find_if(syms, [fieldID](InnerSymPropertiesAttr p) {
304  return p.getFieldID() == fieldID;
305  });
306  assert(it != syms.end());
307  syms.erase(it);
308  return InnerSymAttr::get(getContext(), syms);
309 }
310 
311 LogicalResult InnerSymAttr::walkSymbols(
312  llvm::function_ref<LogicalResult(StringAttr)> callback) const {
313  for (auto p : getImpl()->props)
314  if (callback(p.getName()).failed())
315  return failure();
316  return success();
317 }
318 
319 Attribute InnerSymAttr::parse(AsmParser &parser, Type type) {
320  StringAttr sym;
321  NamedAttrList dummyList;
322  SmallVector<InnerSymPropertiesAttr, 4> names;
323  if (!parser.parseOptionalSymbolName(sym, "dummy", dummyList)) {
324  auto prop = parser.getChecked<InnerSymPropertiesAttr>(
325  parser.getContext(), sym, 0,
326  StringAttr::get(parser.getContext(), "public"));
327  if (!prop)
328  return {};
329  names.push_back(prop);
330  } else if (parser.parseCommaSeparatedList(
331  OpAsmParser::Delimiter::Square, [&]() -> ParseResult {
332  InnerSymPropertiesAttr prop;
333  if (parser.parseCustomAttributeWithFallback(
334  prop, mlir::Type{}, "dummy", dummyList))
335  return failure();
336 
337  names.push_back(prop);
338 
339  return success();
340  }))
341  return Attribute();
342 
343  std::sort(names.begin(), names.end(),
344  [&](InnerSymPropertiesAttr a, InnerSymPropertiesAttr b) {
345  return a.getFieldID() < b.getFieldID();
346  });
347 
348  return InnerSymAttr::get(parser.getContext(), names);
349 }
350 
351 void InnerSymAttr::print(AsmPrinter &odsPrinter) const {
352 
353  auto props = getProps();
354  if (props.size() == 1 && props[0].getSymVisibility().getValue() == "public" &&
355  props[0].getFieldID() == 0) {
356  odsPrinter << "@" << props[0].getName().getValue();
357  return;
358  }
359  auto names = props.vec();
360 
361  std::sort(names.begin(), names.end(),
362  [&](InnerSymPropertiesAttr a, InnerSymPropertiesAttr b) {
363  return a.getFieldID() < b.getFieldID();
364  });
365  odsPrinter << "[";
366  llvm::interleaveComma(names, odsPrinter, [&](InnerSymPropertiesAttr attr) {
367  attr.print(odsPrinter);
368  });
369  odsPrinter << "]";
370 }
371 
372 //===----------------------------------------------------------------------===//
373 // ParamDeclAttr
374 //===----------------------------------------------------------------------===//
375 
376 Attribute ParamDeclAttr::parse(AsmParser &p, Type trailing) {
377  std::string name;
378  Type type;
379  Attribute value;
380  // < "FOO" : i32 > : i32
381  // < "FOO" : i32 = 0 > : i32
382  // < "FOO" : none >
383  if (p.parseLess() || p.parseString(&name) || p.parseColonType(type))
384  return Attribute();
385 
386  if (succeeded(p.parseOptionalEqual())) {
387  if (p.parseAttribute(value, type))
388  return Attribute();
389  }
390 
391  if (p.parseGreater())
392  return Attribute();
393 
394  if (value)
395  return ParamDeclAttr::get(p.getContext(),
396  p.getBuilder().getStringAttr(name), type, value);
397  return ParamDeclAttr::get(name, type);
398 }
399 
400 void ParamDeclAttr::print(AsmPrinter &p) const {
401  p << "<" << getName() << ": " << getType();
402  if (getValue()) {
403  p << " = ";
404  p.printAttributeWithoutType(getValue());
405  }
406  p << ">";
407 }
408 
409 //===----------------------------------------------------------------------===//
410 // ParamDeclRefAttr
411 //===----------------------------------------------------------------------===//
412 
413 Attribute ParamDeclRefAttr::parse(AsmParser &p, Type type) {
414  StringAttr name;
415  if (p.parseLess() || p.parseAttribute(name) || p.parseGreater() ||
416  (!type && (p.parseColon() || p.parseType(type))))
417  return Attribute();
418 
419  return ParamDeclRefAttr::get(name, type);
420 }
421 
422 void ParamDeclRefAttr::print(AsmPrinter &p) const {
423  p << "<" << getName() << ">";
424 }
425 
426 //===----------------------------------------------------------------------===//
427 // ParamVerbatimAttr
428 //===----------------------------------------------------------------------===//
429 
430 Attribute ParamVerbatimAttr::parse(AsmParser &p, Type type) {
431  StringAttr text;
432  if (p.parseLess() || p.parseAttribute(text) || p.parseGreater() ||
433  (!type && (p.parseColon() || p.parseType(type))))
434  return Attribute();
435 
436  return ParamVerbatimAttr::get(p.getContext(), text, type);
437 }
438 
439 void ParamVerbatimAttr::print(AsmPrinter &p) const {
440  p << "<" << getValue() << ">";
441 }
442 
443 //===----------------------------------------------------------------------===//
444 // ParamExprAttr
445 //===----------------------------------------------------------------------===//
446 
447 /// Given a binary function, if the two operands are known constant integers,
448 /// use the specified fold function to compute the result.
449 static TypedAttr foldBinaryOp(
450  ArrayRef<TypedAttr> operands,
451  llvm::function_ref<APInt(const APInt &, const APInt &)> calculate) {
452  assert(operands.size() == 2 && "binary operator always has two operands");
453  if (auto lhs = dyn_cast<IntegerAttr>(operands[0]))
454  if (auto rhs = dyn_cast<IntegerAttr>(operands[1]))
455  return IntegerAttr::get(lhs.getType(),
456  calculate(lhs.getValue(), rhs.getValue()));
457  return {};
458 }
459 
460 /// Given a unary function, if the operand is a known constant integer,
461 /// use the specified fold function to compute the result.
462 static TypedAttr
463 foldUnaryOp(ArrayRef<TypedAttr> operands,
464  llvm::function_ref<APInt(const APInt &)> calculate) {
465  assert(operands.size() == 1 && "unary operator always has one operand");
466  if (auto intAttr = dyn_cast<IntegerAttr>(operands[0]))
467  return IntegerAttr::get(intAttr.getType(), calculate(intAttr.getValue()));
468  return {};
469 }
470 
471 /// If the specified attribute is a ParamExprAttr with the specified opcode,
472 /// return it. Otherwise return null.
473 static ParamExprAttr dyn_castPE(PEO opcode, Attribute value) {
474  if (auto expr = dyn_cast<ParamExprAttr>(value))
475  if (expr.getOpcode() == opcode)
476  return expr;
477  return {};
478 }
479 
480 /// This implements a < comparison for two operands to an associative operation
481 /// imposing an ordering upon them.
482 ///
483 /// The ordering provided puts more complex things to the start of the list,
484 /// from left to right:
485 /// expressions :: verbatims :: decl.refs :: constant
486 ///
487 static bool paramExprOperandSortPredicate(Attribute lhs, Attribute rhs) {
488  // Simplify the code below - we never have to care about exactly equal values.
489  if (lhs == rhs)
490  return false;
491 
492  // All expressions are "less than" a constant, since they appear on the right.
493  if (isa<IntegerAttr>(rhs)) {
494  // We don't bother to order constants w.r.t. each other since they will be
495  // folded - they can all compare equal.
496  return !isa<IntegerAttr>(lhs);
497  }
498  if (isa<IntegerAttr>(lhs))
499  return false;
500 
501  // Next up are named parameters.
502  if (auto rhsParam = dyn_cast<ParamDeclRefAttr>(rhs)) {
503  // Parameters are sorted lexically w.r.t. each other.
504  if (auto lhsParam = dyn_cast<ParamDeclRefAttr>(lhs))
505  return lhsParam.getName().getValue() < rhsParam.getName().getValue();
506  // They otherwise appear on the right of other things.
507  return true;
508  }
509  if (isa<ParamDeclRefAttr>(lhs))
510  return false;
511 
512  // Next up are verbatim parameters.
513  if (auto rhsParam = dyn_cast<ParamVerbatimAttr>(rhs)) {
514  // Verbatims are sorted lexically w.r.t. each other.
515  if (auto lhsParam = dyn_cast<ParamVerbatimAttr>(lhs))
516  return lhsParam.getValue().getValue() < rhsParam.getValue().getValue();
517  // They otherwise appear on the right of other things.
518  return true;
519  }
520  if (isa<ParamVerbatimAttr>(lhs))
521  return false;
522 
523  // The only thing left are nested expressions.
524  auto lhsExpr = cast<ParamExprAttr>(lhs), rhsExpr = cast<ParamExprAttr>(rhs);
525  // Sort by the string form of the opcode, e.g. add, .. mul,... then xor.
526  if (lhsExpr.getOpcode() != rhsExpr.getOpcode())
527  return stringifyPEO(lhsExpr.getOpcode()) <
528  stringifyPEO(rhsExpr.getOpcode());
529 
530  // If they are the same opcode, then sort by arity: more complex to the left.
531  ArrayRef<TypedAttr> lhsOperands = lhsExpr.getOperands(),
532  rhsOperands = rhsExpr.getOperands();
533  if (lhsOperands.size() != rhsOperands.size())
534  return lhsOperands.size() > rhsOperands.size();
535 
536  // We know the two subexpressions are different (they'd otherwise be pointer
537  // equivalent) so just go compare all of the elements.
538  for (size_t i = 0, e = lhsOperands.size(); i != e; ++i) {
539  if (paramExprOperandSortPredicate(lhsOperands[i], rhsOperands[i]))
540  return true;
541  if (paramExprOperandSortPredicate(rhsOperands[i], lhsOperands[i]))
542  return false;
543  }
544 
545  llvm_unreachable("expressions should never be equivalent");
546  return false;
547 }
548 
549 /// Given a fully associative variadic integer operation, constant fold any
550 /// constant operands and move them to the right. If the whole expression is
551 /// constant, then return that, otherwise update the operands list.
552 static TypedAttr simplifyAssocOp(
553  PEO opcode, SmallVector<TypedAttr, 4> &operands,
554  llvm::function_ref<APInt(const APInt &, const APInt &)> calculateFn,
555  llvm::function_ref<bool(const APInt &)> identityConstantFn,
556  llvm::function_ref<bool(const APInt &)> destructiveConstantFn = {}) {
557  auto type = operands[0].getType();
558  assert(isHWIntegerType(type));
559  if (operands.size() == 1)
560  return operands[0];
561 
562  // Flatten any of the same operation into the operand list:
563  // `(add x, (add y, z))` => `(add x, y, z)`.
564  for (size_t i = 0, e = operands.size(); i != e; ++i) {
565  if (auto subexpr = dyn_castPE(opcode, operands[i])) {
566  std::swap(operands[i], operands.back());
567  operands.pop_back();
568  --e;
569  --i;
570  operands.append(subexpr.getOperands().begin(),
571  subexpr.getOperands().end());
572  }
573  }
574 
575  // Impose an ordering on the operands, pushing subexpressions to the left and
576  // constants to the right, with verbatims and parameters in the middle - but
577  // predictably ordered w.r.t. each other.
578  llvm::stable_sort(operands, paramExprOperandSortPredicate);
579 
580  // Merge any constants, they will appear at the back of the operand list now.
581  if (isa<IntegerAttr>(operands.back())) {
582  while (operands.size() >= 2 &&
583  isa<IntegerAttr>(operands[operands.size() - 2])) {
584  APInt c1 = cast<IntegerAttr>(operands.pop_back_val()).getValue();
585  APInt c2 = cast<IntegerAttr>(operands.pop_back_val()).getValue();
586  auto resultConstant = IntegerAttr::get(type, calculateFn(c1, c2));
587  operands.push_back(resultConstant);
588  }
589 
590  auto resultCst = cast<IntegerAttr>(operands.back());
591 
592  // If the resulting constant is the destructive constant (e.g. `x*0`), then
593  // return it.
594  if (destructiveConstantFn && destructiveConstantFn(resultCst.getValue()))
595  return resultCst;
596 
597  // Remove the constant back to our operand list if it is the identity
598  // constant for this operator (e.g. `x*1`) and there are other operands.
599  if (identityConstantFn(resultCst.getValue()) && operands.size() != 1)
600  operands.pop_back();
601  }
602 
603  return operands.size() == 1 ? operands[0] : TypedAttr();
604 }
605 
606 /// Analyze an operand to an add. If it is a multiplication by a constant (e.g.
607 /// `(a*b*42)` then split it into the non-constant and the constant portions
608 /// (e.g. `a*b` and `42`). Otherwise return the operand as the first value and
609 /// null as the second (standin for "multiplication by 1").
610 static std::pair<TypedAttr, TypedAttr> decomposeAddend(TypedAttr operand) {
611  if (auto mul = dyn_castPE(PEO::Mul, operand))
612  if (auto cst = dyn_cast<IntegerAttr>(mul.getOperands().back())) {
613  auto nonCst = ParamExprAttr::get(PEO::Mul, mul.getOperands().drop_back());
614  return {nonCst, cst};
615  }
616  return {operand, TypedAttr()};
617 }
618 
619 static TypedAttr getOneOfType(Type type) {
620  return IntegerAttr::get(type, APInt(type.getIntOrFloatBitWidth(), 1));
621 }
622 
623 static TypedAttr simplifyAdd(SmallVector<TypedAttr, 4> &operands) {
624  if (auto result = simplifyAssocOp(
625  PEO::Add, operands, [](auto a, auto b) { return a + b; },
626  /*identityCst*/ [](auto cst) { return cst.isZero(); }))
627  return result;
628 
629  // Canonicalize the add by splitting all addends into their variable and
630  // constant factors.
631  SmallVector<std::pair<TypedAttr, TypedAttr>> decomposedOperands;
632  llvm::SmallDenseSet<TypedAttr> nonConstantParts;
633  for (auto &op : operands) {
634  decomposedOperands.push_back(decomposeAddend(op));
635 
636  // Keep track of non-constant parts we've already seen. If we see multiple
637  // uses of the same value, then we can fold them together with a multiply.
638  // This handles things like `(a+b+a)` => `(a*2 + b)` and `(a*2 + b + a)` =>
639  // `(a*3 + b)`.
640  if (!nonConstantParts.insert(decomposedOperands.back().first).second) {
641  // The thing we multiply will be the common expression.
642  TypedAttr mulOperand = decomposedOperands.back().first;
643 
644  // Find the index of the first occurrence.
645  size_t i = 0;
646  while (decomposedOperands[i].first != mulOperand)
647  ++i;
648  // Remove both occurrences from the operand list.
649  operands.erase(operands.begin() + (&op - &operands[0]));
650  operands.erase(operands.begin() + i);
651 
652  auto type = mulOperand.getType();
653  auto c1 = decomposedOperands[i].second,
654  c2 = decomposedOperands.back().second;
655  // Fill in missing constant multiplicands with 1.
656  if (!c1)
657  c1 = getOneOfType(type);
658  if (!c2)
659  c2 = getOneOfType(type);
660  // Re-add the "a"*(c1+c2) expression to the operand list and
661  // re-canonicalize.
662  auto constant = ParamExprAttr::get(PEO::Add, c1, c2);
663  auto mulCst = ParamExprAttr::get(PEO::Mul, mulOperand, constant);
664  operands.push_back(mulCst);
665  return ParamExprAttr::get(PEO::Add, operands);
666  }
667  }
668 
669  return {};
670 }
671 
672 static TypedAttr simplifyMul(SmallVector<TypedAttr, 4> &operands) {
673  if (auto result = simplifyAssocOp(
674  PEO::Mul, operands, [](auto a, auto b) { return a * b; },
675  /*identityCst*/ [](auto cst) { return cst.isOne(); },
676  /*destructiveCst*/ [](auto cst) { return cst.isZero(); }))
677  return result;
678 
679  // We always build a sum-of-products representation, so if we see an addition
680  // as a subexpr, we need to pull it out: (a+b)*c*d ==> (a*c*d + b*c*d).
681  for (size_t i = 0, e = operands.size(); i != e; ++i) {
682  if (auto subexpr = dyn_castPE(PEO::Add, operands[i])) {
683  // Pull the `c*d` operands out - it is whatever operands remain after
684  // removing the `(a+b)` term.
685  SmallVector<TypedAttr> mulOperands(operands.begin(), operands.end());
686  mulOperands.erase(mulOperands.begin() + i);
687 
688  // Build each add operand.
689  SmallVector<TypedAttr> addOperands;
690  for (auto addOperand : subexpr.getOperands()) {
691  mulOperands.push_back(addOperand);
692  addOperands.push_back(ParamExprAttr::get(PEO::Mul, mulOperands));
693  mulOperands.pop_back();
694  }
695  // Canonicalize and form the add expression.
696  return ParamExprAttr::get(PEO::Add, addOperands);
697  }
698  }
699 
700  return {};
701 }
702 static TypedAttr simplifyAnd(SmallVector<TypedAttr, 4> &operands) {
703  return simplifyAssocOp(
704  PEO::And, operands, [](auto a, auto b) { return a & b; },
705  /*identityCst*/ [](auto cst) { return cst.isAllOnes(); },
706  /*destructiveCst*/ [](auto cst) { return cst.isZero(); });
707 }
708 
709 static TypedAttr simplifyOr(SmallVector<TypedAttr, 4> &operands) {
710  return simplifyAssocOp(
711  PEO::Or, operands, [](auto a, auto b) { return a | b; },
712  /*identityCst*/ [](auto cst) { return cst.isZero(); },
713  /*destructiveCst*/ [](auto cst) { return cst.isAllOnes(); });
714 }
715 
716 static TypedAttr simplifyXor(SmallVector<TypedAttr, 4> &operands) {
717  return simplifyAssocOp(
718  PEO::Xor, operands, [](auto a, auto b) { return a ^ b; },
719  /*identityCst*/ [](auto cst) { return cst.isZero(); });
720 }
721 
722 static TypedAttr simplifyShl(SmallVector<TypedAttr, 4> &operands) {
723  assert(isHWIntegerType(operands[0].getType()));
724 
725  if (auto rhs = dyn_cast<IntegerAttr>(operands[1])) {
726  // Constant fold simple integers.
727  if (auto lhs = dyn_cast<IntegerAttr>(operands[0]))
728  return IntegerAttr::get(lhs.getType(),
729  lhs.getValue().shl(rhs.getValue()));
730 
731  // Canonicalize `x << cst` => `x * (1<<cst)` to compose correctly with
732  // add/mul canonicalization.
733  auto rhsCst = APInt::getOneBitSet(rhs.getValue().getBitWidth(),
734  rhs.getValue().getZExtValue());
735  return ParamExprAttr::get(PEO::Mul, operands[0],
736  IntegerAttr::get(rhs.getType(), rhsCst));
737  }
738  return {};
739 }
740 
741 static TypedAttr simplifyShrU(SmallVector<TypedAttr, 4> &operands) {
742  assert(isHWIntegerType(operands[0].getType()));
743  // Implement support for identities like `x >> 0`.
744  if (auto rhs = dyn_cast<IntegerAttr>(operands[1]))
745  if (rhs.getValue().isZero())
746  return operands[0];
747 
748  return foldBinaryOp(operands, [](auto a, auto b) { return a.lshr(b); });
749 }
750 
751 static TypedAttr simplifyShrS(SmallVector<TypedAttr, 4> &operands) {
752  assert(isHWIntegerType(operands[0].getType()));
753  // Implement support for identities like `x >> 0`.
754  if (auto rhs = dyn_cast<IntegerAttr>(operands[1]))
755  if (rhs.getValue().isZero())
756  return operands[0];
757 
758  return foldBinaryOp(operands, [](auto a, auto b) { return a.ashr(b); });
759 }
760 
761 static TypedAttr simplifyDivU(SmallVector<TypedAttr, 4> &operands) {
762  assert(isHWIntegerType(operands[0].getType()));
763  // Implement support for identities like `x/1`.
764  if (auto rhs = dyn_cast<IntegerAttr>(operands[1]))
765  if (rhs.getValue().isOne())
766  return operands[0];
767 
768  return foldBinaryOp(operands, [](auto a, auto b) { return a.udiv(b); });
769 }
770 
771 static TypedAttr simplifyDivS(SmallVector<TypedAttr, 4> &operands) {
772  assert(isHWIntegerType(operands[0].getType()));
773  // Implement support for identities like `x/1`.
774  if (auto rhs = dyn_cast<IntegerAttr>(operands[1]))
775  if (rhs.getValue().isOne())
776  return operands[0];
777 
778  return foldBinaryOp(operands, [](auto a, auto b) { return a.sdiv(b); });
779 }
780 
781 static TypedAttr simplifyModU(SmallVector<TypedAttr, 4> &operands) {
782  assert(isHWIntegerType(operands[0].getType()));
783  // Implement support for identities like `x%1`.
784  if (auto rhs = dyn_cast<IntegerAttr>(operands[1]))
785  if (rhs.getValue().isOne())
786  return IntegerAttr::get(rhs.getType(), 0);
787 
788  return foldBinaryOp(operands, [](auto a, auto b) { return a.urem(b); });
789 }
790 
791 static TypedAttr simplifyModS(SmallVector<TypedAttr, 4> &operands) {
792  assert(isHWIntegerType(operands[0].getType()));
793  // Implement support for identities like `x%1`.
794  if (auto rhs = dyn_cast<IntegerAttr>(operands[1]))
795  if (rhs.getValue().isOne())
796  return IntegerAttr::get(rhs.getType(), 0);
797 
798  return foldBinaryOp(operands, [](auto a, auto b) { return a.srem(b); });
799 }
800 
801 static TypedAttr simplifyCLog2(SmallVector<TypedAttr, 4> &operands) {
802  assert(isHWIntegerType(operands[0].getType()));
803  return foldUnaryOp(operands, [](auto a) {
804  // Following the Verilog spec, clog2(0) is 0
805  return APInt(a.getBitWidth(), a == 0 ? 0 : a.ceilLogBase2());
806  });
807 }
808 
809 static TypedAttr simplifyStrConcat(SmallVector<TypedAttr, 4> &operands) {
810  // Combine all adjacent strings.
811  SmallVector<TypedAttr> newOperands;
812  SmallVector<StringAttr> stringsToCombine;
813  auto combineAndPush = [&]() {
814  if (stringsToCombine.empty())
815  return;
816  // Concatenate buffered strings, push to ops.
817  SmallString<32> newString;
818  for (auto part : stringsToCombine)
819  newString.append(part.getValue());
820  newOperands.push_back(
821  StringAttr::get(stringsToCombine[0].getContext(), newString));
822  stringsToCombine.clear();
823  };
824 
825  for (TypedAttr op : operands) {
826  if (auto strOp = dyn_cast<StringAttr>(op)) {
827  // Queue up adjacent strings.
828  stringsToCombine.push_back(strOp);
829  } else {
830  combineAndPush();
831  newOperands.push_back(op);
832  }
833  }
834  combineAndPush();
835 
836  assert(!newOperands.empty());
837  if (newOperands.size() == 1)
838  return newOperands[0];
839  if (newOperands.size() < operands.size())
840  return ParamExprAttr::get(PEO::StrConcat, newOperands);
841  return {};
842 }
843 
844 /// Build a parameter expression. This automatically canonicalizes and
845 /// folds, so it may not necessarily return a ParamExprAttr.
846 TypedAttr ParamExprAttr::get(PEO opcode, ArrayRef<TypedAttr> operandsIn) {
847  assert(!operandsIn.empty() && "Cannot have expr with no operands");
848  // All operands must have the same type, which is the type of the result.
849  auto type = operandsIn.front().getType();
850  assert(llvm::all_of(operandsIn.drop_front(),
851  [&](auto op) { return op.getType() == type; }));
852 
853  SmallVector<TypedAttr, 4> operands(operandsIn.begin(), operandsIn.end());
854 
855  // Verify and canonicalize parameter expressions.
856  TypedAttr result;
857  switch (opcode) {
858  case PEO::Add:
859  result = simplifyAdd(operands);
860  break;
861  case PEO::Mul:
862  result = simplifyMul(operands);
863  break;
864  case PEO::And:
865  result = simplifyAnd(operands);
866  break;
867  case PEO::Or:
868  result = simplifyOr(operands);
869  break;
870  case PEO::Xor:
871  result = simplifyXor(operands);
872  break;
873  case PEO::Shl:
874  result = simplifyShl(operands);
875  break;
876  case PEO::ShrU:
877  result = simplifyShrU(operands);
878  break;
879  case PEO::ShrS:
880  result = simplifyShrS(operands);
881  break;
882  case PEO::DivU:
883  result = simplifyDivU(operands);
884  break;
885  case PEO::DivS:
886  result = simplifyDivS(operands);
887  break;
888  case PEO::ModU:
889  result = simplifyModU(operands);
890  break;
891  case PEO::ModS:
892  result = simplifyModS(operands);
893  break;
894  case PEO::CLog2:
895  result = simplifyCLog2(operands);
896  break;
897  case PEO::StrConcat:
898  result = simplifyStrConcat(operands);
899  break;
900  }
901 
902  // If we folded to an operand, return it.
903  if (result)
904  return result;
905 
906  return Base::get(operands[0].getContext(), opcode, operands, type);
907 }
908 
909 Attribute ParamExprAttr::parse(AsmParser &p, Type type) {
910  // We require an opcode suffix like `#hw.param.expr.add`, we don't allow
911  // parsing a plain `#hw.param.expr` on its own.
912  p.emitError(p.getNameLoc(), "#hw.param.expr should have opcode suffix");
913  return {};
914 }
915 
916 /// Internal method used for .mlir file parsing when parsing the
917 /// "#hw.param.expr.mul" form of the attribute.
918 static Attribute parseParamExprWithOpcode(StringRef opcodeStr,
919  DialectAsmParser &p, Type type) {
920  SmallVector<TypedAttr> operands;
921  if (p.parseCommaSeparatedList(
922  mlir::AsmParser::Delimiter::LessGreater, [&]() -> ParseResult {
923  operands.push_back({});
924  return p.parseAttribute(operands.back(), type);
925  }))
926  return {};
927 
928  std::optional<PEO> opcode = symbolizePEO(opcodeStr);
929  if (!opcode.has_value()) {
930  p.emitError(p.getNameLoc(), "unknown parameter expr operator name");
931  return {};
932  }
933 
934  return ParamExprAttr::get(*opcode, operands);
935 }
936 
937 void ParamExprAttr::print(AsmPrinter &p) const {
938  p << "." << stringifyPEO(getOpcode()) << '<';
939  llvm::interleaveComma(getOperands(), p.getStream(),
940  [&](Attribute op) { p.printAttributeWithoutType(op); });
941  p << '>';
942 }
943 
944 // Replaces any ParamDeclRefAttr within a parametric expression with its
945 // corresponding value from the map of provided parameters.
946 static FailureOr<Attribute>
947 replaceDeclRefInExpr(Location loc,
948  const std::map<std::string, Attribute> &parameters,
949  Attribute paramAttr, bool emitErrors) {
950  if (dyn_cast<IntegerAttr>(paramAttr)) {
951  // Nothing to do, constant value.
952  return paramAttr;
953  }
954  if (auto paramRefAttr = dyn_cast<hw::ParamDeclRefAttr>(paramAttr)) {
955  // Get the value from the provided parameters.
956  auto it = parameters.find(paramRefAttr.getName().str());
957  if (it == parameters.end()) {
958  if (emitErrors)
959  return emitError(loc)
960  << "Could not find parameter " << paramRefAttr.getName().str()
961  << " in the provided parameters for the expression!";
962  return failure();
963  }
964  return it->second;
965  }
966  if (auto paramExprAttr = dyn_cast<hw::ParamExprAttr>(paramAttr)) {
967  // Recurse into all operands of the expression.
968  llvm::SmallVector<TypedAttr, 4> replacedOperands;
969  for (auto operand : paramExprAttr.getOperands()) {
970  auto res = replaceDeclRefInExpr(loc, parameters, operand, emitErrors);
971  if (failed(res))
972  return {failure()};
973  replacedOperands.push_back(cast<TypedAttr>(*res));
974  }
975  return {
976  hw::ParamExprAttr::get(paramExprAttr.getOpcode(), replacedOperands)};
977  }
978  llvm_unreachable("Unhandled parametric attribute");
979  return {};
980 }
981 
982 FailureOr<TypedAttr> hw::evaluateParametricAttr(Location loc,
983  ArrayAttr parameters,
984  Attribute paramAttr,
985  bool emitErrors) {
986  // Create a map of the provided parameters for faster lookup.
987  std::map<std::string, Attribute> parameterMap;
988  for (auto param : parameters) {
989  auto paramDecl = cast<ParamDeclAttr>(param);
990  parameterMap[paramDecl.getName().str()] = paramDecl.getValue();
991  }
992 
993  // First, replace any ParamDeclRefAttr in the expression with its
994  // corresponding value in 'parameters'.
995  auto paramAttrRes =
996  replaceDeclRefInExpr(loc, parameterMap, paramAttr, emitErrors);
997  if (failed(paramAttrRes))
998  return {failure()};
999  paramAttr = *paramAttrRes;
1000 
1001  // Then, evaluate the parametric attribute.
1002  if (isa<IntegerAttr, hw::ParamDeclRefAttr>(paramAttr))
1003  return cast<TypedAttr>(paramAttr);
1004  if (auto paramExprAttr = dyn_cast<hw::ParamExprAttr>(paramAttr)) {
1005  // Since any ParamDeclRefAttr was replaced within the expression,
1006  // we re-evaluate the expression through the existing ParamExprAttr
1007  // canonicalizer.
1008  return ParamExprAttr::get(paramExprAttr.getOpcode(),
1009  paramExprAttr.getOperands());
1010  }
1011 
1012  llvm_unreachable("Unhandled parametric attribute");
1013  return TypedAttr();
1014 }
1015 
1016 template <typename TArray>
1017 FailureOr<Type> evaluateParametricArrayType(Location loc, ArrayAttr parameters,
1018  TArray arrayType, bool emitErrors) {
1019  auto size = evaluateParametricAttr(loc, parameters, arrayType.getSizeAttr(),
1020  emitErrors);
1021  if (failed(size))
1022  return failure();
1023  auto elementType = evaluateParametricType(
1024  loc, parameters, arrayType.getElementType(), emitErrors);
1025  if (failed(elementType))
1026  return failure();
1027 
1028  // If the size was evaluated to a constant, use a 64-bit integer
1029  // attribute version of it
1030  if (auto intAttr = dyn_cast<IntegerAttr>(*size))
1031  return TArray::get(
1032  arrayType.getContext(), *elementType,
1033  IntegerAttr::get(IntegerType::get(arrayType.getContext(), 64),
1034  intAttr.getValue().getSExtValue()));
1035 
1036  // Otherwise parameter references are still involved
1037  return TArray::get(arrayType.getContext(), *elementType, *size);
1038 }
1039 
1040 FailureOr<Type> hw::evaluateParametricType(Location loc, ArrayAttr parameters,
1041  Type type, bool emitErrors) {
1042  return llvm::TypeSwitch<Type, FailureOr<Type>>(type)
1043  .Case<hw::IntType>([&](hw::IntType t) -> FailureOr<Type> {
1044  auto evaluatedWidth =
1045  evaluateParametricAttr(loc, parameters, t.getWidth(), emitErrors);
1046  if (failed(evaluatedWidth))
1047  return {failure()};
1048 
1049  // If the width was evaluated to a constant, return an `IntegerType`
1050  if (auto intAttr = dyn_cast<IntegerAttr>(*evaluatedWidth))
1051  return {IntegerType::get(type.getContext(),
1052  intAttr.getValue().getSExtValue())};
1053 
1054  // Otherwise parameter references are still involved
1055  return hw::IntType::get(cast<TypedAttr>(*evaluatedWidth));
1056  })
1057  .Case<hw::ArrayType, hw::UnpackedArrayType>(
1058  [&](auto arrayType) -> FailureOr<Type> {
1059  return evaluateParametricArrayType(loc, parameters, arrayType,
1060  emitErrors);
1061  })
1062  .Default([&](auto) { return type; });
1063 }
1064 
1065 // Returns true if any part of this parametric attribute contains a reference
1066 // to a parameter declaration.
1067 static bool isParamAttrWithParamRef(Attribute expr) {
1068  return llvm::TypeSwitch<Attribute, bool>(expr)
1069  .Case([](ParamExprAttr attr) {
1070  return llvm::any_of(attr.getOperands(), isParamAttrWithParamRef);
1071  })
1072  .Case([](ParamDeclRefAttr) { return true; })
1073  .Default([](auto) { return false; });
1074 }
1075 
1076 bool hw::isParametricType(mlir::Type t) {
1077  return llvm::TypeSwitch<Type, bool>(t)
1078  .Case<hw::IntType>(
1079  [&](hw::IntType t) { return isParamAttrWithParamRef(t.getWidth()); })
1080  .Case<hw::ArrayType, hw::UnpackedArrayType>([&](auto arrayType) {
1081  return isParametricType(arrayType.getElementType()) ||
1082  isParamAttrWithParamRef(arrayType.getSizeAttr());
1083  })
1084  .Default([](auto) { return false; });
1085 }
assert(baseType &&"element must be base type")
static TypedAttr foldBinaryOp(ArrayRef< TypedAttr > operands, llvm::function_ref< APInt(const APInt &, const APInt &)> calculate)
Given a binary function, if the two operands are known constant integers, use the specified fold func...
static TypedAttr simplifyDivS(SmallVector< TypedAttr, 4 > &operands)
static TypedAttr simplifyAssocOp(PEO opcode, SmallVector< TypedAttr, 4 > &operands, llvm::function_ref< APInt(const APInt &, const APInt &)> calculateFn, llvm::function_ref< bool(const APInt &)> identityConstantFn, llvm::function_ref< bool(const APInt &)> destructiveConstantFn={})
Given a fully associative variadic integer operation, constant fold any constant operands and move th...
static TypedAttr simplifyDivU(SmallVector< TypedAttr, 4 > &operands)
static TypedAttr simplifyCLog2(SmallVector< TypedAttr, 4 > &operands)
static TypedAttr simplifyModU(SmallVector< TypedAttr, 4 > &operands)
static TypedAttr simplifyOr(SmallVector< TypedAttr, 4 > &operands)
static TypedAttr simplifyShl(SmallVector< TypedAttr, 4 > &operands)
static void printSymbolName(AsmPrinter &p, StringAttr sym)
static TypedAttr simplifyShrS(SmallVector< TypedAttr, 4 > &operands)
static TypedAttr foldUnaryOp(ArrayRef< TypedAttr > operands, llvm::function_ref< APInt(const APInt &)> calculate)
Given a unary function, if the operand is a known constant integer, use the specified fold function t...
static TypedAttr simplifyMul(SmallVector< TypedAttr, 4 > &operands)
static TypedAttr getOneOfType(Type type)
static TypedAttr simplifyAnd(SmallVector< TypedAttr, 4 > &operands)
static std::pair< TypedAttr, TypedAttr > decomposeAddend(TypedAttr operand)
Analyze an operand to an add.
static TypedAttr simplifyModS(SmallVector< TypedAttr, 4 > &operands)
static Attribute parseParamExprWithOpcode(StringRef opcode, DialectAsmParser &p, Type type)
Internal method used for .mlir file parsing when parsing the "#hw.param.expr.mul" form of the attribu...
static bool paramExprOperandSortPredicate(Attribute lhs, Attribute rhs)
This implements a < comparison for two operands to an associative operation imposing an ordering upon...
static std::string canonicalizeFilename(const Twine &directory, const Twine &filename)
static TypedAttr simplifyShrU(SmallVector< TypedAttr, 4 > &operands)
static TypedAttr simplifyAdd(SmallVector< TypedAttr, 4 > &operands)
static TypedAttr simplifyStrConcat(SmallVector< TypedAttr, 4 > &operands)
static TypedAttr simplifyXor(SmallVector< TypedAttr, 4 > &operands)
static ParamExprAttr dyn_castPE(PEO opcode, Attribute value)
If the specified attribute is a ParamExprAttr with the specified opcode, return it.
static StringAttr append(StringAttr base, const Twine &suffix)
Return a attribute with the specified suffix appended.
static LogicalResult verify(Value clock, bool eventExists, mlir::Location loc)
Definition: SVOps.cpp:2459
Direction get(bool isOutput)
Returns an output direction if isOutput is true, otherwise returns an input direction.
Definition: CalyxOps.cpp:55
uint64_t getFieldID(Type type, uint64_t index)
StringAttr getName(ArrayAttr names, size_t idx)
Return the name at the specified index of the ArrayAttr or null if it cannot be determined.
bool isHWIntegerType(mlir::Type type)
Return true if the specified type is a value HW Integer type.
Definition: HWTypes.cpp:60
bool isHWEnumType(mlir::Type type)
Return true if the specified type is a HW Enum type.
Definition: HWTypes.cpp:73
mlir::Type getCanonicalType(mlir::Type type)
Definition: HWTypes.cpp:49
The InstanceGraph op interface, see InstanceGraphInterface.td for more details.
Definition: DebugAnalysis.h:21