CIRCT  20.0.0git
Naming.cpp
Go to the documentation of this file.
1 //===- Naming.cpp - Utilities for handling names ----------------*- C++ -*-===//
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 
9 #include "circt/Support/Naming.h"
10 #include "mlir/IR/BuiltinAttributes.h"
11 #include "mlir/IR/Operation.h"
12 #include "llvm/ADT/StringRef.h"
13 
14 using namespace circt;
15 
16 bool circt::isUselessName(StringRef name) {
17  if (name.empty())
18  return true;
19  // Ignore _.*
20  return name.starts_with("_T") || name.starts_with("_WIRE");
21 }
22 
23 // Heuristic to pick the best name.
24 // Good names are not useless, don't start with an underscore, minimize
25 // underscores in them, and are short. This function deterministically favors
26 // the second name on ties.
27 static bool isNameBetter(StringRef a, StringRef b) {
28  if (a.empty())
29  return false;
30  if (b.empty())
31  return true;
32  if (isUselessName(a))
33  return false;
34  if (isUselessName(b))
35  return true;
36  if (a.starts_with("_"))
37  return false;
38  if (b.starts_with("_"))
39  return true;
40  if (b.count('_') < a.count('_'))
41  return false;
42  if (b.count('_') > a.count('_'))
43  return true;
44  return a.size() <= b.size();
45 }
46 
47 StringRef circt::chooseName(StringRef a, StringRef b) {
48  return isNameBetter(a, b) ? a : b;
49 }
50 
51 StringAttr circt::chooseName(StringAttr a, StringAttr b) {
52  if (!a)
53  return b;
54  if (!b)
55  return a;
56  return isNameBetter(a.getValue(), b.getValue()) ? a : b;
57 }
58 
59 static StringAttr getNameOrHint(Operation *a) {
60  StringAttr name = a->getAttrOfType<StringAttr>("name");
61  if (!name || name.getValue().empty())
62  return a->getAttrOfType<StringAttr>("sv.namehint");
63  return name;
64 }
65 
66 StringAttr circt::chooseName(Operation *a, Operation *b) {
67  return chooseName(getNameOrHint(a), getNameOrHint(b));
68 }
static StringAttr getNameOrHint(Operation *a)
Definition: Naming.cpp:59
static bool isNameBetter(StringRef a, StringRef b)
Definition: Naming.cpp:27
The InstanceGraph op interface, see InstanceGraphInterface.td for more details.
Definition: DebugAnalysis.h:21
bool isUselessName(StringRef name)
Return true if this is a possibly useless temporary name.
Definition: Naming.cpp:16
StringRef chooseName(StringRef a, StringRef b)
Choose a good name for an item from two options.
Definition: Naming.cpp:47