aboutsummaryrefslogtreecommitdiff
path: root/src/main/scala/firrtl/passes/wiring/Wiring.scala
blob: 45eb61bfda4cf8c556df4bd8186f97de9534cd5a (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
// SPDX-License-Identifier: Apache-2.0

package firrtl.passes
package wiring

import firrtl._
import firrtl.ir._

import scala.collection.mutable
import firrtl.annotations._
import firrtl.annotations.AnnotationUtils._
import firrtl.analyses.InstanceKeyGraph
import WiringUtils._
import firrtl.analyses.InstanceKeyGraph.InstanceKey
import firrtl.graph.EulerTour

/** A data store of one sink--source wiring relationship */
case class WiringInfo(source: ComponentName, sinks: Seq[Named], pin: String)

/** A data store of wiring names */
case class WiringNames(compName: String, source: String, sinks: Seq[Named], pin: String)

/** Pass that computes and applies a sequence of wiring modifications
  *
  * @constructor construct a new Wiring pass
  * @param wiSeq the [[WiringInfo]] to apply
  */
class Wiring(wiSeq: Seq[WiringInfo]) extends Pass {
  def run(c: Circuit): Circuit = analyze(c)
    .foldLeft(c) {
      case (cx, (tpe, modsMap)) => cx.copy(modules = cx.modules.map(onModule(tpe, modsMap)))
    }

  /** Converts multiple units of wiring information to module modifications */
  private def analyze(c: Circuit): Seq[(Type, Map[String, Modifications])] = {

    val names = wiSeq
      .map(wi =>
        (wi.source, wi.sinks, wi.pin) match {
          case (ComponentName(comp, ModuleName(source, _)), sinks, pin) =>
            WiringNames(comp, source, sinks, pin)
        }
      )

    val portNames = mutable.Seq.fill(names.size)(Map[String, String]())
    c.modules.foreach { m =>
      val ns = Namespace(m)
      names.zipWithIndex.foreach {
        case (WiringNames(c, so, si, p), i) =>
          portNames(i) = portNames(i) +
            (m.name -> {
              if (si.exists(getModuleName(_) == m.name)) ns.newName(p)
              else ns.newName(tokenize(c).filterNot("[]." contains _).mkString("_"))
            })
      }
    }

    val iGraph = InstanceKeyGraph(c)
    names.zip(portNames).map {
      case (WiringNames(comp, so, si, _), pn) =>
        computeModifications(c, iGraph, comp, so, si, pn)
    }
  }

  /** Converts a single unit of wiring information to module modifications
    *
    * @param c the circuit that will be modified
    * @param iGraph an InstanceGraph representation of the circuit
    * @param compName the name of a component
    * @param source the name of the source component
    * @param sinks a list of sink components/modules that the source
    * should be connected to
    * @param portNames a mapping of module names to new ports/wires
    * that should be generated if needed
    *
    * @return a tuple of the component type and a map of module names
    * to pending modifications
    */
  private def computeModifications(
    c:         Circuit,
    iGraph:    InstanceKeyGraph,
    compName:  String,
    source:    String,
    sinks:     Seq[Named],
    portNames: Map[String, String]
  ): (Type, Map[String, Modifications]) = {

    val sourceComponentType = getType(c, source, compName)
    val sinkComponents: Map[String, Seq[String]] = sinks.collect { case ComponentName(c, ModuleName(m, _)) => (c, m) }
      .foldLeft(new scala.collection.immutable.HashMap[String, Seq[String]]) {
        case (a, (c, m)) => a ++ Map(m -> (Seq(c) ++ a.getOrElse(m, Nil)))
      }

    // Determine "ownership" of sources to sinks via minimum distance
    val owners = sinksToSourcesSeq(sinks, source, iGraph)

    // Determine port and pending modifications for all sink--source
    // ownership pairs
    val meta = new mutable.HashMap[String, Modifications]
      .withDefaultValue(Modifications())

    // only make something a wire if it isn't an output or input already
    def makeWire(m: Modifications, portName: String): Modifications =
      m.copy(addPortOrWire = Some(m.addPortOrWire.getOrElse((portName, DecWire))))
    def makeWireC(m: Modifications, portName: String, c: (String, String)): Modifications =
      m.copy(addPortOrWire = Some(m.addPortOrWire.getOrElse((portName, DecWire))), cons = (m.cons :+ c).distinct)

    val tour = EulerTour(iGraph.graph, iGraph.top)
    // Finds the lowest common ancestor instances for two module names in a design
    def lowestCommonAncestor(moduleA: Seq[InstanceKey], moduleB: Seq[InstanceKey]): Seq[InstanceKey] =
      tour.rmq(moduleA, moduleB)

    owners.foreach {
      case (sink, source) =>
        val lca = lowestCommonAncestor(sink, source)

        // Compute metadata along Sink to LCA paths.
        sink.drop(lca.size - 1).sliding(2).toList.reverse.foreach {
          case Seq(InstanceKey(_, pm), InstanceKey(ci, cm)) =>
            val to = s"$ci.${portNames(cm)}"
            val from = s"${portNames(pm)}"
            meta(pm) = makeWireC(meta(pm), portNames(pm), (to, from))
            meta(cm) = meta(cm).copy(
              addPortOrWire = Some((portNames(cm), DecInput))
            )
          // Case where the sink is the LCA
          case Seq(InstanceKey(_, pm)) =>
            // Case where the source is also the LCA
            if (source.drop(lca.size).isEmpty) {
              meta(pm) = makeWire(meta(pm), portNames(pm))
            } else {
              val InstanceKey(ci, cm) = source.drop(lca.size).head
              val to = s"${portNames(pm)}"
              val from = s"$ci.${portNames(cm)}"
              meta(pm) = makeWireC(meta(pm), portNames(pm), (to, from))
            }
        }

        // Compute metadata for the Sink
        sink.last match {
          case InstanceKey(_, m) =>
            if (sinkComponents.contains(m)) {
              val from = s"${portNames(m)}"
              sinkComponents(m).foreach(to =>
                meta(m) = meta(m).copy(
                  cons = (meta(m).cons :+ ((to, from))).distinct
                )
              )
            }
        }

        // Compute metadata for the Source
        source.last match {
          case InstanceKey(_, m) =>
            val to = s"${portNames(m)}"
            val from = compName
            meta(m) = meta(m).copy(
              cons = (meta(m).cons :+ ((to, from))).distinct
            )
        }

        // Compute metadata along Source to LCA path
        source.drop(lca.size - 1).sliding(2).toList.reverse.map {
          case Seq(InstanceKey(_, pm), InstanceKey(ci, cm)) => {
            val to = s"${portNames(pm)}"
            val from = s"$ci.${portNames(cm)}"
            meta(pm) = meta(pm).copy(
              cons = (meta(pm).cons :+ ((to, from))).distinct
            )
            meta(cm) = meta(cm).copy(
              addPortOrWire = Some((portNames(cm), DecOutput))
            )
          }
          // Case where the source is the LCA
          case Seq(InstanceKey(_, pm)) => {
            // Case where the sink is also the LCA. We do nothing here,
            // as we've created the connecting wire above
            if (sink.drop(lca.size).isEmpty) {} else {
              val InstanceKey(ci, cm) = sink.drop(lca.size).head
              val to = s"$ci.${portNames(cm)}"
              val from = s"${portNames(pm)}"
              meta(pm) = meta(pm).copy(
                cons = (meta(pm).cons :+ ((to, from))).distinct
              )
            }
          }
        }
    }
    (sourceComponentType, meta.toMap)
  }

  /** Apply modifications to a module */
  private def onModule(t: Type, map: Map[String, Modifications])(m: DefModule) = {
    map.get(m.name) match {
      case None => m
      case Some(l) =>
        val defines = mutable.ArrayBuffer[Statement]()
        val connects = mutable.ArrayBuffer[Statement]()
        val ports = mutable.ArrayBuffer[Port]()
        l.addPortOrWire match {
          case None =>
          case Some((s, dt)) =>
            dt match {
              case DecInput  => ports += Port(NoInfo, s, Input, t)
              case DecOutput => ports += Port(NoInfo, s, Output, t)
              case DecWire   => defines += DefWire(NoInfo, s, t)
            }
        }
        connects ++= (l.cons.map {
          case ((l, r)) =>
            Connect(NoInfo, toExp(l), toExp(r))
        })
        m match {
          case Module(i, n, ps, body) =>
            val stmts = body match {
              case Block(sx) => sx
              case s         => Seq(s)
            }
            Module(i, n, ps ++ ports, Block(List() ++ defines ++ stmts ++ connects))
          case ExtModule(i, n, ps, dn, p) => ExtModule(i, n, ps ++ ports, dn, p)
        }
    }
  }
}