Skip to content

Commit 5159a71

Browse files
randall77joedian
authored andcommitted
[release-branch.go1.22] cmd/compile: put constants before variables in initialization order
Fixes #67820. Change-Id: I03f4d4577b88ad0a92b260b2efd0cb9fe5082b2f Reviewed-on: https://go-review.googlesource.com/c/go/+/575075 Reviewed-by: Robert Griesemer <[email protected]> Reviewed-by: Keith Randall <[email protected]> LUCI-TryBot-Result: Go LUCI <[email protected]> Reviewed-on: https://go-review.googlesource.com/c/go/+/590395 Reviewed-by: Michael Knyszek <[email protected]> Reviewed-by: Keith Randall <[email protected]>
1 parent 11b861e commit 5159a71

File tree

4 files changed

+49
-0
lines changed

4 files changed

+49
-0
lines changed

src/cmd/compile/internal/types2/initorder.go

+8
Original file line numberDiff line numberDiff line change
@@ -310,6 +310,14 @@ func (a nodeQueue) Swap(i, j int) {
310310

311311
func (a nodeQueue) Less(i, j int) bool {
312312
x, y := a[i], a[j]
313+
314+
// Prioritize all constants before non-constants. See go.dev/issue/66575/.
315+
_, xConst := x.obj.(*Const)
316+
_, yConst := y.obj.(*Const)
317+
if xConst != yConst {
318+
return xConst
319+
}
320+
313321
// nodes are prioritized by number of incoming dependencies (1st key)
314322
// and source order (2nd key)
315323
return x.ndeps < y.ndeps || x.ndeps == y.ndeps && x.obj.order() < y.obj.order()

src/go/types/initorder.go

+8
Original file line numberDiff line numberDiff line change
@@ -307,6 +307,14 @@ func (a nodeQueue) Swap(i, j int) {
307307

308308
func (a nodeQueue) Less(i, j int) bool {
309309
x, y := a[i], a[j]
310+
311+
// Prioritize all constants before non-constants. See go.dev/issue/66575/.
312+
_, xConst := x.obj.(*Const)
313+
_, yConst := y.obj.(*Const)
314+
if xConst != yConst {
315+
return xConst
316+
}
317+
310318
// nodes are prioritized by number of incoming dependencies (1st key)
311319
// and source order (2nd key)
312320
return x.ndeps < y.ndeps || x.ndeps == y.ndeps && x.obj.order() < y.obj.order()

test/fixedbugs/issue66575.go

+31
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
// run
2+
3+
// Copyright 2024 The Go Authors. All rights reserved.
4+
// Use of this source code is governed by a BSD-style
5+
// license that can be found in the LICENSE file.
6+
7+
package main
8+
9+
var (
10+
v0 = initv0()
11+
v1 = initv1()
12+
)
13+
14+
const c = "c"
15+
16+
func initv0() string {
17+
println("initv0")
18+
if c != "" { // have a dependency on c
19+
return ""
20+
}
21+
return ""
22+
}
23+
24+
func initv1() string {
25+
println("initv1")
26+
return ""
27+
}
28+
29+
func main() {
30+
// do nothing
31+
}

test/fixedbugs/issue66575.out

+2
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
initv0
2+
initv1

0 commit comments

Comments
 (0)