Debian Codegraph @

go/analysis/passes/fieldalignment/fieldalignment.go

raw symbols SCIP
1 // Copyright 2020 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 // Package fieldalignment defines an Analyzer that detects structs that would use less
6 // memory if their fields were sorted.
7 package fieldalignment
8
9 import (
10 "bytes"
11 "fmt"
12 "go/ast"
13 "go/format"
14 "go/token"
15 "go/types"
16 "sort"
17
18 "golang.org/x/tools/go/analysis"
19 "golang.org/x/tools/go/analysis/passes/inspect"
20 "golang.org/x/tools/go/ast/inspector"
21 "golang.org/x/tools/internal/astutil"
22 )
23
24 const Doc = `find structs that would use less memory if their fields were sorted
25
26 This analyzer finds structs that can be rearranged to use less memory, and provides
27 a suggested edit with the most compact order.
28
29 Note that there are two different diagnostics reported. One checks struct size,
30 and the other reports "pointer bytes" used. Pointer bytes is how many bytes of the
31 object that the garbage collector has to potentially scan for pointers, for example:
32
33 struct { uint32; string }
34
35 have 16 pointer bytes because the garbage collector has to scan up through the string's
36 inner pointer.
37
38 struct { string; *uint32 }
39
40 has 24 pointer bytes because it has to scan further through the *uint32.
41
42 struct { string; uint32 }
43
44 has 8 because it can stop immediately after the string pointer.
45
46 Be aware that the most compact order is not always the most efficient.
47 In rare cases it may cause two variables each updated by its own goroutine
48 to occupy the same CPU cache line, inducing a form of memory contention
49 known as "false sharing" that slows down both goroutines.
50
51 Unlike most analyzers, which report likely mistakes, the diagnostics
52 produced by fieldanalyzer very rarely indicate a significant problem,
53 so the analyzer is not included in typical suites such as vet or
54 gopls. Use this standalone command to run it on your code:
55
56 $ go install golang.org/x/tools/go/analysis/passes/fieldalignment/cmd/fieldalignment@latest
57 $ fieldalignment [packages]
58
59 `
60
61 var Analyzer = &analysis.Analyzer{
62 Name: "fieldalignment",
63 Doc: Doc,
64 URL: "https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/fieldalignment",
65 Requires: []*analysis.Analyzer{inspect.Analyzer},
66 Run: run,
67 }
68
69 func run(pass *analysis.Pass) (any, error) {
70 inspect := pass.ResultOf[inspect.Analyzer].(*inspector.Inspector)
71 nodeFilter := []ast.Node{
72 (*ast.StructType)(nil),
73 }
74 inspect.Preorder(nodeFilter, func(node ast.Node) {
75 var s *ast.StructType
76 var ok bool
77 if s, ok = node.(*ast.StructType); !ok {
78 return
79 }
80 if tv, ok := pass.TypesInfo.Types[s]; ok {
81 fieldalignment(pass, s, tv.Type.(*types.Struct))
82 }
83 })
84 return nil, nil
85 }
86
87 var unsafePointerTyp = types.Unsafe.Scope().Lookup("Pointer").(*types.TypeName).Type()
88
89 func fieldalignment(pass *analysis.Pass, node *ast.StructType, typ *types.Struct) {
90 wordSize := pass.TypesSizes.Sizeof(unsafePointerTyp)
91 maxAlign := pass.TypesSizes.Alignof(unsafePointerTyp)
92
93 s := gcSizes{wordSize, maxAlign}
94 optimal, indexes := optimalOrder(typ, &s)
95 optsz, optptrs := s.Sizeof(optimal), s.ptrdata(optimal)
96
97 var message string
98 if sz := s.Sizeof(typ); sz != optsz {
99 message = fmt.Sprintf("struct of size %d could be %d", sz, optsz)
100 } else if ptrs := s.ptrdata(typ); ptrs != optptrs {
101 message = fmt.Sprintf("struct with %d pointer bytes could be %d", ptrs, optptrs)
102 } else {
103 // Already optimal order.
104 return
105 }
106
107 // Analyzers borrow syntax tree; they do not own them and must modify them.
108 // This Clone operation is a quick fix to the data race introduced
109 // in CL 278872 by the clearing of the Comment and Doc fields below.
110 node = astutil.CloneNode(node)
111
112 // Flatten the ast node since it could have multiple field names per list item while
113 // *types.Struct only have one item per field.
114 // TODO: Preserve multi-named fields instead of flattening.
115 var flat []*ast.Field
116 for _, f := range node.Fields.List {
117 // TODO: Preserve comment, for now get rid of them.
118 // See https://github.com/golang/go/issues/20744
119 f.Comment = nil
120 f.Doc = nil
121 if len(f.Names) <= 1 {
122 flat = append(flat, f)
123 continue
124 }
125 for _, name := range f.Names {
126 flat = append(flat, &ast.Field{
127 Names: []*ast.Ident{name},
128 Type: f.Type,
129 })
130 }
131 }
132
133 // Sort fields according to the optimal order.
134 var reordered []*ast.Field
135 for _, index := range indexes {
136 reordered = append(reordered, flat[index])
137 }
138
139 newStr := &ast.StructType{
140 Fields: &ast.FieldList{
141 List: reordered,
142 },
143 }
144
145 // Write the newly aligned struct node to get the content for suggested fixes.
146 var buf bytes.Buffer
147 if err := format.Node(&buf, token.NewFileSet(), newStr); err != nil {
148 return
149 }
150
151 pass.Report(analysis.Diagnostic{
152 Pos: node.Pos(),
153 End: node.Pos() + token.Pos(len("struct")),
154 Message: message,
155 SuggestedFixes: []analysis.SuggestedFix{{
156 Message: "Rearrange fields",
157 TextEdits: []analysis.TextEdit{{
158 Pos: node.Pos(),
159 End: node.End(),
160 NewText: buf.Bytes(),
161 }},
162 }},
163 })
164 }
165
166 func optimalOrder(str *types.Struct, sizes *gcSizes) (*types.Struct, []int) {
167 nf := str.NumFields()
168
169 type elem struct {
170 index int
171 alignof int64
172 sizeof int64
173 ptrdata int64
174 }
175
176 elems := make([]elem, nf)
177 for i := range nf {
178 field := str.Field(i)
179 ft := field.Type()
180 elems[i] = elem{
181 i,
182 sizes.Alignof(ft),
183 sizes.Sizeof(ft),
184 sizes.ptrdata(ft),
185 }
186 }
187
188 sort.Slice(elems, func(i, j int) bool {
189 ei := &elems[i]
190 ej := &elems[j]
191
192 // Place zero sized objects before non-zero sized objects.
193 zeroi := ei.sizeof == 0
194 zeroj := ej.sizeof == 0
195 if zeroi != zeroj {
196 return zeroi
197 }
198
199 // Next, place more tightly aligned objects before less tightly aligned objects.
200 if ei.alignof != ej.alignof {
201 return ei.alignof > ej.alignof
202 }
203
204 // Place pointerful objects before pointer-free objects.
205 noptrsi := ei.ptrdata == 0
206 noptrsj := ej.ptrdata == 0
207 if noptrsi != noptrsj {
208 return noptrsj
209 }
210
211 if !noptrsi {
212 // If both have pointers...
213
214 // ... then place objects with less trailing
215 // non-pointer bytes earlier. That is, place
216 // the field with the most trailing
217 // non-pointer bytes at the end of the
218 // pointerful section.
219 traili := ei.sizeof - ei.ptrdata
220 trailj := ej.sizeof - ej.ptrdata
221 if traili != trailj {
222 return traili < trailj
223 }
224 }
225
226 // Lastly, order by size.
227 if ei.sizeof != ej.sizeof {
228 return ei.sizeof > ej.sizeof
229 }
230
231 return false
232 })
233
234 fields := make([]*types.Var, nf)
235 indexes := make([]int, nf)
236 for i, e := range elems {
237 fields[i] = str.Field(e.index)
238 indexes[i] = e.index
239 }
240 return types.NewStruct(fields, nil), indexes
241 }
242
243 // Code below based on go/types.StdSizes.
244
245 type gcSizes struct {
246 WordSize int64
247 MaxAlign int64
248 }
249
250 func (s *gcSizes) Alignof(T types.Type) int64 {
251 // For arrays and structs, alignment is defined in terms
252 // of alignment of the elements and fields, respectively.
253 switch t := T.Underlying().(type) {
254 case *types.Array:
255 // spec: "For a variable x of array type: unsafe.Alignof(x)
256 // is the same as unsafe.Alignof(x[0]), but at least 1."
257 return s.Alignof(t.Elem())
258 case *types.Struct:
259 // spec: "For a variable x of struct type: unsafe.Alignof(x)
260 // is the largest of the values unsafe.Alignof(x.f) for each
261 // field f of x, but at least 1."
262 max := int64(1)
263 for i, nf := 0, t.NumFields(); i < nf; i++ {
264 if a := s.Alignof(t.Field(i).Type()); a > max {
265 max = a
266 }
267 }
268 return max
269 }
270 a := s.Sizeof(T) // may be 0
271 // spec: "For a variable x of any type: unsafe.Alignof(x) is at least 1."
272 if a < 1 {
273 return 1
274 }
275 if a > s.MaxAlign {
276 return s.MaxAlign
277 }
278 return a
279 }
280
281 var basicSizes = [...]byte{
282 types.Bool: 1,
283 types.Int8: 1,
284 types.Int16: 2,
285 types.Int32: 4,
286 types.Int64: 8,
287 types.Uint8: 1,
288 types.Uint16: 2,
289 types.Uint32: 4,
290 types.Uint64: 8,
291 types.Float32: 4,
292 types.Float64: 8,
293 types.Complex64: 8,
294 types.Complex128: 16,
295 }
296
297 func (s *gcSizes) Sizeof(T types.Type) int64 {
298 switch t := T.Underlying().(type) {
299 case *types.Basic:
300 k := t.Kind()
301 if int(k) < len(basicSizes) {
302 if s := basicSizes[k]; s > 0 {
303 return int64(s)
304 }
305 }
306 if k == types.String {
307 return s.WordSize * 2
308 }
309 case *types.Array:
310 return t.Len() * s.Sizeof(t.Elem())
311 case *types.Slice:
312 return s.WordSize * 3
313 case *types.Struct:
314 nf := t.NumFields()
315 if nf == 0 {
316 return 0
317 }
318
319 var o int64
320 max := int64(1)
321 for i := range nf {
322 ft := t.Field(i).Type()
323 a, sz := s.Alignof(ft), s.Sizeof(ft)
324 if a > max {
325 max = a
326 }
327 if i == nf-1 && sz == 0 && o != 0 {
328 sz = 1
329 }
330 o = align(o, a) + sz
331 }
332 return align(o, max)
333 case *types.Interface:
334 return s.WordSize * 2
335 }
336 return s.WordSize // catch-all
337 }
338
339 // align returns the smallest y >= x such that y % a == 0.
340 func align(x, a int64) int64 {
341 y := x + a - 1
342 return y - y%a
343 }
344
345 func (s *gcSizes) ptrdata(T types.Type) int64 {
346 switch t := T.Underlying().(type) {
347 case *types.Basic:
348 switch t.Kind() {
349 case types.String, types.UnsafePointer:
350 return s.WordSize
351 }
352 return 0
353 case *types.Chan, *types.Map, *types.Pointer, *types.Signature, *types.Slice:
354 return s.WordSize
355 case *types.Interface:
356 return 2 * s.WordSize
357 case *types.Array:
358 n := t.Len()
359 if n == 0 {
360 return 0
361 }
362 a := s.ptrdata(t.Elem())
363 if a == 0 {
364 return 0
365 }
366 z := s.Sizeof(t.Elem())
367 return (n-1)*z + a
368 case *types.Struct:
369 nf := t.NumFields()
370 if nf == 0 {
371 return 0
372 }
373
374 var o, p int64
375 for i := range nf {
376 ft := t.Field(i).Type()
377 a, sz := s.Alignof(ft), s.Sizeof(ft)
378 fp := s.ptrdata(ft)
379 o = align(o, a)
380 if fp != 0 {
381 p = o + fp
382 }
383 o += sz
384 }
385 return p
386 }
387
388 panic("impossible")
389 }