]> Cypherpunks.ru repositories - gostls13.git/blobdiff - src/cmd/compile/internal/pkginit/initorder.go
[dev.regabi] all: merge master (dab3e5a) into dev.regabi
[gostls13.git] / src / cmd / compile / internal / pkginit / initorder.go
similarity index 64%
rename from src/cmd/compile/internal/gc/initorder.go
rename to src/cmd/compile/internal/pkginit/initorder.go
index e2084fd03862ca8ea9f7e79557f2df1038ba9056..97d69629fbae9e5167ec68abe39c9264a8c979cc 100644 (file)
@@ -2,12 +2,16 @@
 // Use of this source code is governed by a BSD-style
 // license that can be found in the LICENSE file.
 
-package gc
+package pkginit
 
 import (
        "bytes"
        "container/heap"
        "fmt"
+
+       "cmd/compile/internal/base"
+       "cmd/compile/internal/ir"
+       "cmd/compile/internal/staticinit"
 )
 
 // Package initialization
@@ -60,56 +64,57 @@ const (
 type InitOrder struct {
        // blocking maps initialization assignments to the assignments
        // that depend on it.
-       blocking map[*Node][]*Node
+       blocking map[ir.Node][]ir.Node
 
        // ready is the queue of Pending initialization assignments
        // that are ready for initialization.
        ready declOrder
+
+       order map[ir.Node]int
 }
 
 // initOrder computes initialization order for a list l of
 // package-level declarations (in declaration order) and outputs the
 // corresponding list of statements to include in the init() function
 // body.
-func initOrder(l []*Node) []*Node {
-       s := InitSchedule{
-               initplans: make(map[*Node]*InitPlan),
-               inittemps: make(map[*Node]*Node),
+func initOrder(l []ir.Node) []ir.Node {
+       s := staticinit.Schedule{
+               Plans: make(map[ir.Node]*staticinit.Plan),
+               Temps: make(map[ir.Node]*ir.Name),
        }
        o := InitOrder{
-               blocking: make(map[*Node][]*Node),
+               blocking: make(map[ir.Node][]ir.Node),
+               order:    make(map[ir.Node]int),
        }
 
        // Process all package-level assignment in declaration order.
        for _, n := range l {
-               switch n.Op {
-               case OAS, OAS2DOTTYPE, OAS2FUNC, OAS2MAPR, OAS2RECV:
+               switch n.Op() {
+               case ir.OAS, ir.OAS2DOTTYPE, ir.OAS2FUNC, ir.OAS2MAPR, ir.OAS2RECV:
                        o.processAssign(n)
-                       o.flushReady(s.staticInit)
-               case ODCLCONST, ODCLFUNC, ODCLTYPE:
+                       o.flushReady(s.StaticInit)
+               case ir.ODCLCONST, ir.ODCLFUNC, ir.ODCLTYPE:
                        // nop
                default:
-                       Fatalf("unexpected package-level statement: %v", n)
+                       base.Fatalf("unexpected package-level statement: %v", n)
                }
        }
 
        // Check that all assignments are now Done; if not, there must
        // have been a dependency cycle.
        for _, n := range l {
-               switch n.Op {
-               case OAS, OAS2DOTTYPE, OAS2FUNC, OAS2MAPR, OAS2RECV:
-                       if n.Initorder() != InitDone {
+               switch n.Op() {
+               case ir.OAS, ir.OAS2DOTTYPE, ir.OAS2FUNC, ir.OAS2MAPR, ir.OAS2RECV:
+                       if o.order[n] != orderDone {
                                // If there have already been errors
                                // printed, those errors may have
                                // confused us and there might not be
                                // a loop. Let the user fix those
                                // first.
-                               if nerrors > 0 {
-                                       errorexit()
-                               }
+                               base.ExitIfErrors()
 
-                               findInitLoopAndExit(firstLHS(n), new([]*Node), make(map[*Node]bool))
-                               Fatalf("initialization unfinished, but failed to identify loop")
+                               o.findInitLoopAndExit(firstLHS(n), new([]*ir.Name), new(ir.NameSet))
+                               base.Fatalf("initialization unfinished, but failed to identify loop")
                        }
                }
        }
@@ -117,58 +122,56 @@ func initOrder(l []*Node) []*Node {
        // Invariant consistency check. If this is non-zero, then we
        // should have found a cycle above.
        if len(o.blocking) != 0 {
-               Fatalf("expected empty map: %v", o.blocking)
+               base.Fatalf("expected empty map: %v", o.blocking)
        }
 
-       return s.out
+       return s.Out
 }
 
-func (o *InitOrder) processAssign(n *Node) {
-       if n.Initorder() != InitNotStarted || n.Xoffset != BADWIDTH {
-               Fatalf("unexpected state: %v, %v, %v", n, n.Initorder(), n.Xoffset)
+func (o *InitOrder) processAssign(n ir.Node) {
+       if _, ok := o.order[n]; ok {
+               base.Fatalf("unexpected state: %v, %v", n, o.order[n])
        }
-
-       n.SetInitorder(InitPending)
-       n.Xoffset = 0
+       o.order[n] = 0
 
        // Compute number of variable dependencies and build the
        // inverse dependency ("blocking") graph.
        for dep := range collectDeps(n, true) {
-               defn := dep.Name.Defn
+               defn := dep.Defn
                // Skip dependencies on functions (PFUNC) and
                // variables already initialized (InitDone).
-               if dep.Class() != PEXTERN || defn.Initorder() == InitDone {
+               if dep.Class != ir.PEXTERN || o.order[defn] == orderDone {
                        continue
                }
-               n.Xoffset++
+               o.order[n]++
                o.blocking[defn] = append(o.blocking[defn], n)
        }
 
-       if n.Xoffset == 0 {
+       if o.order[n] == 0 {
                heap.Push(&o.ready, n)
        }
 }
 
+const orderDone = -1000
+
 // flushReady repeatedly applies initialize to the earliest (in
 // declaration order) assignment ready for initialization and updates
 // the inverse dependency ("blocking") graph.
-func (o *InitOrder) flushReady(initialize func(*Node)) {
+func (o *InitOrder) flushReady(initialize func(ir.Node)) {
        for o.ready.Len() != 0 {
-               n := heap.Pop(&o.ready).(*Node)
-               if n.Initorder() != InitPending || n.Xoffset != 0 {
-                       Fatalf("unexpected state: %v, %v, %v", n, n.Initorder(), n.Xoffset)
+               n := heap.Pop(&o.ready).(ir.Node)
+               if order, ok := o.order[n]; !ok || order != 0 {
+                       base.Fatalf("unexpected state: %v, %v, %v", n, ok, order)
                }
 
                initialize(n)
-               n.SetInitorder(InitDone)
-               n.Xoffset = BADWIDTH
+               o.order[n] = orderDone
 
                blocked := o.blocking[n]
                delete(o.blocking, n)
 
                for _, m := range blocked {
-                       m.Xoffset--
-                       if m.Xoffset == 0 {
+                       if o.order[m]--; o.order[m] == 0 {
                                heap.Push(&o.ready, m)
                        }
                }
@@ -181,7 +184,7 @@ func (o *InitOrder) flushReady(initialize func(*Node)) {
 // path points to a slice used for tracking the sequence of
 // variables/functions visited. Using a pointer to a slice allows the
 // slice capacity to grow and limit reallocations.
-func findInitLoopAndExit(n *Node, path *[]*Node, ok map[*Node]bool) {
+func (o *InitOrder) findInitLoopAndExit(n *ir.Name, path *[]*ir.Name, ok *ir.NameSet) {
        for i, x := range *path {
                if x == n {
                        reportInitLoopAndExit((*path)[i:])
@@ -191,24 +194,25 @@ func findInitLoopAndExit(n *Node, path *[]*Node, ok map[*Node]bool) {
 
        // There might be multiple loops involving n; by sorting
        // references, we deterministically pick the one reported.
-       refers := collectDeps(n.Name.Defn, false).Sorted(func(ni, nj *Node) bool {
-               return ni.Pos.Before(nj.Pos)
+       refers := collectDeps(n.Defn, false).Sorted(func(ni, nj *ir.Name) bool {
+               return ni.Pos().Before(nj.Pos())
        })
 
        *path = append(*path, n)
        for _, ref := range refers {
                // Short-circuit variables that were initialized.
-               if ref.Class() == PEXTERN && ref.Name.Defn.Initorder() == InitDone || ok[ref] {
+               if ref.Class == ir.PEXTERN && o.order[ref.Defn] == orderDone || ok.Has(ref) {
                        continue
                }
-               findInitLoopAndExit(ref, path, ok)
+
+               o.findInitLoopAndExit(ref, path, ok)
        }
 
        // n is not involved in a cycle.
        // Record that fact to avoid checking it again when reached another way,
        // or else this traversal will take exponential time traversing all paths
        // through the part of the package's call graph implicated in the cycle.
-       ok[n] = true
+       ok.Add(n)
 
        *path = (*path)[:len(*path)-1]
 }
@@ -216,12 +220,12 @@ func findInitLoopAndExit(n *Node, path *[]*Node, ok map[*Node]bool) {
 // reportInitLoopAndExit reports and initialization loop as an error
 // and exits. However, if l is not actually an initialization loop, it
 // simply returns instead.
-func reportInitLoopAndExit(l []*Node) {
+func reportInitLoopAndExit(l []*ir.Name) {
        // Rotate loop so that the earliest variable declaration is at
        // the start.
        i := -1
        for j, n := range l {
-               if n.Class() == PEXTERN && (i == -1 || n.Pos.Before(l[i].Pos)) {
+               if n.Class == ir.PEXTERN && (i == -1 || n.Pos().Before(l[i].Pos())) {
                        i = j
                }
        }
@@ -239,69 +243,75 @@ func reportInitLoopAndExit(l []*Node) {
        var msg bytes.Buffer
        fmt.Fprintf(&msg, "initialization loop:\n")
        for _, n := range l {
-               fmt.Fprintf(&msg, "\t%v: %v refers to\n", n.Line(), n)
+               fmt.Fprintf(&msg, "\t%v: %v refers to\n", ir.Line(n), n)
        }
-       fmt.Fprintf(&msg, "\t%v: %v", l[0].Line(), l[0])
+       fmt.Fprintf(&msg, "\t%v: %v", ir.Line(l[0]), l[0])
 
-       yyerrorl(l[0].Pos, msg.String())
-       errorexit()
+       base.ErrorfAt(l[0].Pos(), msg.String())
+       base.ErrorExit()
 }
 
 // collectDeps returns all of the package-level functions and
 // variables that declaration n depends on. If transitive is true,
 // then it also includes the transitive dependencies of any depended
 // upon functions (but not variables).
-func collectDeps(n *Node, transitive bool) NodeSet {
+func collectDeps(n ir.Node, transitive bool) ir.NameSet {
        d := initDeps{transitive: transitive}
-       switch n.Op {
-       case OAS:
-               d.inspect(n.Right)
-       case OAS2DOTTYPE, OAS2FUNC, OAS2MAPR, OAS2RECV:
-               d.inspect(n.Right)
-       case ODCLFUNC:
-               d.inspectList(n.Nbody)
+       switch n.Op() {
+       case ir.OAS:
+               n := n.(*ir.AssignStmt)
+               d.inspect(n.Y)
+       case ir.OAS2DOTTYPE, ir.OAS2FUNC, ir.OAS2MAPR, ir.OAS2RECV:
+               n := n.(*ir.AssignListStmt)
+               d.inspect(n.Rhs[0])
+       case ir.ODCLFUNC:
+               n := n.(*ir.Func)
+               d.inspectList(n.Body)
        default:
-               Fatalf("unexpected Op: %v", n.Op)
+               base.Fatalf("unexpected Op: %v", n.Op())
        }
        return d.seen
 }
 
 type initDeps struct {
        transitive bool
-       seen       NodeSet
+       seen       ir.NameSet
+       cvisit     func(ir.Node)
+}
+
+func (d *initDeps) cachedVisit() func(ir.Node) {
+       if d.cvisit == nil {
+               d.cvisit = d.visit // cache closure
+       }
+       return d.cvisit
 }
 
-func (d *initDeps) inspect(n *Node)     { inspect(n, d.visit) }
-func (d *initDeps) inspectList(l Nodes) { inspectList(l, d.visit) }
+func (d *initDeps) inspect(n ir.Node)      { ir.Visit(n, d.cachedVisit()) }
+func (d *initDeps) inspectList(l ir.Nodes) { ir.VisitList(l, d.cachedVisit()) }
 
 // visit calls foundDep on any package-level functions or variables
 // referenced by n, if any.
-func (d *initDeps) visit(n *Node) bool {
-       switch n.Op {
-       case ONAME:
-               if n.isMethodExpression() {
-                       d.foundDep(asNode(n.Type.FuncType().Nname))
-                       return false
-               }
-
-               switch n.Class() {
-               case PEXTERN, PFUNC:
+func (d *initDeps) visit(n ir.Node) {
+       switch n.Op() {
+       case ir.ONAME:
+               n := n.(*ir.Name)
+               switch n.Class {
+               case ir.PEXTERN, ir.PFUNC:
                        d.foundDep(n)
                }
 
-       case OCLOSURE:
-               d.inspectList(n.Func.Closure.Nbody)
+       case ir.OCLOSURE:
+               n := n.(*ir.ClosureExpr)
+               d.inspectList(n.Func.Body)
 
-       case ODOTMETH, OCALLPART:
-               d.foundDep(asNode(n.Type.FuncType().Nname))
+       case ir.ODOTMETH, ir.OCALLPART, ir.OMETHEXPR:
+               d.foundDep(ir.MethodExprName(n))
        }
-
-       return true
 }
 
 // foundDep records that we've found a dependency on n by adding it to
 // seen.
-func (d *initDeps) foundDep(n *Node) {
+func (d *initDeps) foundDep(n *ir.Name) {
        // Can happen with method expressions involving interface
        // types; e.g., fixedbugs/issue4495.go.
        if n == nil {
@@ -310,7 +320,7 @@ func (d *initDeps) foundDep(n *Node) {
 
        // Names without definitions aren't interesting as far as
        // initialization ordering goes.
-       if n.Name.Defn == nil {
+       if n.Defn == nil {
                return
        }
 
@@ -318,8 +328,8 @@ func (d *initDeps) foundDep(n *Node) {
                return
        }
        d.seen.Add(n)
-       if d.transitive && n.Class() == PFUNC {
-               d.inspectList(n.Name.Defn.Nbody)
+       if d.transitive && n.Class == ir.PFUNC {
+               d.inspectList(n.Defn.(*ir.Func).Body)
        }
 }
 
@@ -330,13 +340,15 @@ func (d *initDeps) foundDep(n *Node) {
 // an OAS node's Pos may not be unique. For example, given the
 // declaration "var a, b = f(), g()", "a" must be ordered before "b",
 // but both OAS nodes use the "=" token's position as their Pos.
-type declOrder []*Node
+type declOrder []ir.Node
 
-func (s declOrder) Len() int           { return len(s) }
-func (s declOrder) Less(i, j int) bool { return firstLHS(s[i]).Pos.Before(firstLHS(s[j]).Pos) }
-func (s declOrder) Swap(i, j int)      { s[i], s[j] = s[j], s[i] }
+func (s declOrder) Len() int { return len(s) }
+func (s declOrder) Less(i, j int) bool {
+       return firstLHS(s[i]).Pos().Before(firstLHS(s[j]).Pos())
+}
+func (s declOrder) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
 
-func (s *declOrder) Push(x interface{}) { *s = append(*s, x.(*Node)) }
+func (s *declOrder) Push(x interface{}) { *s = append(*s, x.(ir.Node)) }
 func (s *declOrder) Pop() interface{} {
        n := (*s)[len(*s)-1]
        *s = (*s)[:len(*s)-1]
@@ -345,14 +357,16 @@ func (s *declOrder) Pop() interface{} {
 
 // firstLHS returns the first expression on the left-hand side of
 // assignment n.
-func firstLHS(n *Node) *Node {
-       switch n.Op {
-       case OAS:
-               return n.Left
-       case OAS2DOTTYPE, OAS2FUNC, OAS2RECV, OAS2MAPR:
-               return n.List.First()
+func firstLHS(n ir.Node) *ir.Name {
+       switch n.Op() {
+       case ir.OAS:
+               n := n.(*ir.AssignStmt)
+               return n.X.Name()
+       case ir.OAS2DOTTYPE, ir.OAS2FUNC, ir.OAS2RECV, ir.OAS2MAPR:
+               n := n.(*ir.AssignListStmt)
+               return n.Lhs[0].Name()
        }
 
-       Fatalf("unexpected Op: %v", n.Op)
+       base.Fatalf("unexpected Op: %v", n.Op())
        return nil
 }