aboutsummaryrefslogtreecommitdiff
path: root/src/main/scala/firrtl/passes/wiring/WiringUtils.scala
blob: 6f9b4f83c43a47819707a4d0a1b7a18063182902 (plain)
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
// SPDX-License-Identifier: Apache-2.0

package firrtl.passes
package wiring

import firrtl._
import firrtl.ir._
import firrtl.Utils._
import firrtl.Mappers._
import firrtl.analyses.InstanceKeyGraph.InstanceKey
import firrtl.traversals.Foreachers._

import scala.collection.mutable
import firrtl.annotations._
import firrtl.annotations.AnnotationUtils._
import firrtl.analyses.{InstanceGraph, InstanceKeyGraph}

/** Declaration kind in lineage (e.g. input port, output port, wire)
  */
sealed trait DecKind
case object DecInput extends DecKind
case object DecOutput extends DecKind
case object DecWire extends DecKind

/** Store of pending wiring information for a Module */
case class Modifications(
  addPortOrWire: Option[(String, DecKind)] = None,
  cons:          Seq[(String, String)] = Seq.empty) {

  override def toString: String = serialize("")

  def serialize(tab: String): String = s"""
                                          |$tab addPortOrWire: $addPortOrWire
                                          |$tab cons: $cons
                                          |""".stripMargin
}

/** A lineage tree representing the instance hierarchy in a design
  */
@deprecated("Use DiGraph/InstanceGraph", "FIRRTL 1.1.1")
case class Lineage(
  name:         String,
  children:     Seq[(String, Lineage)] = Seq.empty,
  source:       Boolean = false,
  sink:         Boolean = false,
  sourceParent: Boolean = false,
  sinkParent:   Boolean = false,
  sharedParent: Boolean = false,
  addPort:      Option[(String, DecKind)] = None,
  cons:         Seq[(String, String)] = Seq.empty) {

  def map(f: Lineage => Lineage): Lineage =
    this.copy(children = children.map { case (i, m) => (i, f(m)) })

  override def toString: String = shortSerialize("")

  def shortSerialize(tab: String): String = s"""
                                               |$tab name: $name,
                                               |$tab children: ${children.map(c =>
    tab + "   " + c._2.shortSerialize(tab + "    ")
  )}
                                               |""".stripMargin

  def foldLeft[B](z: B)(op: (B, (String, Lineage)) => B): B =
    this.children.foldLeft(z)(op)

  def serialize(tab: String): String = s"""
                                          |$tab name: $name,
                                          |$tab source: $source,
                                          |$tab sink: $sink,
                                          |$tab sourceParent: $sourceParent,
                                          |$tab sinkParent: $sinkParent,
                                          |$tab sharedParent: $sharedParent,
                                          |$tab addPort: $addPort
                                          |$tab cons: $cons
                                          |$tab children: ${children.map(c =>
    tab + "   " + c._2.serialize(tab + "    ")
  )}
                                          |""".stripMargin
}

object WiringUtils {
  @deprecated("Use DiGraph/InstanceGraph", "FIRRTL 1.1.1")
  type ChildrenMap = mutable.HashMap[String, Seq[(String, String)]]

  /** Given a circuit, returns a map from module name to children
    * instance/module names
    */
  @deprecated("Use DiGraph/InstanceGraph", "FIRRTL 1.1.1")
  def getChildrenMap(c: Circuit): ChildrenMap = {
    val childrenMap = new ChildrenMap()
    def getChildren(mname: String)(s: Statement): Unit = s match {
      case s: DefInstance =>
        childrenMap(mname) = childrenMap(mname) :+ ((s.name, s.module))
      case s => s.foreach(getChildren(mname))
    }
    c.modules.foreach { m =>
      childrenMap(m.name) = Nil
      m.foreach(getChildren(m.name))
    }
    childrenMap
  }

  /** Returns a module's lineage, containing all children lineages as well
    */
  @deprecated("Use DiGraph/InstanceGraph", "FIRRTL 1.1.1")
  def getLineage(childrenMap: ChildrenMap, module: String): Lineage =
    Lineage(module, childrenMap(module).map { case (i, m) => (i, getLineage(childrenMap, m)) })

  /** Return a map of sink instances to source instances that minimizes
    * distance
    *
    * @param sinks a sequence of sink modules
    * @param source the source module
    * @param i a graph representing a circuit
    * @return a map of sink instance names to source instance names
    * @throws WiringException if a sink is equidistant to two sources
    */
  @deprecated(
    "This method can lead to non-determinism in your compiler pass and exposes internal details." +
      " Please file an issue with firrtl if you have a use case!",
    "Firrtl 1.4"
  )
  def sinksToSources(sinks: Seq[Named], source: String, i: InstanceGraph): Map[Seq[WDefInstance], Seq[WDefInstance]] = {
    // The order of owners influences the order of the results, it thus needs to be deterministic with a  LinkedHashMap.
    val owners = new mutable.LinkedHashMap[Seq[WDefInstance], Vector[Seq[WDefInstance]]]
    val queue = new mutable.Queue[Seq[WDefInstance]]
    val visited = new mutable.HashMap[Seq[WDefInstance], Boolean].withDefaultValue(false)

    val sourcePaths = i.fullHierarchy.collect { case (k, v) if k.module == source => v }
    sourcePaths.flatten.foreach { l =>
      queue.enqueue(l)
      owners(l) = Vector(l)
    }

    val sinkModuleNames = sinks.map(getModuleName).toSet
    val sinkPaths = i.fullHierarchy.collect { case (k, v) if sinkModuleNames.contains(k.module) => v }
    // sinkInsts needs to have unique entries but is also iterated over which is why we use a LinkedHashSet
    val sinkInsts = mutable.LinkedHashSet() ++ sinkPaths.flatten

    /** If we're lucky and there is only one source, then that source owns
      * all sinks. If we're unlucky, we need to do a full (slow) BFS
      * to figure out who owns what. Currently, the BFS is not
      * performant.
      *
      * [todo] The performance of this will need to be improved.
      * Possible directions are that if we're purely source-under-sink
      * or sink-under-source, then ownership is trivially a mapping
      * down/up. Ownership seems to require a BFS if we have
      * sources/sinks not under sinks/sources.
      */
    if (queue.size == 1) {
      val u = queue.dequeue()
      sinkInsts.foreach { v => owners(v) = Vector(u) }
    } else {
      while (queue.nonEmpty) {
        val u = queue.dequeue()
        visited(u) = true

        val edges = (i.graph.getEdges(u.last).map(u :+ _).toVector :+ u.dropRight(1))

        // [todo] This is the critical section
        edges
          .filter(e => !visited(e) && e.nonEmpty)
          .foreach { v =>
            owners(v) = owners.getOrElse(v, Vector()) ++ owners(u)
            queue.enqueue(v)
          }
      }

      // Check that every sink has one unique owner. The only time that
      // this should fail is if a sink is equidistant to two sources.
      sinkInsts.foreach { s =>
        if (!owners.contains(s) || owners(s).size > 1) {
          throw new WiringException(s"Unable to determine source mapping for sink '${s.map(_.name)}'")
        }
      }
    }

    owners.collect { case (k, v) if sinkInsts.contains(k) => (k, v.flatten) }.toMap
  }

  /** Return a map of sink instances to source instances that minimizes
    * distance
    *
    * @param sinks a sequence of sink modules
    * @param source the source module
    * @param i a graph representing a circuit
    * @return a map of sink instance names to source instance names
    * @throws WiringException if a sink is equidistant to two sources
    */
  private[firrtl] def sinksToSourcesSeq(
    sinks:  Seq[Named],
    source: String,
    i:      InstanceKeyGraph
  ): Seq[(Seq[InstanceKey], Seq[InstanceKey])] = {
    // The order of owners influences the order of the results, it thus needs to be deterministic with a  LinkedHashMap.
    val owners = new mutable.LinkedHashMap[Seq[InstanceKey], Vector[Seq[InstanceKey]]]
    val queue = new mutable.Queue[Seq[InstanceKey]]
    val visited = new mutable.HashMap[Seq[InstanceKey], Boolean].withDefaultValue(false)

    val sourcePaths = i.fullHierarchy.collect { case (k, v) if k.module == source => v }
    sourcePaths.flatten.foreach { l =>
      queue.enqueue(l)
      owners(l) = Vector(l)
    }

    val sinkModuleNames = sinks.map(getModuleName).toSet
    val sinkPaths = i.fullHierarchy.collect { case (k, v) if sinkModuleNames.contains(k.module) => v }
    // sinkInsts needs to have unique entries but is also iterated over which is why we use a LinkedHashSet
    val sinkInsts = mutable.LinkedHashSet() ++ sinkPaths.flatten

    /** If we're lucky and there is only one source, then that source owns
      * all sinks. If we're unlucky, we need to do a full (slow) BFS
      * to figure out who owns what. Currently, the BFS is not
      * performant.
      *
      * [todo] The performance of this will need to be improved.
      * Possible directions are that if we're purely source-under-sink
      * or sink-under-source, then ownership is trivially a mapping
      * down/up. Ownership seems to require a BFS if we have
      * sources/sinks not under sinks/sources.
      */
    if (queue.size == 1) {
      val u = queue.dequeue()
      sinkInsts.foreach { v => owners(v) = Vector(u) }
    } else {
      while (queue.nonEmpty) {
        val u = queue.dequeue()
        visited(u) = true

        val edges = i.graph.getEdges(u.last).map(u :+ _).toVector :+ u.dropRight(1)

        // [todo] This is the critical section
        edges
          .filter(e => !visited(e) && e.nonEmpty)
          .foreach { v =>
            owners(v) = owners.getOrElse(v, Vector()) ++ owners(u)
            queue.enqueue(v)
          }
      }

      // Check that every sink has one unique owner. The only time that
      // this should fail is if a sink is equidistant to two sources.
      sinkInsts.foreach { s =>
        if (!owners.contains(s) || owners(s).size > 1) {
          throw new WiringException(s"Unable to determine source mapping for sink '${s.map(_.name)}'")
        }
      }
    }

    owners.collect { case (k, v) if sinkInsts.contains(k) => (k, v.flatten) }.toSeq
  }

  /** Helper script to extract a module name from a named Module or Target */
  def getModuleName(n: Named): String = {
    n match {
      case ModuleName(m, _)                   => m
      case ComponentName(_, ModuleName(m, _)) => m
      case _                                  => throw new WiringException("Only Components or Modules have an associated Module name")
    }
  }

  /** Determine the Type of a specific component
    *
    * @param c the circuit containing the target module
    * @param module the module containing the target component
    * @param comp the target component
    * @return the component's type
    * @throws WiringException if the module is not contained in the
    * circuit or if the component is not contained in the module
    */
  def getType(c: Circuit, module: String, comp: String): Type = {
    def getRoot(e: Expression): String = e match {
      case r: Reference => r.name
      case i: SubIndex  => getRoot(i.expr)
      case a: SubAccess => getRoot(a.expr)
      case f: SubField  => getRoot(f.expr)
    }
    val eComp = toExp(comp)
    val root = getRoot(eComp)
    var tpe: Option[Type] = None
    def getType(s: Statement): Statement = s match {
      case DefRegister(_, n, t, _, _, _) if n == root =>
        tpe = Some(t)
        s
      case DefWire(_, n, t) if n == root =>
        tpe = Some(t)
        s
      case WDefInstance(_, n, _, t) if n == root =>
        tpe = Some(t)
        s
      case DefNode(_, n, e) if n == root =>
        tpe = Some(e.tpe)
        s
      case sx: DefMemory if sx.name == root =>
        tpe = Some(MemPortUtils.memType(sx))
        sx
      case sx => sx.map(getType)
    }
    val m = c.modules.find(_.name == module).getOrElse {
      throw new WiringException(s"Must have a module named $module")
    }
    tpe = m.ports.find(_.name == root).map(_.tpe)
    m match {
      case Module(i, n, ps, b) => getType(b)
      case e: ExtModule =>
    }
    tpe match {
      case None => throw new WiringException(s"Didn't find $comp in $module!")
      case Some(t) =>
        def setType(e: Expression): Expression = e.map(setType) match {
          case ex: Reference => ex.copy(tpe = t)
          case ex: SubField  => ex.copy(tpe = field_type(ex.expr.tpe, ex.name))
          case ex: SubIndex  => ex.copy(tpe = sub_type(ex.expr.tpe))
          case ex: SubAccess => ex.copy(tpe = sub_type(ex.expr.tpe))
        }
        setType(eComp).tpe
    }
  }
}