codekingpro commited on
Commit
fc11197
·
verified ·
1 Parent(s): 4929087

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. go/src/cmd/compile/internal/abi/abiutils.go +688 -0
  2. go/src/cmd/compile/internal/abt/avlint32.go +825 -0
  3. go/src/cmd/compile/internal/abt/avlint32_test.go +700 -0
  4. go/src/cmd/compile/internal/amd64/galign.go +27 -0
  5. go/src/cmd/compile/internal/amd64/ggen.go +41 -0
  6. go/src/cmd/compile/internal/amd64/simdssa.go +0 -0
  7. go/src/cmd/compile/internal/amd64/ssa.go +2568 -0
  8. go/src/cmd/compile/internal/amd64/versions_test.go +434 -0
  9. go/src/cmd/compile/internal/arm/galign.go +25 -0
  10. go/src/cmd/compile/internal/arm/ggen.go +60 -0
  11. go/src/cmd/compile/internal/arm/ssa.go +1115 -0
  12. go/src/cmd/compile/internal/arm64/galign.go +27 -0
  13. go/src/cmd/compile/internal/arm64/ggen.go +44 -0
  14. go/src/cmd/compile/internal/arm64/ssa.go +1800 -0
  15. go/src/cmd/compile/internal/base/base.go +27 -0
  16. go/src/cmd/compile/internal/base/bootstrap_false.go +11 -0
  17. go/src/cmd/compile/internal/base/bootstrap_true.go +11 -0
  18. go/src/cmd/compile/internal/base/debug.go +95 -0
  19. go/src/cmd/compile/internal/base/flag.go +607 -0
  20. go/src/cmd/compile/internal/base/hashdebug.go +421 -0
  21. go/src/cmd/compile/internal/base/hashdebug_test.go +140 -0
  22. go/src/cmd/compile/internal/base/link.go +53 -0
  23. go/src/cmd/compile/internal/base/mapfile_mmap.go +45 -0
  24. go/src/cmd/compile/internal/base/mapfile_read.go +21 -0
  25. go/src/cmd/compile/internal/base/print.go +288 -0
  26. go/src/cmd/compile/internal/base/startheap.go +272 -0
  27. go/src/cmd/compile/internal/base/timings.go +237 -0
  28. go/src/cmd/compile/internal/bitvec/bv.go +200 -0
  29. go/src/cmd/compile/internal/bloop/bloop.go +402 -0
  30. go/src/cmd/compile/internal/compare/compare.go +385 -0
  31. go/src/cmd/compile/internal/compare/compare_test.go +101 -0
  32. go/src/cmd/compile/internal/coverage/cover.go +200 -0
  33. go/src/cmd/compile/internal/deadlocals/deadlocals.go +199 -0
  34. go/src/cmd/compile/internal/devirtualize/devirtualize.go +600 -0
  35. go/src/cmd/compile/internal/devirtualize/pgo.go +829 -0
  36. go/src/cmd/compile/internal/devirtualize/pgo_test.go +219 -0
  37. go/src/cmd/compile/internal/dwarfgen/dwarf.go +672 -0
  38. go/src/cmd/compile/internal/dwarfgen/dwinl.go +441 -0
  39. go/src/cmd/compile/internal/dwarfgen/linenum_test.go +105 -0
  40. go/src/cmd/compile/internal/dwarfgen/marker.go +94 -0
  41. go/src/cmd/compile/internal/dwarfgen/scope.go +136 -0
  42. go/src/cmd/compile/internal/dwarfgen/scope_test.go +528 -0
  43. go/src/cmd/compile/internal/escape/alias.go +528 -0
  44. go/src/cmd/compile/internal/escape/assign.go +128 -0
  45. go/src/cmd/compile/internal/escape/call.go +425 -0
  46. go/src/cmd/compile/internal/escape/escape.go +672 -0
  47. go/src/cmd/compile/internal/escape/expr.go +341 -0
  48. go/src/cmd/compile/internal/escape/graph.go +360 -0
  49. go/src/cmd/compile/internal/escape/leaks.go +144 -0
  50. go/src/cmd/compile/internal/escape/solve.go +397 -0
go/src/cmd/compile/internal/abi/abiutils.go ADDED
@@ -0,0 +1,688 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 abi
6
+
7
+ import (
8
+ "cmd/compile/internal/base"
9
+ "cmd/compile/internal/ir"
10
+ "cmd/compile/internal/types"
11
+ "cmd/internal/obj"
12
+ "cmd/internal/src"
13
+ "fmt"
14
+ "math"
15
+ "sync"
16
+ )
17
+
18
+ //......................................................................
19
+ //
20
+ // Public/exported bits of the ABI utilities.
21
+ //
22
+
23
+ // ABIParamResultInfo stores the results of processing a given
24
+ // function type to compute stack layout and register assignments. For
25
+ // each input and output parameter we capture whether the param was
26
+ // register-assigned (and to which register(s)) or the stack offset
27
+ // for the param if is not going to be passed in registers according
28
+ // to the rules in the Go internal ABI specification (1.17).
29
+ type ABIParamResultInfo struct {
30
+ inparams []ABIParamAssignment // Includes receiver for method calls. Does NOT include hidden closure pointer.
31
+ outparams []ABIParamAssignment
32
+ offsetToSpillArea int64
33
+ spillAreaSize int64
34
+ inRegistersUsed int
35
+ outRegistersUsed int
36
+ config *ABIConfig // to enable String() method
37
+ }
38
+
39
+ func (a *ABIParamResultInfo) Config() *ABIConfig {
40
+ return a.config
41
+ }
42
+
43
+ func (a *ABIParamResultInfo) InParams() []ABIParamAssignment {
44
+ return a.inparams
45
+ }
46
+
47
+ func (a *ABIParamResultInfo) OutParams() []ABIParamAssignment {
48
+ return a.outparams
49
+ }
50
+
51
+ func (a *ABIParamResultInfo) InRegistersUsed() int {
52
+ return a.inRegistersUsed
53
+ }
54
+
55
+ func (a *ABIParamResultInfo) OutRegistersUsed() int {
56
+ return a.outRegistersUsed
57
+ }
58
+
59
+ func (a *ABIParamResultInfo) InParam(i int) *ABIParamAssignment {
60
+ return &a.inparams[i]
61
+ }
62
+
63
+ func (a *ABIParamResultInfo) OutParam(i int) *ABIParamAssignment {
64
+ return &a.outparams[i]
65
+ }
66
+
67
+ func (a *ABIParamResultInfo) SpillAreaOffset() int64 {
68
+ return a.offsetToSpillArea
69
+ }
70
+
71
+ func (a *ABIParamResultInfo) SpillAreaSize() int64 {
72
+ return a.spillAreaSize
73
+ }
74
+
75
+ // ArgWidth returns the amount of stack needed for all the inputs
76
+ // and outputs of a function or method, including ABI-defined parameter
77
+ // slots and ABI-defined spill slots for register-resident parameters.
78
+ // The name is inherited from (*Type).ArgWidth(), which it replaces.
79
+ func (a *ABIParamResultInfo) ArgWidth() int64 {
80
+ return a.spillAreaSize + a.offsetToSpillArea - a.config.LocalsOffset()
81
+ }
82
+
83
+ // RegIndex stores the index into the set of machine registers used by
84
+ // the ABI on a specific architecture for parameter passing. RegIndex
85
+ // values 0 through N-1 (where N is the number of integer registers
86
+ // used for param passing according to the ABI rules) describe integer
87
+ // registers; values N through M (where M is the number of floating
88
+ // point registers used). Thus if the ABI says there are 5 integer
89
+ // registers and 7 floating point registers, then RegIndex value of 4
90
+ // indicates the 5th integer register, and a RegIndex value of 11
91
+ // indicates the 7th floating point register.
92
+ type RegIndex uint8
93
+
94
+ // ABIParamAssignment holds information about how a specific param or
95
+ // result will be passed: in registers (in which case 'Registers' is
96
+ // populated) or on the stack (in which case 'Offset' is set to a
97
+ // non-negative stack offset). The values in 'Registers' are indices
98
+ // (as described above), not architected registers.
99
+ type ABIParamAssignment struct {
100
+ Type *types.Type
101
+ Name *ir.Name
102
+ Registers []RegIndex
103
+ offset int32
104
+ }
105
+
106
+ // Offset returns the stack offset for addressing the parameter that "a" describes.
107
+ // This will panic if "a" describes a register-allocated parameter.
108
+ func (a *ABIParamAssignment) Offset() int32 {
109
+ if len(a.Registers) > 0 {
110
+ base.Fatalf("register allocated parameters have no offset")
111
+ }
112
+ return a.offset
113
+ }
114
+
115
+ // RegisterTypes returns a slice of the types of the registers
116
+ // corresponding to a slice of parameters. The returned slice
117
+ // has capacity for one more, likely a memory type.
118
+ func RegisterTypes(apa []ABIParamAssignment) []*types.Type {
119
+ rcount := 0
120
+ for _, pa := range apa {
121
+ rcount += len(pa.Registers)
122
+ }
123
+ if rcount == 0 {
124
+ // Note that this catches top-level struct{} and [0]Foo, which are stack allocated.
125
+ return make([]*types.Type, 0, 1)
126
+ }
127
+ rts := make([]*types.Type, 0, rcount+1)
128
+ for _, pa := range apa {
129
+ if len(pa.Registers) == 0 {
130
+ continue
131
+ }
132
+ rts = appendParamTypes(rts, pa.Type)
133
+ }
134
+ return rts
135
+ }
136
+
137
+ func (pa *ABIParamAssignment) RegisterTypesAndOffsets() ([]*types.Type, []int64) {
138
+ l := len(pa.Registers)
139
+ if l == 0 {
140
+ return nil, nil
141
+ }
142
+ typs := make([]*types.Type, 0, l)
143
+ offs := make([]int64, 0, l)
144
+ offs, _ = appendParamOffsets(offs, 0, pa.Type) // 0 is aligned for everything.
145
+ return appendParamTypes(typs, pa.Type), offs
146
+ }
147
+
148
+ func appendParamTypes(rts []*types.Type, t *types.Type) []*types.Type {
149
+ w := t.Size()
150
+ if w == 0 {
151
+ return rts
152
+ }
153
+ if t.IsScalar() || t.IsPtrShaped() || t.IsSIMD() {
154
+ if t.IsComplex() {
155
+ c := types.FloatForComplex(t)
156
+ return append(rts, c, c)
157
+ } else {
158
+ if int(t.Size()) <= types.RegSize || t.IsSIMD() {
159
+ return append(rts, t)
160
+ }
161
+ // assume 64bit int on 32-bit machine
162
+ // TODO endianness? Should high-order (sign bits) word come first?
163
+ if t.IsSigned() {
164
+ rts = append(rts, types.Types[types.TINT32])
165
+ } else {
166
+ rts = append(rts, types.Types[types.TUINT32])
167
+ }
168
+ return append(rts, types.Types[types.TUINT32])
169
+ }
170
+ } else {
171
+ typ := t.Kind()
172
+ switch typ {
173
+ case types.TARRAY:
174
+ for i := int64(0); i < t.NumElem(); i++ { // 0 gets no registers, plus future-proofing.
175
+ rts = appendParamTypes(rts, t.Elem())
176
+ }
177
+ case types.TSTRUCT:
178
+ for _, f := range t.Fields() {
179
+ if f.Type.Size() > 0 { // embedded zero-width types receive no registers
180
+ rts = appendParamTypes(rts, f.Type)
181
+ }
182
+ }
183
+ case types.TSLICE:
184
+ return appendParamTypes(rts, synthSlice)
185
+ case types.TSTRING:
186
+ return appendParamTypes(rts, synthString)
187
+ case types.TINTER:
188
+ return appendParamTypes(rts, synthIface)
189
+ }
190
+ }
191
+ return rts
192
+ }
193
+
194
+ // appendParamOffsets appends the offset(s) of type t, starting from "at",
195
+ // to input offsets, and returns the longer slice and the next unused offset.
196
+ // at should already be aligned for t.
197
+ func appendParamOffsets(offsets []int64, at int64, t *types.Type) ([]int64, int64) {
198
+ w := t.Size()
199
+ if w == 0 {
200
+ return offsets, at
201
+ }
202
+ if t.IsSIMD() {
203
+ return append(offsets, at), at + w
204
+ }
205
+ if t.IsScalar() || t.IsPtrShaped() {
206
+ if t.IsComplex() || int(t.Size()) > types.RegSize { // complex and *int64 on 32-bit
207
+ s := w / 2
208
+ return append(offsets, at, at+s), at + w
209
+ } else {
210
+ return append(offsets, at), at + w
211
+ }
212
+ } else {
213
+ typ := t.Kind()
214
+ switch typ {
215
+ case types.TARRAY:
216
+ te := t.Elem()
217
+ for i := int64(0); i < t.NumElem(); i++ {
218
+ at = align(at, te)
219
+ offsets, at = appendParamOffsets(offsets, at, te)
220
+ }
221
+ case types.TSTRUCT:
222
+ at0 := at
223
+ for i, f := range t.Fields() {
224
+ at = at0 + f.Offset // Fields may be over-aligned, see wasm32.
225
+ offsets, at = appendParamOffsets(offsets, at, f.Type)
226
+ if f.Type.Size() == 0 && i == t.NumFields()-1 {
227
+ at++ // last field has zero width
228
+ }
229
+ }
230
+ at = align(at, t) // type size is rounded up to its alignment
231
+ case types.TSLICE:
232
+ return appendParamOffsets(offsets, at, synthSlice)
233
+ case types.TSTRING:
234
+ return appendParamOffsets(offsets, at, synthString)
235
+ case types.TINTER:
236
+ return appendParamOffsets(offsets, at, synthIface)
237
+ }
238
+ }
239
+ return offsets, at
240
+ }
241
+
242
+ // FrameOffset returns the frame-pointer-relative location that a function
243
+ // would spill its input or output parameter to, if such a spill slot exists.
244
+ // If there is none defined (e.g., register-allocated outputs) it panics.
245
+ // For register-allocated inputs that is their spill offset reserved for morestack;
246
+ // for stack-allocated inputs and outputs, that is their location on the stack.
247
+ // (In a future version of the ABI, register-resident inputs may lose their defined
248
+ // spill area to help reduce stack sizes.)
249
+ func (a *ABIParamAssignment) FrameOffset(i *ABIParamResultInfo) int64 {
250
+ if a.offset == -1 {
251
+ base.Fatalf("function parameter has no ABI-defined frame-pointer offset")
252
+ }
253
+ if len(a.Registers) == 0 { // passed on stack
254
+ return int64(a.offset) - i.config.LocalsOffset()
255
+ }
256
+ // spill area for registers
257
+ return int64(a.offset) + i.SpillAreaOffset() - i.config.LocalsOffset()
258
+ }
259
+
260
+ // RegAmounts holds a specified number of integer/float registers.
261
+ type RegAmounts struct {
262
+ intRegs int
263
+ floatRegs int
264
+ }
265
+
266
+ // ABIConfig captures the number of registers made available
267
+ // by the ABI rules for parameter passing and result returning.
268
+ type ABIConfig struct {
269
+ // Do we need anything more than this?
270
+ offsetForLocals int64 // e.g., obj.(*Link).Arch.FixedFrameSize -- extra linkage information on some architectures.
271
+ regAmounts RegAmounts
272
+ which obj.ABI
273
+ }
274
+
275
+ // NewABIConfig returns a new ABI configuration for an architecture with
276
+ // iRegsCount integer/pointer registers and fRegsCount floating point registers.
277
+ func NewABIConfig(iRegsCount, fRegsCount int, offsetForLocals int64, which uint8) *ABIConfig {
278
+ return &ABIConfig{offsetForLocals: offsetForLocals, regAmounts: RegAmounts{iRegsCount, fRegsCount}, which: obj.ABI(which)}
279
+ }
280
+
281
+ // Copy returns config.
282
+ //
283
+ // TODO(mdempsky): Remove.
284
+ func (config *ABIConfig) Copy() *ABIConfig {
285
+ return config
286
+ }
287
+
288
+ // Which returns the ABI number
289
+ func (config *ABIConfig) Which() obj.ABI {
290
+ return config.which
291
+ }
292
+
293
+ // LocalsOffset returns the architecture-dependent offset from SP for args and results.
294
+ // In theory this is only used for debugging; it ought to already be incorporated into
295
+ // results from the ABI-related methods
296
+ func (config *ABIConfig) LocalsOffset() int64 {
297
+ return config.offsetForLocals
298
+ }
299
+
300
+ // FloatIndexFor translates r into an index in the floating point parameter
301
+ // registers. If the result is negative, the input index was actually for the
302
+ // integer parameter registers.
303
+ func (config *ABIConfig) FloatIndexFor(r RegIndex) int64 {
304
+ return int64(r) - int64(config.regAmounts.intRegs)
305
+ }
306
+
307
+ // NumParamRegs returns the total number of registers used to
308
+ // represent a parameter of the given type, which must be register
309
+ // assignable.
310
+ func (config *ABIConfig) NumParamRegs(typ *types.Type) int {
311
+ intRegs, floatRegs := typ.Registers()
312
+ if intRegs == math.MaxUint8 && floatRegs == math.MaxUint8 {
313
+ base.Fatalf("cannot represent parameters of type %v in registers", typ)
314
+ }
315
+ return int(intRegs) + int(floatRegs)
316
+ }
317
+
318
+ // ABIAnalyzeTypes takes slices of parameter and result types, and returns an ABIParamResultInfo,
319
+ // based on the given configuration. This is the same result computed by config.ABIAnalyze applied to the
320
+ // corresponding method/function type, except that all the embedded parameter names are nil.
321
+ // This is intended for use by ssagen/ssa.go:(*state).rtcall, for runtime functions that lack a parsed function type.
322
+ func (config *ABIConfig) ABIAnalyzeTypes(params, results []*types.Type) *ABIParamResultInfo {
323
+ setup()
324
+ s := assignState{
325
+ stackOffset: config.offsetForLocals,
326
+ rTotal: config.regAmounts,
327
+ }
328
+
329
+ assignParams := func(params []*types.Type, isResult bool) []ABIParamAssignment {
330
+ res := make([]ABIParamAssignment, len(params))
331
+ for i, param := range params {
332
+ res[i] = s.assignParam(param, nil, isResult)
333
+ }
334
+ return res
335
+ }
336
+
337
+ info := &ABIParamResultInfo{config: config}
338
+
339
+ // Inputs
340
+ info.inparams = assignParams(params, false)
341
+ s.stackOffset = types.RoundUp(s.stackOffset, int64(types.RegSize))
342
+ info.inRegistersUsed = s.rUsed.intRegs + s.rUsed.floatRegs
343
+
344
+ // Outputs
345
+ s.rUsed = RegAmounts{}
346
+ info.outparams = assignParams(results, true)
347
+ // The spill area is at a register-aligned offset and its size is rounded up to a register alignment.
348
+ // TODO in theory could align offset only to minimum required by spilled data types.
349
+ info.offsetToSpillArea = alignTo(s.stackOffset, types.RegSize)
350
+ info.spillAreaSize = alignTo(s.spillOffset, types.RegSize)
351
+ info.outRegistersUsed = s.rUsed.intRegs + s.rUsed.floatRegs
352
+
353
+ return info
354
+ }
355
+
356
+ // ABIAnalyzeFuncType takes a function type 'ft' and an ABI rules description
357
+ // 'config' and analyzes the function to determine how its parameters
358
+ // and results will be passed (in registers or on the stack), returning
359
+ // an ABIParamResultInfo object that holds the results of the analysis.
360
+ func (config *ABIConfig) ABIAnalyzeFuncType(ft *types.Type) *ABIParamResultInfo {
361
+ setup()
362
+ s := assignState{
363
+ stackOffset: config.offsetForLocals,
364
+ rTotal: config.regAmounts,
365
+ }
366
+
367
+ assignParams := func(params []*types.Field, isResult bool) []ABIParamAssignment {
368
+ res := make([]ABIParamAssignment, len(params))
369
+ for i, param := range params {
370
+ var name *ir.Name
371
+ if param.Nname != nil {
372
+ name = param.Nname.(*ir.Name)
373
+ }
374
+ res[i] = s.assignParam(param.Type, name, isResult)
375
+ }
376
+ return res
377
+ }
378
+
379
+ info := &ABIParamResultInfo{config: config}
380
+
381
+ // Inputs
382
+ info.inparams = assignParams(ft.RecvParams(), false)
383
+ s.stackOffset = types.RoundUp(s.stackOffset, int64(types.RegSize))
384
+ info.inRegistersUsed = s.rUsed.intRegs + s.rUsed.floatRegs
385
+
386
+ // Outputs
387
+ s.rUsed = RegAmounts{}
388
+ info.outparams = assignParams(ft.Results(), true)
389
+ // The spill area is at a register-aligned offset and its size is rounded up to a register alignment.
390
+ // TODO in theory could align offset only to minimum required by spilled data types.
391
+ info.offsetToSpillArea = alignTo(s.stackOffset, types.RegSize)
392
+ info.spillAreaSize = alignTo(s.spillOffset, types.RegSize)
393
+ info.outRegistersUsed = s.rUsed.intRegs + s.rUsed.floatRegs
394
+ return info
395
+ }
396
+
397
+ // ABIAnalyze returns the same result as ABIAnalyzeFuncType, but also
398
+ // updates the offsets of all the receiver, input, and output fields.
399
+ // If setNname is true, it also sets the FrameOffset of the Nname for
400
+ // the field(s); this is for use when compiling a function and figuring out
401
+ // spill locations. Doing this for callers can cause races for register
402
+ // outputs because their frame location transitions from BOGUS_FUNARG_OFFSET
403
+ // to zero to an as-if-AUTO offset that has no use for callers.
404
+ func (config *ABIConfig) ABIAnalyze(t *types.Type, setNname bool) *ABIParamResultInfo {
405
+ result := config.ABIAnalyzeFuncType(t)
406
+
407
+ // Fill in the frame offsets for receiver, inputs, results
408
+ for i, f := range t.RecvParams() {
409
+ config.updateOffset(result, f, result.inparams[i], false, setNname)
410
+ }
411
+ for i, f := range t.Results() {
412
+ config.updateOffset(result, f, result.outparams[i], true, setNname)
413
+ }
414
+ return result
415
+ }
416
+
417
+ func (config *ABIConfig) updateOffset(result *ABIParamResultInfo, f *types.Field, a ABIParamAssignment, isResult, setNname bool) {
418
+ if f.Offset != types.BADWIDTH {
419
+ base.Fatalf("field offset for %s at %s has been set to %d", f.Sym, base.FmtPos(f.Pos), f.Offset)
420
+ }
421
+
422
+ // Everything except return values in registers has either a frame home (if not in a register) or a frame spill location.
423
+ if !isResult || len(a.Registers) == 0 {
424
+ // The type frame offset DOES NOT show effects of minimum frame size.
425
+ // Getting this wrong breaks stackmaps, see liveness/plive.go:WriteFuncMap and typebits/typebits.go:Set
426
+ off := a.FrameOffset(result)
427
+ if setNname && f.Nname != nil {
428
+ f.Nname.(*ir.Name).SetFrameOffset(off)
429
+ f.Nname.(*ir.Name).SetIsOutputParamInRegisters(false)
430
+ }
431
+ } else {
432
+ if setNname && f.Nname != nil {
433
+ fname := f.Nname.(*ir.Name)
434
+ fname.SetIsOutputParamInRegisters(true)
435
+ fname.SetFrameOffset(0)
436
+ }
437
+ }
438
+ }
439
+
440
+ //......................................................................
441
+ //
442
+ // Non-public portions.
443
+
444
+ // regString produces a human-readable version of a RegIndex.
445
+ func (c *RegAmounts) regString(r RegIndex) string {
446
+ if int(r) < c.intRegs {
447
+ return fmt.Sprintf("I%d", int(r))
448
+ } else if int(r) < c.intRegs+c.floatRegs {
449
+ return fmt.Sprintf("F%d", int(r)-c.intRegs)
450
+ }
451
+ return fmt.Sprintf("<?>%d", r)
452
+ }
453
+
454
+ // ToString method renders an ABIParamAssignment in human-readable
455
+ // form, suitable for debugging or unit testing.
456
+ func (ri *ABIParamAssignment) ToString(config *ABIConfig, extra bool) string {
457
+ regs := "R{"
458
+ offname := "spilloffset" // offset is for spill for register(s)
459
+ if len(ri.Registers) == 0 {
460
+ offname = "offset" // offset is for memory arg
461
+ }
462
+ for _, r := range ri.Registers {
463
+ regs += " " + config.regAmounts.regString(r)
464
+ if extra {
465
+ regs += fmt.Sprintf("(%d)", r)
466
+ }
467
+ }
468
+ if extra {
469
+ regs += fmt.Sprintf(" | #I=%d, #F=%d", config.regAmounts.intRegs, config.regAmounts.floatRegs)
470
+ }
471
+ return fmt.Sprintf("%s } %s: %d typ: %v", regs, offname, ri.offset, ri.Type)
472
+ }
473
+
474
+ // String method renders an ABIParamResultInfo in human-readable
475
+ // form, suitable for debugging or unit testing.
476
+ func (ri *ABIParamResultInfo) String() string {
477
+ res := ""
478
+ for k, p := range ri.inparams {
479
+ res += fmt.Sprintf("IN %d: %s\n", k, p.ToString(ri.config, false))
480
+ }
481
+ for k, r := range ri.outparams {
482
+ res += fmt.Sprintf("OUT %d: %s\n", k, r.ToString(ri.config, false))
483
+ }
484
+ res += fmt.Sprintf("offsetToSpillArea: %d spillAreaSize: %d",
485
+ ri.offsetToSpillArea, ri.spillAreaSize)
486
+ return res
487
+ }
488
+
489
+ // assignState holds intermediate state during the register assigning process
490
+ // for a given function signature.
491
+ type assignState struct {
492
+ rTotal RegAmounts // total reg amounts from ABI rules
493
+ rUsed RegAmounts // regs used by params completely assigned so far
494
+ stackOffset int64 // current stack offset
495
+ spillOffset int64 // current spill offset
496
+ }
497
+
498
+ // align returns a rounded up to t's alignment.
499
+ func align(a int64, t *types.Type) int64 {
500
+ return alignTo(a, int(uint8(t.Alignment())))
501
+ }
502
+
503
+ // alignTo returns a rounded up to t, where t must be 0 or a power of 2.
504
+ func alignTo(a int64, t int) int64 {
505
+ if t == 0 {
506
+ return a
507
+ }
508
+ return types.RoundUp(a, int64(t))
509
+ }
510
+
511
+ // nextSlot allocates the next available slot for typ.
512
+ func nextSlot(offsetp *int64, typ *types.Type) int64 {
513
+ offset := align(*offsetp, typ)
514
+ *offsetp = offset + typ.Size()
515
+ return offset
516
+ }
517
+
518
+ // allocateRegs returns an ordered list of register indices for a parameter or result
519
+ // that we've just determined to be register-assignable. The number of registers
520
+ // needed is assumed to be stored in state.pUsed.
521
+ func (state *assignState) allocateRegs(regs []RegIndex, t *types.Type) []RegIndex {
522
+ if t.Size() == 0 {
523
+ return regs
524
+ }
525
+ ri := state.rUsed.intRegs
526
+ rf := state.rUsed.floatRegs
527
+ if t.IsScalar() || t.IsPtrShaped() || t.IsSIMD() {
528
+ if t.IsComplex() {
529
+ regs = append(regs, RegIndex(rf+state.rTotal.intRegs), RegIndex(rf+1+state.rTotal.intRegs))
530
+ rf += 2
531
+ } else if t.IsFloat() || t.IsSIMD() {
532
+ regs = append(regs, RegIndex(rf+state.rTotal.intRegs))
533
+ rf += 1
534
+ } else {
535
+ n := (int(t.Size()) + types.RegSize - 1) / types.RegSize
536
+ for i := 0; i < n; i++ { // looking ahead to really big integers
537
+ regs = append(regs, RegIndex(ri))
538
+ ri += 1
539
+ }
540
+ }
541
+ state.rUsed.intRegs = ri
542
+ state.rUsed.floatRegs = rf
543
+ return regs
544
+ } else {
545
+ typ := t.Kind()
546
+ switch typ {
547
+ case types.TARRAY:
548
+ for i := int64(0); i < t.NumElem(); i++ {
549
+ regs = state.allocateRegs(regs, t.Elem())
550
+ }
551
+ return regs
552
+ case types.TSTRUCT:
553
+ for _, f := range t.Fields() {
554
+ regs = state.allocateRegs(regs, f.Type)
555
+ }
556
+ return regs
557
+ case types.TSLICE:
558
+ return state.allocateRegs(regs, synthSlice)
559
+ case types.TSTRING:
560
+ return state.allocateRegs(regs, synthString)
561
+ case types.TINTER:
562
+ return state.allocateRegs(regs, synthIface)
563
+ }
564
+ }
565
+ base.Fatalf("was not expecting type %s", t)
566
+ panic("unreachable")
567
+ }
568
+
569
+ // synthOnce ensures that we only create the synth* fake types once.
570
+ var synthOnce sync.Once
571
+
572
+ // synthSlice, synthString, and syncIface are synthesized struct types
573
+ // meant to capture the underlying implementations of string/slice/interface.
574
+ var synthSlice *types.Type
575
+ var synthString *types.Type
576
+ var synthIface *types.Type
577
+
578
+ // setup performs setup for the register assignment utilities, manufacturing
579
+ // a small set of synthesized types that we'll need along the way.
580
+ func setup() {
581
+ synthOnce.Do(func() {
582
+ fname := types.BuiltinPkg.Lookup
583
+ nxp := src.NoXPos
584
+ bp := types.NewPtr(types.Types[types.TUINT8])
585
+ it := types.Types[types.TINT]
586
+ synthSlice = types.NewStruct([]*types.Field{
587
+ types.NewField(nxp, fname("ptr"), bp),
588
+ types.NewField(nxp, fname("len"), it),
589
+ types.NewField(nxp, fname("cap"), it),
590
+ })
591
+ types.CalcStructSize(synthSlice)
592
+ synthString = types.NewStruct([]*types.Field{
593
+ types.NewField(nxp, fname("data"), bp),
594
+ types.NewField(nxp, fname("len"), it),
595
+ })
596
+ types.CalcStructSize(synthString)
597
+ unsp := types.Types[types.TUNSAFEPTR]
598
+ synthIface = types.NewStruct([]*types.Field{
599
+ types.NewField(nxp, fname("f1"), unsp),
600
+ types.NewField(nxp, fname("f2"), unsp),
601
+ })
602
+ types.CalcStructSize(synthIface)
603
+ })
604
+ }
605
+
606
+ // assignParam processes a given receiver, param, or result
607
+ // of field f to determine whether it can be register assigned.
608
+ // The result of the analysis is recorded in the result
609
+ // ABIParamResultInfo held in 'state'.
610
+ func (state *assignState) assignParam(typ *types.Type, name *ir.Name, isResult bool) ABIParamAssignment {
611
+ registers := state.tryAllocRegs(typ)
612
+
613
+ var offset int64 = -1
614
+ if registers == nil { // stack allocated; needs stack slot
615
+ offset = nextSlot(&state.stackOffset, typ)
616
+ } else if !isResult { // register-allocated param; needs spill slot
617
+ offset = nextSlot(&state.spillOffset, typ)
618
+ }
619
+
620
+ return ABIParamAssignment{
621
+ Type: typ,
622
+ Name: name,
623
+ Registers: registers,
624
+ offset: int32(offset),
625
+ }
626
+ }
627
+
628
+ // tryAllocRegs attempts to allocate registers to represent a
629
+ // parameter of the given type. If unsuccessful, it returns nil.
630
+ func (state *assignState) tryAllocRegs(typ *types.Type) []RegIndex {
631
+ if typ.Size() == 0 {
632
+ return nil // zero-size parameters are defined as being stack allocated
633
+ }
634
+
635
+ intRegs, floatRegs := typ.Registers()
636
+ if int(intRegs) > state.rTotal.intRegs-state.rUsed.intRegs || int(floatRegs) > state.rTotal.floatRegs-state.rUsed.floatRegs {
637
+ return nil // too few available registers
638
+ }
639
+
640
+ regs := make([]RegIndex, 0, int(intRegs)+int(floatRegs))
641
+ return state.allocateRegs(regs, typ)
642
+ }
643
+
644
+ // ComputePadding returns a list of "post element" padding values in
645
+ // the case where we have a structure being passed in registers. Given
646
+ // a param assignment corresponding to a struct, it returns a list
647
+ // containing padding values for each field, e.g. the Kth element in
648
+ // the list is the amount of padding between field K and the following
649
+ // field. For things that are not structs (or structs without padding)
650
+ // it returns a list of zeros. Example:
651
+ //
652
+ // type small struct {
653
+ // x uint16
654
+ // y uint8
655
+ // z int32
656
+ // w int32
657
+ // }
658
+ //
659
+ // For this struct we would return a list [0, 1, 0, 0], meaning that
660
+ // we have one byte of padding after the second field, and no bytes of
661
+ // padding after any of the other fields. Input parameter "storage" is
662
+ // a slice with enough capacity to accommodate padding elements for
663
+ // the architected register set in question.
664
+ func (pa *ABIParamAssignment) ComputePadding(storage []uint64) []uint64 {
665
+ nr := len(pa.Registers)
666
+ padding := storage[:nr]
667
+ clear(padding)
668
+ if pa.Type.Kind() != types.TSTRUCT || nr == 0 {
669
+ return padding
670
+ }
671
+ types := make([]*types.Type, 0, nr)
672
+ types = appendParamTypes(types, pa.Type)
673
+ if len(types) != nr {
674
+ panic("internal error")
675
+ }
676
+ offsets, _ := appendParamOffsets([]int64{}, 0, pa.Type)
677
+ for idx, t := range types {
678
+ ts := t.Size()
679
+ off := offsets[idx] + ts
680
+ if idx < len(types)-1 {
681
+ noff := offsets[idx+1]
682
+ if noff != off {
683
+ padding[idx] = uint64(noff - off)
684
+ }
685
+ }
686
+ }
687
+ return padding
688
+ }
go/src/cmd/compile/internal/abt/avlint32.go ADDED
@@ -0,0 +1,825 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2022 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 abt
6
+
7
+ import (
8
+ "fmt"
9
+ "strconv"
10
+ "strings"
11
+ )
12
+
13
+ const (
14
+ LEAF_HEIGHT = 1
15
+ ZERO_HEIGHT = 0
16
+ NOT_KEY32 = int32(-0x80000000)
17
+ )
18
+
19
+ // T is the exported applicative balanced tree data type.
20
+ // A T can be used as a value; updates to one copy of the value
21
+ // do not change other copies.
22
+ type T struct {
23
+ root *node32
24
+ size int
25
+ }
26
+
27
+ // node32 is the internal tree node data type
28
+ type node32 struct {
29
+ // Standard conventions hold for left = smaller, right = larger
30
+ left, right *node32
31
+ data any
32
+ key int32
33
+ height_ int8
34
+ }
35
+
36
+ func makeNode(key int32) *node32 {
37
+ return &node32{key: key, height_: LEAF_HEIGHT}
38
+ }
39
+
40
+ // IsEmpty returns true iff t is empty.
41
+ func (t *T) IsEmpty() bool {
42
+ return t.root == nil
43
+ }
44
+
45
+ // IsSingle returns true iff t is a singleton (leaf).
46
+ func (t *T) IsSingle() bool {
47
+ return t.root != nil && t.root.isLeaf()
48
+ }
49
+
50
+ // VisitInOrder applies f to the key and data pairs in t,
51
+ // with keys ordered from smallest to largest.
52
+ func (t *T) VisitInOrder(f func(int32, any)) {
53
+ if t.root == nil {
54
+ return
55
+ }
56
+ t.root.visitInOrder(f)
57
+ }
58
+
59
+ func (n *node32) nilOrData() any {
60
+ if n == nil {
61
+ return nil
62
+ }
63
+ return n.data
64
+ }
65
+
66
+ func (n *node32) nilOrKeyAndData() (k int32, d any) {
67
+ if n == nil {
68
+ k = NOT_KEY32
69
+ d = nil
70
+ } else {
71
+ k = n.key
72
+ d = n.data
73
+ }
74
+ return
75
+ }
76
+
77
+ func (n *node32) height() int8 {
78
+ if n == nil {
79
+ return 0
80
+ }
81
+ return n.height_
82
+ }
83
+
84
+ // Find returns the data associated with x in the tree, or
85
+ // nil if x is not in the tree.
86
+ func (t *T) Find(x int32) any {
87
+ return t.root.find(x).nilOrData()
88
+ }
89
+
90
+ // Insert either adds x to the tree if x was not previously
91
+ // a key in the tree, or updates the data for x in the tree if
92
+ // x was already a key in the tree. The previous data associated
93
+ // with x is returned, and is nil if x was not previously a
94
+ // key in the tree.
95
+ func (t *T) Insert(x int32, data any) any {
96
+ if x == NOT_KEY32 {
97
+ panic("Cannot use sentinel value -0x80000000 as key")
98
+ }
99
+ n := t.root
100
+ var newroot *node32
101
+ var o *node32
102
+ if n == nil {
103
+ n = makeNode(x)
104
+ newroot = n
105
+ } else {
106
+ newroot, n, o = n.aInsert(x)
107
+ }
108
+ var r any
109
+ if o != nil {
110
+ r = o.data
111
+ } else {
112
+ t.size++
113
+ }
114
+ n.data = data
115
+ t.root = newroot
116
+ return r
117
+ }
118
+
119
+ func (t *T) Copy() *T {
120
+ u := *t
121
+ return &u
122
+ }
123
+
124
+ func (t *T) Delete(x int32) any {
125
+ n := t.root
126
+ if n == nil {
127
+ return nil
128
+ }
129
+ d, s := n.aDelete(x)
130
+ if d == nil {
131
+ return nil
132
+ }
133
+ t.root = s
134
+ t.size--
135
+ return d.data
136
+ }
137
+
138
+ func (t *T) DeleteMin() (int32, any) {
139
+ n := t.root
140
+ if n == nil {
141
+ return NOT_KEY32, nil
142
+ }
143
+ d, s := n.aDeleteMin()
144
+ if d == nil {
145
+ return NOT_KEY32, nil
146
+ }
147
+ t.root = s
148
+ t.size--
149
+ return d.key, d.data
150
+ }
151
+
152
+ func (t *T) DeleteMax() (int32, any) {
153
+ n := t.root
154
+ if n == nil {
155
+ return NOT_KEY32, nil
156
+ }
157
+ d, s := n.aDeleteMax()
158
+ if d == nil {
159
+ return NOT_KEY32, nil
160
+ }
161
+ t.root = s
162
+ t.size--
163
+ return d.key, d.data
164
+ }
165
+
166
+ func (t *T) Size() int {
167
+ return t.size
168
+ }
169
+
170
+ // Intersection returns the intersection of t and u, where the result
171
+ // data for any common keys is given by f(t's data, u's data) -- f need
172
+ // not be symmetric. If f returns nil, then the key and data are not
173
+ // added to the result. If f itself is nil, then whatever value was
174
+ // already present in the smaller set is used.
175
+ func (t *T) Intersection(u *T, f func(x, y any) any) *T {
176
+ if t.Size() == 0 || u.Size() == 0 {
177
+ return &T{}
178
+ }
179
+
180
+ // For faster execution and less allocation, prefer t smaller, iterate over t.
181
+ if t.Size() <= u.Size() {
182
+ v := t.Copy()
183
+ for it := t.Iterator(); !it.Done(); {
184
+ k, d := it.Next()
185
+ e := u.Find(k)
186
+ if e == nil {
187
+ v.Delete(k)
188
+ continue
189
+ }
190
+ if f == nil {
191
+ continue
192
+ }
193
+ if c := f(d, e); c != d {
194
+ if c == nil {
195
+ v.Delete(k)
196
+ } else {
197
+ v.Insert(k, c)
198
+ }
199
+ }
200
+ }
201
+ return v
202
+ }
203
+ v := u.Copy()
204
+ for it := u.Iterator(); !it.Done(); {
205
+ k, e := it.Next()
206
+ d := t.Find(k)
207
+ if d == nil {
208
+ v.Delete(k)
209
+ continue
210
+ }
211
+ if f == nil {
212
+ continue
213
+ }
214
+ if c := f(d, e); c != d {
215
+ if c == nil {
216
+ v.Delete(k)
217
+ } else {
218
+ v.Insert(k, c)
219
+ }
220
+ }
221
+ }
222
+
223
+ return v
224
+ }
225
+
226
+ // Union returns the union of t and u, where the result data for any common keys
227
+ // is given by f(t's data, u's data) -- f need not be symmetric. If f returns nil,
228
+ // then the key and data are not added to the result. If f itself is nil, then
229
+ // whatever value was already present in the larger set is used.
230
+ func (t *T) Union(u *T, f func(x, y any) any) *T {
231
+ if t.Size() == 0 {
232
+ return u
233
+ }
234
+ if u.Size() == 0 {
235
+ return t
236
+ }
237
+
238
+ if t.Size() >= u.Size() {
239
+ v := t.Copy()
240
+ for it := u.Iterator(); !it.Done(); {
241
+ k, e := it.Next()
242
+ d := t.Find(k)
243
+ if d == nil {
244
+ v.Insert(k, e)
245
+ continue
246
+ }
247
+ if f == nil {
248
+ continue
249
+ }
250
+ if c := f(d, e); c != d {
251
+ if c == nil {
252
+ v.Delete(k)
253
+ } else {
254
+ v.Insert(k, c)
255
+ }
256
+ }
257
+ }
258
+ return v
259
+ }
260
+
261
+ v := u.Copy()
262
+ for it := t.Iterator(); !it.Done(); {
263
+ k, d := it.Next()
264
+ e := u.Find(k)
265
+ if e == nil {
266
+ v.Insert(k, d)
267
+ continue
268
+ }
269
+ if f == nil {
270
+ continue
271
+ }
272
+ if c := f(d, e); c != d {
273
+ if c == nil {
274
+ v.Delete(k)
275
+ } else {
276
+ v.Insert(k, c)
277
+ }
278
+ }
279
+ }
280
+ return v
281
+ }
282
+
283
+ // Difference returns the difference of t and u, subject to the result
284
+ // of f applied to data corresponding to equal keys. If f returns nil
285
+ // (or if f is nil) then the key+data are excluded, as usual. If f
286
+ // returns not-nil, then that key+data pair is inserted. instead.
287
+ func (t *T) Difference(u *T, f func(x, y any) any) *T {
288
+ if t.Size() == 0 {
289
+ return &T{}
290
+ }
291
+ if u.Size() == 0 {
292
+ return t
293
+ }
294
+ v := t.Copy()
295
+ for it := t.Iterator(); !it.Done(); {
296
+ k, d := it.Next()
297
+ e := u.Find(k)
298
+ if e != nil {
299
+ if f == nil {
300
+ v.Delete(k)
301
+ continue
302
+ }
303
+ c := f(d, e)
304
+ if c == nil {
305
+ v.Delete(k)
306
+ continue
307
+ }
308
+ if c != d {
309
+ v.Insert(k, c)
310
+ }
311
+ }
312
+ }
313
+ return v
314
+ }
315
+
316
+ func (t *T) Iterator() Iterator {
317
+ return Iterator{it: t.root.iterator()}
318
+ }
319
+
320
+ func (t *T) Equals(u *T) bool {
321
+ if t == u {
322
+ return true
323
+ }
324
+ if t.Size() != u.Size() {
325
+ return false
326
+ }
327
+ return t.root.equals(u.root)
328
+ }
329
+
330
+ func (t *T) String() string {
331
+ var b strings.Builder
332
+ first := true
333
+ for it := t.Iterator(); !it.Done(); {
334
+ k, v := it.Next()
335
+ if first {
336
+ first = false
337
+ } else {
338
+ b.WriteString("; ")
339
+ }
340
+ b.WriteString(strconv.FormatInt(int64(k), 10))
341
+ b.WriteString(":")
342
+ fmt.Fprint(&b, v)
343
+ }
344
+ return b.String()
345
+ }
346
+
347
+ func (t *node32) equals(u *node32) bool {
348
+ if t == u {
349
+ return true
350
+ }
351
+ it, iu := t.iterator(), u.iterator()
352
+ for !it.done() && !iu.done() {
353
+ nt := it.next()
354
+ nu := iu.next()
355
+ if nt == nu {
356
+ continue
357
+ }
358
+ if nt.key != nu.key {
359
+ return false
360
+ }
361
+ if nt.data != nu.data {
362
+ return false
363
+ }
364
+ }
365
+ return it.done() == iu.done()
366
+ }
367
+
368
+ func (t *T) Equiv(u *T, eqv func(x, y any) bool) bool {
369
+ if t == u {
370
+ return true
371
+ }
372
+ if t.Size() != u.Size() {
373
+ return false
374
+ }
375
+ return t.root.equiv(u.root, eqv)
376
+ }
377
+
378
+ func (t *node32) equiv(u *node32, eqv func(x, y any) bool) bool {
379
+ if t == u {
380
+ return true
381
+ }
382
+ it, iu := t.iterator(), u.iterator()
383
+ for !it.done() && !iu.done() {
384
+ nt := it.next()
385
+ nu := iu.next()
386
+ if nt == nu {
387
+ continue
388
+ }
389
+ if nt.key != nu.key {
390
+ return false
391
+ }
392
+ if !eqv(nt.data, nu.data) {
393
+ return false
394
+ }
395
+ }
396
+ return it.done() == iu.done()
397
+ }
398
+
399
+ type iterator struct {
400
+ parents []*node32
401
+ }
402
+
403
+ type Iterator struct {
404
+ it iterator
405
+ }
406
+
407
+ func (it *Iterator) Next() (int32, any) {
408
+ x := it.it.next()
409
+ if x == nil {
410
+ return NOT_KEY32, nil
411
+ }
412
+ return x.key, x.data
413
+ }
414
+
415
+ func (it *Iterator) Done() bool {
416
+ return len(it.it.parents) == 0
417
+ }
418
+
419
+ func (t *node32) iterator() iterator {
420
+ if t == nil {
421
+ return iterator{}
422
+ }
423
+ it := iterator{parents: make([]*node32, 0, int(t.height()))}
424
+ it.leftmost(t)
425
+ return it
426
+ }
427
+
428
+ func (it *iterator) leftmost(t *node32) {
429
+ for t != nil {
430
+ it.parents = append(it.parents, t)
431
+ t = t.left
432
+ }
433
+ }
434
+
435
+ func (it *iterator) done() bool {
436
+ return len(it.parents) == 0
437
+ }
438
+
439
+ func (it *iterator) next() *node32 {
440
+ l := len(it.parents)
441
+ if l == 0 {
442
+ return nil
443
+ }
444
+ x := it.parents[l-1] // return value
445
+ if x.right != nil {
446
+ it.leftmost(x.right)
447
+ return x
448
+ }
449
+ // discard visited top of parents
450
+ l--
451
+ it.parents = it.parents[:l]
452
+ y := x // y is known visited/returned
453
+ for l > 0 && y == it.parents[l-1].right {
454
+ y = it.parents[l-1]
455
+ l--
456
+ it.parents = it.parents[:l]
457
+ }
458
+
459
+ return x
460
+ }
461
+
462
+ // Min returns the minimum element of t.
463
+ // If t is empty, then (NOT_KEY32, nil) is returned.
464
+ func (t *T) Min() (k int32, d any) {
465
+ return t.root.min().nilOrKeyAndData()
466
+ }
467
+
468
+ // Max returns the maximum element of t.
469
+ // If t is empty, then (NOT_KEY32, nil) is returned.
470
+ func (t *T) Max() (k int32, d any) {
471
+ return t.root.max().nilOrKeyAndData()
472
+ }
473
+
474
+ // Glb returns the greatest-lower-bound-exclusive of x and the associated
475
+ // data. If x has no glb in the tree, then (NOT_KEY32, nil) is returned.
476
+ func (t *T) Glb(x int32) (k int32, d any) {
477
+ return t.root.glb(x, false).nilOrKeyAndData()
478
+ }
479
+
480
+ // GlbEq returns the greatest-lower-bound-inclusive of x and the associated
481
+ // data. If x has no glbEQ in the tree, then (NOT_KEY32, nil) is returned.
482
+ func (t *T) GlbEq(x int32) (k int32, d any) {
483
+ return t.root.glb(x, true).nilOrKeyAndData()
484
+ }
485
+
486
+ // Lub returns the least-upper-bound-exclusive of x and the associated
487
+ // data. If x has no lub in the tree, then (NOT_KEY32, nil) is returned.
488
+ func (t *T) Lub(x int32) (k int32, d any) {
489
+ return t.root.lub(x, false).nilOrKeyAndData()
490
+ }
491
+
492
+ // LubEq returns the least-upper-bound-inclusive of x and the associated
493
+ // data. If x has no lubEq in the tree, then (NOT_KEY32, nil) is returned.
494
+ func (t *T) LubEq(x int32) (k int32, d any) {
495
+ return t.root.lub(x, true).nilOrKeyAndData()
496
+ }
497
+
498
+ func (t *node32) isLeaf() bool {
499
+ return t.left == nil && t.right == nil && t.height_ == LEAF_HEIGHT
500
+ }
501
+
502
+ func (t *node32) visitInOrder(f func(int32, any)) {
503
+ if t.left != nil {
504
+ t.left.visitInOrder(f)
505
+ }
506
+ f(t.key, t.data)
507
+ if t.right != nil {
508
+ t.right.visitInOrder(f)
509
+ }
510
+ }
511
+
512
+ func (t *node32) find(key int32) *node32 {
513
+ for t != nil {
514
+ if key < t.key {
515
+ t = t.left
516
+ } else if key > t.key {
517
+ t = t.right
518
+ } else {
519
+ return t
520
+ }
521
+ }
522
+ return nil
523
+ }
524
+
525
+ func (t *node32) min() *node32 {
526
+ if t == nil {
527
+ return t
528
+ }
529
+ for t.left != nil {
530
+ t = t.left
531
+ }
532
+ return t
533
+ }
534
+
535
+ func (t *node32) max() *node32 {
536
+ if t == nil {
537
+ return t
538
+ }
539
+ for t.right != nil {
540
+ t = t.right
541
+ }
542
+ return t
543
+ }
544
+
545
+ func (t *node32) glb(key int32, allow_eq bool) *node32 {
546
+ var best *node32 = nil
547
+ for t != nil {
548
+ if key <= t.key {
549
+ if allow_eq && key == t.key {
550
+ return t
551
+ }
552
+ // t is too big, glb is to left.
553
+ t = t.left
554
+ } else {
555
+ // t is a lower bound, record it and seek a better one.
556
+ best = t
557
+ t = t.right
558
+ }
559
+ }
560
+ return best
561
+ }
562
+
563
+ func (t *node32) lub(key int32, allow_eq bool) *node32 {
564
+ var best *node32 = nil
565
+ for t != nil {
566
+ if key >= t.key {
567
+ if allow_eq && key == t.key {
568
+ return t
569
+ }
570
+ // t is too small, lub is to right.
571
+ t = t.right
572
+ } else {
573
+ // t is an upper bound, record it and seek a better one.
574
+ best = t
575
+ t = t.left
576
+ }
577
+ }
578
+ return best
579
+ }
580
+
581
+ func (t *node32) aInsert(x int32) (newroot, newnode, oldnode *node32) {
582
+ // oldnode default of nil is good, others should be assigned.
583
+ if x == t.key {
584
+ oldnode = t
585
+ newt := *t
586
+ newnode = &newt
587
+ newroot = newnode
588
+ return
589
+ }
590
+ if x < t.key {
591
+ if t.left == nil {
592
+ t = t.copy()
593
+ n := makeNode(x)
594
+ t.left = n
595
+ newnode = n
596
+ newroot = t
597
+ t.height_ = 2 // was balanced w/ 0, sibling is height 0 or 1
598
+ return
599
+ }
600
+ var new_l *node32
601
+ new_l, newnode, oldnode = t.left.aInsert(x)
602
+ t = t.copy()
603
+ t.left = new_l
604
+ if new_l.height() > 1+t.right.height() {
605
+ newroot = t.aLeftIsHigh(newnode)
606
+ } else {
607
+ t.height_ = 1 + max(t.left.height(), t.right.height())
608
+ newroot = t
609
+ }
610
+ } else { // x > t.key
611
+ if t.right == nil {
612
+ t = t.copy()
613
+ n := makeNode(x)
614
+ t.right = n
615
+ newnode = n
616
+ newroot = t
617
+ t.height_ = 2 // was balanced w/ 0, sibling is height 0 or 1
618
+ return
619
+ }
620
+ var new_r *node32
621
+ new_r, newnode, oldnode = t.right.aInsert(x)
622
+ t = t.copy()
623
+ t.right = new_r
624
+ if new_r.height() > 1+t.left.height() {
625
+ newroot = t.aRightIsHigh(newnode)
626
+ } else {
627
+ t.height_ = 1 + max(t.left.height(), t.right.height())
628
+ newroot = t
629
+ }
630
+ }
631
+ return
632
+ }
633
+
634
+ func (t *node32) aDelete(key int32) (deleted, newSubTree *node32) {
635
+ if t == nil {
636
+ return nil, nil
637
+ }
638
+
639
+ if key < t.key {
640
+ oh := t.left.height()
641
+ d, tleft := t.left.aDelete(key)
642
+ if tleft == t.left {
643
+ return d, t
644
+ }
645
+ return d, t.copy().aRebalanceAfterLeftDeletion(oh, tleft)
646
+ } else if key > t.key {
647
+ oh := t.right.height()
648
+ d, tright := t.right.aDelete(key)
649
+ if tright == t.right {
650
+ return d, t
651
+ }
652
+ return d, t.copy().aRebalanceAfterRightDeletion(oh, tright)
653
+ }
654
+
655
+ if t.height() == LEAF_HEIGHT {
656
+ return t, nil
657
+ }
658
+
659
+ // Interior delete by removing left.Max or right.Min,
660
+ // then swapping contents
661
+ if t.left.height() > t.right.height() {
662
+ oh := t.left.height()
663
+ d, tleft := t.left.aDeleteMax()
664
+ r := t
665
+ t = t.copy()
666
+ t.data, t.key = d.data, d.key
667
+ return r, t.aRebalanceAfterLeftDeletion(oh, tleft)
668
+ }
669
+
670
+ oh := t.right.height()
671
+ d, tright := t.right.aDeleteMin()
672
+ r := t
673
+ t = t.copy()
674
+ t.data, t.key = d.data, d.key
675
+ return r, t.aRebalanceAfterRightDeletion(oh, tright)
676
+ }
677
+
678
+ func (t *node32) aDeleteMin() (deleted, newSubTree *node32) {
679
+ if t == nil {
680
+ return nil, nil
681
+ }
682
+ if t.left == nil { // leaf or left-most
683
+ return t, t.right
684
+ }
685
+ oh := t.left.height()
686
+ d, tleft := t.left.aDeleteMin()
687
+ if tleft == t.left {
688
+ return d, t
689
+ }
690
+ return d, t.copy().aRebalanceAfterLeftDeletion(oh, tleft)
691
+ }
692
+
693
+ func (t *node32) aDeleteMax() (deleted, newSubTree *node32) {
694
+ if t == nil {
695
+ return nil, nil
696
+ }
697
+
698
+ if t.right == nil { // leaf or right-most
699
+ return t, t.left
700
+ }
701
+
702
+ oh := t.right.height()
703
+ d, tright := t.right.aDeleteMax()
704
+ if tright == t.right {
705
+ return d, t
706
+ }
707
+ return d, t.copy().aRebalanceAfterRightDeletion(oh, tright)
708
+ }
709
+
710
+ func (t *node32) aRebalanceAfterLeftDeletion(oldLeftHeight int8, tleft *node32) *node32 {
711
+ t.left = tleft
712
+
713
+ if oldLeftHeight == tleft.height() || oldLeftHeight == t.right.height() {
714
+ // this node is still balanced and its height is unchanged
715
+ return t
716
+ }
717
+
718
+ if oldLeftHeight > t.right.height() {
719
+ // left was larger
720
+ t.height_--
721
+ return t
722
+ }
723
+
724
+ // left height fell by 1 and it was already less than right height
725
+ t.right = t.right.copy()
726
+ return t.aRightIsHigh(nil)
727
+ }
728
+
729
+ func (t *node32) aRebalanceAfterRightDeletion(oldRightHeight int8, tright *node32) *node32 {
730
+ t.right = tright
731
+
732
+ if oldRightHeight == tright.height() || oldRightHeight == t.left.height() {
733
+ // this node is still balanced and its height is unchanged
734
+ return t
735
+ }
736
+
737
+ if oldRightHeight > t.left.height() {
738
+ // left was larger
739
+ t.height_--
740
+ return t
741
+ }
742
+
743
+ // right height fell by 1 and it was already less than left height
744
+ t.left = t.left.copy()
745
+ return t.aLeftIsHigh(nil)
746
+ }
747
+
748
+ // aRightIsHigh does rotations necessary to fix a high right child
749
+ // assume that t and t.right are already fresh copies.
750
+ func (t *node32) aRightIsHigh(newnode *node32) *node32 {
751
+ right := t.right
752
+ if right.right.height() < right.left.height() {
753
+ // double rotation
754
+ if newnode != right.left {
755
+ right.left = right.left.copy()
756
+ }
757
+ t.right = right.leftToRoot()
758
+ }
759
+ t = t.rightToRoot()
760
+ return t
761
+ }
762
+
763
+ // aLeftIsHigh does rotations necessary to fix a high left child
764
+ // assume that t and t.left are already fresh copies.
765
+ func (t *node32) aLeftIsHigh(newnode *node32) *node32 {
766
+ left := t.left
767
+ if left.left.height() < left.right.height() {
768
+ // double rotation
769
+ if newnode != left.right {
770
+ left.right = left.right.copy()
771
+ }
772
+ t.left = left.rightToRoot()
773
+ }
774
+ t = t.leftToRoot()
775
+ return t
776
+ }
777
+
778
+ // rightToRoot does that rotation, modifying t and t.right in the process.
779
+ func (t *node32) rightToRoot() *node32 {
780
+ // this
781
+ // left right
782
+ // rl rr
783
+ //
784
+ // becomes
785
+ //
786
+ // right
787
+ // this rr
788
+ // left rl
789
+ //
790
+ right := t.right
791
+ rl := right.left
792
+ right.left = t
793
+ // parent's child ptr fixed in caller
794
+ t.right = rl
795
+ t.height_ = 1 + max(rl.height(), t.left.height())
796
+ right.height_ = 1 + max(t.height(), right.right.height())
797
+ return right
798
+ }
799
+
800
+ // leftToRoot does that rotation, modifying t and t.left in the process.
801
+ func (t *node32) leftToRoot() *node32 {
802
+ // this
803
+ // left right
804
+ // ll lr
805
+ //
806
+ // becomes
807
+ //
808
+ // left
809
+ // ll this
810
+ // lr right
811
+ //
812
+ left := t.left
813
+ lr := left.right
814
+ left.right = t
815
+ // parent's child ptr fixed in caller
816
+ t.left = lr
817
+ t.height_ = 1 + max(lr.height(), t.right.height())
818
+ left.height_ = 1 + max(t.height(), left.left.height())
819
+ return left
820
+ }
821
+
822
+ func (t *node32) copy() *node32 {
823
+ u := *t
824
+ return &u
825
+ }
go/src/cmd/compile/internal/abt/avlint32_test.go ADDED
@@ -0,0 +1,700 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2022 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 abt
6
+
7
+ import (
8
+ "fmt"
9
+ "strconv"
10
+ "testing"
11
+ )
12
+
13
+ func makeTree(te *testing.T, x []int32, check bool) (t *T, k int, min, max int32) {
14
+ t = &T{}
15
+ k = 0
16
+ min = int32(0x7fffffff)
17
+ max = int32(-0x80000000)
18
+ history := []*T{}
19
+
20
+ for _, d := range x {
21
+ d = d + d // double everything for Glb/Lub testing.
22
+
23
+ if check {
24
+ history = append(history, t.Copy())
25
+ }
26
+
27
+ t.Insert(d, stringer(fmt.Sprintf("%v", d)))
28
+
29
+ k++
30
+ if d < min {
31
+ min = d
32
+ }
33
+ if d > max {
34
+ max = d
35
+ }
36
+
37
+ if !check {
38
+ continue
39
+ }
40
+
41
+ for j, old := range history {
42
+ s, i := old.wellFormed()
43
+ if s != "" {
44
+ te.Errorf("Old tree consistency problem %v at k=%d, j=%d, old=\n%v, t=\n%v", s, k, j, old.DebugString(), t.DebugString())
45
+ return
46
+ }
47
+ if i != j {
48
+ te.Errorf("Wrong tree size %v, expected %v for old %v", i, j, old.DebugString())
49
+ }
50
+ }
51
+ s, i := t.wellFormed()
52
+ if s != "" {
53
+ te.Errorf("Tree consistency problem at %v", s)
54
+ return
55
+ }
56
+ if i != k {
57
+ te.Errorf("Wrong tree size %v, expected %v for %v", i, k, t.DebugString())
58
+ return
59
+ }
60
+ if t.Size() != k {
61
+ te.Errorf("Wrong t.Size() %v, expected %v for %v", t.Size(), k, t.DebugString())
62
+ return
63
+ }
64
+ }
65
+ return
66
+ }
67
+
68
+ func applicInsert(te *testing.T, x []int32) {
69
+ makeTree(te, x, true)
70
+ }
71
+
72
+ func applicFind(te *testing.T, x []int32) {
73
+ t, _, _, _ := makeTree(te, x, false)
74
+
75
+ for _, d := range x {
76
+ d = d + d // double everything for Glb/Lub testing.
77
+ s := fmt.Sprintf("%v", d)
78
+ f := t.Find(d)
79
+
80
+ // data
81
+ if s != fmt.Sprint(f) {
82
+ te.Errorf("s(%v) != f(%v)", s, f)
83
+ }
84
+ }
85
+ }
86
+
87
+ func applicBounds(te *testing.T, x []int32) {
88
+ t, _, min, max := makeTree(te, x, false)
89
+ for _, d := range x {
90
+ d = d + d // double everything for Glb/Lub testing.
91
+ s := fmt.Sprintf("%v", d)
92
+
93
+ kg, g := t.Glb(d + 1)
94
+ kge, ge := t.GlbEq(d)
95
+ kl, l := t.Lub(d - 1)
96
+ kle, le := t.LubEq(d)
97
+
98
+ // keys
99
+ if d != kg {
100
+ te.Errorf("d(%v) != kg(%v)", d, kg)
101
+ }
102
+ if d != kl {
103
+ te.Errorf("d(%v) != kl(%v)", d, kl)
104
+ }
105
+ if d != kge {
106
+ te.Errorf("d(%v) != kge(%v)", d, kge)
107
+ }
108
+ if d != kle {
109
+ te.Errorf("d(%v) != kle(%v)", d, kle)
110
+ }
111
+ // data
112
+ if s != fmt.Sprint(g) {
113
+ te.Errorf("s(%v) != g(%v)", s, g)
114
+ }
115
+ if s != fmt.Sprint(l) {
116
+ te.Errorf("s(%v) != l(%v)", s, l)
117
+ }
118
+ if s != fmt.Sprint(ge) {
119
+ te.Errorf("s(%v) != ge(%v)", s, ge)
120
+ }
121
+ if s != fmt.Sprint(le) {
122
+ te.Errorf("s(%v) != le(%v)", s, le)
123
+ }
124
+ }
125
+
126
+ for _, d := range x {
127
+ d = d + d // double everything for Glb/Lub testing.
128
+ s := fmt.Sprintf("%v", d)
129
+ kge, ge := t.GlbEq(d + 1)
130
+ kle, le := t.LubEq(d - 1)
131
+ if d != kge {
132
+ te.Errorf("d(%v) != kge(%v)", d, kge)
133
+ }
134
+ if d != kle {
135
+ te.Errorf("d(%v) != kle(%v)", d, kle)
136
+ }
137
+ if s != fmt.Sprint(ge) {
138
+ te.Errorf("s(%v) != ge(%v)", s, ge)
139
+ }
140
+ if s != fmt.Sprint(le) {
141
+ te.Errorf("s(%v) != le(%v)", s, le)
142
+ }
143
+ }
144
+
145
+ kg, g := t.Glb(min)
146
+ kge, ge := t.GlbEq(min - 1)
147
+ kl, l := t.Lub(max)
148
+ kle, le := t.LubEq(max + 1)
149
+ fmin := t.Find(min - 1)
150
+ fmax := t.Find(max + 1)
151
+
152
+ if kg != NOT_KEY32 || kge != NOT_KEY32 || kl != NOT_KEY32 || kle != NOT_KEY32 {
153
+ te.Errorf("Got non-error-key for missing query")
154
+ }
155
+
156
+ if g != nil || ge != nil || l != nil || le != nil || fmin != nil || fmax != nil {
157
+ te.Errorf("Got non-error-data for missing query")
158
+ }
159
+ }
160
+
161
+ func applicDeleteMin(te *testing.T, x []int32) {
162
+ t, _, _, _ := makeTree(te, x, false)
163
+ _, size := t.wellFormed()
164
+ history := []*T{}
165
+ for !t.IsEmpty() {
166
+ k, _ := t.Min()
167
+ history = append(history, t.Copy())
168
+ kd, _ := t.DeleteMin()
169
+ if kd != k {
170
+ te.Errorf("Deleted minimum key %v not equal to minimum %v", kd, k)
171
+ }
172
+ for j, old := range history {
173
+ s, i := old.wellFormed()
174
+ if s != "" {
175
+ te.Errorf("Tree consistency problem %s at old after DeleteMin, old=\n%stree=\n%v", s, old.DebugString(), t.DebugString())
176
+ return
177
+ }
178
+ if i != len(x)-j {
179
+ te.Errorf("Wrong old tree size %v, expected %v after DeleteMin, old=\n%vtree\n%v", i, len(x)-j, old.DebugString(), t.DebugString())
180
+ return
181
+ }
182
+ }
183
+ size--
184
+ s, i := t.wellFormed()
185
+ if s != "" {
186
+ te.Errorf("Tree consistency problem at %v after DeleteMin, tree=\n%v", s, t.DebugString())
187
+ return
188
+ }
189
+ if i != size {
190
+ te.Errorf("Wrong tree size %v, expected %v after DeleteMin", i, size)
191
+ return
192
+ }
193
+ if t.Size() != size {
194
+ te.Errorf("Wrong t.Size() %v, expected %v for %v", t.Size(), i, t.DebugString())
195
+ return
196
+ }
197
+ }
198
+ }
199
+
200
+ func applicDeleteMax(te *testing.T, x []int32) {
201
+ t, _, _, _ := makeTree(te, x, false)
202
+ _, size := t.wellFormed()
203
+ history := []*T{}
204
+
205
+ for !t.IsEmpty() {
206
+ k, _ := t.Max()
207
+ history = append(history, t.Copy())
208
+ kd, _ := t.DeleteMax()
209
+ if kd != k {
210
+ te.Errorf("Deleted maximum key %v not equal to maximum %v", kd, k)
211
+ }
212
+
213
+ for j, old := range history {
214
+ s, i := old.wellFormed()
215
+ if s != "" {
216
+ te.Errorf("Tree consistency problem %s at old after DeleteMin, old=\n%stree=\n%v", s, old.DebugString(), t.DebugString())
217
+ return
218
+ }
219
+ if i != len(x)-j {
220
+ te.Errorf("Wrong old tree size %v, expected %v after DeleteMin, old=\n%vtree\n%v", i, len(x)-j, old.DebugString(), t.DebugString())
221
+ return
222
+ }
223
+ }
224
+
225
+ size--
226
+ s, i := t.wellFormed()
227
+ if s != "" {
228
+ te.Errorf("Tree consistency problem at %v after DeleteMax, tree=\n%v", s, t.DebugString())
229
+ return
230
+ }
231
+ if i != size {
232
+ te.Errorf("Wrong tree size %v, expected %v after DeleteMax", i, size)
233
+ return
234
+ }
235
+ if t.Size() != size {
236
+ te.Errorf("Wrong t.Size() %v, expected %v for %v", t.Size(), i, t.DebugString())
237
+ return
238
+ }
239
+ }
240
+ }
241
+
242
+ func applicDelete(te *testing.T, x []int32) {
243
+ t, _, _, _ := makeTree(te, x, false)
244
+ _, size := t.wellFormed()
245
+ history := []*T{}
246
+
247
+ missing := t.Delete(11)
248
+ if missing != nil {
249
+ te.Errorf("Returned a value when there should have been none, %v", missing)
250
+ return
251
+ }
252
+
253
+ s, i := t.wellFormed()
254
+ if s != "" {
255
+ te.Errorf("Tree consistency problem at %v after delete of missing value, tree=\n%v", s, t.DebugString())
256
+ return
257
+ }
258
+ if size != i {
259
+ te.Errorf("Delete of missing data should not change tree size, expected %d, got %d", size, i)
260
+ return
261
+ }
262
+
263
+ for _, d := range x {
264
+ d += d // double
265
+ vWant := fmt.Sprintf("%v", d)
266
+ history = append(history, t.Copy())
267
+ v := t.Delete(d)
268
+
269
+ for j, old := range history {
270
+ s, i := old.wellFormed()
271
+ if s != "" {
272
+ te.Errorf("Tree consistency problem %s at old after DeleteMin, old=\n%stree=\n%v", s, old.DebugString(), t.DebugString())
273
+ return
274
+ }
275
+ if i != len(x)-j {
276
+ te.Errorf("Wrong old tree size %v, expected %v after DeleteMin, old=\n%vtree\n%v", i, len(x)-j, old.DebugString(), t.DebugString())
277
+ return
278
+ }
279
+ }
280
+
281
+ if v.(*sstring).s != vWant {
282
+ te.Errorf("Deleted %v expected %v but got %v", d, vWant, v)
283
+ return
284
+ }
285
+ size--
286
+ s, i := t.wellFormed()
287
+ if s != "" {
288
+ te.Errorf("Tree consistency problem at %v after Delete %d, tree=\n%v", s, d, t.DebugString())
289
+ return
290
+ }
291
+ if i != size {
292
+ te.Errorf("Wrong tree size %v, expected %v after Delete", i, size)
293
+ return
294
+ }
295
+ if t.Size() != size {
296
+ te.Errorf("Wrong t.Size() %v, expected %v for %v", t.Size(), i, t.DebugString())
297
+ return
298
+ }
299
+ }
300
+
301
+ }
302
+
303
+ func applicIterator(te *testing.T, x []int32) {
304
+ t, _, _, _ := makeTree(te, x, false)
305
+ it := t.Iterator()
306
+ for !it.Done() {
307
+ k0, d0 := it.Next()
308
+ k1, d1 := t.DeleteMin()
309
+ if k0 != k1 || d0 != d1 {
310
+ te.Errorf("Iterator and deleteMin mismatch, k0, k1, d0, d1 = %v, %v, %v, %v", k0, k1, d0, d1)
311
+ return
312
+ }
313
+ }
314
+ if t.Size() != 0 {
315
+ te.Errorf("Iterator ended early, remaining tree = \n%s", t.DebugString())
316
+ return
317
+ }
318
+ }
319
+
320
+ func equiv(a, b any) bool {
321
+ sa, sb := a.(*sstring), b.(*sstring)
322
+ return *sa == *sb
323
+ }
324
+
325
+ func applicEquals(te *testing.T, x, y []int32) {
326
+ t, _, _, _ := makeTree(te, x, false)
327
+ u, _, _, _ := makeTree(te, y, false)
328
+ if !t.Equiv(t, equiv) {
329
+ te.Errorf("Equiv failure, t == t, =\n%v", t.DebugString())
330
+ return
331
+ }
332
+ if !t.Equiv(t.Copy(), equiv) {
333
+ te.Errorf("Equiv failure, t == t.Copy(), =\n%v", t.DebugString())
334
+ return
335
+ }
336
+ if !t.Equiv(u, equiv) {
337
+ te.Errorf("Equiv failure, t == u, =\n%v", t.DebugString())
338
+ return
339
+ }
340
+ v := t.Copy()
341
+
342
+ v.DeleteMax()
343
+ if t.Equiv(v, equiv) {
344
+ te.Errorf("!Equiv failure, t != v, =\n%v\nand%v\n", t.DebugString(), v.DebugString())
345
+ return
346
+ }
347
+
348
+ if v.Equiv(u, equiv) {
349
+ te.Errorf("!Equiv failure, v != u, =\n%v\nand%v\n", v.DebugString(), u.DebugString())
350
+ return
351
+ }
352
+
353
+ }
354
+
355
+ func tree(x []int32) *T {
356
+ t := &T{}
357
+ for _, d := range x {
358
+ t.Insert(d, stringer(fmt.Sprintf("%v", d)))
359
+ }
360
+ return t
361
+ }
362
+
363
+ func treePlus1(x []int32) *T {
364
+ t := &T{}
365
+ for _, d := range x {
366
+ t.Insert(d, stringer(fmt.Sprintf("%v", d+1)))
367
+ }
368
+ return t
369
+ }
370
+ func TestApplicInsert(t *testing.T) {
371
+ applicInsert(t, []int32{24, 22, 20, 18, 16, 14, 12, 10, 8, 6, 4, 2, 1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25})
372
+ applicInsert(t, []int32{1, 2, 3, 4})
373
+ applicInsert(t, []int32{1, 2, 3, 4, 5, 6, 7, 8, 9})
374
+ applicInsert(t, []int32{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})
375
+ applicInsert(t, []int32{25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1})
376
+ applicInsert(t, []int32{25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1})
377
+ applicInsert(t, []int32{1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24})
378
+ applicInsert(t, []int32{1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 24, 22, 20, 18, 16, 14, 12, 10, 8, 6, 4, 2})
379
+ }
380
+
381
+ func TestApplicFind(t *testing.T) {
382
+ applicFind(t, []int32{24, 22, 20, 18, 16, 14, 12, 10, 8, 6, 4, 2, 1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25})
383
+ applicFind(t, []int32{1, 2, 3, 4})
384
+ applicFind(t, []int32{1, 2, 3, 4, 5, 6, 7, 8, 9})
385
+ applicFind(t, []int32{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})
386
+ applicFind(t, []int32{25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1})
387
+ applicFind(t, []int32{25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1})
388
+ applicFind(t, []int32{1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24})
389
+ applicFind(t, []int32{1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 24, 22, 20, 18, 16, 14, 12, 10, 8, 6, 4, 2})
390
+ }
391
+
392
+ func TestBounds(t *testing.T) {
393
+ applicBounds(t, []int32{24, 22, 20, 18, 16, 14, 12, 10, 8, 6, 4, 2, 1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25})
394
+ applicBounds(t, []int32{1, 2, 3, 4})
395
+ applicBounds(t, []int32{1, 2, 3, 4, 5, 6, 7, 8, 9})
396
+ applicBounds(t, []int32{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})
397
+ applicBounds(t, []int32{25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1})
398
+ applicBounds(t, []int32{25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1})
399
+ applicBounds(t, []int32{1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24})
400
+ applicBounds(t, []int32{1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 24, 22, 20, 18, 16, 14, 12, 10, 8, 6, 4, 2})
401
+ }
402
+ func TestDeleteMin(t *testing.T) {
403
+ applicDeleteMin(t, []int32{1, 2, 3, 4})
404
+ applicDeleteMin(t, []int32{24, 22, 20, 18, 16, 14, 12, 10, 8, 6, 4, 2, 1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25})
405
+ applicDeleteMin(t, []int32{1, 2, 3, 4, 5, 6, 7, 8, 9})
406
+ applicDeleteMin(t, []int32{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})
407
+ applicDeleteMin(t, []int32{25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1})
408
+ applicDeleteMin(t, []int32{25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1})
409
+ applicDeleteMin(t, []int32{1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24})
410
+ applicDeleteMin(t, []int32{1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 24, 22, 20, 18, 16, 14, 12, 10, 8, 6, 4, 2})
411
+ }
412
+ func TestDeleteMax(t *testing.T) {
413
+ applicDeleteMax(t, []int32{24, 22, 20, 18, 16, 14, 12, 10, 8, 6, 4, 2, 1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25})
414
+ applicDeleteMax(t, []int32{1, 2, 3, 4})
415
+ applicDeleteMax(t, []int32{1, 2, 3, 4, 5, 6, 7, 8, 9})
416
+ applicDeleteMax(t, []int32{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})
417
+ applicDeleteMax(t, []int32{25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1})
418
+ applicDeleteMax(t, []int32{25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1})
419
+ applicDeleteMax(t, []int32{1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24})
420
+ applicDeleteMax(t, []int32{1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 24, 22, 20, 18, 16, 14, 12, 10, 8, 6, 4, 2})
421
+ }
422
+ func TestDelete(t *testing.T) {
423
+ applicDelete(t, []int32{24, 22, 20, 18, 16, 14, 12, 10, 8, 6, 4, 2, 1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25})
424
+ applicDelete(t, []int32{1, 2, 3, 4})
425
+ applicDelete(t, []int32{1, 2, 3, 4, 5, 6, 7, 8, 9})
426
+ applicDelete(t, []int32{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})
427
+ applicDelete(t, []int32{25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1})
428
+ applicDelete(t, []int32{25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1})
429
+ applicDelete(t, []int32{1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24})
430
+ applicDelete(t, []int32{1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 24, 22, 20, 18, 16, 14, 12, 10, 8, 6, 4, 2})
431
+ }
432
+ func TestIterator(t *testing.T) {
433
+ applicIterator(t, []int32{1, 2, 3, 4})
434
+ applicIterator(t, []int32{1, 2, 3, 4, 5, 6, 7, 8, 9})
435
+ applicIterator(t, []int32{24, 22, 20, 18, 16, 14, 12, 10, 8, 6, 4, 2, 1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25})
436
+ applicIterator(t, []int32{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})
437
+ applicIterator(t, []int32{25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1})
438
+ applicIterator(t, []int32{25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1})
439
+ applicIterator(t, []int32{1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24})
440
+ applicIterator(t, []int32{1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 24, 22, 20, 18, 16, 14, 12, 10, 8, 6, 4, 2})
441
+ }
442
+ func TestEquals(t *testing.T) {
443
+ applicEquals(t, []int32{1, 2, 3, 4}, []int32{4, 3, 2, 1})
444
+
445
+ applicEquals(t, []int32{24, 22, 20, 18, 16, 14, 12, 10, 8, 6, 4, 2, 1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25},
446
+ []int32{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})
447
+ applicEquals(t, []int32{25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1},
448
+ []int32{25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1})
449
+ applicEquals(t, []int32{1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24},
450
+ []int32{1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 24, 22, 20, 18, 16, 14, 12, 10, 8, 6, 4, 2})
451
+ }
452
+
453
+ func first(x, y any) any {
454
+ return x
455
+ }
456
+ func second(x, y any) any {
457
+ return y
458
+ }
459
+ func alwaysNil(x, y any) any {
460
+ return nil
461
+ }
462
+ func smaller(x, y any) any {
463
+ xi, _ := strconv.Atoi(fmt.Sprint(x))
464
+ yi, _ := strconv.Atoi(fmt.Sprint(y))
465
+ if xi < yi {
466
+ return x
467
+ }
468
+ return y
469
+ }
470
+ func assert(t *testing.T, expected, got *T, what string) {
471
+ s, _ := got.wellFormed()
472
+ if s != "" {
473
+ t.Errorf("Tree consistency problem %v for 'got' in assert for %s, tree=\n%v", s, what, got.DebugString())
474
+ return
475
+ }
476
+
477
+ if !expected.Equiv(got, equiv) {
478
+ t.Errorf("%s fail, expected\n%vgot\n%v\n", what, expected.DebugString(), got.DebugString())
479
+ }
480
+ }
481
+
482
+ func TestSetOps(t *testing.T) {
483
+ A := tree([]int32{1, 2, 3, 4})
484
+ B := tree([]int32{3, 4, 5, 6, 7})
485
+
486
+ AIB := tree([]int32{3, 4})
487
+ ADB := tree([]int32{1, 2})
488
+ BDA := tree([]int32{5, 6, 7})
489
+ AUB := tree([]int32{1, 2, 3, 4, 5, 6, 7})
490
+ AXB := tree([]int32{1, 2, 5, 6, 7})
491
+
492
+ aib1 := A.Intersection(B, first)
493
+ assert(t, AIB, aib1, "aib1")
494
+ if A.Find(3) != aib1.Find(3) {
495
+ t.Errorf("Failed aliasing/reuse check, A/aib1")
496
+ }
497
+ aib2 := A.Intersection(B, second)
498
+ assert(t, AIB, aib2, "aib2")
499
+ if B.Find(3) != aib2.Find(3) {
500
+ t.Errorf("Failed aliasing/reuse check, B/aib2")
501
+ }
502
+ aib3 := B.Intersection(A, first)
503
+ assert(t, AIB, aib3, "aib3")
504
+ if A.Find(3) != aib3.Find(3) {
505
+ // A is smaller, intersection favors reuse from smaller when function is "first"
506
+ t.Errorf("Failed aliasing/reuse check, A/aib3")
507
+ }
508
+ aib4 := B.Intersection(A, second)
509
+ assert(t, AIB, aib4, "aib4")
510
+ if A.Find(3) != aib4.Find(3) {
511
+ t.Errorf("Failed aliasing/reuse check, A/aib4")
512
+ }
513
+
514
+ aub1 := A.Union(B, first)
515
+ assert(t, AUB, aub1, "aub1")
516
+ if B.Find(3) != aub1.Find(3) {
517
+ // B is larger, union favors reuse from larger when function is "first"
518
+ t.Errorf("Failed aliasing/reuse check, A/aub1")
519
+ }
520
+ aub2 := A.Union(B, second)
521
+ assert(t, AUB, aub2, "aub2")
522
+ if B.Find(3) != aub2.Find(3) {
523
+ t.Errorf("Failed aliasing/reuse check, B/aub2")
524
+ }
525
+ aub3 := B.Union(A, first)
526
+ assert(t, AUB, aub3, "aub3")
527
+ if B.Find(3) != aub3.Find(3) {
528
+ t.Errorf("Failed aliasing/reuse check, B/aub3")
529
+ }
530
+ aub4 := B.Union(A, second)
531
+ assert(t, AUB, aub4, "aub4")
532
+ if A.Find(3) != aub4.Find(3) {
533
+ t.Errorf("Failed aliasing/reuse check, A/aub4")
534
+ }
535
+
536
+ axb1 := A.Union(B, alwaysNil)
537
+ assert(t, AXB, axb1, "axb1")
538
+ axb2 := B.Union(A, alwaysNil)
539
+ assert(t, AXB, axb2, "axb2")
540
+
541
+ adb := A.Difference(B, alwaysNil)
542
+ assert(t, ADB, adb, "adb")
543
+ bda := B.Difference(A, nil)
544
+ assert(t, BDA, bda, "bda")
545
+
546
+ Ap1 := treePlus1([]int32{1, 2, 3, 4})
547
+
548
+ ada1_1 := A.Difference(Ap1, smaller)
549
+ assert(t, A, ada1_1, "ada1_1")
550
+ ada1_2 := Ap1.Difference(A, smaller)
551
+ assert(t, A, ada1_2, "ada1_2")
552
+
553
+ }
554
+
555
+ type sstring struct {
556
+ s string
557
+ }
558
+
559
+ func (s *sstring) String() string {
560
+ return s.s
561
+ }
562
+
563
+ func stringer(s string) any {
564
+ return &sstring{s}
565
+ }
566
+
567
+ // wellFormed ensures that a red-black tree meets
568
+ // all of its invariants and returns a string identifying
569
+ // the first problem encountered. If there is no problem
570
+ // then the returned string is empty. The size is also
571
+ // returned to allow comparison of calculated tree size
572
+ // with expected.
573
+ func (t *T) wellFormed() (s string, i int) {
574
+ if t.root == nil {
575
+ s = ""
576
+ i = 0
577
+ return
578
+ }
579
+ return t.root.wellFormedSubtree(nil, -0x80000000, 0x7fffffff)
580
+ }
581
+
582
+ // wellFormedSubtree ensures that a red-black subtree meets
583
+ // all of its invariants and returns a string identifying
584
+ // the first problem encountered. If there is no problem
585
+ // then the returned string is empty. The size is also
586
+ // returned to allow comparison of calculated tree size
587
+ // with expected.
588
+ func (t *node32) wellFormedSubtree(parent *node32, keyMin, keyMax int32) (s string, i int) {
589
+ i = -1 // initialize to a failing value
590
+ s = "" // s is the reason for failure; empty means okay.
591
+
592
+ if keyMin >= t.key {
593
+ s = " min >= t.key"
594
+ return
595
+ }
596
+
597
+ if keyMax <= t.key {
598
+ s = " max <= t.key"
599
+ return
600
+ }
601
+
602
+ l := t.left
603
+ r := t.right
604
+
605
+ lh := l.height()
606
+ rh := r.height()
607
+ mh := max(lh, rh)
608
+ th := t.height()
609
+ dh := lh - rh
610
+ if dh < 0 {
611
+ dh = -dh
612
+ }
613
+ if dh > 1 {
614
+ s = fmt.Sprintf(" dh > 1, t=%d", t.key)
615
+ return
616
+ }
617
+
618
+ if l == nil && r == nil {
619
+ if th != LEAF_HEIGHT {
620
+ s = " leaf height wrong"
621
+ return
622
+ }
623
+ }
624
+
625
+ if th != mh+1 {
626
+ s = " th != mh + 1"
627
+ return
628
+ }
629
+
630
+ if l != nil {
631
+ if th <= lh {
632
+ s = " t.height <= l.height"
633
+ } else if th > 2+lh {
634
+ s = " t.height > 2+l.height"
635
+ } else if t.key <= l.key {
636
+ s = " t.key <= l.key"
637
+ }
638
+ if s != "" {
639
+ return
640
+ }
641
+
642
+ }
643
+
644
+ if r != nil {
645
+ if th <= rh {
646
+ s = " t.height <= r.height"
647
+ } else if th > 2+rh {
648
+ s = " t.height > 2+r.height"
649
+ } else if t.key >= r.key {
650
+ s = " t.key >= r.key"
651
+ }
652
+ if s != "" {
653
+ return
654
+ }
655
+ }
656
+
657
+ ii := 1
658
+ if l != nil {
659
+ res, il := l.wellFormedSubtree(t, keyMin, t.key)
660
+ if res != "" {
661
+ s = ".L" + res
662
+ return
663
+ }
664
+ ii += il
665
+ }
666
+ if r != nil {
667
+ res, ir := r.wellFormedSubtree(t, t.key, keyMax)
668
+ if res != "" {
669
+ s = ".R" + res
670
+ return
671
+ }
672
+ ii += ir
673
+ }
674
+ i = ii
675
+ return
676
+ }
677
+
678
+ func (t *T) DebugString() string {
679
+ if t.root == nil {
680
+ return ""
681
+ }
682
+ return t.root.DebugString(0)
683
+ }
684
+
685
+ // DebugString prints the tree with nested information
686
+ // to allow an eyeball check on the tree balance.
687
+ func (t *node32) DebugString(indent int) string {
688
+ s := ""
689
+ if t.left != nil {
690
+ s = s + t.left.DebugString(indent+1)
691
+ }
692
+ for i := 0; i < indent; i++ {
693
+ s = s + " "
694
+ }
695
+ s = s + fmt.Sprintf("%v=%v:%d\n", t.key, t.data, t.height_)
696
+ if t.right != nil {
697
+ s = s + t.right.DebugString(indent+1)
698
+ }
699
+ return s
700
+ }
go/src/cmd/compile/internal/amd64/galign.go ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2009 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 amd64
6
+
7
+ import (
8
+ "cmd/compile/internal/ssagen"
9
+ "cmd/internal/obj/x86"
10
+ )
11
+
12
+ var leaptr = x86.ALEAQ
13
+
14
+ func Init(arch *ssagen.ArchInfo) {
15
+ arch.LinkArch = &x86.Linkamd64
16
+ arch.REGSP = x86.REGSP
17
+ arch.MAXWIDTH = 1 << 50
18
+
19
+ arch.ZeroRange = zerorange
20
+ arch.Ginsnop = ginsnop
21
+
22
+ arch.SSAMarkMoves = ssaMarkMoves
23
+ arch.SSAGenValue = ssaGenValue
24
+ arch.SSAGenBlock = ssaGenBlock
25
+ arch.LoadRegResult = loadRegResult
26
+ arch.SpillArgReg = spillArgReg
27
+ }
go/src/cmd/compile/internal/amd64/ggen.go ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2009 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 amd64
6
+
7
+ import (
8
+ "cmd/compile/internal/objw"
9
+ "cmd/internal/obj"
10
+ "cmd/internal/obj/x86"
11
+ )
12
+
13
+ func zerorange(pp *objw.Progs, p *obj.Prog, off, cnt int64, state *uint32) *obj.Prog {
14
+ if cnt%8 != 0 {
15
+ panic("zeroed region not aligned")
16
+ }
17
+ for cnt >= 16 {
18
+ p = pp.Append(p, x86.AMOVUPS, obj.TYPE_REG, x86.REG_X15, 0, obj.TYPE_MEM, x86.REG_SP, off)
19
+ off += 16
20
+ cnt -= 16
21
+ }
22
+ if cnt != 0 {
23
+ p = pp.Append(p, x86.AMOVQ, obj.TYPE_REG, x86.REG_X15, 0, obj.TYPE_MEM, x86.REG_SP, off)
24
+ }
25
+ return p
26
+ }
27
+
28
+ func ginsnop(pp *objw.Progs) *obj.Prog {
29
+ // This is a hardware nop (1-byte 0x90) instruction,
30
+ // even though we describe it as an explicit XCHGL here.
31
+ // Particularly, this does not zero the high 32 bits
32
+ // like typical *L opcodes.
33
+ // (gas assembles "xchg %eax,%eax" to 0x87 0xc0, which
34
+ // does zero the high 32 bits.)
35
+ p := pp.Prog(x86.AXCHGL)
36
+ p.From.Type = obj.TYPE_REG
37
+ p.From.Reg = x86.REG_AX
38
+ p.To.Type = obj.TYPE_REG
39
+ p.To.Reg = x86.REG_AX
40
+ return p
41
+ }
go/src/cmd/compile/internal/amd64/simdssa.go ADDED
The diff for this file is too large to render. See raw diff
 
go/src/cmd/compile/internal/amd64/ssa.go ADDED
@@ -0,0 +1,2568 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2016 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 amd64
6
+
7
+ import (
8
+ "fmt"
9
+ "math"
10
+
11
+ "cmd/compile/internal/base"
12
+ "cmd/compile/internal/ir"
13
+ "cmd/compile/internal/logopt"
14
+ "cmd/compile/internal/objw"
15
+ "cmd/compile/internal/ssa"
16
+ "cmd/compile/internal/ssagen"
17
+ "cmd/compile/internal/types"
18
+ "cmd/internal/obj"
19
+ "cmd/internal/obj/x86"
20
+ "internal/abi"
21
+ )
22
+
23
+ // ssaMarkMoves marks any MOVXconst ops that need to avoid clobbering flags.
24
+ func ssaMarkMoves(s *ssagen.State, b *ssa.Block) {
25
+ flive := b.FlagsLiveAtEnd
26
+ for _, c := range b.ControlValues() {
27
+ flive = c.Type.IsFlags() || flive
28
+ }
29
+ for i := len(b.Values) - 1; i >= 0; i-- {
30
+ v := b.Values[i]
31
+ if flive && (v.Op == ssa.OpAMD64MOVLconst || v.Op == ssa.OpAMD64MOVQconst) {
32
+ // The "mark" is any non-nil Aux value.
33
+ v.Aux = ssa.AuxMark
34
+ }
35
+ if v.Type.IsFlags() {
36
+ flive = false
37
+ }
38
+ for _, a := range v.Args {
39
+ if a.Type.IsFlags() {
40
+ flive = true
41
+ }
42
+ }
43
+ }
44
+ }
45
+
46
+ func isFPReg(r int16) bool {
47
+ return x86.REG_X0 <= r && r <= x86.REG_Z31
48
+ }
49
+
50
+ func isKReg(r int16) bool {
51
+ return x86.REG_K0 <= r && r <= x86.REG_K7
52
+ }
53
+
54
+ func isLowFPReg(r int16) bool {
55
+ return x86.REG_X0 <= r && r <= x86.REG_X15
56
+ }
57
+
58
+ // loadByRegWidth returns the load instruction of the given register of a given width.
59
+ func loadByRegWidth(r int16, width int64) obj.As {
60
+ // Avoid partial register write for GPR
61
+ if !isFPReg(r) && !isKReg(r) {
62
+ switch width {
63
+ case 1:
64
+ return x86.AMOVBLZX
65
+ case 2:
66
+ return x86.AMOVWLZX
67
+ }
68
+ }
69
+ // Otherwise, there's no difference between load and store opcodes.
70
+ return storeByRegWidth(r, width)
71
+ }
72
+
73
+ // storeByRegWidth returns the store instruction of the given register of a given width.
74
+ // It's also used for loading const to a reg.
75
+ func storeByRegWidth(r int16, width int64) obj.As {
76
+ if isFPReg(r) {
77
+ switch width {
78
+ case 4:
79
+ return x86.AMOVSS
80
+ case 8:
81
+ return x86.AMOVSD
82
+ case 16:
83
+ // int128s are in SSE registers
84
+ if isLowFPReg(r) {
85
+ return x86.AMOVUPS
86
+ } else {
87
+ return x86.AVMOVDQU
88
+ }
89
+ case 32:
90
+ return x86.AVMOVDQU
91
+ case 64:
92
+ return x86.AVMOVDQU64
93
+ }
94
+ }
95
+ if isKReg(r) {
96
+ return x86.AKMOVQ
97
+ }
98
+ // gp
99
+ switch width {
100
+ case 1:
101
+ return x86.AMOVB
102
+ case 2:
103
+ return x86.AMOVW
104
+ case 4:
105
+ return x86.AMOVL
106
+ case 8:
107
+ return x86.AMOVQ
108
+ }
109
+ panic(fmt.Sprintf("bad store reg=%v, width=%d", r, width))
110
+ }
111
+
112
+ // moveByRegsWidth returns the reg->reg move instruction of the given dest/src registers of a given width.
113
+ func moveByRegsWidth(dest, src int16, width int64) obj.As {
114
+ // fp -> fp
115
+ if isFPReg(dest) && isFPReg(src) {
116
+ // Moving the whole sse2 register is faster
117
+ // than moving just the correct low portion of it.
118
+ // There is no xmm->xmm move with 1 byte opcode,
119
+ // so use movups, which has 2 byte opcode.
120
+ if isLowFPReg(dest) && isLowFPReg(src) && width <= 16 {
121
+ return x86.AMOVUPS
122
+ }
123
+ if width <= 32 {
124
+ return x86.AVMOVDQU
125
+ }
126
+ return x86.AVMOVDQU64
127
+ }
128
+ // k -> gp, gp -> k, k -> k
129
+ if isKReg(dest) || isKReg(src) {
130
+ if isFPReg(dest) || isFPReg(src) {
131
+ panic(fmt.Sprintf("bad move, src=%v, dest=%v, width=%d", src, dest, width))
132
+ }
133
+ return x86.AKMOVQ
134
+ }
135
+ // gp -> fp, fp -> gp, gp -> gp
136
+ switch width {
137
+ case 1:
138
+ // Avoids partial register write
139
+ return x86.AMOVL
140
+ case 2:
141
+ return x86.AMOVL
142
+ case 4:
143
+ return x86.AMOVL
144
+ case 8:
145
+ return x86.AMOVQ
146
+ case 16:
147
+ if isLowFPReg(dest) && isLowFPReg(src) {
148
+ // int128s are in SSE registers
149
+ return x86.AMOVUPS
150
+ } else {
151
+ return x86.AVMOVDQU
152
+ }
153
+ case 32:
154
+ return x86.AVMOVDQU
155
+ case 64:
156
+ return x86.AVMOVDQU64
157
+ }
158
+ panic(fmt.Sprintf("bad move, src=%v, dest=%v, width=%d", src, dest, width))
159
+ }
160
+
161
+ // opregreg emits instructions for
162
+ //
163
+ // dest := dest(To) op src(From)
164
+ //
165
+ // and also returns the created obj.Prog so it
166
+ // may be further adjusted (offset, scale, etc).
167
+ func opregreg(s *ssagen.State, op obj.As, dest, src int16) *obj.Prog {
168
+ p := s.Prog(op)
169
+ p.From.Type = obj.TYPE_REG
170
+ p.To.Type = obj.TYPE_REG
171
+ p.To.Reg = dest
172
+ p.From.Reg = src
173
+ return p
174
+ }
175
+
176
+ // memIdx fills out a as an indexed memory reference for v.
177
+ // It assumes that the base register and the index register
178
+ // are v.Args[0].Reg() and v.Args[1].Reg(), respectively.
179
+ // The caller must still use gc.AddAux/gc.AddAux2 to handle v.Aux as necessary.
180
+ func memIdx(a *obj.Addr, v *ssa.Value) {
181
+ r, i := v.Args[0].Reg(), v.Args[1].Reg()
182
+ a.Type = obj.TYPE_MEM
183
+ a.Scale = v.Op.Scale()
184
+ if a.Scale == 1 && i == x86.REG_SP {
185
+ r, i = i, r
186
+ }
187
+ a.Reg = r
188
+ a.Index = i
189
+ }
190
+
191
+ func getgFromTLS(s *ssagen.State, r int16) {
192
+ // See the comments in cmd/internal/obj/x86/obj6.go
193
+ // near CanUse1InsnTLS for a detailed explanation of these instructions.
194
+ if x86.CanUse1InsnTLS(base.Ctxt) {
195
+ // MOVQ (TLS), r
196
+ p := s.Prog(x86.AMOVQ)
197
+ p.From.Type = obj.TYPE_MEM
198
+ p.From.Reg = x86.REG_TLS
199
+ p.To.Type = obj.TYPE_REG
200
+ p.To.Reg = r
201
+ } else {
202
+ // MOVQ TLS, r
203
+ // MOVQ (r)(TLS*1), r
204
+ p := s.Prog(x86.AMOVQ)
205
+ p.From.Type = obj.TYPE_REG
206
+ p.From.Reg = x86.REG_TLS
207
+ p.To.Type = obj.TYPE_REG
208
+ p.To.Reg = r
209
+ q := s.Prog(x86.AMOVQ)
210
+ q.From.Type = obj.TYPE_MEM
211
+ q.From.Reg = r
212
+ q.From.Index = x86.REG_TLS
213
+ q.From.Scale = 1
214
+ q.To.Type = obj.TYPE_REG
215
+ q.To.Reg = r
216
+ }
217
+ }
218
+
219
+ func ssaGenValue(s *ssagen.State, v *ssa.Value) {
220
+ switch v.Op {
221
+ case ssa.OpAMD64VFMADD231SD, ssa.OpAMD64VFMADD231SS:
222
+ p := s.Prog(v.Op.Asm())
223
+ p.From = obj.Addr{Type: obj.TYPE_REG, Reg: v.Args[2].Reg()}
224
+ p.To = obj.Addr{Type: obj.TYPE_REG, Reg: v.Reg()}
225
+ p.AddRestSourceReg(v.Args[1].Reg())
226
+ case ssa.OpAMD64ADDQ, ssa.OpAMD64ADDL:
227
+ r := v.Reg()
228
+ r1 := v.Args[0].Reg()
229
+ r2 := v.Args[1].Reg()
230
+ switch {
231
+ case r == r1:
232
+ p := s.Prog(v.Op.Asm())
233
+ p.From.Type = obj.TYPE_REG
234
+ p.From.Reg = r2
235
+ p.To.Type = obj.TYPE_REG
236
+ p.To.Reg = r
237
+ case r == r2:
238
+ p := s.Prog(v.Op.Asm())
239
+ p.From.Type = obj.TYPE_REG
240
+ p.From.Reg = r1
241
+ p.To.Type = obj.TYPE_REG
242
+ p.To.Reg = r
243
+ default:
244
+ var asm obj.As
245
+ if v.Op == ssa.OpAMD64ADDQ {
246
+ asm = x86.ALEAQ
247
+ } else {
248
+ asm = x86.ALEAL
249
+ }
250
+ p := s.Prog(asm)
251
+ p.From.Type = obj.TYPE_MEM
252
+ p.From.Reg = r1
253
+ p.From.Scale = 1
254
+ p.From.Index = r2
255
+ p.To.Type = obj.TYPE_REG
256
+ p.To.Reg = r
257
+ }
258
+ // 2-address opcode arithmetic
259
+ case ssa.OpAMD64SUBQ, ssa.OpAMD64SUBL,
260
+ ssa.OpAMD64MULQ, ssa.OpAMD64MULL,
261
+ ssa.OpAMD64ANDQ, ssa.OpAMD64ANDL,
262
+ ssa.OpAMD64ORQ, ssa.OpAMD64ORL,
263
+ ssa.OpAMD64XORQ, ssa.OpAMD64XORL,
264
+ ssa.OpAMD64SHLQ, ssa.OpAMD64SHLL,
265
+ ssa.OpAMD64SHRQ, ssa.OpAMD64SHRL, ssa.OpAMD64SHRW, ssa.OpAMD64SHRB,
266
+ ssa.OpAMD64SARQ, ssa.OpAMD64SARL, ssa.OpAMD64SARW, ssa.OpAMD64SARB,
267
+ ssa.OpAMD64ROLQ, ssa.OpAMD64ROLL, ssa.OpAMD64ROLW, ssa.OpAMD64ROLB,
268
+ ssa.OpAMD64RORQ, ssa.OpAMD64RORL, ssa.OpAMD64RORW, ssa.OpAMD64RORB,
269
+ ssa.OpAMD64ADDSS, ssa.OpAMD64ADDSD, ssa.OpAMD64SUBSS, ssa.OpAMD64SUBSD,
270
+ ssa.OpAMD64MULSS, ssa.OpAMD64MULSD, ssa.OpAMD64DIVSS, ssa.OpAMD64DIVSD,
271
+ ssa.OpAMD64MINSS, ssa.OpAMD64MINSD,
272
+ ssa.OpAMD64POR, ssa.OpAMD64PXOR,
273
+ ssa.OpAMD64BTSL, ssa.OpAMD64BTSQ,
274
+ ssa.OpAMD64BTCL, ssa.OpAMD64BTCQ,
275
+ ssa.OpAMD64BTRL, ssa.OpAMD64BTRQ,
276
+ ssa.OpAMD64PCMPEQB, ssa.OpAMD64PSIGNB,
277
+ ssa.OpAMD64PUNPCKLBW:
278
+ opregreg(s, v.Op.Asm(), v.Reg(), v.Args[1].Reg())
279
+
280
+ case ssa.OpAMD64PSHUFLW:
281
+ p := s.Prog(v.Op.Asm())
282
+ imm := v.AuxInt
283
+ if imm < 0 || imm > 255 {
284
+ v.Fatalf("Invalid source selection immediate")
285
+ }
286
+ p.From.Offset = imm
287
+ p.From.Type = obj.TYPE_CONST
288
+ p.AddRestSourceReg(v.Args[0].Reg())
289
+ p.To.Type = obj.TYPE_REG
290
+ p.To.Reg = v.Reg()
291
+
292
+ case ssa.OpAMD64PSHUFBbroadcast:
293
+ // PSHUFB with a control mask of zero copies byte 0 to all
294
+ // bytes in the register.
295
+ //
296
+ // X15 is always zero with ABIInternal.
297
+ if s.ABI != obj.ABIInternal {
298
+ // zero X15 manually
299
+ opregreg(s, x86.AXORPS, x86.REG_X15, x86.REG_X15)
300
+ }
301
+
302
+ p := s.Prog(v.Op.Asm())
303
+ p.From.Type = obj.TYPE_REG
304
+ p.To.Type = obj.TYPE_REG
305
+ p.To.Reg = v.Reg()
306
+ p.From.Reg = x86.REG_X15
307
+
308
+ case ssa.OpAMD64SHRDQ, ssa.OpAMD64SHLDQ:
309
+ p := s.Prog(v.Op.Asm())
310
+ lo, hi, bits := v.Args[0].Reg(), v.Args[1].Reg(), v.Args[2].Reg()
311
+ p.From.Type = obj.TYPE_REG
312
+ p.From.Reg = bits
313
+ p.To.Type = obj.TYPE_REG
314
+ p.To.Reg = lo
315
+ p.AddRestSourceReg(hi)
316
+
317
+ case ssa.OpAMD64BLSIQ, ssa.OpAMD64BLSIL,
318
+ ssa.OpAMD64BLSMSKQ, ssa.OpAMD64BLSMSKL,
319
+ ssa.OpAMD64BLSRQ, ssa.OpAMD64BLSRL:
320
+ p := s.Prog(v.Op.Asm())
321
+ p.From.Type = obj.TYPE_REG
322
+ p.From.Reg = v.Args[0].Reg()
323
+ p.To.Type = obj.TYPE_REG
324
+ switch v.Op {
325
+ case ssa.OpAMD64BLSRQ, ssa.OpAMD64BLSRL:
326
+ p.To.Reg = v.Reg0()
327
+ default:
328
+ p.To.Reg = v.Reg()
329
+ }
330
+
331
+ case ssa.OpAMD64ANDNQ, ssa.OpAMD64ANDNL:
332
+ p := s.Prog(v.Op.Asm())
333
+ p.From.Type = obj.TYPE_REG
334
+ p.From.Reg = v.Args[0].Reg()
335
+ p.To.Type = obj.TYPE_REG
336
+ p.To.Reg = v.Reg()
337
+ p.AddRestSourceReg(v.Args[1].Reg())
338
+
339
+ case ssa.OpAMD64SARXL, ssa.OpAMD64SARXQ,
340
+ ssa.OpAMD64SHLXL, ssa.OpAMD64SHLXQ,
341
+ ssa.OpAMD64SHRXL, ssa.OpAMD64SHRXQ:
342
+ p := opregreg(s, v.Op.Asm(), v.Reg(), v.Args[1].Reg())
343
+ p.AddRestSourceReg(v.Args[0].Reg())
344
+
345
+ case ssa.OpAMD64SHLXLload, ssa.OpAMD64SHLXQload,
346
+ ssa.OpAMD64SHRXLload, ssa.OpAMD64SHRXQload,
347
+ ssa.OpAMD64SARXLload, ssa.OpAMD64SARXQload:
348
+ p := opregreg(s, v.Op.Asm(), v.Reg(), v.Args[1].Reg())
349
+ m := obj.Addr{Type: obj.TYPE_MEM, Reg: v.Args[0].Reg()}
350
+ ssagen.AddAux(&m, v)
351
+ p.AddRestSource(m)
352
+
353
+ case ssa.OpAMD64SHLXLloadidx1, ssa.OpAMD64SHLXLloadidx4, ssa.OpAMD64SHLXLloadidx8,
354
+ ssa.OpAMD64SHRXLloadidx1, ssa.OpAMD64SHRXLloadidx4, ssa.OpAMD64SHRXLloadidx8,
355
+ ssa.OpAMD64SARXLloadidx1, ssa.OpAMD64SARXLloadidx4, ssa.OpAMD64SARXLloadidx8,
356
+ ssa.OpAMD64SHLXQloadidx1, ssa.OpAMD64SHLXQloadidx8,
357
+ ssa.OpAMD64SHRXQloadidx1, ssa.OpAMD64SHRXQloadidx8,
358
+ ssa.OpAMD64SARXQloadidx1, ssa.OpAMD64SARXQloadidx8:
359
+ p := opregreg(s, v.Op.Asm(), v.Reg(), v.Args[2].Reg())
360
+ m := obj.Addr{Type: obj.TYPE_MEM}
361
+ memIdx(&m, v)
362
+ ssagen.AddAux(&m, v)
363
+ p.AddRestSource(m)
364
+
365
+ case ssa.OpAMD64DIVQU, ssa.OpAMD64DIVLU, ssa.OpAMD64DIVWU:
366
+ // Arg[0] (the dividend) is in AX.
367
+ // Arg[1] (the divisor) can be in any other register.
368
+ // Result[0] (the quotient) is in AX.
369
+ // Result[1] (the remainder) is in DX.
370
+ r := v.Args[1].Reg()
371
+
372
+ // Zero extend dividend.
373
+ opregreg(s, x86.AXORL, x86.REG_DX, x86.REG_DX)
374
+
375
+ // Issue divide.
376
+ p := s.Prog(v.Op.Asm())
377
+ p.From.Type = obj.TYPE_REG
378
+ p.From.Reg = r
379
+
380
+ case ssa.OpAMD64DIVQ, ssa.OpAMD64DIVL, ssa.OpAMD64DIVW:
381
+ // Arg[0] (the dividend) is in AX.
382
+ // Arg[1] (the divisor) can be in any other register.
383
+ // Result[0] (the quotient) is in AX.
384
+ // Result[1] (the remainder) is in DX.
385
+ r := v.Args[1].Reg()
386
+
387
+ var opCMP, opNEG, opSXD obj.As
388
+ switch v.Op {
389
+ case ssa.OpAMD64DIVQ:
390
+ opCMP, opNEG, opSXD = x86.ACMPQ, x86.ANEGQ, x86.ACQO
391
+ case ssa.OpAMD64DIVL:
392
+ opCMP, opNEG, opSXD = x86.ACMPL, x86.ANEGL, x86.ACDQ
393
+ case ssa.OpAMD64DIVW:
394
+ opCMP, opNEG, opSXD = x86.ACMPW, x86.ANEGW, x86.ACWD
395
+ }
396
+
397
+ // CPU faults upon signed overflow, which occurs when the most
398
+ // negative int is divided by -1. Handle divide by -1 as a special case.
399
+ var j1, j2 *obj.Prog
400
+ if ssa.DivisionNeedsFixUp(v) {
401
+ c := s.Prog(opCMP)
402
+ c.From.Type = obj.TYPE_REG
403
+ c.From.Reg = r
404
+ c.To.Type = obj.TYPE_CONST
405
+ c.To.Offset = -1
406
+
407
+ // Divisor is not -1, proceed with normal division.
408
+ j1 = s.Prog(x86.AJNE)
409
+ j1.To.Type = obj.TYPE_BRANCH
410
+
411
+ // Divisor is -1, manually compute quotient and remainder via fixup code.
412
+ // n / -1 = -n
413
+ n1 := s.Prog(opNEG)
414
+ n1.To.Type = obj.TYPE_REG
415
+ n1.To.Reg = x86.REG_AX
416
+
417
+ // n % -1 == 0
418
+ opregreg(s, x86.AXORL, x86.REG_DX, x86.REG_DX)
419
+
420
+ // TODO(khr): issue only the -1 fixup code we need.
421
+ // For instance, if only the quotient is used, no point in zeroing the remainder.
422
+
423
+ // Skip over normal division.
424
+ j2 = s.Prog(obj.AJMP)
425
+ j2.To.Type = obj.TYPE_BRANCH
426
+ }
427
+
428
+ // Sign extend dividend and perform division.
429
+ p := s.Prog(opSXD)
430
+ if j1 != nil {
431
+ j1.To.SetTarget(p)
432
+ }
433
+ p = s.Prog(v.Op.Asm())
434
+ p.From.Type = obj.TYPE_REG
435
+ p.From.Reg = r
436
+
437
+ if j2 != nil {
438
+ j2.To.SetTarget(s.Pc())
439
+ }
440
+
441
+ case ssa.OpAMD64HMULQ, ssa.OpAMD64HMULL, ssa.OpAMD64HMULQU, ssa.OpAMD64HMULLU:
442
+ // the frontend rewrites constant division by 8/16/32 bit integers into
443
+ // HMUL by a constant
444
+ // SSA rewrites generate the 64 bit versions
445
+
446
+ // Arg[0] is already in AX as it's the only register we allow
447
+ // and DX is the only output we care about (the high bits)
448
+ p := s.Prog(v.Op.Asm())
449
+ p.From.Type = obj.TYPE_REG
450
+ p.From.Reg = v.Args[1].Reg()
451
+
452
+ // IMULB puts the high portion in AH instead of DL,
453
+ // so move it to DL for consistency
454
+ if v.Type.Size() == 1 {
455
+ m := s.Prog(x86.AMOVB)
456
+ m.From.Type = obj.TYPE_REG
457
+ m.From.Reg = x86.REG_AH
458
+ m.To.Type = obj.TYPE_REG
459
+ m.To.Reg = x86.REG_DX
460
+ }
461
+
462
+ case ssa.OpAMD64MULQU, ssa.OpAMD64MULLU:
463
+ // Arg[0] is already in AX as it's the only register we allow
464
+ // results lo in AX
465
+ p := s.Prog(v.Op.Asm())
466
+ p.From.Type = obj.TYPE_REG
467
+ p.From.Reg = v.Args[1].Reg()
468
+
469
+ case ssa.OpAMD64MULQU2:
470
+ // Arg[0] is already in AX as it's the only register we allow
471
+ // results hi in DX, lo in AX
472
+ p := s.Prog(v.Op.Asm())
473
+ p.From.Type = obj.TYPE_REG
474
+ p.From.Reg = v.Args[1].Reg()
475
+
476
+ case ssa.OpAMD64DIVQU2:
477
+ // Arg[0], Arg[1] are already in Dx, AX, as they're the only registers we allow
478
+ // results q in AX, r in DX
479
+ p := s.Prog(v.Op.Asm())
480
+ p.From.Type = obj.TYPE_REG
481
+ p.From.Reg = v.Args[2].Reg()
482
+
483
+ case ssa.OpAMD64AVGQU:
484
+ // compute (x+y)/2 unsigned.
485
+ // Do a 64-bit add, the overflow goes into the carry.
486
+ // Shift right once and pull the carry back into the 63rd bit.
487
+ p := s.Prog(x86.AADDQ)
488
+ p.From.Type = obj.TYPE_REG
489
+ p.To.Type = obj.TYPE_REG
490
+ p.To.Reg = v.Reg()
491
+ p.From.Reg = v.Args[1].Reg()
492
+ p = s.Prog(x86.ARCRQ)
493
+ p.From.Type = obj.TYPE_CONST
494
+ p.From.Offset = 1
495
+ p.To.Type = obj.TYPE_REG
496
+ p.To.Reg = v.Reg()
497
+
498
+ case ssa.OpAMD64ADDQcarry, ssa.OpAMD64ADCQ:
499
+ r := v.Reg0()
500
+ r0 := v.Args[0].Reg()
501
+ r1 := v.Args[1].Reg()
502
+ switch r {
503
+ case r0:
504
+ p := s.Prog(v.Op.Asm())
505
+ p.From.Type = obj.TYPE_REG
506
+ p.From.Reg = r1
507
+ p.To.Type = obj.TYPE_REG
508
+ p.To.Reg = r
509
+ case r1:
510
+ p := s.Prog(v.Op.Asm())
511
+ p.From.Type = obj.TYPE_REG
512
+ p.From.Reg = r0
513
+ p.To.Type = obj.TYPE_REG
514
+ p.To.Reg = r
515
+ default:
516
+ v.Fatalf("output not in same register as an input %s", v.LongString())
517
+ }
518
+
519
+ case ssa.OpAMD64SUBQborrow, ssa.OpAMD64SBBQ:
520
+ p := s.Prog(v.Op.Asm())
521
+ p.From.Type = obj.TYPE_REG
522
+ p.From.Reg = v.Args[1].Reg()
523
+ p.To.Type = obj.TYPE_REG
524
+ p.To.Reg = v.Reg0()
525
+
526
+ case ssa.OpAMD64ADDQconstcarry, ssa.OpAMD64ADCQconst, ssa.OpAMD64SUBQconstborrow, ssa.OpAMD64SBBQconst:
527
+ p := s.Prog(v.Op.Asm())
528
+ p.From.Type = obj.TYPE_CONST
529
+ p.From.Offset = v.AuxInt
530
+ p.To.Type = obj.TYPE_REG
531
+ p.To.Reg = v.Reg0()
532
+
533
+ case ssa.OpAMD64ADDQconst, ssa.OpAMD64ADDLconst:
534
+ r := v.Reg()
535
+ a := v.Args[0].Reg()
536
+ if r == a {
537
+ switch v.AuxInt {
538
+ case 1:
539
+ var asm obj.As
540
+ // Software optimization manual recommends add $1,reg.
541
+ // But inc/dec is 1 byte smaller. ICC always uses inc
542
+ // Clang/GCC choose depending on flags, but prefer add.
543
+ // Experiments show that inc/dec is both a little faster
544
+ // and make a binary a little smaller.
545
+ if v.Op == ssa.OpAMD64ADDQconst {
546
+ asm = x86.AINCQ
547
+ } else {
548
+ asm = x86.AINCL
549
+ }
550
+ p := s.Prog(asm)
551
+ p.To.Type = obj.TYPE_REG
552
+ p.To.Reg = r
553
+ return
554
+ case -1:
555
+ var asm obj.As
556
+ if v.Op == ssa.OpAMD64ADDQconst {
557
+ asm = x86.ADECQ
558
+ } else {
559
+ asm = x86.ADECL
560
+ }
561
+ p := s.Prog(asm)
562
+ p.To.Type = obj.TYPE_REG
563
+ p.To.Reg = r
564
+ return
565
+ case 0x80:
566
+ // 'SUBQ $-0x80, r' is shorter to encode than
567
+ // and functionally equivalent to 'ADDQ $0x80, r'.
568
+ asm := x86.ASUBL
569
+ if v.Op == ssa.OpAMD64ADDQconst {
570
+ asm = x86.ASUBQ
571
+ }
572
+ p := s.Prog(asm)
573
+ p.From.Type = obj.TYPE_CONST
574
+ p.From.Offset = -0x80
575
+ p.To.Type = obj.TYPE_REG
576
+ p.To.Reg = r
577
+ return
578
+
579
+ }
580
+ p := s.Prog(v.Op.Asm())
581
+ p.From.Type = obj.TYPE_CONST
582
+ p.From.Offset = v.AuxInt
583
+ p.To.Type = obj.TYPE_REG
584
+ p.To.Reg = r
585
+ return
586
+ }
587
+ var asm obj.As
588
+ if v.Op == ssa.OpAMD64ADDQconst {
589
+ asm = x86.ALEAQ
590
+ } else {
591
+ asm = x86.ALEAL
592
+ }
593
+ p := s.Prog(asm)
594
+ p.From.Type = obj.TYPE_MEM
595
+ p.From.Reg = a
596
+ p.From.Offset = v.AuxInt
597
+ p.To.Type = obj.TYPE_REG
598
+ p.To.Reg = r
599
+
600
+ case ssa.OpAMD64CMOVQEQ, ssa.OpAMD64CMOVLEQ, ssa.OpAMD64CMOVWEQ,
601
+ ssa.OpAMD64CMOVQLT, ssa.OpAMD64CMOVLLT, ssa.OpAMD64CMOVWLT,
602
+ ssa.OpAMD64CMOVQNE, ssa.OpAMD64CMOVLNE, ssa.OpAMD64CMOVWNE,
603
+ ssa.OpAMD64CMOVQGT, ssa.OpAMD64CMOVLGT, ssa.OpAMD64CMOVWGT,
604
+ ssa.OpAMD64CMOVQLE, ssa.OpAMD64CMOVLLE, ssa.OpAMD64CMOVWLE,
605
+ ssa.OpAMD64CMOVQGE, ssa.OpAMD64CMOVLGE, ssa.OpAMD64CMOVWGE,
606
+ ssa.OpAMD64CMOVQHI, ssa.OpAMD64CMOVLHI, ssa.OpAMD64CMOVWHI,
607
+ ssa.OpAMD64CMOVQLS, ssa.OpAMD64CMOVLLS, ssa.OpAMD64CMOVWLS,
608
+ ssa.OpAMD64CMOVQCC, ssa.OpAMD64CMOVLCC, ssa.OpAMD64CMOVWCC,
609
+ ssa.OpAMD64CMOVQCS, ssa.OpAMD64CMOVLCS, ssa.OpAMD64CMOVWCS,
610
+ ssa.OpAMD64CMOVQGTF, ssa.OpAMD64CMOVLGTF, ssa.OpAMD64CMOVWGTF,
611
+ ssa.OpAMD64CMOVQGEF, ssa.OpAMD64CMOVLGEF, ssa.OpAMD64CMOVWGEF:
612
+ p := s.Prog(v.Op.Asm())
613
+ p.From.Type = obj.TYPE_REG
614
+ p.From.Reg = v.Args[1].Reg()
615
+ p.To.Type = obj.TYPE_REG
616
+ p.To.Reg = v.Reg()
617
+
618
+ case ssa.OpAMD64CMOVQNEF, ssa.OpAMD64CMOVLNEF, ssa.OpAMD64CMOVWNEF:
619
+ // Flag condition: ^ZERO || PARITY
620
+ // Generate:
621
+ // CMOV*NE SRC,DST
622
+ // CMOV*PS SRC,DST
623
+ p := s.Prog(v.Op.Asm())
624
+ p.From.Type = obj.TYPE_REG
625
+ p.From.Reg = v.Args[1].Reg()
626
+ p.To.Type = obj.TYPE_REG
627
+ p.To.Reg = v.Reg()
628
+ var q *obj.Prog
629
+ if v.Op == ssa.OpAMD64CMOVQNEF {
630
+ q = s.Prog(x86.ACMOVQPS)
631
+ } else if v.Op == ssa.OpAMD64CMOVLNEF {
632
+ q = s.Prog(x86.ACMOVLPS)
633
+ } else {
634
+ q = s.Prog(x86.ACMOVWPS)
635
+ }
636
+ q.From.Type = obj.TYPE_REG
637
+ q.From.Reg = v.Args[1].Reg()
638
+ q.To.Type = obj.TYPE_REG
639
+ q.To.Reg = v.Reg()
640
+
641
+ case ssa.OpAMD64CMOVQEQF, ssa.OpAMD64CMOVLEQF, ssa.OpAMD64CMOVWEQF:
642
+ // Flag condition: ZERO && !PARITY
643
+ // Generate:
644
+ // MOV SRC,TMP
645
+ // CMOV*NE DST,TMP
646
+ // CMOV*PC TMP,DST
647
+ //
648
+ // TODO(rasky): we could generate:
649
+ // CMOV*NE DST,SRC
650
+ // CMOV*PC SRC,DST
651
+ // But this requires a way for regalloc to know that SRC might be
652
+ // clobbered by this instruction.
653
+ t := v.RegTmp()
654
+ opregreg(s, moveByRegsWidth(t, v.Args[1].Reg(), v.Type.Size()), t, v.Args[1].Reg())
655
+
656
+ p := s.Prog(v.Op.Asm())
657
+ p.From.Type = obj.TYPE_REG
658
+ p.From.Reg = v.Reg()
659
+ p.To.Type = obj.TYPE_REG
660
+ p.To.Reg = t
661
+ var q *obj.Prog
662
+ if v.Op == ssa.OpAMD64CMOVQEQF {
663
+ q = s.Prog(x86.ACMOVQPC)
664
+ } else if v.Op == ssa.OpAMD64CMOVLEQF {
665
+ q = s.Prog(x86.ACMOVLPC)
666
+ } else {
667
+ q = s.Prog(x86.ACMOVWPC)
668
+ }
669
+ q.From.Type = obj.TYPE_REG
670
+ q.From.Reg = t
671
+ q.To.Type = obj.TYPE_REG
672
+ q.To.Reg = v.Reg()
673
+
674
+ case ssa.OpAMD64MULQconst, ssa.OpAMD64MULLconst:
675
+ r := v.Reg()
676
+ p := s.Prog(v.Op.Asm())
677
+ p.From.Type = obj.TYPE_CONST
678
+ p.From.Offset = v.AuxInt
679
+ p.To.Type = obj.TYPE_REG
680
+ p.To.Reg = r
681
+ p.AddRestSourceReg(v.Args[0].Reg())
682
+
683
+ case ssa.OpAMD64ANDQconst:
684
+ asm := v.Op.Asm()
685
+ // If the constant is positive and fits into 32 bits, use ANDL.
686
+ // This saves a few bytes of encoding.
687
+ if 0 <= v.AuxInt && v.AuxInt <= (1<<32-1) {
688
+ asm = x86.AANDL
689
+ }
690
+ p := s.Prog(asm)
691
+ p.From.Type = obj.TYPE_CONST
692
+ p.From.Offset = v.AuxInt
693
+ p.To.Type = obj.TYPE_REG
694
+ p.To.Reg = v.Reg()
695
+
696
+ case ssa.OpAMD64SUBQconst, ssa.OpAMD64SUBLconst,
697
+ ssa.OpAMD64ANDLconst,
698
+ ssa.OpAMD64ORQconst, ssa.OpAMD64ORLconst,
699
+ ssa.OpAMD64XORQconst, ssa.OpAMD64XORLconst,
700
+ ssa.OpAMD64SHLQconst, ssa.OpAMD64SHLLconst,
701
+ ssa.OpAMD64SHRQconst, ssa.OpAMD64SHRLconst, ssa.OpAMD64SHRWconst, ssa.OpAMD64SHRBconst,
702
+ ssa.OpAMD64SARQconst, ssa.OpAMD64SARLconst, ssa.OpAMD64SARWconst, ssa.OpAMD64SARBconst,
703
+ ssa.OpAMD64ROLQconst, ssa.OpAMD64ROLLconst, ssa.OpAMD64ROLWconst, ssa.OpAMD64ROLBconst:
704
+ p := s.Prog(v.Op.Asm())
705
+ p.From.Type = obj.TYPE_CONST
706
+ p.From.Offset = v.AuxInt
707
+ p.To.Type = obj.TYPE_REG
708
+ p.To.Reg = v.Reg()
709
+ case ssa.OpAMD64SBBQcarrymask, ssa.OpAMD64SBBLcarrymask:
710
+ r := v.Reg()
711
+ p := s.Prog(v.Op.Asm())
712
+ p.From.Type = obj.TYPE_REG
713
+ p.From.Reg = r
714
+ p.To.Type = obj.TYPE_REG
715
+ p.To.Reg = r
716
+ case ssa.OpAMD64LEAQ1, ssa.OpAMD64LEAQ2, ssa.OpAMD64LEAQ4, ssa.OpAMD64LEAQ8,
717
+ ssa.OpAMD64LEAL1, ssa.OpAMD64LEAL2, ssa.OpAMD64LEAL4, ssa.OpAMD64LEAL8,
718
+ ssa.OpAMD64LEAW1, ssa.OpAMD64LEAW2, ssa.OpAMD64LEAW4, ssa.OpAMD64LEAW8:
719
+ p := s.Prog(v.Op.Asm())
720
+ memIdx(&p.From, v)
721
+ o := v.Reg()
722
+ p.To.Type = obj.TYPE_REG
723
+ p.To.Reg = o
724
+ if v.AuxInt != 0 && v.Aux == nil {
725
+ // Emit an additional LEA to add the displacement instead of creating a slow 3 operand LEA.
726
+ switch v.Op {
727
+ case ssa.OpAMD64LEAQ1, ssa.OpAMD64LEAQ2, ssa.OpAMD64LEAQ4, ssa.OpAMD64LEAQ8:
728
+ p = s.Prog(x86.ALEAQ)
729
+ case ssa.OpAMD64LEAL1, ssa.OpAMD64LEAL2, ssa.OpAMD64LEAL4, ssa.OpAMD64LEAL8:
730
+ p = s.Prog(x86.ALEAL)
731
+ case ssa.OpAMD64LEAW1, ssa.OpAMD64LEAW2, ssa.OpAMD64LEAW4, ssa.OpAMD64LEAW8:
732
+ p = s.Prog(x86.ALEAW)
733
+ }
734
+ p.From.Type = obj.TYPE_MEM
735
+ p.From.Reg = o
736
+ p.To.Type = obj.TYPE_REG
737
+ p.To.Reg = o
738
+ }
739
+ ssagen.AddAux(&p.From, v)
740
+ case ssa.OpAMD64LEAQ, ssa.OpAMD64LEAL, ssa.OpAMD64LEAW:
741
+ p := s.Prog(v.Op.Asm())
742
+ p.From.Type = obj.TYPE_MEM
743
+ p.From.Reg = v.Args[0].Reg()
744
+ ssagen.AddAux(&p.From, v)
745
+ p.To.Type = obj.TYPE_REG
746
+ p.To.Reg = v.Reg()
747
+ case ssa.OpAMD64CMPQ, ssa.OpAMD64CMPL, ssa.OpAMD64CMPW, ssa.OpAMD64CMPB,
748
+ ssa.OpAMD64TESTQ, ssa.OpAMD64TESTL, ssa.OpAMD64TESTW, ssa.OpAMD64TESTB,
749
+ ssa.OpAMD64BTL, ssa.OpAMD64BTQ:
750
+ opregreg(s, v.Op.Asm(), v.Args[1].Reg(), v.Args[0].Reg())
751
+ case ssa.OpAMD64UCOMISS, ssa.OpAMD64UCOMISD:
752
+ // Go assembler has swapped operands for UCOMISx relative to CMP,
753
+ // must account for that right here.
754
+ opregreg(s, v.Op.Asm(), v.Args[0].Reg(), v.Args[1].Reg())
755
+ case ssa.OpAMD64CMPQconst, ssa.OpAMD64CMPLconst, ssa.OpAMD64CMPWconst, ssa.OpAMD64CMPBconst:
756
+ p := s.Prog(v.Op.Asm())
757
+ p.From.Type = obj.TYPE_REG
758
+ p.From.Reg = v.Args[0].Reg()
759
+ p.To.Type = obj.TYPE_CONST
760
+ p.To.Offset = v.AuxInt
761
+ case ssa.OpAMD64BTLconst, ssa.OpAMD64BTQconst,
762
+ ssa.OpAMD64TESTQconst, ssa.OpAMD64TESTLconst, ssa.OpAMD64TESTWconst, ssa.OpAMD64TESTBconst,
763
+ ssa.OpAMD64BTSQconst,
764
+ ssa.OpAMD64BTCQconst,
765
+ ssa.OpAMD64BTRQconst:
766
+ op := v.Op
767
+ if op == ssa.OpAMD64BTQconst && v.AuxInt < 32 {
768
+ // Emit 32-bit version because it's shorter
769
+ op = ssa.OpAMD64BTLconst
770
+ }
771
+ p := s.Prog(op.Asm())
772
+ p.From.Type = obj.TYPE_CONST
773
+ p.From.Offset = v.AuxInt
774
+ p.To.Type = obj.TYPE_REG
775
+ p.To.Reg = v.Args[0].Reg()
776
+ case ssa.OpAMD64CMPQload, ssa.OpAMD64CMPLload, ssa.OpAMD64CMPWload, ssa.OpAMD64CMPBload:
777
+ p := s.Prog(v.Op.Asm())
778
+ p.From.Type = obj.TYPE_MEM
779
+ p.From.Reg = v.Args[0].Reg()
780
+ ssagen.AddAux(&p.From, v)
781
+ p.To.Type = obj.TYPE_REG
782
+ p.To.Reg = v.Args[1].Reg()
783
+ case ssa.OpAMD64CMPQconstload, ssa.OpAMD64CMPLconstload, ssa.OpAMD64CMPWconstload, ssa.OpAMD64CMPBconstload:
784
+ sc := v.AuxValAndOff()
785
+ p := s.Prog(v.Op.Asm())
786
+ p.From.Type = obj.TYPE_MEM
787
+ p.From.Reg = v.Args[0].Reg()
788
+ ssagen.AddAux2(&p.From, v, sc.Off64())
789
+ p.To.Type = obj.TYPE_CONST
790
+ p.To.Offset = sc.Val64()
791
+ case ssa.OpAMD64CMPQloadidx8, ssa.OpAMD64CMPQloadidx1, ssa.OpAMD64CMPLloadidx4, ssa.OpAMD64CMPLloadidx1, ssa.OpAMD64CMPWloadidx2, ssa.OpAMD64CMPWloadidx1, ssa.OpAMD64CMPBloadidx1:
792
+ p := s.Prog(v.Op.Asm())
793
+ memIdx(&p.From, v)
794
+ ssagen.AddAux(&p.From, v)
795
+ p.To.Type = obj.TYPE_REG
796
+ p.To.Reg = v.Args[2].Reg()
797
+ case ssa.OpAMD64CMPQconstloadidx8, ssa.OpAMD64CMPQconstloadidx1, ssa.OpAMD64CMPLconstloadidx4, ssa.OpAMD64CMPLconstloadidx1, ssa.OpAMD64CMPWconstloadidx2, ssa.OpAMD64CMPWconstloadidx1, ssa.OpAMD64CMPBconstloadidx1:
798
+ sc := v.AuxValAndOff()
799
+ p := s.Prog(v.Op.Asm())
800
+ memIdx(&p.From, v)
801
+ ssagen.AddAux2(&p.From, v, sc.Off64())
802
+ p.To.Type = obj.TYPE_CONST
803
+ p.To.Offset = sc.Val64()
804
+ case ssa.OpAMD64MOVLconst, ssa.OpAMD64MOVQconst:
805
+ x := v.Reg()
806
+
807
+ // If flags aren't live (indicated by v.Aux == nil),
808
+ // then we can rewrite MOV $0, AX into XOR AX, AX.
809
+ if v.AuxInt == 0 && v.Aux == nil {
810
+ opregreg(s, x86.AXORL, x, x)
811
+ break
812
+ }
813
+
814
+ asm := v.Op.Asm()
815
+ // Use MOVL to move a small constant into a register
816
+ // when the constant is positive and fits into 32 bits.
817
+ if 0 <= v.AuxInt && v.AuxInt <= (1<<32-1) {
818
+ // The upper 32bit are zeroed automatically when using MOVL.
819
+ asm = x86.AMOVL
820
+ }
821
+ p := s.Prog(asm)
822
+ p.From.Type = obj.TYPE_CONST
823
+ p.From.Offset = v.AuxInt
824
+ p.To.Type = obj.TYPE_REG
825
+ p.To.Reg = x
826
+
827
+ case ssa.OpAMD64MOVSSconst, ssa.OpAMD64MOVSDconst:
828
+ x := v.Reg()
829
+ if !isFPReg(x) && v.AuxInt == 0 && v.Aux == nil {
830
+ opregreg(s, x86.AXORL, x, x)
831
+ break
832
+ }
833
+ p := s.Prog(storeByRegWidth(x, v.Type.Size()))
834
+ p.From.Type = obj.TYPE_FCONST
835
+ p.From.Val = math.Float64frombits(uint64(v.AuxInt))
836
+ p.To.Type = obj.TYPE_REG
837
+ p.To.Reg = x
838
+ case ssa.OpAMD64MOVQload, ssa.OpAMD64MOVLload, ssa.OpAMD64MOVWload, ssa.OpAMD64MOVBload, ssa.OpAMD64MOVOload,
839
+ ssa.OpAMD64MOVSSload, ssa.OpAMD64MOVSDload, ssa.OpAMD64MOVBQSXload, ssa.OpAMD64MOVWQSXload, ssa.OpAMD64MOVLQSXload,
840
+ ssa.OpAMD64MOVBEQload, ssa.OpAMD64MOVBELload:
841
+ p := s.Prog(v.Op.Asm())
842
+ p.From.Type = obj.TYPE_MEM
843
+ p.From.Reg = v.Args[0].Reg()
844
+ ssagen.AddAux(&p.From, v)
845
+ p.To.Type = obj.TYPE_REG
846
+ p.To.Reg = v.Reg()
847
+ case ssa.OpAMD64MOVBloadidx1, ssa.OpAMD64MOVWloadidx1, ssa.OpAMD64MOVLloadidx1, ssa.OpAMD64MOVQloadidx1, ssa.OpAMD64MOVSSloadidx1, ssa.OpAMD64MOVSDloadidx1,
848
+ ssa.OpAMD64MOVQloadidx8, ssa.OpAMD64MOVSDloadidx8, ssa.OpAMD64MOVLloadidx8, ssa.OpAMD64MOVLloadidx4, ssa.OpAMD64MOVSSloadidx4, ssa.OpAMD64MOVWloadidx2,
849
+ ssa.OpAMD64MOVBELloadidx1, ssa.OpAMD64MOVBELloadidx4, ssa.OpAMD64MOVBELloadidx8, ssa.OpAMD64MOVBEQloadidx1, ssa.OpAMD64MOVBEQloadidx8:
850
+ p := s.Prog(v.Op.Asm())
851
+ memIdx(&p.From, v)
852
+ ssagen.AddAux(&p.From, v)
853
+ p.To.Type = obj.TYPE_REG
854
+ p.To.Reg = v.Reg()
855
+ case ssa.OpAMD64MOVQstore, ssa.OpAMD64MOVSSstore, ssa.OpAMD64MOVSDstore, ssa.OpAMD64MOVLstore, ssa.OpAMD64MOVWstore, ssa.OpAMD64MOVBstore, ssa.OpAMD64MOVOstore,
856
+ ssa.OpAMD64ADDQmodify, ssa.OpAMD64SUBQmodify, ssa.OpAMD64ANDQmodify, ssa.OpAMD64ORQmodify, ssa.OpAMD64XORQmodify,
857
+ ssa.OpAMD64ADDLmodify, ssa.OpAMD64SUBLmodify, ssa.OpAMD64ANDLmodify, ssa.OpAMD64ORLmodify, ssa.OpAMD64XORLmodify,
858
+ ssa.OpAMD64MOVBEQstore, ssa.OpAMD64MOVBELstore, ssa.OpAMD64MOVBEWstore:
859
+ p := s.Prog(v.Op.Asm())
860
+ p.From.Type = obj.TYPE_REG
861
+ p.From.Reg = v.Args[1].Reg()
862
+ p.To.Type = obj.TYPE_MEM
863
+ p.To.Reg = v.Args[0].Reg()
864
+ ssagen.AddAux(&p.To, v)
865
+ case ssa.OpAMD64MOVBstoreidx1, ssa.OpAMD64MOVWstoreidx1, ssa.OpAMD64MOVLstoreidx1, ssa.OpAMD64MOVQstoreidx1, ssa.OpAMD64MOVSSstoreidx1, ssa.OpAMD64MOVSDstoreidx1,
866
+ ssa.OpAMD64MOVQstoreidx8, ssa.OpAMD64MOVSDstoreidx8, ssa.OpAMD64MOVLstoreidx8, ssa.OpAMD64MOVSSstoreidx4, ssa.OpAMD64MOVLstoreidx4, ssa.OpAMD64MOVWstoreidx2,
867
+ ssa.OpAMD64ADDLmodifyidx1, ssa.OpAMD64ADDLmodifyidx4, ssa.OpAMD64ADDLmodifyidx8, ssa.OpAMD64ADDQmodifyidx1, ssa.OpAMD64ADDQmodifyidx8,
868
+ ssa.OpAMD64SUBLmodifyidx1, ssa.OpAMD64SUBLmodifyidx4, ssa.OpAMD64SUBLmodifyidx8, ssa.OpAMD64SUBQmodifyidx1, ssa.OpAMD64SUBQmodifyidx8,
869
+ ssa.OpAMD64ANDLmodifyidx1, ssa.OpAMD64ANDLmodifyidx4, ssa.OpAMD64ANDLmodifyidx8, ssa.OpAMD64ANDQmodifyidx1, ssa.OpAMD64ANDQmodifyidx8,
870
+ ssa.OpAMD64ORLmodifyidx1, ssa.OpAMD64ORLmodifyidx4, ssa.OpAMD64ORLmodifyidx8, ssa.OpAMD64ORQmodifyidx1, ssa.OpAMD64ORQmodifyidx8,
871
+ ssa.OpAMD64XORLmodifyidx1, ssa.OpAMD64XORLmodifyidx4, ssa.OpAMD64XORLmodifyidx8, ssa.OpAMD64XORQmodifyidx1, ssa.OpAMD64XORQmodifyidx8,
872
+ ssa.OpAMD64MOVBEWstoreidx1, ssa.OpAMD64MOVBEWstoreidx2, ssa.OpAMD64MOVBELstoreidx1, ssa.OpAMD64MOVBELstoreidx4, ssa.OpAMD64MOVBELstoreidx8, ssa.OpAMD64MOVBEQstoreidx1, ssa.OpAMD64MOVBEQstoreidx8:
873
+ p := s.Prog(v.Op.Asm())
874
+ p.From.Type = obj.TYPE_REG
875
+ p.From.Reg = v.Args[2].Reg()
876
+ memIdx(&p.To, v)
877
+ ssagen.AddAux(&p.To, v)
878
+ case ssa.OpAMD64ADDQconstmodify, ssa.OpAMD64ADDLconstmodify:
879
+ sc := v.AuxValAndOff()
880
+ off := sc.Off64()
881
+ val := sc.Val()
882
+ if val == 1 || val == -1 {
883
+ var asm obj.As
884
+ if v.Op == ssa.OpAMD64ADDQconstmodify {
885
+ if val == 1 {
886
+ asm = x86.AINCQ
887
+ } else {
888
+ asm = x86.ADECQ
889
+ }
890
+ } else {
891
+ if val == 1 {
892
+ asm = x86.AINCL
893
+ } else {
894
+ asm = x86.ADECL
895
+ }
896
+ }
897
+ p := s.Prog(asm)
898
+ p.To.Type = obj.TYPE_MEM
899
+ p.To.Reg = v.Args[0].Reg()
900
+ ssagen.AddAux2(&p.To, v, off)
901
+ break
902
+ }
903
+ fallthrough
904
+ case ssa.OpAMD64ANDQconstmodify, ssa.OpAMD64ANDLconstmodify, ssa.OpAMD64ORQconstmodify, ssa.OpAMD64ORLconstmodify,
905
+ ssa.OpAMD64XORQconstmodify, ssa.OpAMD64XORLconstmodify,
906
+ ssa.OpAMD64BTSQconstmodify, ssa.OpAMD64BTRQconstmodify, ssa.OpAMD64BTCQconstmodify:
907
+ sc := v.AuxValAndOff()
908
+ off := sc.Off64()
909
+ val := sc.Val64()
910
+ p := s.Prog(v.Op.Asm())
911
+ p.From.Type = obj.TYPE_CONST
912
+ p.From.Offset = val
913
+ p.To.Type = obj.TYPE_MEM
914
+ p.To.Reg = v.Args[0].Reg()
915
+ ssagen.AddAux2(&p.To, v, off)
916
+
917
+ case ssa.OpAMD64MOVQstoreconst, ssa.OpAMD64MOVLstoreconst, ssa.OpAMD64MOVWstoreconst, ssa.OpAMD64MOVBstoreconst:
918
+ p := s.Prog(v.Op.Asm())
919
+ p.From.Type = obj.TYPE_CONST
920
+ sc := v.AuxValAndOff()
921
+ p.From.Offset = sc.Val64()
922
+ p.To.Type = obj.TYPE_MEM
923
+ p.To.Reg = v.Args[0].Reg()
924
+ ssagen.AddAux2(&p.To, v, sc.Off64())
925
+ case ssa.OpAMD64MOVOstoreconst:
926
+ sc := v.AuxValAndOff()
927
+ if sc.Val() != 0 {
928
+ v.Fatalf("MOVO for non zero constants not implemented: %s", v.LongString())
929
+ }
930
+
931
+ if s.ABI != obj.ABIInternal {
932
+ // zero X15 manually
933
+ opregreg(s, x86.AXORPS, x86.REG_X15, x86.REG_X15)
934
+ }
935
+ p := s.Prog(v.Op.Asm())
936
+ p.From.Type = obj.TYPE_REG
937
+ p.From.Reg = x86.REG_X15
938
+ p.To.Type = obj.TYPE_MEM
939
+ p.To.Reg = v.Args[0].Reg()
940
+ ssagen.AddAux2(&p.To, v, sc.Off64())
941
+
942
+ case ssa.OpAMD64MOVQstoreconstidx1, ssa.OpAMD64MOVQstoreconstidx8, ssa.OpAMD64MOVLstoreconstidx1, ssa.OpAMD64MOVLstoreconstidx4, ssa.OpAMD64MOVWstoreconstidx1, ssa.OpAMD64MOVWstoreconstidx2, ssa.OpAMD64MOVBstoreconstidx1,
943
+ ssa.OpAMD64ADDLconstmodifyidx1, ssa.OpAMD64ADDLconstmodifyidx4, ssa.OpAMD64ADDLconstmodifyidx8, ssa.OpAMD64ADDQconstmodifyidx1, ssa.OpAMD64ADDQconstmodifyidx8,
944
+ ssa.OpAMD64ANDLconstmodifyidx1, ssa.OpAMD64ANDLconstmodifyidx4, ssa.OpAMD64ANDLconstmodifyidx8, ssa.OpAMD64ANDQconstmodifyidx1, ssa.OpAMD64ANDQconstmodifyidx8,
945
+ ssa.OpAMD64ORLconstmodifyidx1, ssa.OpAMD64ORLconstmodifyidx4, ssa.OpAMD64ORLconstmodifyidx8, ssa.OpAMD64ORQconstmodifyidx1, ssa.OpAMD64ORQconstmodifyidx8,
946
+ ssa.OpAMD64XORLconstmodifyidx1, ssa.OpAMD64XORLconstmodifyidx4, ssa.OpAMD64XORLconstmodifyidx8, ssa.OpAMD64XORQconstmodifyidx1, ssa.OpAMD64XORQconstmodifyidx8:
947
+ p := s.Prog(v.Op.Asm())
948
+ p.From.Type = obj.TYPE_CONST
949
+ sc := v.AuxValAndOff()
950
+ p.From.Offset = sc.Val64()
951
+ switch {
952
+ case p.As == x86.AADDQ && p.From.Offset == 1:
953
+ p.As = x86.AINCQ
954
+ p.From.Type = obj.TYPE_NONE
955
+ case p.As == x86.AADDQ && p.From.Offset == -1:
956
+ p.As = x86.ADECQ
957
+ p.From.Type = obj.TYPE_NONE
958
+ case p.As == x86.AADDL && p.From.Offset == 1:
959
+ p.As = x86.AINCL
960
+ p.From.Type = obj.TYPE_NONE
961
+ case p.As == x86.AADDL && p.From.Offset == -1:
962
+ p.As = x86.ADECL
963
+ p.From.Type = obj.TYPE_NONE
964
+ }
965
+ memIdx(&p.To, v)
966
+ ssagen.AddAux2(&p.To, v, sc.Off64())
967
+ case ssa.OpAMD64MOVLQSX, ssa.OpAMD64MOVWQSX, ssa.OpAMD64MOVBQSX, ssa.OpAMD64MOVLQZX, ssa.OpAMD64MOVWQZX, ssa.OpAMD64MOVBQZX,
968
+ ssa.OpAMD64CVTTSS2SL, ssa.OpAMD64CVTTSD2SL, ssa.OpAMD64CVTTSS2SQ, ssa.OpAMD64CVTTSD2SQ,
969
+ ssa.OpAMD64CVTSS2SD, ssa.OpAMD64CVTSD2SS, ssa.OpAMD64VPBROADCASTB, ssa.OpAMD64PMOVMSKB:
970
+ opregreg(s, v.Op.Asm(), v.Reg(), v.Args[0].Reg())
971
+ case ssa.OpAMD64CVTSL2SD, ssa.OpAMD64CVTSQ2SD, ssa.OpAMD64CVTSQ2SS, ssa.OpAMD64CVTSL2SS:
972
+ r := v.Reg()
973
+ // Break false dependency on destination register.
974
+ opregreg(s, x86.AXORPS, r, r)
975
+ opregreg(s, v.Op.Asm(), r, v.Args[0].Reg())
976
+ case ssa.OpAMD64MOVQi2f, ssa.OpAMD64MOVQf2i, ssa.OpAMD64MOVLi2f, ssa.OpAMD64MOVLf2i:
977
+ var p *obj.Prog
978
+ switch v.Op {
979
+ case ssa.OpAMD64MOVQi2f, ssa.OpAMD64MOVQf2i:
980
+ p = s.Prog(x86.AMOVQ)
981
+ case ssa.OpAMD64MOVLi2f, ssa.OpAMD64MOVLf2i:
982
+ p = s.Prog(x86.AMOVL)
983
+ }
984
+ p.From.Type = obj.TYPE_REG
985
+ p.From.Reg = v.Args[0].Reg()
986
+ p.To.Type = obj.TYPE_REG
987
+ p.To.Reg = v.Reg()
988
+ case ssa.OpAMD64ADDQload, ssa.OpAMD64ADDLload, ssa.OpAMD64SUBQload, ssa.OpAMD64SUBLload,
989
+ ssa.OpAMD64ANDQload, ssa.OpAMD64ANDLload, ssa.OpAMD64ORQload, ssa.OpAMD64ORLload,
990
+ ssa.OpAMD64XORQload, ssa.OpAMD64XORLload, ssa.OpAMD64ADDSDload, ssa.OpAMD64ADDSSload,
991
+ ssa.OpAMD64SUBSDload, ssa.OpAMD64SUBSSload, ssa.OpAMD64MULSDload, ssa.OpAMD64MULSSload,
992
+ ssa.OpAMD64DIVSDload, ssa.OpAMD64DIVSSload:
993
+ p := s.Prog(v.Op.Asm())
994
+ p.From.Type = obj.TYPE_MEM
995
+ p.From.Reg = v.Args[1].Reg()
996
+ ssagen.AddAux(&p.From, v)
997
+ p.To.Type = obj.TYPE_REG
998
+ p.To.Reg = v.Reg()
999
+ case ssa.OpAMD64ADDLloadidx1, ssa.OpAMD64ADDLloadidx4, ssa.OpAMD64ADDLloadidx8, ssa.OpAMD64ADDQloadidx1, ssa.OpAMD64ADDQloadidx8,
1000
+ ssa.OpAMD64SUBLloadidx1, ssa.OpAMD64SUBLloadidx4, ssa.OpAMD64SUBLloadidx8, ssa.OpAMD64SUBQloadidx1, ssa.OpAMD64SUBQloadidx8,
1001
+ ssa.OpAMD64ANDLloadidx1, ssa.OpAMD64ANDLloadidx4, ssa.OpAMD64ANDLloadidx8, ssa.OpAMD64ANDQloadidx1, ssa.OpAMD64ANDQloadidx8,
1002
+ ssa.OpAMD64ORLloadidx1, ssa.OpAMD64ORLloadidx4, ssa.OpAMD64ORLloadidx8, ssa.OpAMD64ORQloadidx1, ssa.OpAMD64ORQloadidx8,
1003
+ ssa.OpAMD64XORLloadidx1, ssa.OpAMD64XORLloadidx4, ssa.OpAMD64XORLloadidx8, ssa.OpAMD64XORQloadidx1, ssa.OpAMD64XORQloadidx8,
1004
+ ssa.OpAMD64ADDSSloadidx1, ssa.OpAMD64ADDSSloadidx4, ssa.OpAMD64ADDSDloadidx1, ssa.OpAMD64ADDSDloadidx8,
1005
+ ssa.OpAMD64SUBSSloadidx1, ssa.OpAMD64SUBSSloadidx4, ssa.OpAMD64SUBSDloadidx1, ssa.OpAMD64SUBSDloadidx8,
1006
+ ssa.OpAMD64MULSSloadidx1, ssa.OpAMD64MULSSloadidx4, ssa.OpAMD64MULSDloadidx1, ssa.OpAMD64MULSDloadidx8,
1007
+ ssa.OpAMD64DIVSSloadidx1, ssa.OpAMD64DIVSSloadidx4, ssa.OpAMD64DIVSDloadidx1, ssa.OpAMD64DIVSDloadidx8:
1008
+ p := s.Prog(v.Op.Asm())
1009
+
1010
+ r, i := v.Args[1].Reg(), v.Args[2].Reg()
1011
+ p.From.Type = obj.TYPE_MEM
1012
+ p.From.Scale = v.Op.Scale()
1013
+ if p.From.Scale == 1 && i == x86.REG_SP {
1014
+ r, i = i, r
1015
+ }
1016
+ p.From.Reg = r
1017
+ p.From.Index = i
1018
+
1019
+ ssagen.AddAux(&p.From, v)
1020
+ p.To.Type = obj.TYPE_REG
1021
+ p.To.Reg = v.Reg()
1022
+
1023
+ case ssa.OpAMD64LoweredZero:
1024
+ if s.ABI != obj.ABIInternal {
1025
+ // zero X15 manually
1026
+ opregreg(s, x86.AXORPS, x86.REG_X15, x86.REG_X15)
1027
+ }
1028
+ ptrReg := v.Args[0].Reg()
1029
+ n := v.AuxInt
1030
+ if n < 16 {
1031
+ v.Fatalf("Zero too small %d", n)
1032
+ }
1033
+ zero16 := func(off int64) {
1034
+ zero16(s, ptrReg, off)
1035
+ }
1036
+
1037
+ // Generate zeroing instructions.
1038
+ var off int64
1039
+ for n >= 16 {
1040
+ zero16(off)
1041
+ off += 16
1042
+ n -= 16
1043
+ }
1044
+ if n != 0 {
1045
+ // use partially overlapped write.
1046
+ // TODO: n <= 8, use smaller write?
1047
+ zero16(off + n - 16)
1048
+ }
1049
+
1050
+ case ssa.OpAMD64LoweredZeroLoop:
1051
+ if s.ABI != obj.ABIInternal {
1052
+ // zero X15 manually
1053
+ opregreg(s, x86.AXORPS, x86.REG_X15, x86.REG_X15)
1054
+ }
1055
+ ptrReg := v.Args[0].Reg()
1056
+ countReg := v.RegTmp()
1057
+ n := v.AuxInt
1058
+ loopSize := int64(64)
1059
+ if n < 3*loopSize {
1060
+ // - a loop count of 0 won't work.
1061
+ // - a loop count of 1 is useless.
1062
+ // - a loop count of 2 is a code size ~tie
1063
+ // 4 instructions to implement the loop
1064
+ // 4 instructions in the loop body
1065
+ // vs
1066
+ // 8 instructions in the straightline code
1067
+ // Might as well use straightline code.
1068
+ v.Fatalf("ZeroLoop size too small %d", n)
1069
+ }
1070
+ zero16 := func(off int64) {
1071
+ zero16(s, ptrReg, off)
1072
+ }
1073
+
1074
+ // Put iteration count in a register.
1075
+ // MOVL $n, countReg
1076
+ p := s.Prog(x86.AMOVL)
1077
+ p.From.Type = obj.TYPE_CONST
1078
+ p.From.Offset = n / loopSize
1079
+ p.To.Type = obj.TYPE_REG
1080
+ p.To.Reg = countReg
1081
+ cntInit := p
1082
+
1083
+ // Zero loopSize bytes starting at ptrReg.
1084
+ for i := range loopSize / 16 {
1085
+ zero16(i * 16)
1086
+ }
1087
+ // ADDQ $loopSize, ptrReg
1088
+ p = s.Prog(x86.AADDQ)
1089
+ p.From.Type = obj.TYPE_CONST
1090
+ p.From.Offset = loopSize
1091
+ p.To.Type = obj.TYPE_REG
1092
+ p.To.Reg = ptrReg
1093
+ // DECL countReg
1094
+ p = s.Prog(x86.ADECL)
1095
+ p.To.Type = obj.TYPE_REG
1096
+ p.To.Reg = countReg
1097
+ // Jump to first instruction in loop if we're not done yet.
1098
+ // JNE head
1099
+ p = s.Prog(x86.AJNE)
1100
+ p.To.Type = obj.TYPE_BRANCH
1101
+ p.To.SetTarget(cntInit.Link)
1102
+
1103
+ // Multiples of the loop size are now done.
1104
+ n %= loopSize
1105
+
1106
+ // Write any fractional portion.
1107
+ var off int64
1108
+ for n >= 16 {
1109
+ zero16(off)
1110
+ off += 16
1111
+ n -= 16
1112
+ }
1113
+ if n != 0 {
1114
+ // Use partially-overlapping write.
1115
+ // TODO: n <= 8, use smaller write?
1116
+ zero16(off + n - 16)
1117
+ }
1118
+
1119
+ case ssa.OpAMD64LoweredMove:
1120
+ dstReg := v.Args[0].Reg()
1121
+ srcReg := v.Args[1].Reg()
1122
+ if dstReg == srcReg {
1123
+ break
1124
+ }
1125
+ tmpReg := int16(x86.REG_X14)
1126
+ n := v.AuxInt
1127
+ if n < 16 {
1128
+ v.Fatalf("Move too small %d", n)
1129
+ }
1130
+ // move 16 bytes from srcReg+off to dstReg+off.
1131
+ move16 := func(off int64) {
1132
+ move16(s, srcReg, dstReg, tmpReg, off)
1133
+ }
1134
+
1135
+ // Generate copying instructions.
1136
+ var off int64
1137
+ for n >= 16 {
1138
+ move16(off)
1139
+ off += 16
1140
+ n -= 16
1141
+ }
1142
+ if n != 0 {
1143
+ // use partially overlapped read/write.
1144
+ // TODO: use smaller operations when we can?
1145
+ move16(off + n - 16)
1146
+ }
1147
+
1148
+ case ssa.OpAMD64LoweredMoveLoop:
1149
+ dstReg := v.Args[0].Reg()
1150
+ srcReg := v.Args[1].Reg()
1151
+ if dstReg == srcReg {
1152
+ break
1153
+ }
1154
+ countReg := v.RegTmp()
1155
+ tmpReg := int16(x86.REG_X14)
1156
+ n := v.AuxInt
1157
+ loopSize := int64(64)
1158
+ if n < 3*loopSize {
1159
+ // - a loop count of 0 won't work.
1160
+ // - a loop count of 1 is useless.
1161
+ // - a loop count of 2 is a code size ~tie
1162
+ // 4 instructions to implement the loop
1163
+ // 4 instructions in the loop body
1164
+ // vs
1165
+ // 8 instructions in the straightline code
1166
+ // Might as well use straightline code.
1167
+ v.Fatalf("ZeroLoop size too small %d", n)
1168
+ }
1169
+ // move 16 bytes from srcReg+off to dstReg+off.
1170
+ move16 := func(off int64) {
1171
+ move16(s, srcReg, dstReg, tmpReg, off)
1172
+ }
1173
+
1174
+ // Put iteration count in a register.
1175
+ // MOVL $n, countReg
1176
+ p := s.Prog(x86.AMOVL)
1177
+ p.From.Type = obj.TYPE_CONST
1178
+ p.From.Offset = n / loopSize
1179
+ p.To.Type = obj.TYPE_REG
1180
+ p.To.Reg = countReg
1181
+ cntInit := p
1182
+
1183
+ // Copy loopSize bytes starting at srcReg to dstReg.
1184
+ for i := range loopSize / 16 {
1185
+ move16(i * 16)
1186
+ }
1187
+ // ADDQ $loopSize, srcReg
1188
+ p = s.Prog(x86.AADDQ)
1189
+ p.From.Type = obj.TYPE_CONST
1190
+ p.From.Offset = loopSize
1191
+ p.To.Type = obj.TYPE_REG
1192
+ p.To.Reg = srcReg
1193
+ // ADDQ $loopSize, dstReg
1194
+ p = s.Prog(x86.AADDQ)
1195
+ p.From.Type = obj.TYPE_CONST
1196
+ p.From.Offset = loopSize
1197
+ p.To.Type = obj.TYPE_REG
1198
+ p.To.Reg = dstReg
1199
+ // DECL countReg
1200
+ p = s.Prog(x86.ADECL)
1201
+ p.To.Type = obj.TYPE_REG
1202
+ p.To.Reg = countReg
1203
+ // Jump to loop header if we're not done yet.
1204
+ // JNE head
1205
+ p = s.Prog(x86.AJNE)
1206
+ p.To.Type = obj.TYPE_BRANCH
1207
+ p.To.SetTarget(cntInit.Link)
1208
+
1209
+ // Multiples of the loop size are now done.
1210
+ n %= loopSize
1211
+
1212
+ // Copy any fractional portion.
1213
+ var off int64
1214
+ for n >= 16 {
1215
+ move16(off)
1216
+ off += 16
1217
+ n -= 16
1218
+ }
1219
+ if n != 0 {
1220
+ // Use partially-overlapping copy.
1221
+ move16(off + n - 16)
1222
+ }
1223
+
1224
+ case ssa.OpCopy: // TODO: use MOVQreg for reg->reg copies instead of OpCopy?
1225
+ if v.Type.IsMemory() {
1226
+ return
1227
+ }
1228
+ x := v.Args[0].Reg()
1229
+ y := v.Reg()
1230
+ if v.Type.IsSIMD() {
1231
+ x = simdOrMaskReg(v.Args[0])
1232
+ y = simdOrMaskReg(v)
1233
+ }
1234
+ if x != y {
1235
+ opregreg(s, moveByRegsWidth(y, x, v.Type.Size()), y, x)
1236
+ }
1237
+ case ssa.OpLoadReg:
1238
+ if v.Type.IsFlags() {
1239
+ v.Fatalf("load flags not implemented: %v", v.LongString())
1240
+ return
1241
+ }
1242
+ r := v.Reg()
1243
+ p := s.Prog(loadByRegWidth(r, v.Type.Size()))
1244
+ ssagen.AddrAuto(&p.From, v.Args[0])
1245
+ p.To.Type = obj.TYPE_REG
1246
+ if v.Type.IsSIMD() {
1247
+ r = simdOrMaskReg(v)
1248
+ }
1249
+ p.To.Reg = r
1250
+
1251
+ case ssa.OpStoreReg:
1252
+ if v.Type.IsFlags() {
1253
+ v.Fatalf("store flags not implemented: %v", v.LongString())
1254
+ return
1255
+ }
1256
+ r := v.Args[0].Reg()
1257
+ if v.Type.IsSIMD() {
1258
+ r = simdOrMaskReg(v.Args[0])
1259
+ }
1260
+ p := s.Prog(storeByRegWidth(r, v.Type.Size()))
1261
+ p.From.Type = obj.TYPE_REG
1262
+ p.From.Reg = r
1263
+ ssagen.AddrAuto(&p.To, v)
1264
+ case ssa.OpAMD64LoweredHasCPUFeature:
1265
+ p := s.Prog(x86.AMOVBLZX)
1266
+ p.From.Type = obj.TYPE_MEM
1267
+ ssagen.AddAux(&p.From, v)
1268
+ p.To.Type = obj.TYPE_REG
1269
+ p.To.Reg = v.Reg()
1270
+ case ssa.OpArgIntReg, ssa.OpArgFloatReg:
1271
+ // The assembler needs to wrap the entry safepoint/stack growth code with spill/unspill
1272
+ // The loop only runs once.
1273
+ for _, ap := range v.Block.Func.RegArgs {
1274
+ // Pass the spill/unspill information along to the assembler, offset by size of return PC pushed on stack.
1275
+ addr := ssagen.SpillSlotAddr(ap, x86.REG_SP, v.Block.Func.Config.PtrSize)
1276
+ reg := ap.Reg
1277
+ t := ap.Type
1278
+ sz := t.Size()
1279
+ if t.IsSIMD() {
1280
+ reg = simdRegBySize(reg, sz)
1281
+ }
1282
+ s.FuncInfo().AddSpill(
1283
+ obj.RegSpill{Reg: reg, Addr: addr, Unspill: loadByRegWidth(reg, sz), Spill: storeByRegWidth(reg, sz)})
1284
+ }
1285
+ v.Block.Func.RegArgs = nil
1286
+ ssagen.CheckArgReg(v)
1287
+ case ssa.OpAMD64LoweredGetClosurePtr:
1288
+ // Closure pointer is DX.
1289
+ ssagen.CheckLoweredGetClosurePtr(v)
1290
+ case ssa.OpAMD64LoweredGetG:
1291
+ if s.ABI == obj.ABIInternal {
1292
+ v.Fatalf("LoweredGetG should not appear in ABIInternal")
1293
+ }
1294
+ r := v.Reg()
1295
+ getgFromTLS(s, r)
1296
+ case ssa.OpAMD64CALLstatic, ssa.OpAMD64CALLtail:
1297
+ if s.ABI == obj.ABI0 && v.Aux.(*ssa.AuxCall).Fn.ABI() == obj.ABIInternal {
1298
+ // zeroing X15 when entering ABIInternal from ABI0
1299
+ zeroX15(s)
1300
+ // set G register from TLS
1301
+ getgFromTLS(s, x86.REG_R14)
1302
+ }
1303
+ if v.Op == ssa.OpAMD64CALLtail {
1304
+ s.TailCall(v)
1305
+ break
1306
+ }
1307
+ s.Call(v)
1308
+ if s.ABI == obj.ABIInternal && v.Aux.(*ssa.AuxCall).Fn.ABI() == obj.ABI0 {
1309
+ // zeroing X15 when entering ABIInternal from ABI0
1310
+ zeroX15(s)
1311
+ // set G register from TLS
1312
+ getgFromTLS(s, x86.REG_R14)
1313
+ }
1314
+ case ssa.OpAMD64CALLclosure, ssa.OpAMD64CALLinter:
1315
+ s.Call(v)
1316
+
1317
+ case ssa.OpAMD64LoweredGetCallerPC:
1318
+ p := s.Prog(x86.AMOVQ)
1319
+ p.From.Type = obj.TYPE_MEM
1320
+ p.From.Offset = -8 // PC is stored 8 bytes below first parameter.
1321
+ p.From.Name = obj.NAME_PARAM
1322
+ p.To.Type = obj.TYPE_REG
1323
+ p.To.Reg = v.Reg()
1324
+
1325
+ case ssa.OpAMD64LoweredGetCallerSP:
1326
+ // caller's SP is the address of the first arg
1327
+ mov := x86.AMOVQ
1328
+ if types.PtrSize == 4 {
1329
+ mov = x86.AMOVL
1330
+ }
1331
+ p := s.Prog(mov)
1332
+ p.From.Type = obj.TYPE_ADDR
1333
+ p.From.Offset = -base.Ctxt.Arch.FixedFrameSize // 0 on amd64, just to be consistent with other architectures
1334
+ p.From.Name = obj.NAME_PARAM
1335
+ p.To.Type = obj.TYPE_REG
1336
+ p.To.Reg = v.Reg()
1337
+
1338
+ case ssa.OpAMD64LoweredWB:
1339
+ p := s.Prog(obj.ACALL)
1340
+ p.To.Type = obj.TYPE_MEM
1341
+ p.To.Name = obj.NAME_EXTERN
1342
+ // AuxInt encodes how many buffer entries we need.
1343
+ p.To.Sym = ir.Syms.GCWriteBarrier[v.AuxInt-1]
1344
+
1345
+ case ssa.OpAMD64LoweredPanicBoundsRR, ssa.OpAMD64LoweredPanicBoundsRC, ssa.OpAMD64LoweredPanicBoundsCR, ssa.OpAMD64LoweredPanicBoundsCC:
1346
+ // Compute the constant we put in the PCData entry for this call.
1347
+ code, signed := ssa.BoundsKind(v.AuxInt).Code()
1348
+ xIsReg := false
1349
+ yIsReg := false
1350
+ xVal := 0
1351
+ yVal := 0
1352
+ switch v.Op {
1353
+ case ssa.OpAMD64LoweredPanicBoundsRR:
1354
+ xIsReg = true
1355
+ xVal = int(v.Args[0].Reg() - x86.REG_AX)
1356
+ yIsReg = true
1357
+ yVal = int(v.Args[1].Reg() - x86.REG_AX)
1358
+ case ssa.OpAMD64LoweredPanicBoundsRC:
1359
+ xIsReg = true
1360
+ xVal = int(v.Args[0].Reg() - x86.REG_AX)
1361
+ c := v.Aux.(ssa.PanicBoundsC).C
1362
+ if c >= 0 && c <= abi.BoundsMaxConst {
1363
+ yVal = int(c)
1364
+ } else {
1365
+ // Move constant to a register
1366
+ yIsReg = true
1367
+ if yVal == xVal {
1368
+ yVal = 1
1369
+ }
1370
+ p := s.Prog(x86.AMOVQ)
1371
+ p.From.Type = obj.TYPE_CONST
1372
+ p.From.Offset = c
1373
+ p.To.Type = obj.TYPE_REG
1374
+ p.To.Reg = x86.REG_AX + int16(yVal)
1375
+ }
1376
+ case ssa.OpAMD64LoweredPanicBoundsCR:
1377
+ yIsReg = true
1378
+ yVal = int(v.Args[0].Reg() - x86.REG_AX)
1379
+ c := v.Aux.(ssa.PanicBoundsC).C
1380
+ if c >= 0 && c <= abi.BoundsMaxConst {
1381
+ xVal = int(c)
1382
+ } else {
1383
+ // Move constant to a register
1384
+ xIsReg = true
1385
+ if xVal == yVal {
1386
+ xVal = 1
1387
+ }
1388
+ p := s.Prog(x86.AMOVQ)
1389
+ p.From.Type = obj.TYPE_CONST
1390
+ p.From.Offset = c
1391
+ p.To.Type = obj.TYPE_REG
1392
+ p.To.Reg = x86.REG_AX + int16(xVal)
1393
+ }
1394
+ case ssa.OpAMD64LoweredPanicBoundsCC:
1395
+ c := v.Aux.(ssa.PanicBoundsCC).Cx
1396
+ if c >= 0 && c <= abi.BoundsMaxConst {
1397
+ xVal = int(c)
1398
+ } else {
1399
+ // Move constant to a register
1400
+ xIsReg = true
1401
+ p := s.Prog(x86.AMOVQ)
1402
+ p.From.Type = obj.TYPE_CONST
1403
+ p.From.Offset = c
1404
+ p.To.Type = obj.TYPE_REG
1405
+ p.To.Reg = x86.REG_AX + int16(xVal)
1406
+ }
1407
+ c = v.Aux.(ssa.PanicBoundsCC).Cy
1408
+ if c >= 0 && c <= abi.BoundsMaxConst {
1409
+ yVal = int(c)
1410
+ } else {
1411
+ // Move constant to a register
1412
+ yIsReg = true
1413
+ yVal = 1
1414
+ p := s.Prog(x86.AMOVQ)
1415
+ p.From.Type = obj.TYPE_CONST
1416
+ p.From.Offset = c
1417
+ p.To.Type = obj.TYPE_REG
1418
+ p.To.Reg = x86.REG_AX + int16(yVal)
1419
+ }
1420
+ }
1421
+ c := abi.BoundsEncode(code, signed, xIsReg, yIsReg, xVal, yVal)
1422
+
1423
+ p := s.Prog(obj.APCDATA)
1424
+ p.From.SetConst(abi.PCDATA_PanicBounds)
1425
+ p.To.SetConst(int64(c))
1426
+ p = s.Prog(obj.ACALL)
1427
+ p.To.Type = obj.TYPE_MEM
1428
+ p.To.Name = obj.NAME_EXTERN
1429
+ p.To.Sym = ir.Syms.PanicBounds
1430
+
1431
+ case ssa.OpAMD64NEGQ, ssa.OpAMD64NEGL,
1432
+ ssa.OpAMD64BSWAPQ, ssa.OpAMD64BSWAPL,
1433
+ ssa.OpAMD64NOTQ, ssa.OpAMD64NOTL:
1434
+ p := s.Prog(v.Op.Asm())
1435
+ p.To.Type = obj.TYPE_REG
1436
+ p.To.Reg = v.Reg()
1437
+
1438
+ case ssa.OpAMD64NEGLflags:
1439
+ p := s.Prog(v.Op.Asm())
1440
+ p.To.Type = obj.TYPE_REG
1441
+ p.To.Reg = v.Reg0()
1442
+
1443
+ case ssa.OpAMD64ADDQconstflags, ssa.OpAMD64ADDLconstflags:
1444
+ p := s.Prog(v.Op.Asm())
1445
+ p.From.Type = obj.TYPE_CONST
1446
+ p.From.Offset = v.AuxInt
1447
+ // Note: the inc/dec instructions do not modify
1448
+ // the carry flag like add$1 / sub$1 do.
1449
+ // We currently never use the CF/OF flags from
1450
+ // these instructions, so that is ok.
1451
+ switch {
1452
+ case p.As == x86.AADDQ && p.From.Offset == 1:
1453
+ p.As = x86.AINCQ
1454
+ p.From.Type = obj.TYPE_NONE
1455
+ case p.As == x86.AADDQ && p.From.Offset == -1:
1456
+ p.As = x86.ADECQ
1457
+ p.From.Type = obj.TYPE_NONE
1458
+ case p.As == x86.AADDL && p.From.Offset == 1:
1459
+ p.As = x86.AINCL
1460
+ p.From.Type = obj.TYPE_NONE
1461
+ case p.As == x86.AADDL && p.From.Offset == -1:
1462
+ p.As = x86.ADECL
1463
+ p.From.Type = obj.TYPE_NONE
1464
+ }
1465
+ p.To.Type = obj.TYPE_REG
1466
+ p.To.Reg = v.Reg0()
1467
+
1468
+ case ssa.OpAMD64BSFQ, ssa.OpAMD64BSRQ, ssa.OpAMD64BSFL, ssa.OpAMD64BSRL, ssa.OpAMD64SQRTSD, ssa.OpAMD64SQRTSS:
1469
+ p := s.Prog(v.Op.Asm())
1470
+ p.From.Type = obj.TYPE_REG
1471
+ p.From.Reg = v.Args[0].Reg()
1472
+ p.To.Type = obj.TYPE_REG
1473
+ switch v.Op {
1474
+ case ssa.OpAMD64BSFQ, ssa.OpAMD64BSRQ:
1475
+ p.To.Reg = v.Reg0()
1476
+ case ssa.OpAMD64BSFL, ssa.OpAMD64BSRL, ssa.OpAMD64SQRTSD, ssa.OpAMD64SQRTSS:
1477
+ p.To.Reg = v.Reg()
1478
+ }
1479
+ case ssa.OpAMD64LoweredRound32F, ssa.OpAMD64LoweredRound64F:
1480
+ // input is already rounded
1481
+ case ssa.OpAMD64ROUNDSD:
1482
+ p := s.Prog(v.Op.Asm())
1483
+ val := v.AuxInt
1484
+ // 0 means math.RoundToEven, 1 Floor, 2 Ceil, 3 Trunc
1485
+ if val < 0 || val > 3 {
1486
+ v.Fatalf("Invalid rounding mode")
1487
+ }
1488
+ p.From.Offset = val
1489
+ p.From.Type = obj.TYPE_CONST
1490
+ p.AddRestSourceReg(v.Args[0].Reg())
1491
+ p.To.Type = obj.TYPE_REG
1492
+ p.To.Reg = v.Reg()
1493
+ case ssa.OpAMD64POPCNTQ, ssa.OpAMD64POPCNTL,
1494
+ ssa.OpAMD64TZCNTQ, ssa.OpAMD64TZCNTL,
1495
+ ssa.OpAMD64LZCNTQ, ssa.OpAMD64LZCNTL:
1496
+ if v.Args[0].Reg() != v.Reg() {
1497
+ // POPCNT/TZCNT/LZCNT have a false dependency on the destination register on Intel cpus.
1498
+ // TZCNT/LZCNT problem affects pre-Skylake models. See discussion at https://gcc.gnu.org/bugzilla/show_bug.cgi?id=62011#c7.
1499
+ // Xor register with itself to break the dependency.
1500
+ opregreg(s, x86.AXORL, v.Reg(), v.Reg())
1501
+ }
1502
+ p := s.Prog(v.Op.Asm())
1503
+ p.From.Type = obj.TYPE_REG
1504
+ p.From.Reg = v.Args[0].Reg()
1505
+ p.To.Type = obj.TYPE_REG
1506
+ p.To.Reg = v.Reg()
1507
+
1508
+ case ssa.OpAMD64SETEQ, ssa.OpAMD64SETNE,
1509
+ ssa.OpAMD64SETL, ssa.OpAMD64SETLE,
1510
+ ssa.OpAMD64SETG, ssa.OpAMD64SETGE,
1511
+ ssa.OpAMD64SETGF, ssa.OpAMD64SETGEF,
1512
+ ssa.OpAMD64SETB, ssa.OpAMD64SETBE,
1513
+ ssa.OpAMD64SETORD, ssa.OpAMD64SETNAN,
1514
+ ssa.OpAMD64SETA, ssa.OpAMD64SETAE,
1515
+ ssa.OpAMD64SETO:
1516
+ p := s.Prog(v.Op.Asm())
1517
+ p.To.Type = obj.TYPE_REG
1518
+ p.To.Reg = v.Reg()
1519
+
1520
+ case ssa.OpAMD64SETEQstore, ssa.OpAMD64SETNEstore,
1521
+ ssa.OpAMD64SETLstore, ssa.OpAMD64SETLEstore,
1522
+ ssa.OpAMD64SETGstore, ssa.OpAMD64SETGEstore,
1523
+ ssa.OpAMD64SETBstore, ssa.OpAMD64SETBEstore,
1524
+ ssa.OpAMD64SETAstore, ssa.OpAMD64SETAEstore:
1525
+ p := s.Prog(v.Op.Asm())
1526
+ p.To.Type = obj.TYPE_MEM
1527
+ p.To.Reg = v.Args[0].Reg()
1528
+ ssagen.AddAux(&p.To, v)
1529
+
1530
+ case ssa.OpAMD64SETEQstoreidx1, ssa.OpAMD64SETNEstoreidx1,
1531
+ ssa.OpAMD64SETLstoreidx1, ssa.OpAMD64SETLEstoreidx1,
1532
+ ssa.OpAMD64SETGstoreidx1, ssa.OpAMD64SETGEstoreidx1,
1533
+ ssa.OpAMD64SETBstoreidx1, ssa.OpAMD64SETBEstoreidx1,
1534
+ ssa.OpAMD64SETAstoreidx1, ssa.OpAMD64SETAEstoreidx1:
1535
+ p := s.Prog(v.Op.Asm())
1536
+ memIdx(&p.To, v)
1537
+ ssagen.AddAux(&p.To, v)
1538
+
1539
+ case ssa.OpAMD64SETNEF:
1540
+ t := v.RegTmp()
1541
+ p := s.Prog(v.Op.Asm())
1542
+ p.To.Type = obj.TYPE_REG
1543
+ p.To.Reg = v.Reg()
1544
+ q := s.Prog(x86.ASETPS)
1545
+ q.To.Type = obj.TYPE_REG
1546
+ q.To.Reg = t
1547
+ // ORL avoids partial register write and is smaller than ORQ, used by old compiler
1548
+ opregreg(s, x86.AORL, v.Reg(), t)
1549
+
1550
+ case ssa.OpAMD64SETEQF:
1551
+ t := v.RegTmp()
1552
+ p := s.Prog(v.Op.Asm())
1553
+ p.To.Type = obj.TYPE_REG
1554
+ p.To.Reg = v.Reg()
1555
+ q := s.Prog(x86.ASETPC)
1556
+ q.To.Type = obj.TYPE_REG
1557
+ q.To.Reg = t
1558
+ // ANDL avoids partial register write and is smaller than ANDQ, used by old compiler
1559
+ opregreg(s, x86.AANDL, v.Reg(), t)
1560
+
1561
+ case ssa.OpAMD64InvertFlags:
1562
+ v.Fatalf("InvertFlags should never make it to codegen %v", v.LongString())
1563
+ case ssa.OpAMD64FlagEQ, ssa.OpAMD64FlagLT_ULT, ssa.OpAMD64FlagLT_UGT, ssa.OpAMD64FlagGT_ULT, ssa.OpAMD64FlagGT_UGT:
1564
+ v.Fatalf("Flag* ops should never make it to codegen %v", v.LongString())
1565
+ case ssa.OpAMD64AddTupleFirst32, ssa.OpAMD64AddTupleFirst64:
1566
+ v.Fatalf("AddTupleFirst* should never make it to codegen %v", v.LongString())
1567
+ case ssa.OpAMD64REPSTOSQ:
1568
+ s.Prog(x86.AREP)
1569
+ s.Prog(x86.ASTOSQ)
1570
+ case ssa.OpAMD64REPMOVSQ:
1571
+ s.Prog(x86.AREP)
1572
+ s.Prog(x86.AMOVSQ)
1573
+ case ssa.OpAMD64LoweredNilCheck:
1574
+ // Issue a load which will fault if the input is nil.
1575
+ // TODO: We currently use the 2-byte instruction TESTB AX, (reg).
1576
+ // Should we use the 3-byte TESTB $0, (reg) instead? It is larger
1577
+ // but it doesn't have false dependency on AX.
1578
+ // Or maybe allocate an output register and use MOVL (reg),reg2 ?
1579
+ // That trades clobbering flags for clobbering a register.
1580
+ p := s.Prog(x86.ATESTB)
1581
+ p.From.Type = obj.TYPE_REG
1582
+ p.From.Reg = x86.REG_AX
1583
+ p.To.Type = obj.TYPE_MEM
1584
+ p.To.Reg = v.Args[0].Reg()
1585
+ if logopt.Enabled() {
1586
+ logopt.LogOpt(v.Pos, "nilcheck", "genssa", v.Block.Func.Name)
1587
+ }
1588
+ if base.Debug.Nil != 0 && v.Pos.Line() > 1 { // v.Pos.Line()==1 in generated wrappers
1589
+ base.WarnfAt(v.Pos, "generated nil check")
1590
+ }
1591
+ case ssa.OpAMD64MOVBatomicload, ssa.OpAMD64MOVLatomicload, ssa.OpAMD64MOVQatomicload:
1592
+ p := s.Prog(v.Op.Asm())
1593
+ p.From.Type = obj.TYPE_MEM
1594
+ p.From.Reg = v.Args[0].Reg()
1595
+ ssagen.AddAux(&p.From, v)
1596
+ p.To.Type = obj.TYPE_REG
1597
+ p.To.Reg = v.Reg0()
1598
+ case ssa.OpAMD64XCHGB, ssa.OpAMD64XCHGL, ssa.OpAMD64XCHGQ:
1599
+ p := s.Prog(v.Op.Asm())
1600
+ p.From.Type = obj.TYPE_REG
1601
+ p.From.Reg = v.Reg0()
1602
+ p.To.Type = obj.TYPE_MEM
1603
+ p.To.Reg = v.Args[1].Reg()
1604
+ ssagen.AddAux(&p.To, v)
1605
+ case ssa.OpAMD64XADDLlock, ssa.OpAMD64XADDQlock:
1606
+ s.Prog(x86.ALOCK)
1607
+ p := s.Prog(v.Op.Asm())
1608
+ p.From.Type = obj.TYPE_REG
1609
+ p.From.Reg = v.Reg0()
1610
+ p.To.Type = obj.TYPE_MEM
1611
+ p.To.Reg = v.Args[1].Reg()
1612
+ ssagen.AddAux(&p.To, v)
1613
+ case ssa.OpAMD64CMPXCHGLlock, ssa.OpAMD64CMPXCHGQlock:
1614
+ if v.Args[1].Reg() != x86.REG_AX {
1615
+ v.Fatalf("input[1] not in AX %s", v.LongString())
1616
+ }
1617
+ s.Prog(x86.ALOCK)
1618
+ p := s.Prog(v.Op.Asm())
1619
+ p.From.Type = obj.TYPE_REG
1620
+ p.From.Reg = v.Args[2].Reg()
1621
+ p.To.Type = obj.TYPE_MEM
1622
+ p.To.Reg = v.Args[0].Reg()
1623
+ ssagen.AddAux(&p.To, v)
1624
+ p = s.Prog(x86.ASETEQ)
1625
+ p.To.Type = obj.TYPE_REG
1626
+ p.To.Reg = v.Reg0()
1627
+ case ssa.OpAMD64ANDBlock, ssa.OpAMD64ANDLlock, ssa.OpAMD64ANDQlock, ssa.OpAMD64ORBlock, ssa.OpAMD64ORLlock, ssa.OpAMD64ORQlock:
1628
+ // Atomic memory operations that don't need to return the old value.
1629
+ s.Prog(x86.ALOCK)
1630
+ p := s.Prog(v.Op.Asm())
1631
+ p.From.Type = obj.TYPE_REG
1632
+ p.From.Reg = v.Args[1].Reg()
1633
+ p.To.Type = obj.TYPE_MEM
1634
+ p.To.Reg = v.Args[0].Reg()
1635
+ ssagen.AddAux(&p.To, v)
1636
+ case ssa.OpAMD64LoweredAtomicAnd64, ssa.OpAMD64LoweredAtomicOr64, ssa.OpAMD64LoweredAtomicAnd32, ssa.OpAMD64LoweredAtomicOr32:
1637
+ // Atomic memory operations that need to return the old value.
1638
+ // We need to do these with compare-and-exchange to get access to the old value.
1639
+ // loop:
1640
+ // MOVQ mask, tmp
1641
+ // MOVQ (addr), AX
1642
+ // ANDQ AX, tmp
1643
+ // LOCK CMPXCHGQ tmp, (addr) : note that AX is implicit old value to compare against
1644
+ // JNE loop
1645
+ // : result in AX
1646
+ mov := x86.AMOVQ
1647
+ op := x86.AANDQ
1648
+ cmpxchg := x86.ACMPXCHGQ
1649
+ switch v.Op {
1650
+ case ssa.OpAMD64LoweredAtomicOr64:
1651
+ op = x86.AORQ
1652
+ case ssa.OpAMD64LoweredAtomicAnd32:
1653
+ mov = x86.AMOVL
1654
+ op = x86.AANDL
1655
+ cmpxchg = x86.ACMPXCHGL
1656
+ case ssa.OpAMD64LoweredAtomicOr32:
1657
+ mov = x86.AMOVL
1658
+ op = x86.AORL
1659
+ cmpxchg = x86.ACMPXCHGL
1660
+ }
1661
+ addr := v.Args[0].Reg()
1662
+ mask := v.Args[1].Reg()
1663
+ tmp := v.RegTmp()
1664
+ p1 := s.Prog(mov)
1665
+ p1.From.Type = obj.TYPE_REG
1666
+ p1.From.Reg = mask
1667
+ p1.To.Type = obj.TYPE_REG
1668
+ p1.To.Reg = tmp
1669
+ p2 := s.Prog(mov)
1670
+ p2.From.Type = obj.TYPE_MEM
1671
+ p2.From.Reg = addr
1672
+ ssagen.AddAux(&p2.From, v)
1673
+ p2.To.Type = obj.TYPE_REG
1674
+ p2.To.Reg = x86.REG_AX
1675
+ p3 := s.Prog(op)
1676
+ p3.From.Type = obj.TYPE_REG
1677
+ p3.From.Reg = x86.REG_AX
1678
+ p3.To.Type = obj.TYPE_REG
1679
+ p3.To.Reg = tmp
1680
+ s.Prog(x86.ALOCK)
1681
+ p5 := s.Prog(cmpxchg)
1682
+ p5.From.Type = obj.TYPE_REG
1683
+ p5.From.Reg = tmp
1684
+ p5.To.Type = obj.TYPE_MEM
1685
+ p5.To.Reg = addr
1686
+ ssagen.AddAux(&p5.To, v)
1687
+ p6 := s.Prog(x86.AJNE)
1688
+ p6.To.Type = obj.TYPE_BRANCH
1689
+ p6.To.SetTarget(p1)
1690
+ case ssa.OpAMD64PrefetchT0, ssa.OpAMD64PrefetchNTA:
1691
+ p := s.Prog(v.Op.Asm())
1692
+ p.From.Type = obj.TYPE_MEM
1693
+ p.From.Reg = v.Args[0].Reg()
1694
+ case ssa.OpClobber:
1695
+ p := s.Prog(x86.AMOVL)
1696
+ p.From.Type = obj.TYPE_CONST
1697
+ p.From.Offset = 0xdeaddead
1698
+ p.To.Type = obj.TYPE_MEM
1699
+ p.To.Reg = x86.REG_SP
1700
+ ssagen.AddAux(&p.To, v)
1701
+ p = s.Prog(x86.AMOVL)
1702
+ p.From.Type = obj.TYPE_CONST
1703
+ p.From.Offset = 0xdeaddead
1704
+ p.To.Type = obj.TYPE_MEM
1705
+ p.To.Reg = x86.REG_SP
1706
+ ssagen.AddAux(&p.To, v)
1707
+ p.To.Offset += 4
1708
+ case ssa.OpClobberReg:
1709
+ x := uint64(0xdeaddeaddeaddead)
1710
+ p := s.Prog(x86.AMOVQ)
1711
+ p.From.Type = obj.TYPE_CONST
1712
+ p.From.Offset = int64(x)
1713
+ p.To.Type = obj.TYPE_REG
1714
+ p.To.Reg = v.Reg()
1715
+
1716
+ // SIMD ops
1717
+ case ssa.OpAMD64VZEROUPPER, ssa.OpAMD64VZEROALL:
1718
+ s.Prog(v.Op.Asm())
1719
+
1720
+ case ssa.OpAMD64Zero128: // no code emitted
1721
+
1722
+ case ssa.OpAMD64Zero256, ssa.OpAMD64Zero512:
1723
+ p := s.Prog(v.Op.Asm())
1724
+ p.From.Type = obj.TYPE_REG
1725
+ p.From.Reg = simdReg(v)
1726
+ p.AddRestSourceReg(simdReg(v))
1727
+ p.To.Type = obj.TYPE_REG
1728
+ p.To.Reg = simdReg(v)
1729
+
1730
+ case ssa.OpAMD64VMOVSSf2v, ssa.OpAMD64VMOVSDf2v:
1731
+ // These are for initializing the least 32/64 bits of a SIMD register from a "float".
1732
+ p := s.Prog(v.Op.Asm())
1733
+ p.From.Type = obj.TYPE_REG
1734
+ p.From.Reg = v.Args[0].Reg()
1735
+ p.AddRestSourceReg(x86.REG_X15)
1736
+ p.To.Type = obj.TYPE_REG
1737
+ p.To.Reg = simdReg(v)
1738
+
1739
+ case ssa.OpAMD64VMOVQload, ssa.OpAMD64VMOVDload,
1740
+ ssa.OpAMD64VMOVSSload, ssa.OpAMD64VMOVSDload:
1741
+ p := s.Prog(v.Op.Asm())
1742
+ p.From.Type = obj.TYPE_MEM
1743
+ p.From.Reg = v.Args[0].Reg()
1744
+ ssagen.AddAux(&p.From, v)
1745
+ p.To.Type = obj.TYPE_REG
1746
+ p.To.Reg = simdReg(v)
1747
+
1748
+ case ssa.OpAMD64VMOVSSconst, ssa.OpAMD64VMOVSDconst:
1749
+ // for loading constants directly into SIMD registers
1750
+ x := simdReg(v)
1751
+ p := s.Prog(v.Op.Asm())
1752
+ p.From.Type = obj.TYPE_FCONST
1753
+ p.From.Val = math.Float64frombits(uint64(v.AuxInt))
1754
+ p.To.Type = obj.TYPE_REG
1755
+ p.To.Reg = x
1756
+
1757
+ case ssa.OpAMD64VMOVD, ssa.OpAMD64VMOVQ:
1758
+ // These are for initializing the least 32/64 bits of a SIMD register from an "int".
1759
+ p := s.Prog(v.Op.Asm())
1760
+ p.From.Type = obj.TYPE_REG
1761
+ p.From.Reg = v.Args[0].Reg()
1762
+ p.To.Type = obj.TYPE_REG
1763
+ p.To.Reg = simdReg(v)
1764
+
1765
+ case ssa.OpAMD64VMOVDQUload128, ssa.OpAMD64VMOVDQUload256, ssa.OpAMD64VMOVDQUload512,
1766
+ ssa.OpAMD64KMOVBload, ssa.OpAMD64KMOVWload, ssa.OpAMD64KMOVDload, ssa.OpAMD64KMOVQload:
1767
+ p := s.Prog(v.Op.Asm())
1768
+ p.From.Type = obj.TYPE_MEM
1769
+ p.From.Reg = v.Args[0].Reg()
1770
+ ssagen.AddAux(&p.From, v)
1771
+ p.To.Type = obj.TYPE_REG
1772
+ p.To.Reg = simdOrMaskReg(v)
1773
+ case ssa.OpAMD64VMOVDQUstore128, ssa.OpAMD64VMOVDQUstore256, ssa.OpAMD64VMOVDQUstore512,
1774
+ ssa.OpAMD64KMOVBstore, ssa.OpAMD64KMOVWstore, ssa.OpAMD64KMOVDstore, ssa.OpAMD64KMOVQstore:
1775
+ p := s.Prog(v.Op.Asm())
1776
+ p.From.Type = obj.TYPE_REG
1777
+ p.From.Reg = simdOrMaskReg(v.Args[1])
1778
+ p.To.Type = obj.TYPE_MEM
1779
+ p.To.Reg = v.Args[0].Reg()
1780
+ ssagen.AddAux(&p.To, v)
1781
+
1782
+ case ssa.OpAMD64VPMASK32load128, ssa.OpAMD64VPMASK64load128, ssa.OpAMD64VPMASK32load256, ssa.OpAMD64VPMASK64load256:
1783
+ p := s.Prog(v.Op.Asm())
1784
+ p.From.Type = obj.TYPE_MEM
1785
+ p.From.Reg = v.Args[0].Reg()
1786
+ ssagen.AddAux(&p.From, v)
1787
+ p.To.Type = obj.TYPE_REG
1788
+ p.To.Reg = simdReg(v)
1789
+ p.AddRestSourceReg(simdReg(v.Args[1])) // masking simd reg
1790
+
1791
+ case ssa.OpAMD64VPMASK32store128, ssa.OpAMD64VPMASK64store128, ssa.OpAMD64VPMASK32store256, ssa.OpAMD64VPMASK64store256:
1792
+ p := s.Prog(v.Op.Asm())
1793
+ p.From.Type = obj.TYPE_REG
1794
+ p.From.Reg = simdReg(v.Args[2])
1795
+ p.To.Type = obj.TYPE_MEM
1796
+ p.To.Reg = v.Args[0].Reg()
1797
+ ssagen.AddAux(&p.To, v)
1798
+ p.AddRestSourceReg(simdReg(v.Args[1])) // masking simd reg
1799
+
1800
+ case ssa.OpAMD64VPMASK64load512, ssa.OpAMD64VPMASK32load512, ssa.OpAMD64VPMASK16load512, ssa.OpAMD64VPMASK8load512:
1801
+ p := s.Prog(v.Op.Asm())
1802
+ p.From.Type = obj.TYPE_MEM
1803
+ p.From.Reg = v.Args[0].Reg()
1804
+ ssagen.AddAux(&p.From, v)
1805
+ p.To.Type = obj.TYPE_REG
1806
+ p.To.Reg = simdReg(v)
1807
+ p.AddRestSourceReg(v.Args[1].Reg()) // simd mask reg
1808
+ x86.ParseSuffix(p, "Z") // must be zero if not in mask
1809
+
1810
+ case ssa.OpAMD64VPMASK64store512, ssa.OpAMD64VPMASK32store512, ssa.OpAMD64VPMASK16store512, ssa.OpAMD64VPMASK8store512:
1811
+ p := s.Prog(v.Op.Asm())
1812
+ p.From.Type = obj.TYPE_REG
1813
+ p.From.Reg = simdReg(v.Args[2])
1814
+ p.To.Type = obj.TYPE_MEM
1815
+ p.To.Reg = v.Args[0].Reg()
1816
+ ssagen.AddAux(&p.To, v)
1817
+ p.AddRestSourceReg(v.Args[1].Reg()) // simd mask reg
1818
+
1819
+ case ssa.OpAMD64VPMOVMToVec8x16,
1820
+ ssa.OpAMD64VPMOVMToVec8x32,
1821
+ ssa.OpAMD64VPMOVMToVec8x64,
1822
+ ssa.OpAMD64VPMOVMToVec16x8,
1823
+ ssa.OpAMD64VPMOVMToVec16x16,
1824
+ ssa.OpAMD64VPMOVMToVec16x32,
1825
+ ssa.OpAMD64VPMOVMToVec32x4,
1826
+ ssa.OpAMD64VPMOVMToVec32x8,
1827
+ ssa.OpAMD64VPMOVMToVec32x16,
1828
+ ssa.OpAMD64VPMOVMToVec64x2,
1829
+ ssa.OpAMD64VPMOVMToVec64x4,
1830
+ ssa.OpAMD64VPMOVMToVec64x8:
1831
+ p := s.Prog(v.Op.Asm())
1832
+ p.From.Type = obj.TYPE_REG
1833
+ p.From.Reg = v.Args[0].Reg()
1834
+ p.To.Type = obj.TYPE_REG
1835
+ p.To.Reg = simdReg(v)
1836
+
1837
+ case ssa.OpAMD64VPMOVVec8x16ToM,
1838
+ ssa.OpAMD64VPMOVVec8x32ToM,
1839
+ ssa.OpAMD64VPMOVVec8x64ToM,
1840
+ ssa.OpAMD64VPMOVVec16x8ToM,
1841
+ ssa.OpAMD64VPMOVVec16x16ToM,
1842
+ ssa.OpAMD64VPMOVVec16x32ToM,
1843
+ ssa.OpAMD64VPMOVVec32x4ToM,
1844
+ ssa.OpAMD64VPMOVVec32x8ToM,
1845
+ ssa.OpAMD64VPMOVVec32x16ToM,
1846
+ ssa.OpAMD64VPMOVVec64x2ToM,
1847
+ ssa.OpAMD64VPMOVVec64x4ToM,
1848
+ ssa.OpAMD64VPMOVVec64x8ToM,
1849
+ ssa.OpAMD64VPMOVMSKB128,
1850
+ ssa.OpAMD64VPMOVMSKB256,
1851
+ ssa.OpAMD64VMOVMSKPS128,
1852
+ ssa.OpAMD64VMOVMSKPS256,
1853
+ ssa.OpAMD64VMOVMSKPD128,
1854
+ ssa.OpAMD64VMOVMSKPD256:
1855
+ p := s.Prog(v.Op.Asm())
1856
+ p.From.Type = obj.TYPE_REG
1857
+ p.From.Reg = simdReg(v.Args[0])
1858
+ p.To.Type = obj.TYPE_REG
1859
+ p.To.Reg = v.Reg()
1860
+
1861
+ case ssa.OpAMD64KMOVQk, ssa.OpAMD64KMOVDk, ssa.OpAMD64KMOVWk, ssa.OpAMD64KMOVBk,
1862
+ ssa.OpAMD64KMOVQi, ssa.OpAMD64KMOVDi, ssa.OpAMD64KMOVWi, ssa.OpAMD64KMOVBi:
1863
+ // See also ssa.OpAMD64KMOVQload
1864
+ p := s.Prog(v.Op.Asm())
1865
+ p.From.Type = obj.TYPE_REG
1866
+ p.From.Reg = v.Args[0].Reg()
1867
+ p.To.Type = obj.TYPE_REG
1868
+ p.To.Reg = v.Reg()
1869
+ case ssa.OpAMD64VPTEST:
1870
+ // Some instructions setting flags put their second operand into the destination reg.
1871
+ // See also CMP[BWDQ].
1872
+ p := s.Prog(v.Op.Asm())
1873
+ p.From.Type = obj.TYPE_REG
1874
+ p.From.Reg = simdReg(v.Args[0])
1875
+ p.To.Type = obj.TYPE_REG
1876
+ p.To.Reg = simdReg(v.Args[1])
1877
+
1878
+ default:
1879
+ if !ssaGenSIMDValue(s, v) {
1880
+ v.Fatalf("genValue not implemented: %s", v.LongString())
1881
+ }
1882
+ }
1883
+ }
1884
+
1885
+ // zeroX15 zeroes the X15 register.
1886
+ func zeroX15(s *ssagen.State) {
1887
+ opregreg(s, x86.AXORPS, x86.REG_X15, x86.REG_X15)
1888
+ }
1889
+
1890
+ // Example instruction: VRSQRTPS X1, X1
1891
+ func simdV11(s *ssagen.State, v *ssa.Value) *obj.Prog {
1892
+ p := s.Prog(v.Op.Asm())
1893
+ p.From.Type = obj.TYPE_REG
1894
+ p.From.Reg = simdReg(v.Args[0])
1895
+ p.To.Type = obj.TYPE_REG
1896
+ p.To.Reg = simdReg(v)
1897
+ return p
1898
+ }
1899
+
1900
+ // Example instruction: VPSUBD X1, X2, X3
1901
+ func simdV21(s *ssagen.State, v *ssa.Value) *obj.Prog {
1902
+ p := s.Prog(v.Op.Asm())
1903
+ p.From.Type = obj.TYPE_REG
1904
+ // Vector registers operands follows a right-to-left order.
1905
+ // e.g. VPSUBD X1, X2, X3 means X3 = X2 - X1.
1906
+ p.From.Reg = simdReg(v.Args[1])
1907
+ p.AddRestSourceReg(simdReg(v.Args[0]))
1908
+ p.To.Type = obj.TYPE_REG
1909
+ p.To.Reg = simdReg(v)
1910
+ return p
1911
+ }
1912
+
1913
+ // This function is to accustomize the shifts.
1914
+ // The 2nd arg is an XMM, and this function merely checks that.
1915
+ // Example instruction: VPSLLQ Z1, X1, Z2
1916
+ func simdVfpv(s *ssagen.State, v *ssa.Value) *obj.Prog {
1917
+ p := s.Prog(v.Op.Asm())
1918
+ p.From.Type = obj.TYPE_REG
1919
+ // Vector registers operands follows a right-to-left order.
1920
+ // e.g. VPSUBD X1, X2, X3 means X3 = X2 - X1.
1921
+ p.From.Reg = v.Args[1].Reg()
1922
+ p.AddRestSourceReg(simdReg(v.Args[0]))
1923
+ p.To.Type = obj.TYPE_REG
1924
+ p.To.Reg = simdReg(v)
1925
+ return p
1926
+ }
1927
+
1928
+ // Example instruction: VPCMPEQW Z26, Z30, K4
1929
+ func simdV2k(s *ssagen.State, v *ssa.Value) *obj.Prog {
1930
+ p := s.Prog(v.Op.Asm())
1931
+ p.From.Type = obj.TYPE_REG
1932
+ p.From.Reg = simdReg(v.Args[1])
1933
+ p.AddRestSourceReg(simdReg(v.Args[0]))
1934
+ p.To.Type = obj.TYPE_REG
1935
+ p.To.Reg = maskReg(v)
1936
+ return p
1937
+ }
1938
+
1939
+ // Example instruction: VPMINUQ X21, X3, K3, X31
1940
+ func simdV2kv(s *ssagen.State, v *ssa.Value) *obj.Prog {
1941
+ p := s.Prog(v.Op.Asm())
1942
+ p.From.Type = obj.TYPE_REG
1943
+ p.From.Reg = simdReg(v.Args[1])
1944
+ p.AddRestSourceReg(simdReg(v.Args[0]))
1945
+ // These "simd*" series of functions assumes:
1946
+ // Any "K" register that serves as the write-mask
1947
+ // or "predicate" for "predicated AVX512 instructions"
1948
+ // sits right at the end of the operand list.
1949
+ // TODO: verify this assumption.
1950
+ p.AddRestSourceReg(maskReg(v.Args[2]))
1951
+ p.To.Type = obj.TYPE_REG
1952
+ p.To.Reg = simdReg(v)
1953
+ return p
1954
+ }
1955
+
1956
+ // Example instruction: VPABSB X1, X2, K3 (masking merging)
1957
+ func simdV2kvResultInArg0(s *ssagen.State, v *ssa.Value) *obj.Prog {
1958
+ p := s.Prog(v.Op.Asm())
1959
+ p.From.Type = obj.TYPE_REG
1960
+ p.From.Reg = simdReg(v.Args[1])
1961
+ // These "simd*" series of functions assumes:
1962
+ // Any "K" register that serves as the write-mask
1963
+ // or "predicate" for "predicated AVX512 instructions"
1964
+ // sits right at the end of the operand list.
1965
+ // TODO: verify this assumption.
1966
+ p.AddRestSourceReg(maskReg(v.Args[2]))
1967
+ p.To.Type = obj.TYPE_REG
1968
+ p.To.Reg = simdReg(v)
1969
+ return p
1970
+ }
1971
+
1972
+ // This function is to accustomize the shifts.
1973
+ // The 2nd arg is an XMM, and this function merely checks that.
1974
+ // Example instruction: VPSLLQ Z1, X1, K1, Z2
1975
+ func simdVfpkv(s *ssagen.State, v *ssa.Value) *obj.Prog {
1976
+ p := s.Prog(v.Op.Asm())
1977
+ p.From.Type = obj.TYPE_REG
1978
+ p.From.Reg = v.Args[1].Reg()
1979
+ p.AddRestSourceReg(simdReg(v.Args[0]))
1980
+ p.AddRestSourceReg(maskReg(v.Args[2]))
1981
+ p.To.Type = obj.TYPE_REG
1982
+ p.To.Reg = simdReg(v)
1983
+ return p
1984
+ }
1985
+
1986
+ // Example instruction: VPCMPEQW Z26, Z30, K1, K4
1987
+ func simdV2kk(s *ssagen.State, v *ssa.Value) *obj.Prog {
1988
+ p := s.Prog(v.Op.Asm())
1989
+ p.From.Type = obj.TYPE_REG
1990
+ p.From.Reg = simdReg(v.Args[1])
1991
+ p.AddRestSourceReg(simdReg(v.Args[0]))
1992
+ p.AddRestSourceReg(maskReg(v.Args[2]))
1993
+ p.To.Type = obj.TYPE_REG
1994
+ p.To.Reg = maskReg(v)
1995
+ return p
1996
+ }
1997
+
1998
+ // Example instruction: VPOPCNTB X14, K4, X16
1999
+ func simdVkv(s *ssagen.State, v *ssa.Value) *obj.Prog {
2000
+ p := s.Prog(v.Op.Asm())
2001
+ p.From.Type = obj.TYPE_REG
2002
+ p.From.Reg = simdReg(v.Args[0])
2003
+ p.AddRestSourceReg(maskReg(v.Args[1]))
2004
+ p.To.Type = obj.TYPE_REG
2005
+ p.To.Reg = simdReg(v)
2006
+ return p
2007
+ }
2008
+
2009
+ // Example instruction: VROUNDPD $7, X2, X2
2010
+ func simdV11Imm8(s *ssagen.State, v *ssa.Value) *obj.Prog {
2011
+ p := s.Prog(v.Op.Asm())
2012
+ p.From.Offset = int64(v.AuxUInt8())
2013
+ p.From.Type = obj.TYPE_CONST
2014
+ p.AddRestSourceReg(simdReg(v.Args[0]))
2015
+ p.To.Type = obj.TYPE_REG
2016
+ p.To.Reg = simdReg(v)
2017
+ return p
2018
+ }
2019
+
2020
+ // Example instruction: VREDUCEPD $126, X1, K3, X31
2021
+ func simdVkvImm8(s *ssagen.State, v *ssa.Value) *obj.Prog {
2022
+ p := s.Prog(v.Op.Asm())
2023
+ p.From.Offset = int64(v.AuxUInt8())
2024
+ p.From.Type = obj.TYPE_CONST
2025
+ p.AddRestSourceReg(simdReg(v.Args[0]))
2026
+ p.AddRestSourceReg(maskReg(v.Args[1]))
2027
+ p.To.Type = obj.TYPE_REG
2028
+ p.To.Reg = simdReg(v)
2029
+ return p
2030
+ }
2031
+
2032
+ // Example instruction: VCMPPS $7, X2, X9, X2
2033
+ func simdV21Imm8(s *ssagen.State, v *ssa.Value) *obj.Prog {
2034
+ p := s.Prog(v.Op.Asm())
2035
+ p.From.Offset = int64(v.AuxUInt8())
2036
+ p.From.Type = obj.TYPE_CONST
2037
+ p.AddRestSourceReg(simdReg(v.Args[1]))
2038
+ p.AddRestSourceReg(simdReg(v.Args[0]))
2039
+ p.To.Type = obj.TYPE_REG
2040
+ p.To.Reg = simdReg(v)
2041
+ return p
2042
+ }
2043
+
2044
+ // Example instruction: VPINSRB $3, DX, X0, X0
2045
+ func simdVgpvImm8(s *ssagen.State, v *ssa.Value) *obj.Prog {
2046
+ p := s.Prog(v.Op.Asm())
2047
+ p.From.Offset = int64(v.AuxUInt8())
2048
+ p.From.Type = obj.TYPE_CONST
2049
+ p.AddRestSourceReg(v.Args[1].Reg())
2050
+ p.AddRestSourceReg(simdReg(v.Args[0]))
2051
+ p.To.Type = obj.TYPE_REG
2052
+ p.To.Reg = simdReg(v)
2053
+ return p
2054
+ }
2055
+
2056
+ // Example instruction: VPCMPD $1, Z1, Z2, K1
2057
+ func simdV2kImm8(s *ssagen.State, v *ssa.Value) *obj.Prog {
2058
+ p := s.Prog(v.Op.Asm())
2059
+ p.From.Offset = int64(v.AuxUInt8())
2060
+ p.From.Type = obj.TYPE_CONST
2061
+ p.AddRestSourceReg(simdReg(v.Args[1]))
2062
+ p.AddRestSourceReg(simdReg(v.Args[0]))
2063
+ p.To.Type = obj.TYPE_REG
2064
+ p.To.Reg = maskReg(v)
2065
+ return p
2066
+ }
2067
+
2068
+ // Example instruction: VPCMPD $1, Z1, Z2, K2, K1
2069
+ func simdV2kkImm8(s *ssagen.State, v *ssa.Value) *obj.Prog {
2070
+ p := s.Prog(v.Op.Asm())
2071
+ p.From.Offset = int64(v.AuxUInt8())
2072
+ p.From.Type = obj.TYPE_CONST
2073
+ p.AddRestSourceReg(simdReg(v.Args[1]))
2074
+ p.AddRestSourceReg(simdReg(v.Args[0]))
2075
+ p.AddRestSourceReg(maskReg(v.Args[2]))
2076
+ p.To.Type = obj.TYPE_REG
2077
+ p.To.Reg = maskReg(v)
2078
+ return p
2079
+ }
2080
+
2081
+ func simdV2kvImm8(s *ssagen.State, v *ssa.Value) *obj.Prog {
2082
+ p := s.Prog(v.Op.Asm())
2083
+ p.From.Offset = int64(v.AuxUInt8())
2084
+ p.From.Type = obj.TYPE_CONST
2085
+ p.AddRestSourceReg(simdReg(v.Args[1]))
2086
+ p.AddRestSourceReg(simdReg(v.Args[0]))
2087
+ p.AddRestSourceReg(maskReg(v.Args[2]))
2088
+ p.To.Type = obj.TYPE_REG
2089
+ p.To.Reg = simdReg(v)
2090
+ return p
2091
+ }
2092
+
2093
+ // Example instruction: VFMADD213PD Z2, Z1, Z0
2094
+ func simdV31ResultInArg0(s *ssagen.State, v *ssa.Value) *obj.Prog {
2095
+ p := s.Prog(v.Op.Asm())
2096
+ p.From.Type = obj.TYPE_REG
2097
+ p.From.Reg = simdReg(v.Args[2])
2098
+ p.AddRestSourceReg(simdReg(v.Args[1]))
2099
+ p.To.Type = obj.TYPE_REG
2100
+ p.To.Reg = simdReg(v)
2101
+ return p
2102
+ }
2103
+
2104
+ func simdV31ResultInArg0Imm8(s *ssagen.State, v *ssa.Value) *obj.Prog {
2105
+ p := s.Prog(v.Op.Asm())
2106
+ p.From.Offset = int64(v.AuxUInt8())
2107
+ p.From.Type = obj.TYPE_CONST
2108
+
2109
+ p.AddRestSourceReg(simdReg(v.Args[2]))
2110
+ p.AddRestSourceReg(simdReg(v.Args[1]))
2111
+ // p.AddRestSourceReg(x86.REG_K0)
2112
+ p.To.Type = obj.TYPE_REG
2113
+ p.To.Reg = simdReg(v)
2114
+ return p
2115
+ }
2116
+
2117
+ // v31loadResultInArg0Imm8
2118
+ // Example instruction:
2119
+ // for (VPTERNLOGD128load {sym} [makeValAndOff(int32(int8(c)),off)] x y ptr mem)
2120
+ func simdV31loadResultInArg0Imm8(s *ssagen.State, v *ssa.Value) *obj.Prog {
2121
+ sc := v.AuxValAndOff()
2122
+ p := s.Prog(v.Op.Asm())
2123
+
2124
+ p.From.Type = obj.TYPE_CONST
2125
+ p.From.Offset = sc.Val64()
2126
+
2127
+ m := obj.Addr{Type: obj.TYPE_MEM, Reg: v.Args[2].Reg()}
2128
+ ssagen.AddAux2(&m, v, sc.Off64())
2129
+ p.AddRestSource(m)
2130
+
2131
+ p.AddRestSourceReg(simdReg(v.Args[1]))
2132
+ return p
2133
+ }
2134
+
2135
+ // Example instruction: VFMADD213PD Z2, Z1, K1, Z0
2136
+ func simdV3kvResultInArg0(s *ssagen.State, v *ssa.Value) *obj.Prog {
2137
+ p := s.Prog(v.Op.Asm())
2138
+ p.From.Type = obj.TYPE_REG
2139
+ p.From.Reg = simdReg(v.Args[2])
2140
+ p.AddRestSourceReg(simdReg(v.Args[1]))
2141
+ p.AddRestSourceReg(maskReg(v.Args[3]))
2142
+ p.To.Type = obj.TYPE_REG
2143
+ p.To.Reg = simdReg(v)
2144
+ return p
2145
+ }
2146
+
2147
+ func simdVgpImm8(s *ssagen.State, v *ssa.Value) *obj.Prog {
2148
+ p := s.Prog(v.Op.Asm())
2149
+ p.From.Offset = int64(v.AuxUInt8())
2150
+ p.From.Type = obj.TYPE_CONST
2151
+ p.AddRestSourceReg(simdReg(v.Args[0]))
2152
+ p.To.Type = obj.TYPE_REG
2153
+ p.To.Reg = v.Reg()
2154
+ return p
2155
+ }
2156
+
2157
+ // Currently unused
2158
+ func simdV31(s *ssagen.State, v *ssa.Value) *obj.Prog {
2159
+ p := s.Prog(v.Op.Asm())
2160
+ p.From.Type = obj.TYPE_REG
2161
+ p.From.Reg = simdReg(v.Args[2])
2162
+ p.AddRestSourceReg(simdReg(v.Args[1]))
2163
+ p.AddRestSourceReg(simdReg(v.Args[0]))
2164
+ p.To.Type = obj.TYPE_REG
2165
+ p.To.Reg = simdReg(v)
2166
+ return p
2167
+ }
2168
+
2169
+ // Currently unused
2170
+ func simdV3kv(s *ssagen.State, v *ssa.Value) *obj.Prog {
2171
+ p := s.Prog(v.Op.Asm())
2172
+ p.From.Type = obj.TYPE_REG
2173
+ p.From.Reg = simdReg(v.Args[2])
2174
+ p.AddRestSourceReg(simdReg(v.Args[1]))
2175
+ p.AddRestSourceReg(simdReg(v.Args[0]))
2176
+ p.AddRestSourceReg(maskReg(v.Args[3]))
2177
+ p.To.Type = obj.TYPE_REG
2178
+ p.To.Reg = simdReg(v)
2179
+ return p
2180
+ }
2181
+
2182
+ // Example instruction: VRCP14PS (DI), K6, X22
2183
+ func simdVkvload(s *ssagen.State, v *ssa.Value) *obj.Prog {
2184
+ p := s.Prog(v.Op.Asm())
2185
+ p.From.Type = obj.TYPE_MEM
2186
+ p.From.Reg = v.Args[0].Reg()
2187
+ ssagen.AddAux(&p.From, v)
2188
+ p.AddRestSourceReg(maskReg(v.Args[1]))
2189
+ p.To.Type = obj.TYPE_REG
2190
+ p.To.Reg = simdReg(v)
2191
+ return p
2192
+ }
2193
+
2194
+ // Example instruction: VPSLLVD (DX), X7, X18
2195
+ func simdV21load(s *ssagen.State, v *ssa.Value) *obj.Prog {
2196
+ p := s.Prog(v.Op.Asm())
2197
+ p.From.Type = obj.TYPE_MEM
2198
+ p.From.Reg = v.Args[1].Reg()
2199
+ ssagen.AddAux(&p.From, v)
2200
+ p.AddRestSourceReg(simdReg(v.Args[0]))
2201
+ p.To.Type = obj.TYPE_REG
2202
+ p.To.Reg = simdReg(v)
2203
+ return p
2204
+ }
2205
+
2206
+ // Example instruction: VPDPWSSD (SI), X24, X18
2207
+ func simdV31loadResultInArg0(s *ssagen.State, v *ssa.Value) *obj.Prog {
2208
+ p := s.Prog(v.Op.Asm())
2209
+ p.From.Type = obj.TYPE_MEM
2210
+ p.From.Reg = v.Args[2].Reg()
2211
+ ssagen.AddAux(&p.From, v)
2212
+ p.AddRestSourceReg(simdReg(v.Args[1]))
2213
+ p.To.Type = obj.TYPE_REG
2214
+ p.To.Reg = simdReg(v)
2215
+ return p
2216
+ }
2217
+
2218
+ // Example instruction: VPDPWSSD (SI), X24, K1, X18
2219
+ func simdV3kvloadResultInArg0(s *ssagen.State, v *ssa.Value) *obj.Prog {
2220
+ p := s.Prog(v.Op.Asm())
2221
+ p.From.Type = obj.TYPE_MEM
2222
+ p.From.Reg = v.Args[2].Reg()
2223
+ ssagen.AddAux(&p.From, v)
2224
+ p.AddRestSourceReg(simdReg(v.Args[1]))
2225
+ p.AddRestSourceReg(maskReg(v.Args[3]))
2226
+ p.To.Type = obj.TYPE_REG
2227
+ p.To.Reg = simdReg(v)
2228
+ return p
2229
+ }
2230
+
2231
+ // Example instruction: VPSLLVD (SI), X1, K1, X2
2232
+ func simdV2kvload(s *ssagen.State, v *ssa.Value) *obj.Prog {
2233
+ p := s.Prog(v.Op.Asm())
2234
+ p.From.Type = obj.TYPE_MEM
2235
+ p.From.Reg = v.Args[1].Reg()
2236
+ ssagen.AddAux(&p.From, v)
2237
+ p.AddRestSourceReg(simdReg(v.Args[0]))
2238
+ p.AddRestSourceReg(maskReg(v.Args[2]))
2239
+ p.To.Type = obj.TYPE_REG
2240
+ p.To.Reg = simdReg(v)
2241
+ return p
2242
+ }
2243
+
2244
+ // Example instruction: VPCMPEQD (SI), X1, K1
2245
+ func simdV2kload(s *ssagen.State, v *ssa.Value) *obj.Prog {
2246
+ p := s.Prog(v.Op.Asm())
2247
+ p.From.Type = obj.TYPE_MEM
2248
+ p.From.Reg = v.Args[1].Reg()
2249
+ ssagen.AddAux(&p.From, v)
2250
+ p.AddRestSourceReg(simdReg(v.Args[0]))
2251
+ p.To.Type = obj.TYPE_REG
2252
+ p.To.Reg = maskReg(v)
2253
+ return p
2254
+ }
2255
+
2256
+ // Example instruction: VCVTTPS2DQ (BX), X2
2257
+ func simdV11load(s *ssagen.State, v *ssa.Value) *obj.Prog {
2258
+ p := s.Prog(v.Op.Asm())
2259
+ p.From.Type = obj.TYPE_MEM
2260
+ p.From.Reg = v.Args[0].Reg()
2261
+ ssagen.AddAux(&p.From, v)
2262
+ p.To.Type = obj.TYPE_REG
2263
+ p.To.Reg = simdReg(v)
2264
+ return p
2265
+ }
2266
+
2267
+ // Example instruction: VPSHUFD $7, (BX), X11
2268
+ func simdV11loadImm8(s *ssagen.State, v *ssa.Value) *obj.Prog {
2269
+ sc := v.AuxValAndOff()
2270
+ p := s.Prog(v.Op.Asm())
2271
+ p.From.Type = obj.TYPE_CONST
2272
+ p.From.Offset = sc.Val64()
2273
+ m := obj.Addr{Type: obj.TYPE_MEM, Reg: v.Args[0].Reg()}
2274
+ ssagen.AddAux2(&m, v, sc.Off64())
2275
+ p.AddRestSource(m)
2276
+ p.To.Type = obj.TYPE_REG
2277
+ p.To.Reg = simdReg(v)
2278
+ return p
2279
+ }
2280
+
2281
+ // Example instruction: VPRORD $81, -15(R14), K7, Y1
2282
+ func simdVkvloadImm8(s *ssagen.State, v *ssa.Value) *obj.Prog {
2283
+ sc := v.AuxValAndOff()
2284
+ p := s.Prog(v.Op.Asm())
2285
+ p.From.Type = obj.TYPE_CONST
2286
+ p.From.Offset = sc.Val64()
2287
+ m := obj.Addr{Type: obj.TYPE_MEM, Reg: v.Args[0].Reg()}
2288
+ ssagen.AddAux2(&m, v, sc.Off64())
2289
+ p.AddRestSource(m)
2290
+ p.AddRestSourceReg(maskReg(v.Args[1]))
2291
+ p.To.Type = obj.TYPE_REG
2292
+ p.To.Reg = simdReg(v)
2293
+ return p
2294
+ }
2295
+
2296
+ // Example instruction: VPSHLDD $82, 7(SI), Y21, Y3
2297
+ func simdV21loadImm8(s *ssagen.State, v *ssa.Value) *obj.Prog {
2298
+ sc := v.AuxValAndOff()
2299
+ p := s.Prog(v.Op.Asm())
2300
+ p.From.Type = obj.TYPE_CONST
2301
+ p.From.Offset = sc.Val64()
2302
+ m := obj.Addr{Type: obj.TYPE_MEM, Reg: v.Args[1].Reg()}
2303
+ ssagen.AddAux2(&m, v, sc.Off64())
2304
+ p.AddRestSource(m)
2305
+ p.AddRestSourceReg(simdReg(v.Args[0]))
2306
+ p.To.Type = obj.TYPE_REG
2307
+ p.To.Reg = simdReg(v)
2308
+ return p
2309
+ }
2310
+
2311
+ // Example instruction: VCMPPS $81, -7(DI), Y16, K3
2312
+ func simdV2kloadImm8(s *ssagen.State, v *ssa.Value) *obj.Prog {
2313
+ sc := v.AuxValAndOff()
2314
+ p := s.Prog(v.Op.Asm())
2315
+ p.From.Type = obj.TYPE_CONST
2316
+ p.From.Offset = sc.Val64()
2317
+ m := obj.Addr{Type: obj.TYPE_MEM, Reg: v.Args[1].Reg()}
2318
+ ssagen.AddAux2(&m, v, sc.Off64())
2319
+ p.AddRestSource(m)
2320
+ p.AddRestSourceReg(simdReg(v.Args[0]))
2321
+ p.To.Type = obj.TYPE_REG
2322
+ p.To.Reg = maskReg(v)
2323
+ return p
2324
+ }
2325
+
2326
+ // Example instruction: VCMPPS $81, -7(DI), Y16, K1, K3
2327
+ func simdV2kkloadImm8(s *ssagen.State, v *ssa.Value) *obj.Prog {
2328
+ sc := v.AuxValAndOff()
2329
+ p := s.Prog(v.Op.Asm())
2330
+ p.From.Type = obj.TYPE_CONST
2331
+ p.From.Offset = sc.Val64()
2332
+ m := obj.Addr{Type: obj.TYPE_MEM, Reg: v.Args[1].Reg()}
2333
+ ssagen.AddAux2(&m, v, sc.Off64())
2334
+ p.AddRestSource(m)
2335
+ p.AddRestSourceReg(simdReg(v.Args[0]))
2336
+ p.AddRestSourceReg(maskReg(v.Args[2]))
2337
+ p.To.Type = obj.TYPE_REG
2338
+ p.To.Reg = maskReg(v)
2339
+ return p
2340
+ }
2341
+
2342
+ // Example instruction: VGF2P8AFFINEINVQB $64, -17(BP), X31, K3, X26
2343
+ func simdV2kvloadImm8(s *ssagen.State, v *ssa.Value) *obj.Prog {
2344
+ sc := v.AuxValAndOff()
2345
+ p := s.Prog(v.Op.Asm())
2346
+ p.From.Type = obj.TYPE_CONST
2347
+ p.From.Offset = sc.Val64()
2348
+ m := obj.Addr{Type: obj.TYPE_MEM, Reg: v.Args[1].Reg()}
2349
+ ssagen.AddAux2(&m, v, sc.Off64())
2350
+ p.AddRestSource(m)
2351
+ p.AddRestSourceReg(simdReg(v.Args[0]))
2352
+ p.AddRestSourceReg(maskReg(v.Args[2]))
2353
+ p.To.Type = obj.TYPE_REG
2354
+ p.To.Reg = simdReg(v)
2355
+ return p
2356
+ }
2357
+
2358
+ // Example instruction: SHA1NEXTE X2, X2
2359
+ func simdV21ResultInArg0(s *ssagen.State, v *ssa.Value) *obj.Prog {
2360
+ p := s.Prog(v.Op.Asm())
2361
+ p.From.Type = obj.TYPE_REG
2362
+ p.From.Reg = simdReg(v.Args[1])
2363
+ p.To.Type = obj.TYPE_REG
2364
+ p.To.Reg = simdReg(v)
2365
+ return p
2366
+ }
2367
+
2368
+ // Example instruction: SHA1RNDS4 $1, X2, X2
2369
+ func simdV21ResultInArg0Imm8(s *ssagen.State, v *ssa.Value) *obj.Prog {
2370
+ p := s.Prog(v.Op.Asm())
2371
+ p.From.Offset = int64(v.AuxUInt8())
2372
+ p.From.Type = obj.TYPE_CONST
2373
+ p.AddRestSourceReg(simdReg(v.Args[1]))
2374
+ p.To.Type = obj.TYPE_REG
2375
+ p.To.Reg = simdReg(v)
2376
+ return p
2377
+ }
2378
+
2379
+ // Example instruction: SHA256RNDS2 X0, X11, X2
2380
+ func simdV31x0AtIn2ResultInArg0(s *ssagen.State, v *ssa.Value) *obj.Prog {
2381
+ return simdV31ResultInArg0(s, v)
2382
+ }
2383
+
2384
+ var blockJump = [...]struct {
2385
+ asm, invasm obj.As
2386
+ }{
2387
+ ssa.BlockAMD64EQ: {x86.AJEQ, x86.AJNE},
2388
+ ssa.BlockAMD64NE: {x86.AJNE, x86.AJEQ},
2389
+ ssa.BlockAMD64LT: {x86.AJLT, x86.AJGE},
2390
+ ssa.BlockAMD64GE: {x86.AJGE, x86.AJLT},
2391
+ ssa.BlockAMD64LE: {x86.AJLE, x86.AJGT},
2392
+ ssa.BlockAMD64GT: {x86.AJGT, x86.AJLE},
2393
+ ssa.BlockAMD64OS: {x86.AJOS, x86.AJOC},
2394
+ ssa.BlockAMD64OC: {x86.AJOC, x86.AJOS},
2395
+ ssa.BlockAMD64ULT: {x86.AJCS, x86.AJCC},
2396
+ ssa.BlockAMD64UGE: {x86.AJCC, x86.AJCS},
2397
+ ssa.BlockAMD64UGT: {x86.AJHI, x86.AJLS},
2398
+ ssa.BlockAMD64ULE: {x86.AJLS, x86.AJHI},
2399
+ ssa.BlockAMD64ORD: {x86.AJPC, x86.AJPS},
2400
+ ssa.BlockAMD64NAN: {x86.AJPS, x86.AJPC},
2401
+ }
2402
+
2403
+ var eqfJumps = [2][2]ssagen.IndexJump{
2404
+ {{Jump: x86.AJNE, Index: 1}, {Jump: x86.AJPS, Index: 1}}, // next == b.Succs[0]
2405
+ {{Jump: x86.AJNE, Index: 1}, {Jump: x86.AJPC, Index: 0}}, // next == b.Succs[1]
2406
+ }
2407
+ var nefJumps = [2][2]ssagen.IndexJump{
2408
+ {{Jump: x86.AJNE, Index: 0}, {Jump: x86.AJPC, Index: 1}}, // next == b.Succs[0]
2409
+ {{Jump: x86.AJNE, Index: 0}, {Jump: x86.AJPS, Index: 0}}, // next == b.Succs[1]
2410
+ }
2411
+
2412
+ func ssaGenBlock(s *ssagen.State, b, next *ssa.Block) {
2413
+ switch b.Kind {
2414
+ case ssa.BlockPlain, ssa.BlockDefer:
2415
+ if b.Succs[0].Block() != next {
2416
+ p := s.Prog(obj.AJMP)
2417
+ p.To.Type = obj.TYPE_BRANCH
2418
+ s.Branches = append(s.Branches, ssagen.Branch{P: p, B: b.Succs[0].Block()})
2419
+ }
2420
+ case ssa.BlockExit, ssa.BlockRetJmp:
2421
+ case ssa.BlockRet:
2422
+ s.Prog(obj.ARET)
2423
+
2424
+ case ssa.BlockAMD64EQF:
2425
+ s.CombJump(b, next, &eqfJumps)
2426
+
2427
+ case ssa.BlockAMD64NEF:
2428
+ s.CombJump(b, next, &nefJumps)
2429
+
2430
+ case ssa.BlockAMD64EQ, ssa.BlockAMD64NE,
2431
+ ssa.BlockAMD64LT, ssa.BlockAMD64GE,
2432
+ ssa.BlockAMD64LE, ssa.BlockAMD64GT,
2433
+ ssa.BlockAMD64OS, ssa.BlockAMD64OC,
2434
+ ssa.BlockAMD64ULT, ssa.BlockAMD64UGT,
2435
+ ssa.BlockAMD64ULE, ssa.BlockAMD64UGE:
2436
+ jmp := blockJump[b.Kind]
2437
+ switch next {
2438
+ case b.Succs[0].Block():
2439
+ s.Br(jmp.invasm, b.Succs[1].Block())
2440
+ case b.Succs[1].Block():
2441
+ s.Br(jmp.asm, b.Succs[0].Block())
2442
+ default:
2443
+ if b.Likely != ssa.BranchUnlikely {
2444
+ s.Br(jmp.asm, b.Succs[0].Block())
2445
+ s.Br(obj.AJMP, b.Succs[1].Block())
2446
+ } else {
2447
+ s.Br(jmp.invasm, b.Succs[1].Block())
2448
+ s.Br(obj.AJMP, b.Succs[0].Block())
2449
+ }
2450
+ }
2451
+
2452
+ case ssa.BlockAMD64JUMPTABLE:
2453
+ // JMP *(TABLE)(INDEX*8)
2454
+ p := s.Prog(obj.AJMP)
2455
+ p.To.Type = obj.TYPE_MEM
2456
+ p.To.Reg = b.Controls[1].Reg()
2457
+ p.To.Index = b.Controls[0].Reg()
2458
+ p.To.Scale = 8
2459
+ // Save jump tables for later resolution of the target blocks.
2460
+ s.JumpTables = append(s.JumpTables, b)
2461
+
2462
+ default:
2463
+ b.Fatalf("branch not implemented: %s", b.LongString())
2464
+ }
2465
+ }
2466
+
2467
+ func loadRegResult(s *ssagen.State, f *ssa.Func, t *types.Type, reg int16, n *ir.Name, off int64) *obj.Prog {
2468
+ p := s.Prog(loadByRegWidth(reg, t.Size()))
2469
+ p.From.Type = obj.TYPE_MEM
2470
+ p.From.Name = obj.NAME_AUTO
2471
+ p.From.Sym = n.Linksym()
2472
+ p.From.Offset = n.FrameOffset() + off
2473
+ p.To.Type = obj.TYPE_REG
2474
+ p.To.Reg = reg
2475
+ return p
2476
+ }
2477
+
2478
+ func spillArgReg(pp *objw.Progs, p *obj.Prog, f *ssa.Func, t *types.Type, reg int16, n *ir.Name, off int64) *obj.Prog {
2479
+ p = pp.Append(p, storeByRegWidth(reg, t.Size()), obj.TYPE_REG, reg, 0, obj.TYPE_MEM, 0, n.FrameOffset()+off)
2480
+ p.To.Name = obj.NAME_PARAM
2481
+ p.To.Sym = n.Linksym()
2482
+ p.Pos = p.Pos.WithNotStmt()
2483
+ return p
2484
+ }
2485
+
2486
+ // zero 16 bytes at reg+off.
2487
+ func zero16(s *ssagen.State, reg int16, off int64) {
2488
+ // MOVUPS X15, off(ptrReg)
2489
+ p := s.Prog(x86.AMOVUPS)
2490
+ p.From.Type = obj.TYPE_REG
2491
+ p.From.Reg = x86.REG_X15
2492
+ p.To.Type = obj.TYPE_MEM
2493
+ p.To.Reg = reg
2494
+ p.To.Offset = off
2495
+ }
2496
+
2497
+ // move 16 bytes from src+off to dst+off using temporary register tmp.
2498
+ func move16(s *ssagen.State, src, dst, tmp int16, off int64) {
2499
+ // MOVUPS off(srcReg), tmpReg
2500
+ // MOVUPS tmpReg, off(dstReg)
2501
+ p := s.Prog(x86.AMOVUPS)
2502
+ p.From.Type = obj.TYPE_MEM
2503
+ p.From.Reg = src
2504
+ p.From.Offset = off
2505
+ p.To.Type = obj.TYPE_REG
2506
+ p.To.Reg = tmp
2507
+ p = s.Prog(x86.AMOVUPS)
2508
+ p.From.Type = obj.TYPE_REG
2509
+ p.From.Reg = tmp
2510
+ p.To.Type = obj.TYPE_MEM
2511
+ p.To.Reg = dst
2512
+ p.To.Offset = off
2513
+ }
2514
+
2515
+ // XXX maybe make this part of v.Reg?
2516
+ // On the other hand, it is architecture-specific.
2517
+ func simdReg(v *ssa.Value) int16 {
2518
+ t := v.Type
2519
+ if !t.IsSIMD() {
2520
+ base.Fatalf("simdReg: not a simd type; v=%s, b=b%d, f=%s", v.LongString(), v.Block.ID, v.Block.Func.Name)
2521
+ }
2522
+ return simdRegBySize(v.Reg(), t.Size())
2523
+ }
2524
+
2525
+ func simdRegBySize(reg int16, size int64) int16 {
2526
+ switch size {
2527
+ case 16:
2528
+ return reg
2529
+ case 32:
2530
+ return reg + (x86.REG_Y0 - x86.REG_X0)
2531
+ case 64:
2532
+ return reg + (x86.REG_Z0 - x86.REG_X0)
2533
+ }
2534
+ panic("simdRegBySize: bad size")
2535
+ }
2536
+
2537
+ // XXX k mask
2538
+ func maskReg(v *ssa.Value) int16 {
2539
+ t := v.Type
2540
+ if !t.IsSIMD() {
2541
+ base.Fatalf("maskReg: not a simd type; v=%s, b=b%d, f=%s", v.LongString(), v.Block.ID, v.Block.Func.Name)
2542
+ }
2543
+ switch t.Size() {
2544
+ case 8:
2545
+ return v.Reg()
2546
+ }
2547
+ panic("unreachable")
2548
+ }
2549
+
2550
+ // XXX k mask + vec
2551
+ func simdOrMaskReg(v *ssa.Value) int16 {
2552
+ t := v.Type
2553
+ if t.Size() <= 8 {
2554
+ return maskReg(v)
2555
+ }
2556
+ return simdReg(v)
2557
+ }
2558
+
2559
+ // XXX this is used for shift operations only.
2560
+ // regalloc will issue OpCopy with incorrect type, but the assigned
2561
+ // register should be correct, and this function is merely checking
2562
+ // the sanity of this part.
2563
+ func simdCheckRegOnly(v *ssa.Value, regStart, regEnd int16) int16 {
2564
+ if v.Reg() > regEnd || v.Reg() < regStart {
2565
+ panic("simdCheckRegOnly: not the desired register")
2566
+ }
2567
+ return v.Reg()
2568
+ }
go/src/cmd/compile/internal/amd64/versions_test.go ADDED
@@ -0,0 +1,434 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2021 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
+ // When using GOEXPERIMENT=boringcrypto, the test program links in the boringcrypto syso,
6
+ // which does not respect GOAMD64, so we skip the test if boringcrypto is enabled.
7
+ //go:build !boringcrypto
8
+
9
+ package amd64_test
10
+
11
+ import (
12
+ "bufio"
13
+ "debug/elf"
14
+ "debug/macho"
15
+ "errors"
16
+ "fmt"
17
+ "go/build"
18
+ "internal/testenv"
19
+ "io"
20
+ "math"
21
+ "math/bits"
22
+ "os"
23
+ "os/exec"
24
+ "regexp"
25
+ "runtime"
26
+ "strconv"
27
+ "strings"
28
+ "testing"
29
+ )
30
+
31
+ // Test to make sure that when building for GOAMD64=v1, we don't
32
+ // use any >v1 instructions.
33
+ func TestGoAMD64v1(t *testing.T) {
34
+ if runtime.GOARCH != "amd64" {
35
+ t.Skip("amd64-only test")
36
+ }
37
+ if runtime.GOOS != "linux" && runtime.GOOS != "darwin" {
38
+ t.Skip("test only works on elf or macho platforms")
39
+ }
40
+ for _, tag := range build.Default.ToolTags {
41
+ if tag == "amd64.v2" {
42
+ t.Skip("compiling for GOAMD64=v2 or higher")
43
+ }
44
+ }
45
+ if os.Getenv("TESTGOAMD64V1") != "" {
46
+ t.Skip("recursive call")
47
+ }
48
+
49
+ // Make a binary which will be a modified version of the
50
+ // currently running binary.
51
+ dst, err := os.CreateTemp("", "TestGoAMD64v1")
52
+ if err != nil {
53
+ t.Fatalf("failed to create temp file: %v", err)
54
+ }
55
+ defer os.Remove(dst.Name())
56
+ dst.Chmod(0500) // make executable
57
+
58
+ // Clobber all the non-v1 opcodes.
59
+ opcodes := map[string]bool{}
60
+ var features []string
61
+ for feature, opcodeList := range featureToOpcodes {
62
+ if runtimeFeatures[feature] {
63
+ features = append(features, fmt.Sprintf("cpu.%s=off", feature))
64
+ }
65
+ for _, op := range opcodeList {
66
+ opcodes[op] = true
67
+ }
68
+ }
69
+ clobber(t, os.Args[0], dst, opcodes)
70
+ if err = dst.Close(); err != nil {
71
+ t.Fatalf("can't close binary: %v", err)
72
+ }
73
+
74
+ // Run the resulting binary.
75
+ cmd := testenv.Command(t, dst.Name())
76
+ testenv.CleanCmdEnv(cmd)
77
+ cmd.Env = append(cmd.Env, "TESTGOAMD64V1=yes")
78
+ // Disable FIPS 140-3 mode, since it would detect the modified binary.
79
+ cmd.Env = append(cmd.Env, fmt.Sprintf("GODEBUG=%s,fips140=off", strings.Join(features, ",")))
80
+ out, err := cmd.CombinedOutput()
81
+ if err != nil {
82
+ t.Fatalf("couldn't execute test: %s\n%s", err, out)
83
+ }
84
+ // Expect to see output of the form "PASS\n", unless the test binary
85
+ // was compiled for coverage (in which case there will be an extra line).
86
+ success := false
87
+ lines := strings.Split(string(out), "\n")
88
+ if len(lines) == 2 {
89
+ success = lines[0] == "PASS" && lines[1] == ""
90
+ } else if len(lines) == 3 {
91
+ success = lines[0] == "PASS" &&
92
+ strings.HasPrefix(lines[1], "coverage") && lines[2] == ""
93
+ }
94
+ if !success {
95
+ t.Fatalf("test reported error: %s lines=%+v", string(out), lines)
96
+ }
97
+ }
98
+
99
+ // Clobber copies the binary src to dst, replacing all the instructions in opcodes with
100
+ // faulting instructions.
101
+ func clobber(t *testing.T, src string, dst *os.File, opcodes map[string]bool) {
102
+ // Run objdump to get disassembly.
103
+ var re *regexp.Regexp
104
+ var disasm io.Reader
105
+ if false {
106
+ // TODO: go tool objdump doesn't disassemble the bmi1 instructions
107
+ // in question correctly. See issue 48584.
108
+ cmd := testenv.Command(t, "go", "tool", "objdump", src)
109
+ var err error
110
+ disasm, err = cmd.StdoutPipe()
111
+ if err != nil {
112
+ t.Fatal(err)
113
+ }
114
+ if err := cmd.Start(); err != nil {
115
+ t.Fatal(err)
116
+ }
117
+ t.Cleanup(func() {
118
+ if err := cmd.Wait(); err != nil {
119
+ t.Error(err)
120
+ }
121
+ })
122
+ re = regexp.MustCompile(`^[^:]*:[-\d]+\s+0x([\da-f]+)\s+([\da-f]+)\s+([A-Z]+)`)
123
+ } else {
124
+ // TODO: we're depending on platform-native objdump here. Hence the Skipf
125
+ // below if it doesn't run for some reason.
126
+ cmd := testenv.Command(t, "objdump", "-d", src)
127
+ var err error
128
+ disasm, err = cmd.StdoutPipe()
129
+ if err != nil {
130
+ t.Fatal(err)
131
+ }
132
+ if err := cmd.Start(); err != nil {
133
+ if errors.Is(err, exec.ErrNotFound) {
134
+ t.Skipf("can't run test due to missing objdump: %s", err)
135
+ }
136
+ t.Fatal(err)
137
+ }
138
+ t.Cleanup(func() {
139
+ if err := cmd.Wait(); err != nil {
140
+ t.Error(err)
141
+ }
142
+ })
143
+ re = regexp.MustCompile(`^\s*([\da-f]+):\s*((?:[\da-f][\da-f] )+)\s*([a-z\d]+)`)
144
+ }
145
+
146
+ // Find all the instruction addresses we need to edit.
147
+ virtualEdits := map[uint64]bool{}
148
+ scanner := bufio.NewScanner(disasm)
149
+ for scanner.Scan() {
150
+ line := scanner.Text()
151
+ parts := re.FindStringSubmatch(line)
152
+ if len(parts) == 0 {
153
+ continue
154
+ }
155
+ addr, err := strconv.ParseUint(parts[1], 16, 64)
156
+ if err != nil {
157
+ continue // not a hex address
158
+ }
159
+ opcode := strings.ToLower(parts[3])
160
+ if !opcodes[opcode] {
161
+ continue
162
+ }
163
+ t.Logf("clobbering instruction %s", line)
164
+ n := (len(parts[2]) - strings.Count(parts[2], " ")) / 2 // number of bytes in instruction encoding
165
+ for i := 0; i < n; i++ {
166
+ // Only really need to make the first byte faulting, but might
167
+ // as well make all the bytes faulting.
168
+ virtualEdits[addr+uint64(i)] = true
169
+ }
170
+ }
171
+
172
+ // Figure out where in the binary the edits must be done.
173
+ physicalEdits := map[uint64]bool{}
174
+ if e, err := elf.Open(src); err == nil {
175
+ for _, sec := range e.Sections {
176
+ vaddr := sec.Addr
177
+ paddr := sec.Offset
178
+ size := sec.Size
179
+ for a := range virtualEdits {
180
+ if a >= vaddr && a < vaddr+size {
181
+ physicalEdits[paddr+(a-vaddr)] = true
182
+ }
183
+ }
184
+ }
185
+ } else if m, err2 := macho.Open(src); err2 == nil {
186
+ for _, sec := range m.Sections {
187
+ vaddr := sec.Addr
188
+ paddr := uint64(sec.Offset)
189
+ size := sec.Size
190
+ for a := range virtualEdits {
191
+ if a >= vaddr && a < vaddr+size {
192
+ physicalEdits[paddr+(a-vaddr)] = true
193
+ }
194
+ }
195
+ }
196
+ } else {
197
+ t.Log(err)
198
+ t.Log(err2)
199
+ t.Fatal("executable format not elf or macho")
200
+ }
201
+ if len(virtualEdits) != len(physicalEdits) {
202
+ t.Fatal("couldn't find an instruction in text sections")
203
+ }
204
+
205
+ // Copy source to destination, making edits along the way.
206
+ f, err := os.Open(src)
207
+ if err != nil {
208
+ t.Fatal(err)
209
+ }
210
+ r := bufio.NewReader(f)
211
+ w := bufio.NewWriter(dst)
212
+ a := uint64(0)
213
+ done := 0
214
+ for {
215
+ b, err := r.ReadByte()
216
+ if err == io.EOF {
217
+ break
218
+ }
219
+ if err != nil {
220
+ t.Fatal("can't read")
221
+ }
222
+ if physicalEdits[a] {
223
+ b = 0xcc // INT3 opcode
224
+ done++
225
+ }
226
+ err = w.WriteByte(b)
227
+ if err != nil {
228
+ t.Fatal("can't write")
229
+ }
230
+ a++
231
+ }
232
+ if done != len(physicalEdits) {
233
+ t.Fatal("physical edits remaining")
234
+ }
235
+ w.Flush()
236
+ f.Close()
237
+ }
238
+
239
+ func setOf(keys ...string) map[string]bool {
240
+ m := make(map[string]bool, len(keys))
241
+ for _, key := range keys {
242
+ m[key] = true
243
+ }
244
+ return m
245
+ }
246
+
247
+ var runtimeFeatures = setOf(
248
+ "adx", "aes", "avx", "avx2", "bmi1", "bmi2", "erms", "fma",
249
+ "pclmulqdq", "popcnt", "rdtscp", "sse3", "sse41", "sse42", "ssse3",
250
+ )
251
+
252
+ var featureToOpcodes = map[string][]string{
253
+ // Note: we include *q, *l, and plain opcodes here.
254
+ // go tool objdump doesn't include a [QL] on popcnt instructions, until CL 351889
255
+ // native objdump doesn't include [QL] on linux.
256
+ "popcnt": {"popcntq", "popcntl", "popcnt"},
257
+ "bmi1": {
258
+ "andnq", "andnl", "andn",
259
+ "blsiq", "blsil", "blsi",
260
+ "blsmskq", "blsmskl", "blsmsk",
261
+ "blsrq", "blsrl", "blsr",
262
+ "tzcntq", "tzcntl", "tzcnt",
263
+ },
264
+ "bmi2": {
265
+ "sarxq", "sarxl", "sarx",
266
+ "shlxq", "shlxl", "shlx",
267
+ "shrxq", "shrxl", "shrx",
268
+ },
269
+ "sse41": {
270
+ "roundsd",
271
+ "pinsrq", "pinsrl", "pinsrd", "pinsrb", "pinsr",
272
+ "pextrq", "pextrl", "pextrd", "pextrb", "pextr",
273
+ "pminsb", "pminsd", "pminuw", "pminud", // Note: ub and sw are ok.
274
+ "pmaxsb", "pmaxsd", "pmaxuw", "pmaxud",
275
+ "pmovzxbw", "pmovzxbd", "pmovzxbq", "pmovzxwd", "pmovzxwq", "pmovzxdq",
276
+ "pmovsxbw", "pmovsxbd", "pmovsxbq", "pmovsxwd", "pmovsxwq", "pmovsxdq",
277
+ "pblendvb",
278
+ },
279
+ "fma": {"vfmadd231sd"},
280
+ "movbe": {"movbeqq", "movbeq", "movbell", "movbel", "movbe"},
281
+ "lzcnt": {"lzcntq", "lzcntl", "lzcnt"},
282
+ }
283
+
284
+ // Test to use POPCNT instruction, if available
285
+ func TestPopCnt(t *testing.T) {
286
+ for _, tt := range []struct {
287
+ x uint64
288
+ want int
289
+ }{
290
+ {0b00001111, 4},
291
+ {0b00001110, 3},
292
+ {0b00001100, 2},
293
+ {0b00000000, 0},
294
+ } {
295
+ if got := bits.OnesCount64(tt.x); got != tt.want {
296
+ t.Errorf("OnesCount64(%#x) = %d, want %d", tt.x, got, tt.want)
297
+ }
298
+ if got := bits.OnesCount32(uint32(tt.x)); got != tt.want {
299
+ t.Errorf("OnesCount32(%#x) = %d, want %d", tt.x, got, tt.want)
300
+ }
301
+ }
302
+ }
303
+
304
+ // Test to use ANDN, if available
305
+ func TestAndNot(t *testing.T) {
306
+ for _, tt := range []struct {
307
+ x, y, want uint64
308
+ }{
309
+ {0b00001111, 0b00000011, 0b1100},
310
+ {0b00001111, 0b00001100, 0b0011},
311
+ {0b00000000, 0b00000000, 0b0000},
312
+ } {
313
+ if got := tt.x &^ tt.y; got != tt.want {
314
+ t.Errorf("%#x &^ %#x = %#x, want %#x", tt.x, tt.y, got, tt.want)
315
+ }
316
+ if got := uint32(tt.x) &^ uint32(tt.y); got != uint32(tt.want) {
317
+ t.Errorf("%#x &^ %#x = %#x, want %#x", tt.x, tt.y, got, tt.want)
318
+ }
319
+ }
320
+ }
321
+
322
+ // Test to use BLSI, if available
323
+ func TestBLSI(t *testing.T) {
324
+ for _, tt := range []struct {
325
+ x, want uint64
326
+ }{
327
+ {0b00001111, 0b001},
328
+ {0b00001110, 0b010},
329
+ {0b00001100, 0b100},
330
+ {0b11000110, 0b010},
331
+ {0b00000000, 0b000},
332
+ } {
333
+ if got := tt.x & -tt.x; got != tt.want {
334
+ t.Errorf("%#x & (-%#x) = %#x, want %#x", tt.x, tt.x, got, tt.want)
335
+ }
336
+ if got := uint32(tt.x) & -uint32(tt.x); got != uint32(tt.want) {
337
+ t.Errorf("%#x & (-%#x) = %#x, want %#x", tt.x, tt.x, got, tt.want)
338
+ }
339
+ }
340
+ }
341
+
342
+ // Test to use BLSMSK, if available
343
+ func TestBLSMSK(t *testing.T) {
344
+ for _, tt := range []struct {
345
+ x, want uint64
346
+ }{
347
+ {0b00001111, 0b001},
348
+ {0b00001110, 0b011},
349
+ {0b00001100, 0b111},
350
+ {0b11000110, 0b011},
351
+ {0b00000000, 1<<64 - 1},
352
+ } {
353
+ if got := tt.x ^ (tt.x - 1); got != tt.want {
354
+ t.Errorf("%#x ^ (%#x-1) = %#x, want %#x", tt.x, tt.x, got, tt.want)
355
+ }
356
+ if got := uint32(tt.x) ^ (uint32(tt.x) - 1); got != uint32(tt.want) {
357
+ t.Errorf("%#x ^ (%#x-1) = %#x, want %#x", tt.x, tt.x, got, uint32(tt.want))
358
+ }
359
+ }
360
+ }
361
+
362
+ // Test to use BLSR, if available
363
+ func TestBLSR(t *testing.T) {
364
+ for _, tt := range []struct {
365
+ x, want uint64
366
+ }{
367
+ {0b00001111, 0b00001110},
368
+ {0b00001110, 0b00001100},
369
+ {0b00001100, 0b00001000},
370
+ {0b11000110, 0b11000100},
371
+ {0b00000000, 0b00000000},
372
+ } {
373
+ if got := tt.x & (tt.x - 1); got != tt.want {
374
+ t.Errorf("%#x & (%#x-1) = %#x, want %#x", tt.x, tt.x, got, tt.want)
375
+ }
376
+ if got := uint32(tt.x) & (uint32(tt.x) - 1); got != uint32(tt.want) {
377
+ t.Errorf("%#x & (%#x-1) = %#x, want %#x", tt.x, tt.x, got, tt.want)
378
+ }
379
+ }
380
+ }
381
+
382
+ func TestTrailingZeros(t *testing.T) {
383
+ for _, tt := range []struct {
384
+ x uint64
385
+ want int
386
+ }{
387
+ {0b00001111, 0},
388
+ {0b00001110, 1},
389
+ {0b00001100, 2},
390
+ {0b00001000, 3},
391
+ {0b00000000, 64},
392
+ } {
393
+ if got := bits.TrailingZeros64(tt.x); got != tt.want {
394
+ t.Errorf("TrailingZeros64(%#x) = %d, want %d", tt.x, got, tt.want)
395
+ }
396
+ want := tt.want
397
+ if want == 64 {
398
+ want = 32
399
+ }
400
+ if got := bits.TrailingZeros32(uint32(tt.x)); got != want {
401
+ t.Errorf("TrailingZeros64(%#x) = %d, want %d", tt.x, got, want)
402
+ }
403
+ }
404
+ }
405
+
406
+ func TestRound(t *testing.T) {
407
+ for _, tt := range []struct {
408
+ x, want float64
409
+ }{
410
+ {1.4, 1},
411
+ {1.5, 2},
412
+ {1.6, 2},
413
+ {2.4, 2},
414
+ {2.5, 2},
415
+ {2.6, 3},
416
+ } {
417
+ if got := math.RoundToEven(tt.x); got != tt.want {
418
+ t.Errorf("RoundToEven(%f) = %f, want %f", tt.x, got, tt.want)
419
+ }
420
+ }
421
+ }
422
+
423
+ func TestFMA(t *testing.T) {
424
+ for _, tt := range []struct {
425
+ x, y, z, want float64
426
+ }{
427
+ {2, 3, 4, 10},
428
+ {3, 4, 5, 17},
429
+ } {
430
+ if got := math.FMA(tt.x, tt.y, tt.z); got != tt.want {
431
+ t.Errorf("FMA(%f,%f,%f) = %f, want %f", tt.x, tt.y, tt.z, got, tt.want)
432
+ }
433
+ }
434
+ }
go/src/cmd/compile/internal/arm/galign.go ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2009 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 arm
6
+
7
+ import (
8
+ "cmd/compile/internal/ssa"
9
+ "cmd/compile/internal/ssagen"
10
+ "cmd/internal/obj/arm"
11
+ "internal/buildcfg"
12
+ )
13
+
14
+ func Init(arch *ssagen.ArchInfo) {
15
+ arch.LinkArch = &arm.Linkarm
16
+ arch.REGSP = arm.REGSP
17
+ arch.MAXWIDTH = (1 << 32) - 1
18
+ arch.SoftFloat = buildcfg.GOARM.SoftFloat
19
+ arch.ZeroRange = zerorange
20
+ arch.Ginsnop = ginsnop
21
+
22
+ arch.SSAMarkMoves = func(s *ssagen.State, b *ssa.Block) {}
23
+ arch.SSAGenValue = ssaGenValue
24
+ arch.SSAGenBlock = ssaGenBlock
25
+ }
go/src/cmd/compile/internal/arm/ggen.go ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2009 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 arm
6
+
7
+ import (
8
+ "cmd/compile/internal/ir"
9
+ "cmd/compile/internal/objw"
10
+ "cmd/compile/internal/types"
11
+ "cmd/internal/obj"
12
+ "cmd/internal/obj/arm"
13
+ )
14
+
15
+ func zerorange(pp *objw.Progs, p *obj.Prog, off, cnt int64, r0 *uint32) *obj.Prog {
16
+ if cnt == 0 {
17
+ return p
18
+ }
19
+ if *r0 == 0 {
20
+ p = pp.Append(p, arm.AMOVW, obj.TYPE_CONST, 0, 0, obj.TYPE_REG, arm.REG_R0, 0)
21
+ *r0 = 1
22
+ }
23
+
24
+ if cnt < int64(4*types.PtrSize) {
25
+ for i := int64(0); i < cnt; i += int64(types.PtrSize) {
26
+ p = pp.Append(p, arm.AMOVW, obj.TYPE_REG, arm.REG_R0, 0, obj.TYPE_MEM, arm.REGSP, 4+off+i)
27
+ }
28
+ } else if cnt <= int64(128*types.PtrSize) {
29
+ p = pp.Append(p, arm.AADD, obj.TYPE_CONST, 0, 4+off, obj.TYPE_REG, arm.REG_R1, 0)
30
+ p.Reg = arm.REGSP
31
+ p = pp.Append(p, obj.ADUFFZERO, obj.TYPE_NONE, 0, 0, obj.TYPE_MEM, 0, 0)
32
+ p.To.Name = obj.NAME_EXTERN
33
+ p.To.Sym = ir.Syms.Duffzero
34
+ p.To.Offset = 4 * (128 - cnt/int64(types.PtrSize))
35
+ } else {
36
+ p = pp.Append(p, arm.AADD, obj.TYPE_CONST, 0, 4+off, obj.TYPE_REG, arm.REG_R1, 0)
37
+ p.Reg = arm.REGSP
38
+ p = pp.Append(p, arm.AADD, obj.TYPE_CONST, 0, cnt, obj.TYPE_REG, arm.REG_R2, 0)
39
+ p.Reg = arm.REG_R1
40
+ p = pp.Append(p, arm.AMOVW, obj.TYPE_REG, arm.REG_R0, 0, obj.TYPE_MEM, arm.REG_R1, 4)
41
+ p1 := p
42
+ p.Scond |= arm.C_PBIT
43
+ p = pp.Append(p, arm.ACMP, obj.TYPE_REG, arm.REG_R1, 0, obj.TYPE_NONE, 0, 0)
44
+ p.Reg = arm.REG_R2
45
+ p = pp.Append(p, arm.ABNE, obj.TYPE_NONE, 0, 0, obj.TYPE_BRANCH, 0, 0)
46
+ p.To.SetTarget(p1)
47
+ }
48
+
49
+ return p
50
+ }
51
+
52
+ func ginsnop(pp *objw.Progs) *obj.Prog {
53
+ p := pp.Prog(arm.AAND)
54
+ p.From.Type = obj.TYPE_REG
55
+ p.From.Reg = arm.REG_R0
56
+ p.To.Type = obj.TYPE_REG
57
+ p.To.Reg = arm.REG_R0
58
+ p.Scond = arm.C_SCOND_EQ
59
+ return p
60
+ }
go/src/cmd/compile/internal/arm/ssa.go ADDED
@@ -0,0 +1,1115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2016 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 arm
6
+
7
+ import (
8
+ "fmt"
9
+ "internal/buildcfg"
10
+ "math"
11
+ "math/bits"
12
+
13
+ "cmd/compile/internal/base"
14
+ "cmd/compile/internal/ir"
15
+ "cmd/compile/internal/logopt"
16
+ "cmd/compile/internal/ssa"
17
+ "cmd/compile/internal/ssagen"
18
+ "cmd/compile/internal/types"
19
+ "cmd/internal/obj"
20
+ "cmd/internal/obj/arm"
21
+ "internal/abi"
22
+ )
23
+
24
+ // loadByType returns the load instruction of the given type.
25
+ func loadByType(t *types.Type) obj.As {
26
+ if t.IsFloat() {
27
+ switch t.Size() {
28
+ case 4:
29
+ return arm.AMOVF
30
+ case 8:
31
+ return arm.AMOVD
32
+ }
33
+ } else {
34
+ switch t.Size() {
35
+ case 1:
36
+ if t.IsSigned() {
37
+ return arm.AMOVB
38
+ } else {
39
+ return arm.AMOVBU
40
+ }
41
+ case 2:
42
+ if t.IsSigned() {
43
+ return arm.AMOVH
44
+ } else {
45
+ return arm.AMOVHU
46
+ }
47
+ case 4:
48
+ return arm.AMOVW
49
+ }
50
+ }
51
+ panic("bad load type")
52
+ }
53
+
54
+ // storeByType returns the store instruction of the given type.
55
+ func storeByType(t *types.Type) obj.As {
56
+ if t.IsFloat() {
57
+ switch t.Size() {
58
+ case 4:
59
+ return arm.AMOVF
60
+ case 8:
61
+ return arm.AMOVD
62
+ }
63
+ } else {
64
+ switch t.Size() {
65
+ case 1:
66
+ return arm.AMOVB
67
+ case 2:
68
+ return arm.AMOVH
69
+ case 4:
70
+ return arm.AMOVW
71
+ }
72
+ }
73
+ panic("bad store type")
74
+ }
75
+
76
+ // shift type is used as Offset in obj.TYPE_SHIFT operands to encode shifted register operands.
77
+ type shift int64
78
+
79
+ // copied from ../../../internal/obj/util.go:/TYPE_SHIFT
80
+ func (v shift) String() string {
81
+ op := "<<>>->@>"[((v>>5)&3)<<1:]
82
+ if v&(1<<4) != 0 {
83
+ // register shift
84
+ return fmt.Sprintf("R%d%c%cR%d", v&15, op[0], op[1], (v>>8)&15)
85
+ } else {
86
+ // constant shift
87
+ return fmt.Sprintf("R%d%c%c%d", v&15, op[0], op[1], (v>>7)&31)
88
+ }
89
+ }
90
+
91
+ // makeshift encodes a register shifted by a constant.
92
+ func makeshift(v *ssa.Value, reg int16, typ int64, s int64) shift {
93
+ if s < 0 || s >= 32 {
94
+ v.Fatalf("shift out of range: %d", s)
95
+ }
96
+ return shift(int64(reg&0xf) | typ | (s&31)<<7)
97
+ }
98
+
99
+ // genshift generates a Prog for r = r0 op (r1 shifted by n).
100
+ func genshift(s *ssagen.State, v *ssa.Value, as obj.As, r0, r1, r int16, typ int64, n int64) *obj.Prog {
101
+ p := s.Prog(as)
102
+ p.From.Type = obj.TYPE_SHIFT
103
+ p.From.Offset = int64(makeshift(v, r1, typ, n))
104
+ p.Reg = r0
105
+ if r != 0 {
106
+ p.To.Type = obj.TYPE_REG
107
+ p.To.Reg = r
108
+ }
109
+ return p
110
+ }
111
+
112
+ // makeregshift encodes a register shifted by a register.
113
+ func makeregshift(r1 int16, typ int64, r2 int16) shift {
114
+ return shift(int64(r1&0xf) | typ | int64(r2&0xf)<<8 | 1<<4)
115
+ }
116
+
117
+ // genregshift generates a Prog for r = r0 op (r1 shifted by r2).
118
+ func genregshift(s *ssagen.State, as obj.As, r0, r1, r2, r int16, typ int64) *obj.Prog {
119
+ p := s.Prog(as)
120
+ p.From.Type = obj.TYPE_SHIFT
121
+ p.From.Offset = int64(makeregshift(r1, typ, r2))
122
+ p.Reg = r0
123
+ if r != 0 {
124
+ p.To.Type = obj.TYPE_REG
125
+ p.To.Reg = r
126
+ }
127
+ return p
128
+ }
129
+
130
+ // find a (lsb, width) pair for BFC
131
+ // lsb must be in [0, 31], width must be in [1, 32 - lsb]
132
+ // return (0xffffffff, 0) if v is not a binary like 0...01...10...0
133
+ func getBFC(v uint32) (uint32, uint32) {
134
+ var m, l uint32
135
+ // BFC is not applicable with zero
136
+ if v == 0 {
137
+ return 0xffffffff, 0
138
+ }
139
+ // find the lowest set bit, for example l=2 for 0x3ffffffc
140
+ l = uint32(bits.TrailingZeros32(v))
141
+ // m-1 represents the highest set bit index, for example m=30 for 0x3ffffffc
142
+ m = 32 - uint32(bits.LeadingZeros32(v))
143
+ // check if v is a binary like 0...01...10...0
144
+ if (1<<m)-(1<<l) == v {
145
+ // it must be m > l for non-zero v
146
+ return l, m - l
147
+ }
148
+ // invalid
149
+ return 0xffffffff, 0
150
+ }
151
+
152
+ func ssaGenValue(s *ssagen.State, v *ssa.Value) {
153
+ switch v.Op {
154
+ case ssa.OpCopy, ssa.OpARMMOVWreg:
155
+ if v.Type.IsMemory() {
156
+ return
157
+ }
158
+ x := v.Args[0].Reg()
159
+ y := v.Reg()
160
+ if x == y {
161
+ return
162
+ }
163
+ as := arm.AMOVW
164
+ if v.Type.IsFloat() {
165
+ switch v.Type.Size() {
166
+ case 4:
167
+ as = arm.AMOVF
168
+ case 8:
169
+ as = arm.AMOVD
170
+ default:
171
+ panic("bad float size")
172
+ }
173
+ }
174
+ p := s.Prog(as)
175
+ p.From.Type = obj.TYPE_REG
176
+ p.From.Reg = x
177
+ p.To.Type = obj.TYPE_REG
178
+ p.To.Reg = y
179
+ case ssa.OpARMMOVWnop:
180
+ // nothing to do
181
+ case ssa.OpLoadReg:
182
+ if v.Type.IsFlags() {
183
+ v.Fatalf("load flags not implemented: %v", v.LongString())
184
+ return
185
+ }
186
+ p := s.Prog(loadByType(v.Type))
187
+ ssagen.AddrAuto(&p.From, v.Args[0])
188
+ p.To.Type = obj.TYPE_REG
189
+ p.To.Reg = v.Reg()
190
+ case ssa.OpStoreReg:
191
+ if v.Type.IsFlags() {
192
+ v.Fatalf("store flags not implemented: %v", v.LongString())
193
+ return
194
+ }
195
+ p := s.Prog(storeByType(v.Type))
196
+ p.From.Type = obj.TYPE_REG
197
+ p.From.Reg = v.Args[0].Reg()
198
+ ssagen.AddrAuto(&p.To, v)
199
+ case ssa.OpARMADD,
200
+ ssa.OpARMADC,
201
+ ssa.OpARMSUB,
202
+ ssa.OpARMSBC,
203
+ ssa.OpARMRSB,
204
+ ssa.OpARMAND,
205
+ ssa.OpARMOR,
206
+ ssa.OpARMXOR,
207
+ ssa.OpARMBIC,
208
+ ssa.OpARMMUL,
209
+ ssa.OpARMADDF,
210
+ ssa.OpARMADDD,
211
+ ssa.OpARMSUBF,
212
+ ssa.OpARMSUBD,
213
+ ssa.OpARMSLL,
214
+ ssa.OpARMSRL,
215
+ ssa.OpARMSRA,
216
+ ssa.OpARMMULF,
217
+ ssa.OpARMMULD,
218
+ ssa.OpARMNMULF,
219
+ ssa.OpARMNMULD,
220
+ ssa.OpARMDIVF,
221
+ ssa.OpARMDIVD:
222
+ r := v.Reg()
223
+ r1 := v.Args[0].Reg()
224
+ r2 := v.Args[1].Reg()
225
+ p := s.Prog(v.Op.Asm())
226
+ p.From.Type = obj.TYPE_REG
227
+ p.From.Reg = r2
228
+ p.Reg = r1
229
+ p.To.Type = obj.TYPE_REG
230
+ p.To.Reg = r
231
+ case ssa.OpARMSRR:
232
+ genregshift(s, arm.AMOVW, 0, v.Args[0].Reg(), v.Args[1].Reg(), v.Reg(), arm.SHIFT_RR)
233
+ case ssa.OpARMMULAF, ssa.OpARMMULAD, ssa.OpARMMULSF, ssa.OpARMMULSD, ssa.OpARMFMULAD:
234
+ r := v.Reg()
235
+ r0 := v.Args[0].Reg()
236
+ r1 := v.Args[1].Reg()
237
+ r2 := v.Args[2].Reg()
238
+ if r != r0 {
239
+ v.Fatalf("result and addend are not in the same register: %v", v.LongString())
240
+ }
241
+ p := s.Prog(v.Op.Asm())
242
+ p.From.Type = obj.TYPE_REG
243
+ p.From.Reg = r2
244
+ p.Reg = r1
245
+ p.To.Type = obj.TYPE_REG
246
+ p.To.Reg = r
247
+ case ssa.OpARMADDS,
248
+ ssa.OpARMADCS,
249
+ ssa.OpARMSUBS:
250
+ r := v.Reg0()
251
+ r1 := v.Args[0].Reg()
252
+ r2 := v.Args[1].Reg()
253
+ p := s.Prog(v.Op.Asm())
254
+ p.Scond = arm.C_SBIT
255
+ p.From.Type = obj.TYPE_REG
256
+ p.From.Reg = r2
257
+ p.Reg = r1
258
+ p.To.Type = obj.TYPE_REG
259
+ p.To.Reg = r
260
+ case ssa.OpARMSRAcond:
261
+ // ARM shift instructions uses only the low-order byte of the shift amount
262
+ // generate conditional instructions to deal with large shifts
263
+ // flag is already set
264
+ // SRA.HS $31, Rarg0, Rdst // shift 31 bits to get the sign bit
265
+ // SRA.LO Rarg1, Rarg0, Rdst
266
+ r := v.Reg()
267
+ r1 := v.Args[0].Reg()
268
+ r2 := v.Args[1].Reg()
269
+ p := s.Prog(arm.ASRA)
270
+ p.Scond = arm.C_SCOND_HS
271
+ p.From.Type = obj.TYPE_CONST
272
+ p.From.Offset = 31
273
+ p.Reg = r1
274
+ p.To.Type = obj.TYPE_REG
275
+ p.To.Reg = r
276
+ p = s.Prog(arm.ASRA)
277
+ p.Scond = arm.C_SCOND_LO
278
+ p.From.Type = obj.TYPE_REG
279
+ p.From.Reg = r2
280
+ p.Reg = r1
281
+ p.To.Type = obj.TYPE_REG
282
+ p.To.Reg = r
283
+ case ssa.OpARMBFX, ssa.OpARMBFXU:
284
+ p := s.Prog(v.Op.Asm())
285
+ p.From.Type = obj.TYPE_CONST
286
+ p.From.Offset = v.AuxInt >> 8
287
+ p.AddRestSourceConst(v.AuxInt & 0xff)
288
+ p.Reg = v.Args[0].Reg()
289
+ p.To.Type = obj.TYPE_REG
290
+ p.To.Reg = v.Reg()
291
+ case ssa.OpARMANDconst, ssa.OpARMBICconst:
292
+ // try to optimize ANDconst and BICconst to BFC, which saves bytes and ticks
293
+ // BFC is only available on ARMv7, and its result and source are in the same register
294
+ if buildcfg.GOARM.Version == 7 && v.Reg() == v.Args[0].Reg() {
295
+ var val uint32
296
+ if v.Op == ssa.OpARMANDconst {
297
+ val = ^uint32(v.AuxInt)
298
+ } else { // BICconst
299
+ val = uint32(v.AuxInt)
300
+ }
301
+ lsb, width := getBFC(val)
302
+ // omit BFC for ARM's imm12
303
+ if 8 < width && width < 24 {
304
+ p := s.Prog(arm.ABFC)
305
+ p.From.Type = obj.TYPE_CONST
306
+ p.From.Offset = int64(width)
307
+ p.AddRestSourceConst(int64(lsb))
308
+ p.To.Type = obj.TYPE_REG
309
+ p.To.Reg = v.Reg()
310
+ break
311
+ }
312
+ }
313
+ // fall back to ordinary form
314
+ fallthrough
315
+ case ssa.OpARMADDconst,
316
+ ssa.OpARMADCconst,
317
+ ssa.OpARMSUBconst,
318
+ ssa.OpARMSBCconst,
319
+ ssa.OpARMRSBconst,
320
+ ssa.OpARMRSCconst,
321
+ ssa.OpARMORconst,
322
+ ssa.OpARMXORconst,
323
+ ssa.OpARMSLLconst,
324
+ ssa.OpARMSRLconst,
325
+ ssa.OpARMSRAconst:
326
+ p := s.Prog(v.Op.Asm())
327
+ p.From.Type = obj.TYPE_CONST
328
+ p.From.Offset = v.AuxInt
329
+ p.Reg = v.Args[0].Reg()
330
+ p.To.Type = obj.TYPE_REG
331
+ p.To.Reg = v.Reg()
332
+ case ssa.OpARMADDSconst,
333
+ ssa.OpARMSUBSconst,
334
+ ssa.OpARMRSBSconst:
335
+ p := s.Prog(v.Op.Asm())
336
+ p.Scond = arm.C_SBIT
337
+ p.From.Type = obj.TYPE_CONST
338
+ p.From.Offset = v.AuxInt
339
+ p.Reg = v.Args[0].Reg()
340
+ p.To.Type = obj.TYPE_REG
341
+ p.To.Reg = v.Reg0()
342
+ case ssa.OpARMSRRconst:
343
+ genshift(s, v, arm.AMOVW, 0, v.Args[0].Reg(), v.Reg(), arm.SHIFT_RR, v.AuxInt)
344
+ case ssa.OpARMADDshiftLL,
345
+ ssa.OpARMADCshiftLL,
346
+ ssa.OpARMSUBshiftLL,
347
+ ssa.OpARMSBCshiftLL,
348
+ ssa.OpARMRSBshiftLL,
349
+ ssa.OpARMRSCshiftLL,
350
+ ssa.OpARMANDshiftLL,
351
+ ssa.OpARMORshiftLL,
352
+ ssa.OpARMXORshiftLL,
353
+ ssa.OpARMBICshiftLL:
354
+ genshift(s, v, v.Op.Asm(), v.Args[0].Reg(), v.Args[1].Reg(), v.Reg(), arm.SHIFT_LL, v.AuxInt)
355
+ case ssa.OpARMADDSshiftLL,
356
+ ssa.OpARMSUBSshiftLL,
357
+ ssa.OpARMRSBSshiftLL:
358
+ p := genshift(s, v, v.Op.Asm(), v.Args[0].Reg(), v.Args[1].Reg(), v.Reg0(), arm.SHIFT_LL, v.AuxInt)
359
+ p.Scond = arm.C_SBIT
360
+ case ssa.OpARMADDshiftRL,
361
+ ssa.OpARMADCshiftRL,
362
+ ssa.OpARMSUBshiftRL,
363
+ ssa.OpARMSBCshiftRL,
364
+ ssa.OpARMRSBshiftRL,
365
+ ssa.OpARMRSCshiftRL,
366
+ ssa.OpARMANDshiftRL,
367
+ ssa.OpARMORshiftRL,
368
+ ssa.OpARMXORshiftRL,
369
+ ssa.OpARMBICshiftRL:
370
+ genshift(s, v, v.Op.Asm(), v.Args[0].Reg(), v.Args[1].Reg(), v.Reg(), arm.SHIFT_LR, v.AuxInt)
371
+ case ssa.OpARMADDSshiftRL,
372
+ ssa.OpARMSUBSshiftRL,
373
+ ssa.OpARMRSBSshiftRL:
374
+ p := genshift(s, v, v.Op.Asm(), v.Args[0].Reg(), v.Args[1].Reg(), v.Reg0(), arm.SHIFT_LR, v.AuxInt)
375
+ p.Scond = arm.C_SBIT
376
+ case ssa.OpARMADDshiftRA,
377
+ ssa.OpARMADCshiftRA,
378
+ ssa.OpARMSUBshiftRA,
379
+ ssa.OpARMSBCshiftRA,
380
+ ssa.OpARMRSBshiftRA,
381
+ ssa.OpARMRSCshiftRA,
382
+ ssa.OpARMANDshiftRA,
383
+ ssa.OpARMORshiftRA,
384
+ ssa.OpARMXORshiftRA,
385
+ ssa.OpARMBICshiftRA:
386
+ genshift(s, v, v.Op.Asm(), v.Args[0].Reg(), v.Args[1].Reg(), v.Reg(), arm.SHIFT_AR, v.AuxInt)
387
+ case ssa.OpARMADDSshiftRA,
388
+ ssa.OpARMSUBSshiftRA,
389
+ ssa.OpARMRSBSshiftRA:
390
+ p := genshift(s, v, v.Op.Asm(), v.Args[0].Reg(), v.Args[1].Reg(), v.Reg0(), arm.SHIFT_AR, v.AuxInt)
391
+ p.Scond = arm.C_SBIT
392
+ case ssa.OpARMXORshiftRR:
393
+ genshift(s, v, v.Op.Asm(), v.Args[0].Reg(), v.Args[1].Reg(), v.Reg(), arm.SHIFT_RR, v.AuxInt)
394
+ case ssa.OpARMMVNshiftLL:
395
+ genshift(s, v, v.Op.Asm(), 0, v.Args[0].Reg(), v.Reg(), arm.SHIFT_LL, v.AuxInt)
396
+ case ssa.OpARMMVNshiftRL:
397
+ genshift(s, v, v.Op.Asm(), 0, v.Args[0].Reg(), v.Reg(), arm.SHIFT_LR, v.AuxInt)
398
+ case ssa.OpARMMVNshiftRA:
399
+ genshift(s, v, v.Op.Asm(), 0, v.Args[0].Reg(), v.Reg(), arm.SHIFT_AR, v.AuxInt)
400
+ case ssa.OpARMMVNshiftLLreg:
401
+ genregshift(s, v.Op.Asm(), 0, v.Args[0].Reg(), v.Args[1].Reg(), v.Reg(), arm.SHIFT_LL)
402
+ case ssa.OpARMMVNshiftRLreg:
403
+ genregshift(s, v.Op.Asm(), 0, v.Args[0].Reg(), v.Args[1].Reg(), v.Reg(), arm.SHIFT_LR)
404
+ case ssa.OpARMMVNshiftRAreg:
405
+ genregshift(s, v.Op.Asm(), 0, v.Args[0].Reg(), v.Args[1].Reg(), v.Reg(), arm.SHIFT_AR)
406
+ case ssa.OpARMADDshiftLLreg,
407
+ ssa.OpARMADCshiftLLreg,
408
+ ssa.OpARMSUBshiftLLreg,
409
+ ssa.OpARMSBCshiftLLreg,
410
+ ssa.OpARMRSBshiftLLreg,
411
+ ssa.OpARMRSCshiftLLreg,
412
+ ssa.OpARMANDshiftLLreg,
413
+ ssa.OpARMORshiftLLreg,
414
+ ssa.OpARMXORshiftLLreg,
415
+ ssa.OpARMBICshiftLLreg:
416
+ genregshift(s, v.Op.Asm(), v.Args[0].Reg(), v.Args[1].Reg(), v.Args[2].Reg(), v.Reg(), arm.SHIFT_LL)
417
+ case ssa.OpARMADDSshiftLLreg,
418
+ ssa.OpARMSUBSshiftLLreg,
419
+ ssa.OpARMRSBSshiftLLreg:
420
+ p := genregshift(s, v.Op.Asm(), v.Args[0].Reg(), v.Args[1].Reg(), v.Args[2].Reg(), v.Reg0(), arm.SHIFT_LL)
421
+ p.Scond = arm.C_SBIT
422
+ case ssa.OpARMADDshiftRLreg,
423
+ ssa.OpARMADCshiftRLreg,
424
+ ssa.OpARMSUBshiftRLreg,
425
+ ssa.OpARMSBCshiftRLreg,
426
+ ssa.OpARMRSBshiftRLreg,
427
+ ssa.OpARMRSCshiftRLreg,
428
+ ssa.OpARMANDshiftRLreg,
429
+ ssa.OpARMORshiftRLreg,
430
+ ssa.OpARMXORshiftRLreg,
431
+ ssa.OpARMBICshiftRLreg:
432
+ genregshift(s, v.Op.Asm(), v.Args[0].Reg(), v.Args[1].Reg(), v.Args[2].Reg(), v.Reg(), arm.SHIFT_LR)
433
+ case ssa.OpARMADDSshiftRLreg,
434
+ ssa.OpARMSUBSshiftRLreg,
435
+ ssa.OpARMRSBSshiftRLreg:
436
+ p := genregshift(s, v.Op.Asm(), v.Args[0].Reg(), v.Args[1].Reg(), v.Args[2].Reg(), v.Reg0(), arm.SHIFT_LR)
437
+ p.Scond = arm.C_SBIT
438
+ case ssa.OpARMADDshiftRAreg,
439
+ ssa.OpARMADCshiftRAreg,
440
+ ssa.OpARMSUBshiftRAreg,
441
+ ssa.OpARMSBCshiftRAreg,
442
+ ssa.OpARMRSBshiftRAreg,
443
+ ssa.OpARMRSCshiftRAreg,
444
+ ssa.OpARMANDshiftRAreg,
445
+ ssa.OpARMORshiftRAreg,
446
+ ssa.OpARMXORshiftRAreg,
447
+ ssa.OpARMBICshiftRAreg:
448
+ genregshift(s, v.Op.Asm(), v.Args[0].Reg(), v.Args[1].Reg(), v.Args[2].Reg(), v.Reg(), arm.SHIFT_AR)
449
+ case ssa.OpARMADDSshiftRAreg,
450
+ ssa.OpARMSUBSshiftRAreg,
451
+ ssa.OpARMRSBSshiftRAreg:
452
+ p := genregshift(s, v.Op.Asm(), v.Args[0].Reg(), v.Args[1].Reg(), v.Args[2].Reg(), v.Reg0(), arm.SHIFT_AR)
453
+ p.Scond = arm.C_SBIT
454
+ case ssa.OpARMHMUL,
455
+ ssa.OpARMHMULU:
456
+ // 32-bit high multiplication
457
+ p := s.Prog(v.Op.Asm())
458
+ p.From.Type = obj.TYPE_REG
459
+ p.From.Reg = v.Args[0].Reg()
460
+ p.Reg = v.Args[1].Reg()
461
+ p.To.Type = obj.TYPE_REGREG
462
+ p.To.Reg = v.Reg()
463
+ p.To.Offset = arm.REGTMP // throw away low 32-bit into tmp register
464
+ case ssa.OpARMMULLU:
465
+ // 32-bit multiplication, results 64-bit, high 32-bit in out0, low 32-bit in out1
466
+ p := s.Prog(v.Op.Asm())
467
+ p.From.Type = obj.TYPE_REG
468
+ p.From.Reg = v.Args[0].Reg()
469
+ p.Reg = v.Args[1].Reg()
470
+ p.To.Type = obj.TYPE_REGREG
471
+ p.To.Reg = v.Reg0() // high 32-bit
472
+ p.To.Offset = int64(v.Reg1()) // low 32-bit
473
+ case ssa.OpARMMULA, ssa.OpARMMULS:
474
+ p := s.Prog(v.Op.Asm())
475
+ p.From.Type = obj.TYPE_REG
476
+ p.From.Reg = v.Args[0].Reg()
477
+ p.Reg = v.Args[1].Reg()
478
+ p.To.Type = obj.TYPE_REGREG2
479
+ p.To.Reg = v.Reg() // result
480
+ p.To.Offset = int64(v.Args[2].Reg()) // addend
481
+ case ssa.OpARMMOVWconst:
482
+ p := s.Prog(v.Op.Asm())
483
+ p.From.Type = obj.TYPE_CONST
484
+ p.From.Offset = v.AuxInt
485
+ p.To.Type = obj.TYPE_REG
486
+ p.To.Reg = v.Reg()
487
+ case ssa.OpARMMOVFconst,
488
+ ssa.OpARMMOVDconst:
489
+ p := s.Prog(v.Op.Asm())
490
+ p.From.Type = obj.TYPE_FCONST
491
+ p.From.Val = math.Float64frombits(uint64(v.AuxInt))
492
+ p.To.Type = obj.TYPE_REG
493
+ p.To.Reg = v.Reg()
494
+ case ssa.OpARMCMP,
495
+ ssa.OpARMCMN,
496
+ ssa.OpARMTST,
497
+ ssa.OpARMTEQ,
498
+ ssa.OpARMCMPF,
499
+ ssa.OpARMCMPD:
500
+ p := s.Prog(v.Op.Asm())
501
+ p.From.Type = obj.TYPE_REG
502
+ // Special layout in ARM assembly
503
+ // Comparing to x86, the operands of ARM's CMP are reversed.
504
+ p.From.Reg = v.Args[1].Reg()
505
+ p.Reg = v.Args[0].Reg()
506
+ case ssa.OpARMCMPconst,
507
+ ssa.OpARMCMNconst,
508
+ ssa.OpARMTSTconst,
509
+ ssa.OpARMTEQconst:
510
+ // Special layout in ARM assembly
511
+ p := s.Prog(v.Op.Asm())
512
+ p.From.Type = obj.TYPE_CONST
513
+ p.From.Offset = v.AuxInt
514
+ p.Reg = v.Args[0].Reg()
515
+ case ssa.OpARMCMPF0,
516
+ ssa.OpARMCMPD0:
517
+ p := s.Prog(v.Op.Asm())
518
+ p.From.Type = obj.TYPE_REG
519
+ p.From.Reg = v.Args[0].Reg()
520
+ case ssa.OpARMCMPshiftLL, ssa.OpARMCMNshiftLL, ssa.OpARMTSTshiftLL, ssa.OpARMTEQshiftLL:
521
+ genshift(s, v, v.Op.Asm(), v.Args[0].Reg(), v.Args[1].Reg(), 0, arm.SHIFT_LL, v.AuxInt)
522
+ case ssa.OpARMCMPshiftRL, ssa.OpARMCMNshiftRL, ssa.OpARMTSTshiftRL, ssa.OpARMTEQshiftRL:
523
+ genshift(s, v, v.Op.Asm(), v.Args[0].Reg(), v.Args[1].Reg(), 0, arm.SHIFT_LR, v.AuxInt)
524
+ case ssa.OpARMCMPshiftRA, ssa.OpARMCMNshiftRA, ssa.OpARMTSTshiftRA, ssa.OpARMTEQshiftRA:
525
+ genshift(s, v, v.Op.Asm(), v.Args[0].Reg(), v.Args[1].Reg(), 0, arm.SHIFT_AR, v.AuxInt)
526
+ case ssa.OpARMCMPshiftLLreg, ssa.OpARMCMNshiftLLreg, ssa.OpARMTSTshiftLLreg, ssa.OpARMTEQshiftLLreg:
527
+ genregshift(s, v.Op.Asm(), v.Args[0].Reg(), v.Args[1].Reg(), v.Args[2].Reg(), 0, arm.SHIFT_LL)
528
+ case ssa.OpARMCMPshiftRLreg, ssa.OpARMCMNshiftRLreg, ssa.OpARMTSTshiftRLreg, ssa.OpARMTEQshiftRLreg:
529
+ genregshift(s, v.Op.Asm(), v.Args[0].Reg(), v.Args[1].Reg(), v.Args[2].Reg(), 0, arm.SHIFT_LR)
530
+ case ssa.OpARMCMPshiftRAreg, ssa.OpARMCMNshiftRAreg, ssa.OpARMTSTshiftRAreg, ssa.OpARMTEQshiftRAreg:
531
+ genregshift(s, v.Op.Asm(), v.Args[0].Reg(), v.Args[1].Reg(), v.Args[2].Reg(), 0, arm.SHIFT_AR)
532
+ case ssa.OpARMMOVWaddr:
533
+ p := s.Prog(arm.AMOVW)
534
+ p.From.Type = obj.TYPE_ADDR
535
+ p.From.Reg = v.Args[0].Reg()
536
+ p.To.Type = obj.TYPE_REG
537
+ p.To.Reg = v.Reg()
538
+
539
+ var wantreg string
540
+ // MOVW $sym+off(base), R
541
+ // the assembler expands it as the following:
542
+ // - base is SP: add constant offset to SP (R13)
543
+ // when constant is large, tmp register (R11) may be used
544
+ // - base is SB: load external address from constant pool (use relocation)
545
+ switch v.Aux.(type) {
546
+ default:
547
+ v.Fatalf("aux is of unknown type %T", v.Aux)
548
+ case *obj.LSym:
549
+ wantreg = "SB"
550
+ ssagen.AddAux(&p.From, v)
551
+ case *ir.Name:
552
+ wantreg = "SP"
553
+ ssagen.AddAux(&p.From, v)
554
+ case nil:
555
+ // No sym, just MOVW $off(SP), R
556
+ wantreg = "SP"
557
+ p.From.Offset = v.AuxInt
558
+ }
559
+ if reg := v.Args[0].RegName(); reg != wantreg {
560
+ v.Fatalf("bad reg %s for symbol type %T, want %s", reg, v.Aux, wantreg)
561
+ }
562
+
563
+ case ssa.OpARMMOVBload,
564
+ ssa.OpARMMOVBUload,
565
+ ssa.OpARMMOVHload,
566
+ ssa.OpARMMOVHUload,
567
+ ssa.OpARMMOVWload,
568
+ ssa.OpARMMOVFload,
569
+ ssa.OpARMMOVDload:
570
+ p := s.Prog(v.Op.Asm())
571
+ p.From.Type = obj.TYPE_MEM
572
+ p.From.Reg = v.Args[0].Reg()
573
+ ssagen.AddAux(&p.From, v)
574
+ p.To.Type = obj.TYPE_REG
575
+ p.To.Reg = v.Reg()
576
+ case ssa.OpARMMOVBstore,
577
+ ssa.OpARMMOVHstore,
578
+ ssa.OpARMMOVWstore,
579
+ ssa.OpARMMOVFstore,
580
+ ssa.OpARMMOVDstore:
581
+ p := s.Prog(v.Op.Asm())
582
+ p.From.Type = obj.TYPE_REG
583
+ p.From.Reg = v.Args[1].Reg()
584
+ p.To.Type = obj.TYPE_MEM
585
+ p.To.Reg = v.Args[0].Reg()
586
+ ssagen.AddAux(&p.To, v)
587
+ case ssa.OpARMMOVWloadidx, ssa.OpARMMOVBUloadidx, ssa.OpARMMOVBloadidx, ssa.OpARMMOVHUloadidx, ssa.OpARMMOVHloadidx:
588
+ // this is just shift 0 bits
589
+ fallthrough
590
+ case ssa.OpARMMOVWloadshiftLL:
591
+ p := genshift(s, v, v.Op.Asm(), 0, v.Args[1].Reg(), v.Reg(), arm.SHIFT_LL, v.AuxInt)
592
+ p.From.Reg = v.Args[0].Reg()
593
+ case ssa.OpARMMOVWloadshiftRL:
594
+ p := genshift(s, v, v.Op.Asm(), 0, v.Args[1].Reg(), v.Reg(), arm.SHIFT_LR, v.AuxInt)
595
+ p.From.Reg = v.Args[0].Reg()
596
+ case ssa.OpARMMOVWloadshiftRA:
597
+ p := genshift(s, v, v.Op.Asm(), 0, v.Args[1].Reg(), v.Reg(), arm.SHIFT_AR, v.AuxInt)
598
+ p.From.Reg = v.Args[0].Reg()
599
+ case ssa.OpARMMOVWstoreidx, ssa.OpARMMOVBstoreidx, ssa.OpARMMOVHstoreidx:
600
+ // this is just shift 0 bits
601
+ fallthrough
602
+ case ssa.OpARMMOVWstoreshiftLL:
603
+ p := s.Prog(v.Op.Asm())
604
+ p.From.Type = obj.TYPE_REG
605
+ p.From.Reg = v.Args[2].Reg()
606
+ p.To.Type = obj.TYPE_SHIFT
607
+ p.To.Reg = v.Args[0].Reg()
608
+ p.To.Offset = int64(makeshift(v, v.Args[1].Reg(), arm.SHIFT_LL, v.AuxInt))
609
+ case ssa.OpARMMOVWstoreshiftRL:
610
+ p := s.Prog(v.Op.Asm())
611
+ p.From.Type = obj.TYPE_REG
612
+ p.From.Reg = v.Args[2].Reg()
613
+ p.To.Type = obj.TYPE_SHIFT
614
+ p.To.Reg = v.Args[0].Reg()
615
+ p.To.Offset = int64(makeshift(v, v.Args[1].Reg(), arm.SHIFT_LR, v.AuxInt))
616
+ case ssa.OpARMMOVWstoreshiftRA:
617
+ p := s.Prog(v.Op.Asm())
618
+ p.From.Type = obj.TYPE_REG
619
+ p.From.Reg = v.Args[2].Reg()
620
+ p.To.Type = obj.TYPE_SHIFT
621
+ p.To.Reg = v.Args[0].Reg()
622
+ p.To.Offset = int64(makeshift(v, v.Args[1].Reg(), arm.SHIFT_AR, v.AuxInt))
623
+ case ssa.OpARMMOVBreg,
624
+ ssa.OpARMMOVBUreg,
625
+ ssa.OpARMMOVHreg,
626
+ ssa.OpARMMOVHUreg:
627
+ a := v.Args[0]
628
+ for a.Op == ssa.OpCopy || a.Op == ssa.OpARMMOVWreg || a.Op == ssa.OpARMMOVWnop {
629
+ a = a.Args[0]
630
+ }
631
+ if a.Op == ssa.OpLoadReg {
632
+ t := a.Type
633
+ switch {
634
+ case v.Op == ssa.OpARMMOVBreg && t.Size() == 1 && t.IsSigned(),
635
+ v.Op == ssa.OpARMMOVBUreg && t.Size() == 1 && !t.IsSigned(),
636
+ v.Op == ssa.OpARMMOVHreg && t.Size() == 2 && t.IsSigned(),
637
+ v.Op == ssa.OpARMMOVHUreg && t.Size() == 2 && !t.IsSigned():
638
+ // arg is a proper-typed load, already zero/sign-extended, don't extend again
639
+ if v.Reg() == v.Args[0].Reg() {
640
+ return
641
+ }
642
+ p := s.Prog(arm.AMOVW)
643
+ p.From.Type = obj.TYPE_REG
644
+ p.From.Reg = v.Args[0].Reg()
645
+ p.To.Type = obj.TYPE_REG
646
+ p.To.Reg = v.Reg()
647
+ return
648
+ default:
649
+ }
650
+ }
651
+ if buildcfg.GOARM.Version >= 6 {
652
+ // generate more efficient "MOVB/MOVBU/MOVH/MOVHU Reg@>0, Reg" on ARMv6 & ARMv7
653
+ genshift(s, v, v.Op.Asm(), 0, v.Args[0].Reg(), v.Reg(), arm.SHIFT_RR, 0)
654
+ return
655
+ }
656
+ fallthrough
657
+ case ssa.OpARMMVN,
658
+ ssa.OpARMCLZ,
659
+ ssa.OpARMREV,
660
+ ssa.OpARMREV16,
661
+ ssa.OpARMRBIT,
662
+ ssa.OpARMSQRTF,
663
+ ssa.OpARMSQRTD,
664
+ ssa.OpARMNEGF,
665
+ ssa.OpARMNEGD,
666
+ ssa.OpARMABSD,
667
+ ssa.OpARMMOVWF,
668
+ ssa.OpARMMOVWD,
669
+ ssa.OpARMMOVFW,
670
+ ssa.OpARMMOVDW,
671
+ ssa.OpARMMOVFD,
672
+ ssa.OpARMMOVDF:
673
+ p := s.Prog(v.Op.Asm())
674
+ p.From.Type = obj.TYPE_REG
675
+ p.From.Reg = v.Args[0].Reg()
676
+ p.To.Type = obj.TYPE_REG
677
+ p.To.Reg = v.Reg()
678
+ case ssa.OpARMMOVWUF,
679
+ ssa.OpARMMOVWUD,
680
+ ssa.OpARMMOVFWU,
681
+ ssa.OpARMMOVDWU:
682
+ p := s.Prog(v.Op.Asm())
683
+ p.Scond = arm.C_UBIT
684
+ p.From.Type = obj.TYPE_REG
685
+ p.From.Reg = v.Args[0].Reg()
686
+ p.To.Type = obj.TYPE_REG
687
+ p.To.Reg = v.Reg()
688
+ case ssa.OpARMCMOVWHSconst:
689
+ p := s.Prog(arm.AMOVW)
690
+ p.Scond = arm.C_SCOND_HS
691
+ p.From.Type = obj.TYPE_CONST
692
+ p.From.Offset = v.AuxInt
693
+ p.To.Type = obj.TYPE_REG
694
+ p.To.Reg = v.Reg()
695
+ case ssa.OpARMCMOVWLSconst:
696
+ p := s.Prog(arm.AMOVW)
697
+ p.Scond = arm.C_SCOND_LS
698
+ p.From.Type = obj.TYPE_CONST
699
+ p.From.Offset = v.AuxInt
700
+ p.To.Type = obj.TYPE_REG
701
+ p.To.Reg = v.Reg()
702
+ case ssa.OpARMCALLstatic, ssa.OpARMCALLclosure, ssa.OpARMCALLinter:
703
+ s.Call(v)
704
+ case ssa.OpARMCALLtail:
705
+ s.TailCall(v)
706
+ case ssa.OpARMCALLudiv:
707
+ p := s.Prog(obj.ACALL)
708
+ p.To.Type = obj.TYPE_MEM
709
+ p.To.Name = obj.NAME_EXTERN
710
+ p.To.Sym = ir.Syms.Udiv
711
+ case ssa.OpARMLoweredWB:
712
+ p := s.Prog(obj.ACALL)
713
+ p.To.Type = obj.TYPE_MEM
714
+ p.To.Name = obj.NAME_EXTERN
715
+ // AuxInt encodes how many buffer entries we need.
716
+ p.To.Sym = ir.Syms.GCWriteBarrier[v.AuxInt-1]
717
+
718
+ case ssa.OpARMLoweredPanicBoundsRR, ssa.OpARMLoweredPanicBoundsRC, ssa.OpARMLoweredPanicBoundsCR, ssa.OpARMLoweredPanicBoundsCC,
719
+ ssa.OpARMLoweredPanicExtendRR, ssa.OpARMLoweredPanicExtendRC:
720
+ // Compute the constant we put in the PCData entry for this call.
721
+ code, signed := ssa.BoundsKind(v.AuxInt).Code()
722
+ xIsReg := false
723
+ yIsReg := false
724
+ xVal := 0
725
+ yVal := 0
726
+ extend := false
727
+ switch v.Op {
728
+ case ssa.OpARMLoweredPanicBoundsRR:
729
+ xIsReg = true
730
+ xVal = int(v.Args[0].Reg() - arm.REG_R0)
731
+ yIsReg = true
732
+ yVal = int(v.Args[1].Reg() - arm.REG_R0)
733
+ case ssa.OpARMLoweredPanicExtendRR:
734
+ extend = true
735
+ xIsReg = true
736
+ hi := int(v.Args[0].Reg() - arm.REG_R0)
737
+ lo := int(v.Args[1].Reg() - arm.REG_R0)
738
+ xVal = hi<<2 + lo // encode 2 register numbers
739
+ yIsReg = true
740
+ yVal = int(v.Args[2].Reg() - arm.REG_R0)
741
+ case ssa.OpARMLoweredPanicBoundsRC:
742
+ xIsReg = true
743
+ xVal = int(v.Args[0].Reg() - arm.REG_R0)
744
+ c := v.Aux.(ssa.PanicBoundsC).C
745
+ if c >= 0 && c <= abi.BoundsMaxConst {
746
+ yVal = int(c)
747
+ } else {
748
+ // Move constant to a register
749
+ yIsReg = true
750
+ if yVal == xVal {
751
+ yVal = 1
752
+ }
753
+ p := s.Prog(arm.AMOVW)
754
+ p.From.Type = obj.TYPE_CONST
755
+ p.From.Offset = c
756
+ p.To.Type = obj.TYPE_REG
757
+ p.To.Reg = arm.REG_R0 + int16(yVal)
758
+ }
759
+ case ssa.OpARMLoweredPanicExtendRC:
760
+ extend = true
761
+ xIsReg = true
762
+ hi := int(v.Args[0].Reg() - arm.REG_R0)
763
+ lo := int(v.Args[1].Reg() - arm.REG_R0)
764
+ xVal = hi<<2 + lo // encode 2 register numbers
765
+ c := v.Aux.(ssa.PanicBoundsC).C
766
+ if c >= 0 && c <= abi.BoundsMaxConst {
767
+ yVal = int(c)
768
+ } else {
769
+ // Move constant to a register
770
+ for yVal == hi || yVal == lo {
771
+ yVal++
772
+ }
773
+ p := s.Prog(arm.AMOVW)
774
+ p.From.Type = obj.TYPE_CONST
775
+ p.From.Offset = c
776
+ p.To.Type = obj.TYPE_REG
777
+ p.To.Reg = arm.REG_R0 + int16(yVal)
778
+ }
779
+ case ssa.OpARMLoweredPanicBoundsCR:
780
+ yIsReg = true
781
+ yVal = int(v.Args[0].Reg() - arm.REG_R0)
782
+ c := v.Aux.(ssa.PanicBoundsC).C
783
+ if c >= 0 && c <= abi.BoundsMaxConst {
784
+ xVal = int(c)
785
+ } else if signed && int64(int32(c)) == c || !signed && int64(uint32(c)) == c {
786
+ // Move constant to a register
787
+ xIsReg = true
788
+ if xVal == yVal {
789
+ xVal = 1
790
+ }
791
+ p := s.Prog(arm.AMOVW)
792
+ p.From.Type = obj.TYPE_CONST
793
+ p.From.Offset = c
794
+ p.To.Type = obj.TYPE_REG
795
+ p.To.Reg = arm.REG_R0 + int16(xVal)
796
+ } else {
797
+ // Move constant to two registers
798
+ extend = true
799
+ xIsReg = true
800
+ hi := 0
801
+ lo := 1
802
+ if hi == yVal {
803
+ hi = 2
804
+ }
805
+ if lo == yVal {
806
+ lo = 2
807
+ }
808
+ xVal = hi<<2 + lo
809
+ p := s.Prog(arm.AMOVW)
810
+ p.From.Type = obj.TYPE_CONST
811
+ p.From.Offset = c >> 32
812
+ p.To.Type = obj.TYPE_REG
813
+ p.To.Reg = arm.REG_R0 + int16(hi)
814
+ p = s.Prog(arm.AMOVW)
815
+ p.From.Type = obj.TYPE_CONST
816
+ p.From.Offset = int64(int32(c))
817
+ p.To.Type = obj.TYPE_REG
818
+ p.To.Reg = arm.REG_R0 + int16(lo)
819
+ }
820
+ case ssa.OpARMLoweredPanicBoundsCC:
821
+ c := v.Aux.(ssa.PanicBoundsCC).Cx
822
+ if c >= 0 && c <= abi.BoundsMaxConst {
823
+ xVal = int(c)
824
+ } else if signed && int64(int32(c)) == c || !signed && int64(uint32(c)) == c {
825
+ // Move constant to a register
826
+ xIsReg = true
827
+ p := s.Prog(arm.AMOVW)
828
+ p.From.Type = obj.TYPE_CONST
829
+ p.From.Offset = c
830
+ p.To.Type = obj.TYPE_REG
831
+ p.To.Reg = arm.REG_R0 + int16(xVal)
832
+ } else {
833
+ // Move constant to two registers
834
+ extend = true
835
+ xIsReg = true
836
+ hi := 0
837
+ lo := 1
838
+ xVal = hi<<2 + lo
839
+ p := s.Prog(arm.AMOVW)
840
+ p.From.Type = obj.TYPE_CONST
841
+ p.From.Offset = c >> 32
842
+ p.To.Type = obj.TYPE_REG
843
+ p.To.Reg = arm.REG_R0 + int16(hi)
844
+ p = s.Prog(arm.AMOVW)
845
+ p.From.Type = obj.TYPE_CONST
846
+ p.From.Offset = int64(int32(c))
847
+ p.To.Type = obj.TYPE_REG
848
+ p.To.Reg = arm.REG_R0 + int16(lo)
849
+ }
850
+ c = v.Aux.(ssa.PanicBoundsCC).Cy
851
+ if c >= 0 && c <= abi.BoundsMaxConst {
852
+ yVal = int(c)
853
+ } else {
854
+ // Move constant to a register
855
+ yIsReg = true
856
+ yVal = 2
857
+ p := s.Prog(arm.AMOVW)
858
+ p.From.Type = obj.TYPE_CONST
859
+ p.From.Offset = c
860
+ p.To.Type = obj.TYPE_REG
861
+ p.To.Reg = arm.REG_R0 + int16(yVal)
862
+ }
863
+ }
864
+ c := abi.BoundsEncode(code, signed, xIsReg, yIsReg, xVal, yVal)
865
+
866
+ p := s.Prog(obj.APCDATA)
867
+ p.From.SetConst(abi.PCDATA_PanicBounds)
868
+ p.To.SetConst(int64(c))
869
+ p = s.Prog(obj.ACALL)
870
+ p.To.Type = obj.TYPE_MEM
871
+ p.To.Name = obj.NAME_EXTERN
872
+ if extend {
873
+ p.To.Sym = ir.Syms.PanicExtend
874
+ } else {
875
+ p.To.Sym = ir.Syms.PanicBounds
876
+ }
877
+
878
+ case ssa.OpARMDUFFZERO:
879
+ p := s.Prog(obj.ADUFFZERO)
880
+ p.To.Type = obj.TYPE_MEM
881
+ p.To.Name = obj.NAME_EXTERN
882
+ p.To.Sym = ir.Syms.Duffzero
883
+ p.To.Offset = v.AuxInt
884
+ case ssa.OpARMDUFFCOPY:
885
+ p := s.Prog(obj.ADUFFCOPY)
886
+ p.To.Type = obj.TYPE_MEM
887
+ p.To.Name = obj.NAME_EXTERN
888
+ p.To.Sym = ir.Syms.Duffcopy
889
+ p.To.Offset = v.AuxInt
890
+ case ssa.OpARMLoweredNilCheck:
891
+ // Issue a load which will fault if arg is nil.
892
+ p := s.Prog(arm.AMOVB)
893
+ p.From.Type = obj.TYPE_MEM
894
+ p.From.Reg = v.Args[0].Reg()
895
+ ssagen.AddAux(&p.From, v)
896
+ p.To.Type = obj.TYPE_REG
897
+ p.To.Reg = arm.REGTMP
898
+ if logopt.Enabled() {
899
+ logopt.LogOpt(v.Pos, "nilcheck", "genssa", v.Block.Func.Name)
900
+ }
901
+ if base.Debug.Nil != 0 && v.Pos.Line() > 1 { // v.Pos.Line()==1 in generated wrappers
902
+ base.WarnfAt(v.Pos, "generated nil check")
903
+ }
904
+ case ssa.OpARMLoweredZero:
905
+ // MOVW.P Rarg2, 4(R1)
906
+ // CMP Rarg1, R1
907
+ // BLE -2(PC)
908
+ // arg1 is the address of the last element to zero
909
+ // arg2 is known to be zero
910
+ // auxint is alignment
911
+ var sz int64
912
+ var mov obj.As
913
+ switch {
914
+ case v.AuxInt%4 == 0:
915
+ sz = 4
916
+ mov = arm.AMOVW
917
+ case v.AuxInt%2 == 0:
918
+ sz = 2
919
+ mov = arm.AMOVH
920
+ default:
921
+ sz = 1
922
+ mov = arm.AMOVB
923
+ }
924
+ p := s.Prog(mov)
925
+ p.Scond = arm.C_PBIT
926
+ p.From.Type = obj.TYPE_REG
927
+ p.From.Reg = v.Args[2].Reg()
928
+ p.To.Type = obj.TYPE_MEM
929
+ p.To.Reg = arm.REG_R1
930
+ p.To.Offset = sz
931
+ p2 := s.Prog(arm.ACMP)
932
+ p2.From.Type = obj.TYPE_REG
933
+ p2.From.Reg = v.Args[1].Reg()
934
+ p2.Reg = arm.REG_R1
935
+ p3 := s.Prog(arm.ABLE)
936
+ p3.To.Type = obj.TYPE_BRANCH
937
+ p3.To.SetTarget(p)
938
+ case ssa.OpARMLoweredMove:
939
+ // MOVW.P 4(R1), Rtmp
940
+ // MOVW.P Rtmp, 4(R2)
941
+ // CMP Rarg2, R1
942
+ // BLE -3(PC)
943
+ // arg2 is the address of the last element of src
944
+ // auxint is alignment
945
+ var sz int64
946
+ var mov obj.As
947
+ switch {
948
+ case v.AuxInt%4 == 0:
949
+ sz = 4
950
+ mov = arm.AMOVW
951
+ case v.AuxInt%2 == 0:
952
+ sz = 2
953
+ mov = arm.AMOVH
954
+ default:
955
+ sz = 1
956
+ mov = arm.AMOVB
957
+ }
958
+ p := s.Prog(mov)
959
+ p.Scond = arm.C_PBIT
960
+ p.From.Type = obj.TYPE_MEM
961
+ p.From.Reg = arm.REG_R1
962
+ p.From.Offset = sz
963
+ p.To.Type = obj.TYPE_REG
964
+ p.To.Reg = arm.REGTMP
965
+ p2 := s.Prog(mov)
966
+ p2.Scond = arm.C_PBIT
967
+ p2.From.Type = obj.TYPE_REG
968
+ p2.From.Reg = arm.REGTMP
969
+ p2.To.Type = obj.TYPE_MEM
970
+ p2.To.Reg = arm.REG_R2
971
+ p2.To.Offset = sz
972
+ p3 := s.Prog(arm.ACMP)
973
+ p3.From.Type = obj.TYPE_REG
974
+ p3.From.Reg = v.Args[2].Reg()
975
+ p3.Reg = arm.REG_R1
976
+ p4 := s.Prog(arm.ABLE)
977
+ p4.To.Type = obj.TYPE_BRANCH
978
+ p4.To.SetTarget(p)
979
+ case ssa.OpARMEqual,
980
+ ssa.OpARMNotEqual,
981
+ ssa.OpARMLessThan,
982
+ ssa.OpARMLessEqual,
983
+ ssa.OpARMGreaterThan,
984
+ ssa.OpARMGreaterEqual,
985
+ ssa.OpARMLessThanU,
986
+ ssa.OpARMLessEqualU,
987
+ ssa.OpARMGreaterThanU,
988
+ ssa.OpARMGreaterEqualU:
989
+ // generate boolean values
990
+ // use conditional move
991
+ p := s.Prog(arm.AMOVW)
992
+ p.From.Type = obj.TYPE_CONST
993
+ p.From.Offset = 0
994
+ p.To.Type = obj.TYPE_REG
995
+ p.To.Reg = v.Reg()
996
+ p = s.Prog(arm.AMOVW)
997
+ p.Scond = condBits[v.Op]
998
+ p.From.Type = obj.TYPE_CONST
999
+ p.From.Offset = 1
1000
+ p.To.Type = obj.TYPE_REG
1001
+ p.To.Reg = v.Reg()
1002
+ case ssa.OpARMLoweredGetClosurePtr:
1003
+ // Closure pointer is R7 (arm.REGCTXT).
1004
+ ssagen.CheckLoweredGetClosurePtr(v)
1005
+ case ssa.OpARMLoweredGetCallerSP:
1006
+ // caller's SP is FixedFrameSize below the address of the first arg
1007
+ p := s.Prog(arm.AMOVW)
1008
+ p.From.Type = obj.TYPE_ADDR
1009
+ p.From.Offset = -base.Ctxt.Arch.FixedFrameSize
1010
+ p.From.Name = obj.NAME_PARAM
1011
+ p.To.Type = obj.TYPE_REG
1012
+ p.To.Reg = v.Reg()
1013
+ case ssa.OpARMLoweredGetCallerPC:
1014
+ p := s.Prog(obj.AGETCALLERPC)
1015
+ p.To.Type = obj.TYPE_REG
1016
+ p.To.Reg = v.Reg()
1017
+ case ssa.OpARMFlagConstant:
1018
+ v.Fatalf("FlagConstant op should never make it to codegen %v", v.LongString())
1019
+ case ssa.OpARMInvertFlags:
1020
+ v.Fatalf("InvertFlags should never make it to codegen %v", v.LongString())
1021
+ case ssa.OpClobber, ssa.OpClobberReg:
1022
+ // TODO: implement for clobberdead experiment. Nop is ok for now.
1023
+ default:
1024
+ v.Fatalf("genValue not implemented: %s", v.LongString())
1025
+ }
1026
+ }
1027
+
1028
+ var condBits = map[ssa.Op]uint8{
1029
+ ssa.OpARMEqual: arm.C_SCOND_EQ,
1030
+ ssa.OpARMNotEqual: arm.C_SCOND_NE,
1031
+ ssa.OpARMLessThan: arm.C_SCOND_LT,
1032
+ ssa.OpARMLessThanU: arm.C_SCOND_LO,
1033
+ ssa.OpARMLessEqual: arm.C_SCOND_LE,
1034
+ ssa.OpARMLessEqualU: arm.C_SCOND_LS,
1035
+ ssa.OpARMGreaterThan: arm.C_SCOND_GT,
1036
+ ssa.OpARMGreaterThanU: arm.C_SCOND_HI,
1037
+ ssa.OpARMGreaterEqual: arm.C_SCOND_GE,
1038
+ ssa.OpARMGreaterEqualU: arm.C_SCOND_HS,
1039
+ }
1040
+
1041
+ var blockJump = map[ssa.BlockKind]struct {
1042
+ asm, invasm obj.As
1043
+ }{
1044
+ ssa.BlockARMEQ: {arm.ABEQ, arm.ABNE},
1045
+ ssa.BlockARMNE: {arm.ABNE, arm.ABEQ},
1046
+ ssa.BlockARMLT: {arm.ABLT, arm.ABGE},
1047
+ ssa.BlockARMGE: {arm.ABGE, arm.ABLT},
1048
+ ssa.BlockARMLE: {arm.ABLE, arm.ABGT},
1049
+ ssa.BlockARMGT: {arm.ABGT, arm.ABLE},
1050
+ ssa.BlockARMULT: {arm.ABLO, arm.ABHS},
1051
+ ssa.BlockARMUGE: {arm.ABHS, arm.ABLO},
1052
+ ssa.BlockARMUGT: {arm.ABHI, arm.ABLS},
1053
+ ssa.BlockARMULE: {arm.ABLS, arm.ABHI},
1054
+ ssa.BlockARMLTnoov: {arm.ABMI, arm.ABPL},
1055
+ ssa.BlockARMGEnoov: {arm.ABPL, arm.ABMI},
1056
+ }
1057
+
1058
+ // To model a 'LEnoov' ('<=' without overflow checking) branching.
1059
+ var leJumps = [2][2]ssagen.IndexJump{
1060
+ {{Jump: arm.ABEQ, Index: 0}, {Jump: arm.ABPL, Index: 1}}, // next == b.Succs[0]
1061
+ {{Jump: arm.ABMI, Index: 0}, {Jump: arm.ABEQ, Index: 0}}, // next == b.Succs[1]
1062
+ }
1063
+
1064
+ // To model a 'GTnoov' ('>' without overflow checking) branching.
1065
+ var gtJumps = [2][2]ssagen.IndexJump{
1066
+ {{Jump: arm.ABMI, Index: 1}, {Jump: arm.ABEQ, Index: 1}}, // next == b.Succs[0]
1067
+ {{Jump: arm.ABEQ, Index: 1}, {Jump: arm.ABPL, Index: 0}}, // next == b.Succs[1]
1068
+ }
1069
+
1070
+ func ssaGenBlock(s *ssagen.State, b, next *ssa.Block) {
1071
+ switch b.Kind {
1072
+ case ssa.BlockPlain, ssa.BlockDefer:
1073
+ if b.Succs[0].Block() != next {
1074
+ p := s.Prog(obj.AJMP)
1075
+ p.To.Type = obj.TYPE_BRANCH
1076
+ s.Branches = append(s.Branches, ssagen.Branch{P: p, B: b.Succs[0].Block()})
1077
+ }
1078
+
1079
+ case ssa.BlockExit, ssa.BlockRetJmp:
1080
+
1081
+ case ssa.BlockRet:
1082
+ s.Prog(obj.ARET)
1083
+
1084
+ case ssa.BlockARMEQ, ssa.BlockARMNE,
1085
+ ssa.BlockARMLT, ssa.BlockARMGE,
1086
+ ssa.BlockARMLE, ssa.BlockARMGT,
1087
+ ssa.BlockARMULT, ssa.BlockARMUGT,
1088
+ ssa.BlockARMULE, ssa.BlockARMUGE,
1089
+ ssa.BlockARMLTnoov, ssa.BlockARMGEnoov:
1090
+ jmp := blockJump[b.Kind]
1091
+ switch next {
1092
+ case b.Succs[0].Block():
1093
+ s.Br(jmp.invasm, b.Succs[1].Block())
1094
+ case b.Succs[1].Block():
1095
+ s.Br(jmp.asm, b.Succs[0].Block())
1096
+ default:
1097
+ if b.Likely != ssa.BranchUnlikely {
1098
+ s.Br(jmp.asm, b.Succs[0].Block())
1099
+ s.Br(obj.AJMP, b.Succs[1].Block())
1100
+ } else {
1101
+ s.Br(jmp.invasm, b.Succs[1].Block())
1102
+ s.Br(obj.AJMP, b.Succs[0].Block())
1103
+ }
1104
+ }
1105
+
1106
+ case ssa.BlockARMLEnoov:
1107
+ s.CombJump(b, next, &leJumps)
1108
+
1109
+ case ssa.BlockARMGTnoov:
1110
+ s.CombJump(b, next, &gtJumps)
1111
+
1112
+ default:
1113
+ b.Fatalf("branch not implemented: %s", b.LongString())
1114
+ }
1115
+ }
go/src/cmd/compile/internal/arm64/galign.go ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2009 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 arm64
6
+
7
+ import (
8
+ "cmd/compile/internal/ssa"
9
+ "cmd/compile/internal/ssagen"
10
+ "cmd/internal/obj/arm64"
11
+ )
12
+
13
+ func Init(arch *ssagen.ArchInfo) {
14
+ arch.LinkArch = &arm64.Linkarm64
15
+ arch.REGSP = arm64.REGSP
16
+ arch.MAXWIDTH = 1 << 50
17
+
18
+ arch.PadFrame = padframe
19
+ arch.ZeroRange = zerorange
20
+ arch.Ginsnop = ginsnop
21
+
22
+ arch.SSAMarkMoves = func(s *ssagen.State, b *ssa.Block) {}
23
+ arch.SSAGenValue = ssaGenValue
24
+ arch.SSAGenBlock = ssaGenBlock
25
+ arch.LoadRegResult = loadRegResult
26
+ arch.SpillArgReg = spillArgReg
27
+ }
go/src/cmd/compile/internal/arm64/ggen.go ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2009 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 arm64
6
+
7
+ import (
8
+ "cmd/compile/internal/objw"
9
+ "cmd/internal/obj"
10
+ "cmd/internal/obj/arm64"
11
+ )
12
+
13
+ func padframe(frame int64) int64 {
14
+ // arm64 requires that the frame size (not counting saved FP&LR)
15
+ // be 16 bytes aligned. If not, pad it.
16
+ if frame%16 != 0 {
17
+ frame += 16 - (frame % 16)
18
+ }
19
+ return frame
20
+ }
21
+
22
+ func zerorange(pp *objw.Progs, p *obj.Prog, off, cnt int64, _ *uint32) *obj.Prog {
23
+ if cnt%8 != 0 {
24
+ panic("zeroed region not aligned")
25
+ }
26
+ off += 8 // return address was ignored in offset calculation
27
+ for cnt >= 16 && off < 512 {
28
+ p = pp.Append(p, arm64.ASTP, obj.TYPE_REGREG, arm64.REGZERO, arm64.REGZERO, obj.TYPE_MEM, arm64.REGSP, off)
29
+ off += 16
30
+ cnt -= 16
31
+ }
32
+ for cnt != 0 {
33
+ p = pp.Append(p, arm64.AMOVD, obj.TYPE_REG, arm64.REGZERO, 0, obj.TYPE_MEM, arm64.REGSP, off)
34
+ off += 8
35
+ cnt -= 8
36
+ }
37
+ return p
38
+ }
39
+
40
+ func ginsnop(pp *objw.Progs) *obj.Prog {
41
+ p := pp.Prog(arm64.AHINT)
42
+ p.From.Type = obj.TYPE_CONST
43
+ return p
44
+ }
go/src/cmd/compile/internal/arm64/ssa.go ADDED
@@ -0,0 +1,1800 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2016 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 arm64
6
+
7
+ import (
8
+ "math"
9
+
10
+ "cmd/compile/internal/base"
11
+ "cmd/compile/internal/ir"
12
+ "cmd/compile/internal/logopt"
13
+ "cmd/compile/internal/objw"
14
+ "cmd/compile/internal/ssa"
15
+ "cmd/compile/internal/ssagen"
16
+ "cmd/compile/internal/types"
17
+ "cmd/internal/obj"
18
+ "cmd/internal/obj/arm64"
19
+ "internal/abi"
20
+ )
21
+
22
+ // loadByType returns the load instruction of the given type.
23
+ func loadByType(t *types.Type) obj.As {
24
+ if t.IsFloat() {
25
+ switch t.Size() {
26
+ case 4:
27
+ return arm64.AFMOVS
28
+ case 8:
29
+ return arm64.AFMOVD
30
+ }
31
+ } else {
32
+ switch t.Size() {
33
+ case 1:
34
+ if t.IsSigned() {
35
+ return arm64.AMOVB
36
+ } else {
37
+ return arm64.AMOVBU
38
+ }
39
+ case 2:
40
+ if t.IsSigned() {
41
+ return arm64.AMOVH
42
+ } else {
43
+ return arm64.AMOVHU
44
+ }
45
+ case 4:
46
+ if t.IsSigned() {
47
+ return arm64.AMOVW
48
+ } else {
49
+ return arm64.AMOVWU
50
+ }
51
+ case 8:
52
+ return arm64.AMOVD
53
+ }
54
+ }
55
+ panic("bad load type")
56
+ }
57
+
58
+ // storeByType returns the store instruction of the given type.
59
+ func storeByType(t *types.Type) obj.As {
60
+ if t.IsFloat() {
61
+ switch t.Size() {
62
+ case 4:
63
+ return arm64.AFMOVS
64
+ case 8:
65
+ return arm64.AFMOVD
66
+ }
67
+ } else {
68
+ switch t.Size() {
69
+ case 1:
70
+ return arm64.AMOVB
71
+ case 2:
72
+ return arm64.AMOVH
73
+ case 4:
74
+ return arm64.AMOVW
75
+ case 8:
76
+ return arm64.AMOVD
77
+ }
78
+ }
79
+ panic("bad store type")
80
+ }
81
+
82
+ // loadByType2 returns an opcode that can load consecutive memory locations into 2 registers with type t.
83
+ // returns obj.AXXX if no such opcode exists.
84
+ func loadByType2(t *types.Type) obj.As {
85
+ if t.IsFloat() {
86
+ switch t.Size() {
87
+ case 4:
88
+ return arm64.AFLDPS
89
+ case 8:
90
+ return arm64.AFLDPD
91
+ }
92
+ } else {
93
+ switch t.Size() {
94
+ case 4:
95
+ return arm64.ALDPW
96
+ case 8:
97
+ return arm64.ALDP
98
+ }
99
+ }
100
+ return obj.AXXX
101
+ }
102
+
103
+ // storeByType2 returns an opcode that can store registers with type t into 2 consecutive memory locations.
104
+ // returns obj.AXXX if no such opcode exists.
105
+ func storeByType2(t *types.Type) obj.As {
106
+ if t.IsFloat() {
107
+ switch t.Size() {
108
+ case 4:
109
+ return arm64.AFSTPS
110
+ case 8:
111
+ return arm64.AFSTPD
112
+ }
113
+ } else {
114
+ switch t.Size() {
115
+ case 4:
116
+ return arm64.ASTPW
117
+ case 8:
118
+ return arm64.ASTP
119
+ }
120
+ }
121
+ return obj.AXXX
122
+ }
123
+
124
+ // makeshift encodes a register shifted by a constant, used as an Offset in Prog.
125
+ func makeshift(v *ssa.Value, reg int16, typ int64, s int64) int64 {
126
+ if s < 0 || s >= 64 {
127
+ v.Fatalf("shift out of range: %d", s)
128
+ }
129
+ return int64(reg&31)<<16 | typ | (s&63)<<10
130
+ }
131
+
132
+ // genshift generates a Prog for r = r0 op (r1 shifted by n).
133
+ func genshift(s *ssagen.State, v *ssa.Value, as obj.As, r0, r1, r int16, typ int64, n int64) *obj.Prog {
134
+ p := s.Prog(as)
135
+ p.From.Type = obj.TYPE_SHIFT
136
+ p.From.Offset = makeshift(v, r1, typ, n)
137
+ p.Reg = r0
138
+ if r != 0 {
139
+ p.To.Type = obj.TYPE_REG
140
+ p.To.Reg = r
141
+ }
142
+ return p
143
+ }
144
+
145
+ // generate the memory operand for the indexed load/store instructions.
146
+ // base and idx are registers.
147
+ func genIndexedOperand(op ssa.Op, base, idx int16) obj.Addr {
148
+ // Reg: base register, Index: (shifted) index register
149
+ mop := obj.Addr{Type: obj.TYPE_MEM, Reg: base}
150
+ switch op {
151
+ case ssa.OpARM64MOVDloadidx8, ssa.OpARM64MOVDstoreidx8,
152
+ ssa.OpARM64FMOVDloadidx8, ssa.OpARM64FMOVDstoreidx8:
153
+ mop.Index = arm64.REG_LSL | 3<<5 | idx&31
154
+ case ssa.OpARM64MOVWloadidx4, ssa.OpARM64MOVWUloadidx4, ssa.OpARM64MOVWstoreidx4,
155
+ ssa.OpARM64FMOVSloadidx4, ssa.OpARM64FMOVSstoreidx4:
156
+ mop.Index = arm64.REG_LSL | 2<<5 | idx&31
157
+ case ssa.OpARM64MOVHloadidx2, ssa.OpARM64MOVHUloadidx2, ssa.OpARM64MOVHstoreidx2:
158
+ mop.Index = arm64.REG_LSL | 1<<5 | idx&31
159
+ default: // not shifted
160
+ mop.Index = idx
161
+ }
162
+ return mop
163
+ }
164
+
165
+ func ssaGenValue(s *ssagen.State, v *ssa.Value) {
166
+ switch v.Op {
167
+ case ssa.OpCopy, ssa.OpARM64MOVDreg:
168
+ if v.Type.IsMemory() {
169
+ return
170
+ }
171
+ x := v.Args[0].Reg()
172
+ y := v.Reg()
173
+ if x == y {
174
+ return
175
+ }
176
+ as := arm64.AMOVD
177
+ if v.Type.IsFloat() {
178
+ switch v.Type.Size() {
179
+ case 4:
180
+ as = arm64.AFMOVS
181
+ case 8:
182
+ as = arm64.AFMOVD
183
+ default:
184
+ panic("bad float size")
185
+ }
186
+ }
187
+ p := s.Prog(as)
188
+ p.From.Type = obj.TYPE_REG
189
+ p.From.Reg = x
190
+ p.To.Type = obj.TYPE_REG
191
+ p.To.Reg = y
192
+ case ssa.OpARM64MOVDnop, ssa.OpARM64ZERO:
193
+ // nothing to do
194
+ case ssa.OpLoadReg:
195
+ if v.Type.IsFlags() {
196
+ v.Fatalf("load flags not implemented: %v", v.LongString())
197
+ return
198
+ }
199
+ p := s.Prog(loadByType(v.Type))
200
+ ssagen.AddrAuto(&p.From, v.Args[0])
201
+ p.To.Type = obj.TYPE_REG
202
+ p.To.Reg = v.Reg()
203
+ case ssa.OpStoreReg:
204
+ if v.Type.IsFlags() {
205
+ v.Fatalf("store flags not implemented: %v", v.LongString())
206
+ return
207
+ }
208
+ p := s.Prog(storeByType(v.Type))
209
+ p.From.Type = obj.TYPE_REG
210
+ p.From.Reg = v.Args[0].Reg()
211
+ ssagen.AddrAuto(&p.To, v)
212
+ case ssa.OpArgIntReg, ssa.OpArgFloatReg:
213
+ ssagen.CheckArgReg(v)
214
+ // The assembler needs to wrap the entry safepoint/stack growth code with spill/unspill
215
+ // The loop only runs once.
216
+ args := v.Block.Func.RegArgs
217
+ if len(args) == 0 {
218
+ break
219
+ }
220
+ v.Block.Func.RegArgs = nil // prevent from running again
221
+
222
+ for i := 0; i < len(args); i++ {
223
+ a := args[i]
224
+ // Offset by size of the saved LR slot.
225
+ addr := ssagen.SpillSlotAddr(a, arm64.REGSP, base.Ctxt.Arch.FixedFrameSize)
226
+ // Look for double-register operations if we can.
227
+ if i < len(args)-1 {
228
+ b := args[i+1]
229
+ if a.Type.Size() == b.Type.Size() &&
230
+ a.Type.IsFloat() == b.Type.IsFloat() &&
231
+ b.Offset == a.Offset+a.Type.Size() {
232
+ ld := loadByType2(a.Type)
233
+ st := storeByType2(a.Type)
234
+ if ld != obj.AXXX && st != obj.AXXX {
235
+ s.FuncInfo().AddSpill(obj.RegSpill{Reg: a.Reg, Reg2: b.Reg, Addr: addr, Unspill: ld, Spill: st})
236
+ i++ // b is done also, skip it.
237
+ continue
238
+ }
239
+ }
240
+ }
241
+ // Pass the spill/unspill information along to the assembler.
242
+ s.FuncInfo().AddSpill(obj.RegSpill{Reg: a.Reg, Addr: addr, Unspill: loadByType(a.Type), Spill: storeByType(a.Type)})
243
+ }
244
+
245
+ case ssa.OpARM64ADD,
246
+ ssa.OpARM64SUB,
247
+ ssa.OpARM64AND,
248
+ ssa.OpARM64OR,
249
+ ssa.OpARM64XOR,
250
+ ssa.OpARM64BIC,
251
+ ssa.OpARM64EON,
252
+ ssa.OpARM64ORN,
253
+ ssa.OpARM64MUL,
254
+ ssa.OpARM64MULW,
255
+ ssa.OpARM64MNEG,
256
+ ssa.OpARM64MNEGW,
257
+ ssa.OpARM64MULH,
258
+ ssa.OpARM64UMULH,
259
+ ssa.OpARM64MULL,
260
+ ssa.OpARM64UMULL,
261
+ ssa.OpARM64DIV,
262
+ ssa.OpARM64UDIV,
263
+ ssa.OpARM64DIVW,
264
+ ssa.OpARM64UDIVW,
265
+ ssa.OpARM64MOD,
266
+ ssa.OpARM64UMOD,
267
+ ssa.OpARM64MODW,
268
+ ssa.OpARM64UMODW,
269
+ ssa.OpARM64SLL,
270
+ ssa.OpARM64SRL,
271
+ ssa.OpARM64SRA,
272
+ ssa.OpARM64FADDS,
273
+ ssa.OpARM64FADDD,
274
+ ssa.OpARM64FSUBS,
275
+ ssa.OpARM64FSUBD,
276
+ ssa.OpARM64FMULS,
277
+ ssa.OpARM64FMULD,
278
+ ssa.OpARM64FNMULS,
279
+ ssa.OpARM64FNMULD,
280
+ ssa.OpARM64FDIVS,
281
+ ssa.OpARM64FDIVD,
282
+ ssa.OpARM64FMINS,
283
+ ssa.OpARM64FMIND,
284
+ ssa.OpARM64FMAXS,
285
+ ssa.OpARM64FMAXD,
286
+ ssa.OpARM64ROR,
287
+ ssa.OpARM64RORW:
288
+ r := v.Reg()
289
+ r1 := v.Args[0].Reg()
290
+ r2 := v.Args[1].Reg()
291
+ p := s.Prog(v.Op.Asm())
292
+ p.From.Type = obj.TYPE_REG
293
+ p.From.Reg = r2
294
+ p.Reg = r1
295
+ p.To.Type = obj.TYPE_REG
296
+ p.To.Reg = r
297
+ case ssa.OpARM64FMADDS,
298
+ ssa.OpARM64FMADDD,
299
+ ssa.OpARM64FNMADDS,
300
+ ssa.OpARM64FNMADDD,
301
+ ssa.OpARM64FMSUBS,
302
+ ssa.OpARM64FMSUBD,
303
+ ssa.OpARM64FNMSUBS,
304
+ ssa.OpARM64FNMSUBD,
305
+ ssa.OpARM64MADD,
306
+ ssa.OpARM64MADDW,
307
+ ssa.OpARM64MSUB,
308
+ ssa.OpARM64MSUBW:
309
+ rt := v.Reg()
310
+ ra := v.Args[0].Reg()
311
+ rm := v.Args[1].Reg()
312
+ rn := v.Args[2].Reg()
313
+ p := s.Prog(v.Op.Asm())
314
+ p.Reg = ra
315
+ p.From.Type = obj.TYPE_REG
316
+ p.From.Reg = rm
317
+ p.AddRestSourceReg(rn)
318
+ p.To.Type = obj.TYPE_REG
319
+ p.To.Reg = rt
320
+ case ssa.OpARM64ADDconst,
321
+ ssa.OpARM64SUBconst,
322
+ ssa.OpARM64ANDconst,
323
+ ssa.OpARM64ORconst,
324
+ ssa.OpARM64XORconst,
325
+ ssa.OpARM64SLLconst,
326
+ ssa.OpARM64SRLconst,
327
+ ssa.OpARM64SRAconst,
328
+ ssa.OpARM64RORconst,
329
+ ssa.OpARM64RORWconst:
330
+ p := s.Prog(v.Op.Asm())
331
+ p.From.Type = obj.TYPE_CONST
332
+ p.From.Offset = v.AuxInt
333
+ p.Reg = v.Args[0].Reg()
334
+ p.To.Type = obj.TYPE_REG
335
+ p.To.Reg = v.Reg()
336
+ case ssa.OpARM64ADDSconstflags:
337
+ p := s.Prog(v.Op.Asm())
338
+ p.From.Type = obj.TYPE_CONST
339
+ p.From.Offset = v.AuxInt
340
+ p.Reg = v.Args[0].Reg()
341
+ p.To.Type = obj.TYPE_REG
342
+ p.To.Reg = v.Reg0()
343
+ case ssa.OpARM64ADCzerocarry:
344
+ p := s.Prog(v.Op.Asm())
345
+ p.From.Type = obj.TYPE_REG
346
+ p.From.Reg = arm64.REGZERO
347
+ p.Reg = arm64.REGZERO
348
+ p.To.Type = obj.TYPE_REG
349
+ p.To.Reg = v.Reg()
350
+ case ssa.OpARM64ADCSflags,
351
+ ssa.OpARM64ADDSflags,
352
+ ssa.OpARM64SBCSflags,
353
+ ssa.OpARM64SUBSflags:
354
+ r := v.Reg0()
355
+ r1 := v.Args[0].Reg()
356
+ r2 := v.Args[1].Reg()
357
+ p := s.Prog(v.Op.Asm())
358
+ p.From.Type = obj.TYPE_REG
359
+ p.From.Reg = r2
360
+ p.Reg = r1
361
+ p.To.Type = obj.TYPE_REG
362
+ p.To.Reg = r
363
+ case ssa.OpARM64NEGSflags:
364
+ p := s.Prog(v.Op.Asm())
365
+ p.From.Type = obj.TYPE_REG
366
+ p.From.Reg = v.Args[0].Reg()
367
+ p.To.Type = obj.TYPE_REG
368
+ p.To.Reg = v.Reg0()
369
+ case ssa.OpARM64NGCzerocarry:
370
+ p := s.Prog(v.Op.Asm())
371
+ p.From.Type = obj.TYPE_REG
372
+ p.From.Reg = arm64.REGZERO
373
+ p.To.Type = obj.TYPE_REG
374
+ p.To.Reg = v.Reg()
375
+ case ssa.OpARM64EXTRconst,
376
+ ssa.OpARM64EXTRWconst:
377
+ p := s.Prog(v.Op.Asm())
378
+ p.From.Type = obj.TYPE_CONST
379
+ p.From.Offset = v.AuxInt
380
+ p.AddRestSourceReg(v.Args[0].Reg())
381
+ p.Reg = v.Args[1].Reg()
382
+ p.To.Type = obj.TYPE_REG
383
+ p.To.Reg = v.Reg()
384
+ case ssa.OpARM64MVNshiftLL, ssa.OpARM64NEGshiftLL:
385
+ genshift(s, v, v.Op.Asm(), 0, v.Args[0].Reg(), v.Reg(), arm64.SHIFT_LL, v.AuxInt)
386
+ case ssa.OpARM64MVNshiftRL, ssa.OpARM64NEGshiftRL:
387
+ genshift(s, v, v.Op.Asm(), 0, v.Args[0].Reg(), v.Reg(), arm64.SHIFT_LR, v.AuxInt)
388
+ case ssa.OpARM64MVNshiftRA, ssa.OpARM64NEGshiftRA:
389
+ genshift(s, v, v.Op.Asm(), 0, v.Args[0].Reg(), v.Reg(), arm64.SHIFT_AR, v.AuxInt)
390
+ case ssa.OpARM64MVNshiftRO:
391
+ genshift(s, v, v.Op.Asm(), 0, v.Args[0].Reg(), v.Reg(), arm64.SHIFT_ROR, v.AuxInt)
392
+ case ssa.OpARM64ADDshiftLL,
393
+ ssa.OpARM64SUBshiftLL,
394
+ ssa.OpARM64ANDshiftLL,
395
+ ssa.OpARM64ORshiftLL,
396
+ ssa.OpARM64XORshiftLL,
397
+ ssa.OpARM64EONshiftLL,
398
+ ssa.OpARM64ORNshiftLL,
399
+ ssa.OpARM64BICshiftLL:
400
+ genshift(s, v, v.Op.Asm(), v.Args[0].Reg(), v.Args[1].Reg(), v.Reg(), arm64.SHIFT_LL, v.AuxInt)
401
+ case ssa.OpARM64ADDshiftRL,
402
+ ssa.OpARM64SUBshiftRL,
403
+ ssa.OpARM64ANDshiftRL,
404
+ ssa.OpARM64ORshiftRL,
405
+ ssa.OpARM64XORshiftRL,
406
+ ssa.OpARM64EONshiftRL,
407
+ ssa.OpARM64ORNshiftRL,
408
+ ssa.OpARM64BICshiftRL:
409
+ genshift(s, v, v.Op.Asm(), v.Args[0].Reg(), v.Args[1].Reg(), v.Reg(), arm64.SHIFT_LR, v.AuxInt)
410
+ case ssa.OpARM64ADDshiftRA,
411
+ ssa.OpARM64SUBshiftRA,
412
+ ssa.OpARM64ANDshiftRA,
413
+ ssa.OpARM64ORshiftRA,
414
+ ssa.OpARM64XORshiftRA,
415
+ ssa.OpARM64EONshiftRA,
416
+ ssa.OpARM64ORNshiftRA,
417
+ ssa.OpARM64BICshiftRA:
418
+ genshift(s, v, v.Op.Asm(), v.Args[0].Reg(), v.Args[1].Reg(), v.Reg(), arm64.SHIFT_AR, v.AuxInt)
419
+ case ssa.OpARM64ANDshiftRO,
420
+ ssa.OpARM64ORshiftRO,
421
+ ssa.OpARM64XORshiftRO,
422
+ ssa.OpARM64EONshiftRO,
423
+ ssa.OpARM64ORNshiftRO,
424
+ ssa.OpARM64BICshiftRO:
425
+ genshift(s, v, v.Op.Asm(), v.Args[0].Reg(), v.Args[1].Reg(), v.Reg(), arm64.SHIFT_ROR, v.AuxInt)
426
+ case ssa.OpARM64MOVDconst:
427
+ p := s.Prog(v.Op.Asm())
428
+ p.From.Type = obj.TYPE_CONST
429
+ p.From.Offset = v.AuxInt
430
+ p.To.Type = obj.TYPE_REG
431
+ p.To.Reg = v.Reg()
432
+ case ssa.OpARM64FMOVSconst,
433
+ ssa.OpARM64FMOVDconst:
434
+ p := s.Prog(v.Op.Asm())
435
+ p.From.Type = obj.TYPE_FCONST
436
+ p.From.Val = math.Float64frombits(uint64(v.AuxInt))
437
+ p.To.Type = obj.TYPE_REG
438
+ p.To.Reg = v.Reg()
439
+ case ssa.OpARM64FCMPS0,
440
+ ssa.OpARM64FCMPD0:
441
+ p := s.Prog(v.Op.Asm())
442
+ p.From.Type = obj.TYPE_FCONST
443
+ p.From.Val = math.Float64frombits(0)
444
+ p.Reg = v.Args[0].Reg()
445
+ case ssa.OpARM64CMP,
446
+ ssa.OpARM64CMPW,
447
+ ssa.OpARM64CMN,
448
+ ssa.OpARM64CMNW,
449
+ ssa.OpARM64TST,
450
+ ssa.OpARM64TSTW,
451
+ ssa.OpARM64FCMPS,
452
+ ssa.OpARM64FCMPD:
453
+ p := s.Prog(v.Op.Asm())
454
+ p.From.Type = obj.TYPE_REG
455
+ p.From.Reg = v.Args[1].Reg()
456
+ p.Reg = v.Args[0].Reg()
457
+ case ssa.OpARM64CMPconst,
458
+ ssa.OpARM64CMPWconst,
459
+ ssa.OpARM64CMNconst,
460
+ ssa.OpARM64CMNWconst,
461
+ ssa.OpARM64TSTconst,
462
+ ssa.OpARM64TSTWconst:
463
+ p := s.Prog(v.Op.Asm())
464
+ p.From.Type = obj.TYPE_CONST
465
+ p.From.Offset = v.AuxInt
466
+ p.Reg = v.Args[0].Reg()
467
+ case ssa.OpARM64CMPshiftLL, ssa.OpARM64CMNshiftLL, ssa.OpARM64TSTshiftLL:
468
+ genshift(s, v, v.Op.Asm(), v.Args[0].Reg(), v.Args[1].Reg(), 0, arm64.SHIFT_LL, v.AuxInt)
469
+ case ssa.OpARM64CMPshiftRL, ssa.OpARM64CMNshiftRL, ssa.OpARM64TSTshiftRL:
470
+ genshift(s, v, v.Op.Asm(), v.Args[0].Reg(), v.Args[1].Reg(), 0, arm64.SHIFT_LR, v.AuxInt)
471
+ case ssa.OpARM64CMPshiftRA, ssa.OpARM64CMNshiftRA, ssa.OpARM64TSTshiftRA:
472
+ genshift(s, v, v.Op.Asm(), v.Args[0].Reg(), v.Args[1].Reg(), 0, arm64.SHIFT_AR, v.AuxInt)
473
+ case ssa.OpARM64TSTshiftRO:
474
+ genshift(s, v, v.Op.Asm(), v.Args[0].Reg(), v.Args[1].Reg(), 0, arm64.SHIFT_ROR, v.AuxInt)
475
+ case ssa.OpARM64MOVDaddr:
476
+ p := s.Prog(arm64.AMOVD)
477
+ p.From.Type = obj.TYPE_ADDR
478
+ p.From.Reg = v.Args[0].Reg()
479
+ p.To.Type = obj.TYPE_REG
480
+ p.To.Reg = v.Reg()
481
+
482
+ var wantreg string
483
+ // MOVD $sym+off(base), R
484
+ // the assembler expands it as the following:
485
+ // - base is SP: add constant offset to SP (R13)
486
+ // when constant is large, tmp register (R11) may be used
487
+ // - base is SB: load external address from constant pool (use relocation)
488
+ switch v.Aux.(type) {
489
+ default:
490
+ v.Fatalf("aux is of unknown type %T", v.Aux)
491
+ case *obj.LSym:
492
+ wantreg = "SB"
493
+ ssagen.AddAux(&p.From, v)
494
+ case *ir.Name:
495
+ wantreg = "SP"
496
+ ssagen.AddAux(&p.From, v)
497
+ case nil:
498
+ // No sym, just MOVD $off(SP), R
499
+ wantreg = "SP"
500
+ p.From.Offset = v.AuxInt
501
+ }
502
+ if reg := v.Args[0].RegName(); reg != wantreg {
503
+ v.Fatalf("bad reg %s for symbol type %T, want %s", reg, v.Aux, wantreg)
504
+ }
505
+ case ssa.OpARM64MOVBload,
506
+ ssa.OpARM64MOVBUload,
507
+ ssa.OpARM64MOVHload,
508
+ ssa.OpARM64MOVHUload,
509
+ ssa.OpARM64MOVWload,
510
+ ssa.OpARM64MOVWUload,
511
+ ssa.OpARM64MOVDload,
512
+ ssa.OpARM64FMOVSload,
513
+ ssa.OpARM64FMOVDload:
514
+ p := s.Prog(v.Op.Asm())
515
+ p.From.Type = obj.TYPE_MEM
516
+ p.From.Reg = v.Args[0].Reg()
517
+ ssagen.AddAux(&p.From, v)
518
+ p.To.Type = obj.TYPE_REG
519
+ p.To.Reg = v.Reg()
520
+ case ssa.OpARM64LDP, ssa.OpARM64LDPW, ssa.OpARM64LDPSW, ssa.OpARM64FLDPD, ssa.OpARM64FLDPS:
521
+ p := s.Prog(v.Op.Asm())
522
+ p.From.Type = obj.TYPE_MEM
523
+ p.From.Reg = v.Args[0].Reg()
524
+ ssagen.AddAux(&p.From, v)
525
+ p.To.Type = obj.TYPE_REGREG
526
+ p.To.Reg = v.Reg0()
527
+ p.To.Offset = int64(v.Reg1())
528
+ case ssa.OpARM64MOVBloadidx,
529
+ ssa.OpARM64MOVBUloadidx,
530
+ ssa.OpARM64MOVHloadidx,
531
+ ssa.OpARM64MOVHUloadidx,
532
+ ssa.OpARM64MOVWloadidx,
533
+ ssa.OpARM64MOVWUloadidx,
534
+ ssa.OpARM64MOVDloadidx,
535
+ ssa.OpARM64FMOVSloadidx,
536
+ ssa.OpARM64FMOVDloadidx,
537
+ ssa.OpARM64MOVHloadidx2,
538
+ ssa.OpARM64MOVHUloadidx2,
539
+ ssa.OpARM64MOVWloadidx4,
540
+ ssa.OpARM64MOVWUloadidx4,
541
+ ssa.OpARM64MOVDloadidx8,
542
+ ssa.OpARM64FMOVDloadidx8,
543
+ ssa.OpARM64FMOVSloadidx4:
544
+ p := s.Prog(v.Op.Asm())
545
+ p.From = genIndexedOperand(v.Op, v.Args[0].Reg(), v.Args[1].Reg())
546
+ p.To.Type = obj.TYPE_REG
547
+ p.To.Reg = v.Reg()
548
+ case ssa.OpARM64LDAR,
549
+ ssa.OpARM64LDARB,
550
+ ssa.OpARM64LDARW:
551
+ p := s.Prog(v.Op.Asm())
552
+ p.From.Type = obj.TYPE_MEM
553
+ p.From.Reg = v.Args[0].Reg()
554
+ ssagen.AddAux(&p.From, v)
555
+ p.To.Type = obj.TYPE_REG
556
+ p.To.Reg = v.Reg0()
557
+ case ssa.OpARM64MOVBstore,
558
+ ssa.OpARM64MOVHstore,
559
+ ssa.OpARM64MOVWstore,
560
+ ssa.OpARM64MOVDstore,
561
+ ssa.OpARM64FMOVSstore,
562
+ ssa.OpARM64FMOVDstore,
563
+ ssa.OpARM64STLRB,
564
+ ssa.OpARM64STLR,
565
+ ssa.OpARM64STLRW:
566
+ p := s.Prog(v.Op.Asm())
567
+ p.From.Type = obj.TYPE_REG
568
+ p.From.Reg = v.Args[1].Reg()
569
+ p.To.Type = obj.TYPE_MEM
570
+ p.To.Reg = v.Args[0].Reg()
571
+ ssagen.AddAux(&p.To, v)
572
+ case ssa.OpARM64MOVBstoreidx,
573
+ ssa.OpARM64MOVHstoreidx,
574
+ ssa.OpARM64MOVWstoreidx,
575
+ ssa.OpARM64MOVDstoreidx,
576
+ ssa.OpARM64FMOVSstoreidx,
577
+ ssa.OpARM64FMOVDstoreidx,
578
+ ssa.OpARM64MOVHstoreidx2,
579
+ ssa.OpARM64MOVWstoreidx4,
580
+ ssa.OpARM64FMOVSstoreidx4,
581
+ ssa.OpARM64MOVDstoreidx8,
582
+ ssa.OpARM64FMOVDstoreidx8:
583
+ p := s.Prog(v.Op.Asm())
584
+ p.To = genIndexedOperand(v.Op, v.Args[0].Reg(), v.Args[1].Reg())
585
+ p.From.Type = obj.TYPE_REG
586
+ p.From.Reg = v.Args[2].Reg()
587
+ case ssa.OpARM64STP, ssa.OpARM64STPW, ssa.OpARM64FSTPD, ssa.OpARM64FSTPS:
588
+ p := s.Prog(v.Op.Asm())
589
+ p.From.Type = obj.TYPE_REGREG
590
+ p.From.Reg = v.Args[1].Reg()
591
+ p.From.Offset = int64(v.Args[2].Reg())
592
+ p.To.Type = obj.TYPE_MEM
593
+ p.To.Reg = v.Args[0].Reg()
594
+ ssagen.AddAux(&p.To, v)
595
+ case ssa.OpARM64BFI,
596
+ ssa.OpARM64BFXIL:
597
+ p := s.Prog(v.Op.Asm())
598
+ p.From.Type = obj.TYPE_CONST
599
+ p.From.Offset = v.AuxInt >> 8
600
+ p.AddRestSourceConst(v.AuxInt & 0xff)
601
+ p.Reg = v.Args[1].Reg()
602
+ p.To.Type = obj.TYPE_REG
603
+ p.To.Reg = v.Reg()
604
+ case ssa.OpARM64SBFIZ,
605
+ ssa.OpARM64SBFX,
606
+ ssa.OpARM64UBFIZ,
607
+ ssa.OpARM64UBFX:
608
+ p := s.Prog(v.Op.Asm())
609
+ p.From.Type = obj.TYPE_CONST
610
+ p.From.Offset = v.AuxInt >> 8
611
+ p.AddRestSourceConst(v.AuxInt & 0xff)
612
+ p.Reg = v.Args[0].Reg()
613
+ p.To.Type = obj.TYPE_REG
614
+ p.To.Reg = v.Reg()
615
+ case ssa.OpARM64LoweredAtomicExchange64,
616
+ ssa.OpARM64LoweredAtomicExchange32,
617
+ ssa.OpARM64LoweredAtomicExchange8:
618
+ // LDAXR (Rarg0), Rout
619
+ // STLXR Rarg1, (Rarg0), Rtmp
620
+ // CBNZ Rtmp, -2(PC)
621
+ var ld, st obj.As
622
+ switch v.Op {
623
+ case ssa.OpARM64LoweredAtomicExchange8:
624
+ ld = arm64.ALDAXRB
625
+ st = arm64.ASTLXRB
626
+ case ssa.OpARM64LoweredAtomicExchange32:
627
+ ld = arm64.ALDAXRW
628
+ st = arm64.ASTLXRW
629
+ case ssa.OpARM64LoweredAtomicExchange64:
630
+ ld = arm64.ALDAXR
631
+ st = arm64.ASTLXR
632
+ }
633
+ r0 := v.Args[0].Reg()
634
+ r1 := v.Args[1].Reg()
635
+ out := v.Reg0()
636
+ p := s.Prog(ld)
637
+ p.From.Type = obj.TYPE_MEM
638
+ p.From.Reg = r0
639
+ p.To.Type = obj.TYPE_REG
640
+ p.To.Reg = out
641
+ p1 := s.Prog(st)
642
+ p1.From.Type = obj.TYPE_REG
643
+ p1.From.Reg = r1
644
+ p1.To.Type = obj.TYPE_MEM
645
+ p1.To.Reg = r0
646
+ p1.RegTo2 = arm64.REGTMP
647
+ p2 := s.Prog(arm64.ACBNZ)
648
+ p2.From.Type = obj.TYPE_REG
649
+ p2.From.Reg = arm64.REGTMP
650
+ p2.To.Type = obj.TYPE_BRANCH
651
+ p2.To.SetTarget(p)
652
+ case ssa.OpARM64LoweredAtomicExchange64Variant,
653
+ ssa.OpARM64LoweredAtomicExchange32Variant,
654
+ ssa.OpARM64LoweredAtomicExchange8Variant:
655
+ var swap obj.As
656
+ switch v.Op {
657
+ case ssa.OpARM64LoweredAtomicExchange8Variant:
658
+ swap = arm64.ASWPALB
659
+ case ssa.OpARM64LoweredAtomicExchange32Variant:
660
+ swap = arm64.ASWPALW
661
+ case ssa.OpARM64LoweredAtomicExchange64Variant:
662
+ swap = arm64.ASWPALD
663
+ }
664
+ r0 := v.Args[0].Reg()
665
+ r1 := v.Args[1].Reg()
666
+ out := v.Reg0()
667
+
668
+ // SWPALD Rarg1, (Rarg0), Rout
669
+ p := s.Prog(swap)
670
+ p.From.Type = obj.TYPE_REG
671
+ p.From.Reg = r1
672
+ p.To.Type = obj.TYPE_MEM
673
+ p.To.Reg = r0
674
+ p.RegTo2 = out
675
+
676
+ case ssa.OpARM64LoweredAtomicAdd64,
677
+ ssa.OpARM64LoweredAtomicAdd32:
678
+ // LDAXR (Rarg0), Rout
679
+ // ADD Rarg1, Rout
680
+ // STLXR Rout, (Rarg0), Rtmp
681
+ // CBNZ Rtmp, -3(PC)
682
+ ld := arm64.ALDAXR
683
+ st := arm64.ASTLXR
684
+ if v.Op == ssa.OpARM64LoweredAtomicAdd32 {
685
+ ld = arm64.ALDAXRW
686
+ st = arm64.ASTLXRW
687
+ }
688
+ r0 := v.Args[0].Reg()
689
+ r1 := v.Args[1].Reg()
690
+ out := v.Reg0()
691
+ p := s.Prog(ld)
692
+ p.From.Type = obj.TYPE_MEM
693
+ p.From.Reg = r0
694
+ p.To.Type = obj.TYPE_REG
695
+ p.To.Reg = out
696
+ p1 := s.Prog(arm64.AADD)
697
+ p1.From.Type = obj.TYPE_REG
698
+ p1.From.Reg = r1
699
+ p1.To.Type = obj.TYPE_REG
700
+ p1.To.Reg = out
701
+ p2 := s.Prog(st)
702
+ p2.From.Type = obj.TYPE_REG
703
+ p2.From.Reg = out
704
+ p2.To.Type = obj.TYPE_MEM
705
+ p2.To.Reg = r0
706
+ p2.RegTo2 = arm64.REGTMP
707
+ p3 := s.Prog(arm64.ACBNZ)
708
+ p3.From.Type = obj.TYPE_REG
709
+ p3.From.Reg = arm64.REGTMP
710
+ p3.To.Type = obj.TYPE_BRANCH
711
+ p3.To.SetTarget(p)
712
+ case ssa.OpARM64LoweredAtomicAdd64Variant,
713
+ ssa.OpARM64LoweredAtomicAdd32Variant:
714
+ // LDADDAL Rarg1, (Rarg0), Rout
715
+ // ADD Rarg1, Rout
716
+ op := arm64.ALDADDALD
717
+ if v.Op == ssa.OpARM64LoweredAtomicAdd32Variant {
718
+ op = arm64.ALDADDALW
719
+ }
720
+ r0 := v.Args[0].Reg()
721
+ r1 := v.Args[1].Reg()
722
+ out := v.Reg0()
723
+ p := s.Prog(op)
724
+ p.From.Type = obj.TYPE_REG
725
+ p.From.Reg = r1
726
+ p.To.Type = obj.TYPE_MEM
727
+ p.To.Reg = r0
728
+ p.RegTo2 = out
729
+ p1 := s.Prog(arm64.AADD)
730
+ p1.From.Type = obj.TYPE_REG
731
+ p1.From.Reg = r1
732
+ p1.To.Type = obj.TYPE_REG
733
+ p1.To.Reg = out
734
+ case ssa.OpARM64LoweredAtomicCas64,
735
+ ssa.OpARM64LoweredAtomicCas32:
736
+ // LDAXR (Rarg0), Rtmp
737
+ // CMP Rarg1, Rtmp
738
+ // BNE 3(PC)
739
+ // STLXR Rarg2, (Rarg0), Rtmp
740
+ // CBNZ Rtmp, -4(PC)
741
+ // CSET EQ, Rout
742
+ ld := arm64.ALDAXR
743
+ st := arm64.ASTLXR
744
+ cmp := arm64.ACMP
745
+ if v.Op == ssa.OpARM64LoweredAtomicCas32 {
746
+ ld = arm64.ALDAXRW
747
+ st = arm64.ASTLXRW
748
+ cmp = arm64.ACMPW
749
+ }
750
+ r0 := v.Args[0].Reg()
751
+ r1 := v.Args[1].Reg()
752
+ r2 := v.Args[2].Reg()
753
+ out := v.Reg0()
754
+ p := s.Prog(ld)
755
+ p.From.Type = obj.TYPE_MEM
756
+ p.From.Reg = r0
757
+ p.To.Type = obj.TYPE_REG
758
+ p.To.Reg = arm64.REGTMP
759
+ p1 := s.Prog(cmp)
760
+ p1.From.Type = obj.TYPE_REG
761
+ p1.From.Reg = r1
762
+ p1.Reg = arm64.REGTMP
763
+ p2 := s.Prog(arm64.ABNE)
764
+ p2.To.Type = obj.TYPE_BRANCH
765
+ p3 := s.Prog(st)
766
+ p3.From.Type = obj.TYPE_REG
767
+ p3.From.Reg = r2
768
+ p3.To.Type = obj.TYPE_MEM
769
+ p3.To.Reg = r0
770
+ p3.RegTo2 = arm64.REGTMP
771
+ p4 := s.Prog(arm64.ACBNZ)
772
+ p4.From.Type = obj.TYPE_REG
773
+ p4.From.Reg = arm64.REGTMP
774
+ p4.To.Type = obj.TYPE_BRANCH
775
+ p4.To.SetTarget(p)
776
+ p5 := s.Prog(arm64.ACSET)
777
+ p5.From.Type = obj.TYPE_SPECIAL // assembler encodes conditional bits in Offset
778
+ p5.From.Offset = int64(arm64.SPOP_EQ)
779
+ p5.To.Type = obj.TYPE_REG
780
+ p5.To.Reg = out
781
+ p2.To.SetTarget(p5)
782
+ case ssa.OpARM64LoweredAtomicCas64Variant,
783
+ ssa.OpARM64LoweredAtomicCas32Variant:
784
+ // Rarg0: ptr
785
+ // Rarg1: old
786
+ // Rarg2: new
787
+ // MOV Rarg1, Rtmp
788
+ // CASAL Rtmp, (Rarg0), Rarg2
789
+ // CMP Rarg1, Rtmp
790
+ // CSET EQ, Rout
791
+ cas := arm64.ACASALD
792
+ cmp := arm64.ACMP
793
+ mov := arm64.AMOVD
794
+ if v.Op == ssa.OpARM64LoweredAtomicCas32Variant {
795
+ cas = arm64.ACASALW
796
+ cmp = arm64.ACMPW
797
+ mov = arm64.AMOVW
798
+ }
799
+ r0 := v.Args[0].Reg()
800
+ r1 := v.Args[1].Reg()
801
+ r2 := v.Args[2].Reg()
802
+ out := v.Reg0()
803
+
804
+ // MOV Rarg1, Rtmp
805
+ p := s.Prog(mov)
806
+ p.From.Type = obj.TYPE_REG
807
+ p.From.Reg = r1
808
+ p.To.Type = obj.TYPE_REG
809
+ p.To.Reg = arm64.REGTMP
810
+
811
+ // CASAL Rtmp, (Rarg0), Rarg2
812
+ p1 := s.Prog(cas)
813
+ p1.From.Type = obj.TYPE_REG
814
+ p1.From.Reg = arm64.REGTMP
815
+ p1.To.Type = obj.TYPE_MEM
816
+ p1.To.Reg = r0
817
+ p1.RegTo2 = r2
818
+
819
+ // CMP Rarg1, Rtmp
820
+ p2 := s.Prog(cmp)
821
+ p2.From.Type = obj.TYPE_REG
822
+ p2.From.Reg = r1
823
+ p2.Reg = arm64.REGTMP
824
+
825
+ // CSET EQ, Rout
826
+ p3 := s.Prog(arm64.ACSET)
827
+ p3.From.Type = obj.TYPE_SPECIAL // assembler encodes conditional bits in Offset
828
+ p3.From.Offset = int64(arm64.SPOP_EQ)
829
+ p3.To.Type = obj.TYPE_REG
830
+ p3.To.Reg = out
831
+
832
+ case ssa.OpARM64LoweredAtomicAnd64,
833
+ ssa.OpARM64LoweredAtomicOr64,
834
+ ssa.OpARM64LoweredAtomicAnd32,
835
+ ssa.OpARM64LoweredAtomicOr32,
836
+ ssa.OpARM64LoweredAtomicAnd8,
837
+ ssa.OpARM64LoweredAtomicOr8:
838
+ // LDAXR[BW] (Rarg0), Rout
839
+ // AND/OR Rarg1, Rout, tmp1
840
+ // STLXR[BW] tmp1, (Rarg0), Rtmp
841
+ // CBNZ Rtmp, -3(PC)
842
+ ld := arm64.ALDAXR
843
+ st := arm64.ASTLXR
844
+ if v.Op == ssa.OpARM64LoweredAtomicAnd32 || v.Op == ssa.OpARM64LoweredAtomicOr32 {
845
+ ld = arm64.ALDAXRW
846
+ st = arm64.ASTLXRW
847
+ }
848
+ if v.Op == ssa.OpARM64LoweredAtomicAnd8 || v.Op == ssa.OpARM64LoweredAtomicOr8 {
849
+ ld = arm64.ALDAXRB
850
+ st = arm64.ASTLXRB
851
+ }
852
+ r0 := v.Args[0].Reg()
853
+ r1 := v.Args[1].Reg()
854
+ out := v.Reg0()
855
+ tmp := v.RegTmp()
856
+ p := s.Prog(ld)
857
+ p.From.Type = obj.TYPE_MEM
858
+ p.From.Reg = r0
859
+ p.To.Type = obj.TYPE_REG
860
+ p.To.Reg = out
861
+ p1 := s.Prog(v.Op.Asm())
862
+ p1.From.Type = obj.TYPE_REG
863
+ p1.From.Reg = r1
864
+ p1.Reg = out
865
+ p1.To.Type = obj.TYPE_REG
866
+ p1.To.Reg = tmp
867
+ p2 := s.Prog(st)
868
+ p2.From.Type = obj.TYPE_REG
869
+ p2.From.Reg = tmp
870
+ p2.To.Type = obj.TYPE_MEM
871
+ p2.To.Reg = r0
872
+ p2.RegTo2 = arm64.REGTMP
873
+ p3 := s.Prog(arm64.ACBNZ)
874
+ p3.From.Type = obj.TYPE_REG
875
+ p3.From.Reg = arm64.REGTMP
876
+ p3.To.Type = obj.TYPE_BRANCH
877
+ p3.To.SetTarget(p)
878
+
879
+ case ssa.OpARM64LoweredAtomicAnd8Variant,
880
+ ssa.OpARM64LoweredAtomicAnd32Variant,
881
+ ssa.OpARM64LoweredAtomicAnd64Variant:
882
+ atomic_clear := arm64.ALDCLRALD
883
+ if v.Op == ssa.OpARM64LoweredAtomicAnd32Variant {
884
+ atomic_clear = arm64.ALDCLRALW
885
+ }
886
+ if v.Op == ssa.OpARM64LoweredAtomicAnd8Variant {
887
+ atomic_clear = arm64.ALDCLRALB
888
+ }
889
+ r0 := v.Args[0].Reg()
890
+ r1 := v.Args[1].Reg()
891
+ out := v.Reg0()
892
+
893
+ // MNV Rarg1 Rtemp
894
+ p := s.Prog(arm64.AMVN)
895
+ p.From.Type = obj.TYPE_REG
896
+ p.From.Reg = r1
897
+ p.To.Type = obj.TYPE_REG
898
+ p.To.Reg = arm64.REGTMP
899
+
900
+ // LDCLRAL[BDW] Rtemp, (Rarg0), Rout
901
+ p1 := s.Prog(atomic_clear)
902
+ p1.From.Type = obj.TYPE_REG
903
+ p1.From.Reg = arm64.REGTMP
904
+ p1.To.Type = obj.TYPE_MEM
905
+ p1.To.Reg = r0
906
+ p1.RegTo2 = out
907
+
908
+ case ssa.OpARM64LoweredAtomicOr8Variant,
909
+ ssa.OpARM64LoweredAtomicOr32Variant,
910
+ ssa.OpARM64LoweredAtomicOr64Variant:
911
+ atomic_or := arm64.ALDORALD
912
+ if v.Op == ssa.OpARM64LoweredAtomicOr32Variant {
913
+ atomic_or = arm64.ALDORALW
914
+ }
915
+ if v.Op == ssa.OpARM64LoweredAtomicOr8Variant {
916
+ atomic_or = arm64.ALDORALB
917
+ }
918
+ r0 := v.Args[0].Reg()
919
+ r1 := v.Args[1].Reg()
920
+ out := v.Reg0()
921
+
922
+ // LDORAL[BDW] Rarg1, (Rarg0), Rout
923
+ p := s.Prog(atomic_or)
924
+ p.From.Type = obj.TYPE_REG
925
+ p.From.Reg = r1
926
+ p.To.Type = obj.TYPE_MEM
927
+ p.To.Reg = r0
928
+ p.RegTo2 = out
929
+
930
+ case ssa.OpARM64MOVBreg,
931
+ ssa.OpARM64MOVBUreg,
932
+ ssa.OpARM64MOVHreg,
933
+ ssa.OpARM64MOVHUreg,
934
+ ssa.OpARM64MOVWreg,
935
+ ssa.OpARM64MOVWUreg:
936
+ a := v.Args[0]
937
+ for a.Op == ssa.OpCopy || a.Op == ssa.OpARM64MOVDreg {
938
+ a = a.Args[0]
939
+ }
940
+ if a.Op == ssa.OpLoadReg {
941
+ t := a.Type
942
+ switch {
943
+ case v.Op == ssa.OpARM64MOVBreg && t.Size() == 1 && t.IsSigned(),
944
+ v.Op == ssa.OpARM64MOVBUreg && t.Size() == 1 && !t.IsSigned(),
945
+ v.Op == ssa.OpARM64MOVHreg && t.Size() == 2 && t.IsSigned(),
946
+ v.Op == ssa.OpARM64MOVHUreg && t.Size() == 2 && !t.IsSigned(),
947
+ v.Op == ssa.OpARM64MOVWreg && t.Size() == 4 && t.IsSigned(),
948
+ v.Op == ssa.OpARM64MOVWUreg && t.Size() == 4 && !t.IsSigned():
949
+ // arg is a proper-typed load, already zero/sign-extended, don't extend again
950
+ if v.Reg() == v.Args[0].Reg() {
951
+ return
952
+ }
953
+ p := s.Prog(arm64.AMOVD)
954
+ p.From.Type = obj.TYPE_REG
955
+ p.From.Reg = v.Args[0].Reg()
956
+ p.To.Type = obj.TYPE_REG
957
+ p.To.Reg = v.Reg()
958
+ return
959
+ default:
960
+ }
961
+ }
962
+ fallthrough
963
+ case ssa.OpARM64MVN,
964
+ ssa.OpARM64NEG,
965
+ ssa.OpARM64FABSD,
966
+ ssa.OpARM64FMOVDfpgp,
967
+ ssa.OpARM64FMOVDgpfp,
968
+ ssa.OpARM64FMOVSfpgp,
969
+ ssa.OpARM64FMOVSgpfp,
970
+ ssa.OpARM64FNEGS,
971
+ ssa.OpARM64FNEGD,
972
+ ssa.OpARM64FSQRTS,
973
+ ssa.OpARM64FSQRTD,
974
+ ssa.OpARM64FCVTZSSW,
975
+ ssa.OpARM64FCVTZSDW,
976
+ ssa.OpARM64FCVTZUSW,
977
+ ssa.OpARM64FCVTZUDW,
978
+ ssa.OpARM64FCVTZSS,
979
+ ssa.OpARM64FCVTZSD,
980
+ ssa.OpARM64FCVTZUS,
981
+ ssa.OpARM64FCVTZUD,
982
+ ssa.OpARM64SCVTFWS,
983
+ ssa.OpARM64SCVTFWD,
984
+ ssa.OpARM64SCVTFS,
985
+ ssa.OpARM64SCVTFD,
986
+ ssa.OpARM64UCVTFWS,
987
+ ssa.OpARM64UCVTFWD,
988
+ ssa.OpARM64UCVTFS,
989
+ ssa.OpARM64UCVTFD,
990
+ ssa.OpARM64FCVTSD,
991
+ ssa.OpARM64FCVTDS,
992
+ ssa.OpARM64REV,
993
+ ssa.OpARM64REVW,
994
+ ssa.OpARM64REV16,
995
+ ssa.OpARM64REV16W,
996
+ ssa.OpARM64RBIT,
997
+ ssa.OpARM64RBITW,
998
+ ssa.OpARM64CLZ,
999
+ ssa.OpARM64CLZW,
1000
+ ssa.OpARM64FRINTAD,
1001
+ ssa.OpARM64FRINTMD,
1002
+ ssa.OpARM64FRINTND,
1003
+ ssa.OpARM64FRINTPD,
1004
+ ssa.OpARM64FRINTZD:
1005
+ p := s.Prog(v.Op.Asm())
1006
+ p.From.Type = obj.TYPE_REG
1007
+ p.From.Reg = v.Args[0].Reg()
1008
+ p.To.Type = obj.TYPE_REG
1009
+ p.To.Reg = v.Reg()
1010
+ case ssa.OpARM64LoweredRound32F, ssa.OpARM64LoweredRound64F:
1011
+ // input is already rounded
1012
+ case ssa.OpARM64VCNT:
1013
+ p := s.Prog(v.Op.Asm())
1014
+ p.From.Type = obj.TYPE_REG
1015
+ p.From.Reg = (v.Args[0].Reg()-arm64.REG_F0)&31 + arm64.REG_ARNG + ((arm64.ARNG_8B & 15) << 5)
1016
+ p.To.Type = obj.TYPE_REG
1017
+ p.To.Reg = (v.Reg()-arm64.REG_F0)&31 + arm64.REG_ARNG + ((arm64.ARNG_8B & 15) << 5)
1018
+ case ssa.OpARM64VUADDLV:
1019
+ p := s.Prog(v.Op.Asm())
1020
+ p.From.Type = obj.TYPE_REG
1021
+ p.From.Reg = (v.Args[0].Reg()-arm64.REG_F0)&31 + arm64.REG_ARNG + ((arm64.ARNG_8B & 15) << 5)
1022
+ p.To.Type = obj.TYPE_REG
1023
+ p.To.Reg = v.Reg() - arm64.REG_F0 + arm64.REG_V0
1024
+ case ssa.OpARM64CSEL, ssa.OpARM64CSEL0:
1025
+ r1 := int16(arm64.REGZERO)
1026
+ if v.Op != ssa.OpARM64CSEL0 {
1027
+ r1 = v.Args[1].Reg()
1028
+ }
1029
+ p := s.Prog(v.Op.Asm())
1030
+ p.From.Type = obj.TYPE_SPECIAL // assembler encodes conditional bits in Offset
1031
+ condCode := condBits[ssa.Op(v.AuxInt)]
1032
+ p.From.Offset = int64(condCode)
1033
+ p.Reg = v.Args[0].Reg()
1034
+ p.AddRestSourceReg(r1)
1035
+ p.To.Type = obj.TYPE_REG
1036
+ p.To.Reg = v.Reg()
1037
+ case ssa.OpARM64CSINC, ssa.OpARM64CSINV, ssa.OpARM64CSNEG:
1038
+ p := s.Prog(v.Op.Asm())
1039
+ p.From.Type = obj.TYPE_SPECIAL // assembler encodes conditional bits in Offset
1040
+ condCode := condBits[ssa.Op(v.AuxInt)]
1041
+ p.From.Offset = int64(condCode)
1042
+ p.Reg = v.Args[0].Reg()
1043
+ p.AddRestSourceReg(v.Args[1].Reg())
1044
+ p.To.Type = obj.TYPE_REG
1045
+ p.To.Reg = v.Reg()
1046
+ case ssa.OpARM64CSETM:
1047
+ p := s.Prog(arm64.ACSETM)
1048
+ p.From.Type = obj.TYPE_SPECIAL // assembler encodes conditional bits in Offset
1049
+ condCode := condBits[ssa.Op(v.AuxInt)]
1050
+ p.From.Offset = int64(condCode)
1051
+ p.To.Type = obj.TYPE_REG
1052
+ p.To.Reg = v.Reg()
1053
+ case ssa.OpARM64CCMP,
1054
+ ssa.OpARM64CCMN,
1055
+ ssa.OpARM64CCMPconst,
1056
+ ssa.OpARM64CCMNconst,
1057
+ ssa.OpARM64CCMPW,
1058
+ ssa.OpARM64CCMNW,
1059
+ ssa.OpARM64CCMPWconst,
1060
+ ssa.OpARM64CCMNWconst:
1061
+ p := s.Prog(v.Op.Asm())
1062
+ p.Reg = v.Args[0].Reg()
1063
+ params := v.AuxArm64ConditionalParams()
1064
+ p.From.Type = obj.TYPE_SPECIAL // assembler encodes conditional bits in Offset
1065
+ p.From.Offset = int64(condBits[params.Cond()])
1066
+ constValue, ok := params.ConstValue()
1067
+ if ok {
1068
+ p.AddRestSourceConst(constValue)
1069
+ } else {
1070
+ p.AddRestSourceReg(v.Args[1].Reg())
1071
+ }
1072
+ p.To.Type = obj.TYPE_CONST
1073
+ p.To.Offset = params.Nzcv()
1074
+ case ssa.OpARM64LoweredZero:
1075
+ ptrReg := v.Args[0].Reg()
1076
+ n := v.AuxInt
1077
+ if n < 16 {
1078
+ v.Fatalf("Zero too small %d", n)
1079
+ }
1080
+
1081
+ // Generate zeroing instructions.
1082
+ var off int64
1083
+ for n >= 16 {
1084
+ // STP (ZR, ZR), off(ptrReg)
1085
+ zero16(s, ptrReg, off, false)
1086
+ off += 16
1087
+ n -= 16
1088
+ }
1089
+ // Write any fractional portion.
1090
+ // An overlapping 16-byte write can't be used here
1091
+ // because STP's offsets must be a multiple of 8.
1092
+ if n > 8 {
1093
+ // MOVD ZR, off(ptrReg)
1094
+ zero8(s, ptrReg, off)
1095
+ off += 8
1096
+ n -= 8
1097
+ }
1098
+ if n != 0 {
1099
+ // MOVD ZR, off+n-8(ptrReg)
1100
+ // TODO: for n<=4 we could use a smaller write.
1101
+ zero8(s, ptrReg, off+n-8)
1102
+ }
1103
+ case ssa.OpARM64LoweredZeroLoop:
1104
+ ptrReg := v.Args[0].Reg()
1105
+ countReg := v.RegTmp()
1106
+ n := v.AuxInt
1107
+ loopSize := int64(64)
1108
+ if n < 3*loopSize {
1109
+ // - a loop count of 0 won't work.
1110
+ // - a loop count of 1 is useless.
1111
+ // - a loop count of 2 is a code size ~tie
1112
+ // 3 instructions to implement the loop
1113
+ // 4 instructions in the loop body
1114
+ // vs
1115
+ // 8 instructions in the straightline code
1116
+ // Might as well use straightline code.
1117
+ v.Fatalf("ZeroLoop size too small %d", n)
1118
+ }
1119
+
1120
+ // Put iteration count in a register.
1121
+ // MOVD $n, countReg
1122
+ p := s.Prog(arm64.AMOVD)
1123
+ p.From.Type = obj.TYPE_CONST
1124
+ p.From.Offset = n / loopSize
1125
+ p.To.Type = obj.TYPE_REG
1126
+ p.To.Reg = countReg
1127
+ cntInit := p
1128
+
1129
+ // Zero loopSize bytes starting at ptrReg.
1130
+ // Increment ptrReg by loopSize as a side effect.
1131
+ for range loopSize / 16 {
1132
+ // STP.P (ZR, ZR), 16(ptrReg)
1133
+ zero16(s, ptrReg, 0, true)
1134
+ // TODO: should we use the postincrement form,
1135
+ // or use a separate += 64 instruction?
1136
+ // postincrement saves an instruction, but maybe
1137
+ // it requires more integer units to do the +=16s.
1138
+ }
1139
+ // Decrement loop count.
1140
+ // SUB $1, countReg
1141
+ p = s.Prog(arm64.ASUB)
1142
+ p.From.Type = obj.TYPE_CONST
1143
+ p.From.Offset = 1
1144
+ p.To.Type = obj.TYPE_REG
1145
+ p.To.Reg = countReg
1146
+ // Jump to loop header if we're not done yet.
1147
+ // CBNZ head
1148
+ p = s.Prog(arm64.ACBNZ)
1149
+ p.From.Type = obj.TYPE_REG
1150
+ p.From.Reg = countReg
1151
+ p.To.Type = obj.TYPE_BRANCH
1152
+ p.To.SetTarget(cntInit.Link)
1153
+
1154
+ // Multiples of the loop size are now done.
1155
+ n %= loopSize
1156
+
1157
+ // Write any fractional portion.
1158
+ var off int64
1159
+ for n >= 16 {
1160
+ // STP (ZR, ZR), off(ptrReg)
1161
+ zero16(s, ptrReg, off, false)
1162
+ off += 16
1163
+ n -= 16
1164
+ }
1165
+ if n > 8 {
1166
+ // Note: an overlapping 16-byte write can't be used
1167
+ // here because STP's offsets must be a multiple of 8.
1168
+ // MOVD ZR, off(ptrReg)
1169
+ zero8(s, ptrReg, off)
1170
+ off += 8
1171
+ n -= 8
1172
+ }
1173
+ if n != 0 {
1174
+ // MOVD ZR, off+n-8(ptrReg)
1175
+ // TODO: for n<=4 we could use a smaller write.
1176
+ zero8(s, ptrReg, off+n-8)
1177
+ }
1178
+ // TODO: maybe we should use the count register to instead
1179
+ // hold an end pointer and compare against that?
1180
+ // ADD $n, ptrReg, endReg
1181
+ // then
1182
+ // CMP ptrReg, endReg
1183
+ // BNE loop
1184
+ // There's a past-the-end pointer here, any problem with that?
1185
+
1186
+ case ssa.OpARM64LoweredMove:
1187
+ dstReg := v.Args[0].Reg()
1188
+ srcReg := v.Args[1].Reg()
1189
+ if dstReg == srcReg {
1190
+ break
1191
+ }
1192
+ tmpReg1 := int16(arm64.REG_R25)
1193
+ tmpFReg1 := int16(arm64.REG_F16)
1194
+ tmpFReg2 := int16(arm64.REG_F17)
1195
+ n := v.AuxInt
1196
+ if n < 16 {
1197
+ v.Fatalf("Move too small %d", n)
1198
+ }
1199
+
1200
+ // Generate copying instructions.
1201
+ var off int64
1202
+ for n >= 32 {
1203
+ // FLDPQ off(srcReg), (tmpFReg1, tmpFReg2)
1204
+ // FSTPQ (tmpFReg1, tmpFReg2), off(dstReg)
1205
+ move32(s, srcReg, dstReg, tmpFReg1, tmpFReg2, off, false)
1206
+ off += 32
1207
+ n -= 32
1208
+ }
1209
+ for n >= 16 {
1210
+ // FMOVQ off(src), tmpFReg1
1211
+ // FMOVQ tmpFReg1, off(dst)
1212
+ move16(s, srcReg, dstReg, tmpFReg1, off, false)
1213
+ off += 16
1214
+ n -= 16
1215
+ }
1216
+ if n > 8 {
1217
+ // MOVD off(srcReg), tmpReg1
1218
+ // MOVD tmpReg1, off(dstReg)
1219
+ move8(s, srcReg, dstReg, tmpReg1, off)
1220
+ off += 8
1221
+ n -= 8
1222
+ }
1223
+ if n != 0 {
1224
+ // MOVD off+n-8(srcReg), tmpReg1
1225
+ // MOVD tmpReg1, off+n-8(dstReg)
1226
+ move8(s, srcReg, dstReg, tmpReg1, off+n-8)
1227
+ }
1228
+ case ssa.OpARM64LoweredMoveLoop:
1229
+ dstReg := v.Args[0].Reg()
1230
+ srcReg := v.Args[1].Reg()
1231
+ if dstReg == srcReg {
1232
+ break
1233
+ }
1234
+ countReg := int16(arm64.REG_R24)
1235
+ tmpReg1 := int16(arm64.REG_R25)
1236
+ tmpFReg1 := int16(arm64.REG_F16)
1237
+ tmpFReg2 := int16(arm64.REG_F17)
1238
+ n := v.AuxInt
1239
+ loopSize := int64(64)
1240
+ if n < 3*loopSize {
1241
+ // - a loop count of 0 won't work.
1242
+ // - a loop count of 1 is useless.
1243
+ // - a loop count of 2 is a code size ~tie
1244
+ // 3 instructions to implement the loop
1245
+ // 4 instructions in the loop body
1246
+ // vs
1247
+ // 8 instructions in the straightline code
1248
+ // Might as well use straightline code.
1249
+ v.Fatalf("ZeroLoop size too small %d", n)
1250
+ }
1251
+
1252
+ // Put iteration count in a register.
1253
+ // MOVD $n, countReg
1254
+ p := s.Prog(arm64.AMOVD)
1255
+ p.From.Type = obj.TYPE_CONST
1256
+ p.From.Offset = n / loopSize
1257
+ p.To.Type = obj.TYPE_REG
1258
+ p.To.Reg = countReg
1259
+ cntInit := p
1260
+
1261
+ // Move loopSize bytes starting at srcReg to dstReg.
1262
+ // Increment srcReg and destReg by loopSize as a side effect.
1263
+ for range loopSize / 32 {
1264
+ // FLDPQ.P 32(srcReg), (tmpFReg1, tmpFReg2)
1265
+ // FSTPQ.P (tmpFReg1, tmpFReg2), 32(dstReg)
1266
+ move32(s, srcReg, dstReg, tmpFReg1, tmpFReg2, 0, true)
1267
+ }
1268
+ // Decrement loop count.
1269
+ // SUB $1, countReg
1270
+ p = s.Prog(arm64.ASUB)
1271
+ p.From.Type = obj.TYPE_CONST
1272
+ p.From.Offset = 1
1273
+ p.To.Type = obj.TYPE_REG
1274
+ p.To.Reg = countReg
1275
+ // Jump to loop header if we're not done yet.
1276
+ // CBNZ head
1277
+ p = s.Prog(arm64.ACBNZ)
1278
+ p.From.Type = obj.TYPE_REG
1279
+ p.From.Reg = countReg
1280
+ p.To.Type = obj.TYPE_BRANCH
1281
+ p.To.SetTarget(cntInit.Link)
1282
+
1283
+ // Multiples of the loop size are now done.
1284
+ n %= loopSize
1285
+
1286
+ // Copy any fractional portion.
1287
+ var off int64
1288
+ for n >= 32 {
1289
+ // FLDPQ off(srcReg), (tmpFReg1, tmpFReg2)
1290
+ // FSTPQ (tmpFReg1, tmpFReg2), off(dstReg)
1291
+ move32(s, srcReg, dstReg, tmpFReg1, tmpFReg2, off, false)
1292
+ off += 32
1293
+ n -= 32
1294
+ }
1295
+ for n >= 16 {
1296
+ // FMOVQ off(src), tmpFReg1
1297
+ // FMOVQ tmpFReg1, off(dst)
1298
+ move16(s, srcReg, dstReg, tmpFReg1, off, false)
1299
+ off += 16
1300
+ n -= 16
1301
+ }
1302
+ if n > 8 {
1303
+ // MOVD off(srcReg), tmpReg1
1304
+ // MOVD tmpReg1, off(dstReg)
1305
+ move8(s, srcReg, dstReg, tmpReg1, off)
1306
+ off += 8
1307
+ n -= 8
1308
+ }
1309
+ if n != 0 {
1310
+ // MOVD off+n-8(srcReg), tmpReg1
1311
+ // MOVD tmpReg1, off+n-8(dstReg)
1312
+ move8(s, srcReg, dstReg, tmpReg1, off+n-8)
1313
+ }
1314
+
1315
+ case ssa.OpARM64CALLstatic, ssa.OpARM64CALLclosure, ssa.OpARM64CALLinter:
1316
+ s.Call(v)
1317
+ case ssa.OpARM64CALLtail:
1318
+ s.TailCall(v)
1319
+ case ssa.OpARM64LoweredWB:
1320
+ p := s.Prog(obj.ACALL)
1321
+ p.To.Type = obj.TYPE_MEM
1322
+ p.To.Name = obj.NAME_EXTERN
1323
+ // AuxInt encodes how many buffer entries we need.
1324
+ p.To.Sym = ir.Syms.GCWriteBarrier[v.AuxInt-1]
1325
+ case ssa.OpARM64LoweredMemEq:
1326
+ p := s.Prog(obj.ACALL)
1327
+ p.To.Type = obj.TYPE_MEM
1328
+ p.To.Name = obj.NAME_EXTERN
1329
+ p.To.Sym = ir.Syms.Memequal
1330
+
1331
+ case ssa.OpARM64LoweredPanicBoundsRR, ssa.OpARM64LoweredPanicBoundsRC, ssa.OpARM64LoweredPanicBoundsCR, ssa.OpARM64LoweredPanicBoundsCC:
1332
+ // Compute the constant we put in the PCData entry for this call.
1333
+ code, signed := ssa.BoundsKind(v.AuxInt).Code()
1334
+ xIsReg := false
1335
+ yIsReg := false
1336
+ xVal := 0
1337
+ yVal := 0
1338
+ switch v.Op {
1339
+ case ssa.OpARM64LoweredPanicBoundsRR:
1340
+ xIsReg = true
1341
+ xVal = int(v.Args[0].Reg() - arm64.REG_R0)
1342
+ yIsReg = true
1343
+ yVal = int(v.Args[1].Reg() - arm64.REG_R0)
1344
+ case ssa.OpARM64LoweredPanicBoundsRC:
1345
+ xIsReg = true
1346
+ xVal = int(v.Args[0].Reg() - arm64.REG_R0)
1347
+ c := v.Aux.(ssa.PanicBoundsC).C
1348
+ if c >= 0 && c <= abi.BoundsMaxConst {
1349
+ yVal = int(c)
1350
+ } else {
1351
+ // Move constant to a register
1352
+ yIsReg = true
1353
+ if yVal == xVal {
1354
+ yVal = 1
1355
+ }
1356
+ p := s.Prog(arm64.AMOVD)
1357
+ p.From.Type = obj.TYPE_CONST
1358
+ p.From.Offset = c
1359
+ p.To.Type = obj.TYPE_REG
1360
+ p.To.Reg = arm64.REG_R0 + int16(yVal)
1361
+ }
1362
+ case ssa.OpARM64LoweredPanicBoundsCR:
1363
+ yIsReg = true
1364
+ yVal = int(v.Args[0].Reg() - arm64.REG_R0)
1365
+ c := v.Aux.(ssa.PanicBoundsC).C
1366
+ if c >= 0 && c <= abi.BoundsMaxConst {
1367
+ xVal = int(c)
1368
+ } else {
1369
+ // Move constant to a register
1370
+ if xVal == yVal {
1371
+ xVal = 1
1372
+ }
1373
+ p := s.Prog(arm64.AMOVD)
1374
+ p.From.Type = obj.TYPE_CONST
1375
+ p.From.Offset = c
1376
+ p.To.Type = obj.TYPE_REG
1377
+ p.To.Reg = arm64.REG_R0 + int16(xVal)
1378
+ }
1379
+ case ssa.OpARM64LoweredPanicBoundsCC:
1380
+ c := v.Aux.(ssa.PanicBoundsCC).Cx
1381
+ if c >= 0 && c <= abi.BoundsMaxConst {
1382
+ xVal = int(c)
1383
+ } else {
1384
+ // Move constant to a register
1385
+ xIsReg = true
1386
+ p := s.Prog(arm64.AMOVD)
1387
+ p.From.Type = obj.TYPE_CONST
1388
+ p.From.Offset = c
1389
+ p.To.Type = obj.TYPE_REG
1390
+ p.To.Reg = arm64.REG_R0 + int16(xVal)
1391
+ }
1392
+ c = v.Aux.(ssa.PanicBoundsCC).Cy
1393
+ if c >= 0 && c <= abi.BoundsMaxConst {
1394
+ yVal = int(c)
1395
+ } else {
1396
+ // Move constant to a register
1397
+ yIsReg = true
1398
+ yVal = 1
1399
+ p := s.Prog(arm64.AMOVD)
1400
+ p.From.Type = obj.TYPE_CONST
1401
+ p.From.Offset = c
1402
+ p.To.Type = obj.TYPE_REG
1403
+ p.To.Reg = arm64.REG_R0 + int16(yVal)
1404
+ }
1405
+ }
1406
+ c := abi.BoundsEncode(code, signed, xIsReg, yIsReg, xVal, yVal)
1407
+
1408
+ p := s.Prog(obj.APCDATA)
1409
+ p.From.SetConst(abi.PCDATA_PanicBounds)
1410
+ p.To.SetConst(int64(c))
1411
+ p = s.Prog(obj.ACALL)
1412
+ p.To.Type = obj.TYPE_MEM
1413
+ p.To.Name = obj.NAME_EXTERN
1414
+ p.To.Sym = ir.Syms.PanicBounds
1415
+
1416
+ case ssa.OpARM64LoweredNilCheck:
1417
+ // Issue a load which will fault if arg is nil.
1418
+ p := s.Prog(arm64.AMOVB)
1419
+ p.From.Type = obj.TYPE_MEM
1420
+ p.From.Reg = v.Args[0].Reg()
1421
+ ssagen.AddAux(&p.From, v)
1422
+ p.To.Type = obj.TYPE_REG
1423
+ p.To.Reg = arm64.REGTMP
1424
+ if logopt.Enabled() {
1425
+ logopt.LogOpt(v.Pos, "nilcheck", "genssa", v.Block.Func.Name)
1426
+ }
1427
+ if base.Debug.Nil != 0 && v.Pos.Line() > 1 { // v.Line==1 in generated wrappers
1428
+ base.WarnfAt(v.Pos, "generated nil check")
1429
+ }
1430
+ case ssa.OpARM64Equal,
1431
+ ssa.OpARM64NotEqual,
1432
+ ssa.OpARM64LessThan,
1433
+ ssa.OpARM64LessEqual,
1434
+ ssa.OpARM64GreaterThan,
1435
+ ssa.OpARM64GreaterEqual,
1436
+ ssa.OpARM64LessThanU,
1437
+ ssa.OpARM64LessEqualU,
1438
+ ssa.OpARM64GreaterThanU,
1439
+ ssa.OpARM64GreaterEqualU,
1440
+ ssa.OpARM64LessThanF,
1441
+ ssa.OpARM64LessEqualF,
1442
+ ssa.OpARM64GreaterThanF,
1443
+ ssa.OpARM64GreaterEqualF,
1444
+ ssa.OpARM64NotLessThanF,
1445
+ ssa.OpARM64NotLessEqualF,
1446
+ ssa.OpARM64NotGreaterThanF,
1447
+ ssa.OpARM64NotGreaterEqualF,
1448
+ ssa.OpARM64LessThanNoov,
1449
+ ssa.OpARM64GreaterEqualNoov:
1450
+ // generate boolean values using CSET
1451
+ p := s.Prog(arm64.ACSET)
1452
+ p.From.Type = obj.TYPE_SPECIAL // assembler encodes conditional bits in Offset
1453
+ condCode := condBits[v.Op]
1454
+ p.From.Offset = int64(condCode)
1455
+ p.To.Type = obj.TYPE_REG
1456
+ p.To.Reg = v.Reg()
1457
+ case ssa.OpARM64PRFM:
1458
+ p := s.Prog(v.Op.Asm())
1459
+ p.From.Type = obj.TYPE_MEM
1460
+ p.From.Reg = v.Args[0].Reg()
1461
+ p.To.Type = obj.TYPE_CONST
1462
+ p.To.Offset = v.AuxInt
1463
+ case ssa.OpARM64LoweredGetClosurePtr:
1464
+ // Closure pointer is R26 (arm64.REGCTXT).
1465
+ ssagen.CheckLoweredGetClosurePtr(v)
1466
+ case ssa.OpARM64LoweredGetCallerSP:
1467
+ // caller's SP is FixedFrameSize below the address of the first arg
1468
+ p := s.Prog(arm64.AMOVD)
1469
+ p.From.Type = obj.TYPE_ADDR
1470
+ p.From.Offset = -base.Ctxt.Arch.FixedFrameSize
1471
+ p.From.Name = obj.NAME_PARAM
1472
+ p.To.Type = obj.TYPE_REG
1473
+ p.To.Reg = v.Reg()
1474
+ case ssa.OpARM64LoweredGetCallerPC:
1475
+ p := s.Prog(obj.AGETCALLERPC)
1476
+ p.To.Type = obj.TYPE_REG
1477
+ p.To.Reg = v.Reg()
1478
+ case ssa.OpARM64DMB:
1479
+ p := s.Prog(v.Op.Asm())
1480
+ p.From.Type = obj.TYPE_CONST
1481
+ p.From.Offset = v.AuxInt
1482
+ case ssa.OpARM64FlagConstant:
1483
+ v.Fatalf("FlagConstant op should never make it to codegen %v", v.LongString())
1484
+ case ssa.OpARM64InvertFlags:
1485
+ v.Fatalf("InvertFlags should never make it to codegen %v", v.LongString())
1486
+ case ssa.OpClobber:
1487
+ // MOVW $0xdeaddead, REGTMP
1488
+ // MOVW REGTMP, (slot)
1489
+ // MOVW REGTMP, 4(slot)
1490
+ p := s.Prog(arm64.AMOVW)
1491
+ p.From.Type = obj.TYPE_CONST
1492
+ p.From.Offset = 0xdeaddead
1493
+ p.To.Type = obj.TYPE_REG
1494
+ p.To.Reg = arm64.REGTMP
1495
+ p = s.Prog(arm64.AMOVW)
1496
+ p.From.Type = obj.TYPE_REG
1497
+ p.From.Reg = arm64.REGTMP
1498
+ p.To.Type = obj.TYPE_MEM
1499
+ p.To.Reg = arm64.REGSP
1500
+ ssagen.AddAux(&p.To, v)
1501
+ p = s.Prog(arm64.AMOVW)
1502
+ p.From.Type = obj.TYPE_REG
1503
+ p.From.Reg = arm64.REGTMP
1504
+ p.To.Type = obj.TYPE_MEM
1505
+ p.To.Reg = arm64.REGSP
1506
+ ssagen.AddAux2(&p.To, v, v.AuxInt+4)
1507
+ case ssa.OpClobberReg:
1508
+ x := uint64(0xdeaddeaddeaddead)
1509
+ p := s.Prog(arm64.AMOVD)
1510
+ p.From.Type = obj.TYPE_CONST
1511
+ p.From.Offset = int64(x)
1512
+ p.To.Type = obj.TYPE_REG
1513
+ p.To.Reg = v.Reg()
1514
+ default:
1515
+ v.Fatalf("genValue not implemented: %s", v.LongString())
1516
+ }
1517
+ }
1518
+
1519
+ var condBits = map[ssa.Op]arm64.SpecialOperand{
1520
+ ssa.OpARM64Equal: arm64.SPOP_EQ,
1521
+ ssa.OpARM64NotEqual: arm64.SPOP_NE,
1522
+ ssa.OpARM64LessThan: arm64.SPOP_LT,
1523
+ ssa.OpARM64LessThanU: arm64.SPOP_LO,
1524
+ ssa.OpARM64LessEqual: arm64.SPOP_LE,
1525
+ ssa.OpARM64LessEqualU: arm64.SPOP_LS,
1526
+ ssa.OpARM64GreaterThan: arm64.SPOP_GT,
1527
+ ssa.OpARM64GreaterThanU: arm64.SPOP_HI,
1528
+ ssa.OpARM64GreaterEqual: arm64.SPOP_GE,
1529
+ ssa.OpARM64GreaterEqualU: arm64.SPOP_HS,
1530
+ ssa.OpARM64LessThanF: arm64.SPOP_MI, // Less than
1531
+ ssa.OpARM64LessEqualF: arm64.SPOP_LS, // Less than or equal to
1532
+ ssa.OpARM64GreaterThanF: arm64.SPOP_GT, // Greater than
1533
+ ssa.OpARM64GreaterEqualF: arm64.SPOP_GE, // Greater than or equal to
1534
+
1535
+ // The following condition codes have unordered to handle comparisons related to NaN.
1536
+ ssa.OpARM64NotLessThanF: arm64.SPOP_PL, // Greater than, equal to, or unordered
1537
+ ssa.OpARM64NotLessEqualF: arm64.SPOP_HI, // Greater than or unordered
1538
+ ssa.OpARM64NotGreaterThanF: arm64.SPOP_LE, // Less than, equal to or unordered
1539
+ ssa.OpARM64NotGreaterEqualF: arm64.SPOP_LT, // Less than or unordered
1540
+
1541
+ ssa.OpARM64LessThanNoov: arm64.SPOP_MI, // Less than but without honoring overflow
1542
+ ssa.OpARM64GreaterEqualNoov: arm64.SPOP_PL, // Greater than or equal to but without honoring overflow
1543
+ }
1544
+
1545
+ var blockJump = map[ssa.BlockKind]struct {
1546
+ asm, invasm obj.As
1547
+ }{
1548
+ ssa.BlockARM64EQ: {arm64.ABEQ, arm64.ABNE},
1549
+ ssa.BlockARM64NE: {arm64.ABNE, arm64.ABEQ},
1550
+ ssa.BlockARM64LT: {arm64.ABLT, arm64.ABGE},
1551
+ ssa.BlockARM64GE: {arm64.ABGE, arm64.ABLT},
1552
+ ssa.BlockARM64LE: {arm64.ABLE, arm64.ABGT},
1553
+ ssa.BlockARM64GT: {arm64.ABGT, arm64.ABLE},
1554
+ ssa.BlockARM64ULT: {arm64.ABLO, arm64.ABHS},
1555
+ ssa.BlockARM64UGE: {arm64.ABHS, arm64.ABLO},
1556
+ ssa.BlockARM64UGT: {arm64.ABHI, arm64.ABLS},
1557
+ ssa.BlockARM64ULE: {arm64.ABLS, arm64.ABHI},
1558
+ ssa.BlockARM64Z: {arm64.ACBZ, arm64.ACBNZ},
1559
+ ssa.BlockARM64NZ: {arm64.ACBNZ, arm64.ACBZ},
1560
+ ssa.BlockARM64ZW: {arm64.ACBZW, arm64.ACBNZW},
1561
+ ssa.BlockARM64NZW: {arm64.ACBNZW, arm64.ACBZW},
1562
+ ssa.BlockARM64TBZ: {arm64.ATBZ, arm64.ATBNZ},
1563
+ ssa.BlockARM64TBNZ: {arm64.ATBNZ, arm64.ATBZ},
1564
+ ssa.BlockARM64FLT: {arm64.ABMI, arm64.ABPL},
1565
+ ssa.BlockARM64FGE: {arm64.ABGE, arm64.ABLT},
1566
+ ssa.BlockARM64FLE: {arm64.ABLS, arm64.ABHI},
1567
+ ssa.BlockARM64FGT: {arm64.ABGT, arm64.ABLE},
1568
+ ssa.BlockARM64LTnoov: {arm64.ABMI, arm64.ABPL},
1569
+ ssa.BlockARM64GEnoov: {arm64.ABPL, arm64.ABMI},
1570
+ }
1571
+
1572
+ // To model a 'LEnoov' ('<=' without overflow checking) branching.
1573
+ var leJumps = [2][2]ssagen.IndexJump{
1574
+ {{Jump: arm64.ABEQ, Index: 0}, {Jump: arm64.ABPL, Index: 1}}, // next == b.Succs[0]
1575
+ {{Jump: arm64.ABMI, Index: 0}, {Jump: arm64.ABEQ, Index: 0}}, // next == b.Succs[1]
1576
+ }
1577
+
1578
+ // To model a 'GTnoov' ('>' without overflow checking) branching.
1579
+ var gtJumps = [2][2]ssagen.IndexJump{
1580
+ {{Jump: arm64.ABMI, Index: 1}, {Jump: arm64.ABEQ, Index: 1}}, // next == b.Succs[0]
1581
+ {{Jump: arm64.ABEQ, Index: 1}, {Jump: arm64.ABPL, Index: 0}}, // next == b.Succs[1]
1582
+ }
1583
+
1584
+ func ssaGenBlock(s *ssagen.State, b, next *ssa.Block) {
1585
+ switch b.Kind {
1586
+ case ssa.BlockPlain, ssa.BlockDefer:
1587
+ if b.Succs[0].Block() != next {
1588
+ p := s.Prog(obj.AJMP)
1589
+ p.To.Type = obj.TYPE_BRANCH
1590
+ s.Branches = append(s.Branches, ssagen.Branch{P: p, B: b.Succs[0].Block()})
1591
+ }
1592
+
1593
+ case ssa.BlockExit, ssa.BlockRetJmp:
1594
+
1595
+ case ssa.BlockRet:
1596
+ s.Prog(obj.ARET)
1597
+
1598
+ case ssa.BlockARM64EQ, ssa.BlockARM64NE,
1599
+ ssa.BlockARM64LT, ssa.BlockARM64GE,
1600
+ ssa.BlockARM64LE, ssa.BlockARM64GT,
1601
+ ssa.BlockARM64ULT, ssa.BlockARM64UGT,
1602
+ ssa.BlockARM64ULE, ssa.BlockARM64UGE,
1603
+ ssa.BlockARM64Z, ssa.BlockARM64NZ,
1604
+ ssa.BlockARM64ZW, ssa.BlockARM64NZW,
1605
+ ssa.BlockARM64FLT, ssa.BlockARM64FGE,
1606
+ ssa.BlockARM64FLE, ssa.BlockARM64FGT,
1607
+ ssa.BlockARM64LTnoov, ssa.BlockARM64GEnoov:
1608
+ jmp := blockJump[b.Kind]
1609
+ var p *obj.Prog
1610
+ switch next {
1611
+ case b.Succs[0].Block():
1612
+ p = s.Br(jmp.invasm, b.Succs[1].Block())
1613
+ case b.Succs[1].Block():
1614
+ p = s.Br(jmp.asm, b.Succs[0].Block())
1615
+ default:
1616
+ if b.Likely != ssa.BranchUnlikely {
1617
+ p = s.Br(jmp.asm, b.Succs[0].Block())
1618
+ s.Br(obj.AJMP, b.Succs[1].Block())
1619
+ } else {
1620
+ p = s.Br(jmp.invasm, b.Succs[1].Block())
1621
+ s.Br(obj.AJMP, b.Succs[0].Block())
1622
+ }
1623
+ }
1624
+ if !b.Controls[0].Type.IsFlags() {
1625
+ p.From.Type = obj.TYPE_REG
1626
+ p.From.Reg = b.Controls[0].Reg()
1627
+ }
1628
+ case ssa.BlockARM64TBZ, ssa.BlockARM64TBNZ:
1629
+ jmp := blockJump[b.Kind]
1630
+ var p *obj.Prog
1631
+ switch next {
1632
+ case b.Succs[0].Block():
1633
+ p = s.Br(jmp.invasm, b.Succs[1].Block())
1634
+ case b.Succs[1].Block():
1635
+ p = s.Br(jmp.asm, b.Succs[0].Block())
1636
+ default:
1637
+ if b.Likely != ssa.BranchUnlikely {
1638
+ p = s.Br(jmp.asm, b.Succs[0].Block())
1639
+ s.Br(obj.AJMP, b.Succs[1].Block())
1640
+ } else {
1641
+ p = s.Br(jmp.invasm, b.Succs[1].Block())
1642
+ s.Br(obj.AJMP, b.Succs[0].Block())
1643
+ }
1644
+ }
1645
+ p.From.Offset = b.AuxInt
1646
+ p.From.Type = obj.TYPE_CONST
1647
+ p.Reg = b.Controls[0].Reg()
1648
+
1649
+ case ssa.BlockARM64LEnoov:
1650
+ s.CombJump(b, next, &leJumps)
1651
+ case ssa.BlockARM64GTnoov:
1652
+ s.CombJump(b, next, &gtJumps)
1653
+
1654
+ case ssa.BlockARM64JUMPTABLE:
1655
+ // MOVD (TABLE)(IDX<<3), Rtmp
1656
+ // JMP (Rtmp)
1657
+ p := s.Prog(arm64.AMOVD)
1658
+ p.From = genIndexedOperand(ssa.OpARM64MOVDloadidx8, b.Controls[1].Reg(), b.Controls[0].Reg())
1659
+ p.To.Type = obj.TYPE_REG
1660
+ p.To.Reg = arm64.REGTMP
1661
+ p = s.Prog(obj.AJMP)
1662
+ p.To.Type = obj.TYPE_MEM
1663
+ p.To.Reg = arm64.REGTMP
1664
+ // Save jump tables for later resolution of the target blocks.
1665
+ s.JumpTables = append(s.JumpTables, b)
1666
+
1667
+ default:
1668
+ b.Fatalf("branch not implemented: %s", b.LongString())
1669
+ }
1670
+ }
1671
+
1672
+ func loadRegResult(s *ssagen.State, f *ssa.Func, t *types.Type, reg int16, n *ir.Name, off int64) *obj.Prog {
1673
+ p := s.Prog(loadByType(t))
1674
+ p.From.Type = obj.TYPE_MEM
1675
+ p.From.Name = obj.NAME_AUTO
1676
+ p.From.Sym = n.Linksym()
1677
+ p.From.Offset = n.FrameOffset() + off
1678
+ p.To.Type = obj.TYPE_REG
1679
+ p.To.Reg = reg
1680
+ return p
1681
+ }
1682
+
1683
+ func spillArgReg(pp *objw.Progs, p *obj.Prog, f *ssa.Func, t *types.Type, reg int16, n *ir.Name, off int64) *obj.Prog {
1684
+ p = pp.Append(p, storeByType(t), obj.TYPE_REG, reg, 0, obj.TYPE_MEM, 0, n.FrameOffset()+off)
1685
+ p.To.Name = obj.NAME_PARAM
1686
+ p.To.Sym = n.Linksym()
1687
+ p.Pos = p.Pos.WithNotStmt()
1688
+ return p
1689
+ }
1690
+
1691
+ // zero16 zeroes 16 bytes at reg+off.
1692
+ // If postInc is true, increment reg by 16.
1693
+ func zero16(s *ssagen.State, reg int16, off int64, postInc bool) {
1694
+ // STP (ZR, ZR), off(reg)
1695
+ p := s.Prog(arm64.ASTP)
1696
+ p.From.Type = obj.TYPE_REGREG
1697
+ p.From.Reg = arm64.REGZERO
1698
+ p.From.Offset = int64(arm64.REGZERO)
1699
+ p.To.Type = obj.TYPE_MEM
1700
+ p.To.Reg = reg
1701
+ p.To.Offset = off
1702
+ if postInc {
1703
+ if off != 0 {
1704
+ panic("can't postinc with non-zero offset")
1705
+ }
1706
+ // STP.P (ZR, ZR), 16(reg)
1707
+ p.Scond = arm64.C_XPOST
1708
+ p.To.Offset = 16
1709
+ }
1710
+ }
1711
+
1712
+ // zero8 zeroes 8 bytes at reg+off.
1713
+ func zero8(s *ssagen.State, reg int16, off int64) {
1714
+ // MOVD ZR, off(reg)
1715
+ p := s.Prog(arm64.AMOVD)
1716
+ p.From.Type = obj.TYPE_REG
1717
+ p.From.Reg = arm64.REGZERO
1718
+ p.To.Type = obj.TYPE_MEM
1719
+ p.To.Reg = reg
1720
+ p.To.Offset = off
1721
+ }
1722
+
1723
+ // move32 copies 32 bytes at src+off to dst+off.
1724
+ // Uses registers tmp1 and tmp2.
1725
+ // If postInc is true, increment src and dst by 32.
1726
+ func move32(s *ssagen.State, src, dst, tmp1, tmp2 int16, off int64, postInc bool) {
1727
+ // FLDPQ off(src), (tmp1, tmp2)
1728
+ ld := s.Prog(arm64.AFLDPQ)
1729
+ ld.From.Type = obj.TYPE_MEM
1730
+ ld.From.Reg = src
1731
+ ld.From.Offset = off
1732
+ ld.To.Type = obj.TYPE_REGREG
1733
+ ld.To.Reg = tmp1
1734
+ ld.To.Offset = int64(tmp2)
1735
+ // FSTPQ (tmp1, tmp2), off(dst)
1736
+ st := s.Prog(arm64.AFSTPQ)
1737
+ st.From.Type = obj.TYPE_REGREG
1738
+ st.From.Reg = tmp1
1739
+ st.From.Offset = int64(tmp2)
1740
+ st.To.Type = obj.TYPE_MEM
1741
+ st.To.Reg = dst
1742
+ st.To.Offset = off
1743
+ if postInc {
1744
+ if off != 0 {
1745
+ panic("can't postinc with non-zero offset")
1746
+ }
1747
+ ld.Scond = arm64.C_XPOST
1748
+ st.Scond = arm64.C_XPOST
1749
+ ld.From.Offset = 32
1750
+ st.To.Offset = 32
1751
+ }
1752
+ }
1753
+
1754
+ // move16 copies 16 bytes at src+off to dst+off.
1755
+ // Uses register tmp1
1756
+ // If postInc is true, increment src and dst by 16.
1757
+ func move16(s *ssagen.State, src, dst, tmp1 int16, off int64, postInc bool) {
1758
+ // FMOVQ off(src), tmp1
1759
+ ld := s.Prog(arm64.AFMOVQ)
1760
+ ld.From.Type = obj.TYPE_MEM
1761
+ ld.From.Reg = src
1762
+ ld.From.Offset = off
1763
+ ld.To.Type = obj.TYPE_REG
1764
+ ld.To.Reg = tmp1
1765
+ // FMOVQ tmp1, off(dst)
1766
+ st := s.Prog(arm64.AFMOVQ)
1767
+ st.From.Type = obj.TYPE_REG
1768
+ st.From.Reg = tmp1
1769
+ st.To.Type = obj.TYPE_MEM
1770
+ st.To.Reg = dst
1771
+ st.To.Offset = off
1772
+ if postInc {
1773
+ if off != 0 {
1774
+ panic("can't postinc with non-zero offset")
1775
+ }
1776
+ ld.Scond = arm64.C_XPOST
1777
+ st.Scond = arm64.C_XPOST
1778
+ ld.From.Offset = 16
1779
+ st.To.Offset = 16
1780
+ }
1781
+ }
1782
+
1783
+ // move8 copies 8 bytes at src+off to dst+off.
1784
+ // Uses register tmp.
1785
+ func move8(s *ssagen.State, src, dst, tmp int16, off int64) {
1786
+ // MOVD off(src), tmp
1787
+ ld := s.Prog(arm64.AMOVD)
1788
+ ld.From.Type = obj.TYPE_MEM
1789
+ ld.From.Reg = src
1790
+ ld.From.Offset = off
1791
+ ld.To.Type = obj.TYPE_REG
1792
+ ld.To.Reg = tmp
1793
+ // MOVD tmp, off(dst)
1794
+ st := s.Prog(arm64.AMOVD)
1795
+ st.From.Type = obj.TYPE_REG
1796
+ st.From.Reg = tmp
1797
+ st.To.Type = obj.TYPE_MEM
1798
+ st.To.Reg = dst
1799
+ st.To.Offset = off
1800
+ }
go/src/cmd/compile/internal/base/base.go ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2009 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 base
6
+
7
+ import (
8
+ "os"
9
+ )
10
+
11
+ var atExitFuncs []func()
12
+
13
+ func AtExit(f func()) {
14
+ atExitFuncs = append(atExitFuncs, f)
15
+ }
16
+
17
+ func Exit(code int) {
18
+ for i := len(atExitFuncs) - 1; i >= 0; i-- {
19
+ f := atExitFuncs[i]
20
+ atExitFuncs = atExitFuncs[:i]
21
+ f()
22
+ }
23
+ os.Exit(code)
24
+ }
25
+
26
+ // To enable tracing support (-t flag), set EnableTrace to true.
27
+ const EnableTrace = false
go/src/cmd/compile/internal/base/bootstrap_false.go ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2021 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
+ //go:build !compiler_bootstrap
6
+
7
+ package base
8
+
9
+ // CompilerBootstrap reports whether the current compiler binary was
10
+ // built with -tags=compiler_bootstrap.
11
+ const CompilerBootstrap = false
go/src/cmd/compile/internal/base/bootstrap_true.go ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2021 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
+ //go:build compiler_bootstrap
6
+
7
+ package base
8
+
9
+ // CompilerBootstrap reports whether the current compiler binary was
10
+ // built with -tags=compiler_bootstrap.
11
+ const CompilerBootstrap = true
go/src/cmd/compile/internal/base/debug.go ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2009 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
+ // Debug arguments, set by -d flag.
6
+
7
+ package base
8
+
9
+ // Debug holds the parsed debugging configuration values.
10
+ var Debug DebugFlags
11
+
12
+ // DebugFlags defines the debugging configuration values (see var Debug).
13
+ // Each struct field is a different value, named for the lower-case of the field name.
14
+ // Each field must be an int or string and must have a `help` struct tag.
15
+ //
16
+ // The -d option takes a comma-separated list of settings.
17
+ // Each setting is name=value; for ints, name is short for name=1.
18
+ type DebugFlags struct {
19
+ AlignHot int `help:"enable hot block alignment (currently requires -pgo)" concurrent:"ok"`
20
+ Append int `help:"print information about append compilation"`
21
+ Checkptr int `help:"instrument unsafe pointer conversions\n0: instrumentation disabled\n1: conversions involving unsafe.Pointer are instrumented\n2: conversions to unsafe.Pointer force heap allocation" concurrent:"ok"`
22
+ Closure int `help:"print information about closure compilation"`
23
+ CompressInstructions int `help:"use compressed instructions when possible (if supported by architecture)"`
24
+ Converthash string `help:"hash value for use in debugging changes to platform-dependent float-to-[u]int conversion" concurrent:"ok"`
25
+ Defer int `help:"print information about defer compilation"`
26
+ DisableNil int `help:"disable nil checks" concurrent:"ok"`
27
+ DumpInlFuncProps string `help:"dump function properties from inl heuristics to specified file"`
28
+ DumpInlCallSiteScores int `help:"dump scored callsites during inlining"`
29
+ InlScoreAdj string `help:"set inliner score adjustments (ex: -d=inlscoreadj=panicPathAdj:10/passConstToNestedIfAdj:-90)"`
30
+ InlBudgetSlack int `help:"amount to expand the initial inline budget when new inliner enabled. Defaults to 80 if option not set." concurrent:"ok"`
31
+ DumpPtrs int `help:"show Node pointers values in dump output"`
32
+ DwarfInl int `help:"print information about DWARF inlined function creation"`
33
+ EscapeMutationsCalls int `help:"print extra escape analysis diagnostics about mutations and calls" concurrent:"ok"`
34
+ EscapeDebug int `help:"print information about escape analysis and resulting optimizations" concurrent:"ok"`
35
+ EscapeAlias int `help:"print information about alias analysis" concurrent:"ok"`
36
+ EscapeAliasCheck int `help:"enable additional validation for alias analysis" concurrent:"ok"`
37
+ Export int `help:"print export data"`
38
+ FIPSHash string `help:"hash value for FIPS debugging" concurrent:"ok"`
39
+ Fmahash string `help:"hash value for use in debugging platform-dependent multiply-add use" concurrent:"ok"`
40
+ FreeAppend int `help:"insert frees of append results when proven safe (0 disabled, 1 enabled, 2 enabled + log)" concurrent:"ok"`
41
+ GCAdjust int `help:"log adjustments to GOGC" concurrent:"ok"`
42
+ GCCheck int `help:"check heap/gc use by compiler" concurrent:"ok"`
43
+ GCProg int `help:"print dump of GC programs"`
44
+ GCStart int `help:"specify \"starting\" compiler's heap size in MiB" concurrent:"ok"`
45
+ Gossahash string `help:"hash value for use in debugging the compiler"`
46
+ InlFuncsWithClosures int `help:"allow functions with closures to be inlined" concurrent:"ok"`
47
+ InlStaticInit int `help:"allow static initialization of inlined calls" concurrent:"ok"`
48
+ Libfuzzer int `help:"enable coverage instrumentation for libfuzzer"`
49
+ LiteralAllocHash string `help:"hash value for use in debugging literal allocation optimizations" concurrent:"ok"`
50
+ LoopVar int `help:"shared (0, default), 1 (private loop variables), 2, private + log"`
51
+ LoopVarHash string `help:"for debugging changes in loop behavior. Overrides experiment and loopvar flag."`
52
+ LocationLists int `help:"print information about DWARF location list creation"`
53
+ MaxShapeLen int `help:"hash shape names longer than this threshold (default 500)" concurrent:"ok"`
54
+ MergeLocals int `help:"merge together non-interfering local stack slots" concurrent:"ok"`
55
+ MergeLocalsDumpFunc string `help:"dump specified func in merge locals"`
56
+ MergeLocalsHash string `help:"hash value for debugging stack slot merging of local variables" concurrent:"ok"`
57
+ MergeLocalsTrace int `help:"trace debug output for locals merging"`
58
+ MergeLocalsHTrace int `help:"hash-selected trace debug output for locals merging"`
59
+ Nil int `help:"print information about nil checks"`
60
+ NoDeadLocals int `help:"disable deadlocals pass" concurrent:"ok"`
61
+ NoOpenDefer int `help:"disable open-coded defers" concurrent:"ok"`
62
+ NoRefName int `help:"do not include referenced symbol names in object file" concurrent:"ok"`
63
+ PCTab string `help:"print named pc-value table\nOne of: pctospadj, pctofile, pctoline, pctoinline, pctopcdata"`
64
+ Panic int `help:"show all compiler panics"`
65
+ Reshape int `help:"print information about expression reshaping"`
66
+ Shapify int `help:"print information about shaping recursive types"`
67
+ Slice int `help:"print information about slice compilation"`
68
+ SoftFloat int `help:"force compiler to emit soft-float code" concurrent:"ok"`
69
+ StaticCopy int `help:"print information about missed static copies" concurrent:"ok"`
70
+ SyncFrames int `help:"how many writer stack frames to include at sync points in unified export data"`
71
+ TailCall int `help:"print information about tail calls"`
72
+ TypeAssert int `help:"print information about type assertion inlining"`
73
+ WB int `help:"print information about write barriers"`
74
+ ABIWrap int `help:"print information about ABI wrapper generation"`
75
+ MayMoreStack string `help:"call named function before all stack growth checks" concurrent:"ok"`
76
+ PGODebug int `help:"debug profile-guided optimizations"`
77
+ PGOHash string `help:"hash value for debugging profile-guided optimizations" concurrent:"ok"`
78
+ PGOInline int `help:"enable profile-guided inlining" concurrent:"ok"`
79
+ PGOInlineCDFThreshold string `help:"cumulative threshold percentage for determining call sites as hot candidates for inlining" concurrent:"ok"`
80
+ PGOInlineBudget int `help:"inline budget for hot functions" concurrent:"ok"`
81
+ PGODevirtualize int `help:"enable profile-guided devirtualization; 0 to disable, 1 to enable interface devirtualization, 2 to enable function devirtualization" concurrent:"ok"`
82
+ RangeFuncCheck int `help:"insert code to check behavior of range iterator functions" concurrent:"ok"`
83
+ VariableMakeHash string `help:"hash value for debugging stack allocation of variable-sized make results" concurrent:"ok"`
84
+ VariableMakeThreshold int `help:"threshold in bytes for possible stack allocation of variable-sized make results" concurrent:"ok"`
85
+ WrapGlobalMapDbg int `help:"debug trace output for global map init wrapping"`
86
+ WrapGlobalMapCtl int `help:"global map init wrap control (0 => default, 1 => off, 2 => stress mode, no size cutoff)"`
87
+ ZeroCopy int `help:"enable zero-copy string->[]byte conversions" concurrent:"ok"`
88
+
89
+ ConcurrentOk bool // true if only concurrentOk flags seen
90
+ }
91
+
92
+ // DebugSSA is called to set a -d ssa/... option.
93
+ // If nil, those options are reported as invalid options.
94
+ // If DebugSSA returns a non-empty string, that text is reported as a compiler error.
95
+ var DebugSSA func(phase, flag string, val int, valString string) string
go/src/cmd/compile/internal/base/flag.go ADDED
@@ -0,0 +1,607 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2009 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 base
6
+
7
+ import (
8
+ "cmd/internal/cov/covcmd"
9
+ "cmd/internal/telemetry/counter"
10
+ "encoding/json"
11
+ "flag"
12
+ "fmt"
13
+ "internal/buildcfg"
14
+ "internal/platform"
15
+ "log"
16
+ "os"
17
+ "reflect"
18
+ "runtime"
19
+ "strings"
20
+
21
+ "cmd/internal/obj"
22
+ "cmd/internal/objabi"
23
+ "cmd/internal/sys"
24
+ )
25
+
26
+ func usage() {
27
+ fmt.Fprintf(os.Stderr, "usage: compile [options] file.go...\n")
28
+ objabi.Flagprint(os.Stderr)
29
+ Exit(2)
30
+ }
31
+
32
+ // Flag holds the parsed command-line flags.
33
+ // See ParseFlag for non-zero defaults.
34
+ var Flag CmdFlags
35
+
36
+ // A CountFlag is a counting integer flag.
37
+ // It accepts -name=value to set the value directly,
38
+ // but it also accepts -name with no =value to increment the count.
39
+ type CountFlag int
40
+
41
+ // CmdFlags defines the command-line flags (see var Flag).
42
+ // Each struct field is a different flag, by default named for the lower-case of the field name.
43
+ // If the flag name is a single letter, the default flag name is left upper-case.
44
+ // If the flag name is "Lower" followed by a single letter, the default flag name is the lower-case of the last letter.
45
+ //
46
+ // If this default flag name can't be made right, the `flag` struct tag can be used to replace it,
47
+ // but this should be done only in exceptional circumstances: it helps everyone if the flag name
48
+ // is obvious from the field name when the flag is used elsewhere in the compiler sources.
49
+ // The `flag:"-"` struct tag makes a field invisible to the flag logic and should also be used sparingly.
50
+ //
51
+ // Each field must have a `help` struct tag giving the flag help message.
52
+ //
53
+ // The allowed field types are bool, int, string, pointers to those (for values stored elsewhere),
54
+ // CountFlag (for a counting flag), and func(string) (for a flag that uses special code for parsing).
55
+ type CmdFlags struct {
56
+ // Single letters
57
+ B CountFlag "help:\"disable bounds checking\""
58
+ C CountFlag "help:\"disable printing of columns in error messages\""
59
+ D string "help:\"set relative `path` for local imports\""
60
+ E CountFlag "help:\"debug symbol export\""
61
+ I func(string) "help:\"add `directory` to import search path\""
62
+ K CountFlag "help:\"debug missing line numbers\""
63
+ L CountFlag "help:\"also show actual source file names in error messages for positions affected by //line directives\""
64
+ N CountFlag "help:\"disable optimizations\""
65
+ S CountFlag "help:\"print assembly listing\""
66
+ // V is added by objabi.AddVersionFlag
67
+ W CountFlag "help:\"debug parse tree after type checking\""
68
+
69
+ LowerC int "help:\"concurrency during compilation (1 means no concurrency)\""
70
+ LowerD flag.Value "help:\"enable debugging settings; try -d help\""
71
+ LowerE CountFlag "help:\"no limit on number of errors reported\""
72
+ LowerH CountFlag "help:\"halt on error\""
73
+ LowerJ CountFlag "help:\"debug runtime-initialized variables\""
74
+ LowerL CountFlag "help:\"disable inlining\""
75
+ LowerM CountFlag "help:\"print optimization decisions\""
76
+ LowerO string "help:\"write output to `file`\""
77
+ LowerP *string "help:\"set expected package import `path`\"" // &Ctxt.Pkgpath, set below
78
+ LowerR CountFlag "help:\"debug generated wrappers\""
79
+ LowerT bool "help:\"enable tracing for debugging the compiler\""
80
+ LowerW CountFlag "help:\"debug type checking\""
81
+ LowerV *bool "help:\"increase debug verbosity\""
82
+
83
+ // Special characters
84
+ Percent CountFlag "flag:\"%\" help:\"debug non-static initializers\""
85
+ CompilingRuntime bool "flag:\"+\" help:\"compiling runtime\""
86
+
87
+ // Longer names
88
+ AsmHdr string "help:\"write assembly header to `file`\""
89
+ ASan bool "help:\"build code compatible with C/C++ address sanitizer\""
90
+ Bench string "help:\"append benchmark times to `file`\""
91
+ BlockProfile string "help:\"write block profile to `file`\""
92
+ BuildID string "help:\"record `id` as the build id in the export metadata\""
93
+ CPUProfile string "help:\"write cpu profile to `file`\""
94
+ Complete bool "help:\"compiling complete package (no C or assembly)\""
95
+ ClobberDead bool "help:\"clobber dead stack slots (for debugging)\""
96
+ ClobberDeadReg bool "help:\"clobber dead registers (for debugging)\""
97
+ Dwarf bool "help:\"generate DWARF symbols\""
98
+ DwarfBASEntries *bool "help:\"use base address selection entries in DWARF\"" // &Ctxt.UseBASEntries, set below
99
+ DwarfLocationLists *bool "help:\"add location lists to DWARF in optimized mode\"" // &Ctxt.Flag_locationlists, set below
100
+ Dynlink *bool "help:\"support references to Go symbols defined in other shared libraries\"" // &Ctxt.Flag_dynlink, set below
101
+ EmbedCfg func(string) "help:\"read go:embed configuration from `file`\""
102
+ Env func(string) "help:\"add `definition` of the form key=value to environment\""
103
+ GenDwarfInl int "help:\"generate DWARF inline info records\"" // 0=disabled, 1=funcs, 2=funcs+formals/locals
104
+ GoVersion string "help:\"required version of the runtime\""
105
+ ImportCfg func(string) "help:\"read import configuration from `file`\""
106
+ InstallSuffix string "help:\"set pkg directory `suffix`\""
107
+ JSON string "help:\"version,file for JSON compiler/optimizer detail output\""
108
+ Lang string "help:\"Go language version source code expects\""
109
+ LinkObj string "help:\"write linker-specific object to `file`\""
110
+ LinkShared *bool "help:\"generate code that will be linked against Go shared libraries\"" // &Ctxt.Flag_linkshared, set below
111
+ Live CountFlag "help:\"debug liveness analysis\""
112
+ MSan bool "help:\"build code compatible with C/C++ memory sanitizer\""
113
+ MemProfile string "help:\"write memory profile to `file`\""
114
+ MemProfileRate int "help:\"set runtime.MemProfileRate to `rate`\""
115
+ MutexProfile string "help:\"write mutex profile to `file`\""
116
+ NoLocalImports bool "help:\"reject local (relative) imports\""
117
+ CoverageCfg func(string) "help:\"read coverage configuration from `file`\""
118
+ Pack bool "help:\"write to file.a instead of file.o\""
119
+ Race bool "help:\"enable race detector\""
120
+ Shared *bool "help:\"generate code that can be linked into a shared library\"" // &Ctxt.Flag_shared, set below
121
+ SmallFrames bool "help:\"reduce the size limit for stack allocated objects\"" // small stacks, to diagnose GC latency; see golang.org/issue/27732
122
+ Spectre string "help:\"enable spectre mitigations in `list` (all, index, ret)\""
123
+ Std bool "help:\"compiling standard library\""
124
+ SymABIs string "help:\"read symbol ABIs from `file`\""
125
+ TraceProfile string "help:\"write an execution trace to `file`\""
126
+ TrimPath string "help:\"remove `prefix` from recorded source file paths\""
127
+ WB bool "help:\"enable write barrier\"" // TODO: remove
128
+ PgoProfile string "help:\"read profile or pre-process profile from `file`\""
129
+ ErrorURL bool "help:\"print explanatory URL with error message if applicable\""
130
+
131
+ // Configuration derived from flags; not a flag itself.
132
+ Cfg struct {
133
+ Embed struct { // set by -embedcfg
134
+ Patterns map[string][]string
135
+ Files map[string]string
136
+ }
137
+ ImportDirs []string // appended to by -I
138
+ ImportMap map[string]string // set by -importcfg
139
+ PackageFile map[string]string // set by -importcfg; nil means not in use
140
+ CoverageInfo *covcmd.CoverFixupConfig // set by -coveragecfg
141
+ SpectreIndex bool // set by -spectre=index or -spectre=all
142
+ // Whether we are adding any sort of code instrumentation, such as
143
+ // when the race detector is enabled.
144
+ Instrumenting bool
145
+ }
146
+ }
147
+
148
+ func addEnv(s string) {
149
+ i := strings.Index(s, "=")
150
+ if i < 0 {
151
+ log.Fatal("-env argument must be of the form key=value")
152
+ }
153
+ os.Setenv(s[:i], s[i+1:])
154
+ }
155
+
156
+ // ParseFlags parses the command-line flags into Flag.
157
+ func ParseFlags() {
158
+ Flag.I = addImportDir
159
+
160
+ Flag.LowerC = runtime.GOMAXPROCS(0)
161
+ Flag.LowerD = objabi.NewDebugFlag(&Debug, DebugSSA)
162
+ Flag.LowerP = &Ctxt.Pkgpath
163
+ Flag.LowerV = &Ctxt.Debugvlog
164
+
165
+ Flag.Dwarf = buildcfg.GOARCH != "wasm"
166
+ Flag.DwarfBASEntries = &Ctxt.UseBASEntries
167
+ Flag.DwarfLocationLists = &Ctxt.Flag_locationlists
168
+ *Flag.DwarfLocationLists = true
169
+ Flag.Dynlink = &Ctxt.Flag_dynlink
170
+ Flag.EmbedCfg = readEmbedCfg
171
+ Flag.Env = addEnv
172
+ Flag.GenDwarfInl = 2
173
+ Flag.ImportCfg = readImportCfg
174
+ Flag.CoverageCfg = readCoverageCfg
175
+ Flag.LinkShared = &Ctxt.Flag_linkshared
176
+ Flag.Shared = &Ctxt.Flag_shared
177
+ Flag.WB = true
178
+
179
+ Debug.ConcurrentOk = true
180
+ Debug.CompressInstructions = 1
181
+ Debug.MaxShapeLen = 500
182
+ Debug.AlignHot = 1
183
+ Debug.InlFuncsWithClosures = 1
184
+ Debug.InlStaticInit = 1
185
+ Debug.FreeAppend = 1
186
+ Debug.PGOInline = 1
187
+ Debug.PGODevirtualize = 2
188
+ Debug.SyncFrames = -1 // disable sync markers by default
189
+ Debug.VariableMakeThreshold = 32 // 32 byte default for stack allocated make results
190
+ Debug.ZeroCopy = 1
191
+ Debug.RangeFuncCheck = 1
192
+ Debug.MergeLocals = 1
193
+
194
+ Debug.Checkptr = -1 // so we can tell whether it is set explicitly
195
+
196
+ Flag.Cfg.ImportMap = make(map[string]string)
197
+
198
+ objabi.AddVersionFlag() // -V
199
+ registerFlags()
200
+ objabi.Flagparse(usage)
201
+ counter.CountFlags("compile/flag:", *flag.CommandLine)
202
+
203
+ if gcd := os.Getenv("GOCOMPILEDEBUG"); gcd != "" {
204
+ // This will only override the flags set in gcd;
205
+ // any others set on the command line remain set.
206
+ Flag.LowerD.Set(gcd)
207
+ }
208
+
209
+ if Debug.Gossahash != "" {
210
+ hashDebug = NewHashDebug("gossahash", Debug.Gossahash, nil)
211
+ }
212
+ obj.SetFIPSDebugHash(Debug.FIPSHash)
213
+
214
+ // Compute whether we're compiling the runtime from the package path. Test
215
+ // code can also use the flag to set this explicitly.
216
+ if Flag.Std && objabi.LookupPkgSpecial(Ctxt.Pkgpath).Runtime {
217
+ Flag.CompilingRuntime = true
218
+ }
219
+
220
+ Ctxt.Std = Flag.Std
221
+
222
+ // Three inputs govern loop iteration variable rewriting, hash, experiment, flag.
223
+ // The loop variable rewriting is:
224
+ // IF non-empty hash, then hash determines behavior (function+line match) (*)
225
+ // ELSE IF experiment and flag==0, then experiment (set flag=1)
226
+ // ELSE flag (note that build sets flag per-package), with behaviors:
227
+ // -1 => no change to behavior.
228
+ // 0 => no change to behavior (unless non-empty hash, see above)
229
+ // 1 => apply change to likely-iteration-variable-escaping loops
230
+ // 2 => apply change, log results
231
+ // 11 => apply change EVERYWHERE, do not log results (for debugging/benchmarking)
232
+ // 12 => apply change EVERYWHERE, log results (for debugging/benchmarking)
233
+ //
234
+ // The expected uses of the these inputs are, in believed most-likely to least likely:
235
+ // GOEXPERIMENT=loopvar -- apply change to entire application
236
+ // -gcflags=some_package=-d=loopvar=1 -- apply change to some_package (**)
237
+ // -gcflags=some_package=-d=loopvar=2 -- apply change to some_package, log it
238
+ // GOEXPERIMENT=loopvar -gcflags=some_package=-d=loopvar=-1 -- apply change to all but one package
239
+ // GOCOMPILEDEBUG=loopvarhash=... -- search for failure cause
240
+ //
241
+ // (*) For debugging purposes, providing loopvar flag >= 11 will expand the hash-eligible set of loops to all.
242
+ // (**) Loop semantics, changed or not, follow code from a package when it is inlined; that is, the behavior
243
+ // of an application compiled with partially modified loop semantics does not depend on inlining.
244
+
245
+ if Debug.LoopVarHash != "" {
246
+ // This first little bit controls the inputs for debug-hash-matching.
247
+ mostInlineOnly := true
248
+ if strings.HasPrefix(Debug.LoopVarHash, "IL") {
249
+ // When hash-searching on a position that is an inline site, default is to use the
250
+ // most-inlined position only. This makes the hash faster, plus there's no point
251
+ // reporting a problem with all the inlining; there's only one copy of the source.
252
+ // However, if for some reason you wanted it per-site, you can get this. (The default
253
+ // hash-search behavior for compiler debugging is at an inline site.)
254
+ Debug.LoopVarHash = Debug.LoopVarHash[2:]
255
+ mostInlineOnly = false
256
+ }
257
+ // end of testing trickiness
258
+ LoopVarHash = NewHashDebug("loopvarhash", Debug.LoopVarHash, nil)
259
+ if Debug.LoopVar < 11 { // >= 11 means all loops are rewrite-eligible
260
+ Debug.LoopVar = 1 // 1 means those loops that syntactically escape their dcl vars are eligible.
261
+ }
262
+ LoopVarHash.SetInlineSuffixOnly(mostInlineOnly)
263
+ } else if buildcfg.Experiment.LoopVar && Debug.LoopVar == 0 {
264
+ Debug.LoopVar = 1
265
+ }
266
+
267
+ if Debug.Converthash != "" {
268
+ ConvertHash = NewHashDebug("converthash", Debug.Converthash, nil)
269
+ } else {
270
+ // quietly disable the convert hash changes
271
+ ConvertHash = NewHashDebug("converthash", "qn", nil)
272
+ }
273
+ if Debug.Fmahash != "" {
274
+ FmaHash = NewHashDebug("fmahash", Debug.Fmahash, nil)
275
+ }
276
+ if Debug.PGOHash != "" {
277
+ PGOHash = NewHashDebug("pgohash", Debug.PGOHash, nil)
278
+ }
279
+ if Debug.LiteralAllocHash != "" {
280
+ LiteralAllocHash = NewHashDebug("literalalloc", Debug.LiteralAllocHash, nil)
281
+ }
282
+
283
+ if Debug.MergeLocalsHash != "" {
284
+ MergeLocalsHash = NewHashDebug("mergelocals", Debug.MergeLocalsHash, nil)
285
+ }
286
+ if Debug.VariableMakeHash != "" {
287
+ VariableMakeHash = NewHashDebug("variablemake", Debug.VariableMakeHash, nil)
288
+ }
289
+
290
+ if Flag.MSan && !platform.MSanSupported(buildcfg.GOOS, buildcfg.GOARCH) {
291
+ log.Fatalf("%s/%s does not support -msan", buildcfg.GOOS, buildcfg.GOARCH)
292
+ }
293
+ if Flag.ASan && !platform.ASanSupported(buildcfg.GOOS, buildcfg.GOARCH) {
294
+ log.Fatalf("%s/%s does not support -asan", buildcfg.GOOS, buildcfg.GOARCH)
295
+ }
296
+ if Flag.Race && !platform.RaceDetectorSupported(buildcfg.GOOS, buildcfg.GOARCH) {
297
+ log.Fatalf("%s/%s does not support -race", buildcfg.GOOS, buildcfg.GOARCH)
298
+ }
299
+ if (*Flag.Shared || *Flag.Dynlink || *Flag.LinkShared) && !Ctxt.Arch.InFamily(sys.AMD64, sys.ARM, sys.ARM64, sys.I386, sys.Loong64, sys.MIPS64, sys.PPC64, sys.RISCV64, sys.S390X) {
300
+ log.Fatalf("%s/%s does not support -shared", buildcfg.GOOS, buildcfg.GOARCH)
301
+ }
302
+ parseSpectre(Flag.Spectre) // left as string for RecordFlags
303
+
304
+ Ctxt.CompressInstructions = Debug.CompressInstructions != 0
305
+ Ctxt.Flag_shared = Ctxt.Flag_dynlink || Ctxt.Flag_shared
306
+ Ctxt.Flag_optimize = Flag.N == 0
307
+ Ctxt.Debugasm = int(Flag.S)
308
+ Ctxt.Flag_maymorestack = Debug.MayMoreStack
309
+ Ctxt.Flag_noRefName = Debug.NoRefName != 0
310
+
311
+ if flag.NArg() < 1 {
312
+ usage()
313
+ }
314
+
315
+ if Flag.GoVersion != "" && Flag.GoVersion != runtime.Version() {
316
+ fmt.Printf("compile: version %q does not match go tool version %q\n", runtime.Version(), Flag.GoVersion)
317
+ Exit(2)
318
+ }
319
+
320
+ if *Flag.LowerP == "" {
321
+ *Flag.LowerP = obj.UnlinkablePkg
322
+ }
323
+
324
+ if Flag.LowerO == "" {
325
+ p := flag.Arg(0)
326
+ if i := strings.LastIndex(p, "/"); i >= 0 {
327
+ p = p[i+1:]
328
+ }
329
+ if runtime.GOOS == "windows" {
330
+ if i := strings.LastIndex(p, `\`); i >= 0 {
331
+ p = p[i+1:]
332
+ }
333
+ }
334
+ if i := strings.LastIndex(p, "."); i >= 0 {
335
+ p = p[:i]
336
+ }
337
+ suffix := ".o"
338
+ if Flag.Pack {
339
+ suffix = ".a"
340
+ }
341
+ Flag.LowerO = p + suffix
342
+ }
343
+ switch {
344
+ case Flag.Race && Flag.MSan:
345
+ log.Fatal("cannot use both -race and -msan")
346
+ case Flag.Race && Flag.ASan:
347
+ log.Fatal("cannot use both -race and -asan")
348
+ case Flag.MSan && Flag.ASan:
349
+ log.Fatal("cannot use both -msan and -asan")
350
+ }
351
+ if Flag.Race || Flag.MSan || Flag.ASan {
352
+ // -race, -msan and -asan imply -d=checkptr for now.
353
+ if Debug.Checkptr == -1 { // if not set explicitly
354
+ Debug.Checkptr = 1
355
+ }
356
+ }
357
+
358
+ if Flag.LowerC < 1 {
359
+ log.Fatalf("-c must be at least 1, got %d", Flag.LowerC)
360
+ }
361
+ if !concurrentBackendAllowed() {
362
+ Flag.LowerC = 1
363
+ }
364
+
365
+ if Flag.CompilingRuntime {
366
+ // It is not possible to build the runtime with no optimizations,
367
+ // because the compiler cannot eliminate enough write barriers.
368
+ Flag.N = 0
369
+ Ctxt.Flag_optimize = true
370
+
371
+ // Runtime can't use -d=checkptr, at least not yet.
372
+ Debug.Checkptr = 0
373
+
374
+ // Fuzzing the runtime isn't interesting either.
375
+ Debug.Libfuzzer = 0
376
+ }
377
+
378
+ if Debug.Checkptr == -1 { // if not set explicitly
379
+ Debug.Checkptr = 0
380
+ }
381
+
382
+ // set via a -d flag
383
+ Ctxt.Debugpcln = Debug.PCTab
384
+
385
+ // https://golang.org/issue/67502
386
+ if buildcfg.GOOS == "plan9" && buildcfg.GOARCH == "386" {
387
+ Debug.AlignHot = 0
388
+ }
389
+ }
390
+
391
+ // registerFlags adds flag registrations for all the fields in Flag.
392
+ // See the comment on type CmdFlags for the rules.
393
+ func registerFlags() {
394
+ var (
395
+ boolType = reflect.TypeFor[bool]()
396
+ intType = reflect.TypeFor[int]()
397
+ stringType = reflect.TypeFor[string]()
398
+ ptrBoolType = reflect.TypeFor[*bool]()
399
+ ptrIntType = reflect.TypeFor[*int]()
400
+ ptrStringType = reflect.TypeFor[*string]()
401
+ countType = reflect.TypeFor[CountFlag]()
402
+ funcType = reflect.TypeFor[func(string)]()
403
+ )
404
+
405
+ v := reflect.ValueOf(&Flag).Elem()
406
+ t := v.Type()
407
+ for i := 0; i < t.NumField(); i++ {
408
+ f := t.Field(i)
409
+ if f.Name == "Cfg" {
410
+ continue
411
+ }
412
+
413
+ var name string
414
+ if len(f.Name) == 1 {
415
+ name = f.Name
416
+ } else if len(f.Name) == 6 && f.Name[:5] == "Lower" && 'A' <= f.Name[5] && f.Name[5] <= 'Z' {
417
+ name = string(rune(f.Name[5] + 'a' - 'A'))
418
+ } else {
419
+ name = strings.ToLower(f.Name)
420
+ }
421
+ if tag := f.Tag.Get("flag"); tag != "" {
422
+ name = tag
423
+ }
424
+
425
+ help := f.Tag.Get("help")
426
+ if help == "" {
427
+ panic(fmt.Sprintf("base.Flag.%s is missing help text", f.Name))
428
+ }
429
+
430
+ if k := f.Type.Kind(); (k == reflect.Ptr || k == reflect.Func) && v.Field(i).IsNil() {
431
+ panic(fmt.Sprintf("base.Flag.%s is uninitialized %v", f.Name, f.Type))
432
+ }
433
+
434
+ switch f.Type {
435
+ case boolType:
436
+ p := v.Field(i).Addr().Interface().(*bool)
437
+ flag.BoolVar(p, name, *p, help)
438
+ case intType:
439
+ p := v.Field(i).Addr().Interface().(*int)
440
+ flag.IntVar(p, name, *p, help)
441
+ case stringType:
442
+ p := v.Field(i).Addr().Interface().(*string)
443
+ flag.StringVar(p, name, *p, help)
444
+ case ptrBoolType:
445
+ p := v.Field(i).Interface().(*bool)
446
+ flag.BoolVar(p, name, *p, help)
447
+ case ptrIntType:
448
+ p := v.Field(i).Interface().(*int)
449
+ flag.IntVar(p, name, *p, help)
450
+ case ptrStringType:
451
+ p := v.Field(i).Interface().(*string)
452
+ flag.StringVar(p, name, *p, help)
453
+ case countType:
454
+ p := (*int)(v.Field(i).Addr().Interface().(*CountFlag))
455
+ objabi.Flagcount(name, help, p)
456
+ case funcType:
457
+ f := v.Field(i).Interface().(func(string))
458
+ objabi.Flagfn1(name, help, f)
459
+ default:
460
+ if val, ok := v.Field(i).Interface().(flag.Value); ok {
461
+ flag.Var(val, name, help)
462
+ } else {
463
+ panic(fmt.Sprintf("base.Flag.%s has unexpected type %s", f.Name, f.Type))
464
+ }
465
+ }
466
+ }
467
+ }
468
+
469
+ // concurrentFlagOk reports whether the current compiler flags
470
+ // are compatible with concurrent compilation.
471
+ func concurrentFlagOk() bool {
472
+ // TODO(rsc): Many of these are fine. Remove them.
473
+ return Flag.Percent == 0 &&
474
+ Flag.E == 0 &&
475
+ Flag.K == 0 &&
476
+ Flag.L == 0 &&
477
+ Flag.LowerH == 0 &&
478
+ Flag.LowerJ == 0 &&
479
+ Flag.LowerM == 0 &&
480
+ Flag.LowerR == 0
481
+ }
482
+
483
+ func concurrentBackendAllowed() bool {
484
+ if !concurrentFlagOk() {
485
+ return false
486
+ }
487
+
488
+ // Debug.S by itself is ok, because all printing occurs
489
+ // while writing the object file, and that is non-concurrent.
490
+ // Adding Debug_vlog, however, causes Debug.S to also print
491
+ // while flushing the plist, which happens concurrently.
492
+ if Ctxt.Debugvlog || !Debug.ConcurrentOk || Flag.Live > 0 {
493
+ return false
494
+ }
495
+ // TODO: Test and delete this condition.
496
+ if buildcfg.Experiment.FieldTrack {
497
+ return false
498
+ }
499
+ // TODO: fix races and enable the following flags
500
+ if Ctxt.Flag_dynlink || Flag.Race {
501
+ return false
502
+ }
503
+ return true
504
+ }
505
+
506
+ func addImportDir(dir string) {
507
+ if dir != "" {
508
+ Flag.Cfg.ImportDirs = append(Flag.Cfg.ImportDirs, dir)
509
+ }
510
+ }
511
+
512
+ func readImportCfg(file string) {
513
+ if Flag.Cfg.ImportMap == nil {
514
+ Flag.Cfg.ImportMap = make(map[string]string)
515
+ }
516
+ Flag.Cfg.PackageFile = map[string]string{}
517
+ data, err := os.ReadFile(file)
518
+ if err != nil {
519
+ log.Fatalf("-importcfg: %v", err)
520
+ }
521
+
522
+ for lineNum, line := range strings.Split(string(data), "\n") {
523
+ lineNum++ // 1-based
524
+ line = strings.TrimSpace(line)
525
+ if line == "" || strings.HasPrefix(line, "#") {
526
+ continue
527
+ }
528
+
529
+ verb, args, found := strings.Cut(line, " ")
530
+ if found {
531
+ args = strings.TrimSpace(args)
532
+ }
533
+ before, after, hasEq := strings.Cut(args, "=")
534
+
535
+ switch verb {
536
+ default:
537
+ log.Fatalf("%s:%d: unknown directive %q", file, lineNum, verb)
538
+ case "importmap":
539
+ if !hasEq || before == "" || after == "" {
540
+ log.Fatalf(`%s:%d: invalid importmap: syntax is "importmap old=new"`, file, lineNum)
541
+ }
542
+ Flag.Cfg.ImportMap[before] = after
543
+ case "packagefile":
544
+ if !hasEq || before == "" || after == "" {
545
+ log.Fatalf(`%s:%d: invalid packagefile: syntax is "packagefile path=filename"`, file, lineNum)
546
+ }
547
+ Flag.Cfg.PackageFile[before] = after
548
+ }
549
+ }
550
+ }
551
+
552
+ func readCoverageCfg(file string) {
553
+ var cfg covcmd.CoverFixupConfig
554
+ data, err := os.ReadFile(file)
555
+ if err != nil {
556
+ log.Fatalf("-coveragecfg: %v", err)
557
+ }
558
+ if err := json.Unmarshal(data, &cfg); err != nil {
559
+ log.Fatalf("error reading -coveragecfg file %q: %v", file, err)
560
+ }
561
+ Flag.Cfg.CoverageInfo = &cfg
562
+ }
563
+
564
+ func readEmbedCfg(file string) {
565
+ data, err := os.ReadFile(file)
566
+ if err != nil {
567
+ log.Fatalf("-embedcfg: %v", err)
568
+ }
569
+ if err := json.Unmarshal(data, &Flag.Cfg.Embed); err != nil {
570
+ log.Fatalf("%s: %v", file, err)
571
+ }
572
+ if Flag.Cfg.Embed.Patterns == nil {
573
+ log.Fatalf("%s: invalid embedcfg: missing Patterns", file)
574
+ }
575
+ if Flag.Cfg.Embed.Files == nil {
576
+ log.Fatalf("%s: invalid embedcfg: missing Files", file)
577
+ }
578
+ }
579
+
580
+ // parseSpectre parses the spectre configuration from the string s.
581
+ func parseSpectre(s string) {
582
+ for f := range strings.SplitSeq(s, ",") {
583
+ f = strings.TrimSpace(f)
584
+ switch f {
585
+ default:
586
+ log.Fatalf("unknown setting -spectre=%s", f)
587
+ case "":
588
+ // nothing
589
+ case "all":
590
+ Flag.Cfg.SpectreIndex = true
591
+ Ctxt.Retpoline = true
592
+ case "index":
593
+ Flag.Cfg.SpectreIndex = true
594
+ case "ret":
595
+ Ctxt.Retpoline = true
596
+ }
597
+ }
598
+
599
+ if Flag.Cfg.SpectreIndex {
600
+ switch buildcfg.GOARCH {
601
+ case "amd64":
602
+ // ok
603
+ default:
604
+ log.Fatalf("GOARCH=%s does not support -spectre=index", buildcfg.GOARCH)
605
+ }
606
+ }
607
+ }
go/src/cmd/compile/internal/base/hashdebug.go ADDED
@@ -0,0 +1,421 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2022 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 base
6
+
7
+ import (
8
+ "bytes"
9
+ "cmd/internal/obj"
10
+ "cmd/internal/src"
11
+ "fmt"
12
+ "internal/bisect"
13
+ "io"
14
+ "os"
15
+ "path/filepath"
16
+ "strconv"
17
+ "strings"
18
+ "sync"
19
+ )
20
+
21
+ type hashAndMask struct {
22
+ // a hash h matches if (h^hash)&mask == 0
23
+ hash uint64
24
+ mask uint64
25
+ name string // base name, or base name + "0", "1", etc.
26
+ }
27
+
28
+ type HashDebug struct {
29
+ mu sync.Mutex // for logfile, posTmp, bytesTmp
30
+ name string // base name of the flag/variable.
31
+ // what file (if any) receives the yes/no logging?
32
+ // default is os.Stdout
33
+ logfile io.Writer
34
+ posTmp []src.Pos
35
+ bytesTmp bytes.Buffer
36
+ matches []hashAndMask // A hash matches if one of these matches.
37
+ excludes []hashAndMask // explicitly excluded hash suffixes
38
+ bisect *bisect.Matcher
39
+ fileSuffixOnly bool // for Pos hashes, remove the directory prefix.
40
+ inlineSuffixOnly bool // for Pos hashes, remove all but the most inline position.
41
+ }
42
+
43
+ // SetInlineSuffixOnly controls whether hashing and reporting use the entire
44
+ // inline position, or just the most-inline suffix. Compiler debugging tends
45
+ // to want the whole inlining, debugging user problems (loopvarhash, e.g.)
46
+ // typically does not need to see the entire inline tree, there is just one
47
+ // copy of the source code.
48
+ func (d *HashDebug) SetInlineSuffixOnly(b bool) *HashDebug {
49
+ d.inlineSuffixOnly = b
50
+ return d
51
+ }
52
+
53
+ // The default compiler-debugging HashDebug, for "-d=gossahash=..."
54
+ var hashDebug *HashDebug
55
+
56
+ var ConvertHash *HashDebug // for debugging float-to-[u]int conversion changes
57
+ var FmaHash *HashDebug // for debugging fused-multiply-add floating point changes
58
+ var LoopVarHash *HashDebug // for debugging shared/private loop variable changes
59
+ var PGOHash *HashDebug // for debugging PGO optimization decisions
60
+ var LiteralAllocHash *HashDebug // for debugging literal allocation optimizations
61
+ var MergeLocalsHash *HashDebug // for debugging local stack slot merging changes
62
+ var VariableMakeHash *HashDebug // for debugging variable-sized make optimizations
63
+
64
+ // DebugHashMatchPkgFunc reports whether debug variable Gossahash
65
+ //
66
+ // 1. is empty (returns true; this is a special more-quickly implemented case of 4 below)
67
+ //
68
+ // 2. is "y" or "Y" (returns true)
69
+ //
70
+ // 3. is "n" or "N" (returns false)
71
+ //
72
+ // 4. does not explicitly exclude the sha1 hash of pkgAndName (see step 6)
73
+ //
74
+ // 5. is a suffix of the sha1 hash of pkgAndName (returns true)
75
+ //
76
+ // 6. OR
77
+ // if the (non-empty) value is in the regular language
78
+ // "(-[01]+/)+?([01]+(/[01]+)+?"
79
+ // (exclude..)(....include...)
80
+ // test the [01]+ exclude substrings, if any suffix-match, return false (4 above)
81
+ // test the [01]+ include substrings, if any suffix-match, return true
82
+ // The include substrings AFTER the first slash are numbered 0,1, etc and
83
+ // are named fmt.Sprintf("%s%d", varname, number)
84
+ // As an extra-special case for multiple failure search,
85
+ // an excludes-only string ending in a slash (terminated, not separated)
86
+ // implicitly specifies the include string "0/1", that is, match everything.
87
+ // (Exclude strings are used for automated search for multiple failures.)
88
+ // Clause 6 is not really intended for human use and only
89
+ // matters for failures that require multiple triggers.
90
+ //
91
+ // Otherwise it returns false.
92
+ //
93
+ // Unless Flags.Gossahash is empty, when DebugHashMatchPkgFunc returns true the message
94
+ //
95
+ // "%s triggered %s\n", varname, pkgAndName
96
+ //
97
+ // is printed on the file named in environment variable GSHS_LOGFILE,
98
+ // or standard out if that is empty. "Varname" is either the name of
99
+ // the variable or the name of the substring, depending on which matched.
100
+ //
101
+ // Typical use:
102
+ //
103
+ // 1. you make a change to the compiler, say, adding a new phase
104
+ //
105
+ // 2. it is broken in some mystifying way, for example, make.bash builds a broken
106
+ // compiler that almost works, but crashes compiling a test in run.bash.
107
+ //
108
+ // 3. add this guard to the code, which by default leaves it broken, but does not
109
+ // run the broken new code if Flags.Gossahash is non-empty and non-matching:
110
+ //
111
+ // if !base.DebugHashMatch(ir.PkgFuncName(fn)) {
112
+ // return nil // early exit, do nothing
113
+ // }
114
+ //
115
+ // 4. rebuild w/o the bad code,
116
+ // GOCOMPILEDEBUG=gossahash=n ./all.bash
117
+ // to verify that you put the guard in the right place with the right sense of the test.
118
+ //
119
+ // 5. use github.com/dr2chase/gossahash to search for the error:
120
+ //
121
+ // go install github.com/dr2chase/gossahash@latest
122
+ //
123
+ // gossahash -- <the thing that fails>
124
+ //
125
+ // for example: GOMAXPROCS=1 gossahash -- ./all.bash
126
+ //
127
+ // 6. gossahash should return a single function whose miscompilation
128
+ // causes the problem, and you can focus on that.
129
+ func DebugHashMatchPkgFunc(pkg, fn string) bool {
130
+ return hashDebug.MatchPkgFunc(pkg, fn, nil)
131
+ }
132
+
133
+ func DebugHashMatchPos(pos src.XPos) bool {
134
+ return hashDebug.MatchPos(pos, nil)
135
+ }
136
+
137
+ // HasDebugHash returns true if Flags.Gossahash is non-empty, which
138
+ // results in hashDebug being not-nil. I.e., if !HasDebugHash(),
139
+ // there is no need to create the string for hashing and testing.
140
+ func HasDebugHash() bool {
141
+ return hashDebug != nil
142
+ }
143
+
144
+ // TODO: Delete when we switch to bisect-only.
145
+ func toHashAndMask(s, varname string) hashAndMask {
146
+ l := len(s)
147
+ if l > 64 {
148
+ s = s[l-64:]
149
+ l = 64
150
+ }
151
+ m := ^(^uint64(0) << l)
152
+ h, err := strconv.ParseUint(s, 2, 64)
153
+ if err != nil {
154
+ Fatalf("Could not parse %s (=%s) as a binary number", varname, s)
155
+ }
156
+
157
+ return hashAndMask{name: varname, hash: h, mask: m}
158
+ }
159
+
160
+ // NewHashDebug returns a new hash-debug tester for the
161
+ // environment variable ev. If ev is not set, it returns
162
+ // nil, allowing a lightweight check for normal-case behavior.
163
+ func NewHashDebug(ev, s string, file io.Writer) *HashDebug {
164
+ if s == "" {
165
+ return nil
166
+ }
167
+
168
+ hd := &HashDebug{name: ev, logfile: file}
169
+ if !strings.Contains(s, "/") {
170
+ m, err := bisect.New(s)
171
+ if err != nil {
172
+ Fatalf("%s: %v", ev, err)
173
+ }
174
+ hd.bisect = m
175
+ return hd
176
+ }
177
+
178
+ // TODO: Delete remainder of function when we switch to bisect-only.
179
+ ss := strings.Split(s, "/")
180
+ // first remove any leading exclusions; these are preceded with "-"
181
+ i := 0
182
+ for len(ss) > 0 {
183
+ s := ss[0]
184
+ if len(s) == 0 || len(s) > 0 && s[0] != '-' {
185
+ break
186
+ }
187
+ ss = ss[1:]
188
+ hd.excludes = append(hd.excludes, toHashAndMask(s[1:], fmt.Sprintf("%s%d", "HASH_EXCLUDE", i)))
189
+ i++
190
+ }
191
+ // hash searches may use additional EVs with 0, 1, 2, ... suffixes.
192
+ i = 0
193
+ for _, s := range ss {
194
+ if s == "" {
195
+ if i != 0 || len(ss) > 1 && ss[1] != "" || len(ss) > 2 {
196
+ Fatalf("Empty hash match string for %s should be first (and only) one", ev)
197
+ }
198
+ // Special case of should match everything.
199
+ hd.matches = append(hd.matches, toHashAndMask("0", fmt.Sprintf("%s0", ev)))
200
+ hd.matches = append(hd.matches, toHashAndMask("1", fmt.Sprintf("%s1", ev)))
201
+ break
202
+ }
203
+ if i == 0 {
204
+ hd.matches = append(hd.matches, toHashAndMask(s, ev))
205
+ } else {
206
+ hd.matches = append(hd.matches, toHashAndMask(s, fmt.Sprintf("%s%d", ev, i-1)))
207
+ }
208
+ i++
209
+ }
210
+ return hd
211
+ }
212
+
213
+ // TODO: Delete when we switch to bisect-only.
214
+ func (d *HashDebug) excluded(hash uint64) bool {
215
+ for _, m := range d.excludes {
216
+ if (m.hash^hash)&m.mask == 0 {
217
+ return true
218
+ }
219
+ }
220
+ return false
221
+ }
222
+
223
+ // TODO: Delete when we switch to bisect-only.
224
+ func hashString(hash uint64) string {
225
+ hstr := ""
226
+ if hash == 0 {
227
+ hstr = "0"
228
+ } else {
229
+ for ; hash != 0; hash = hash >> 1 {
230
+ hstr = string('0'+byte(hash&1)) + hstr
231
+ }
232
+ }
233
+ if len(hstr) > 24 {
234
+ hstr = hstr[len(hstr)-24:]
235
+ }
236
+ return hstr
237
+ }
238
+
239
+ // TODO: Delete when we switch to bisect-only.
240
+ func (d *HashDebug) match(hash uint64) *hashAndMask {
241
+ for i, m := range d.matches {
242
+ if (m.hash^hash)&m.mask == 0 {
243
+ return &d.matches[i]
244
+ }
245
+ }
246
+ return nil
247
+ }
248
+
249
+ // MatchPkgFunc returns true if either the variable used to create d is
250
+ // unset, or if its value is y, or if it is a suffix of the base-two
251
+ // representation of the hash of pkg and fn. If the variable is not nil,
252
+ // then a true result is accompanied by stylized output to d.logfile, which
253
+ // is used for automated bug search.
254
+ func (d *HashDebug) MatchPkgFunc(pkg, fn string, note func() string) bool {
255
+ if d == nil {
256
+ return true
257
+ }
258
+ // Written this way to make inlining likely.
259
+ return d.matchPkgFunc(pkg, fn, note)
260
+ }
261
+
262
+ func (d *HashDebug) matchPkgFunc(pkg, fn string, note func() string) bool {
263
+ hash := bisect.Hash(pkg, fn)
264
+ return d.matchAndLog(hash, func() string { return pkg + "." + fn }, note)
265
+ }
266
+
267
+ // MatchPos is similar to MatchPkgFunc, but for hash computation
268
+ // it uses the source position including all inlining information instead of
269
+ // package name and path.
270
+ // Note that the default answer for no environment variable (d == nil)
271
+ // is "yes", do the thing.
272
+ func (d *HashDebug) MatchPos(pos src.XPos, desc func() string) bool {
273
+ if d == nil {
274
+ return true
275
+ }
276
+ // Written this way to make inlining likely.
277
+ return d.matchPos(Ctxt, pos, desc)
278
+ }
279
+
280
+ func (d *HashDebug) matchPos(ctxt *obj.Link, pos src.XPos, note func() string) bool {
281
+ return d.matchPosWithInfo(ctxt, pos, nil, note)
282
+ }
283
+
284
+ func (d *HashDebug) matchPosWithInfo(ctxt *obj.Link, pos src.XPos, info any, note func() string) bool {
285
+ hash := d.hashPos(ctxt, pos)
286
+ if info != nil {
287
+ hash = bisect.Hash(hash, info)
288
+ }
289
+ return d.matchAndLog(hash,
290
+ func() string {
291
+ r := d.fmtPos(ctxt, pos)
292
+ if info != nil {
293
+ r += fmt.Sprintf(" (%v)", info)
294
+ }
295
+ return r
296
+ },
297
+ note)
298
+ }
299
+
300
+ // MatchPosWithInfo is similar to MatchPos, but with additional information
301
+ // that is included for hash computation, so it can distinguish multiple
302
+ // matches on the same source location.
303
+ // Note that the default answer for no environment variable (d == nil)
304
+ // is "yes", do the thing.
305
+ func (d *HashDebug) MatchPosWithInfo(pos src.XPos, info any, desc func() string) bool {
306
+ if d == nil {
307
+ return true
308
+ }
309
+ // Written this way to make inlining likely.
310
+ return d.matchPosWithInfo(Ctxt, pos, info, desc)
311
+ }
312
+
313
+ // matchAndLog is the core matcher. It reports whether the hash matches the pattern.
314
+ // If a report needs to be printed, match prints that report to the log file.
315
+ // The text func must be non-nil and should return a user-readable
316
+ // representation of what was hashed. The note func may be nil; if non-nil,
317
+ // it should return additional information to display to the user when this
318
+ // change is selected.
319
+ func (d *HashDebug) matchAndLog(hash uint64, text, note func() string) bool {
320
+ if d.bisect != nil {
321
+ enabled := d.bisect.ShouldEnable(hash)
322
+ if d.bisect.ShouldPrint(hash) {
323
+ disabled := ""
324
+ if !enabled {
325
+ disabled = " [DISABLED]"
326
+ }
327
+ var t string
328
+ if !d.bisect.MarkerOnly() {
329
+ t = text()
330
+ if note != nil {
331
+ if n := note(); n != "" {
332
+ t += ": " + n + disabled
333
+ disabled = ""
334
+ }
335
+ }
336
+ }
337
+ d.log(d.name, hash, strings.TrimSpace(t+disabled))
338
+ }
339
+ return enabled
340
+ }
341
+
342
+ // TODO: Delete rest of function body when we switch to bisect-only.
343
+ if d.excluded(hash) {
344
+ return false
345
+ }
346
+ if m := d.match(hash); m != nil {
347
+ d.log(m.name, hash, text())
348
+ return true
349
+ }
350
+ return false
351
+ }
352
+
353
+ // short returns the form of file name to use for d.
354
+ // The default is the full path, but fileSuffixOnly selects
355
+ // just the final path element.
356
+ func (d *HashDebug) short(name string) string {
357
+ if d.fileSuffixOnly {
358
+ return filepath.Base(name)
359
+ }
360
+ return name
361
+ }
362
+
363
+ // hashPos returns a hash of the position pos, including its entire inline stack.
364
+ // If d.inlineSuffixOnly is true, hashPos only considers the innermost (leaf) position on the inline stack.
365
+ func (d *HashDebug) hashPos(ctxt *obj.Link, pos src.XPos) uint64 {
366
+ if d.inlineSuffixOnly {
367
+ p := ctxt.InnermostPos(pos)
368
+ return bisect.Hash(d.short(p.Filename()), p.Line(), p.Col())
369
+ }
370
+ h := bisect.Hash()
371
+ ctxt.AllPos(pos, func(p src.Pos) {
372
+ h = bisect.Hash(h, d.short(p.Filename()), p.Line(), p.Col())
373
+ })
374
+ return h
375
+ }
376
+
377
+ // fmtPos returns a textual formatting of the position pos, including its entire inline stack.
378
+ // If d.inlineSuffixOnly is true, fmtPos only considers the innermost (leaf) position on the inline stack.
379
+ func (d *HashDebug) fmtPos(ctxt *obj.Link, pos src.XPos) string {
380
+ format := func(p src.Pos) string {
381
+ return fmt.Sprintf("%s:%d:%d", d.short(p.Filename()), p.Line(), p.Col())
382
+ }
383
+ if d.inlineSuffixOnly {
384
+ return format(ctxt.InnermostPos(pos))
385
+ }
386
+ var stk []string
387
+ ctxt.AllPos(pos, func(p src.Pos) {
388
+ stk = append(stk, format(p))
389
+ })
390
+ return strings.Join(stk, "; ")
391
+ }
392
+
393
+ // log prints a match with the given hash and textual formatting.
394
+ // TODO: Delete varname parameter when we switch to bisect-only.
395
+ func (d *HashDebug) log(varname string, hash uint64, text string) {
396
+ d.mu.Lock()
397
+ defer d.mu.Unlock()
398
+
399
+ file := d.logfile
400
+ if file == nil {
401
+ if tmpfile := os.Getenv("GSHS_LOGFILE"); tmpfile != "" {
402
+ var err error
403
+ file, err = os.OpenFile(tmpfile, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
404
+ if err != nil {
405
+ Fatalf("could not open hash-testing logfile %s", tmpfile)
406
+ return
407
+ }
408
+ }
409
+ if file == nil {
410
+ file = os.Stdout
411
+ }
412
+ d.logfile = file
413
+ }
414
+
415
+ // Bisect output.
416
+ fmt.Fprintf(file, "%s %s\n", text, bisect.Marker(hash))
417
+
418
+ // Gossahash output.
419
+ // TODO: Delete rest of function when we switch to bisect-only.
420
+ fmt.Fprintf(file, "%s triggered %s %s\n", varname, text, hashString(hash))
421
+ }
go/src/cmd/compile/internal/base/hashdebug_test.go ADDED
@@ -0,0 +1,140 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2022 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 base
6
+
7
+ import (
8
+ "bytes"
9
+ "internal/bisect"
10
+ "strings"
11
+ "testing"
12
+ )
13
+
14
+ func TestHashDebugGossahashY(t *testing.T) {
15
+ hd := NewHashDebug("GOSSAHASH", "y", new(bytes.Buffer))
16
+ if hd == nil {
17
+ t.Errorf("NewHashDebug should not return nil for GOSSASHASH=y")
18
+ }
19
+ if !hd.MatchPkgFunc("anything", "anyfunc", nil) {
20
+ t.Errorf("NewHashDebug should return yes for everything for GOSSASHASH=y")
21
+ }
22
+ }
23
+
24
+ func TestHashDebugGossahashN(t *testing.T) {
25
+ hd := NewHashDebug("GOSSAHASH", "n", new(bytes.Buffer))
26
+ if hd == nil {
27
+ t.Errorf("NewHashDebug should not return nil for GOSSASHASH=n")
28
+ }
29
+ if hd.MatchPkgFunc("anything", "anyfunc", nil) {
30
+ t.Errorf("NewHashDebug should return no for everything for GOSSASHASH=n")
31
+ }
32
+ }
33
+
34
+ func TestHashDebugGossahashEmpty(t *testing.T) {
35
+ hd := NewHashDebug("GOSSAHASH", "", nil)
36
+ if hd != nil {
37
+ t.Errorf("NewHashDebug should return nil for GOSSASHASH=\"\"")
38
+ }
39
+ }
40
+
41
+ func TestHashDebugMagic(t *testing.T) {
42
+ hd := NewHashDebug("FOOXYZZY", "y", nil)
43
+ hd0 := NewHashDebug("FOOXYZZY0", "n", nil)
44
+ if hd == nil {
45
+ t.Errorf("NewHashDebug should have succeeded for FOOXYZZY")
46
+ }
47
+ if hd0 == nil {
48
+ t.Errorf("NewHashDebug should have succeeded for FOOXYZZY0")
49
+ }
50
+ }
51
+
52
+ func TestHash(t *testing.T) {
53
+ h0 := bisect.Hash("bar", "0")
54
+ h1 := bisect.Hash("bar", "1")
55
+ t.Logf(`These values are used in other tests: Hash("bar", "0")=%#64b, Hash("bar", "1")=%#64b`, h0, h1)
56
+ if h0 == h1 {
57
+ t.Errorf("Hashes 0x%x and 0x%x should differ", h0, h1)
58
+ }
59
+ }
60
+
61
+ func TestHashMatch(t *testing.T) {
62
+ b := new(bytes.Buffer)
63
+ hd := NewHashDebug("GOSSAHASH", "v1110", b)
64
+ check := hd.MatchPkgFunc("bar", "0", func() string { return "note" })
65
+ msg := b.String()
66
+ t.Logf("message was '%s'", msg)
67
+ if !check {
68
+ t.Errorf("GOSSAHASH=1110 should have matched for 'bar', '0'")
69
+ }
70
+ wantPrefix(t, msg, "bar.0: note [bisect-match ")
71
+ wantContains(t, msg, "\nGOSSAHASH triggered bar.0: note ")
72
+ }
73
+
74
+ func TestYMatch(t *testing.T) {
75
+ b := new(bytes.Buffer)
76
+ hd := NewHashDebug("GOSSAHASH", "vy", b)
77
+ check := hd.MatchPkgFunc("bar", "0", nil)
78
+ msg := b.String()
79
+ t.Logf("message was '%s'", msg)
80
+ if !check {
81
+ t.Errorf("GOSSAHASH=y should have matched for 'bar', '0'")
82
+ }
83
+ wantPrefix(t, msg, "bar.0 [bisect-match ")
84
+ wantContains(t, msg, "\nGOSSAHASH triggered bar.0 010100100011100101011110")
85
+ }
86
+
87
+ func TestNMatch(t *testing.T) {
88
+ b := new(bytes.Buffer)
89
+ hd := NewHashDebug("GOSSAHASH", "vn", b)
90
+ check := hd.MatchPkgFunc("bar", "0", nil)
91
+ msg := b.String()
92
+ t.Logf("message was '%s'", msg)
93
+ if check {
94
+ t.Errorf("GOSSAHASH=n should NOT have matched for 'bar', '0'")
95
+ }
96
+ wantPrefix(t, msg, "bar.0 [DISABLED] [bisect-match ")
97
+ wantContains(t, msg, "\nGOSSAHASH triggered bar.0 [DISABLED] 010100100011100101011110")
98
+ }
99
+
100
+ func TestHashNoMatch(t *testing.T) {
101
+ b := new(bytes.Buffer)
102
+ hd := NewHashDebug("GOSSAHASH", "01110", b)
103
+ check := hd.MatchPkgFunc("bar", "0", nil)
104
+ msg := b.String()
105
+ t.Logf("message was '%s'", msg)
106
+ if check {
107
+ t.Errorf("GOSSAHASH=001100 should NOT have matched for 'bar', '0'")
108
+ }
109
+ if msg != "" {
110
+ t.Errorf("Message should have been empty, instead %s", msg)
111
+ }
112
+
113
+ }
114
+
115
+ func TestHashSecondMatch(t *testing.T) {
116
+ b := new(bytes.Buffer)
117
+ hd := NewHashDebug("GOSSAHASH", "01110/11110", b)
118
+
119
+ check := hd.MatchPkgFunc("bar", "0", nil)
120
+ msg := b.String()
121
+ t.Logf("message was '%s'", msg)
122
+ if !check {
123
+ t.Errorf("GOSSAHASH=001100, GOSSAHASH0=0011 should have matched for 'bar', '0'")
124
+ }
125
+ wantContains(t, msg, "\nGOSSAHASH0 triggered bar")
126
+ }
127
+
128
+ func wantPrefix(t *testing.T, got, want string) {
129
+ t.Helper()
130
+ if !strings.HasPrefix(got, want) {
131
+ t.Errorf("want prefix %q, got:\n%s", want, got)
132
+ }
133
+ }
134
+
135
+ func wantContains(t *testing.T, got, want string) {
136
+ t.Helper()
137
+ if !strings.Contains(got, want) {
138
+ t.Errorf("want contains %q, got:\n%s", want, got)
139
+ }
140
+ }
go/src/cmd/compile/internal/base/link.go ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2021 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 base
6
+
7
+ import (
8
+ "cmd/internal/obj"
9
+ )
10
+
11
+ // ReservedImports are import paths used internally for generated
12
+ // symbols by the compiler.
13
+ //
14
+ // The linker uses the magic symbol prefixes "go:" and "type:".
15
+ // Avoid potential confusion between import paths and symbols
16
+ // by rejecting these reserved imports for now. Also, people
17
+ // "can do weird things in GOPATH and we'd prefer they didn't
18
+ // do _that_ weird thing" (per rsc). See also #4257.
19
+ var ReservedImports = map[string]bool{
20
+ "go": true,
21
+ "type": true,
22
+ }
23
+
24
+ var Ctxt *obj.Link
25
+
26
+ // TODO(mdempsky): These should probably be obj.Link methods.
27
+
28
+ // PkgLinksym returns the linker symbol for name within the given
29
+ // package prefix. For user packages, prefix should be the package
30
+ // path encoded with objabi.PathToPrefix.
31
+ func PkgLinksym(prefix, name string, abi obj.ABI) *obj.LSym {
32
+ if name == "_" {
33
+ // TODO(mdempsky): Cleanup callers and Fatalf instead.
34
+ return linksym(prefix, "_", abi)
35
+ }
36
+ sep := "."
37
+ if ReservedImports[prefix] {
38
+ sep = ":"
39
+ }
40
+ return linksym(prefix, prefix+sep+name, abi)
41
+ }
42
+
43
+ // Linkname returns the linker symbol for the given name as it might
44
+ // appear within a //go:linkname directive.
45
+ func Linkname(name string, abi obj.ABI) *obj.LSym {
46
+ return linksym("_", name, abi)
47
+ }
48
+
49
+ // linksym is an internal helper function for implementing the above
50
+ // exported APIs.
51
+ func linksym(pkg, name string, abi obj.ABI) *obj.LSym {
52
+ return Ctxt.LookupABIInit(name, abi, func(r *obj.LSym) { r.Pkg = pkg })
53
+ }
go/src/cmd/compile/internal/base/mapfile_mmap.go ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2018 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
+ //go:build unix
6
+
7
+ package base
8
+
9
+ import (
10
+ "internal/unsafeheader"
11
+ "os"
12
+ "runtime"
13
+ "syscall"
14
+ "unsafe"
15
+ )
16
+
17
+ // TODO(mdempsky): Is there a higher-level abstraction that still
18
+ // works well for iimport?
19
+
20
+ // MapFile returns length bytes from the file starting at the
21
+ // specified offset as a string.
22
+ func MapFile(f *os.File, offset, length int64) (string, error) {
23
+ // POSIX mmap: "The implementation may require that off is a
24
+ // multiple of the page size."
25
+ x := offset & int64(os.Getpagesize()-1)
26
+ offset -= x
27
+ length += x
28
+
29
+ buf, err := syscall.Mmap(int(f.Fd()), offset, int(length), syscall.PROT_READ, syscall.MAP_SHARED)
30
+ runtime.KeepAlive(f)
31
+ if err != nil {
32
+ return "", err
33
+ }
34
+
35
+ buf = buf[x:]
36
+ pSlice := (*unsafeheader.Slice)(unsafe.Pointer(&buf))
37
+
38
+ var res string
39
+ pString := (*unsafeheader.String)(unsafe.Pointer(&res))
40
+
41
+ pString.Data = pSlice.Data
42
+ pString.Len = pSlice.Len
43
+
44
+ return res, nil
45
+ }
go/src/cmd/compile/internal/base/mapfile_read.go ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2018 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
+ //go:build !unix
6
+
7
+ package base
8
+
9
+ import (
10
+ "io"
11
+ "os"
12
+ )
13
+
14
+ func MapFile(f *os.File, offset, length int64) (string, error) {
15
+ buf := make([]byte, length)
16
+ _, err := io.ReadFull(io.NewSectionReader(f, offset, length), buf)
17
+ if err != nil {
18
+ return "", err
19
+ }
20
+ return string(buf), nil
21
+ }
go/src/cmd/compile/internal/base/print.go ADDED
@@ -0,0 +1,288 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 base
6
+
7
+ import (
8
+ "fmt"
9
+ "internal/buildcfg"
10
+ "internal/types/errors"
11
+ "os"
12
+ "runtime/debug"
13
+ "sort"
14
+ "strings"
15
+
16
+ "cmd/internal/src"
17
+ "cmd/internal/telemetry/counter"
18
+ )
19
+
20
+ // An errorMsg is a queued error message, waiting to be printed.
21
+ type errorMsg struct {
22
+ pos src.XPos
23
+ msg string
24
+ code errors.Code
25
+ }
26
+
27
+ // Pos is the current source position being processed,
28
+ // printed by Errorf, ErrorfLang, Fatalf, and Warnf.
29
+ var Pos src.XPos
30
+
31
+ var (
32
+ errorMsgs []errorMsg
33
+ numErrors int // number of entries in errorMsgs that are errors (as opposed to warnings)
34
+ numSyntaxErrors int
35
+ )
36
+
37
+ // Errors returns the number of errors reported.
38
+ func Errors() int {
39
+ return numErrors
40
+ }
41
+
42
+ // SyntaxErrors returns the number of syntax errors reported.
43
+ func SyntaxErrors() int {
44
+ return numSyntaxErrors
45
+ }
46
+
47
+ // addErrorMsg adds a new errorMsg (which may be a warning) to errorMsgs.
48
+ func addErrorMsg(pos src.XPos, code errors.Code, format string, args ...any) {
49
+ msg := fmt.Sprintf(format, args...)
50
+ // Only add the position if know the position.
51
+ // See issue golang.org/issue/11361.
52
+ if pos.IsKnown() {
53
+ msg = fmt.Sprintf("%v: %s", FmtPos(pos), msg)
54
+ }
55
+ errorMsgs = append(errorMsgs, errorMsg{
56
+ pos: pos,
57
+ msg: msg + "\n",
58
+ code: code,
59
+ })
60
+ }
61
+
62
+ // FmtPos formats pos as a file:line string.
63
+ func FmtPos(pos src.XPos) string {
64
+ if Ctxt == nil {
65
+ return "???"
66
+ }
67
+ return Ctxt.OutermostPos(pos).Format(Flag.C == 0, Flag.L == 1)
68
+ }
69
+
70
+ // byPos sorts errors by source position.
71
+ type byPos []errorMsg
72
+
73
+ func (x byPos) Len() int { return len(x) }
74
+ func (x byPos) Less(i, j int) bool { return x[i].pos.Before(x[j].pos) }
75
+ func (x byPos) Swap(i, j int) { x[i], x[j] = x[j], x[i] }
76
+
77
+ // FlushErrors sorts errors seen so far by line number, prints them to stdout,
78
+ // and empties the errors array.
79
+ func FlushErrors() {
80
+ if Ctxt != nil && Ctxt.Bso != nil {
81
+ Ctxt.Bso.Flush()
82
+ }
83
+ if len(errorMsgs) == 0 {
84
+ return
85
+ }
86
+ sort.Stable(byPos(errorMsgs))
87
+ for i, err := range errorMsgs {
88
+ if i == 0 || err.msg != errorMsgs[i-1].msg {
89
+ fmt.Print(err.msg)
90
+ }
91
+ }
92
+ errorMsgs = errorMsgs[:0]
93
+ }
94
+
95
+ // lasterror keeps track of the most recently issued error,
96
+ // to avoid printing multiple error messages on the same line.
97
+ var lasterror struct {
98
+ syntax src.XPos // source position of last syntax error
99
+ other src.XPos // source position of last non-syntax error
100
+ msg string // error message of last non-syntax error
101
+ }
102
+
103
+ // sameline reports whether two positions a, b are on the same line.
104
+ func sameline(a, b src.XPos) bool {
105
+ p := Ctxt.PosTable.Pos(a)
106
+ q := Ctxt.PosTable.Pos(b)
107
+ return p.Base() == q.Base() && p.Line() == q.Line()
108
+ }
109
+
110
+ // Errorf reports a formatted error at the current line.
111
+ func Errorf(format string, args ...any) {
112
+ ErrorfAt(Pos, 0, format, args...)
113
+ }
114
+
115
+ // ErrorfAt reports a formatted error message at pos.
116
+ func ErrorfAt(pos src.XPos, code errors.Code, format string, args ...any) {
117
+ msg := fmt.Sprintf(format, args...)
118
+
119
+ if strings.HasPrefix(msg, "syntax error") {
120
+ numSyntaxErrors++
121
+ // only one syntax error per line, no matter what error
122
+ if sameline(lasterror.syntax, pos) {
123
+ return
124
+ }
125
+ lasterror.syntax = pos
126
+ } else {
127
+ // only one of multiple equal non-syntax errors per line
128
+ // (FlushErrors shows only one of them, so we filter them
129
+ // here as best as we can (they may not appear in order)
130
+ // so that we don't count them here and exit early, and
131
+ // then have nothing to show for.)
132
+ if sameline(lasterror.other, pos) && lasterror.msg == msg {
133
+ return
134
+ }
135
+ lasterror.other = pos
136
+ lasterror.msg = msg
137
+ }
138
+
139
+ addErrorMsg(pos, code, "%s", msg)
140
+ numErrors++
141
+
142
+ hcrash()
143
+ if numErrors >= 10 && Flag.LowerE == 0 {
144
+ FlushErrors()
145
+ fmt.Printf("%v: too many errors\n", FmtPos(pos))
146
+ ErrorExit()
147
+ }
148
+ }
149
+
150
+ // UpdateErrorDot is a clumsy hack that rewrites the last error,
151
+ // if it was "LINE: undefined: NAME", to be "LINE: undefined: NAME in EXPR".
152
+ // It is used to give better error messages for dot (selector) expressions.
153
+ func UpdateErrorDot(line string, name, expr string) {
154
+ if len(errorMsgs) == 0 {
155
+ return
156
+ }
157
+ e := &errorMsgs[len(errorMsgs)-1]
158
+ if strings.HasPrefix(e.msg, line) && e.msg == fmt.Sprintf("%v: undefined: %v\n", line, name) {
159
+ e.msg = fmt.Sprintf("%v: undefined: %v in %v\n", line, name, expr)
160
+ }
161
+ }
162
+
163
+ // Warn reports a formatted warning at the current line.
164
+ // In general the Go compiler does NOT generate warnings,
165
+ // so this should be used only when the user has opted in
166
+ // to additional output by setting a particular flag.
167
+ func Warn(format string, args ...any) {
168
+ WarnfAt(Pos, format, args...)
169
+ }
170
+
171
+ // WarnfAt reports a formatted warning at pos.
172
+ // In general the Go compiler does NOT generate warnings,
173
+ // so this should be used only when the user has opted in
174
+ // to additional output by setting a particular flag.
175
+ func WarnfAt(pos src.XPos, format string, args ...any) {
176
+ addErrorMsg(pos, 0, format, args...)
177
+ if Flag.LowerM != 0 {
178
+ FlushErrors()
179
+ }
180
+ }
181
+
182
+ // Fatalf reports a fatal error - an internal problem - at the current line and exits.
183
+ // If other errors have already been printed, then Fatalf just quietly exits.
184
+ // (The internal problem may have been caused by incomplete information
185
+ // after the already-reported errors, so best to let users fix those and
186
+ // try again without being bothered about a spurious internal error.)
187
+ //
188
+ // But if no errors have been printed, or if -d panic has been specified,
189
+ // Fatalf prints the error as an "internal compiler error". In a released build,
190
+ // it prints an error asking to file a bug report. In development builds, it
191
+ // prints a stack trace.
192
+ //
193
+ // If -h has been specified, Fatalf panics to force the usual runtime info dump.
194
+ func Fatalf(format string, args ...any) {
195
+ FatalfAt(Pos, format, args...)
196
+ }
197
+
198
+ var bugStack = counter.NewStack("compile/bug", 16) // 16 is arbitrary; used by gopls and crashmonitor
199
+
200
+ // FatalfAt reports a fatal error - an internal problem - at pos and exits.
201
+ // If other errors have already been printed, then FatalfAt just quietly exits.
202
+ // (The internal problem may have been caused by incomplete information
203
+ // after the already-reported errors, so best to let users fix those and
204
+ // try again without being bothered about a spurious internal error.)
205
+ //
206
+ // But if no errors have been printed, or if -d panic has been specified,
207
+ // FatalfAt prints the error as an "internal compiler error". In a released build,
208
+ // it prints an error asking to file a bug report. In development builds, it
209
+ // prints a stack trace.
210
+ //
211
+ // If -h has been specified, FatalfAt panics to force the usual runtime info dump.
212
+ func FatalfAt(pos src.XPos, format string, args ...any) {
213
+ FlushErrors()
214
+
215
+ bugStack.Inc()
216
+
217
+ if Debug.Panic != 0 || numErrors == 0 {
218
+ fmt.Printf("%v: internal compiler error: ", FmtPos(pos))
219
+ fmt.Printf(format, args...)
220
+ fmt.Printf("\n")
221
+
222
+ // If this is a released compiler version, ask for a bug report.
223
+ if Debug.Panic == 0 && strings.HasPrefix(buildcfg.Version, "go") && !strings.Contains(buildcfg.Version, "devel") {
224
+ fmt.Printf("\n")
225
+ fmt.Printf("Please file a bug report including a short program that triggers the error.\n")
226
+ fmt.Printf("https://go.dev/issue/new\n")
227
+ } else {
228
+ // Not a release; dump a stack trace, too.
229
+ fmt.Println()
230
+ os.Stdout.Write(debug.Stack())
231
+ fmt.Println()
232
+ }
233
+ }
234
+
235
+ hcrash()
236
+ ErrorExit()
237
+ }
238
+
239
+ // Assert reports "assertion failed" with Fatalf, unless b is true.
240
+ func Assert(b bool) {
241
+ if !b {
242
+ Fatalf("assertion failed")
243
+ }
244
+ }
245
+
246
+ // Assertf reports a fatal error with Fatalf, unless b is true.
247
+ func Assertf(b bool, format string, args ...any) {
248
+ if !b {
249
+ Fatalf(format, args...)
250
+ }
251
+ }
252
+
253
+ // AssertfAt reports a fatal error with FatalfAt, unless b is true.
254
+ func AssertfAt(b bool, pos src.XPos, format string, args ...any) {
255
+ if !b {
256
+ FatalfAt(pos, format, args...)
257
+ }
258
+ }
259
+
260
+ // hcrash crashes the compiler when -h is set, to find out where a message is generated.
261
+ func hcrash() {
262
+ if Flag.LowerH != 0 {
263
+ FlushErrors()
264
+ if Flag.LowerO != "" {
265
+ os.Remove(Flag.LowerO)
266
+ }
267
+ panic("-h")
268
+ }
269
+ }
270
+
271
+ // ErrorExit handles an error-status exit.
272
+ // It flushes any pending errors, removes the output file, and exits.
273
+ func ErrorExit() {
274
+ FlushErrors()
275
+ if Flag.LowerO != "" {
276
+ os.Remove(Flag.LowerO)
277
+ }
278
+ os.Exit(2)
279
+ }
280
+
281
+ // ExitIfErrors calls ErrorExit if any errors have been reported.
282
+ func ExitIfErrors() {
283
+ if Errors() > 0 {
284
+ ErrorExit()
285
+ }
286
+ }
287
+
288
+ var AutogeneratedPos src.XPos
go/src/cmd/compile/internal/base/startheap.go ADDED
@@ -0,0 +1,272 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2025 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 base
6
+
7
+ import (
8
+ "fmt"
9
+ "os"
10
+ "runtime"
11
+ "runtime/debug"
12
+ "runtime/metrics"
13
+ "sync"
14
+ )
15
+
16
+ // forEachGC calls fn each GC cycle until it returns false.
17
+ func forEachGC(fn func() bool) {
18
+ type T [32]byte // large enough to avoid runtime's tiny object allocator
19
+ var finalizer func(*T)
20
+ finalizer = func(p *T) {
21
+
22
+ if fn() {
23
+ runtime.SetFinalizer(p, finalizer)
24
+ }
25
+ }
26
+
27
+ finalizer(new(T))
28
+ }
29
+
30
+ // AdjustStartingHeap modifies GOGC so that GC should not occur until the heap
31
+ // grows to the requested size. This is intended but not promised, though it
32
+ // is true-mostly, depending on when the adjustment occurs and on the
33
+ // compiler's input and behavior. Once the live heap is approximately half
34
+ // this size, GOGC is reset to its value when AdjustStartingHeap was called;
35
+ // subsequent GCs may reduce the heap below the requested size, but this
36
+ // function does not affect that.
37
+ //
38
+ // logHeapTweaks (-d=gcadjust=1) enables logging of GOGC adjustment events.
39
+ //
40
+ // The temporarily requested GOGC is derated from what would be the "obvious"
41
+ // value necessary to hit the starting heap goal because the obvious
42
+ // (goal/live-1)*100 value seems to grow RSS a little more than it "should"
43
+ // (compared to GOMEMLIMIT, e.g.) and the assumption is that the GC's control
44
+ // algorithms are tuned for GOGC near 100, and not tuned for huge values of
45
+ // GOGC. Different derating factors apply for "lo" and "hi" values of GOGC;
46
+ // lo is below derateBreak, hi is above derateBreak. The derating factors,
47
+ // expressed as integer percentages, are derateLoPct and derateHiPct.
48
+ // 60-75 is an okay value for derateLoPct, 30-65 seems like a good value for
49
+ // derateHiPct, and 600 seems like a good value for derateBreak. If these
50
+ // are zero, defaults are used instead.
51
+ //
52
+ // NOTE: If you think this code would help startup time in your own
53
+ // application and you decide to use it, please benchmark first to see if it
54
+ // actually works for you (it may not: the Go compiler is not typical), and
55
+ // whatever the outcome, please leave a comment on bug #56546. This code
56
+ // uses supported interfaces, but depends more than we like on
57
+ // current+observed behavior of the garbage collector, so if many people need
58
+ // this feature, we should consider/propose a better way to accomplish it.
59
+ func AdjustStartingHeap(requestedHeapGoal, derateBreak, derateLoPct, derateHiPct uint64, logHeapTweaks bool) {
60
+ mp := runtime.GOMAXPROCS(0)
61
+
62
+ const (
63
+ SHgoal = "/gc/heap/goal:bytes"
64
+ SHcount = "/gc/cycles/total:gc-cycles"
65
+ SHallocs = "/gc/heap/allocs:bytes"
66
+ SHfrees = "/gc/heap/frees:bytes"
67
+ )
68
+
69
+ var sample = []metrics.Sample{{Name: SHgoal}, {Name: SHcount}, {Name: SHallocs}, {Name: SHfrees}}
70
+
71
+ const (
72
+ SH_GOAL = 0
73
+ SH_COUNT = 1
74
+ SH_ALLOCS = 2
75
+ SH_FREES = 3
76
+
77
+ MB = 1_000_000
78
+ )
79
+
80
+ // These particular magic numbers are designed to make the RSS footprint of -d=-gcstart=2000
81
+ // resemble that of GOMEMLIMIT=2000MiB GOGC=10000 when building large projects
82
+ // (e.g. the Go compiler itself, and the microsoft's typescript AST package),
83
+ // with the further restriction that these magic numbers did a good job of reducing user-cpu
84
+ // for builds at either gcstart=2000 or gcstart=128.
85
+ //
86
+ // The benchmarking to obtain this was (a version of):
87
+ //
88
+ // for i in {1..50} ; do
89
+ // for what in std cmd/compile cmd/fix cmd/go github.com/microsoft/typescript-go/internal/ast ; do
90
+ // whatbase=`basename ${what}`
91
+ // for sh in 128 2000 ; do
92
+ // for br in 500 600 ; do
93
+ // for shlo in 65 70; do
94
+ // for shhi in 55 60 ; do
95
+ // benchcmd -n=2 ${whatbase} go build -a \
96
+ // -gcflags=all=-d=gcstart=${sh},gcstartloderate=${shlo},gcstarthiderate=${shhi},gcstartbreak=${br} \
97
+ // ${what} | tee -a startheap${sh}_${br}_${shhi}_${shlo}.bench
98
+ // done
99
+ // done
100
+ // done
101
+ // done
102
+ // done
103
+ // done
104
+ //
105
+ // benchcmd is "go install github.com/aclements/go-misc/benchcmd@latest"
106
+
107
+ if derateBreak == 0 {
108
+ derateBreak = 600
109
+ }
110
+ if derateLoPct == 0 {
111
+ derateLoPct = 70
112
+ }
113
+ if derateHiPct == 0 {
114
+ derateHiPct = 55
115
+ }
116
+
117
+ gogcDerate := func(myGogc uint64) uint64 {
118
+ if myGogc < derateBreak {
119
+ return (myGogc * derateLoPct) / 100
120
+ }
121
+ return (myGogc * derateHiPct) / 100
122
+ }
123
+
124
+ // Assumptions and observations of Go's garbage collector, as of Go 1.17-1.20:
125
+
126
+ // - the initial heap goal is 4MiB, by fiat. It is possible for Go to start
127
+ // with a heap as small as 512k, so this may change in the future.
128
+
129
+ // - except for the first heap goal, heap goal is a function of
130
+ // observed-live at the previous GC and current GOGC. After the first
131
+ // GC, adjusting GOGC immediately updates GOGC; before the first GC,
132
+ // adjusting GOGC does not modify goal (but the change takes effect after
133
+ // the first GC).
134
+
135
+ // - the before/after first GC behavior is not guaranteed anywhere, it's
136
+ // just behavior, and it's a bad idea to rely on it.
137
+
138
+ // - we don't know exactly when GC will run, even after we adjust GOGC; the
139
+ // first GC may not have happened yet, may have already happened, or may
140
+ // be currently in progress, and GCs can start for several reasons.
141
+
142
+ // - forEachGC above will run the provided function at some delay after each
143
+ // GC's mark phase terminates; finalizers are run after marking as the
144
+ // spans containing finalizable objects are swept, driven by GC
145
+ // background activity and allocation demand.
146
+
147
+ // - "live at last GC" is not available through the current metrics
148
+ // interface. Instead, live is estimated by knowing the adjusted value of
149
+ // GOGC and the new heap goal following a GC (this requires knowing that
150
+ // at least one GC has occurred):
151
+ // estLive = 100 * newGoal / (100 + currentGogc)
152
+ // this new value of GOGC
153
+ // newGogc = 100*requestedHeapGoal/estLive - 100
154
+ // will result in the desired goal. The logging code checks that the
155
+ // resulting goal is correct.
156
+
157
+ // There's a small risk that the finalizer will be slow to run after a GC
158
+ // that expands the goal to a huge value, and that this will lead to
159
+ // out-of-memory. This doesn't seem to happen; in experiments on a variety
160
+ // of machines with a variety of extra loads to disrupt scheduling, the
161
+ // worst overshoot observed was 50% past requestedHeapGoal.
162
+
163
+ metrics.Read(sample)
164
+ for _, s := range sample {
165
+ if s.Value.Kind() == metrics.KindBad {
166
+ // Just return, a slightly slower compilation is a tolerable outcome.
167
+ if logHeapTweaks {
168
+ fmt.Fprintf(os.Stderr, "GCAdjust: Regret unexpected KindBad for metric %s\n", s.Name)
169
+ }
170
+ return
171
+ }
172
+ }
173
+
174
+ // Tinker with GOGC to make the heap grow rapidly at first.
175
+ currentGoal := sample[SH_GOAL].Value.Uint64() // Believe this will be 4MByte or less, perhaps 512k
176
+ myGogc := 100 * requestedHeapGoal / currentGoal
177
+ myGogc = gogcDerate(myGogc)
178
+ if myGogc <= 125 {
179
+ return
180
+ }
181
+
182
+ if logHeapTweaks {
183
+ sample := append([]metrics.Sample(nil), sample...) // avoid races with GC callback
184
+ AtExit(func() {
185
+ metrics.Read(sample)
186
+ goal := sample[SH_GOAL].Value.Uint64()
187
+ count := sample[SH_COUNT].Value.Uint64()
188
+ oldGogc := debug.SetGCPercent(100)
189
+ if oldGogc == 100 {
190
+ fmt.Fprintf(os.Stderr, "GCAdjust: AtExit goal %dMB gogc %d count %d maxprocs %d\n",
191
+ goal/MB, oldGogc, count, mp)
192
+ } else {
193
+ inUse := sample[SH_ALLOCS].Value.Uint64() - sample[SH_FREES].Value.Uint64()
194
+ overPct := 100 * (int(inUse) - int(requestedHeapGoal)) / int(requestedHeapGoal)
195
+ fmt.Fprintf(os.Stderr, "GCAdjust: AtExit goal %dMB gogc %d count %d maxprocs %d overPct %d\n",
196
+ goal/MB, oldGogc, count, mp, overPct)
197
+
198
+ }
199
+ })
200
+ }
201
+
202
+ originalGOGC := debug.SetGCPercent(int(myGogc))
203
+
204
+ // forEachGC finalizers ought not overlap, but they could run in separate threads.
205
+ // This ought not matter, but just in case it bothers the/a race detector,
206
+ // use this mutex.
207
+ var forEachGCLock sync.Mutex
208
+
209
+ adjustFunc := func() bool {
210
+
211
+ forEachGCLock.Lock()
212
+ defer forEachGCLock.Unlock()
213
+
214
+ metrics.Read(sample)
215
+ goal := sample[SH_GOAL].Value.Uint64()
216
+ count := sample[SH_COUNT].Value.Uint64()
217
+
218
+ if goal <= requestedHeapGoal { // Stay the course
219
+ if logHeapTweaks {
220
+ fmt.Fprintf(os.Stderr, "GCAdjust: Reuse GOGC adjust, current goal %dMB, count is %d, current gogc %d\n",
221
+ goal/MB, count, myGogc)
222
+ }
223
+ return true
224
+ }
225
+
226
+ // Believe goal has been adjusted upwards, else it would be less-than-or-equal to requestedHeapGoal
227
+ calcLive := 100 * goal / (100 + myGogc)
228
+
229
+ if 2*calcLive < requestedHeapGoal { // calcLive can exceed requestedHeapGoal!
230
+ myGogc = 100*requestedHeapGoal/calcLive - 100
231
+ myGogc = gogcDerate(myGogc)
232
+
233
+ if myGogc > 125 {
234
+ // Not done growing the heap.
235
+ oldGogc := debug.SetGCPercent(int(myGogc))
236
+
237
+ if logHeapTweaks {
238
+ // Check that the new goal looks right
239
+ inUse := sample[SH_ALLOCS].Value.Uint64() - sample[SH_FREES].Value.Uint64()
240
+ metrics.Read(sample)
241
+ newGoal := sample[SH_GOAL].Value.Uint64()
242
+ pctOff := 100 * (int64(newGoal) - int64(requestedHeapGoal)) / int64(requestedHeapGoal)
243
+ // Check that the new goal is close to requested. 3% of make.bash fails this test. Why, TBD.
244
+ if pctOff < 2 {
245
+ fmt.Fprintf(os.Stderr, "GCAdjust: Retry GOGC adjust, current goal %dMB, count is %d, gogc was %d, is now %d, calcLive %dMB pctOff %d\n",
246
+ goal/MB, count, oldGogc, myGogc, calcLive/MB, pctOff)
247
+ } else {
248
+ // The GC is being annoying and not giving us the goal that we requested, say more to help understand when/why.
249
+ fmt.Fprintf(os.Stderr, "GCAdjust: Retry GOGC adjust, current goal %dMB, count is %d, gogc was %d, is now %d, calcLive %dMB pctOff %d inUse %dMB\n",
250
+ goal/MB, count, oldGogc, myGogc, calcLive/MB, pctOff, inUse/MB)
251
+ }
252
+ }
253
+ return true
254
+ }
255
+ }
256
+
257
+ // In this case we're done boosting GOGC, set it to its original value and don't set a new finalizer.
258
+ oldGogc := debug.SetGCPercent(originalGOGC)
259
+ // inUse helps estimate how late the finalizer ran; at the instant the previous GC ended,
260
+ // it was (in theory) equal to the previous GC's heap goal. In a growing heap it is
261
+ // expected to grow to the new heap goal.
262
+ if logHeapTweaks {
263
+ inUse := sample[SH_ALLOCS].Value.Uint64() - sample[SH_FREES].Value.Uint64()
264
+ overPct := 100 * (int(inUse) - int(requestedHeapGoal)) / int(requestedHeapGoal)
265
+ fmt.Fprintf(os.Stderr, "GCAdjust: Reset GOGC adjust, old goal %dMB, count is %d, gogc was %d, gogc is now %d, calcLive %dMB inUse %dMB overPct %d\n",
266
+ goal/MB, count, oldGogc, originalGOGC, calcLive/MB, inUse/MB, overPct)
267
+ }
268
+ return false
269
+ }
270
+
271
+ forEachGC(adjustFunc)
272
+ }
go/src/cmd/compile/internal/base/timings.go ADDED
@@ -0,0 +1,237 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2016 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 base
6
+
7
+ import (
8
+ "fmt"
9
+ "io"
10
+ "strings"
11
+ "time"
12
+ )
13
+
14
+ var Timer Timings
15
+
16
+ // Timings collects the execution times of labeled phases
17
+ // which are added through a sequence of Start/Stop calls.
18
+ // Events may be associated with each phase via AddEvent.
19
+ type Timings struct {
20
+ list []timestamp
21
+ events map[int][]*event // lazily allocated
22
+ }
23
+
24
+ type timestamp struct {
25
+ time time.Time
26
+ label string
27
+ start bool
28
+ }
29
+
30
+ type event struct {
31
+ size int64 // count or amount of data processed (allocations, data size, lines, funcs, ...)
32
+ unit string // unit of size measure (count, MB, lines, funcs, ...)
33
+ }
34
+
35
+ func (t *Timings) append(labels []string, start bool) {
36
+ t.list = append(t.list, timestamp{time.Now(), strings.Join(labels, ":"), start})
37
+ }
38
+
39
+ // Start marks the beginning of a new phase and implicitly stops the previous phase.
40
+ // The phase name is the colon-separated concatenation of the labels.
41
+ func (t *Timings) Start(labels ...string) {
42
+ t.append(labels, true)
43
+ }
44
+
45
+ // Stop marks the end of a phase and implicitly starts a new phase.
46
+ // The labels are added to the labels of the ended phase.
47
+ func (t *Timings) Stop(labels ...string) {
48
+ t.append(labels, false)
49
+ }
50
+
51
+ // AddEvent associates an event, i.e., a count, or an amount of data,
52
+ // with the most recently started or stopped phase; or the very first
53
+ // phase if Start or Stop hasn't been called yet. The unit specifies
54
+ // the unit of measurement (e.g., MB, lines, no. of funcs, etc.).
55
+ func (t *Timings) AddEvent(size int64, unit string) {
56
+ m := t.events
57
+ if m == nil {
58
+ m = make(map[int][]*event)
59
+ t.events = m
60
+ }
61
+ i := len(t.list)
62
+ if i > 0 {
63
+ i--
64
+ }
65
+ m[i] = append(m[i], &event{size, unit})
66
+ }
67
+
68
+ // Write prints the phase times to w.
69
+ // The prefix is printed at the start of each line.
70
+ func (t *Timings) Write(w io.Writer, prefix string) {
71
+ if len(t.list) > 0 {
72
+ var lines lines
73
+
74
+ // group of phases with shared non-empty label prefix
75
+ var group struct {
76
+ label string // label prefix
77
+ tot time.Duration // accumulated phase time
78
+ size int // number of phases collected in group
79
+ }
80
+
81
+ // accumulated time between Stop/Start timestamps
82
+ var unaccounted time.Duration
83
+
84
+ // process Start/Stop timestamps
85
+ pt := &t.list[0] // previous timestamp
86
+ tot := t.list[len(t.list)-1].time.Sub(pt.time)
87
+ for i := 1; i < len(t.list); i++ {
88
+ qt := &t.list[i] // current timestamp
89
+ dt := qt.time.Sub(pt.time)
90
+
91
+ var label string
92
+ var events []*event
93
+ if pt.start {
94
+ // previous phase started
95
+ label = pt.label
96
+ events = t.events[i-1]
97
+ if qt.start {
98
+ // start implicitly ended previous phase; nothing to do
99
+ } else {
100
+ // stop ended previous phase; append stop labels, if any
101
+ if qt.label != "" {
102
+ label += ":" + qt.label
103
+ }
104
+ // events associated with stop replace prior events
105
+ if e := t.events[i]; e != nil {
106
+ events = e
107
+ }
108
+ }
109
+ } else {
110
+ // previous phase stopped
111
+ if qt.start {
112
+ // between a stopped and started phase; unaccounted time
113
+ unaccounted += dt
114
+ } else {
115
+ // previous stop implicitly started current phase
116
+ label = qt.label
117
+ events = t.events[i]
118
+ }
119
+ }
120
+ if label != "" {
121
+ // add phase to existing group, or start a new group
122
+ l := commonPrefix(group.label, label)
123
+ if group.size == 1 && l != "" || group.size > 1 && l == group.label {
124
+ // add to existing group
125
+ group.label = l
126
+ group.tot += dt
127
+ group.size++
128
+ } else {
129
+ // start a new group
130
+ if group.size > 1 {
131
+ lines.add(prefix+group.label+"subtotal", 1, group.tot, tot, nil)
132
+ }
133
+ group.label = label
134
+ group.tot = dt
135
+ group.size = 1
136
+ }
137
+
138
+ // write phase
139
+ lines.add(prefix+label, 1, dt, tot, events)
140
+ }
141
+
142
+ pt = qt
143
+ }
144
+
145
+ if group.size > 1 {
146
+ lines.add(prefix+group.label+"subtotal", 1, group.tot, tot, nil)
147
+ }
148
+
149
+ if unaccounted != 0 {
150
+ lines.add(prefix+"unaccounted", 1, unaccounted, tot, nil)
151
+ }
152
+
153
+ lines.add(prefix+"total", 1, tot, tot, nil)
154
+
155
+ lines.write(w)
156
+ }
157
+ }
158
+
159
+ func commonPrefix(a, b string) string {
160
+ i := 0
161
+ for i < len(a) && i < len(b) && a[i] == b[i] {
162
+ i++
163
+ }
164
+ return a[:i]
165
+ }
166
+
167
+ type lines [][]string
168
+
169
+ func (lines *lines) add(label string, n int, dt, tot time.Duration, events []*event) {
170
+ var line []string
171
+ add := func(format string, args ...any) {
172
+ line = append(line, fmt.Sprintf(format, args...))
173
+ }
174
+
175
+ add("%s", label)
176
+ add(" %d", n)
177
+ add(" %d ns/op", dt)
178
+ add(" %.2f %%", float64(dt)/float64(tot)*100)
179
+
180
+ for _, e := range events {
181
+ add(" %d", e.size)
182
+ add(" %s", e.unit)
183
+ add(" %d", int64(float64(e.size)/dt.Seconds()+0.5))
184
+ add(" %s/s", e.unit)
185
+ }
186
+
187
+ *lines = append(*lines, line)
188
+ }
189
+
190
+ func (lines lines) write(w io.Writer) {
191
+ // determine column widths and contents
192
+ var widths []int
193
+ var number []bool
194
+ for _, line := range lines {
195
+ for i, col := range line {
196
+ if i < len(widths) {
197
+ if len(col) > widths[i] {
198
+ widths[i] = len(col)
199
+ }
200
+ } else {
201
+ widths = append(widths, len(col))
202
+ number = append(number, isnumber(col)) // first line determines column contents
203
+ }
204
+ }
205
+ }
206
+
207
+ // make column widths a multiple of align for more stable output
208
+ const align = 1 // set to a value > 1 to enable
209
+ if align > 1 {
210
+ for i, w := range widths {
211
+ w += align - 1
212
+ widths[i] = w - w%align
213
+ }
214
+ }
215
+
216
+ // print lines taking column widths and contents into account
217
+ for _, line := range lines {
218
+ for i, col := range line {
219
+ format := "%-*s"
220
+ if number[i] {
221
+ format = "%*s" // numbers are right-aligned
222
+ }
223
+ fmt.Fprintf(w, format, widths[i], col)
224
+ }
225
+ fmt.Fprintln(w)
226
+ }
227
+ }
228
+
229
+ func isnumber(s string) bool {
230
+ for _, ch := range s {
231
+ if ch <= ' ' {
232
+ continue // ignore leading whitespace
233
+ }
234
+ return '0' <= ch && ch <= '9' || ch == '.' || ch == '-' || ch == '+'
235
+ }
236
+ return false
237
+ }
go/src/cmd/compile/internal/bitvec/bv.go ADDED
@@ -0,0 +1,200 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2013 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 bitvec
6
+
7
+ import (
8
+ "math/bits"
9
+
10
+ "cmd/compile/internal/base"
11
+ "cmd/internal/src"
12
+ )
13
+
14
+ const (
15
+ wordBits = 32
16
+ wordMask = wordBits - 1
17
+ wordShift = 5
18
+ )
19
+
20
+ // A BitVec is a bit vector.
21
+ type BitVec struct {
22
+ N int32 // number of bits in vector
23
+ B []uint32 // words holding bits
24
+ }
25
+
26
+ func New(n int32) BitVec {
27
+ nword := (n + wordBits - 1) / wordBits
28
+ return BitVec{n, make([]uint32, nword)}
29
+ }
30
+
31
+ type Bulk struct {
32
+ words []uint32
33
+ nbit int32
34
+ nword int32
35
+ }
36
+
37
+ func NewBulk(nbit int32, count int32, pos src.XPos) Bulk {
38
+ nword := (nbit + wordBits - 1) / wordBits
39
+ size := int64(nword) * int64(count)
40
+ if int64(int32(size*4)) != size*4 {
41
+ base.FatalfAt(pos, "NewBulk too big: nbit=%d count=%d nword=%d size=%d", nbit, count, nword, size)
42
+ }
43
+ return Bulk{
44
+ words: make([]uint32, size),
45
+ nbit: nbit,
46
+ nword: nword,
47
+ }
48
+ }
49
+
50
+ func (b *Bulk) Next() BitVec {
51
+ out := BitVec{b.nbit, b.words[:b.nword]}
52
+ b.words = b.words[b.nword:]
53
+ return out
54
+ }
55
+
56
+ func (bv1 BitVec) Eq(bv2 BitVec) bool {
57
+ if bv1.N != bv2.N {
58
+ base.Fatalf("bvequal: lengths %d and %d are not equal", bv1.N, bv2.N)
59
+ }
60
+ for i, x := range bv1.B {
61
+ if x != bv2.B[i] {
62
+ return false
63
+ }
64
+ }
65
+ return true
66
+ }
67
+
68
+ func (dst BitVec) Copy(src BitVec) {
69
+ copy(dst.B, src.B)
70
+ }
71
+
72
+ func (bv BitVec) Get(i int32) bool {
73
+ if i < 0 || i >= bv.N {
74
+ base.Fatalf("bvget: index %d is out of bounds with length %d\n", i, bv.N)
75
+ }
76
+ mask := uint32(1 << uint(i%wordBits))
77
+ return bv.B[i>>wordShift]&mask != 0
78
+ }
79
+
80
+ func (bv BitVec) Set(i int32) {
81
+ if i < 0 || i >= bv.N {
82
+ base.Fatalf("bvset: index %d is out of bounds with length %d\n", i, bv.N)
83
+ }
84
+ mask := uint32(1 << uint(i%wordBits))
85
+ bv.B[i/wordBits] |= mask
86
+ }
87
+
88
+ func (bv BitVec) Unset(i int32) {
89
+ if i < 0 || i >= bv.N {
90
+ base.Fatalf("bvunset: index %d is out of bounds with length %d\n", i, bv.N)
91
+ }
92
+ mask := uint32(1 << uint(i%wordBits))
93
+ bv.B[i/wordBits] &^= mask
94
+ }
95
+
96
+ // Next returns the smallest index >= i for which bvget(bv, i) == 1.
97
+ // If there is no such index, bvnext returns -1.
98
+ func (bv BitVec) Next(i int32) int32 {
99
+ if i >= bv.N {
100
+ return -1
101
+ }
102
+
103
+ // Jump i ahead to next word with bits.
104
+ if bv.B[i>>wordShift]>>uint(i&wordMask) == 0 {
105
+ i &^= wordMask
106
+ i += wordBits
107
+ for i < bv.N && bv.B[i>>wordShift] == 0 {
108
+ i += wordBits
109
+ }
110
+ }
111
+
112
+ if i >= bv.N {
113
+ return -1
114
+ }
115
+
116
+ // Find 1 bit.
117
+ w := bv.B[i>>wordShift] >> uint(i&wordMask)
118
+ i += int32(bits.TrailingZeros32(w))
119
+
120
+ return i
121
+ }
122
+
123
+ func (bv BitVec) IsEmpty() bool {
124
+ for _, x := range bv.B {
125
+ if x != 0 {
126
+ return false
127
+ }
128
+ }
129
+ return true
130
+ }
131
+
132
+ func (bv BitVec) Count() int {
133
+ n := 0
134
+ for _, x := range bv.B {
135
+ n += bits.OnesCount32(x)
136
+ }
137
+ return n
138
+ }
139
+
140
+ func (bv BitVec) Not() {
141
+ for i, x := range bv.B {
142
+ bv.B[i] = ^x
143
+ }
144
+ if bv.N%wordBits != 0 {
145
+ bv.B[len(bv.B)-1] &= 1<<uint(bv.N%wordBits) - 1 // clear bits past N in the last word
146
+ }
147
+ }
148
+
149
+ // union
150
+ func (dst BitVec) Or(src1, src2 BitVec) {
151
+ if len(src1.B) == 0 {
152
+ return
153
+ }
154
+ _, _ = dst.B[len(src1.B)-1], src2.B[len(src1.B)-1] // hoist bounds checks out of the loop
155
+
156
+ for i, x := range src1.B {
157
+ dst.B[i] = x | src2.B[i]
158
+ }
159
+ }
160
+
161
+ // intersection
162
+ func (dst BitVec) And(src1, src2 BitVec) {
163
+ if len(src1.B) == 0 {
164
+ return
165
+ }
166
+ _, _ = dst.B[len(src1.B)-1], src2.B[len(src1.B)-1] // hoist bounds checks out of the loop
167
+
168
+ for i, x := range src1.B {
169
+ dst.B[i] = x & src2.B[i]
170
+ }
171
+ }
172
+
173
+ // difference
174
+ func (dst BitVec) AndNot(src1, src2 BitVec) {
175
+ if len(src1.B) == 0 {
176
+ return
177
+ }
178
+ _, _ = dst.B[len(src1.B)-1], src2.B[len(src1.B)-1] // hoist bounds checks out of the loop
179
+
180
+ for i, x := range src1.B {
181
+ dst.B[i] = x &^ src2.B[i]
182
+ }
183
+ }
184
+
185
+ func (bv BitVec) String() string {
186
+ s := make([]byte, 2+bv.N)
187
+ copy(s, "#*")
188
+ for i := int32(0); i < bv.N; i++ {
189
+ ch := byte('0')
190
+ if bv.Get(i) {
191
+ ch = '1'
192
+ }
193
+ s[2+i] = ch
194
+ }
195
+ return string(s)
196
+ }
197
+
198
+ func (bv BitVec) Clear() {
199
+ clear(bv.B)
200
+ }
go/src/cmd/compile/internal/bloop/bloop.go ADDED
@@ -0,0 +1,402 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2025 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 bloop
6
+
7
+ // This file contains support routines for keeping
8
+ // statements alive
9
+ // in such loops (example):
10
+ //
11
+ // for b.Loop() {
12
+ // var a, b int
13
+ // a = 5
14
+ // b = 6
15
+ // f(a, b)
16
+ // }
17
+ //
18
+ // The results of a, b and f(a, b) will be kept alive.
19
+ //
20
+ // Formally, the lhs (if they are [ir.Name]-s) of
21
+ // [ir.AssignStmt], [ir.AssignListStmt],
22
+ // [ir.AssignOpStmt], and the results of [ir.CallExpr]
23
+ // or its args if it doesn't return a value will be kept
24
+ // alive.
25
+ //
26
+ // The keep alive logic is implemented with as wrapping a
27
+ // runtime.KeepAlive around the Name.
28
+ //
29
+ // TODO: currently this is implemented with KeepAlive
30
+ // because it will prevent DSE and DCE which is probably
31
+ // what we want right now. And KeepAlive takes an ssa
32
+ // value instead of a symbol, which is easier to manage.
33
+ // But since KeepAlive's context was mainly in the runtime
34
+ // and GC, should we implement a new intrinsic that lowers
35
+ // to OpVarLive? Peeling out the symbols is a bit tricky
36
+ // and also VarLive seems to assume that there exists a
37
+ // VarDef on the same symbol that dominates it.
38
+
39
+ import (
40
+ "cmd/compile/internal/base"
41
+ "cmd/compile/internal/ir"
42
+ "cmd/compile/internal/reflectdata"
43
+ "cmd/compile/internal/typecheck"
44
+ "cmd/compile/internal/types"
45
+ "cmd/internal/src"
46
+ )
47
+
48
+ // getNameFromNode tries to iteratively peel down the node to
49
+ // get the name.
50
+ func getNameFromNode(n ir.Node) *ir.Name {
51
+ // Tries to iteratively peel down the node to get the names.
52
+ for n != nil {
53
+ switch n.Op() {
54
+ case ir.ONAME:
55
+ // Found the name, stop the loop.
56
+ return n.(*ir.Name)
57
+ case ir.OSLICE, ir.OSLICE3:
58
+ n = n.(*ir.SliceExpr).X
59
+ case ir.ODOT:
60
+ n = n.(*ir.SelectorExpr).X
61
+ case ir.OCONV, ir.OCONVIFACE, ir.OCONVNOP:
62
+ n = n.(*ir.ConvExpr).X
63
+ case ir.OADDR:
64
+ n = n.(*ir.AddrExpr).X
65
+ case ir.ODOTPTR:
66
+ n = n.(*ir.SelectorExpr).X
67
+ case ir.OINDEX, ir.OINDEXMAP:
68
+ n = n.(*ir.IndexExpr).X
69
+ default:
70
+ n = nil
71
+ }
72
+ }
73
+ return nil
74
+ }
75
+
76
+ // getAddressableNameFromNode is like getNameFromNode but returns nil if the node is not addressable.
77
+ func getAddressableNameFromNode(n ir.Node) *ir.Name {
78
+ if name := getNameFromNode(n); name != nil && ir.IsAddressable(name) {
79
+ return name
80
+ }
81
+ return nil
82
+ }
83
+
84
+ // keepAliveAt returns a statement that is either curNode, or a
85
+ // block containing curNode followed by a call to runtime.KeepAlive for each
86
+ // node in ns. These calls ensure that nodes in ns will be live until
87
+ // after curNode's execution.
88
+ func keepAliveAt(ns []ir.Node, curNode ir.Node) ir.Node {
89
+ if len(ns) == 0 {
90
+ return curNode
91
+ }
92
+
93
+ pos := curNode.Pos()
94
+ calls := []ir.Node{curNode}
95
+ for _, n := range ns {
96
+ if n == nil {
97
+ continue
98
+ }
99
+ if n.Sym() == nil {
100
+ continue
101
+ }
102
+ if n.Sym().IsBlank() {
103
+ continue
104
+ }
105
+ if !ir.IsAddressable(n) {
106
+ base.FatalfAt(n.Pos(), "keepAliveAt: node %v is not addressable", n)
107
+ }
108
+ arg := ir.NewConvExpr(pos, ir.OCONV, types.Types[types.TUNSAFEPTR], typecheck.NodAddr(n))
109
+ if !n.Type().IsInterface() {
110
+ srcRType0 := reflectdata.TypePtrAt(pos, n.Type())
111
+ arg.TypeWord = srcRType0
112
+ arg.SrcRType = srcRType0
113
+ }
114
+ callExpr := typecheck.Call(pos,
115
+ typecheck.LookupRuntime("KeepAlive"),
116
+ []ir.Node{arg}, false).(*ir.CallExpr)
117
+ callExpr.IsCompilerVarLive = true
118
+ callExpr.NoInline = true
119
+ calls = append(calls, callExpr)
120
+ }
121
+
122
+ return ir.NewBlockStmt(pos, calls)
123
+ }
124
+
125
+ func debugName(name *ir.Name, pos src.XPos) {
126
+ if base.Flag.LowerM > 1 {
127
+ if name.Linksym() != nil {
128
+ base.WarnfAt(pos, "%s will be kept alive", name.Linksym().Name)
129
+ } else {
130
+ base.WarnfAt(pos, "expr will be kept alive")
131
+ }
132
+ }
133
+ }
134
+
135
+ // preserveStmt transforms stmt so that any names defined/assigned within it
136
+ // are used after stmt's execution, preventing their dead code elimination
137
+ // and dead store elimination. The return value is the transformed statement.
138
+ func preserveStmt(curFn *ir.Func, stmt ir.Node) (ret ir.Node) {
139
+ ret = stmt
140
+ switch n := stmt.(type) {
141
+ case *ir.AssignStmt:
142
+ // If the left hand side is blank, we need to assign it to a temp
143
+ // so that it can be kept alive.
144
+ if ir.IsBlank(n.X) {
145
+ tmp := typecheck.TempAt(n.Pos(), curFn, n.Y.Type())
146
+ n.X = tmp
147
+ n.Def = true
148
+ n.PtrInit().Append(typecheck.Stmt(ir.NewDecl(n.Pos(), ir.ODCL, tmp)))
149
+ stmt = typecheck.AssignExpr(n)
150
+ n = stmt.(*ir.AssignStmt)
151
+ }
152
+ // Peel down struct and slice indexing to get the names
153
+ name := getAddressableNameFromNode(n.X)
154
+ if name != nil {
155
+ debugName(name, n.Pos())
156
+ ret = keepAliveAt([]ir.Node{name}, n)
157
+ } else if deref, ok := n.X.(*ir.StarExpr); ok && deref != nil {
158
+ ret = keepAliveAt([]ir.Node{deref}, n)
159
+ if base.Flag.LowerM > 1 {
160
+ base.WarnfAt(n.Pos(), "dereference will be kept alive")
161
+ }
162
+ } else if base.Flag.LowerM > 1 {
163
+ base.WarnfAt(n.Pos(), "expr is unknown to bloop pass")
164
+ }
165
+ case *ir.AssignListStmt:
166
+ ns := []ir.Node{}
167
+ hasBlank := false
168
+ for i, lhs := range n.Lhs {
169
+ if ir.IsBlank(lhs) {
170
+ // If the left hand side has blanks, we need to assign them to temps
171
+ // so that they can be kept alive.
172
+ var typ *types.Type
173
+ // AssignListStmt can have tuple or a list of expressions on the right hand side.
174
+ if len(n.Rhs) == 1 && n.Rhs[0].Type() != nil &&
175
+ n.Rhs[0].Type().IsTuple() &&
176
+ len(n.Lhs) == n.Rhs[0].Type().NumFields() {
177
+ typ = n.Rhs[0].Type().Field(i).Type
178
+ } else if len(n.Rhs) == len(n.Lhs) {
179
+ typ = n.Rhs[i].Type()
180
+ } else {
181
+ // Unrecognized shapes, skip?
182
+ base.WarnfAt(n.Pos(), "unrecognized shape for assign list stmt for blank assignment")
183
+ continue
184
+ }
185
+ tmp := typecheck.TempAt(n.Pos(), curFn, typ)
186
+ n.Lhs[i] = tmp
187
+ n.PtrInit().Append(typecheck.Stmt(ir.NewDecl(n.Pos(), ir.ODCL, tmp)))
188
+ hasBlank = true
189
+ lhs = tmp
190
+ }
191
+ name := getAddressableNameFromNode(lhs)
192
+ if name != nil {
193
+ debugName(name, n.Pos())
194
+ ns = append(ns, name)
195
+ } else if deref, ok := lhs.(*ir.StarExpr); ok && deref != nil {
196
+ ns = append(ns, deref)
197
+ if base.Flag.LowerM > 1 {
198
+ base.WarnfAt(n.Pos(), "dereference will be kept alive")
199
+ }
200
+ } else if base.Flag.LowerM > 1 {
201
+ base.WarnfAt(n.Pos(), "expr is unknown to bloop pass")
202
+ }
203
+ }
204
+ if hasBlank {
205
+ // blank nodes are rewritten to temps, we need to typecheck the node again.
206
+ n.Def = true
207
+ stmt = typecheck.AssignExpr(n)
208
+ n = stmt.(*ir.AssignListStmt)
209
+ }
210
+ ret = keepAliveAt(ns, n)
211
+ case *ir.AssignOpStmt:
212
+ name := getAddressableNameFromNode(n.X)
213
+ if name != nil {
214
+ debugName(name, n.Pos())
215
+ ret = keepAliveAt([]ir.Node{name}, n)
216
+ } else if deref, ok := n.X.(*ir.StarExpr); ok && deref != nil {
217
+ ret = keepAliveAt([]ir.Node{deref}, n)
218
+ if base.Flag.LowerM > 1 {
219
+ base.WarnfAt(n.Pos(), "dereference will be kept alive")
220
+ }
221
+ } else if base.Flag.LowerM > 1 {
222
+ base.WarnfAt(n.Pos(), "expr is unknown to bloop pass")
223
+ }
224
+ case *ir.CallExpr:
225
+ curNode := stmt
226
+ if n.Fun != nil && n.Fun.Type() != nil && n.Fun.Type().NumResults() != 0 {
227
+ ns := []ir.Node{}
228
+ // This function's results are not assigned, assign them to
229
+ // auto tmps and then keepAliveAt these autos.
230
+ // Note: markStmt assumes the context that it's called - this CallExpr is
231
+ // not within another OAS2, which is guaranteed by the case above.
232
+ results := n.Fun.Type().Results()
233
+ lhs := make([]ir.Node, len(results))
234
+ for i, res := range results {
235
+ tmp := typecheck.TempAt(n.Pos(), curFn, res.Type)
236
+ lhs[i] = tmp
237
+ ns = append(ns, tmp)
238
+ }
239
+
240
+ // Create an assignment statement.
241
+ assign := typecheck.AssignExpr(
242
+ ir.NewAssignListStmt(n.Pos(), ir.OAS2, lhs,
243
+ []ir.Node{n})).(*ir.AssignListStmt)
244
+ assign.Def = true
245
+ for _, tmp := range lhs {
246
+ // Place temp declarations in the loop body to help escape analysis.
247
+ assign.PtrInit().Append(typecheck.Stmt(ir.NewDecl(assign.Pos(), ir.ODCL, tmp.(*ir.Name))))
248
+ }
249
+ curNode = assign
250
+ plural := ""
251
+ if len(results) > 1 {
252
+ plural = "s"
253
+ }
254
+ if base.Flag.LowerM > 1 {
255
+ base.WarnfAt(n.Pos(), "function result%s will be kept alive", plural)
256
+ }
257
+ ret = keepAliveAt(ns, curNode)
258
+ } else {
259
+ // This function probably doesn't return anything, keep its args alive.
260
+ argTmps := []ir.Node{}
261
+ names := []ir.Node{}
262
+ for i, a := range n.Args {
263
+ if name := getAddressableNameFromNode(a); name != nil {
264
+ // If they are name, keep them alive directly.
265
+ debugName(name, n.Pos())
266
+ names = append(names, name)
267
+ } else if a.Op() == ir.OSLICELIT {
268
+ // variadic args are encoded as slice literal.
269
+ s := a.(*ir.CompLitExpr)
270
+ ns := []ir.Node{}
271
+ for i, elem := range s.List {
272
+ if name := getAddressableNameFromNode(elem); name != nil {
273
+ debugName(name, n.Pos())
274
+ ns = append(ns, name)
275
+ } else {
276
+ // We need a temporary to save this arg.
277
+ tmp := typecheck.TempAt(elem.Pos(), curFn, elem.Type())
278
+ assign := ir.NewAssignStmt(elem.Pos(), tmp, elem)
279
+ assign.Def = true
280
+ // Place temp declarations in the loop body to help escape analysis.
281
+ assign.PtrInit().Append(typecheck.Stmt(ir.NewDecl(assign.Pos(), ir.ODCL, tmp)))
282
+ argTmps = append(argTmps, typecheck.AssignExpr(assign))
283
+ names = append(names, tmp)
284
+ s.List[i] = tmp
285
+ if base.Flag.LowerM > 1 {
286
+ base.WarnfAt(n.Pos(), "function arg will be kept alive")
287
+ }
288
+ }
289
+ }
290
+ names = append(names, ns...)
291
+ } else {
292
+ // expressions, we need to assign them to temps and change the original arg to reference
293
+ // them.
294
+ tmp := typecheck.TempAt(n.Pos(), curFn, a.Type())
295
+ assign := ir.NewAssignStmt(n.Pos(), tmp, a)
296
+ assign.Def = true
297
+ // Place temp declarations in the loop body to help escape analysis.
298
+ assign.PtrInit().Append(typecheck.Stmt(ir.NewDecl(assign.Pos(), ir.ODCL, tmp)))
299
+ argTmps = append(argTmps, typecheck.AssignExpr(assign))
300
+ names = append(names, tmp)
301
+ n.Args[i] = tmp
302
+ if base.Flag.LowerM > 1 {
303
+ base.WarnfAt(n.Pos(), "function arg will be kept alive")
304
+ }
305
+ }
306
+ }
307
+ if len(argTmps) > 0 {
308
+ argTmps = append(argTmps, n)
309
+ curNode = ir.NewBlockStmt(n.Pos(), argTmps)
310
+ }
311
+ ret = keepAliveAt(names, curNode)
312
+ }
313
+ }
314
+ return
315
+ }
316
+
317
+ func preserveStmts(curFn *ir.Func, list ir.Nodes) {
318
+ for i := range list {
319
+ list[i] = preserveStmt(curFn, list[i])
320
+ }
321
+ }
322
+
323
+ // isTestingBLoop returns true if it matches the node as a
324
+ // testing.(*B).Loop. See issue #61515.
325
+ func isTestingBLoop(t ir.Node) bool {
326
+ if t.Op() != ir.OFOR {
327
+ return false
328
+ }
329
+ nFor, ok := t.(*ir.ForStmt)
330
+ if !ok || nFor.Cond == nil || nFor.Cond.Op() != ir.OCALLFUNC {
331
+ return false
332
+ }
333
+ n, ok := nFor.Cond.(*ir.CallExpr)
334
+ if !ok || n.Fun == nil || n.Fun.Op() != ir.OMETHEXPR {
335
+ return false
336
+ }
337
+ name := ir.MethodExprName(n.Fun)
338
+ if name == nil {
339
+ return false
340
+ }
341
+ if fSym := name.Sym(); fSym != nil && name.Class == ir.PFUNC && fSym.Pkg != nil &&
342
+ fSym.Name == "(*B).Loop" && fSym.Pkg.Path == "testing" {
343
+ // Attempting to match a function call to testing.(*B).Loop
344
+ return true
345
+ }
346
+ return false
347
+ }
348
+
349
+ type editor struct {
350
+ inBloop bool
351
+ curFn *ir.Func
352
+ }
353
+
354
+ func (e editor) edit(n ir.Node) ir.Node {
355
+ e.inBloop = isTestingBLoop(n) || e.inBloop
356
+ // It's in bloop, mark the stmts with bodies.
357
+ ir.EditChildren(n, e.edit)
358
+ if e.inBloop {
359
+ switch n := n.(type) {
360
+ case *ir.ForStmt:
361
+ preserveStmts(e.curFn, n.Body)
362
+ case *ir.IfStmt:
363
+ preserveStmts(e.curFn, n.Body)
364
+ preserveStmts(e.curFn, n.Else)
365
+ case *ir.BlockStmt:
366
+ preserveStmts(e.curFn, n.List)
367
+ case *ir.CaseClause:
368
+ preserveStmts(e.curFn, n.List)
369
+ preserveStmts(e.curFn, n.Body)
370
+ case *ir.CommClause:
371
+ preserveStmts(e.curFn, n.Body)
372
+ case *ir.RangeStmt:
373
+ preserveStmts(e.curFn, n.Body)
374
+ }
375
+ }
376
+ return n
377
+ }
378
+
379
+ // BloopWalk performs a walk on all functions in the package
380
+ // if it imports testing and wrap the results of all qualified
381
+ // statements in a runtime.KeepAlive intrinsic call. See package
382
+ // doc for more details.
383
+ //
384
+ // for b.Loop() {...}
385
+ //
386
+ // loop's body.
387
+ func BloopWalk(pkg *ir.Package) {
388
+ hasTesting := false
389
+ for _, i := range pkg.Imports {
390
+ if i.Path == "testing" {
391
+ hasTesting = true
392
+ break
393
+ }
394
+ }
395
+ if !hasTesting {
396
+ return
397
+ }
398
+ for _, fn := range pkg.Funcs {
399
+ e := editor{false, fn}
400
+ ir.EditChildren(fn, e.edit)
401
+ }
402
+ }
go/src/cmd/compile/internal/compare/compare.go ADDED
@@ -0,0 +1,385 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2022 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 compare contains code for generating comparison
6
+ // routines for structs, strings and interfaces.
7
+ package compare
8
+
9
+ import (
10
+ "cmd/compile/internal/base"
11
+ "cmd/compile/internal/ir"
12
+ "cmd/compile/internal/typecheck"
13
+ "cmd/compile/internal/types"
14
+ "fmt"
15
+ "math/bits"
16
+ "sort"
17
+ )
18
+
19
+ // IsRegularMemory reports whether t can be compared/hashed as regular memory.
20
+ func IsRegularMemory(t *types.Type) bool {
21
+ return types.AlgType(t) == types.AMEM
22
+ }
23
+
24
+ // Memrun finds runs of struct fields for which memory-only algs are appropriate.
25
+ // t is the parent struct type, and start is the field index at which to start the run.
26
+ // size is the length in bytes of the memory included in the run.
27
+ // next is the index just after the end of the memory run.
28
+ func Memrun(t *types.Type, start int) (size int64, next int) {
29
+ next = start
30
+ for {
31
+ next++
32
+ if next == t.NumFields() {
33
+ break
34
+ }
35
+ // Stop run after a padded field.
36
+ if types.IsPaddedField(t, next-1) {
37
+ break
38
+ }
39
+ // Also, stop before a blank or non-memory field.
40
+ if f := t.Field(next); f.Sym.IsBlank() || !IsRegularMemory(f.Type) {
41
+ break
42
+ }
43
+ // For issue 46283, don't combine fields if the resulting load would
44
+ // require a larger alignment than the component fields.
45
+ if base.Ctxt.Arch.Alignment > 1 {
46
+ align := t.Alignment()
47
+ if off := t.Field(start).Offset; off&(align-1) != 0 {
48
+ // Offset is less aligned than the containing type.
49
+ // Use offset to determine alignment.
50
+ align = 1 << uint(bits.TrailingZeros64(uint64(off)))
51
+ }
52
+ size := t.Field(next).End() - t.Field(start).Offset
53
+ if size > align {
54
+ break
55
+ }
56
+ }
57
+ }
58
+ return t.Field(next-1).End() - t.Field(start).Offset, next
59
+ }
60
+
61
+ // EqCanPanic reports whether == on type t could panic (has an interface somewhere).
62
+ // t must be comparable.
63
+ func EqCanPanic(t *types.Type) bool {
64
+ switch t.Kind() {
65
+ default:
66
+ return false
67
+ case types.TINTER:
68
+ return true
69
+ case types.TARRAY:
70
+ return EqCanPanic(t.Elem())
71
+ case types.TSTRUCT:
72
+ for _, f := range t.Fields() {
73
+ if !f.Sym.IsBlank() && EqCanPanic(f.Type) {
74
+ return true
75
+ }
76
+ }
77
+ return false
78
+ }
79
+ }
80
+
81
+ // EqStructCost returns the cost of an equality comparison of two structs.
82
+ //
83
+ // The cost is determined using an algorithm which takes into consideration
84
+ // the size of the registers in the current architecture and the size of the
85
+ // memory-only fields in the struct.
86
+ func EqStructCost(t *types.Type) int64 {
87
+ cost := int64(0)
88
+
89
+ for i, fields := 0, t.Fields(); i < len(fields); {
90
+ f := fields[i]
91
+
92
+ // Skip blank-named fields.
93
+ if f.Sym.IsBlank() {
94
+ i++
95
+ continue
96
+ }
97
+
98
+ n, _, next := eqStructFieldCost(t, i)
99
+
100
+ cost += n
101
+ i = next
102
+ }
103
+
104
+ return cost
105
+ }
106
+
107
+ // eqStructFieldCost returns the cost of an equality comparison of two struct fields.
108
+ // t is the parent struct type, and i is the index of the field in the parent struct type.
109
+ // eqStructFieldCost may compute the cost of several adjacent fields at once. It returns
110
+ // the cost, the size of the set of fields it computed the cost for (in bytes), and the
111
+ // index of the first field not part of the set of fields for which the cost
112
+ // has already been calculated.
113
+ func eqStructFieldCost(t *types.Type, i int) (int64, int64, int) {
114
+ var (
115
+ cost = int64(0)
116
+ regSize = int64(types.RegSize)
117
+
118
+ size int64
119
+ next int
120
+ )
121
+
122
+ if base.Ctxt.Arch.CanMergeLoads {
123
+ // If we can merge adjacent loads then we can calculate the cost of the
124
+ // comparison using the size of the memory run and the size of the registers.
125
+ size, next = Memrun(t, i)
126
+ cost = size / regSize
127
+ if size%regSize != 0 {
128
+ cost++
129
+ }
130
+ return cost, size, next
131
+ }
132
+
133
+ // If we cannot merge adjacent loads then we have to use the size of the
134
+ // field and take into account the type to determine how many loads and compares
135
+ // are needed.
136
+ ft := t.Field(i).Type
137
+ size = ft.Size()
138
+ next = i + 1
139
+
140
+ return calculateCostForType(ft), size, next
141
+ }
142
+
143
+ func calculateCostForType(t *types.Type) int64 {
144
+ var cost int64
145
+ switch t.Kind() {
146
+ case types.TSTRUCT:
147
+ return EqStructCost(t)
148
+ case types.TSLICE:
149
+ // Slices are not comparable.
150
+ base.Fatalf("calculateCostForType: unexpected slice type")
151
+ case types.TARRAY:
152
+ elemCost := calculateCostForType(t.Elem())
153
+ cost = t.NumElem() * elemCost
154
+ case types.TSTRING, types.TINTER, types.TCOMPLEX64, types.TCOMPLEX128:
155
+ cost = 2
156
+ case types.TINT64, types.TUINT64:
157
+ cost = 8 / int64(types.RegSize)
158
+ default:
159
+ cost = 1
160
+ }
161
+ return cost
162
+ }
163
+
164
+ // EqStruct compares two structs np and nq for equality.
165
+ // It works by building a list of boolean conditions to satisfy.
166
+ // Conditions must be evaluated in the returned order and
167
+ // properly short-circuited by the caller.
168
+ // The first return value is the flattened list of conditions,
169
+ // the second value is a boolean indicating whether any of the
170
+ // comparisons could panic.
171
+ func EqStruct(t *types.Type, np, nq ir.Node) ([]ir.Node, bool) {
172
+ // The conditions are a list-of-lists. Conditions are reorderable
173
+ // within each inner list. The outer lists must be evaluated in order.
174
+ var conds [][]ir.Node
175
+ conds = append(conds, []ir.Node{})
176
+ and := func(n ir.Node) {
177
+ i := len(conds) - 1
178
+ conds[i] = append(conds[i], n)
179
+ }
180
+
181
+ // Walk the struct using memequal for runs of AMEM
182
+ // and calling specific equality tests for the others.
183
+ for i, fields := 0, t.Fields(); i < len(fields); {
184
+ f := fields[i]
185
+
186
+ // Skip blank-named fields.
187
+ if f.Sym.IsBlank() {
188
+ i++
189
+ continue
190
+ }
191
+
192
+ typeCanPanic := EqCanPanic(f.Type)
193
+
194
+ // Compare non-memory fields with field equality.
195
+ if !IsRegularMemory(f.Type) {
196
+ if typeCanPanic {
197
+ // Enforce ordering by starting a new set of reorderable conditions.
198
+ conds = append(conds, []ir.Node{})
199
+ }
200
+ switch {
201
+ case f.Type.IsString():
202
+ p := typecheck.DotField(base.Pos, typecheck.Expr(np), i)
203
+ q := typecheck.DotField(base.Pos, typecheck.Expr(nq), i)
204
+ eqlen, eqmem := EqString(p, q)
205
+ and(eqlen)
206
+ and(eqmem)
207
+ default:
208
+ and(eqfield(np, nq, i))
209
+ }
210
+ if typeCanPanic {
211
+ // Also enforce ordering after something that can panic.
212
+ conds = append(conds, []ir.Node{})
213
+ }
214
+ i++
215
+ continue
216
+ }
217
+
218
+ cost, size, next := eqStructFieldCost(t, i)
219
+ if cost <= 4 {
220
+ // Cost of 4 or less: use plain field equality.
221
+ for j := i; j < next; j++ {
222
+ and(eqfield(np, nq, j))
223
+ }
224
+ } else {
225
+ // Higher cost: use memequal.
226
+ cc := eqmem(np, nq, i, size)
227
+ and(cc)
228
+ }
229
+ i = next
230
+ }
231
+
232
+ // Sort conditions to put runtime calls last.
233
+ // Preserve the rest of the ordering.
234
+ var flatConds []ir.Node
235
+ for _, c := range conds {
236
+ isCall := func(n ir.Node) bool {
237
+ return n.Op() == ir.OCALL || n.Op() == ir.OCALLFUNC
238
+ }
239
+ sort.SliceStable(c, func(i, j int) bool {
240
+ return !isCall(c[i]) && isCall(c[j])
241
+ })
242
+ flatConds = append(flatConds, c...)
243
+ }
244
+ return flatConds, len(conds) > 1
245
+ }
246
+
247
+ // EqString returns the nodes
248
+ //
249
+ // len(s) == len(t)
250
+ //
251
+ // and
252
+ //
253
+ // memequal(s.ptr, t.ptr, len(s))
254
+ //
255
+ // which can be used to construct string equality comparison.
256
+ // eqlen must be evaluated before eqmem, and shortcircuiting is required.
257
+ func EqString(s, t ir.Node) (eqlen *ir.BinaryExpr, eqmem *ir.CallExpr) {
258
+ s = typecheck.Conv(s, types.Types[types.TSTRING])
259
+ t = typecheck.Conv(t, types.Types[types.TSTRING])
260
+ sptr := ir.NewUnaryExpr(base.Pos, ir.OSPTR, s)
261
+ tptr := ir.NewUnaryExpr(base.Pos, ir.OSPTR, t)
262
+ slen := typecheck.Conv(ir.NewUnaryExpr(base.Pos, ir.OLEN, s), types.Types[types.TUINTPTR])
263
+ tlen := typecheck.Conv(ir.NewUnaryExpr(base.Pos, ir.OLEN, t), types.Types[types.TUINTPTR])
264
+
265
+ // Pick the 3rd arg to memequal. Both slen and tlen are fine to use, because we short
266
+ // circuit the memequal call if they aren't the same. But if one is a constant some
267
+ // memequal optimizations are easier to apply.
268
+ probablyConstant := func(n ir.Node) bool {
269
+ if n.Op() == ir.OCONVNOP {
270
+ n = n.(*ir.ConvExpr).X
271
+ }
272
+ if n.Op() == ir.OLITERAL {
273
+ return true
274
+ }
275
+ if n.Op() != ir.ONAME {
276
+ return false
277
+ }
278
+ name := n.(*ir.Name)
279
+ if name.Class != ir.PAUTO {
280
+ return false
281
+ }
282
+ if def := name.Defn; def == nil {
283
+ // n starts out as the empty string
284
+ return true
285
+ } else if def.Op() == ir.OAS && (def.(*ir.AssignStmt).Y == nil || def.(*ir.AssignStmt).Y.Op() == ir.OLITERAL) {
286
+ // n starts out as a constant string
287
+ return true
288
+ }
289
+ return false
290
+ }
291
+ cmplen := slen
292
+ if probablyConstant(t) && !probablyConstant(s) {
293
+ cmplen = tlen
294
+ }
295
+
296
+ fn := typecheck.LookupRuntime("memequal", types.Types[types.TUINT8], types.Types[types.TUINT8])
297
+ call := typecheck.Call(base.Pos, fn, []ir.Node{sptr, tptr, ir.Copy(cmplen)}, false).(*ir.CallExpr)
298
+
299
+ cmp := ir.NewBinaryExpr(base.Pos, ir.OEQ, slen, tlen)
300
+ cmp = typecheck.Expr(cmp).(*ir.BinaryExpr)
301
+ cmp.SetType(types.Types[types.TBOOL])
302
+ return cmp, call
303
+ }
304
+
305
+ // EqInterface returns the nodes
306
+ //
307
+ // s.tab == t.tab (or s.typ == t.typ, as appropriate)
308
+ //
309
+ // and
310
+ //
311
+ // ifaceeq(s.tab, s.data, t.data) (or efaceeq(s.typ, s.data, t.data), as appropriate)
312
+ //
313
+ // which can be used to construct interface equality comparison.
314
+ // eqtab must be evaluated before eqdata, and shortcircuiting is required.
315
+ func EqInterface(s, t ir.Node) (eqtab *ir.BinaryExpr, eqdata *ir.CallExpr) {
316
+ if !types.Identical(s.Type(), t.Type()) {
317
+ base.Fatalf("EqInterface %v %v", s.Type(), t.Type())
318
+ }
319
+ // func ifaceeq(tab *uintptr, x, y unsafe.Pointer) (ret bool)
320
+ // func efaceeq(typ *uintptr, x, y unsafe.Pointer) (ret bool)
321
+ var fn ir.Node
322
+ if s.Type().IsEmptyInterface() {
323
+ fn = typecheck.LookupRuntime("efaceeq")
324
+ } else {
325
+ fn = typecheck.LookupRuntime("ifaceeq")
326
+ }
327
+
328
+ stab := ir.NewUnaryExpr(base.Pos, ir.OITAB, s)
329
+ ttab := ir.NewUnaryExpr(base.Pos, ir.OITAB, t)
330
+ sdata := ir.NewUnaryExpr(base.Pos, ir.OIDATA, s)
331
+ tdata := ir.NewUnaryExpr(base.Pos, ir.OIDATA, t)
332
+ sdata.SetType(types.Types[types.TUNSAFEPTR])
333
+ tdata.SetType(types.Types[types.TUNSAFEPTR])
334
+ sdata.SetTypecheck(1)
335
+ tdata.SetTypecheck(1)
336
+
337
+ call := typecheck.Call(base.Pos, fn, []ir.Node{stab, sdata, tdata}, false).(*ir.CallExpr)
338
+
339
+ cmp := ir.NewBinaryExpr(base.Pos, ir.OEQ, stab, ttab)
340
+ cmp = typecheck.Expr(cmp).(*ir.BinaryExpr)
341
+ cmp.SetType(types.Types[types.TBOOL])
342
+ return cmp, call
343
+ }
344
+
345
+ // eqfield returns the node
346
+ //
347
+ // p.field == q.field
348
+ func eqfield(p, q ir.Node, field int) ir.Node {
349
+ nx := typecheck.DotField(base.Pos, typecheck.Expr(p), field)
350
+ ny := typecheck.DotField(base.Pos, typecheck.Expr(q), field)
351
+ return typecheck.Expr(ir.NewBinaryExpr(base.Pos, ir.OEQ, nx, ny))
352
+ }
353
+
354
+ // eqmem returns the node
355
+ //
356
+ // memequal(&p.field, &q.field, size)
357
+ func eqmem(p, q ir.Node, field int, size int64) ir.Node {
358
+ nx := typecheck.Expr(typecheck.NodAddr(typecheck.DotField(base.Pos, p, field)))
359
+ ny := typecheck.Expr(typecheck.NodAddr(typecheck.DotField(base.Pos, q, field)))
360
+
361
+ fn, needsize := eqmemfunc(size, nx.Type().Elem())
362
+ call := ir.NewCallExpr(base.Pos, ir.OCALL, fn, nil)
363
+ call.Args.Append(nx)
364
+ call.Args.Append(ny)
365
+ if needsize {
366
+ call.Args.Append(ir.NewInt(base.Pos, size))
367
+ }
368
+
369
+ return call
370
+ }
371
+
372
+ func eqmemfunc(size int64, t *types.Type) (fn *ir.Name, needsize bool) {
373
+ if !base.Ctxt.Arch.CanMergeLoads && t.Alignment() < int64(base.Ctxt.Arch.Alignment) && t.Alignment() < t.Size() {
374
+ // We can't use larger comparisons if the value might not be aligned
375
+ // enough for the larger comparison. See issues 46283 and 67160.
376
+ size = 0
377
+ }
378
+ switch size {
379
+ case 1, 2, 4, 8, 16:
380
+ buf := fmt.Sprintf("memequal%d", int(size)*8)
381
+ return typecheck.LookupRuntime(buf, t, t), false
382
+ }
383
+
384
+ return typecheck.LookupRuntime("memequal", t, t), true
385
+ }
go/src/cmd/compile/internal/compare/compare_test.go ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2022 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 compare
6
+
7
+ import (
8
+ "cmd/compile/internal/base"
9
+ "cmd/compile/internal/typecheck"
10
+ "cmd/compile/internal/types"
11
+ "cmd/internal/obj"
12
+ "cmd/internal/src"
13
+ "cmd/internal/sys"
14
+ "testing"
15
+ )
16
+
17
+ type typefn func() *types.Type
18
+
19
+ func init() {
20
+ // These are the few constants that need to be initialized in order to use
21
+ // the types package without using the typecheck package by calling
22
+ // typecheck.InitUniverse() (the normal way to initialize the types package).
23
+ types.PtrSize = 8
24
+ types.RegSize = 8
25
+ types.MaxWidth = 1 << 50
26
+ base.Ctxt = &obj.Link{Arch: &obj.LinkArch{Arch: &sys.Arch{Alignment: 1, CanMergeLoads: true}}}
27
+ typecheck.InitUniverse()
28
+ }
29
+
30
+ func TestEqStructCost(t *testing.T) {
31
+ repeat := func(n int, typ *types.Type) []*types.Type {
32
+ typs := make([]*types.Type, n)
33
+ for i := range typs {
34
+ typs[i] = typ
35
+ }
36
+ return typs
37
+ }
38
+
39
+ tt := []struct {
40
+ name string
41
+ cost int64
42
+ nonMergeLoadCost int64
43
+ fieldTypes []*types.Type
44
+ }{
45
+ {"struct without fields", 0, 0, nil},
46
+ {"struct with 1 byte field", 1, 1, repeat(1, types.ByteType)},
47
+ {"struct with 8 byte fields", 1, 8, repeat(8, types.ByteType)},
48
+ {"struct with 16 byte fields", 2, 16, repeat(16, types.ByteType)},
49
+ {"struct with 32 byte fields", 4, 32, repeat(32, types.ByteType)},
50
+ {"struct with 2 int32 fields", 1, 2, repeat(2, types.Types[types.TINT32])},
51
+ {"struct with 2 int32 fields and 1 int64", 2, 3,
52
+ []*types.Type{
53
+ types.Types[types.TINT32],
54
+ types.Types[types.TINT32],
55
+ types.Types[types.TINT64],
56
+ },
57
+ },
58
+ {"struct with 1 int field and 1 string", 3, 3,
59
+ []*types.Type{
60
+ types.Types[types.TINT64],
61
+ types.Types[types.TSTRING],
62
+ },
63
+ },
64
+ {"struct with 2 strings", 4, 4, repeat(2, types.Types[types.TSTRING])},
65
+ {"struct with 1 large byte array field", 26, 101,
66
+ []*types.Type{
67
+ types.NewArray(types.Types[types.TUINT16], 101),
68
+ },
69
+ },
70
+ {"struct with string array field", 4, 4,
71
+ []*types.Type{
72
+ types.NewArray(types.Types[types.TSTRING], 2),
73
+ },
74
+ },
75
+ }
76
+
77
+ for _, tc := range tt {
78
+ t.Run(tc.name, func(t *testing.T) {
79
+ fields := make([]*types.Field, len(tc.fieldTypes))
80
+ for i, ftyp := range tc.fieldTypes {
81
+ fields[i] = types.NewField(src.NoXPos, typecheck.LookupNum("f", i), ftyp)
82
+ }
83
+ typ := types.NewStruct(fields)
84
+ types.CalcSize(typ)
85
+
86
+ want := tc.cost
87
+ base.Ctxt.Arch.CanMergeLoads = true
88
+ actual := EqStructCost(typ)
89
+ if actual != want {
90
+ t.Errorf("CanMergeLoads=true EqStructCost(%v) = %d, want %d", typ, actual, want)
91
+ }
92
+
93
+ base.Ctxt.Arch.CanMergeLoads = false
94
+ want = tc.nonMergeLoadCost
95
+ actual = EqStructCost(typ)
96
+ if actual != want {
97
+ t.Errorf("CanMergeLoads=false EqStructCost(%v) = %d, want %d", typ, actual, want)
98
+ }
99
+ })
100
+ }
101
+ }
go/src/cmd/compile/internal/coverage/cover.go ADDED
@@ -0,0 +1,200 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2022 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 coverage
6
+
7
+ // This package contains support routines for coverage "fixup" in the
8
+ // compiler, which happens when compiling a package whose source code
9
+ // has been run through "cmd/cover" to add instrumentation. The two
10
+ // important entry points are FixupVars (called prior to package init
11
+ // generation) and FixupInit (called following package init
12
+ // generation).
13
+
14
+ import (
15
+ "cmd/compile/internal/base"
16
+ "cmd/compile/internal/ir"
17
+ "cmd/compile/internal/typecheck"
18
+ "cmd/compile/internal/types"
19
+ "cmd/internal/objabi"
20
+ "internal/coverage"
21
+ "strconv"
22
+ "strings"
23
+ )
24
+
25
+ // names records state information collected in the first fixup
26
+ // phase so that it can be passed to the second fixup phase.
27
+ type names struct {
28
+ MetaVar *ir.Name
29
+ PkgIdVar *ir.Name
30
+ InitFn *ir.Func
31
+ CounterMode coverage.CounterMode
32
+ CounterGran coverage.CounterGranularity
33
+ }
34
+
35
+ // Fixup adds calls to the pkg init function as appropriate to
36
+ // register coverage-related variables with the runtime.
37
+ //
38
+ // It also reclassifies selected variables (for example, tagging
39
+ // coverage counter variables with flags so that they can be handled
40
+ // properly downstream).
41
+ func Fixup() {
42
+ if base.Flag.Cfg.CoverageInfo == nil {
43
+ return // not using coverage
44
+ }
45
+
46
+ metaVarName := base.Flag.Cfg.CoverageInfo.MetaVar
47
+ pkgIdVarName := base.Flag.Cfg.CoverageInfo.PkgIdVar
48
+ counterMode := base.Flag.Cfg.CoverageInfo.CounterMode
49
+ counterGran := base.Flag.Cfg.CoverageInfo.CounterGranularity
50
+ counterPrefix := base.Flag.Cfg.CoverageInfo.CounterPrefix
51
+ var metavar *ir.Name
52
+ var pkgidvar *ir.Name
53
+
54
+ ckTypSanity := func(nm *ir.Name, tag string) {
55
+ if nm.Type() == nil || nm.Type().HasPointers() {
56
+ base.Fatalf("unsuitable %s %q mentioned in coveragecfg, improper type '%v'", tag, nm.Sym().Name, nm.Type())
57
+ }
58
+ }
59
+
60
+ for _, nm := range typecheck.Target.Externs {
61
+ s := nm.Sym()
62
+ switch s.Name {
63
+ case metaVarName:
64
+ metavar = nm
65
+ ckTypSanity(nm, "metavar")
66
+ nm.MarkReadonly()
67
+ continue
68
+ case pkgIdVarName:
69
+ pkgidvar = nm
70
+ ckTypSanity(nm, "pkgidvar")
71
+ nm.SetCoverageAuxVar(true)
72
+ s := nm.Linksym()
73
+ s.Type = objabi.SCOVERAGE_AUXVAR
74
+ continue
75
+ }
76
+ if strings.HasPrefix(s.Name, counterPrefix) {
77
+ ckTypSanity(nm, "countervar")
78
+ nm.SetCoverageAuxVar(true)
79
+ s := nm.Linksym()
80
+ s.Type = objabi.SCOVERAGE_COUNTER
81
+ }
82
+ }
83
+ cm := coverage.ParseCounterMode(counterMode)
84
+ if cm == coverage.CtrModeInvalid {
85
+ base.Fatalf("bad setting %q for covermode in coveragecfg:",
86
+ counterMode)
87
+ }
88
+ var cg coverage.CounterGranularity
89
+ switch counterGran {
90
+ case "perblock":
91
+ cg = coverage.CtrGranularityPerBlock
92
+ case "perfunc":
93
+ cg = coverage.CtrGranularityPerFunc
94
+ default:
95
+ base.Fatalf("bad setting %q for covergranularity in coveragecfg:",
96
+ counterGran)
97
+ }
98
+
99
+ cnames := names{
100
+ MetaVar: metavar,
101
+ PkgIdVar: pkgidvar,
102
+ CounterMode: cm,
103
+ CounterGran: cg,
104
+ }
105
+
106
+ for _, fn := range typecheck.Target.Funcs {
107
+ if ir.FuncName(fn) == "init" {
108
+ cnames.InitFn = fn
109
+ break
110
+ }
111
+ }
112
+ if cnames.InitFn == nil {
113
+ panic("unexpected (no init func for -cover build)")
114
+ }
115
+
116
+ hashv, len := metaHashAndLen()
117
+ if cnames.CounterMode != coverage.CtrModeTestMain {
118
+ registerMeta(cnames, hashv, len)
119
+ }
120
+ if base.Ctxt.Pkgpath == "main" {
121
+ addInitHookCall(cnames.InitFn, cnames.CounterMode)
122
+ }
123
+ }
124
+
125
+ func metaHashAndLen() ([16]byte, int) {
126
+
127
+ // Read meta-data hash from config entry.
128
+ mhash := base.Flag.Cfg.CoverageInfo.MetaHash
129
+ if len(mhash) != 32 {
130
+ base.Fatalf("unexpected: got metahash length %d want 32", len(mhash))
131
+ }
132
+ var hv [16]byte
133
+ for i := 0; i < 16; i++ {
134
+ nib := mhash[i*2 : i*2+2]
135
+ x, err := strconv.ParseInt(nib, 16, 32)
136
+ if err != nil {
137
+ base.Fatalf("metahash bad byte %q", nib)
138
+ }
139
+ hv[i] = byte(x)
140
+ }
141
+
142
+ // Return hash and meta-data len
143
+ return hv, base.Flag.Cfg.CoverageInfo.MetaLen
144
+ }
145
+
146
+ func registerMeta(cnames names, hashv [16]byte, mdlen int) {
147
+ // Materialize expression for hash (an array literal)
148
+ pos := cnames.InitFn.Pos()
149
+ elist := make([]ir.Node, 0, 16)
150
+ for i := 0; i < 16; i++ {
151
+ elem := ir.NewInt(base.Pos, int64(hashv[i]))
152
+ elist = append(elist, elem)
153
+ }
154
+ ht := types.NewArray(types.Types[types.TUINT8], 16)
155
+ hashx := ir.NewCompLitExpr(pos, ir.OCOMPLIT, ht, elist)
156
+
157
+ // Materalize expression corresponding to address of the meta-data symbol.
158
+ mdax := typecheck.NodAddr(cnames.MetaVar)
159
+ mdauspx := typecheck.ConvNop(mdax, types.Types[types.TUNSAFEPTR])
160
+
161
+ // Materialize expression for length.
162
+ lenx := ir.NewInt(base.Pos, int64(mdlen)) // untyped
163
+
164
+ // Generate a call to runtime.addCovMeta, e.g.
165
+ //
166
+ // pkgIdVar = runtime.addCovMeta(&sym, len, hash, pkgpath, pkid, cmode, cgran)
167
+ //
168
+ fn := typecheck.LookupRuntime("addCovMeta")
169
+ pkid := coverage.HardCodedPkgID(base.Ctxt.Pkgpath)
170
+ pkIdNode := ir.NewInt(base.Pos, int64(pkid))
171
+ cmodeNode := ir.NewInt(base.Pos, int64(cnames.CounterMode))
172
+ cgranNode := ir.NewInt(base.Pos, int64(cnames.CounterGran))
173
+ pkPathNode := ir.NewString(base.Pos, base.Ctxt.Pkgpath)
174
+ callx := typecheck.Call(pos, fn, []ir.Node{mdauspx, lenx, hashx,
175
+ pkPathNode, pkIdNode, cmodeNode, cgranNode}, false)
176
+ assign := callx
177
+ if pkid == coverage.NotHardCoded {
178
+ assign = typecheck.Stmt(ir.NewAssignStmt(pos, cnames.PkgIdVar, callx))
179
+ }
180
+
181
+ // Tack the call onto the start of our init function. We do this
182
+ // early in the init since it's possible that instrumented function
183
+ // bodies (with counter updates) might be inlined into init.
184
+ cnames.InitFn.Body.Prepend(assign)
185
+ }
186
+
187
+ // addInitHookCall generates a call to runtime/coverage.initHook() and
188
+ // inserts it into the package main init function, which will kick off
189
+ // the process for coverage data writing (emit meta data, and register
190
+ // an exit hook to emit counter data).
191
+ func addInitHookCall(initfn *ir.Func, cmode coverage.CounterMode) {
192
+ typecheck.InitCoverage()
193
+ pos := initfn.Pos()
194
+ istest := cmode == coverage.CtrModeTestMain
195
+ initf := typecheck.LookupCoverage("initHook")
196
+ istestNode := ir.NewBool(base.Pos, istest)
197
+ args := []ir.Node{istestNode}
198
+ callx := typecheck.Call(pos, initf, args, false)
199
+ initfn.Body.Append(callx)
200
+ }
go/src/cmd/compile/internal/deadlocals/deadlocals.go ADDED
@@ -0,0 +1,199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2024 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
+ // The deadlocals pass removes assignments to unused local variables.
6
+ package deadlocals
7
+
8
+ import (
9
+ "cmd/compile/internal/base"
10
+ "cmd/compile/internal/ir"
11
+ "cmd/compile/internal/types"
12
+ "cmd/internal/src"
13
+ "fmt"
14
+ "go/constant"
15
+ )
16
+
17
+ // Funcs applies the deadlocals pass to fns.
18
+ func Funcs(fns []*ir.Func) {
19
+ if base.Flag.N != 0 || base.Debug.NoDeadLocals != 0 {
20
+ return
21
+ }
22
+
23
+ zero := ir.NewBasicLit(base.AutogeneratedPos, types.Types[types.TINT], constant.MakeInt64(0))
24
+
25
+ for _, fn := range fns {
26
+ if fn.IsClosure() {
27
+ continue
28
+ }
29
+
30
+ v := newVisitor(fn)
31
+ v.nodes(fn.Body)
32
+
33
+ for _, k := range v.defsKeys {
34
+ assigns := v.defs[k]
35
+ for _, as := range assigns {
36
+ // Kludge for "missing func info" linker panic.
37
+ // See also closureInitLSym in inline/inl.go.
38
+ if clo, ok := (*as.rhs).(*ir.ClosureExpr); ok && clo.Op() == ir.OCLOSURE {
39
+ if clo.Func.IsClosure() {
40
+ ir.InitLSym(clo.Func, true)
41
+ }
42
+ }
43
+
44
+ *as.lhs = ir.BlankNode
45
+ *as.rhs = zero
46
+ }
47
+ if len(assigns) > 0 {
48
+ // k.Defn might be pointing at one of the
49
+ // assignments we're overwriting.
50
+ k.Defn = nil
51
+ }
52
+ }
53
+ }
54
+ }
55
+
56
+ type visitor struct {
57
+ curfn *ir.Func
58
+ // defs[name] contains assignments that can be discarded if name can be discarded.
59
+ // if defs[name] is defined nil, then name is actually used.
60
+ defs map[*ir.Name][]assign
61
+ defsKeys []*ir.Name // insertion order of keys, for reproducible iteration (and builds)
62
+
63
+ doNode func(ir.Node) bool
64
+ }
65
+
66
+ type assign struct {
67
+ pos src.XPos
68
+ lhs, rhs *ir.Node
69
+ }
70
+
71
+ func newVisitor(fn *ir.Func) *visitor {
72
+ v := &visitor{
73
+ curfn: fn,
74
+ defs: make(map[*ir.Name][]assign),
75
+ }
76
+ v.doNode = func(n ir.Node) bool {
77
+ v.node(n)
78
+ return false
79
+ }
80
+ return v
81
+ }
82
+
83
+ func (v *visitor) node(n ir.Node) {
84
+ if n == nil {
85
+ return
86
+ }
87
+
88
+ switch n.Op() {
89
+ default:
90
+ ir.DoChildrenWithHidden(n, v.doNode)
91
+ case ir.OCLOSURE:
92
+ n := n.(*ir.ClosureExpr)
93
+ v.nodes(n.Init())
94
+ for _, cv := range n.Func.ClosureVars {
95
+ v.node(cv)
96
+ }
97
+ v.nodes(n.Func.Body)
98
+
99
+ case ir.ODCL:
100
+ // ignore
101
+ case ir.ONAME:
102
+ n := n.(*ir.Name)
103
+ n = n.Canonical()
104
+ if isLocal(n, false) {
105
+ // Force any lazy definitions.
106
+ s, ok := v.defs[n]
107
+ if !ok {
108
+ v.defsKeys = append(v.defsKeys, n)
109
+ }
110
+ v.defs[n] = nil
111
+ for _, as := range s {
112
+ // do the visit that was skipped in v.assign when as was appended to v.defs[n]
113
+ v.node(*as.rhs)
114
+ }
115
+ }
116
+
117
+ case ir.OAS:
118
+ n := n.(*ir.AssignStmt)
119
+ v.assign(n.Pos(), &n.X, &n.Y, false)
120
+ case ir.OAS2:
121
+ n := n.(*ir.AssignListStmt)
122
+
123
+ // If all LHS vars are blank, treat them as intentional
124
+ // uses of corresponding RHS vars. If any are non-blank
125
+ // then any blanks are discards.
126
+ hasNonBlank := false
127
+ for i := range n.Lhs {
128
+ if !ir.IsBlank(n.Lhs[i]) {
129
+ hasNonBlank = true
130
+ break
131
+ }
132
+ }
133
+ for i := range n.Lhs {
134
+ v.assign(n.Pos(), &n.Lhs[i], &n.Rhs[i], hasNonBlank)
135
+ }
136
+ }
137
+ }
138
+
139
+ func (v *visitor) nodes(list ir.Nodes) {
140
+ for _, n := range list {
141
+ v.node(n)
142
+ }
143
+ }
144
+
145
+ func hasEffects(n ir.Node) bool {
146
+ if n == nil {
147
+ return false
148
+ }
149
+ if len(n.Init()) != 0 {
150
+ return true
151
+ }
152
+
153
+ switch n.Op() {
154
+ // TODO(mdempsky): More.
155
+ case ir.ONAME, ir.OLITERAL, ir.ONIL, ir.OCLOSURE:
156
+ return false
157
+ }
158
+ return true
159
+ }
160
+
161
+ func (v *visitor) assign(pos src.XPos, lhs, rhs *ir.Node, blankIsNotUse bool) {
162
+ name, ok := (*lhs).(*ir.Name)
163
+ if !ok {
164
+ v.node(*lhs) // XXX: Interpret as variable, not value.
165
+ v.node(*rhs)
166
+ return
167
+ }
168
+ name = name.Canonical()
169
+
170
+ if isLocal(name, blankIsNotUse) && !hasEffects(*rhs) {
171
+ if s, ok := v.defs[name]; !ok || s != nil {
172
+ // !ok || s != nil is FALSE if previously "v.defs[name] = nil" -- that marks a use.
173
+ if !ok {
174
+ v.defsKeys = append(v.defsKeys, name)
175
+ }
176
+ v.defs[name] = append(s, assign{pos, lhs, rhs})
177
+ return // don't visit rhs unless that node ends up live, later.
178
+ }
179
+ }
180
+
181
+ v.node(*rhs)
182
+ }
183
+
184
+ func isLocal(n *ir.Name, blankIsNotUse bool) bool {
185
+ if ir.IsBlank(n) {
186
+ // Treat single assignments as intentional use (false), anything else is a discard (true).
187
+ return blankIsNotUse
188
+ }
189
+
190
+ switch n.Class {
191
+ case ir.PAUTO, ir.PPARAM:
192
+ return true
193
+ case ir.PPARAMOUT:
194
+ return false
195
+ case ir.PEXTERN, ir.PFUNC:
196
+ return false
197
+ }
198
+ panic(fmt.Sprintf("unexpected Class: %+v", n))
199
+ }
go/src/cmd/compile/internal/devirtualize/devirtualize.go ADDED
@@ -0,0 +1,600 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 devirtualize implements two "devirtualization" optimization passes:
6
+ //
7
+ // - "Static" devirtualization which replaces interface method calls with
8
+ // direct concrete-type method calls where possible.
9
+ // - "Profile-guided" devirtualization which replaces indirect calls with a
10
+ // conditional direct call to the hottest concrete callee from a profile, as
11
+ // well as a fallback using the original indirect call.
12
+ package devirtualize
13
+
14
+ import (
15
+ "cmd/compile/internal/base"
16
+ "cmd/compile/internal/ir"
17
+ "cmd/compile/internal/typecheck"
18
+ "cmd/compile/internal/types"
19
+ )
20
+
21
+ const go126ImprovedConcreteTypeAnalysis = true
22
+
23
+ // StaticCall devirtualizes the given call if possible when the concrete callee
24
+ // is available statically.
25
+ func StaticCall(s *State, call *ir.CallExpr) {
26
+ // For promoted methods (including value-receiver methods promoted
27
+ // to pointer-receivers), the interface method wrapper may contain
28
+ // expressions that can panic (e.g., ODEREF, ODOTPTR,
29
+ // ODOTINTER). Devirtualization involves inlining these expressions
30
+ // (and possible panics) to the call site. This normally isn't a
31
+ // problem, but for go/defer statements it can move the panic from
32
+ // when/where the call executes to the go/defer statement itself,
33
+ // which is a visible change in semantics (e.g., #52072). To prevent
34
+ // this, we skip devirtualizing calls within go/defer statements
35
+ // altogether.
36
+ if call.GoDefer {
37
+ return
38
+ }
39
+
40
+ if call.Op() != ir.OCALLINTER {
41
+ return
42
+ }
43
+
44
+ sel := call.Fun.(*ir.SelectorExpr)
45
+ var typ *types.Type
46
+ if go126ImprovedConcreteTypeAnalysis {
47
+ typ = concreteType(s, sel.X)
48
+ if typ == nil {
49
+ return
50
+ }
51
+
52
+ // Don't create type-assertions that would be impossible at compile-time.
53
+ // This can happen in such case: any(0).(interface {A()}).A(), this typechecks without
54
+ // any errors, but will cause a runtime panic. We statically know that int(0) does not
55
+ // implement that interface, thus we skip the devirtualization, as it is not possible
56
+ // to make an assertion: any(0).(interface{A()}).(int) (int does not implement interface{A()}).
57
+ if !typecheck.Implements(typ, sel.X.Type()) {
58
+ return
59
+ }
60
+ } else {
61
+ r := ir.StaticValue(sel.X)
62
+ if r.Op() != ir.OCONVIFACE {
63
+ return
64
+ }
65
+ recv := r.(*ir.ConvExpr)
66
+ typ = recv.X.Type()
67
+ if typ.IsInterface() {
68
+ return
69
+ }
70
+ }
71
+
72
+ // If typ is a shape type, then it was a type argument originally
73
+ // and we'd need an indirect call through the dictionary anyway.
74
+ // We're unable to devirtualize this call.
75
+ if typ.IsShape() {
76
+ return
77
+ }
78
+
79
+ // If typ *has* a shape type, then it's a shaped, instantiated
80
+ // type like T[go.shape.int], and its methods (may) have an extra
81
+ // dictionary parameter. We could devirtualize this call if we
82
+ // could derive an appropriate dictionary argument.
83
+ //
84
+ // TODO(mdempsky): If typ has a promoted non-generic method,
85
+ // then that method won't require a dictionary argument. We could
86
+ // still devirtualize those calls.
87
+ //
88
+ // TODO(mdempsky): We have the *runtime.itab in recv.TypeWord. It
89
+ // should be possible to compute the represented type's runtime
90
+ // dictionary from this (e.g., by adding a pointer from T[int]'s
91
+ // *runtime._type to .dict.T[int]; or by recognizing static
92
+ // references to go:itab.T[int],iface and constructing a direct
93
+ // reference to .dict.T[int]).
94
+ if typ.HasShape() {
95
+ if base.Flag.LowerM != 0 {
96
+ base.WarnfAt(call.Pos(), "cannot devirtualize %v: shaped receiver %v", call, typ)
97
+ }
98
+ return
99
+ }
100
+
101
+ // Further, if sel.X's type has a shape type, then it's a shaped
102
+ // interface type. In this case, the (non-dynamic) TypeAssertExpr
103
+ // we construct below would attempt to create an itab
104
+ // corresponding to this shaped interface type; but the actual
105
+ // itab pointer in the interface value will correspond to the
106
+ // original (non-shaped) interface type instead. These are
107
+ // functionally equivalent, but they have distinct pointer
108
+ // identities, which leads to the type assertion failing.
109
+ //
110
+ // TODO(mdempsky): We know the type assertion here is safe, so we
111
+ // could instead set a flag so that walk skips the itab check. For
112
+ // now, punting is easy and safe.
113
+ if sel.X.Type().HasShape() {
114
+ if base.Flag.LowerM != 0 {
115
+ base.WarnfAt(call.Pos(), "cannot devirtualize %v: shaped interface %v", call, sel.X.Type())
116
+ }
117
+ return
118
+ }
119
+
120
+ dt := ir.NewTypeAssertExpr(sel.Pos(), sel.X, typ)
121
+
122
+ if go126ImprovedConcreteTypeAnalysis {
123
+ // Consider:
124
+ //
125
+ // var v Iface
126
+ // v.A()
127
+ // v = &Impl{}
128
+ //
129
+ // Here in the devirtualizer, we determine the concrete type of v as being an *Impl,
130
+ // but it can still be a nil interface, we have not detected that. The v.(*Impl)
131
+ // type assertion that we make here would also have failed, but with a different
132
+ // panic "pkg.Iface is nil, not *pkg.Impl", where previously we would get a nil panic.
133
+ // We fix this, by introducing an additional nilcheck on the itab.
134
+ // Calling a method on a nil interface (in most cases) is a bug in a program, so it is fine
135
+ // to devirtualize and further (possibly) inline them, even though we would never reach
136
+ // the called function.
137
+ dt.UseNilPanic = true
138
+ dt.SetPos(call.Pos())
139
+ }
140
+
141
+ x := typecheck.XDotMethod(sel.Pos(), dt, sel.Sel, true)
142
+ switch x.Op() {
143
+ case ir.ODOTMETH:
144
+ if base.Flag.LowerM != 0 {
145
+ base.WarnfAt(call.Pos(), "devirtualizing %v to %v", sel, typ)
146
+ }
147
+ call.SetOp(ir.OCALLMETH)
148
+ call.Fun = x
149
+ case ir.ODOTINTER:
150
+ // Promoted method from embedded interface-typed field (#42279).
151
+ if base.Flag.LowerM != 0 {
152
+ base.WarnfAt(call.Pos(), "partially devirtualizing %v to %v", sel, typ)
153
+ }
154
+ call.SetOp(ir.OCALLINTER)
155
+ call.Fun = x
156
+ default:
157
+ base.FatalfAt(call.Pos(), "failed to devirtualize %v (%v)", x, x.Op())
158
+ }
159
+
160
+ // Duplicated logic from typecheck for function call return
161
+ // value types.
162
+ //
163
+ // Receiver parameter size may have changed; need to update
164
+ // call.Type to get correct stack offsets for result
165
+ // parameters.
166
+ types.CheckSize(x.Type())
167
+ switch ft := x.Type(); ft.NumResults() {
168
+ case 0:
169
+ case 1:
170
+ call.SetType(ft.Result(0).Type)
171
+ default:
172
+ call.SetType(ft.ResultsTuple())
173
+ }
174
+
175
+ // Desugar OCALLMETH, if we created one (#57309).
176
+ typecheck.FixMethodCall(call)
177
+ }
178
+
179
+ const concreteTypeDebug = false
180
+
181
+ // concreteType determines the concrete type of n, following OCONVIFACEs and type asserts.
182
+ // Returns nil when the concrete type could not be determined, or when there are multiple
183
+ // (different) types assigned to an interface.
184
+ func concreteType(s *State, n ir.Node) (typ *types.Type) {
185
+ typ = concreteType1(s, n, make(map[*ir.Name]struct{}))
186
+ if typ == &noType {
187
+ return nil
188
+ }
189
+ if typ != nil && typ.IsInterface() {
190
+ base.FatalfAt(n.Pos(), "typ.IsInterface() = true; want = false; typ = %v", typ)
191
+ }
192
+ return typ
193
+ }
194
+
195
+ // noType is a sentinel value returned by [concreteType1].
196
+ var noType types.Type
197
+
198
+ // concreteType1 analyzes the node n and returns its concrete type if it is statically known.
199
+ // Otherwise, it returns a nil Type, indicating that a concrete type was not determined.
200
+ // When n is known to be statically nil or a self-assignment is detected, it returns a sentinel [noType] type instead.
201
+ func concreteType1(s *State, n ir.Node, seen map[*ir.Name]struct{}) (outT *types.Type) {
202
+ nn := n // for debug messages
203
+
204
+ if concreteTypeDebug {
205
+ defer func() {
206
+ t := "&noType"
207
+ if outT != &noType {
208
+ t = outT.String()
209
+ }
210
+ base.Warn("concreteType1(%v) -> %v", nn, t)
211
+ }()
212
+ }
213
+
214
+ for {
215
+ if concreteTypeDebug {
216
+ base.Warn("concreteType1(%v): analyzing %v", nn, n)
217
+ }
218
+
219
+ if !n.Type().IsInterface() {
220
+ return n.Type()
221
+ }
222
+
223
+ switch n1 := n.(type) {
224
+ case *ir.ConvExpr:
225
+ if n1.Op() == ir.OCONVNOP {
226
+ if !n1.Type().IsInterface() || !types.Identical(n1.Type().Underlying(), n1.X.Type().Underlying()) {
227
+ // As we check (directly before this switch) whether n is an interface, thus we should only reach
228
+ // here for iface conversions where both operands are the same.
229
+ base.FatalfAt(n1.Pos(), "not identical/interface types found n1.Type = %v; n1.X.Type = %v", n1.Type(), n1.X.Type())
230
+ }
231
+ n = n1.X
232
+ continue
233
+ }
234
+ if n1.Op() == ir.OCONVIFACE {
235
+ n = n1.X
236
+ continue
237
+ }
238
+ case *ir.InlinedCallExpr:
239
+ if n1.Op() == ir.OINLCALL {
240
+ n = n1.SingleResult()
241
+ continue
242
+ }
243
+ case *ir.ParenExpr:
244
+ n = n1.X
245
+ continue
246
+ case *ir.TypeAssertExpr:
247
+ n = n1.X
248
+ continue
249
+ }
250
+ break
251
+ }
252
+
253
+ if n.Op() != ir.ONAME {
254
+ return nil
255
+ }
256
+
257
+ name := n.(*ir.Name).Canonical()
258
+ if name.Class != ir.PAUTO {
259
+ return nil
260
+ }
261
+
262
+ if name.Op() != ir.ONAME {
263
+ base.FatalfAt(name.Pos(), "name.Op = %v; want = ONAME", n.Op())
264
+ }
265
+
266
+ // name.Curfn must be set, as we checked name.Class != ir.PAUTO before.
267
+ if name.Curfn == nil {
268
+ base.FatalfAt(name.Pos(), "name.Curfn = nil; want not nil")
269
+ }
270
+
271
+ if name.Addrtaken() {
272
+ return nil // conservatively assume it's reassigned with a different type indirectly
273
+ }
274
+
275
+ if _, ok := seen[name]; ok {
276
+ return &noType // Already analyzed assignments to name, no need to do that twice.
277
+ }
278
+ seen[name] = struct{}{}
279
+
280
+ if concreteTypeDebug {
281
+ base.Warn("concreteType1(%v): analyzing assignments to %v", nn, name)
282
+ }
283
+
284
+ var typ *types.Type
285
+ for _, v := range s.assignments(name) {
286
+ var t *types.Type
287
+ switch v := v.(type) {
288
+ case *types.Type:
289
+ t = v
290
+ case ir.Node:
291
+ t = concreteType1(s, v, seen)
292
+ if t == &noType {
293
+ continue
294
+ }
295
+ }
296
+ if t == nil {
297
+ return nil // unknown concrete type
298
+ }
299
+
300
+ // Methods are only declared on named types, and each named type
301
+ // is represented by a unique [*types.Type], thus pointer comparison
302
+ // is fine here.
303
+ //
304
+ // The only scenario where [types.IdenticalStrict] could help here is with
305
+ // unnamed struct types that embed another type (e.g. foo = struct { Impl }{}).
306
+ // However, such patterns are uncommon and not worth the additional complexity
307
+ // in the devirtualizer.
308
+ if typ != nil && typ != t {
309
+ return nil // assigned with a different type
310
+ }
311
+
312
+ typ = t
313
+ }
314
+
315
+ if typ == nil {
316
+ // Variable either declared with zero value, or only assigned with nil.
317
+ return &noType
318
+ }
319
+
320
+ return typ
321
+ }
322
+
323
+ // assignment can be one of:
324
+ // - nil - assignment from an interface type.
325
+ // - *types.Type - assignment from a concrete type (non-interface).
326
+ // - ir.Node - assignment from an ir.Node.
327
+ //
328
+ // In most cases assignment should be an [ir.Node], but in cases where we
329
+ // do not follow the data-flow, we return either a concrete type (*types.Type) or a nil.
330
+ // For example in range over a slice, if the slice elem is of an interface type, then we return
331
+ // a nil, otherwise the elem's concrete type (We do so because we do not analyze assignment to the
332
+ // slice being ranged-over).
333
+ type assignment any
334
+
335
+ // State holds precomputed state for use in [StaticCall].
336
+ type State struct {
337
+ // ifaceAssignments maps interface variables to all their assignments
338
+ // defined inside functions stored in the analyzedFuncs set.
339
+ // Note: it does not include direct assignments to nil.
340
+ ifaceAssignments map[*ir.Name][]assignment
341
+
342
+ // ifaceCallExprAssigns stores every [*ir.CallExpr], which has an interface
343
+ // result, that is assigned to a variable.
344
+ ifaceCallExprAssigns map[*ir.CallExpr][]ifaceAssignRef
345
+
346
+ // analyzedFuncs is a set of Funcs that were analyzed for iface assignments.
347
+ analyzedFuncs map[*ir.Func]struct{}
348
+ }
349
+
350
+ type ifaceAssignRef struct {
351
+ name *ir.Name // ifaceAssignments[name]
352
+ assignmentIndex int // ifaceAssignments[name][assignmentIndex]
353
+ returnIndex int // (*ir.CallExpr).Result(returnIndex)
354
+ }
355
+
356
+ // InlinedCall updates the [State] to take into account a newly inlined call.
357
+ func (s *State) InlinedCall(fun *ir.Func, origCall *ir.CallExpr, inlinedCall *ir.InlinedCallExpr) {
358
+ if _, ok := s.analyzedFuncs[fun]; !ok {
359
+ // Full analyze has not been yet executed for the provided function, so we can skip it for now.
360
+ // When no devirtualization happens in a function, it is unnecessary to analyze it.
361
+ return
362
+ }
363
+
364
+ // Analyze assignments in the newly inlined function.
365
+ s.analyze(inlinedCall.Init())
366
+ s.analyze(inlinedCall.Body)
367
+
368
+ refs, ok := s.ifaceCallExprAssigns[origCall]
369
+ if !ok {
370
+ return
371
+ }
372
+ delete(s.ifaceCallExprAssigns, origCall)
373
+
374
+ // Update assignments to reference the new ReturnVars of the inlined call.
375
+ for _, ref := range refs {
376
+ vt := &s.ifaceAssignments[ref.name][ref.assignmentIndex]
377
+ if *vt != nil {
378
+ base.Fatalf("unexpected non-nil assignment")
379
+ }
380
+ if concreteTypeDebug {
381
+ base.Warn(
382
+ "InlinedCall(%v, %v): replacing interface node in (%v,%v) to %v (typ %v)",
383
+ origCall, inlinedCall, ref.name, ref.assignmentIndex,
384
+ inlinedCall.ReturnVars[ref.returnIndex],
385
+ inlinedCall.ReturnVars[ref.returnIndex].Type(),
386
+ )
387
+ }
388
+
389
+ // Update ifaceAssignments with an ir.Node from the inlined function’s ReturnVars.
390
+ // This may enable future devirtualization of calls that reference ref.name.
391
+ // We will get calls to [StaticCall] from the interleaved package,
392
+ // to try devirtualize such calls afterwards.
393
+ *vt = inlinedCall.ReturnVars[ref.returnIndex]
394
+ }
395
+ }
396
+
397
+ // assignments returns all assignments to n.
398
+ func (s *State) assignments(n *ir.Name) []assignment {
399
+ fun := n.Curfn
400
+ if fun == nil {
401
+ base.FatalfAt(n.Pos(), "n.Curfn = <nil>")
402
+ }
403
+ if n.Class != ir.PAUTO {
404
+ base.FatalfAt(n.Pos(), "n.Class = %v; want = PAUTO", n.Class)
405
+ }
406
+
407
+ if !n.Type().IsInterface() {
408
+ base.FatalfAt(n.Pos(), "name passed to assignments is not of an interface type: %v", n.Type())
409
+ }
410
+
411
+ // Analyze assignments in func, if not analyzed before.
412
+ if _, ok := s.analyzedFuncs[fun]; !ok {
413
+ if concreteTypeDebug {
414
+ base.Warn("assignments(): analyzing assignments in %v func", fun)
415
+ }
416
+ if s.analyzedFuncs == nil {
417
+ s.ifaceAssignments = make(map[*ir.Name][]assignment)
418
+ s.ifaceCallExprAssigns = make(map[*ir.CallExpr][]ifaceAssignRef)
419
+ s.analyzedFuncs = make(map[*ir.Func]struct{})
420
+ }
421
+ s.analyzedFuncs[fun] = struct{}{}
422
+ s.analyze(fun.Init())
423
+ s.analyze(fun.Body)
424
+ }
425
+
426
+ return s.ifaceAssignments[n]
427
+ }
428
+
429
+ // analyze analyzes every assignment to interface variables in nodes, updating [State].
430
+ func (s *State) analyze(nodes ir.Nodes) {
431
+ assign := func(name ir.Node, assignment assignment) (*ir.Name, int) {
432
+ if name == nil || name.Op() != ir.ONAME || ir.IsBlank(name) {
433
+ return nil, -1
434
+ }
435
+
436
+ n, ok := ir.OuterValue(name).(*ir.Name)
437
+ if !ok || n.Curfn == nil {
438
+ return nil, -1
439
+ }
440
+
441
+ // Do not track variables that are not of interface types.
442
+ // For devirtualization they are unnecessary, we will not even look them up.
443
+ if !n.Type().IsInterface() {
444
+ return nil, -1
445
+ }
446
+
447
+ n = n.Canonical()
448
+ if n.Op() != ir.ONAME {
449
+ base.FatalfAt(n.Pos(), "n.Op = %v; want = ONAME", n.Op())
450
+ }
451
+ if n.Class != ir.PAUTO {
452
+ return nil, -1
453
+ }
454
+
455
+ switch a := assignment.(type) {
456
+ case nil:
457
+ case *types.Type:
458
+ if a != nil && a.IsInterface() {
459
+ assignment = nil // non-concrete type
460
+ }
461
+ case ir.Node:
462
+ // nil assignment, we can safely ignore them, see [StaticCall].
463
+ if ir.IsNil(a) {
464
+ return nil, -1
465
+ }
466
+ default:
467
+ base.Fatalf("unexpected type: %v", assignment)
468
+ }
469
+
470
+ if concreteTypeDebug {
471
+ base.Warn("analyze(): assignment found %v = %v", name, assignment)
472
+ }
473
+
474
+ s.ifaceAssignments[n] = append(s.ifaceAssignments[n], assignment)
475
+ return n, len(s.ifaceAssignments[n]) - 1
476
+ }
477
+
478
+ var do func(n ir.Node)
479
+ do = func(n ir.Node) {
480
+ switch n.Op() {
481
+ case ir.OAS:
482
+ n := n.(*ir.AssignStmt)
483
+ if rhs := n.Y; rhs != nil {
484
+ for {
485
+ if r, ok := rhs.(*ir.ParenExpr); ok {
486
+ rhs = r.X
487
+ continue
488
+ }
489
+ break
490
+ }
491
+ if call, ok := rhs.(*ir.CallExpr); ok && call.Fun != nil {
492
+ retTyp := call.Fun.Type().Results()[0].Type
493
+ n, idx := assign(n.X, retTyp)
494
+ if n != nil && retTyp.IsInterface() {
495
+ // We have a call expression, that returns an interface, store it for later evaluation.
496
+ // In case this func gets inlined later, we will update the assignment (added before)
497
+ // with a reference to ReturnVars, see [State.InlinedCall], which might allow for future devirtualizing of n.X.
498
+ s.ifaceCallExprAssigns[call] = append(s.ifaceCallExprAssigns[call], ifaceAssignRef{n, idx, 0})
499
+ }
500
+ } else {
501
+ assign(n.X, rhs)
502
+ }
503
+ }
504
+ case ir.OAS2:
505
+ n := n.(*ir.AssignListStmt)
506
+ for i, p := range n.Lhs {
507
+ if n.Rhs[i] != nil {
508
+ assign(p, n.Rhs[i])
509
+ }
510
+ }
511
+ case ir.OAS2DOTTYPE:
512
+ n := n.(*ir.AssignListStmt)
513
+ if n.Rhs[0] == nil {
514
+ base.FatalfAt(n.Pos(), "n.Rhs[0] == nil; n = %v", n)
515
+ }
516
+ assign(n.Lhs[0], n.Rhs[0])
517
+ assign(n.Lhs[1], nil) // boolean does not have methods to devirtualize
518
+ case ir.OAS2MAPR, ir.OAS2RECV, ir.OSELRECV2:
519
+ n := n.(*ir.AssignListStmt)
520
+ if n.Rhs[0] == nil {
521
+ base.FatalfAt(n.Pos(), "n.Rhs[0] == nil; n = %v", n)
522
+ }
523
+ assign(n.Lhs[0], n.Rhs[0].Type())
524
+ assign(n.Lhs[1], nil) // boolean does not have methods to devirtualize
525
+ case ir.OAS2FUNC:
526
+ n := n.(*ir.AssignListStmt)
527
+ rhs := n.Rhs[0]
528
+ for {
529
+ if r, ok := rhs.(*ir.ParenExpr); ok {
530
+ rhs = r.X
531
+ continue
532
+ }
533
+ break
534
+ }
535
+ if call, ok := rhs.(*ir.CallExpr); ok {
536
+ for i, p := range n.Lhs {
537
+ retTyp := call.Fun.Type().Results()[i].Type
538
+ n, idx := assign(p, retTyp)
539
+ if n != nil && retTyp.IsInterface() {
540
+ // We have a call expression, that returns an interface, store it for later evaluation.
541
+ // In case this func gets inlined later, we will update the assignment (added before)
542
+ // with a reference to ReturnVars, see [State.InlinedCall], which might allow for future devirtualizing of n.X.
543
+ s.ifaceCallExprAssigns[call] = append(s.ifaceCallExprAssigns[call], ifaceAssignRef{n, idx, i})
544
+ }
545
+ }
546
+ } else if call, ok := rhs.(*ir.InlinedCallExpr); ok {
547
+ for i, p := range n.Lhs {
548
+ assign(p, call.ReturnVars[i])
549
+ }
550
+ } else {
551
+ base.FatalfAt(n.Pos(), "unexpected type %T in OAS2FUNC Rhs[0]", call)
552
+ }
553
+ case ir.ORANGE:
554
+ n := n.(*ir.RangeStmt)
555
+ xTyp := n.X.Type()
556
+
557
+ // Range over an array pointer.
558
+ if xTyp.IsPtr() && xTyp.Elem().IsArray() {
559
+ xTyp = xTyp.Elem()
560
+ }
561
+
562
+ if xTyp.IsArray() || xTyp.IsSlice() {
563
+ assign(n.Key, nil) // integer does not have methods to devirtualize
564
+ assign(n.Value, xTyp.Elem())
565
+ } else if xTyp.IsChan() {
566
+ assign(n.Key, xTyp.Elem())
567
+ base.AssertfAt(n.Value == nil, n.Pos(), "n.Value != nil in range over chan")
568
+ } else if xTyp.IsMap() {
569
+ assign(n.Key, xTyp.Key())
570
+ assign(n.Value, xTyp.Elem())
571
+ } else if xTyp.IsInteger() || xTyp.IsString() {
572
+ // Range over int/string, results do not have methods, so nothing to devirtualize.
573
+ assign(n.Key, nil)
574
+ assign(n.Value, nil)
575
+ } else {
576
+ // We will not reach here in case of a range-over-func, as it is
577
+ // rewritten to function calls in the noder package.
578
+ base.FatalfAt(n.Pos(), "range over unexpected type %v", n.X.Type())
579
+ }
580
+ case ir.OSWITCH:
581
+ n := n.(*ir.SwitchStmt)
582
+ if guard, ok := n.Tag.(*ir.TypeSwitchGuard); ok {
583
+ for _, v := range n.Cases {
584
+ if v.Var == nil {
585
+ base.Assert(guard.Tag == nil)
586
+ continue
587
+ }
588
+ assign(v.Var, guard.X)
589
+ }
590
+ }
591
+ case ir.OCLOSURE:
592
+ n := n.(*ir.ClosureExpr)
593
+ if _, ok := s.analyzedFuncs[n.Func]; !ok {
594
+ s.analyzedFuncs[n.Func] = struct{}{}
595
+ ir.Visit(n.Func, do)
596
+ }
597
+ }
598
+ }
599
+ ir.VisitList(nodes, do)
600
+ }
go/src/cmd/compile/internal/devirtualize/pgo.go ADDED
@@ -0,0 +1,829 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2023 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 devirtualize
6
+
7
+ import (
8
+ "cmd/compile/internal/base"
9
+ "cmd/compile/internal/inline"
10
+ "cmd/compile/internal/ir"
11
+ "cmd/compile/internal/logopt"
12
+ "cmd/compile/internal/pgoir"
13
+ "cmd/compile/internal/typecheck"
14
+ "cmd/compile/internal/types"
15
+ "cmd/internal/obj"
16
+ "cmd/internal/src"
17
+ "encoding/json"
18
+ "fmt"
19
+ "os"
20
+ "strings"
21
+ )
22
+
23
+ // CallStat summarizes a single call site.
24
+ //
25
+ // This is used only for debug logging.
26
+ type CallStat struct {
27
+ Pkg string // base.Ctxt.Pkgpath
28
+ Pos string // file:line:col of call.
29
+
30
+ Caller string // Linker symbol name of calling function.
31
+
32
+ // Direct or indirect call.
33
+ Direct bool
34
+
35
+ // For indirect calls, interface call or other indirect function call.
36
+ Interface bool
37
+
38
+ // Total edge weight from this call site.
39
+ Weight int64
40
+
41
+ // Hottest callee from this call site, regardless of type
42
+ // compatibility.
43
+ Hottest string
44
+ HottestWeight int64
45
+
46
+ // Devirtualized callee if != "".
47
+ //
48
+ // Note that this may be different than Hottest because we apply
49
+ // type-check restrictions, which helps distinguish multiple calls on
50
+ // the same line.
51
+ Devirtualized string
52
+ DevirtualizedWeight int64
53
+ }
54
+
55
+ // ProfileGuided performs call devirtualization of indirect calls based on
56
+ // profile information.
57
+ //
58
+ // Specifically, it performs conditional devirtualization of interface calls or
59
+ // function value calls for the hottest callee.
60
+ //
61
+ // That is, for interface calls it performs a transformation like:
62
+ //
63
+ // type Iface interface {
64
+ // Foo()
65
+ // }
66
+ //
67
+ // type Concrete struct{}
68
+ //
69
+ // func (Concrete) Foo() {}
70
+ //
71
+ // func foo(i Iface) {
72
+ // i.Foo()
73
+ // }
74
+ //
75
+ // to:
76
+ //
77
+ // func foo(i Iface) {
78
+ // if c, ok := i.(Concrete); ok {
79
+ // c.Foo()
80
+ // } else {
81
+ // i.Foo()
82
+ // }
83
+ // }
84
+ //
85
+ // For function value calls it performs a transformation like:
86
+ //
87
+ // func Concrete() {}
88
+ //
89
+ // func foo(fn func()) {
90
+ // fn()
91
+ // }
92
+ //
93
+ // to:
94
+ //
95
+ // func foo(fn func()) {
96
+ // if internal/abi.FuncPCABIInternal(fn) == internal/abi.FuncPCABIInternal(Concrete) {
97
+ // Concrete()
98
+ // } else {
99
+ // fn()
100
+ // }
101
+ // }
102
+ //
103
+ // The primary benefit of this transformation is enabling inlining of the
104
+ // direct call.
105
+ func ProfileGuided(fn *ir.Func, p *pgoir.Profile) {
106
+ ir.CurFunc = fn
107
+
108
+ name := ir.LinkFuncName(fn)
109
+
110
+ var jsonW *json.Encoder
111
+ if base.Debug.PGODebug >= 3 {
112
+ jsonW = json.NewEncoder(os.Stdout)
113
+ }
114
+
115
+ var edit func(n ir.Node) ir.Node
116
+ edit = func(n ir.Node) ir.Node {
117
+ if n == nil {
118
+ return n
119
+ }
120
+
121
+ ir.EditChildren(n, edit)
122
+
123
+ call, ok := n.(*ir.CallExpr)
124
+ if !ok {
125
+ return n
126
+ }
127
+
128
+ var stat *CallStat
129
+ if base.Debug.PGODebug >= 3 {
130
+ // Statistics about every single call. Handy for external data analysis.
131
+ //
132
+ // TODO(prattmic): Log via logopt?
133
+ stat = constructCallStat(p, fn, name, call)
134
+ if stat != nil {
135
+ defer func() {
136
+ jsonW.Encode(&stat)
137
+ }()
138
+ }
139
+ }
140
+
141
+ op := call.Op()
142
+ if op != ir.OCALLFUNC && op != ir.OCALLINTER {
143
+ return n
144
+ }
145
+
146
+ if base.Debug.PGODebug >= 2 {
147
+ fmt.Printf("%v: PGO devirtualize considering call %v\n", ir.Line(call), call)
148
+ }
149
+
150
+ if call.GoDefer {
151
+ if base.Debug.PGODebug >= 2 {
152
+ fmt.Printf("%v: can't PGO devirtualize go/defer call %v\n", ir.Line(call), call)
153
+ }
154
+ return n
155
+ }
156
+
157
+ var newNode ir.Node
158
+ var callee *ir.Func
159
+ var weight int64
160
+ switch op {
161
+ case ir.OCALLFUNC:
162
+ newNode, callee, weight = maybeDevirtualizeFunctionCall(p, fn, call)
163
+ case ir.OCALLINTER:
164
+ newNode, callee, weight = maybeDevirtualizeInterfaceCall(p, fn, call)
165
+ default:
166
+ panic("unreachable")
167
+ }
168
+
169
+ if newNode == nil {
170
+ return n
171
+ }
172
+
173
+ if stat != nil {
174
+ stat.Devirtualized = ir.LinkFuncName(callee)
175
+ stat.DevirtualizedWeight = weight
176
+ }
177
+
178
+ return newNode
179
+ }
180
+
181
+ ir.EditChildren(fn, edit)
182
+ }
183
+
184
+ // Devirtualize interface call if possible and eligible. Returns the new
185
+ // ir.Node if call was devirtualized, and if so also the callee and weight of
186
+ // the devirtualized edge.
187
+ func maybeDevirtualizeInterfaceCall(p *pgoir.Profile, fn *ir.Func, call *ir.CallExpr) (ir.Node, *ir.Func, int64) {
188
+ if base.Debug.PGODevirtualize < 1 {
189
+ return nil, nil, 0
190
+ }
191
+
192
+ // Bail if we do not have a hot callee.
193
+ callee, weight := findHotConcreteInterfaceCallee(p, fn, call)
194
+ if callee == nil {
195
+ return nil, nil, 0
196
+ }
197
+ // Bail if we do not have a Type node for the hot callee.
198
+ ctyp := methodRecvType(callee)
199
+ if ctyp == nil {
200
+ return nil, nil, 0
201
+ }
202
+ // Bail if we know for sure it won't inline.
203
+ if !shouldPGODevirt(callee) {
204
+ return nil, nil, 0
205
+ }
206
+ // Bail if de-selected by PGO Hash.
207
+ if !base.PGOHash.MatchPosWithInfo(call.Pos(), "devirt", nil) {
208
+ return nil, nil, 0
209
+ }
210
+
211
+ return rewriteInterfaceCall(call, fn, callee, ctyp), callee, weight
212
+ }
213
+
214
+ // Devirtualize an indirect function call if possible and eligible. Returns the new
215
+ // ir.Node if call was devirtualized, and if so also the callee and weight of
216
+ // the devirtualized edge.
217
+ func maybeDevirtualizeFunctionCall(p *pgoir.Profile, fn *ir.Func, call *ir.CallExpr) (ir.Node, *ir.Func, int64) {
218
+ if base.Debug.PGODevirtualize < 2 {
219
+ return nil, nil, 0
220
+ }
221
+
222
+ // Bail if this is a direct call; no devirtualization necessary.
223
+ callee := pgoir.DirectCallee(call.Fun)
224
+ if callee != nil {
225
+ return nil, nil, 0
226
+ }
227
+
228
+ // Bail if we do not have a hot callee.
229
+ callee, weight := findHotConcreteFunctionCallee(p, fn, call)
230
+ if callee == nil {
231
+ return nil, nil, 0
232
+ }
233
+
234
+ // TODO(go.dev/issue/61577): Closures need the closure context passed
235
+ // via the context register. That requires extra plumbing that we
236
+ // haven't done yet.
237
+ if callee.OClosure != nil {
238
+ if base.Debug.PGODebug >= 3 {
239
+ fmt.Printf("callee %s is a closure, skipping\n", ir.FuncName(callee))
240
+ }
241
+ return nil, nil, 0
242
+ }
243
+ // runtime.memhash_varlen does not look like a closure, but it uses
244
+ // internal/runtime/sys.GetClosurePtr to access data encoded by
245
+ // callers, which are generated by
246
+ // cmd/compile/internal/reflectdata.genhash.
247
+ if callee.Sym().Pkg.Path == "runtime" && callee.Sym().Name == "memhash_varlen" {
248
+ if base.Debug.PGODebug >= 3 {
249
+ fmt.Printf("callee %s is a closure (runtime.memhash_varlen), skipping\n", ir.FuncName(callee))
250
+ }
251
+ return nil, nil, 0
252
+ }
253
+ // TODO(prattmic): We don't properly handle methods as callees in two
254
+ // different dimensions:
255
+ //
256
+ // 1. Method expressions. e.g.,
257
+ //
258
+ // var fn func(*os.File, []byte) (int, error) = (*os.File).Read
259
+ //
260
+ // In this case, typ will report *os.File as the receiver while
261
+ // ctyp reports it as the first argument. types.Identical ignores
262
+ // receiver parameters, so it treats these as different, even though
263
+ // they are still call compatible.
264
+ //
265
+ // 2. Method values. e.g.,
266
+ //
267
+ // var f *os.File
268
+ // var fn func([]byte) (int, error) = f.Read
269
+ //
270
+ // types.Identical will treat these as compatible (since receiver
271
+ // parameters are ignored). However, in this case, we do not call
272
+ // (*os.File).Read directly. Instead, f is stored in closure context
273
+ // and we call the wrapper (*os.File).Read-fm. However, runtime/pprof
274
+ // hides wrappers from profiles, making it appear that there is a call
275
+ // directly to the method. We could recognize this pattern return the
276
+ // wrapper rather than the method.
277
+ //
278
+ // N.B. perf profiles will report wrapper symbols directly, so
279
+ // ideally we should support direct wrapper references as well.
280
+ if callee.Type().Recv() != nil {
281
+ if base.Debug.PGODebug >= 3 {
282
+ fmt.Printf("callee %s is a method, skipping\n", ir.FuncName(callee))
283
+ }
284
+ return nil, nil, 0
285
+ }
286
+
287
+ // Bail if we know for sure it won't inline.
288
+ if !shouldPGODevirt(callee) {
289
+ return nil, nil, 0
290
+ }
291
+ // Bail if de-selected by PGO Hash.
292
+ if !base.PGOHash.MatchPosWithInfo(call.Pos(), "devirt", nil) {
293
+ return nil, nil, 0
294
+ }
295
+
296
+ return rewriteFunctionCall(call, fn, callee), callee, weight
297
+ }
298
+
299
+ // shouldPGODevirt checks if we should perform PGO devirtualization to the
300
+ // target function.
301
+ //
302
+ // PGO devirtualization is most valuable when the callee is inlined, so if it
303
+ // won't inline we can skip devirtualizing.
304
+ func shouldPGODevirt(fn *ir.Func) bool {
305
+ var reason string
306
+ if base.Flag.LowerM > 1 || logopt.Enabled() {
307
+ defer func() {
308
+ if reason != "" {
309
+ if base.Flag.LowerM > 1 {
310
+ fmt.Printf("%v: should not PGO devirtualize %v: %s\n", ir.Line(fn), ir.FuncName(fn), reason)
311
+ }
312
+ if logopt.Enabled() {
313
+ logopt.LogOpt(fn.Pos(), ": should not PGO devirtualize function", "pgoir-devirtualize", ir.FuncName(fn), reason)
314
+ }
315
+ }
316
+ }()
317
+ }
318
+
319
+ reason = inline.InlineImpossible(fn)
320
+ if reason != "" {
321
+ return false
322
+ }
323
+
324
+ // TODO(prattmic): checking only InlineImpossible is very conservative,
325
+ // primarily excluding only functions with pragmas. We probably want to
326
+ // move in either direction. Either:
327
+ //
328
+ // 1. Don't even bother to check InlineImpossible, as it affects so few
329
+ // functions.
330
+ //
331
+ // 2. Or consider the function body (notably cost) to better determine
332
+ // if the function will actually inline.
333
+
334
+ return true
335
+ }
336
+
337
+ // constructCallStat builds an initial CallStat describing this call, for
338
+ // logging. If the call is devirtualized, the devirtualization fields should be
339
+ // updated.
340
+ func constructCallStat(p *pgoir.Profile, fn *ir.Func, name string, call *ir.CallExpr) *CallStat {
341
+ switch call.Op() {
342
+ case ir.OCALLFUNC, ir.OCALLINTER, ir.OCALLMETH:
343
+ default:
344
+ // We don't care about logging builtin functions.
345
+ return nil
346
+ }
347
+
348
+ stat := CallStat{
349
+ Pkg: base.Ctxt.Pkgpath,
350
+ Pos: ir.Line(call),
351
+ Caller: name,
352
+ }
353
+
354
+ offset := pgoir.NodeLineOffset(call, fn)
355
+
356
+ hotter := func(e *pgoir.IREdge) bool {
357
+ if stat.Hottest == "" {
358
+ return true
359
+ }
360
+ if e.Weight != stat.HottestWeight {
361
+ return e.Weight > stat.HottestWeight
362
+ }
363
+ // If weight is the same, arbitrarily sort lexicographally, as
364
+ // findHotConcreteCallee does.
365
+ return e.Dst.Name() < stat.Hottest
366
+ }
367
+
368
+ callerNode := p.WeightedCG.IRNodes[name]
369
+ if callerNode == nil {
370
+ return nil
371
+ }
372
+
373
+ // Sum of all edges from this callsite, regardless of callee.
374
+ // For direct calls, this should be the same as the single edge
375
+ // weight (except for multiple calls on one line, which we
376
+ // can't distinguish).
377
+ for _, edge := range callerNode.OutEdges {
378
+ if edge.CallSiteOffset != offset {
379
+ continue
380
+ }
381
+ stat.Weight += edge.Weight
382
+ if hotter(edge) {
383
+ stat.HottestWeight = edge.Weight
384
+ stat.Hottest = edge.Dst.Name()
385
+ }
386
+ }
387
+
388
+ switch call.Op() {
389
+ case ir.OCALLFUNC:
390
+ stat.Interface = false
391
+
392
+ callee := pgoir.DirectCallee(call.Fun)
393
+ if callee != nil {
394
+ stat.Direct = true
395
+ if stat.Hottest == "" {
396
+ stat.Hottest = ir.LinkFuncName(callee)
397
+ }
398
+ } else {
399
+ stat.Direct = false
400
+ }
401
+ case ir.OCALLINTER:
402
+ stat.Direct = false
403
+ stat.Interface = true
404
+ case ir.OCALLMETH:
405
+ base.FatalfAt(call.Pos(), "OCALLMETH missed by typecheck")
406
+ }
407
+
408
+ return &stat
409
+ }
410
+
411
+ // copyInputs copies the inputs to a call: the receiver (for interface calls)
412
+ // or function value (for function value calls) and the arguments. These
413
+ // expressions are evaluated once and assigned to temporaries.
414
+ //
415
+ // The assignment statement is added to init and the copied receiver/fn
416
+ // expression and copied arguments expressions are returned.
417
+ func copyInputs(curfn *ir.Func, pos src.XPos, recvOrFn ir.Node, args []ir.Node, init *ir.Nodes) (ir.Node, []ir.Node) {
418
+ // Evaluate receiver/fn and argument expressions. The receiver/fn is
419
+ // used twice but we don't want to cause side effects twice. The
420
+ // arguments are used in two different calls and we can't trivially
421
+ // copy them.
422
+ //
423
+ // recvOrFn must be first in the assignment list as its side effects
424
+ // must be ordered before argument side effects.
425
+ var lhs, rhs []ir.Node
426
+ newRecvOrFn := typecheck.TempAt(pos, curfn, recvOrFn.Type())
427
+ lhs = append(lhs, newRecvOrFn)
428
+ rhs = append(rhs, recvOrFn)
429
+
430
+ for _, arg := range args {
431
+ argvar := typecheck.TempAt(pos, curfn, arg.Type())
432
+
433
+ lhs = append(lhs, argvar)
434
+ rhs = append(rhs, arg)
435
+ }
436
+
437
+ asList := ir.NewAssignListStmt(pos, ir.OAS2, lhs, rhs)
438
+ init.Append(typecheck.Stmt(asList))
439
+
440
+ return newRecvOrFn, lhs[1:]
441
+ }
442
+
443
+ // retTemps returns a slice of temporaries to be used for storing result values from call.
444
+ func retTemps(curfn *ir.Func, pos src.XPos, call *ir.CallExpr) []ir.Node {
445
+ sig := call.Fun.Type()
446
+ var retvars []ir.Node
447
+ for _, ret := range sig.Results() {
448
+ retvars = append(retvars, typecheck.TempAt(pos, curfn, ret.Type))
449
+ }
450
+ return retvars
451
+ }
452
+
453
+ // condCall returns an ir.InlinedCallExpr that performs a call to thenCall if
454
+ // cond is true and elseCall if cond is false. The return variables of the
455
+ // InlinedCallExpr evaluate to the return values from the call.
456
+ func condCall(curfn *ir.Func, pos src.XPos, cond ir.Node, thenCall, elseCall *ir.CallExpr, init ir.Nodes) *ir.InlinedCallExpr {
457
+ // Doesn't matter whether we use thenCall or elseCall, they must have
458
+ // the same return types.
459
+ retvars := retTemps(curfn, pos, thenCall)
460
+
461
+ var thenBlock, elseBlock ir.Nodes
462
+ if len(retvars) == 0 {
463
+ thenBlock.Append(thenCall)
464
+ elseBlock.Append(elseCall)
465
+ } else {
466
+ // Copy slice so edits in one location don't affect another.
467
+ thenRet := append([]ir.Node(nil), retvars...)
468
+ thenAsList := ir.NewAssignListStmt(pos, ir.OAS2, thenRet, []ir.Node{thenCall})
469
+ thenBlock.Append(typecheck.Stmt(thenAsList))
470
+
471
+ elseRet := append([]ir.Node(nil), retvars...)
472
+ elseAsList := ir.NewAssignListStmt(pos, ir.OAS2, elseRet, []ir.Node{elseCall})
473
+ elseBlock.Append(typecheck.Stmt(elseAsList))
474
+ }
475
+
476
+ nif := ir.NewIfStmt(pos, cond, thenBlock, elseBlock)
477
+ nif.SetInit(init)
478
+ nif.Likely = true
479
+
480
+ body := []ir.Node{typecheck.Stmt(nif)}
481
+
482
+ // This isn't really an inlined call of course, but InlinedCallExpr
483
+ // makes handling reassignment of return values easier.
484
+ res := ir.NewInlinedCallExpr(pos, body, retvars)
485
+ res.SetType(thenCall.Type())
486
+ res.SetTypecheck(1)
487
+ return res
488
+ }
489
+
490
+ // rewriteInterfaceCall devirtualizes the given interface call using a direct
491
+ // method call to concretetyp.
492
+ func rewriteInterfaceCall(call *ir.CallExpr, curfn, callee *ir.Func, concretetyp *types.Type) ir.Node {
493
+ if base.Flag.LowerM != 0 {
494
+ fmt.Printf("%v: PGO devirtualizing interface call %v to %v\n", ir.Line(call), call.Fun, callee)
495
+ }
496
+
497
+ // We generate an OINCALL of:
498
+ //
499
+ // var recv Iface
500
+ //
501
+ // var arg1 A1
502
+ // var argN AN
503
+ //
504
+ // var ret1 R1
505
+ // var retN RN
506
+ //
507
+ // recv, arg1, argN = recv expr, arg1 expr, argN expr
508
+ //
509
+ // t, ok := recv.(Concrete)
510
+ // if ok {
511
+ // ret1, retN = t.Method(arg1, ... argN)
512
+ // } else {
513
+ // ret1, retN = recv.Method(arg1, ... argN)
514
+ // }
515
+ //
516
+ // OINCALL retvars: ret1, ... retN
517
+ //
518
+ // This isn't really an inlined call of course, but InlinedCallExpr
519
+ // makes handling reassignment of return values easier.
520
+ //
521
+ // TODO(prattmic): This increases the size of the AST in the caller,
522
+ // making it less like to inline. We may want to compensate for this
523
+ // somehow.
524
+
525
+ sel := call.Fun.(*ir.SelectorExpr)
526
+ method := sel.Sel
527
+ pos := call.Pos()
528
+ init := ir.TakeInit(call)
529
+
530
+ recv, args := copyInputs(curfn, pos, sel.X, call.Args.Take(), &init)
531
+
532
+ // Copy slice so edits in one location don't affect another.
533
+ argvars := append([]ir.Node(nil), args...)
534
+ call.Args = argvars
535
+
536
+ tmpnode := typecheck.TempAt(base.Pos, curfn, concretetyp)
537
+ tmpok := typecheck.TempAt(base.Pos, curfn, types.Types[types.TBOOL])
538
+
539
+ assert := ir.NewTypeAssertExpr(pos, recv, concretetyp)
540
+
541
+ assertAsList := ir.NewAssignListStmt(pos, ir.OAS2, []ir.Node{tmpnode, tmpok}, []ir.Node{typecheck.Expr(assert)})
542
+ init.Append(typecheck.Stmt(assertAsList))
543
+
544
+ concreteCallee := typecheck.XDotMethod(pos, tmpnode, method, true)
545
+ // Copy slice so edits in one location don't affect another.
546
+ argvars = append([]ir.Node(nil), argvars...)
547
+ concreteCall := typecheck.Call(pos, concreteCallee, argvars, call.IsDDD).(*ir.CallExpr)
548
+
549
+ res := condCall(curfn, pos, tmpok, concreteCall, call, init)
550
+
551
+ if base.Debug.PGODebug >= 3 {
552
+ fmt.Printf("PGO devirtualizing interface call to %+v. After: %+v\n", concretetyp, res)
553
+ }
554
+
555
+ return res
556
+ }
557
+
558
+ // rewriteFunctionCall devirtualizes the given OCALLFUNC using a direct
559
+ // function call to callee.
560
+ func rewriteFunctionCall(call *ir.CallExpr, curfn, callee *ir.Func) ir.Node {
561
+ if base.Flag.LowerM != 0 {
562
+ fmt.Printf("%v: PGO devirtualizing function call %v to %v\n", ir.Line(call), call.Fun, callee)
563
+ }
564
+
565
+ // We generate an OINCALL of:
566
+ //
567
+ // var fn FuncType
568
+ //
569
+ // var arg1 A1
570
+ // var argN AN
571
+ //
572
+ // var ret1 R1
573
+ // var retN RN
574
+ //
575
+ // fn, arg1, argN = fn expr, arg1 expr, argN expr
576
+ //
577
+ // fnPC := internal/abi.FuncPCABIInternal(fn)
578
+ // concretePC := internal/abi.FuncPCABIInternal(concrete)
579
+ //
580
+ // if fnPC == concretePC {
581
+ // ret1, retN = concrete(arg1, ... argN) // Same closure context passed (TODO)
582
+ // } else {
583
+ // ret1, retN = fn(arg1, ... argN)
584
+ // }
585
+ //
586
+ // OINCALL retvars: ret1, ... retN
587
+ //
588
+ // This isn't really an inlined call of course, but InlinedCallExpr
589
+ // makes handling reassignment of return values easier.
590
+
591
+ pos := call.Pos()
592
+ init := ir.TakeInit(call)
593
+
594
+ fn, args := copyInputs(curfn, pos, call.Fun, call.Args.Take(), &init)
595
+
596
+ // Copy slice so edits in one location don't affect another.
597
+ argvars := append([]ir.Node(nil), args...)
598
+ call.Args = argvars
599
+
600
+ // FuncPCABIInternal takes an interface{}, emulate that. This is needed
601
+ // for to ensure we get the MAKEFACE we need for SSA.
602
+ fnIface := typecheck.Expr(ir.NewConvExpr(pos, ir.OCONV, types.Types[types.TINTER], fn))
603
+ calleeIface := typecheck.Expr(ir.NewConvExpr(pos, ir.OCONV, types.Types[types.TINTER], callee.Nname))
604
+
605
+ fnPC := ir.FuncPC(pos, fnIface, obj.ABIInternal)
606
+ concretePC := ir.FuncPC(pos, calleeIface, obj.ABIInternal)
607
+
608
+ pcEq := typecheck.Expr(ir.NewBinaryExpr(base.Pos, ir.OEQ, fnPC, concretePC))
609
+
610
+ // TODO(go.dev/issue/61577): Handle callees that a closures and need a
611
+ // copy of the closure context from call. For now, we skip callees that
612
+ // are closures in maybeDevirtualizeFunctionCall.
613
+ if callee.OClosure != nil {
614
+ base.Fatalf("Callee is a closure: %+v", callee)
615
+ }
616
+
617
+ // Copy slice so edits in one location don't affect another.
618
+ argvars = append([]ir.Node(nil), argvars...)
619
+ concreteCall := typecheck.Call(pos, callee.Nname, argvars, call.IsDDD).(*ir.CallExpr)
620
+
621
+ res := condCall(curfn, pos, pcEq, concreteCall, call, init)
622
+
623
+ if base.Debug.PGODebug >= 3 {
624
+ fmt.Printf("PGO devirtualizing function call to %+v. After: %+v\n", ir.FuncName(callee), res)
625
+ }
626
+
627
+ return res
628
+ }
629
+
630
+ // methodRecvType returns the type containing method fn. Returns nil if fn
631
+ // is not a method.
632
+ func methodRecvType(fn *ir.Func) *types.Type {
633
+ recv := fn.Nname.Type().Recv()
634
+ if recv == nil {
635
+ return nil
636
+ }
637
+ return recv.Type
638
+ }
639
+
640
+ // interfaceCallRecvTypeAndMethod returns the type and the method of the interface
641
+ // used in an interface call.
642
+ func interfaceCallRecvTypeAndMethod(call *ir.CallExpr) (*types.Type, *types.Sym) {
643
+ if call.Op() != ir.OCALLINTER {
644
+ base.Fatalf("Call isn't OCALLINTER: %+v", call)
645
+ }
646
+
647
+ sel, ok := call.Fun.(*ir.SelectorExpr)
648
+ if !ok {
649
+ base.Fatalf("OCALLINTER doesn't contain SelectorExpr: %+v", call)
650
+ }
651
+
652
+ return sel.X.Type(), sel.Sel
653
+ }
654
+
655
+ // findHotConcreteCallee returns the *ir.Func of the hottest callee of a call,
656
+ // if available, and its edge weight. extraFn can perform additional
657
+ // applicability checks on each candidate edge. If extraFn returns false,
658
+ // candidate will not be considered a valid callee candidate.
659
+ func findHotConcreteCallee(p *pgoir.Profile, caller *ir.Func, call *ir.CallExpr, extraFn func(callerName string, callOffset int, candidate *pgoir.IREdge) bool) (*ir.Func, int64) {
660
+ callerName := ir.LinkFuncName(caller)
661
+ callerNode := p.WeightedCG.IRNodes[callerName]
662
+ callOffset := pgoir.NodeLineOffset(call, caller)
663
+
664
+ if callerNode == nil {
665
+ return nil, 0
666
+ }
667
+
668
+ var hottest *pgoir.IREdge
669
+
670
+ // Returns true if e is hotter than hottest.
671
+ //
672
+ // Naively this is just e.Weight > hottest.Weight, but because OutEdges
673
+ // has arbitrary iteration order, we need to apply additional sort
674
+ // criteria when e.Weight == hottest.Weight to ensure we have stable
675
+ // selection.
676
+ hotter := func(e *pgoir.IREdge) bool {
677
+ if hottest == nil {
678
+ return true
679
+ }
680
+ if e.Weight != hottest.Weight {
681
+ return e.Weight > hottest.Weight
682
+ }
683
+
684
+ // Now e.Weight == hottest.Weight, we must select on other
685
+ // criteria.
686
+
687
+ // If only one edge has IR, prefer that one.
688
+ if (hottest.Dst.AST == nil) != (e.Dst.AST == nil) {
689
+ if e.Dst.AST != nil {
690
+ return true
691
+ }
692
+ return false
693
+ }
694
+
695
+ // Arbitrary, but the callee names will always differ. Select
696
+ // the lexicographically first callee.
697
+ return e.Dst.Name() < hottest.Dst.Name()
698
+ }
699
+
700
+ for _, e := range callerNode.OutEdges {
701
+ if e.CallSiteOffset != callOffset {
702
+ continue
703
+ }
704
+
705
+ if !hotter(e) {
706
+ // TODO(prattmic): consider total caller weight? i.e.,
707
+ // if the hottest callee is only 10% of the weight,
708
+ // maybe don't devirtualize? Similarly, if this is call
709
+ // is globally very cold, there is not much value in
710
+ // devirtualizing.
711
+ if base.Debug.PGODebug >= 2 {
712
+ fmt.Printf("%v: edge %s:%d -> %s (weight %d): too cold (hottest %d)\n", ir.Line(call), callerName, callOffset, e.Dst.Name(), e.Weight, hottest.Weight)
713
+ }
714
+ continue
715
+ }
716
+
717
+ if e.Dst.AST == nil {
718
+ // Destination isn't visible from this package
719
+ // compilation.
720
+ //
721
+ // We must assume it implements the interface.
722
+ //
723
+ // We still record this as the hottest callee so far
724
+ // because we only want to return the #1 hottest
725
+ // callee. If we skip this then we'd return the #2
726
+ // hottest callee.
727
+ if base.Debug.PGODebug >= 2 {
728
+ fmt.Printf("%v: edge %s:%d -> %s (weight %d) (missing IR): hottest so far\n", ir.Line(call), callerName, callOffset, e.Dst.Name(), e.Weight)
729
+ }
730
+ hottest = e
731
+ continue
732
+ }
733
+
734
+ if extraFn != nil && !extraFn(callerName, callOffset, e) {
735
+ continue
736
+ }
737
+
738
+ if base.Debug.PGODebug >= 2 {
739
+ fmt.Printf("%v: edge %s:%d -> %s (weight %d): hottest so far\n", ir.Line(call), callerName, callOffset, e.Dst.Name(), e.Weight)
740
+ }
741
+ hottest = e
742
+ }
743
+
744
+ if hottest == nil || hottest.Weight == 0 {
745
+ if base.Debug.PGODebug >= 2 {
746
+ fmt.Printf("%v: call %s:%d: no hot callee\n", ir.Line(call), callerName, callOffset)
747
+ }
748
+ return nil, 0
749
+ }
750
+
751
+ if base.Debug.PGODebug >= 2 {
752
+ fmt.Printf("%v: call %s:%d: hottest callee %s (weight %d)\n", ir.Line(call), callerName, callOffset, hottest.Dst.Name(), hottest.Weight)
753
+ }
754
+ return hottest.Dst.AST, hottest.Weight
755
+ }
756
+
757
+ // findHotConcreteInterfaceCallee returns the *ir.Func of the hottest callee of an
758
+ // interface call, if available, and its edge weight.
759
+ func findHotConcreteInterfaceCallee(p *pgoir.Profile, caller *ir.Func, call *ir.CallExpr) (*ir.Func, int64) {
760
+ inter, method := interfaceCallRecvTypeAndMethod(call)
761
+
762
+ return findHotConcreteCallee(p, caller, call, func(callerName string, callOffset int, e *pgoir.IREdge) bool {
763
+ ctyp := methodRecvType(e.Dst.AST)
764
+ if ctyp == nil {
765
+ // Not a method.
766
+ // TODO(prattmic): Support non-interface indirect calls.
767
+ if base.Debug.PGODebug >= 2 {
768
+ fmt.Printf("%v: edge %s:%d -> %s (weight %d): callee not a method\n", ir.Line(call), callerName, callOffset, e.Dst.Name(), e.Weight)
769
+ }
770
+ return false
771
+ }
772
+
773
+ // If ctyp doesn't implement inter it is most likely from a
774
+ // different call on the same line
775
+ if !typecheck.Implements(ctyp, inter) {
776
+ // TODO(prattmic): this is overly strict. Consider if
777
+ // ctyp is a partial implementation of an interface
778
+ // that gets embedded in types that complete the
779
+ // interface. It would still be OK to devirtualize a
780
+ // call to this method.
781
+ //
782
+ // What we'd need to do is check that the function
783
+ // pointer in the itab matches the method we want,
784
+ // rather than doing a full type assertion.
785
+ if base.Debug.PGODebug >= 2 {
786
+ why := typecheck.ImplementsExplain(ctyp, inter)
787
+ fmt.Printf("%v: edge %s:%d -> %s (weight %d): %v doesn't implement %v (%s)\n", ir.Line(call), callerName, callOffset, e.Dst.Name(), e.Weight, ctyp, inter, why)
788
+ }
789
+ return false
790
+ }
791
+
792
+ // If the method name is different it is most likely from a
793
+ // different call on the same line
794
+ if !strings.HasSuffix(e.Dst.Name(), "."+method.Name) {
795
+ if base.Debug.PGODebug >= 2 {
796
+ fmt.Printf("%v: edge %s:%d -> %s (weight %d): callee is a different method\n", ir.Line(call), callerName, callOffset, e.Dst.Name(), e.Weight)
797
+ }
798
+ return false
799
+ }
800
+
801
+ return true
802
+ })
803
+ }
804
+
805
+ // findHotConcreteFunctionCallee returns the *ir.Func of the hottest callee of an
806
+ // indirect function call, if available, and its edge weight.
807
+ func findHotConcreteFunctionCallee(p *pgoir.Profile, caller *ir.Func, call *ir.CallExpr) (*ir.Func, int64) {
808
+ typ := call.Fun.Type().Underlying()
809
+
810
+ return findHotConcreteCallee(p, caller, call, func(callerName string, callOffset int, e *pgoir.IREdge) bool {
811
+ ctyp := e.Dst.AST.Type().Underlying()
812
+
813
+ // If ctyp doesn't match typ it is most likely from a different
814
+ // call on the same line.
815
+ //
816
+ // Note that we are comparing underlying types, as different
817
+ // defined types are OK. e.g., a call to a value of type
818
+ // net/http.HandlerFunc can be devirtualized to a function with
819
+ // the same underlying type.
820
+ if !types.Identical(typ, ctyp) {
821
+ if base.Debug.PGODebug >= 2 {
822
+ fmt.Printf("%v: edge %s:%d -> %s (weight %d): %v doesn't match %v\n", ir.Line(call), callerName, callOffset, e.Dst.Name(), e.Weight, ctyp, typ)
823
+ }
824
+ return false
825
+ }
826
+
827
+ return true
828
+ })
829
+ }
go/src/cmd/compile/internal/devirtualize/pgo_test.go ADDED
@@ -0,0 +1,219 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2023 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 devirtualize
6
+
7
+ import (
8
+ "cmd/compile/internal/base"
9
+ "cmd/compile/internal/ir"
10
+ "cmd/compile/internal/pgoir"
11
+ "cmd/compile/internal/typecheck"
12
+ "cmd/compile/internal/types"
13
+ "cmd/internal/obj"
14
+ "cmd/internal/pgo"
15
+ "cmd/internal/src"
16
+ "cmd/internal/sys"
17
+ "testing"
18
+ )
19
+
20
+ func init() {
21
+ // These are the few constants that need to be initialized in order to use
22
+ // the types package without using the typecheck package by calling
23
+ // typecheck.InitUniverse() (the normal way to initialize the types package).
24
+ types.PtrSize = 8
25
+ types.RegSize = 8
26
+ types.MaxWidth = 1 << 50
27
+ base.Ctxt = &obj.Link{Arch: &obj.LinkArch{Arch: &sys.Arch{Alignment: 1, CanMergeLoads: true}}}
28
+ typecheck.InitUniverse()
29
+ base.Debug.PGODebug = 3
30
+ }
31
+
32
+ func makePos(b *src.PosBase, line, col uint) src.XPos {
33
+ return base.Ctxt.PosTable.XPos(src.MakePos(b, line, col))
34
+ }
35
+
36
+ type profileBuilder struct {
37
+ p *pgoir.Profile
38
+ }
39
+
40
+ func newProfileBuilder() *profileBuilder {
41
+ // findHotConcreteCallee only uses pgoir.Profile.WeightedCG, so we're
42
+ // going to take a shortcut and only construct that.
43
+ return &profileBuilder{
44
+ p: &pgoir.Profile{
45
+ WeightedCG: &pgoir.IRGraph{
46
+ IRNodes: make(map[string]*pgoir.IRNode),
47
+ },
48
+ },
49
+ }
50
+ }
51
+
52
+ // Profile returns the constructed profile.
53
+ func (p *profileBuilder) Profile() *pgoir.Profile {
54
+ return p.p
55
+ }
56
+
57
+ // NewNode creates a new IRNode and adds it to the profile.
58
+ //
59
+ // fn may be nil, in which case the node will set LinkerSymbolName.
60
+ func (p *profileBuilder) NewNode(name string, fn *ir.Func) *pgoir.IRNode {
61
+ n := &pgoir.IRNode{
62
+ OutEdges: make(map[pgo.NamedCallEdge]*pgoir.IREdge),
63
+ }
64
+ if fn != nil {
65
+ n.AST = fn
66
+ } else {
67
+ n.LinkerSymbolName = name
68
+ }
69
+ p.p.WeightedCG.IRNodes[name] = n
70
+ return n
71
+ }
72
+
73
+ // Add a new call edge from caller to callee.
74
+ func addEdge(caller, callee *pgoir.IRNode, offset int, weight int64) {
75
+ namedEdge := pgo.NamedCallEdge{
76
+ CallerName: caller.Name(),
77
+ CalleeName: callee.Name(),
78
+ CallSiteOffset: offset,
79
+ }
80
+ irEdge := &pgoir.IREdge{
81
+ Src: caller,
82
+ Dst: callee,
83
+ CallSiteOffset: offset,
84
+ Weight: weight,
85
+ }
86
+ caller.OutEdges[namedEdge] = irEdge
87
+ }
88
+
89
+ // Create a new struct type named structName with a method named methName and
90
+ // return the method.
91
+ func makeStructWithMethod(pkg *types.Pkg, structName, methName string) *ir.Func {
92
+ // type structName struct{}
93
+ structType := types.NewStruct(nil)
94
+
95
+ // func (structName) methodName()
96
+ recv := types.NewField(src.NoXPos, typecheck.Lookup(structName), structType)
97
+ sig := types.NewSignature(recv, nil, nil)
98
+ fn := ir.NewFunc(src.NoXPos, src.NoXPos, pkg.Lookup(structName+"."+methName), sig)
99
+
100
+ // Add the method to the struct.
101
+ structType.SetMethods([]*types.Field{types.NewField(src.NoXPos, typecheck.Lookup(methName), sig)})
102
+
103
+ return fn
104
+ }
105
+
106
+ func TestFindHotConcreteInterfaceCallee(t *testing.T) {
107
+ p := newProfileBuilder()
108
+
109
+ pkgFoo := types.NewPkg("example.com/foo", "foo")
110
+ basePos := src.NewFileBase("foo.go", "/foo.go")
111
+
112
+ const (
113
+ // Caller start line.
114
+ callerStart = 42
115
+
116
+ // The line offset of the call we care about.
117
+ callOffset = 1
118
+
119
+ // The line offset of some other call we don't care about.
120
+ wrongCallOffset = 2
121
+ )
122
+
123
+ // type IFace interface {
124
+ // Foo()
125
+ // }
126
+ fooSig := types.NewSignature(types.FakeRecv(), nil, nil)
127
+ method := types.NewField(src.NoXPos, typecheck.Lookup("Foo"), fooSig)
128
+ iface := types.NewInterface([]*types.Field{method})
129
+
130
+ callerFn := ir.NewFunc(makePos(basePos, callerStart, 1), src.NoXPos, pkgFoo.Lookup("Caller"), types.NewSignature(nil, nil, nil))
131
+
132
+ hotCalleeFn := makeStructWithMethod(pkgFoo, "HotCallee", "Foo")
133
+ coldCalleeFn := makeStructWithMethod(pkgFoo, "ColdCallee", "Foo")
134
+ wrongLineCalleeFn := makeStructWithMethod(pkgFoo, "WrongLineCallee", "Foo")
135
+ wrongMethodCalleeFn := makeStructWithMethod(pkgFoo, "WrongMethodCallee", "Bar")
136
+
137
+ callerNode := p.NewNode("example.com/foo.Caller", callerFn)
138
+ hotCalleeNode := p.NewNode("example.com/foo.HotCallee.Foo", hotCalleeFn)
139
+ coldCalleeNode := p.NewNode("example.com/foo.ColdCallee.Foo", coldCalleeFn)
140
+ wrongLineCalleeNode := p.NewNode("example.com/foo.WrongCalleeLine.Foo", wrongLineCalleeFn)
141
+ wrongMethodCalleeNode := p.NewNode("example.com/foo.WrongCalleeMethod.Foo", wrongMethodCalleeFn)
142
+
143
+ hotMissingCalleeNode := p.NewNode("example.com/bar.HotMissingCallee.Foo", nil)
144
+
145
+ addEdge(callerNode, wrongLineCalleeNode, wrongCallOffset, 100) // Really hot, but wrong line.
146
+ addEdge(callerNode, wrongMethodCalleeNode, callOffset, 100) // Really hot, but wrong method type.
147
+ addEdge(callerNode, hotCalleeNode, callOffset, 10)
148
+ addEdge(callerNode, coldCalleeNode, callOffset, 1)
149
+
150
+ // Equal weight, but IR missing.
151
+ //
152
+ // N.B. example.com/bar sorts lexicographically before example.com/foo,
153
+ // so if the IR availability of hotCalleeNode doesn't get precedence,
154
+ // this would be mistakenly selected.
155
+ addEdge(callerNode, hotMissingCalleeNode, callOffset, 10)
156
+
157
+ // IFace.Foo()
158
+ sel := typecheck.NewMethodExpr(src.NoXPos, iface, typecheck.Lookup("Foo"))
159
+ call := ir.NewCallExpr(makePos(basePos, callerStart+callOffset, 1), ir.OCALLINTER, sel, nil)
160
+
161
+ gotFn, gotWeight := findHotConcreteInterfaceCallee(p.Profile(), callerFn, call)
162
+ if gotFn != hotCalleeFn {
163
+ t.Errorf("findHotConcreteInterfaceCallee func got %v want %v", gotFn, hotCalleeFn)
164
+ }
165
+ if gotWeight != 10 {
166
+ t.Errorf("findHotConcreteInterfaceCallee weight got %v want 10", gotWeight)
167
+ }
168
+ }
169
+
170
+ func TestFindHotConcreteFunctionCallee(t *testing.T) {
171
+ // TestFindHotConcreteInterfaceCallee already covered basic weight
172
+ // comparisons, which is shared logic. Here we just test type signature
173
+ // disambiguation.
174
+
175
+ p := newProfileBuilder()
176
+
177
+ pkgFoo := types.NewPkg("example.com/foo", "foo")
178
+ basePos := src.NewFileBase("foo.go", "/foo.go")
179
+
180
+ const (
181
+ // Caller start line.
182
+ callerStart = 42
183
+
184
+ // The line offset of the call we care about.
185
+ callOffset = 1
186
+ )
187
+
188
+ callerFn := ir.NewFunc(makePos(basePos, callerStart, 1), src.NoXPos, pkgFoo.Lookup("Caller"), types.NewSignature(nil, nil, nil))
189
+
190
+ // func HotCallee()
191
+ hotCalleeFn := ir.NewFunc(src.NoXPos, src.NoXPos, pkgFoo.Lookup("HotCallee"), types.NewSignature(nil, nil, nil))
192
+
193
+ // func WrongCallee() bool
194
+ wrongCalleeFn := ir.NewFunc(src.NoXPos, src.NoXPos, pkgFoo.Lookup("WrongCallee"), types.NewSignature(nil, nil,
195
+ []*types.Field{
196
+ types.NewField(src.NoXPos, nil, types.Types[types.TBOOL]),
197
+ },
198
+ ))
199
+
200
+ callerNode := p.NewNode("example.com/foo.Caller", callerFn)
201
+ hotCalleeNode := p.NewNode("example.com/foo.HotCallee", hotCalleeFn)
202
+ wrongCalleeNode := p.NewNode("example.com/foo.WrongCallee", wrongCalleeFn)
203
+
204
+ addEdge(callerNode, wrongCalleeNode, callOffset, 100) // Really hot, but wrong function type.
205
+ addEdge(callerNode, hotCalleeNode, callOffset, 10)
206
+
207
+ // var fn func()
208
+ name := ir.NewNameAt(src.NoXPos, typecheck.Lookup("fn"), types.NewSignature(nil, nil, nil))
209
+ // fn()
210
+ call := ir.NewCallExpr(makePos(basePos, callerStart+callOffset, 1), ir.OCALL, name, nil)
211
+
212
+ gotFn, gotWeight := findHotConcreteFunctionCallee(p.Profile(), callerFn, call)
213
+ if gotFn != hotCalleeFn {
214
+ t.Errorf("findHotConcreteFunctionCallee func got %v want %v", gotFn, hotCalleeFn)
215
+ }
216
+ if gotWeight != 10 {
217
+ t.Errorf("findHotConcreteFunctionCallee weight got %v want 10", gotWeight)
218
+ }
219
+ }
go/src/cmd/compile/internal/dwarfgen/dwarf.go ADDED
@@ -0,0 +1,672 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2011 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 dwarfgen
6
+
7
+ import (
8
+ "bytes"
9
+ "flag"
10
+ "fmt"
11
+ "internal/buildcfg"
12
+ "slices"
13
+ "sort"
14
+ "strings"
15
+
16
+ "cmd/compile/internal/base"
17
+ "cmd/compile/internal/ir"
18
+ "cmd/compile/internal/reflectdata"
19
+ "cmd/compile/internal/ssa"
20
+ "cmd/compile/internal/ssagen"
21
+ "cmd/compile/internal/typecheck"
22
+ "cmd/compile/internal/types"
23
+ "cmd/internal/dwarf"
24
+ "cmd/internal/obj"
25
+ "cmd/internal/objabi"
26
+ "cmd/internal/src"
27
+ )
28
+
29
+ func Info(ctxt *obj.Link, fnsym *obj.LSym, infosym *obj.LSym, curfn obj.Func) (scopes []dwarf.Scope, inlcalls dwarf.InlCalls) {
30
+ fn := curfn.(*ir.Func)
31
+
32
+ if fn.Nname != nil {
33
+ expect := fn.Linksym()
34
+ if fnsym.ABI() == obj.ABI0 {
35
+ expect = fn.LinksymABI(obj.ABI0)
36
+ }
37
+ if fnsym != expect {
38
+ base.Fatalf("unexpected fnsym: %v != %v", fnsym, expect)
39
+ }
40
+ }
41
+
42
+ // Back when there were two different *Funcs for a function, this code
43
+ // was not consistent about whether a particular *Node being processed
44
+ // was an ODCLFUNC or ONAME node. Partly this is because inlined function
45
+ // bodies have no ODCLFUNC node, which was it's own inconsistency.
46
+ // In any event, the handling of the two different nodes for DWARF purposes
47
+ // was subtly different, likely in unintended ways. CL 272253 merged the
48
+ // two nodes' Func fields, so that code sees the same *Func whether it is
49
+ // holding the ODCLFUNC or the ONAME. This resulted in changes in the
50
+ // DWARF output. To preserve the existing DWARF output and leave an
51
+ // intentional change for a future CL, this code does the following when
52
+ // fn.Op == ONAME:
53
+ //
54
+ // 1. Disallow use of createComplexVars in createDwarfVars.
55
+ // It was not possible to reach that code for an ONAME before,
56
+ // because the DebugInfo was set only on the ODCLFUNC Func.
57
+ // Calling into it in the ONAME case causes an index out of bounds panic.
58
+ //
59
+ // 2. Do not populate apdecls. fn.Func.Dcl was in the ODCLFUNC Func,
60
+ // not the ONAME Func. Populating apdecls for the ONAME case results
61
+ // in selected being populated after createSimpleVars is called in
62
+ // createDwarfVars, and then that causes the loop to skip all the entries
63
+ // in dcl, meaning that the RecordAutoType calls don't happen.
64
+ //
65
+ // These two adjustments keep toolstash -cmp working for now.
66
+ // Deciding the right answer is, as they say, future work.
67
+ //
68
+ // We can tell the difference between the old ODCLFUNC and ONAME
69
+ // cases by looking at the infosym.Name. If it's empty, DebugInfo is
70
+ // being called from (*obj.Link).populateDWARF, which used to use
71
+ // the ODCLFUNC. If it's non-empty (the name will end in $abstract),
72
+ // DebugInfo is being called from (*obj.Link).DwarfAbstractFunc,
73
+ // which used to use the ONAME form.
74
+ isODCLFUNC := infosym.Name == ""
75
+
76
+ var apdecls []*ir.Name
77
+ // Populate decls for fn.
78
+ if isODCLFUNC {
79
+ for _, n := range fn.Dcl {
80
+ if n.Op() != ir.ONAME { // might be OTYPE or OLITERAL
81
+ continue
82
+ }
83
+ switch n.Class {
84
+ case ir.PAUTO:
85
+ if !n.Used() {
86
+ // Text == nil -> generating abstract function
87
+ if fnsym.Func().Text != nil {
88
+ base.Fatalf("debuginfo unused node (AllocFrame should truncate fn.Func.Dcl)")
89
+ }
90
+ continue
91
+ }
92
+ case ir.PPARAM, ir.PPARAMOUT:
93
+ default:
94
+ continue
95
+ }
96
+ if !ssa.IsVarWantedForDebug(n) {
97
+ continue
98
+ }
99
+ apdecls = append(apdecls, n)
100
+ if n.Type().Kind() == types.TSSA {
101
+ // Can happen for TypeInt128 types. This only happens for
102
+ // spill locations, so not a huge deal.
103
+ continue
104
+ }
105
+ fnsym.Func().RecordAutoType(reflectdata.TypeLinksym(n.Type()))
106
+ }
107
+ }
108
+
109
+ var closureVars map[*ir.Name]int64
110
+ if fn.Needctxt() {
111
+ closureVars = make(map[*ir.Name]int64)
112
+ csiter := typecheck.NewClosureStructIter(fn.ClosureVars)
113
+ for {
114
+ n, _, offset := csiter.Next()
115
+ if n == nil {
116
+ break
117
+ }
118
+ closureVars[n] = offset
119
+ if n.Heapaddr != nil {
120
+ closureVars[n.Heapaddr] = offset
121
+ }
122
+ }
123
+ }
124
+
125
+ decls, dwarfVars := createDwarfVars(fnsym, isODCLFUNC, fn, apdecls, closureVars)
126
+
127
+ // For each type referenced by the functions auto vars but not
128
+ // already referenced by a dwarf var, attach an R_USETYPE relocation to
129
+ // the function symbol to insure that the type included in DWARF
130
+ // processing during linking.
131
+ // Do the same with R_USEIFACE relocations from the function symbol for the
132
+ // same reason.
133
+ // All these R_USETYPE relocations are only looked at if the function
134
+ // survives deadcode elimination in the linker.
135
+ typesyms := []*obj.LSym{}
136
+ for t := range fnsym.Func().Autot {
137
+ typesyms = append(typesyms, t)
138
+ }
139
+ for i := range fnsym.R {
140
+ if fnsym.R[i].Type == objabi.R_USEIFACE && !strings.HasPrefix(fnsym.R[i].Sym.Name, "go:itab.") {
141
+ // Types referenced through itab will be referenced from somewhere else
142
+ typesyms = append(typesyms, fnsym.R[i].Sym)
143
+ }
144
+ }
145
+ slices.SortFunc(typesyms, func(a, b *obj.LSym) int {
146
+ return strings.Compare(a.Name, b.Name)
147
+ })
148
+ var lastsym *obj.LSym
149
+ for _, sym := range typesyms {
150
+ if sym == lastsym {
151
+ continue
152
+ }
153
+ lastsym = sym
154
+ infosym.AddRel(ctxt, obj.Reloc{Type: objabi.R_USETYPE, Sym: sym})
155
+ }
156
+ fnsym.Func().Autot = nil
157
+
158
+ var varScopes []ir.ScopeID
159
+ for _, decl := range decls {
160
+ pos := declPos(decl)
161
+ varScopes = append(varScopes, findScope(fn.Marks, pos))
162
+ }
163
+
164
+ scopes = assembleScopes(fnsym, fn, dwarfVars, varScopes)
165
+ if base.Flag.GenDwarfInl > 0 {
166
+ inlcalls = assembleInlines(fnsym, dwarfVars)
167
+ }
168
+ return scopes, inlcalls
169
+ }
170
+
171
+ func declPos(decl *ir.Name) src.XPos {
172
+ return decl.Canonical().Pos()
173
+ }
174
+
175
+ // createDwarfVars process fn, returning a list of DWARF variables and the
176
+ // Nodes they represent.
177
+ func createDwarfVars(fnsym *obj.LSym, complexOK bool, fn *ir.Func, apDecls []*ir.Name, closureVars map[*ir.Name]int64) ([]*ir.Name, []*dwarf.Var) {
178
+ // Collect a raw list of DWARF vars.
179
+ var vars []*dwarf.Var
180
+ var decls []*ir.Name
181
+ var selected ir.NameSet
182
+
183
+ if base.Ctxt.Flag_locationlists && base.Ctxt.Flag_optimize && fn.DebugInfo != nil && complexOK {
184
+ decls, vars, selected = createComplexVars(fnsym, fn, closureVars)
185
+ } else if fn.ABI == obj.ABIInternal && base.Flag.N != 0 && complexOK {
186
+ decls, vars, selected = createABIVars(fnsym, fn, apDecls, closureVars)
187
+ } else {
188
+ decls, vars, selected = createSimpleVars(fnsym, apDecls, closureVars)
189
+ }
190
+ if fn.DebugInfo != nil {
191
+ // Recover zero sized variables eliminated by the stackframe pass
192
+ for _, n := range fn.DebugInfo.(*ssa.FuncDebug).OptDcl {
193
+ if n.Class != ir.PAUTO {
194
+ continue
195
+ }
196
+ types.CalcSize(n.Type())
197
+ if n.Type().Size() == 0 {
198
+ decls = append(decls, n)
199
+ vars = append(vars, createSimpleVar(fnsym, n, closureVars))
200
+ vars[len(vars)-1].StackOffset = 0
201
+ fnsym.Func().RecordAutoType(reflectdata.TypeLinksym(n.Type()))
202
+ }
203
+ }
204
+ }
205
+
206
+ dcl := apDecls
207
+ if fnsym.WasInlined() {
208
+ dcl = preInliningDcls(fnsym)
209
+ } else {
210
+ // The backend's stackframe pass prunes away entries from the
211
+ // fn's Dcl list, including PARAMOUT nodes that correspond to
212
+ // output params passed in registers. Add back in these
213
+ // entries here so that we can process them properly during
214
+ // DWARF-gen. See issue 48573 for more details.
215
+ debugInfo := fn.DebugInfo.(*ssa.FuncDebug)
216
+ for _, n := range debugInfo.RegOutputParams {
217
+ if !ssa.IsVarWantedForDebug(n) {
218
+ continue
219
+ }
220
+ if n.Class != ir.PPARAMOUT || !n.IsOutputParamInRegisters() {
221
+ base.Fatalf("invalid ir.Name on debugInfo.RegOutputParams list")
222
+ }
223
+ dcl = append(dcl, n)
224
+ }
225
+ }
226
+
227
+ // If optimization is enabled, the list above will typically be
228
+ // missing some of the original pre-optimization variables in the
229
+ // function (they may have been promoted to registers, folded into
230
+ // constants, dead-coded away, etc). Input arguments not eligible
231
+ // for SSA optimization are also missing. Here we add back in entries
232
+ // for selected missing vars. Note that the recipe below creates a
233
+ // conservative location. The idea here is that we want to
234
+ // communicate to the user that "yes, there is a variable named X
235
+ // in this function, but no, I don't have enough information to
236
+ // reliably report its contents."
237
+ // For non-SSA-able arguments, however, the correct information
238
+ // is known -- they have a single home on the stack.
239
+ for _, n := range dcl {
240
+ if selected.Has(n) {
241
+ continue
242
+ }
243
+ c := n.Sym().Name[0]
244
+ if c == '.' || n.Type().IsUntyped() {
245
+ continue
246
+ }
247
+ if n.Class == ir.PPARAM && !ssa.CanSSA(n.Type()) {
248
+ // SSA-able args get location lists, and may move in and
249
+ // out of registers, so those are handled elsewhere.
250
+ // Autos and named output params seem to get handled
251
+ // with VARDEF, which creates location lists.
252
+ // Args not of SSA-able type are treated here; they
253
+ // are homed on the stack in a single place for the
254
+ // entire call.
255
+ vars = append(vars, createSimpleVar(fnsym, n, closureVars))
256
+ decls = append(decls, n)
257
+ continue
258
+ }
259
+ typename := dwarf.InfoPrefix + types.TypeSymName(n.Type())
260
+ decls = append(decls, n)
261
+ tag := dwarf.DW_TAG_variable
262
+ isReturnValue := (n.Class == ir.PPARAMOUT)
263
+ if n.Class == ir.PPARAM || n.Class == ir.PPARAMOUT {
264
+ tag = dwarf.DW_TAG_formal_parameter
265
+ }
266
+ inlIndex := 0
267
+ if base.Flag.GenDwarfInl > 1 {
268
+ if n.InlFormal() || n.InlLocal() {
269
+ inlIndex = posInlIndex(n.Pos()) + 1
270
+ if n.InlFormal() {
271
+ tag = dwarf.DW_TAG_formal_parameter
272
+ }
273
+ }
274
+ }
275
+ declpos := base.Ctxt.InnermostPos(n.Pos())
276
+ dvar := &dwarf.Var{
277
+ Name: n.Sym().Name,
278
+ IsReturnValue: isReturnValue,
279
+ Tag: tag,
280
+ WithLoclist: true,
281
+ StackOffset: int32(n.FrameOffset()),
282
+ Type: base.Ctxt.Lookup(typename),
283
+ DeclFile: declpos.RelFilename(),
284
+ DeclLine: declpos.RelLine(),
285
+ DeclCol: declpos.RelCol(),
286
+ InlIndex: int32(inlIndex),
287
+ ChildIndex: -1,
288
+ DictIndex: n.DictIndex,
289
+ ClosureOffset: closureOffset(n, closureVars),
290
+ }
291
+ if n.Esc() == ir.EscHeap {
292
+ if n.Heapaddr == nil {
293
+ base.Fatalf("invalid heap allocated var without Heapaddr")
294
+ }
295
+ debug := fn.DebugInfo.(*ssa.FuncDebug)
296
+ list := createHeapDerefLocationList(n, debug.EntryID)
297
+ dvar.PutLocationList = func(listSym, startPC dwarf.Sym) {
298
+ debug.PutLocationList(list, base.Ctxt, listSym.(*obj.LSym), startPC.(*obj.LSym))
299
+ }
300
+ }
301
+ vars = append(vars, dvar)
302
+ // Record go type to ensure that it gets emitted by the linker.
303
+ fnsym.Func().RecordAutoType(reflectdata.TypeLinksym(n.Type()))
304
+ }
305
+
306
+ // Sort decls and vars.
307
+ sortDeclsAndVars(fn, decls, vars)
308
+
309
+ return decls, vars
310
+ }
311
+
312
+ // sortDeclsAndVars sorts the decl and dwarf var lists according to
313
+ // parameter declaration order, so as to insure that when a subprogram
314
+ // DIE is emitted, its parameter children appear in declaration order.
315
+ // Prior to the advent of the register ABI, sorting by frame offset
316
+ // would achieve this; with the register we now need to go back to the
317
+ // original function signature.
318
+ func sortDeclsAndVars(fn *ir.Func, decls []*ir.Name, vars []*dwarf.Var) {
319
+ paramOrder := make(map[*ir.Name]int)
320
+ idx := 1
321
+ for _, f := range fn.Type().RecvParamsResults() {
322
+ if n, ok := f.Nname.(*ir.Name); ok {
323
+ paramOrder[n] = idx
324
+ idx++
325
+ }
326
+ }
327
+ sort.Stable(varsAndDecls{decls, vars, paramOrder})
328
+ }
329
+
330
+ type varsAndDecls struct {
331
+ decls []*ir.Name
332
+ vars []*dwarf.Var
333
+ paramOrder map[*ir.Name]int
334
+ }
335
+
336
+ func (v varsAndDecls) Len() int {
337
+ return len(v.decls)
338
+ }
339
+
340
+ func (v varsAndDecls) Less(i, j int) bool {
341
+ nameLT := func(ni, nj *ir.Name) bool {
342
+ oi, foundi := v.paramOrder[ni]
343
+ oj, foundj := v.paramOrder[nj]
344
+ if foundi {
345
+ if foundj {
346
+ return oi < oj
347
+ } else {
348
+ return true
349
+ }
350
+ }
351
+ return false
352
+ }
353
+ return nameLT(v.decls[i], v.decls[j])
354
+ }
355
+
356
+ func (v varsAndDecls) Swap(i, j int) {
357
+ v.vars[i], v.vars[j] = v.vars[j], v.vars[i]
358
+ v.decls[i], v.decls[j] = v.decls[j], v.decls[i]
359
+ }
360
+
361
+ // Given a function that was inlined at some point during the
362
+ // compilation, return a sorted list of nodes corresponding to the
363
+ // autos/locals in that function prior to inlining. If this is a
364
+ // function that is not local to the package being compiled, then the
365
+ // names of the variables may have been "versioned" to avoid conflicts
366
+ // with local vars; disregard this versioning when sorting.
367
+ func preInliningDcls(fnsym *obj.LSym) []*ir.Name {
368
+ fn := base.Ctxt.DwFixups.GetPrecursorFunc(fnsym).(*ir.Func)
369
+ var rdcl []*ir.Name
370
+ for _, n := range fn.Inl.Dcl {
371
+ c := n.Sym().Name[0]
372
+ // Avoid reporting "_" parameters, since if there are more than
373
+ // one, it can result in a collision later on, as in #23179.
374
+ if n.Sym().Name == "_" || c == '.' || n.Type().IsUntyped() {
375
+ continue
376
+ }
377
+ rdcl = append(rdcl, n)
378
+ }
379
+ return rdcl
380
+ }
381
+
382
+ // createSimpleVars creates a DWARF entry for every variable declared in the
383
+ // function, claiming that they are permanently on the stack.
384
+ func createSimpleVars(fnsym *obj.LSym, apDecls []*ir.Name, closureVars map[*ir.Name]int64) ([]*ir.Name, []*dwarf.Var, ir.NameSet) {
385
+ var vars []*dwarf.Var
386
+ var decls []*ir.Name
387
+ var selected ir.NameSet
388
+ for _, n := range apDecls {
389
+ if ir.IsAutoTmp(n) {
390
+ continue
391
+ }
392
+
393
+ decls = append(decls, n)
394
+ vars = append(vars, createSimpleVar(fnsym, n, closureVars))
395
+ selected.Add(n)
396
+ }
397
+ return decls, vars, selected
398
+ }
399
+
400
+ func createSimpleVar(fnsym *obj.LSym, n *ir.Name, closureVars map[*ir.Name]int64) *dwarf.Var {
401
+ var tag int
402
+ var offs int64
403
+
404
+ localAutoOffset := func() int64 {
405
+ offs = n.FrameOffset()
406
+ if base.Ctxt.Arch.FixedFrameSize == 0 {
407
+ offs -= int64(types.PtrSize)
408
+ }
409
+ if buildcfg.FramePointerEnabled {
410
+ offs -= int64(types.PtrSize)
411
+ }
412
+ return offs
413
+ }
414
+
415
+ switch n.Class {
416
+ case ir.PAUTO:
417
+ offs = localAutoOffset()
418
+ tag = dwarf.DW_TAG_variable
419
+ case ir.PPARAM, ir.PPARAMOUT:
420
+ tag = dwarf.DW_TAG_formal_parameter
421
+ if n.IsOutputParamInRegisters() {
422
+ offs = localAutoOffset()
423
+ } else {
424
+ offs = n.FrameOffset() + base.Ctxt.Arch.FixedFrameSize
425
+ }
426
+
427
+ default:
428
+ base.Fatalf("createSimpleVar unexpected class %v for node %v", n.Class, n)
429
+ }
430
+
431
+ typename := dwarf.InfoPrefix + types.TypeSymName(n.Type())
432
+ delete(fnsym.Func().Autot, reflectdata.TypeLinksym(n.Type()))
433
+ inlIndex := 0
434
+ if base.Flag.GenDwarfInl > 1 {
435
+ if n.InlFormal() || n.InlLocal() {
436
+ inlIndex = posInlIndex(n.Pos()) + 1
437
+ if n.InlFormal() {
438
+ tag = dwarf.DW_TAG_formal_parameter
439
+ }
440
+ }
441
+ }
442
+ declpos := base.Ctxt.InnermostPos(declPos(n))
443
+ return &dwarf.Var{
444
+ Name: n.Sym().Name,
445
+ IsReturnValue: n.Class == ir.PPARAMOUT,
446
+ IsInlFormal: n.InlFormal(),
447
+ Tag: tag,
448
+ StackOffset: int32(offs),
449
+ Type: base.Ctxt.Lookup(typename),
450
+ DeclFile: declpos.RelFilename(),
451
+ DeclLine: declpos.RelLine(),
452
+ DeclCol: declpos.RelCol(),
453
+ InlIndex: int32(inlIndex),
454
+ ChildIndex: -1,
455
+ DictIndex: n.DictIndex,
456
+ ClosureOffset: closureOffset(n, closureVars),
457
+ }
458
+ }
459
+
460
+ // createABIVars creates DWARF variables for functions in which the
461
+ // register ABI is enabled but optimization is turned off. It uses a
462
+ // hybrid approach in which register-resident input params are
463
+ // captured with location lists, and all other vars use the "simple"
464
+ // strategy.
465
+ func createABIVars(fnsym *obj.LSym, fn *ir.Func, apDecls []*ir.Name, closureVars map[*ir.Name]int64) ([]*ir.Name, []*dwarf.Var, ir.NameSet) {
466
+
467
+ // Invoke createComplexVars to generate dwarf vars for input parameters
468
+ // that are register-allocated according to the ABI rules.
469
+ decls, vars, selected := createComplexVars(fnsym, fn, closureVars)
470
+
471
+ // Now fill in the remainder of the variables: input parameters
472
+ // that are not register-resident, output parameters, and local
473
+ // variables.
474
+ for _, n := range apDecls {
475
+ if ir.IsAutoTmp(n) {
476
+ continue
477
+ }
478
+ if _, ok := selected[n]; ok {
479
+ // already handled
480
+ continue
481
+ }
482
+
483
+ decls = append(decls, n)
484
+ vars = append(vars, createSimpleVar(fnsym, n, closureVars))
485
+ selected.Add(n)
486
+ }
487
+
488
+ return decls, vars, selected
489
+ }
490
+
491
+ // createComplexVars creates recomposed DWARF vars with location lists,
492
+ // suitable for describing optimized code.
493
+ func createComplexVars(fnsym *obj.LSym, fn *ir.Func, closureVars map[*ir.Name]int64) ([]*ir.Name, []*dwarf.Var, ir.NameSet) {
494
+ debugInfo := fn.DebugInfo.(*ssa.FuncDebug)
495
+
496
+ // Produce a DWARF variable entry for each user variable.
497
+ var decls []*ir.Name
498
+ var vars []*dwarf.Var
499
+ var ssaVars ir.NameSet
500
+
501
+ for varID, dvar := range debugInfo.Vars {
502
+ n := dvar
503
+ ssaVars.Add(n)
504
+ for _, slot := range debugInfo.VarSlots[varID] {
505
+ ssaVars.Add(debugInfo.Slots[slot].N)
506
+ }
507
+
508
+ if dvar := createComplexVar(fnsym, fn, ssa.VarID(varID), closureVars); dvar != nil {
509
+ decls = append(decls, n)
510
+ vars = append(vars, dvar)
511
+ }
512
+ }
513
+
514
+ return decls, vars, ssaVars
515
+ }
516
+
517
+ // createComplexVar builds a single DWARF variable entry and location list.
518
+ func createComplexVar(fnsym *obj.LSym, fn *ir.Func, varID ssa.VarID, closureVars map[*ir.Name]int64) *dwarf.Var {
519
+ debug := fn.DebugInfo.(*ssa.FuncDebug)
520
+ n := debug.Vars[varID]
521
+
522
+ var tag int
523
+ switch n.Class {
524
+ case ir.PAUTO:
525
+ tag = dwarf.DW_TAG_variable
526
+ case ir.PPARAM, ir.PPARAMOUT:
527
+ tag = dwarf.DW_TAG_formal_parameter
528
+ default:
529
+ return nil
530
+ }
531
+
532
+ gotype := reflectdata.TypeLinksym(n.Type())
533
+ delete(fnsym.Func().Autot, gotype)
534
+ typename := dwarf.InfoPrefix + gotype.Name[len("type:"):]
535
+ inlIndex := 0
536
+ if base.Flag.GenDwarfInl > 1 {
537
+ if n.InlFormal() || n.InlLocal() {
538
+ inlIndex = posInlIndex(n.Pos()) + 1
539
+ if n.InlFormal() {
540
+ tag = dwarf.DW_TAG_formal_parameter
541
+ }
542
+ }
543
+ }
544
+ declpos := base.Ctxt.InnermostPos(n.Pos())
545
+ dvar := &dwarf.Var{
546
+ Name: n.Sym().Name,
547
+ IsReturnValue: n.Class == ir.PPARAMOUT,
548
+ IsInlFormal: n.InlFormal(),
549
+ Tag: tag,
550
+ WithLoclist: true,
551
+ Type: base.Ctxt.Lookup(typename),
552
+ // The stack offset is used as a sorting key, so for decomposed
553
+ // variables just give it the first one. It's not used otherwise.
554
+ // This won't work well if the first slot hasn't been assigned a stack
555
+ // location, but it's not obvious how to do better.
556
+ StackOffset: ssagen.StackOffset(debug.Slots[debug.VarSlots[varID][0]]),
557
+ DeclFile: declpos.RelFilename(),
558
+ DeclLine: declpos.RelLine(),
559
+ DeclCol: declpos.RelCol(),
560
+ InlIndex: int32(inlIndex),
561
+ ChildIndex: -1,
562
+ DictIndex: n.DictIndex,
563
+ ClosureOffset: closureOffset(n, closureVars),
564
+ }
565
+ list := debug.LocationLists[varID]
566
+ if len(list) != 0 {
567
+ dvar.PutLocationList = func(listSym, startPC dwarf.Sym) {
568
+ debug.PutLocationList(list, base.Ctxt, listSym.(*obj.LSym), startPC.(*obj.LSym))
569
+ }
570
+ }
571
+ return dvar
572
+ }
573
+
574
+ // createHeapDerefLocationList creates a location list for a heap-escaped variable
575
+ // that describes "dereference pointer at stack offset"
576
+ func createHeapDerefLocationList(n *ir.Name, entryID ssa.ID) []byte {
577
+ // Get the stack offset where the heap pointer is stored
578
+ heapPtrOffset := n.Heapaddr.FrameOffset()
579
+ if base.Ctxt.Arch.FixedFrameSize == 0 {
580
+ heapPtrOffset -= int64(types.PtrSize)
581
+ }
582
+ if buildcfg.FramePointerEnabled {
583
+ heapPtrOffset -= int64(types.PtrSize)
584
+ }
585
+
586
+ // Create a location expression: DW_OP_fbreg <offset> DW_OP_deref
587
+ var locExpr []byte
588
+ var sizeIdx int
589
+ locExpr, sizeIdx = ssa.SetupLocList(base.Ctxt, entryID, locExpr, ssa.BlockStart.ID, ssa.FuncEnd.ID)
590
+ locExpr = append(locExpr, dwarf.DW_OP_fbreg)
591
+ locExpr = dwarf.AppendSleb128(locExpr, heapPtrOffset)
592
+ locExpr = append(locExpr, dwarf.DW_OP_deref)
593
+ base.Ctxt.Arch.ByteOrder.PutUint16(locExpr[sizeIdx:], uint16(len(locExpr)-sizeIdx-2))
594
+ return locExpr
595
+ }
596
+
597
+ // RecordFlags records the specified command-line flags to be placed
598
+ // in the DWARF info.
599
+ func RecordFlags(flags ...string) {
600
+ if base.Ctxt.Pkgpath == "" {
601
+ base.Fatalf("missing pkgpath")
602
+ }
603
+
604
+ type BoolFlag interface {
605
+ IsBoolFlag() bool
606
+ }
607
+ type CountFlag interface {
608
+ IsCountFlag() bool
609
+ }
610
+ var cmd bytes.Buffer
611
+ for _, name := range flags {
612
+ f := flag.Lookup(name)
613
+ if f == nil {
614
+ continue
615
+ }
616
+ getter := f.Value.(flag.Getter)
617
+ if getter.String() == f.DefValue {
618
+ // Flag has default value, so omit it.
619
+ continue
620
+ }
621
+ if bf, ok := f.Value.(BoolFlag); ok && bf.IsBoolFlag() {
622
+ val, ok := getter.Get().(bool)
623
+ if ok && val {
624
+ fmt.Fprintf(&cmd, " -%s", f.Name)
625
+ continue
626
+ }
627
+ }
628
+ if cf, ok := f.Value.(CountFlag); ok && cf.IsCountFlag() {
629
+ val, ok := getter.Get().(int)
630
+ if ok && val == 1 {
631
+ fmt.Fprintf(&cmd, " -%s", f.Name)
632
+ continue
633
+ }
634
+ }
635
+ fmt.Fprintf(&cmd, " -%s=%v", f.Name, getter.Get())
636
+ }
637
+
638
+ // Adds flag to producer string signaling whether regabi is turned on or
639
+ // off.
640
+ // Once regabi is turned on across the board and the relative GOEXPERIMENT
641
+ // knobs no longer exist this code should be removed.
642
+ if buildcfg.Experiment.RegabiArgs {
643
+ cmd.Write([]byte(" regabi"))
644
+ }
645
+
646
+ if cmd.Len() == 0 {
647
+ return
648
+ }
649
+ s := base.Ctxt.Lookup(dwarf.CUInfoPrefix + "producer." + base.Ctxt.Pkgpath)
650
+ s.Type = objabi.SDWARFCUINFO
651
+ // Sometimes (for example when building tests) we can link
652
+ // together two package main archives. So allow dups.
653
+ s.Set(obj.AttrDuplicateOK, true)
654
+ base.Ctxt.Data = append(base.Ctxt.Data, s)
655
+ s.P = cmd.Bytes()[1:]
656
+ }
657
+
658
+ // RecordPackageName records the name of the package being
659
+ // compiled, so that the linker can save it in the compile unit's DIE.
660
+ func RecordPackageName() {
661
+ s := base.Ctxt.Lookup(dwarf.CUInfoPrefix + "packagename." + base.Ctxt.Pkgpath)
662
+ s.Type = objabi.SDWARFCUINFO
663
+ // Sometimes (for example when building tests) we can link
664
+ // together two package main archives. So allow dups.
665
+ s.Set(obj.AttrDuplicateOK, true)
666
+ base.Ctxt.Data = append(base.Ctxt.Data, s)
667
+ s.P = []byte(types.LocalPkg.Name)
668
+ }
669
+
670
+ func closureOffset(n *ir.Name, closureVars map[*ir.Name]int64) int64 {
671
+ return closureVars[n]
672
+ }
go/src/cmd/compile/internal/dwarfgen/dwinl.go ADDED
@@ -0,0 +1,441 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2017 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 dwarfgen
6
+
7
+ import (
8
+ "fmt"
9
+ "strings"
10
+
11
+ "cmd/compile/internal/base"
12
+ "cmd/compile/internal/ir"
13
+ "cmd/internal/dwarf"
14
+ "cmd/internal/obj"
15
+ "cmd/internal/src"
16
+ )
17
+
18
+ // To identify variables by original source position.
19
+ type varPos struct {
20
+ DeclName string
21
+ DeclFile string
22
+ DeclLine uint
23
+ DeclCol uint
24
+ }
25
+
26
+ // This is the main entry point for collection of raw material to
27
+ // drive generation of DWARF "inlined subroutine" DIEs. See proposal
28
+ // 22080 for more details and background info.
29
+ func assembleInlines(fnsym *obj.LSym, dwVars []*dwarf.Var) dwarf.InlCalls {
30
+ var inlcalls dwarf.InlCalls
31
+
32
+ if base.Debug.DwarfInl != 0 {
33
+ base.Ctxt.Logf("assembling DWARF inlined routine info for %v\n", fnsym.Name)
34
+ }
35
+
36
+ // This maps inline index (from Ctxt.InlTree) to index in inlcalls.Calls
37
+ imap := make(map[int]int)
38
+
39
+ // Walk progs to build up the InlCalls data structure
40
+ var prevpos src.XPos
41
+ for p := fnsym.Func().Text; p != nil; p = p.Link {
42
+ if p.Pos == prevpos {
43
+ continue
44
+ }
45
+ ii := posInlIndex(p.Pos)
46
+ if ii >= 0 {
47
+ insertInlCall(&inlcalls, ii, imap)
48
+ }
49
+ prevpos = p.Pos
50
+ }
51
+
52
+ // This is used to partition DWARF vars by inline index. Vars not
53
+ // produced by the inliner will wind up in the vmap[0] entry.
54
+ vmap := make(map[int32][]*dwarf.Var)
55
+
56
+ // Now walk the dwarf vars and partition them based on whether they
57
+ // were produced by the inliner (dwv.InlIndex > 0) or were original
58
+ // vars/params from the function (dwv.InlIndex == 0).
59
+ for _, dwv := range dwVars {
60
+
61
+ vmap[dwv.InlIndex] = append(vmap[dwv.InlIndex], dwv)
62
+
63
+ // Zero index => var was not produced by an inline
64
+ if dwv.InlIndex == 0 {
65
+ continue
66
+ }
67
+
68
+ // Look up index in our map, then tack the var in question
69
+ // onto the vars list for the correct inlined call.
70
+ ii := int(dwv.InlIndex) - 1
71
+ idx, ok := imap[ii]
72
+ if !ok {
73
+ // We can occasionally encounter a var produced by the
74
+ // inliner for which there is no remaining prog; add a new
75
+ // entry to the call list in this scenario.
76
+ idx = insertInlCall(&inlcalls, ii, imap)
77
+ }
78
+ inlcalls.Calls[idx].InlVars =
79
+ append(inlcalls.Calls[idx].InlVars, dwv)
80
+ }
81
+
82
+ // Post process the map above to assign child indices to vars.
83
+ //
84
+ // A given variable is treated differently depending on whether it
85
+ // is part of the top-level function (ii == 0) or if it was
86
+ // produced as a result of an inline (ii != 0).
87
+ //
88
+ // If a variable was not produced by an inline and its containing
89
+ // function was not inlined, then we just assign an ordering of
90
+ // based on variable name.
91
+ //
92
+ // If a variable was not produced by an inline and its containing
93
+ // function was inlined, then we need to assign a child index
94
+ // based on the order of vars in the abstract function (in
95
+ // addition, those vars that don't appear in the abstract
96
+ // function, such as "~r1", are flagged as such).
97
+ //
98
+ // If a variable was produced by an inline, then we locate it in
99
+ // the pre-inlining decls for the target function and assign child
100
+ // index accordingly.
101
+ for ii, sl := range vmap {
102
+ var m map[varPos]int
103
+ if ii == 0 {
104
+ if !fnsym.WasInlined() {
105
+ for j, v := range sl {
106
+ v.ChildIndex = int32(j)
107
+ }
108
+ continue
109
+ }
110
+ m = makePreinlineDclMap(fnsym)
111
+ } else {
112
+ ifnlsym := base.Ctxt.InlTree.InlinedFunction(int(ii - 1))
113
+ m = makePreinlineDclMap(ifnlsym)
114
+ }
115
+
116
+ // Here we assign child indices to variables based on
117
+ // pre-inlined decls, and set the "IsInAbstract" flag
118
+ // appropriately. In addition: parameter and local variable
119
+ // names are given "middle dot" version numbers as part of the
120
+ // writing them out to export data (see issue 4326). If DWARF
121
+ // inlined routine generation is turned on, we want to undo
122
+ // this versioning, since DWARF variables in question will be
123
+ // parented by the inlined routine and not the top-level
124
+ // caller.
125
+ synthCount := len(m)
126
+ for _, v := range sl {
127
+ vp := varPos{
128
+ DeclName: v.Name,
129
+ DeclFile: v.DeclFile,
130
+ DeclLine: v.DeclLine,
131
+ DeclCol: v.DeclCol,
132
+ }
133
+ synthesized := strings.HasPrefix(v.Name, "~") || v.Name == "_"
134
+ if idx, found := m[vp]; found {
135
+ v.ChildIndex = int32(idx)
136
+ v.IsInAbstract = !synthesized
137
+ } else {
138
+ // Variable can't be found in the pre-inline dcl list.
139
+ // In the top-level case (ii=0) this can happen
140
+ // because a composite variable was split into pieces,
141
+ // and we're looking at a piece. We can also see
142
+ // return temps (~r%d) that were created during
143
+ // lowering, or unnamed params ("_").
144
+ v.ChildIndex = int32(synthCount)
145
+ synthCount++
146
+ }
147
+ }
148
+ }
149
+
150
+ // Make a second pass through the progs to compute PC ranges for
151
+ // the various inlined calls.
152
+ start := int64(-1)
153
+ curii := -1
154
+ var prevp *obj.Prog
155
+ for p := fnsym.Func().Text; p != nil; prevp, p = p, p.Link {
156
+ if prevp != nil && p.Pos == prevp.Pos {
157
+ continue
158
+ }
159
+ ii := posInlIndex(p.Pos)
160
+ if ii == curii {
161
+ continue
162
+ }
163
+ // Close out the current range
164
+ if start != -1 {
165
+ addRange(inlcalls.Calls, start, p.Pc, curii, imap)
166
+ }
167
+ // Begin new range
168
+ start = p.Pc
169
+ curii = ii
170
+ }
171
+ if start != -1 {
172
+ addRange(inlcalls.Calls, start, fnsym.Size, curii, imap)
173
+ }
174
+
175
+ // Issue 33188: if II foo is a child of II bar, then ensure that
176
+ // bar's ranges include the ranges of foo (the loop above will produce
177
+ // disjoint ranges).
178
+ for k, c := range inlcalls.Calls {
179
+ if c.Root {
180
+ unifyCallRanges(inlcalls, k)
181
+ }
182
+ }
183
+
184
+ // Debugging
185
+ if base.Debug.DwarfInl != 0 {
186
+ dumpInlCalls(inlcalls)
187
+ dumpInlVars(dwVars)
188
+ }
189
+
190
+ // Perform a consistency check on inlined routine PC ranges
191
+ // produced by unifyCallRanges above. In particular, complain in
192
+ // cases where you have A -> B -> C (e.g. C is inlined into B, and
193
+ // B is inlined into A) and the ranges for B are not enclosed
194
+ // within the ranges for A, or C within B.
195
+ for k, c := range inlcalls.Calls {
196
+ if c.Root {
197
+ checkInlCall(fnsym.Name, inlcalls, fnsym.Size, k, -1)
198
+ }
199
+ }
200
+
201
+ return inlcalls
202
+ }
203
+
204
+ // Secondary hook for DWARF inlined subroutine generation. This is called
205
+ // late in the compilation when it is determined that we need an
206
+ // abstract function DIE for an inlined routine imported from a
207
+ // previously compiled package.
208
+ func AbstractFunc(fn *obj.LSym) {
209
+ ifn := base.Ctxt.DwFixups.GetPrecursorFunc(fn)
210
+ if ifn == nil {
211
+ base.Ctxt.Diag("failed to locate precursor fn for %v", fn)
212
+ return
213
+ }
214
+ _ = ifn.(*ir.Func)
215
+ if base.Debug.DwarfInl != 0 {
216
+ base.Ctxt.Logf("DwarfAbstractFunc(%v)\n", fn.Name)
217
+ }
218
+ base.Ctxt.DwarfAbstractFunc(ifn, fn)
219
+ }
220
+
221
+ // Given a function that was inlined as part of the compilation, dig
222
+ // up the pre-inlining DCL list for the function and create a map that
223
+ // supports lookup of pre-inline dcl index, based on variable
224
+ // position/name. NB: the recipe for computing variable pos/file/line
225
+ // needs to be kept in sync with the similar code in gc.createSimpleVars
226
+ // and related functions.
227
+ func makePreinlineDclMap(fnsym *obj.LSym) map[varPos]int {
228
+ dcl := preInliningDcls(fnsym)
229
+ m := make(map[varPos]int)
230
+ for i, n := range dcl {
231
+ pos := base.Ctxt.InnermostPos(n.Pos())
232
+ vp := varPos{
233
+ DeclName: n.Sym().Name,
234
+ DeclFile: pos.RelFilename(),
235
+ DeclLine: pos.RelLine(),
236
+ DeclCol: pos.RelCol(),
237
+ }
238
+ if _, found := m[vp]; found {
239
+ // We can see collisions (variables with the same name/file/line/col) in obfuscated or machine-generated code -- see issue 44378 for an example. Skip duplicates in such cases, since it is unlikely that a human will be debugging such code.
240
+ continue
241
+ }
242
+ m[vp] = i
243
+ }
244
+ return m
245
+ }
246
+
247
+ func insertInlCall(dwcalls *dwarf.InlCalls, inlIdx int, imap map[int]int) int {
248
+ callIdx, found := imap[inlIdx]
249
+ if found {
250
+ return callIdx
251
+ }
252
+
253
+ // Haven't seen this inline yet. Visit parent of inline if there
254
+ // is one. We do this first so that parents appear before their
255
+ // children in the resulting table.
256
+ parCallIdx := -1
257
+ parInlIdx := base.Ctxt.InlTree.Parent(inlIdx)
258
+ if parInlIdx >= 0 {
259
+ parCallIdx = insertInlCall(dwcalls, parInlIdx, imap)
260
+ }
261
+
262
+ // Create new entry for this inline
263
+ inlinedFn := base.Ctxt.InlTree.InlinedFunction(inlIdx)
264
+ callXPos := base.Ctxt.InlTree.CallPos(inlIdx)
265
+ callPos := base.Ctxt.InnermostPos(callXPos)
266
+ absFnSym := base.Ctxt.DwFixups.AbsFuncDwarfSym(inlinedFn)
267
+ ic := dwarf.InlCall{
268
+ InlIndex: inlIdx,
269
+ CallPos: callPos,
270
+ AbsFunSym: absFnSym,
271
+ Root: parCallIdx == -1,
272
+ }
273
+ dwcalls.Calls = append(dwcalls.Calls, ic)
274
+ callIdx = len(dwcalls.Calls) - 1
275
+ imap[inlIdx] = callIdx
276
+
277
+ if parCallIdx != -1 {
278
+ // Add this inline to parent's child list
279
+ dwcalls.Calls[parCallIdx].Children = append(dwcalls.Calls[parCallIdx].Children, callIdx)
280
+ }
281
+
282
+ return callIdx
283
+ }
284
+
285
+ // Given a src.XPos, return its associated inlining index if it
286
+ // corresponds to something created as a result of an inline, or -1 if
287
+ // there is no inline info. Note that the index returned will refer to
288
+ // the deepest call in the inlined stack, e.g. if you have "A calls B
289
+ // calls C calls D" and all three callees are inlined (B, C, and D),
290
+ // the index for a node from the inlined body of D will refer to the
291
+ // call to D from C. Whew.
292
+ func posInlIndex(xpos src.XPos) int {
293
+ pos := base.Ctxt.PosTable.Pos(xpos)
294
+ if b := pos.Base(); b != nil {
295
+ ii := b.InliningIndex()
296
+ if ii >= 0 {
297
+ return ii
298
+ }
299
+ }
300
+ return -1
301
+ }
302
+
303
+ func addRange(calls []dwarf.InlCall, start, end int64, ii int, imap map[int]int) {
304
+ if start == -1 {
305
+ panic("bad range start")
306
+ }
307
+ if end == -1 {
308
+ panic("bad range end")
309
+ }
310
+ if ii == -1 {
311
+ return
312
+ }
313
+ if start == end {
314
+ return
315
+ }
316
+ // Append range to correct inlined call
317
+ callIdx, found := imap[ii]
318
+ if !found {
319
+ base.Fatalf("can't find inlIndex %d in imap for prog at %d\n", ii, start)
320
+ }
321
+ call := &calls[callIdx]
322
+ call.Ranges = append(call.Ranges, dwarf.Range{Start: start, End: end})
323
+ }
324
+
325
+ func dumpInlCall(inlcalls dwarf.InlCalls, idx, ilevel int) {
326
+ for i := 0; i < ilevel; i++ {
327
+ base.Ctxt.Logf(" ")
328
+ }
329
+ ic := inlcalls.Calls[idx]
330
+ callee := base.Ctxt.InlTree.InlinedFunction(ic.InlIndex)
331
+ base.Ctxt.Logf(" %d: II:%d (%s) V: (", idx, ic.InlIndex, callee.Name)
332
+ for _, f := range ic.InlVars {
333
+ base.Ctxt.Logf(" %v", f.Name)
334
+ }
335
+ base.Ctxt.Logf(" ) C: (")
336
+ for _, k := range ic.Children {
337
+ base.Ctxt.Logf(" %v", k)
338
+ }
339
+ base.Ctxt.Logf(" ) R:")
340
+ for _, r := range ic.Ranges {
341
+ base.Ctxt.Logf(" [%d,%d)", r.Start, r.End)
342
+ }
343
+ base.Ctxt.Logf("\n")
344
+ for _, k := range ic.Children {
345
+ dumpInlCall(inlcalls, k, ilevel+1)
346
+ }
347
+
348
+ }
349
+
350
+ func dumpInlCalls(inlcalls dwarf.InlCalls) {
351
+ for k, c := range inlcalls.Calls {
352
+ if c.Root {
353
+ dumpInlCall(inlcalls, k, 0)
354
+ }
355
+ }
356
+ }
357
+
358
+ func dumpInlVars(dwvars []*dwarf.Var) {
359
+ for i, dwv := range dwvars {
360
+ typ := "local"
361
+ if dwv.Tag == dwarf.DW_TAG_formal_parameter {
362
+ typ = "param"
363
+ }
364
+ ia := 0
365
+ if dwv.IsInAbstract {
366
+ ia = 1
367
+ }
368
+ base.Ctxt.Logf("V%d: %s CI:%d II:%d IA:%d %s\n", i, dwv.Name, dwv.ChildIndex, dwv.InlIndex-1, ia, typ)
369
+ }
370
+ }
371
+
372
+ func rangesContains(par []dwarf.Range, rng dwarf.Range) (bool, string) {
373
+ for _, r := range par {
374
+ if rng.Start >= r.Start && rng.End <= r.End {
375
+ return true, ""
376
+ }
377
+ }
378
+ msg := fmt.Sprintf("range [%d,%d) not contained in {", rng.Start, rng.End)
379
+ for _, r := range par {
380
+ msg += fmt.Sprintf(" [%d,%d)", r.Start, r.End)
381
+ }
382
+ msg += " }"
383
+ return false, msg
384
+ }
385
+
386
+ func rangesContainsAll(parent, child []dwarf.Range) (bool, string) {
387
+ for _, r := range child {
388
+ c, m := rangesContains(parent, r)
389
+ if !c {
390
+ return false, m
391
+ }
392
+ }
393
+ return true, ""
394
+ }
395
+
396
+ // checkInlCall verifies that the PC ranges for inline info 'idx' are
397
+ // enclosed/contained within the ranges of its parent inline (or if
398
+ // this is a root/toplevel inline, checks that the ranges fall within
399
+ // the extent of the top level function). A panic is issued if a
400
+ // malformed range is found.
401
+ func checkInlCall(funcName string, inlCalls dwarf.InlCalls, funcSize int64, idx, parentIdx int) {
402
+
403
+ // Callee
404
+ ic := inlCalls.Calls[idx]
405
+ callee := base.Ctxt.InlTree.InlinedFunction(ic.InlIndex).Name
406
+ calleeRanges := ic.Ranges
407
+
408
+ // Caller
409
+ caller := funcName
410
+ parentRanges := []dwarf.Range{dwarf.Range{Start: int64(0), End: funcSize}}
411
+ if parentIdx != -1 {
412
+ pic := inlCalls.Calls[parentIdx]
413
+ caller = base.Ctxt.InlTree.InlinedFunction(pic.InlIndex).Name
414
+ parentRanges = pic.Ranges
415
+ }
416
+
417
+ // Callee ranges contained in caller ranges?
418
+ c, m := rangesContainsAll(parentRanges, calleeRanges)
419
+ if !c {
420
+ base.Fatalf("** malformed inlined routine range in %s: caller %s callee %s II=%d %s\n", funcName, caller, callee, idx, m)
421
+ }
422
+
423
+ // Now visit kids
424
+ for _, k := range ic.Children {
425
+ checkInlCall(funcName, inlCalls, funcSize, k, idx)
426
+ }
427
+ }
428
+
429
+ // unifyCallRanges ensures that the ranges for a given inline
430
+ // transitively include all of the ranges for its child inlines.
431
+ func unifyCallRanges(inlcalls dwarf.InlCalls, idx int) {
432
+ ic := &inlcalls.Calls[idx]
433
+ for _, childIdx := range ic.Children {
434
+ // First make sure child ranges are unified.
435
+ unifyCallRanges(inlcalls, childIdx)
436
+
437
+ // Then merge child ranges into ranges for this inline.
438
+ cic := inlcalls.Calls[childIdx]
439
+ ic.Ranges = dwarf.MergeRanges(ic.Ranges, cic.Ranges)
440
+ }
441
+ }
go/src/cmd/compile/internal/dwarfgen/linenum_test.go ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2025 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 dwarfgen
6
+
7
+ import (
8
+ "debug/dwarf"
9
+ "internal/platform"
10
+ "internal/testenv"
11
+ "io"
12
+ "runtime"
13
+ "testing"
14
+ )
15
+
16
+ func TestIssue75249(t *testing.T) {
17
+ testenv.MustHaveGoRun(t)
18
+ t.Parallel()
19
+
20
+ if !platform.ExecutableHasDWARF(runtime.GOOS, runtime.GOARCH) {
21
+ t.Skipf("skipping on %s/%s: no DWARF symbol table in executables", runtime.GOOS, runtime.GOARCH)
22
+ }
23
+
24
+ code := `
25
+ package main
26
+
27
+ type Data struct {
28
+ Field1 int
29
+ Field2 *int
30
+ Field3 int
31
+ Field4 *int
32
+ Field5 int
33
+ Field6 *int
34
+ Field7 int
35
+ Field8 *int
36
+ }
37
+
38
+ //go:noinline
39
+ func InitializeData(d *Data) {
40
+ d.Field1++ // line 16
41
+ d.Field2 = d.Field4
42
+ d.Field3++
43
+ d.Field4 = d.Field6
44
+ d.Field5++
45
+ d.Field6 = d.Field8
46
+ d.Field7++
47
+ d.Field8 = d.Field2 // line 23
48
+ }
49
+
50
+ func main() {
51
+ var data Data
52
+ InitializeData(&data)
53
+ }
54
+ `
55
+
56
+ _, f := gobuild(t, t.TempDir(), true, []testline{{line: code}})
57
+ defer f.Close()
58
+
59
+ dwarfData, err := f.DWARF()
60
+ if err != nil {
61
+ t.Fatal(err)
62
+ }
63
+ dwarfReader := dwarfData.Reader()
64
+
65
+ for {
66
+ entry, err := dwarfReader.Next()
67
+ if err != nil {
68
+ t.Fatal(err)
69
+ }
70
+ if entry == nil {
71
+ break
72
+ }
73
+ if entry.Tag != dwarf.TagCompileUnit {
74
+ continue
75
+ }
76
+ name := entry.AttrField(dwarf.AttrName)
77
+ if name == nil || name.Class != dwarf.ClassString || name.Val != "main" {
78
+ continue
79
+ }
80
+ lr, err := dwarfData.LineReader(entry)
81
+ if err != nil {
82
+ t.Fatal(err)
83
+ }
84
+ stmts := map[int]bool{}
85
+ for {
86
+ var le dwarf.LineEntry
87
+ err := lr.Next(&le)
88
+ if err == io.EOF {
89
+ break
90
+ }
91
+ if err != nil {
92
+ t.Fatal(err)
93
+ }
94
+ if !le.IsStmt {
95
+ continue
96
+ }
97
+ stmts[le.Line] = true
98
+ }
99
+ for i := 16; i <= 23; i++ {
100
+ if !stmts[i] {
101
+ t.Errorf("missing statement at line %d", i)
102
+ }
103
+ }
104
+ }
105
+ }
go/src/cmd/compile/internal/dwarfgen/marker.go ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2021 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 dwarfgen
6
+
7
+ import (
8
+ "cmd/compile/internal/base"
9
+ "cmd/compile/internal/ir"
10
+ "cmd/internal/src"
11
+ )
12
+
13
+ // A ScopeMarker tracks scope nesting and boundaries for later use
14
+ // during DWARF generation.
15
+ type ScopeMarker struct {
16
+ parents []ir.ScopeID
17
+ marks []ir.Mark
18
+ }
19
+
20
+ // checkPos validates the given position and returns the current scope.
21
+ func (m *ScopeMarker) checkPos(pos src.XPos) ir.ScopeID {
22
+ if !pos.IsKnown() {
23
+ base.Fatalf("unknown scope position")
24
+ }
25
+
26
+ if len(m.marks) == 0 {
27
+ return 0
28
+ }
29
+
30
+ last := &m.marks[len(m.marks)-1]
31
+ if xposBefore(pos, last.Pos) {
32
+ base.FatalfAt(pos, "non-monotonic scope positions\n\t%v: previous scope position", base.FmtPos(last.Pos))
33
+ }
34
+ return last.Scope
35
+ }
36
+
37
+ // Push records a transition to a new child scope of the current scope.
38
+ func (m *ScopeMarker) Push(pos src.XPos) {
39
+ current := m.checkPos(pos)
40
+
41
+ m.parents = append(m.parents, current)
42
+ child := ir.ScopeID(len(m.parents))
43
+
44
+ m.marks = append(m.marks, ir.Mark{Pos: pos, Scope: child})
45
+ }
46
+
47
+ // Pop records a transition back to the current scope's parent.
48
+ func (m *ScopeMarker) Pop(pos src.XPos) {
49
+ current := m.checkPos(pos)
50
+
51
+ parent := m.parents[current-1]
52
+
53
+ m.marks = append(m.marks, ir.Mark{Pos: pos, Scope: parent})
54
+ }
55
+
56
+ // Unpush removes the current scope, which must be empty.
57
+ func (m *ScopeMarker) Unpush() {
58
+ i := len(m.marks) - 1
59
+ current := m.marks[i].Scope
60
+
61
+ if current != ir.ScopeID(len(m.parents)) {
62
+ base.FatalfAt(m.marks[i].Pos, "current scope is not empty")
63
+ }
64
+
65
+ m.parents = m.parents[:current-1]
66
+ m.marks = m.marks[:i]
67
+ }
68
+
69
+ // WriteTo writes the recorded scope marks to the given function,
70
+ // and resets the marker for reuse.
71
+ func (m *ScopeMarker) WriteTo(fn *ir.Func) {
72
+ m.compactMarks()
73
+
74
+ fn.Parents = make([]ir.ScopeID, len(m.parents))
75
+ copy(fn.Parents, m.parents)
76
+ m.parents = m.parents[:0]
77
+
78
+ fn.Marks = make([]ir.Mark, len(m.marks))
79
+ copy(fn.Marks, m.marks)
80
+ m.marks = m.marks[:0]
81
+ }
82
+
83
+ func (m *ScopeMarker) compactMarks() {
84
+ n := 0
85
+ for _, next := range m.marks {
86
+ if n > 0 && next.Pos == m.marks[n-1].Pos {
87
+ m.marks[n-1].Scope = next.Scope
88
+ continue
89
+ }
90
+ m.marks[n] = next
91
+ n++
92
+ }
93
+ m.marks = m.marks[:n]
94
+ }
go/src/cmd/compile/internal/dwarfgen/scope.go ADDED
@@ -0,0 +1,136 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2017 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 dwarfgen
6
+
7
+ import (
8
+ "sort"
9
+
10
+ "cmd/compile/internal/base"
11
+ "cmd/compile/internal/ir"
12
+ "cmd/internal/dwarf"
13
+ "cmd/internal/obj"
14
+ "cmd/internal/src"
15
+ )
16
+
17
+ // See golang.org/issue/20390.
18
+ func xposBefore(p, q src.XPos) bool {
19
+ return base.Ctxt.PosTable.Pos(p).Before(base.Ctxt.PosTable.Pos(q))
20
+ }
21
+
22
+ func findScope(marks []ir.Mark, pos src.XPos) ir.ScopeID {
23
+ i := sort.Search(len(marks), func(i int) bool {
24
+ return xposBefore(pos, marks[i].Pos)
25
+ })
26
+ if i == 0 {
27
+ return 0
28
+ }
29
+ return marks[i-1].Scope
30
+ }
31
+
32
+ func assembleScopes(fnsym *obj.LSym, fn *ir.Func, dwarfVars []*dwarf.Var, varScopes []ir.ScopeID) []dwarf.Scope {
33
+ // Initialize the DWARF scope tree based on lexical scopes.
34
+ dwarfScopes := make([]dwarf.Scope, 1+len(fn.Parents))
35
+ for i, parent := range fn.Parents {
36
+ dwarfScopes[i+1].Parent = int32(parent)
37
+ }
38
+
39
+ scopeVariables(dwarfVars, varScopes, dwarfScopes, fnsym.ABI() != obj.ABI0)
40
+ if fnsym.Func().Text != nil {
41
+ scopePCs(fnsym, fn.Marks, dwarfScopes)
42
+ }
43
+ return compactScopes(dwarfScopes)
44
+ }
45
+
46
+ // scopeVariables assigns DWARF variable records to their scopes.
47
+ func scopeVariables(dwarfVars []*dwarf.Var, varScopes []ir.ScopeID, dwarfScopes []dwarf.Scope, regabi bool) {
48
+ if regabi {
49
+ sort.Stable(varsByScope{dwarfVars, varScopes})
50
+ } else {
51
+ sort.Stable(varsByScopeAndOffset{dwarfVars, varScopes})
52
+ }
53
+
54
+ i0 := 0
55
+ for i := range dwarfVars {
56
+ if varScopes[i] == varScopes[i0] {
57
+ continue
58
+ }
59
+ dwarfScopes[varScopes[i0]].Vars = dwarfVars[i0:i]
60
+ i0 = i
61
+ }
62
+ if i0 < len(dwarfVars) {
63
+ dwarfScopes[varScopes[i0]].Vars = dwarfVars[i0:]
64
+ }
65
+ }
66
+
67
+ // scopePCs assigns PC ranges to their scopes.
68
+ func scopePCs(fnsym *obj.LSym, marks []ir.Mark, dwarfScopes []dwarf.Scope) {
69
+ // If there aren't any child scopes (in particular, when scope
70
+ // tracking is disabled), we can skip a whole lot of work.
71
+ if len(marks) == 0 {
72
+ return
73
+ }
74
+ p0 := fnsym.Func().Text
75
+ scope := findScope(marks, p0.Pos)
76
+ for p := p0; p != nil; p = p.Link {
77
+ if p.Pos == p0.Pos {
78
+ continue
79
+ }
80
+ dwarfScopes[scope].AppendRange(dwarf.Range{Start: p0.Pc, End: p.Pc})
81
+ p0 = p
82
+ scope = findScope(marks, p0.Pos)
83
+ }
84
+ if p0.Pc < fnsym.Size {
85
+ dwarfScopes[scope].AppendRange(dwarf.Range{Start: p0.Pc, End: fnsym.Size})
86
+ }
87
+ }
88
+
89
+ func compactScopes(dwarfScopes []dwarf.Scope) []dwarf.Scope {
90
+ // Reverse pass to propagate PC ranges to parent scopes.
91
+ for i := len(dwarfScopes) - 1; i > 0; i-- {
92
+ s := &dwarfScopes[i]
93
+ dwarfScopes[s.Parent].UnifyRanges(s)
94
+ }
95
+
96
+ return dwarfScopes
97
+ }
98
+
99
+ type varsByScopeAndOffset struct {
100
+ vars []*dwarf.Var
101
+ scopes []ir.ScopeID
102
+ }
103
+
104
+ func (v varsByScopeAndOffset) Len() int {
105
+ return len(v.vars)
106
+ }
107
+
108
+ func (v varsByScopeAndOffset) Less(i, j int) bool {
109
+ if v.scopes[i] != v.scopes[j] {
110
+ return v.scopes[i] < v.scopes[j]
111
+ }
112
+ return v.vars[i].StackOffset < v.vars[j].StackOffset
113
+ }
114
+
115
+ func (v varsByScopeAndOffset) Swap(i, j int) {
116
+ v.vars[i], v.vars[j] = v.vars[j], v.vars[i]
117
+ v.scopes[i], v.scopes[j] = v.scopes[j], v.scopes[i]
118
+ }
119
+
120
+ type varsByScope struct {
121
+ vars []*dwarf.Var
122
+ scopes []ir.ScopeID
123
+ }
124
+
125
+ func (v varsByScope) Len() int {
126
+ return len(v.vars)
127
+ }
128
+
129
+ func (v varsByScope) Less(i, j int) bool {
130
+ return v.scopes[i] < v.scopes[j]
131
+ }
132
+
133
+ func (v varsByScope) Swap(i, j int) {
134
+ v.vars[i], v.vars[j] = v.vars[j], v.vars[i]
135
+ v.scopes[i], v.scopes[j] = v.scopes[j], v.scopes[i]
136
+ }
go/src/cmd/compile/internal/dwarfgen/scope_test.go ADDED
@@ -0,0 +1,528 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2016 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 dwarfgen
6
+
7
+ import (
8
+ "cmp"
9
+ "debug/dwarf"
10
+ "fmt"
11
+ "internal/platform"
12
+ "internal/testenv"
13
+ "os"
14
+ "path/filepath"
15
+ "runtime"
16
+ "slices"
17
+ "strconv"
18
+ "strings"
19
+ "testing"
20
+
21
+ "cmd/internal/objfile"
22
+ )
23
+
24
+ type testline struct {
25
+ // line is one line of go source
26
+ line string
27
+
28
+ // scopes is a list of scope IDs of all the lexical scopes that this line
29
+ // of code belongs to.
30
+ // Scope IDs are assigned by traversing the tree of lexical blocks of a
31
+ // function in pre-order
32
+ // Scope IDs are function specific, i.e. scope 0 is always the root scope
33
+ // of the function that this line belongs to. Empty scopes are not assigned
34
+ // an ID (because they are not saved in debug_info).
35
+ // Scope 0 is always omitted from this list since all lines always belong
36
+ // to it.
37
+ scopes []int
38
+
39
+ // vars is the list of variables that belong in scopes[len(scopes)-1].
40
+ // Local variables are prefixed with "var ", formal parameters with "arg ".
41
+ // Must be ordered alphabetically.
42
+ // Set to nil to skip the check.
43
+ vars []string
44
+
45
+ // decl is the list of variables declared at this line.
46
+ decl []string
47
+
48
+ // declBefore is the list of variables declared at or before this line.
49
+ declBefore []string
50
+ }
51
+
52
+ var testfile = []testline{
53
+ {line: "package main"},
54
+ {line: "var sink any"},
55
+ {line: "func f1(x int) { }"},
56
+ {line: "func f2(x int) { }"},
57
+ {line: "func f3(x int) { }"},
58
+ {line: "func f4(x int) { }"},
59
+ {line: "func f5(x int) { }"},
60
+ {line: "func f6(x int) { }"},
61
+ {line: "func leak(x interface{}) { sink = x }"},
62
+ {line: "func gret1() int { return 2 }"},
63
+ {line: "func gretbool() bool { return true }"},
64
+ {line: "func gret3() (int, int, int) { return 0, 1, 2 }"},
65
+ {line: "var v = []int{ 0, 1, 2 }"},
66
+ {line: "var ch = make(chan int)"},
67
+ {line: "var floatch = make(chan float64)"},
68
+ {line: "var iface interface{}"},
69
+ {line: "func TestNestedFor() {", vars: []string{"var a int"}},
70
+ {line: " a := 0", decl: []string{"a"}},
71
+ {line: " f1(a)"},
72
+ {line: " for i := 0; i < 5; i++ {", scopes: []int{1}, vars: []string{"var i int"}, decl: []string{"i"}},
73
+ {line: " f2(i)", scopes: []int{1}},
74
+ {line: " for i := 0; i < 5; i++ {", scopes: []int{1, 2}, vars: []string{"var i int"}, decl: []string{"i"}},
75
+ {line: " f3(i)", scopes: []int{1, 2}},
76
+ {line: " }"},
77
+ {line: " f4(i)", scopes: []int{1}},
78
+ {line: " }"},
79
+ {line: " f5(a)"},
80
+ {line: "}"},
81
+ {line: "func TestOas2() {", vars: []string{}},
82
+ {line: " if a, b, c := gret3(); a != 1 {", scopes: []int{1}, vars: []string{"var a int", "var b int", "var c int"}},
83
+ {line: " f1(a)", scopes: []int{1}},
84
+ {line: " f1(b)", scopes: []int{1}},
85
+ {line: " f1(c)", scopes: []int{1}},
86
+ {line: " }"},
87
+ {line: " for i, x := range v {", scopes: []int{2}, vars: []string{"var i int", "var x int"}},
88
+ {line: " f1(i)", scopes: []int{2}},
89
+ {line: " f1(x)", scopes: []int{2}},
90
+ {line: " }"},
91
+ {line: " if a, ok := <- ch; ok {", scopes: []int{3}, vars: []string{"var a int", "var ok bool"}},
92
+ {line: " f1(a)", scopes: []int{3}},
93
+ {line: " }"},
94
+ {line: " if a, ok := iface.(int); ok {", scopes: []int{4}, vars: []string{"var a int", "var ok bool"}},
95
+ {line: " f1(a)", scopes: []int{4}},
96
+ {line: " }"},
97
+ {line: "}"},
98
+ {line: "func TestIfElse() {"},
99
+ {line: " if x := gret1(); x != 0 {", scopes: []int{1}, vars: []string{"var x int"}},
100
+ {line: " a := 0", scopes: []int{1, 2}, vars: []string{"var a int"}},
101
+ {line: " f1(a); f1(x)", scopes: []int{1, 2}},
102
+ {line: " } else {"},
103
+ {line: " b := 1", scopes: []int{1, 3}, vars: []string{"var b int"}},
104
+ {line: " f1(b); f1(x+1)", scopes: []int{1, 3}},
105
+ {line: " }"},
106
+ {line: "}"},
107
+ {line: "func TestSwitch() {", vars: []string{}},
108
+ {line: " switch x := gret1(); x {", scopes: []int{1}, vars: []string{"var x int"}},
109
+ {line: " case 0:", scopes: []int{1, 2}},
110
+ {line: " i := x + 5", scopes: []int{1, 2}, vars: []string{"var i int"}},
111
+ {line: " f1(x); f1(i)", scopes: []int{1, 2}},
112
+ {line: " case 1:", scopes: []int{1, 3}},
113
+ {line: " j := x + 10", scopes: []int{1, 3}, vars: []string{"var j int"}},
114
+ {line: " f1(x); f1(j)", scopes: []int{1, 3}},
115
+ {line: " case 2:", scopes: []int{1, 4}},
116
+ {line: " k := x + 2", scopes: []int{1, 4}, vars: []string{"var k int"}},
117
+ {line: " f1(x); f1(k)", scopes: []int{1, 4}},
118
+ {line: " }"},
119
+ {line: "}"},
120
+ {line: "func TestTypeSwitch() {", vars: []string{}},
121
+ {line: " switch x := iface.(type) {"},
122
+ {line: " case int:", scopes: []int{1}},
123
+ {line: " f1(x)", scopes: []int{1}, vars: []string{"var x int"}},
124
+ {line: " case uint8:", scopes: []int{2}},
125
+ {line: " f1(int(x))", scopes: []int{2}, vars: []string{"var x uint8"}},
126
+ {line: " case float64:", scopes: []int{3}},
127
+ {line: " f1(int(x)+1)", scopes: []int{3}, vars: []string{"var x float64"}},
128
+ {line: " }"},
129
+ {line: "}"},
130
+ {line: "func TestSelectScope() {"},
131
+ {line: " select {"},
132
+ {line: " case i := <- ch:", scopes: []int{1}},
133
+ {line: " f1(i)", scopes: []int{1}, vars: []string{"var i int"}},
134
+ {line: " case f := <- floatch:", scopes: []int{2}},
135
+ {line: " f1(int(f))", scopes: []int{2}, vars: []string{"var f float64"}},
136
+ {line: " }"},
137
+ {line: "}"},
138
+ {line: "func TestBlock() {", vars: []string{"var a int"}},
139
+ {line: " a := 1"},
140
+ {line: " {"},
141
+ {line: " b := 2", scopes: []int{1}, vars: []string{"var b int"}},
142
+ {line: " f1(b)", scopes: []int{1}},
143
+ {line: " f1(a)", scopes: []int{1}},
144
+ {line: " }"},
145
+ {line: "}"},
146
+ {line: "func TestDiscontiguousRanges() {", vars: []string{"var a int"}},
147
+ {line: " a := 0"},
148
+ {line: " f1(a)"},
149
+ {line: " {"},
150
+ {line: " b := 0", scopes: []int{1}, vars: []string{"var b int"}},
151
+ {line: " f2(b)", scopes: []int{1}},
152
+ {line: " if gretbool() {", scopes: []int{1}},
153
+ {line: " c := 0", scopes: []int{1, 2}, vars: []string{"var c int"}},
154
+ {line: " f3(c)", scopes: []int{1, 2}},
155
+ {line: " } else {"},
156
+ {line: " c := 1.1", scopes: []int{1, 3}, vars: []string{"var c float64"}},
157
+ {line: " f4(int(c))", scopes: []int{1, 3}},
158
+ {line: " }"},
159
+ {line: " f5(b)", scopes: []int{1}},
160
+ {line: " }"},
161
+ {line: " f6(a)"},
162
+ {line: "}"},
163
+ {line: "func TestClosureScope() {", vars: []string{"var a int", "var b int", "var f func(int)"}},
164
+ {line: " a := 1; b := 1"},
165
+ {line: " f := func(c int) {", scopes: []int{0}, vars: []string{"arg c int", "var &b *int", "var a int", "var d int"}, declBefore: []string{"&b", "a"}},
166
+ {line: " d := 3"},
167
+ {line: " f1(c); f1(d)"},
168
+ {line: " if e := 3; e != 0 {", scopes: []int{1}, vars: []string{"var e int"}},
169
+ {line: " f1(e)", scopes: []int{1}},
170
+ {line: " f1(a)", scopes: []int{1}},
171
+ {line: " b = 2", scopes: []int{1}},
172
+ {line: " }"},
173
+ {line: " }"},
174
+ {line: " f(3); f1(b)"},
175
+ {line: "}"},
176
+ {line: "func TestEscape() {"},
177
+ {line: " a := 1", vars: []string{"var a int"}},
178
+ {line: " {"},
179
+ {line: " b := 2", scopes: []int{1}, vars: []string{"var &b *int", "var p *int"}},
180
+ {line: " p := &b", scopes: []int{1}},
181
+ {line: " f1(a)", scopes: []int{1}},
182
+ {line: " leak(p)", scopes: []int{1}},
183
+ {line: " }"},
184
+ {line: "}"},
185
+ {line: "var fglob func() int"},
186
+ {line: "func TestCaptureVar(flag bool) {"},
187
+ {line: " a := 1", vars: []string{"arg flag bool", "var a int"}}, // TODO(register args) restore "arg ~r1 func() int",
188
+ {line: " if flag {"},
189
+ {line: " b := 2", scopes: []int{1}, vars: []string{"var b int", "var f func() int"}},
190
+ {line: " f := func() int {", scopes: []int{1, 0}},
191
+ {line: " return b + 1"},
192
+ {line: " }"},
193
+ {line: " fglob = f", scopes: []int{1}},
194
+ {line: " }"},
195
+ {line: " f1(a)"},
196
+ {line: "}"},
197
+ {line: "func main() {"},
198
+ {line: " TestNestedFor()"},
199
+ {line: " TestOas2()"},
200
+ {line: " TestIfElse()"},
201
+ {line: " TestSwitch()"},
202
+ {line: " TestTypeSwitch()"},
203
+ {line: " TestSelectScope()"},
204
+ {line: " TestBlock()"},
205
+ {line: " TestDiscontiguousRanges()"},
206
+ {line: " TestClosureScope()"},
207
+ {line: " TestEscape()"},
208
+ {line: " TestCaptureVar(true)"},
209
+ {line: "}"},
210
+ }
211
+
212
+ const detailOutput = false
213
+
214
+ // Compiles testfile checks that the description of lexical blocks emitted
215
+ // by the linker in debug_info, for each function in the main package,
216
+ // corresponds to what we expect it to be.
217
+ func TestScopeRanges(t *testing.T) {
218
+ testenv.MustHaveGoBuild(t)
219
+ t.Parallel()
220
+
221
+ if !platform.ExecutableHasDWARF(runtime.GOOS, runtime.GOARCH) {
222
+ t.Skipf("skipping on %s/%s: no DWARF symbol table in executables", runtime.GOOS, runtime.GOARCH)
223
+ }
224
+
225
+ src, f := gobuild(t, t.TempDir(), false, testfile)
226
+ defer f.Close()
227
+
228
+ // the compiler uses forward slashes for paths even on windows
229
+ src = strings.ReplaceAll(src, "\\", "/")
230
+
231
+ pcln, err := f.PCLineTable()
232
+ if err != nil {
233
+ t.Fatal(err)
234
+ }
235
+ dwarfData, err := f.DWARF()
236
+ if err != nil {
237
+ t.Fatal(err)
238
+ }
239
+ dwarfReader := dwarfData.Reader()
240
+
241
+ lines := make(map[line][]*lexblock)
242
+
243
+ for {
244
+ entry, err := dwarfReader.Next()
245
+ if err != nil {
246
+ t.Fatal(err)
247
+ }
248
+ if entry == nil {
249
+ break
250
+ }
251
+
252
+ if entry.Tag != dwarf.TagSubprogram {
253
+ continue
254
+ }
255
+
256
+ name, ok := entry.Val(dwarf.AttrName).(string)
257
+ if !ok || !strings.HasPrefix(name, "main.Test") {
258
+ continue
259
+ }
260
+
261
+ var scope lexblock
262
+ ctxt := scopexplainContext{
263
+ dwarfData: dwarfData,
264
+ dwarfReader: dwarfReader,
265
+ scopegen: 1,
266
+ }
267
+
268
+ readScope(&ctxt, &scope, entry)
269
+
270
+ scope.markLines(pcln, lines)
271
+ }
272
+
273
+ anyerror := false
274
+ for i := range testfile {
275
+ tgt := testfile[i].scopes
276
+ out := lines[line{src, i + 1}]
277
+
278
+ if detailOutput {
279
+ t.Logf("%s // %v", testfile[i].line, out)
280
+ }
281
+
282
+ scopesok := checkScopes(tgt, out)
283
+ if !scopesok {
284
+ t.Logf("mismatch at line %d %q: expected: %v got: %v\n", i, testfile[i].line, tgt, scopesToString(out))
285
+ }
286
+
287
+ varsok := true
288
+ if testfile[i].vars != nil {
289
+ if len(out) > 0 {
290
+ varsok = checkVars(testfile[i].vars, out[len(out)-1].vars)
291
+ if !varsok {
292
+ t.Logf("variable mismatch at line %d %q for scope %d: expected: %v got: %v\n", i+1, testfile[i].line, out[len(out)-1].id, testfile[i].vars, out[len(out)-1].vars)
293
+ }
294
+ for j := range testfile[i].decl {
295
+ if line := declLineForVar(out[len(out)-1].vars, testfile[i].decl[j]); line != i+1 {
296
+ t.Errorf("wrong declaration line for variable %s, expected %d got: %d", testfile[i].decl[j], i+1, line)
297
+ }
298
+ }
299
+
300
+ for j := range testfile[i].declBefore {
301
+ if line := declLineForVar(out[len(out)-1].vars, testfile[i].declBefore[j]); line > i+1 {
302
+ t.Errorf("wrong declaration line for variable %s, expected %d (or less) got: %d", testfile[i].declBefore[j], i+1, line)
303
+ }
304
+ }
305
+ }
306
+ }
307
+
308
+ anyerror = anyerror || !scopesok || !varsok
309
+ }
310
+
311
+ if anyerror {
312
+ t.Fatalf("mismatched output")
313
+ }
314
+ }
315
+
316
+ func scopesToString(v []*lexblock) string {
317
+ r := make([]string, len(v))
318
+ for i, s := range v {
319
+ r[i] = strconv.Itoa(s.id)
320
+ }
321
+ return "[ " + strings.Join(r, ", ") + " ]"
322
+ }
323
+
324
+ func checkScopes(tgt []int, out []*lexblock) bool {
325
+ if len(out) > 0 {
326
+ // omit scope 0
327
+ out = out[1:]
328
+ }
329
+ if len(tgt) != len(out) {
330
+ return false
331
+ }
332
+ for i := range tgt {
333
+ if tgt[i] != out[i].id {
334
+ return false
335
+ }
336
+ }
337
+ return true
338
+ }
339
+
340
+ func checkVars(tgt []string, out []variable) bool {
341
+ if len(tgt) != len(out) {
342
+ return false
343
+ }
344
+ for i := range tgt {
345
+ if tgt[i] != out[i].expr {
346
+ return false
347
+ }
348
+ }
349
+ return true
350
+ }
351
+
352
+ func declLineForVar(scope []variable, name string) int {
353
+ for i := range scope {
354
+ if scope[i].name() == name {
355
+ return scope[i].declLine
356
+ }
357
+ }
358
+ return -1
359
+ }
360
+
361
+ type lexblock struct {
362
+ id int
363
+ ranges [][2]uint64
364
+ vars []variable
365
+ scopes []lexblock
366
+ }
367
+
368
+ type variable struct {
369
+ expr string
370
+ declLine int
371
+ }
372
+
373
+ func (v *variable) name() string {
374
+ return strings.Split(v.expr, " ")[1]
375
+ }
376
+
377
+ type line struct {
378
+ file string
379
+ lineno int
380
+ }
381
+
382
+ type scopexplainContext struct {
383
+ dwarfData *dwarf.Data
384
+ dwarfReader *dwarf.Reader
385
+ scopegen int
386
+ }
387
+
388
+ // readScope reads the DW_TAG_lexical_block or the DW_TAG_subprogram in
389
+ // entry and writes a description in scope.
390
+ // Nested DW_TAG_lexical_block entries are read recursively.
391
+ func readScope(ctxt *scopexplainContext, scope *lexblock, entry *dwarf.Entry) {
392
+ var err error
393
+ scope.ranges, err = ctxt.dwarfData.Ranges(entry)
394
+ if err != nil {
395
+ panic(err)
396
+ }
397
+ for {
398
+ e, err := ctxt.dwarfReader.Next()
399
+ if err != nil {
400
+ panic(err)
401
+ }
402
+ switch e.Tag {
403
+ case 0:
404
+ slices.SortFunc(scope.vars, func(a, b variable) int {
405
+ return cmp.Compare(a.expr, b.expr)
406
+ })
407
+ return
408
+ case dwarf.TagFormalParameter:
409
+ typ, err := ctxt.dwarfData.Type(e.Val(dwarf.AttrType).(dwarf.Offset))
410
+ if err != nil {
411
+ panic(err)
412
+ }
413
+ scope.vars = append(scope.vars, entryToVar(e, "arg", typ))
414
+ case dwarf.TagVariable:
415
+ typ, err := ctxt.dwarfData.Type(e.Val(dwarf.AttrType).(dwarf.Offset))
416
+ if err != nil {
417
+ panic(err)
418
+ }
419
+ scope.vars = append(scope.vars, entryToVar(e, "var", typ))
420
+ case dwarf.TagLexDwarfBlock:
421
+ scope.scopes = append(scope.scopes, lexblock{id: ctxt.scopegen})
422
+ ctxt.scopegen++
423
+ readScope(ctxt, &scope.scopes[len(scope.scopes)-1], e)
424
+ }
425
+ }
426
+ }
427
+
428
+ func entryToVar(e *dwarf.Entry, kind string, typ dwarf.Type) variable {
429
+ return variable{
430
+ fmt.Sprintf("%s %s %s", kind, e.Val(dwarf.AttrName).(string), typ.String()),
431
+ int(e.Val(dwarf.AttrDeclLine).(int64)),
432
+ }
433
+ }
434
+
435
+ // markLines marks all lines that belong to this scope with this scope
436
+ // Recursively calls markLines for all children scopes.
437
+ func (scope *lexblock) markLines(pcln objfile.Liner, lines map[line][]*lexblock) {
438
+ for _, r := range scope.ranges {
439
+ for pc := r[0]; pc < r[1]; pc++ {
440
+ file, lineno, _ := pcln.PCToLine(pc)
441
+ l := line{file, lineno}
442
+ if len(lines[l]) == 0 || lines[l][len(lines[l])-1] != scope {
443
+ lines[l] = append(lines[l], scope)
444
+ }
445
+ }
446
+ }
447
+
448
+ for i := range scope.scopes {
449
+ scope.scopes[i].markLines(pcln, lines)
450
+ }
451
+ }
452
+
453
+ func gobuild(t *testing.T, dir string, optimized bool, testfile []testline) (string, *objfile.File) {
454
+ src := filepath.Join(dir, "test.go")
455
+ dst := filepath.Join(dir, "out.o")
456
+
457
+ f, err := os.Create(src)
458
+ if err != nil {
459
+ t.Fatal(err)
460
+ }
461
+ for i := range testfile {
462
+ f.Write([]byte(testfile[i].line))
463
+ f.Write([]byte{'\n'})
464
+ }
465
+ f.Close()
466
+
467
+ args := []string{"build"}
468
+ if !optimized {
469
+ args = append(args, "-gcflags=-N -l")
470
+ }
471
+ args = append(args, "-o", dst, src)
472
+
473
+ cmd := testenv.Command(t, testenv.GoToolPath(t), args...)
474
+ if b, err := cmd.CombinedOutput(); err != nil {
475
+ t.Logf("build: %s\n", string(b))
476
+ t.Fatal(err)
477
+ }
478
+
479
+ pkg, err := objfile.Open(dst)
480
+ if err != nil {
481
+ t.Fatal(err)
482
+ }
483
+ return src, pkg
484
+ }
485
+
486
+ // TestEmptyDwarfRanges tests that no list entry in debug_ranges has start == end.
487
+ // See issue #23928.
488
+ func TestEmptyDwarfRanges(t *testing.T) {
489
+ testenv.MustHaveGoRun(t)
490
+ t.Parallel()
491
+
492
+ if !platform.ExecutableHasDWARF(runtime.GOOS, runtime.GOARCH) {
493
+ t.Skipf("skipping on %s/%s: no DWARF symbol table in executables", runtime.GOOS, runtime.GOARCH)
494
+ }
495
+
496
+ _, f := gobuild(t, t.TempDir(), true, []testline{{line: "package main"}, {line: "func main(){ println(\"hello\") }"}})
497
+ defer f.Close()
498
+
499
+ dwarfData, err := f.DWARF()
500
+ if err != nil {
501
+ t.Fatal(err)
502
+ }
503
+ dwarfReader := dwarfData.Reader()
504
+
505
+ for {
506
+ entry, err := dwarfReader.Next()
507
+ if err != nil {
508
+ t.Fatal(err)
509
+ }
510
+ if entry == nil {
511
+ break
512
+ }
513
+
514
+ ranges, err := dwarfData.Ranges(entry)
515
+ if err != nil {
516
+ t.Fatal(err)
517
+ }
518
+ if ranges == nil {
519
+ continue
520
+ }
521
+
522
+ for _, rng := range ranges {
523
+ if rng[0] == rng[1] {
524
+ t.Errorf("range entry with start == end: %v", rng)
525
+ }
526
+ }
527
+ }
528
+ }
go/src/cmd/compile/internal/escape/alias.go ADDED
@@ -0,0 +1,528 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2025 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 escape
6
+
7
+ import (
8
+ "cmd/compile/internal/base"
9
+ "cmd/compile/internal/ir"
10
+ "cmd/internal/src"
11
+ "fmt"
12
+ "maps"
13
+ "path/filepath"
14
+ )
15
+
16
+ type aliasAnalysis struct {
17
+ // fn is the function being analyzed.
18
+ fn *ir.Func
19
+
20
+ // candidateSlices are declared slices that
21
+ // start unaliased and might still be unaliased.
22
+ candidateSlices map[*ir.Name]candidateSlice
23
+
24
+ // noAliasAppends are appends that have been
25
+ // proven to use an unaliased slice.
26
+ noAliasAppends []*ir.CallExpr
27
+
28
+ // loops is a stack of observed loops,
29
+ // each with a list of candidate appends.
30
+ loops [][]candidateAppend
31
+
32
+ // State for optional validation checking (doubleCheck mode):
33
+ processed map[ir.Node]int // count of times each node was processed, for doubleCheck mode
34
+ doubleCheck bool // whether to do doubleCheck mode
35
+ }
36
+
37
+ // candidateSlice tracks information about a declared slice
38
+ // that might be unaliased.
39
+ type candidateSlice struct {
40
+ loopDepth int // depth of loop when slice was declared
41
+ }
42
+
43
+ // candidateAppend tracks information about an OAPPEND that
44
+ // might be using an unaliased slice.
45
+ type candidateAppend struct {
46
+ s *ir.Name // the slice argument in 's = append(s, ...)'
47
+ call *ir.CallExpr // the append call
48
+ }
49
+
50
+ // aliasAnalysis looks for specific patterns of slice usage and proves
51
+ // that certain appends are operating on non-aliased slices.
52
+ //
53
+ // This allows us to emit calls to free the backing arrays for certain
54
+ // non-aliased slices at runtime when we know the memory is logically dead.
55
+ //
56
+ // The analysis is conservative, giving up on any operation we do not
57
+ // explicitly understand.
58
+ func (aa *aliasAnalysis) analyze(fn *ir.Func) {
59
+ // Walk the function body to discover slice declarations, their uses,
60
+ // and any append that we can prove is using an unaliased slice.
61
+ //
62
+ // An example is:
63
+ //
64
+ // var s []T
65
+ // for _, v := range input {
66
+ // f()
67
+ // s = append(s, g(v)) // s cannot be aliased here
68
+ // h()
69
+ // }
70
+ // return s
71
+ //
72
+ // Here, we can prove that the append to s is operating on an unaliased slice,
73
+ // and that conclusion is unaffected by s later being returned and escaping.
74
+ //
75
+ // In contrast, in this example, the aliasing of s in the loop body means the
76
+ // append can be operating on an aliased slice, so we do not record s as unaliased:
77
+ //
78
+ // var s []T
79
+ // var alias []T
80
+ // for _, v := range input {
81
+ // s = append(s, v) // s is aliased on second pass through loop body
82
+ // alias = s
83
+ // }
84
+ //
85
+ // Arbitrary uses of s after an append do not affect the aliasing conclusion
86
+ // for that append, but only if the append cannot be revisited at execution time
87
+ // via a loop or goto.
88
+ //
89
+ // We track the loop depth when a slice was declared and verify all uses of a slice
90
+ // are non-aliasing until we return to that depth. In other words, we make sure
91
+ // we have processed any possible execution-time revisiting of the slice prior
92
+ // to making our final determination.
93
+ //
94
+ // This approach helps for example with nested loops, such as:
95
+ //
96
+ // var s []int
97
+ // for range 10 {
98
+ // for range 10 {
99
+ // s = append(s, 0) // s is proven as non-aliased here
100
+ // }
101
+ // }
102
+ // alias = s // both loops are complete
103
+ //
104
+ // Or in contrast:
105
+ //
106
+ // var s []int
107
+ // for range 10 {
108
+ // for range 10 {
109
+ // s = append(s, 0) // s is treated as aliased here
110
+ // }
111
+ // alias = s // aliased, and outermost loop cycles back
112
+ // }
113
+ //
114
+ // As we walk the function, we look for things like:
115
+ //
116
+ // 1. Slice declarations (currently supporting 'var s []T', 's := make([]T, ...)',
117
+ // and 's := []T{...}').
118
+ // 2. Appends to a slice of the form 's = append(s, ...)'.
119
+ // 3. Other uses of the slice, which we treat as potential aliasing outside
120
+ // of a few known safe cases.
121
+ // 4. A start of a loop, which we track in a stack so that
122
+ // any uses of a slice within a loop body are treated as potential
123
+ // aliasing, including statements in the loop body after an append.
124
+ // Candidate appends are stored in the loop stack at the loop depth of their
125
+ // corresponding slice declaration (rather than the loop depth of the append),
126
+ // which essentially postpones a decision about the candidate append.
127
+ // 5. An end of a loop, which pops the loop stack and allows us to
128
+ // conclusively treat candidate appends from the loop body based
129
+ // on the loop depth of the slice declaration.
130
+ //
131
+ // Note that as we pop a candidate append at the end of a loop, we know
132
+ // its corresponding slice was unaliased throughout the loop being popped
133
+ // if the slice is still in the candidate slice map (without having been
134
+ // removed for potential aliasing), and we know we can make a final decision
135
+ // about a candidate append if we have returned to the loop depth
136
+ // where its slice was declared. In other words, there is no unanalyzed
137
+ // control flow that could take us back at execution-time to the
138
+ // candidate append in the now analyzed loop. This helps for example
139
+ // with nested loops, such as in our examples just above.
140
+ //
141
+ // We give up on a particular candidate slice if we see any use of it
142
+ // that we don't explicitly understand, and we give up on all of
143
+ // our candidate slices if we see any goto or label, which could be
144
+ // unstructured control flow. (TODO(thepudds): we remove the goto/label
145
+ // restriction in a subsequent CL.)
146
+ //
147
+ // Note that the intended use is to indicate that a slice is safe to pass
148
+ // to runtime.freegc, which currently requires that the passed pointer
149
+ // point to the base of its heap object.
150
+ //
151
+ // Therefore, we currently do not allow any re-slicing of the slice, though we could
152
+ // potentially allow s[0:x] or s[:x] or similar. (Slice expressions that alter
153
+ // the capacity might be possible to allow with freegc changes, though they are
154
+ // currently disallowed here like all slice expressions).
155
+ //
156
+ // TODO(thepudds): we could support the slice being used as non-escaping function call parameter
157
+ // but to do that, we need to verify any creation of specials via user code triggers an escape,
158
+ // or mail better runtime.freegc support for specials, or have a temporary compile-time solution
159
+ // for specials. (Currently, this analysis side-steps specials because any use of a slice
160
+ // that might cause a user-created special will cause it to be treated as aliased, and
161
+ // separately, runtime.freegc handles profiling-related specials).
162
+
163
+ // Initialize.
164
+ aa.fn = fn
165
+ aa.candidateSlices = make(map[*ir.Name]candidateSlice) // slices that might be unaliased
166
+
167
+ // doubleCheck controls whether we do a sanity check of our processing logic
168
+ // by counting each node visited in our main pass, and then comparing those counts
169
+ // against a simple walk at the end. The main intent is to help catch missing
170
+ // any nodes squirreled away in some spot we forgot to examine in our main pass.
171
+ aa.doubleCheck = base.Debug.EscapeAliasCheck > 0
172
+ aa.processed = make(map[ir.Node]int)
173
+
174
+ if base.Debug.EscapeAlias >= 2 {
175
+ aa.diag(fn.Pos(), fn, "====== starting func", "======")
176
+ }
177
+
178
+ ir.DoChildren(fn, aa.visit)
179
+
180
+ for _, call := range aa.noAliasAppends {
181
+ if base.Debug.EscapeAlias >= 1 {
182
+ base.WarnfAt(call.Pos(), "alias analysis: append using non-aliased slice: %v in func %v",
183
+ call, fn)
184
+ }
185
+ if base.Debug.FreeAppend > 0 {
186
+ call.AppendNoAlias = true
187
+ }
188
+ }
189
+
190
+ if aa.doubleCheck {
191
+ doubleCheckProcessed(fn, aa.processed)
192
+ }
193
+ }
194
+
195
+ func (aa *aliasAnalysis) visit(n ir.Node) bool {
196
+ if n == nil {
197
+ return false
198
+ }
199
+
200
+ if base.Debug.EscapeAlias >= 3 {
201
+ fmt.Printf("%-25s alias analysis: visiting node: %12s %-18T %v\n",
202
+ fmtPosShort(n.Pos())+":", n.Op().String(), n, n)
203
+ }
204
+
205
+ // As we visit nodes, we want to ensure we handle all children
206
+ // without missing any (through ignorance or future changes).
207
+ // We do this by counting nodes as we visit them or otherwise
208
+ // declare a node to be fully processed.
209
+ //
210
+ // In particular, we want to ensure we don't miss the use
211
+ // of a slice in some expression that might be an aliasing usage.
212
+ //
213
+ // When doubleCheck is enabled, we compare the counts
214
+ // accumulated in our analysis against counts from a trivial walk,
215
+ // failing if there is any mismatch.
216
+ //
217
+ // This call here counts that we have visited this node n
218
+ // via our main visit method. (In contrast, some nodes won't
219
+ // be visited by the main visit method, but instead will be
220
+ // manually marked via countProcessed when we believe we have fully
221
+ // dealt with the node).
222
+ aa.countProcessed(n)
223
+
224
+ switch n.Op() {
225
+ case ir.ODCL:
226
+ decl := n.(*ir.Decl)
227
+
228
+ if decl.X != nil && decl.X.Type().IsSlice() && decl.X.Class == ir.PAUTO {
229
+ s := decl.X
230
+ if _, ok := aa.candidateSlices[s]; ok {
231
+ base.FatalfAt(n.Pos(), "candidate slice already tracked as candidate: %v", s)
232
+ }
233
+ if base.Debug.EscapeAlias >= 2 {
234
+ aa.diag(n.Pos(), s, "adding candidate slice", "(loop depth: %d)", len(aa.loops))
235
+ }
236
+ aa.candidateSlices[s] = candidateSlice{loopDepth: len(aa.loops)}
237
+ }
238
+ // No children aside from the declared ONAME.
239
+ aa.countProcessed(decl.X)
240
+ return false
241
+
242
+ case ir.ONAME:
243
+
244
+ // We are seeing a name we have not already handled in another case,
245
+ // so remove any corresponding candidate slice.
246
+ if n.Type().IsSlice() {
247
+ name := n.(*ir.Name)
248
+ _, ok := aa.candidateSlices[name]
249
+ if ok {
250
+ delete(aa.candidateSlices, name)
251
+ if base.Debug.EscapeAlias >= 2 {
252
+ aa.diag(n.Pos(), name, "removing candidate slice", "")
253
+ }
254
+ }
255
+ }
256
+ // No children.
257
+ return false
258
+
259
+ case ir.OAS2:
260
+ n := n.(*ir.AssignListStmt)
261
+ aa.analyzeAssign(n, n.Lhs, n.Rhs)
262
+ return false
263
+
264
+ case ir.OAS:
265
+ assign := n.(*ir.AssignStmt)
266
+ aa.analyzeAssign(n, []ir.Node{assign.X}, []ir.Node{assign.Y})
267
+ return false
268
+
269
+ case ir.OFOR, ir.ORANGE:
270
+ aa.visitList(n.Init())
271
+
272
+ if n.Op() == ir.ORANGE {
273
+ // TODO(thepudds): previously we visited this range expression
274
+ // in the switch just below, after pushing the loop. This current placement
275
+ // is more correct, but generate a test or find an example in stdlib or similar
276
+ // where it matters. (Our current tests do not complain.)
277
+ aa.visit(n.(*ir.RangeStmt).X)
278
+ }
279
+
280
+ // Push a new loop.
281
+ aa.loops = append(aa.loops, nil)
282
+
283
+ // Process the loop.
284
+ switch n.Op() {
285
+ case ir.OFOR:
286
+ forstmt := n.(*ir.ForStmt)
287
+ aa.visit(forstmt.Cond)
288
+ aa.visitList(forstmt.Body)
289
+ aa.visit(forstmt.Post)
290
+ case ir.ORANGE:
291
+ rangestmt := n.(*ir.RangeStmt)
292
+ aa.visit(rangestmt.Key)
293
+ aa.visit(rangestmt.Value)
294
+ aa.visitList(rangestmt.Body)
295
+ default:
296
+ base.Fatalf("loop not OFOR or ORANGE: %v", n)
297
+ }
298
+
299
+ // Pop the loop.
300
+ var candidateAppends []candidateAppend
301
+ candidateAppends, aa.loops = aa.loops[len(aa.loops)-1], aa.loops[:len(aa.loops)-1]
302
+ for _, a := range candidateAppends {
303
+ // We are done with the loop, so we can validate any candidate appends
304
+ // that have not had their slice removed yet. We know a slice is unaliased
305
+ // throughout the loop if the slice is still in the candidate slice map.
306
+ if cs, ok := aa.candidateSlices[a.s]; ok {
307
+ if cs.loopDepth == len(aa.loops) {
308
+ // We've returned to the loop depth where the slice was declared and
309
+ // hence made it all the way through any loops that started after
310
+ // that declaration.
311
+ if base.Debug.EscapeAlias >= 2 {
312
+ aa.diag(n.Pos(), a.s, "proved non-aliased append",
313
+ "(completed loop, decl at depth: %d)", cs.loopDepth)
314
+ }
315
+ aa.noAliasAppends = append(aa.noAliasAppends, a.call)
316
+ } else if cs.loopDepth < len(aa.loops) {
317
+ if base.Debug.EscapeAlias >= 2 {
318
+ aa.diag(n.Pos(), a.s, "cannot prove non-aliased append",
319
+ "(completed loop, decl at depth: %d)", cs.loopDepth)
320
+ }
321
+ } else {
322
+ panic("impossible: candidate slice loopDepth > current loop depth")
323
+ }
324
+ }
325
+ }
326
+ return false
327
+
328
+ case ir.OLEN, ir.OCAP:
329
+ n := n.(*ir.UnaryExpr)
330
+ if n.X.Op() == ir.ONAME {
331
+ // This does not disqualify a candidate slice.
332
+ aa.visitList(n.Init())
333
+ aa.countProcessed(n.X)
334
+ } else {
335
+ ir.DoChildren(n, aa.visit)
336
+ }
337
+ return false
338
+
339
+ case ir.OCLOSURE:
340
+ // Give up on all our in-progress slices.
341
+ closure := n.(*ir.ClosureExpr)
342
+ if base.Debug.EscapeAlias >= 2 {
343
+ aa.diag(n.Pos(), closure.Func, "clearing all in-progress slices due to OCLOSURE",
344
+ "(was %d in-progress slices)", len(aa.candidateSlices))
345
+ }
346
+ clear(aa.candidateSlices)
347
+ return ir.DoChildren(n, aa.visit)
348
+
349
+ case ir.OLABEL, ir.OGOTO:
350
+ // Give up on all our in-progress slices.
351
+ if base.Debug.EscapeAlias >= 2 {
352
+ aa.diag(n.Pos(), n, "clearing all in-progress slices due to label or goto",
353
+ "(was %d in-progress slices)", len(aa.candidateSlices))
354
+ }
355
+ clear(aa.candidateSlices)
356
+ return false
357
+
358
+ default:
359
+ return ir.DoChildren(n, aa.visit)
360
+ }
361
+ }
362
+
363
+ func (aa *aliasAnalysis) visitList(nodes []ir.Node) {
364
+ for _, n := range nodes {
365
+ aa.visit(n)
366
+ }
367
+ }
368
+
369
+ // analyzeAssign evaluates the assignment dsts... = srcs...
370
+ //
371
+ // assign is an *ir.AssignStmt or *ir.AssignListStmt.
372
+ func (aa *aliasAnalysis) analyzeAssign(assign ir.Node, dsts, srcs []ir.Node) {
373
+ aa.visitList(assign.Init())
374
+ for i := range dsts {
375
+ dst := dsts[i]
376
+ src := srcs[i]
377
+
378
+ if dst.Op() != ir.ONAME || !dst.Type().IsSlice() {
379
+ // Nothing for us to do aside from visiting the remaining children.
380
+ aa.visit(dst)
381
+ aa.visit(src)
382
+ continue
383
+ }
384
+
385
+ // We have a slice being assigned to an ONAME.
386
+
387
+ // Check for simple zero value assignments to an ONAME, which we ignore.
388
+ if src == nil {
389
+ aa.countProcessed(dst)
390
+ continue
391
+ }
392
+
393
+ if base.Debug.EscapeAlias >= 4 {
394
+ srcfn := ""
395
+ if src.Op() == ir.ONAME {
396
+ srcfn = fmt.Sprintf("%v.", src.Name().Curfn)
397
+ }
398
+ aa.diag(assign.Pos(), assign, "visiting slice assignment", "%v.%v = %s%v (%s %T = %s %T)",
399
+ dst.Name().Curfn, dst, srcfn, src, dst.Op().String(), dst, src.Op().String(), src)
400
+ }
401
+
402
+ // Now check what we have on the RHS.
403
+ switch src.Op() {
404
+ // Cases:
405
+
406
+ // Check for s := make([]T, ...) or s := []T{...}, along with the '=' version
407
+ // of those which does not alias s as long as s is not used in the make.
408
+ //
409
+ // TODO(thepudds): we need to be sure that 's := []T{1,2,3}' does not end up backed by a
410
+ // global static. Ad-hoc testing indicates that example and similar seem to be
411
+ // stack allocated, but that was not exhaustive testing. We do have runtime.freegc
412
+ // able to throw if it finds a global static, but should test more.
413
+ //
414
+ // TODO(thepudds): could also possibly allow 's := append([]T(nil), ...)'
415
+ // and 's := append([]T{}, ...)'.
416
+ case ir.OMAKESLICE, ir.OSLICELIT:
417
+ name := dst.(*ir.Name)
418
+ if name.Class == ir.PAUTO {
419
+ if base.Debug.EscapeAlias > 1 {
420
+ aa.diag(assign.Pos(), assign, "assignment from make or slice literal", "")
421
+ }
422
+ // If this is Def=true, the ODCL in the init will causes this to be tracked
423
+ // as a candidate slice. We walk the init and RHS but avoid visiting the name
424
+ // in the LHS, which would remove the slice from the candidate list after it
425
+ // was just added.
426
+ aa.visit(src)
427
+ aa.countProcessed(name)
428
+ continue
429
+ }
430
+
431
+ // Check for s = append(s, <...>).
432
+ case ir.OAPPEND:
433
+ s := dst.(*ir.Name)
434
+ call := src.(*ir.CallExpr)
435
+ if call.Args[0] == s {
436
+ // Matches s = append(s, <...>).
437
+ // First visit other arguments in case they use s.
438
+ aa.visitList(call.Args[1:])
439
+ // Mark the call as processed, and s twice.
440
+ aa.countProcessed(s, call, s)
441
+
442
+ // We have now examined all non-ONAME children of assign.
443
+
444
+ // This is now the heart of the analysis.
445
+ // Check to see if this slice is a live candidate.
446
+ cs, ok := aa.candidateSlices[s]
447
+ if ok {
448
+ if cs.loopDepth == len(aa.loops) {
449
+ // No new loop has started after the declaration of s,
450
+ // so this is definitive.
451
+ if base.Debug.EscapeAlias >= 2 {
452
+ aa.diag(assign.Pos(), assign, "proved non-aliased append",
453
+ "(loop depth: %d, equals decl depth)", len(aa.loops))
454
+ }
455
+ aa.noAliasAppends = append(aa.noAliasAppends, call)
456
+ } else if cs.loopDepth < len(aa.loops) {
457
+ // A new loop has started since the declaration of s,
458
+ // so we can't validate this append yet, but
459
+ // remember it in case we can validate it later when
460
+ // all loops using s are done.
461
+ aa.loops[cs.loopDepth] = append(aa.loops[cs.loopDepth],
462
+ candidateAppend{s: s, call: call})
463
+ } else {
464
+ panic("impossible: candidate slice loopDepth > current loop depth")
465
+ }
466
+ }
467
+ continue
468
+ }
469
+ } // End of switch on src.Op().
470
+
471
+ // Reached bottom of the loop over assignments.
472
+ // If we get here, we need to visit the dst and src normally.
473
+ aa.visit(dst)
474
+ aa.visit(src)
475
+ }
476
+ }
477
+
478
+ func (aa *aliasAnalysis) countProcessed(nodes ...ir.Node) {
479
+ if aa.doubleCheck {
480
+ for _, n := range nodes {
481
+ aa.processed[n]++
482
+ }
483
+ }
484
+ }
485
+
486
+ func (aa *aliasAnalysis) diag(pos src.XPos, n ir.Node, what string, format string, args ...any) {
487
+ fmt.Printf("%-25s alias analysis: %-30s %-20s %s\n",
488
+ fmtPosShort(pos)+":",
489
+ what+":",
490
+ fmt.Sprintf("%v", n),
491
+ fmt.Sprintf(format, args...))
492
+ }
493
+
494
+ // doubleCheckProcessed does a sanity check for missed nodes in our visit.
495
+ func doubleCheckProcessed(fn *ir.Func, processed map[ir.Node]int) {
496
+ // Do a trivial walk while counting the nodes
497
+ // to compare against the counts in processed.
498
+
499
+ observed := make(map[ir.Node]int)
500
+ var walk func(n ir.Node) bool
501
+ walk = func(n ir.Node) bool {
502
+ observed[n]++
503
+ return ir.DoChildren(n, walk)
504
+ }
505
+ ir.DoChildren(fn, walk)
506
+
507
+ if !maps.Equal(processed, observed) {
508
+ // The most likely mistake might be something was missed while building processed,
509
+ // so print extra details in that direction.
510
+ for n, observedCount := range observed {
511
+ processedCount, ok := processed[n]
512
+ if processedCount != observedCount || !ok {
513
+ base.WarnfAt(n.Pos(),
514
+ "alias analysis: mismatch for %T: %v: processed %d times, observed %d times",
515
+ n, n, processedCount, observedCount)
516
+ }
517
+ }
518
+ base.FatalfAt(fn.Pos(), "alias analysis: mismatch in visited nodes")
519
+ }
520
+ }
521
+
522
+ func fmtPosShort(xpos src.XPos) string {
523
+ // TODO(thepudds): I think I did this a simpler way a while ago? Or maybe add base.FmtPosShort
524
+ // or similar? Or maybe just use base.FmtPos and give up on nicely aligned log messages?
525
+ pos := base.Ctxt.PosTable.Pos(xpos)
526
+ shortLine := filepath.Base(pos.AbsFilename()) + ":" + pos.LineNumber()
527
+ return shortLine
528
+ }
go/src/cmd/compile/internal/escape/assign.go ADDED
@@ -0,0 +1,128 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2018 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 escape
6
+
7
+ import (
8
+ "cmd/compile/internal/base"
9
+ "cmd/compile/internal/ir"
10
+ )
11
+
12
+ // addr evaluates an addressable expression n and returns a hole
13
+ // that represents storing into the represented location.
14
+ func (e *escape) addr(n ir.Node) hole {
15
+ if n == nil || ir.IsBlank(n) {
16
+ // Can happen in select case, range, maybe others.
17
+ return e.discardHole()
18
+ }
19
+
20
+ k := e.heapHole()
21
+
22
+ switch n.Op() {
23
+ default:
24
+ base.Fatalf("unexpected addr: %v", n)
25
+ case ir.ONAME:
26
+ n := n.(*ir.Name)
27
+ if n.Class == ir.PEXTERN {
28
+ break
29
+ }
30
+ k = e.oldLoc(n).asHole()
31
+ case ir.OLINKSYMOFFSET:
32
+ break
33
+ case ir.ODOT:
34
+ n := n.(*ir.SelectorExpr)
35
+ k = e.addr(n.X)
36
+ case ir.OINDEX:
37
+ n := n.(*ir.IndexExpr)
38
+ e.discard(n.Index)
39
+ if n.X.Type().IsArray() {
40
+ k = e.addr(n.X)
41
+ } else {
42
+ e.mutate(n.X)
43
+ }
44
+ case ir.ODEREF:
45
+ n := n.(*ir.StarExpr)
46
+ e.mutate(n.X)
47
+ case ir.ODOTPTR:
48
+ n := n.(*ir.SelectorExpr)
49
+ e.mutate(n.X)
50
+ case ir.OINDEXMAP:
51
+ n := n.(*ir.IndexExpr)
52
+ e.discard(n.X)
53
+ e.assignHeap(n.Index, "key of map put", n)
54
+ }
55
+
56
+ return k
57
+ }
58
+
59
+ func (e *escape) mutate(n ir.Node) {
60
+ e.expr(e.mutatorHole(), n)
61
+ }
62
+
63
+ func (e *escape) addrs(l ir.Nodes) []hole {
64
+ var ks []hole
65
+ for _, n := range l {
66
+ ks = append(ks, e.addr(n))
67
+ }
68
+ return ks
69
+ }
70
+
71
+ func (e *escape) assignHeap(src ir.Node, why string, where ir.Node) {
72
+ e.expr(e.heapHole().note(where, why), src)
73
+ }
74
+
75
+ // assignList evaluates the assignment dsts... = srcs....
76
+ func (e *escape) assignList(dsts, srcs []ir.Node, why string, where ir.Node) {
77
+ ks := e.addrs(dsts)
78
+ for i, k := range ks {
79
+ var src ir.Node
80
+ if i < len(srcs) {
81
+ src = srcs[i]
82
+ }
83
+
84
+ if dst := dsts[i]; dst != nil {
85
+ // Detect implicit conversion of uintptr to unsafe.Pointer when
86
+ // storing into reflect.{Slice,String}Header.
87
+ if dst.Op() == ir.ODOTPTR && ir.IsReflectHeaderDataField(dst) {
88
+ e.unsafeValue(e.heapHole().note(where, why), src)
89
+ continue
90
+ }
91
+
92
+ // Filter out some no-op assignments for escape analysis.
93
+ if src != nil && isSelfAssign(dst, src) {
94
+ if base.Flag.LowerM != 0 {
95
+ base.WarnfAt(where.Pos(), "%v ignoring self-assignment in %v", e.curfn, where)
96
+ }
97
+ k = e.discardHole()
98
+ }
99
+ }
100
+
101
+ e.expr(k.note(where, why), src)
102
+ }
103
+
104
+ e.reassigned(ks, where)
105
+ }
106
+
107
+ // reassigned marks the locations associated with the given holes as
108
+ // reassigned, unless the location represents a variable declared and
109
+ // assigned exactly once by where.
110
+ func (e *escape) reassigned(ks []hole, where ir.Node) {
111
+ if as, ok := where.(*ir.AssignStmt); ok && as.Op() == ir.OAS && as.Y == nil {
112
+ if dst, ok := as.X.(*ir.Name); ok && dst.Op() == ir.ONAME && dst.Defn == nil {
113
+ // Zero-value assignment for variable declared without an
114
+ // explicit initial value. Assume this is its initialization
115
+ // statement.
116
+ return
117
+ }
118
+ }
119
+
120
+ for _, k := range ks {
121
+ loc := k.dst
122
+ // Variables declared by range statements are assigned on every iteration.
123
+ if n, ok := loc.n.(*ir.Name); ok && n.Defn == where && where.Op() != ir.ORANGE {
124
+ continue
125
+ }
126
+ loc.reassigned = true
127
+ }
128
+ }
go/src/cmd/compile/internal/escape/call.go ADDED
@@ -0,0 +1,425 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2018 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 escape
6
+
7
+ import (
8
+ "cmd/compile/internal/base"
9
+ "cmd/compile/internal/ir"
10
+ "cmd/compile/internal/typecheck"
11
+ "cmd/compile/internal/types"
12
+ "cmd/internal/src"
13
+ "strings"
14
+ )
15
+
16
+ // call evaluates a call expressions, including builtin calls. ks
17
+ // should contain the holes representing where the function callee's
18
+ // results flows.
19
+ func (e *escape) call(ks []hole, call ir.Node) {
20
+ argument := func(k hole, arg ir.Node) {
21
+ // TODO(mdempsky): Should be "call argument".
22
+ e.expr(k.note(call, "call parameter"), arg)
23
+ }
24
+
25
+ switch call.Op() {
26
+ default:
27
+ ir.Dump("esc", call)
28
+ base.Fatalf("unexpected call op: %v", call.Op())
29
+
30
+ case ir.OCALLFUNC, ir.OCALLINTER:
31
+ call := call.(*ir.CallExpr)
32
+ typecheck.AssertFixedCall(call)
33
+
34
+ // Pick out the function callee, if statically known.
35
+ //
36
+ // TODO(mdempsky): Change fn from *ir.Name to *ir.Func, but some
37
+ // functions (e.g., runtime builtins, method wrappers, generated
38
+ // eq/hash functions) don't have it set. Investigate whether
39
+ // that's a concern.
40
+ var fn *ir.Name
41
+ switch call.Op() {
42
+ case ir.OCALLFUNC:
43
+ // TODO(thepudds): use an ir.ReassignOracle here.
44
+ v := ir.StaticValue(call.Fun)
45
+ fn = ir.StaticCalleeName(v)
46
+ }
47
+
48
+ // argumentParam handles escape analysis of assigning a call
49
+ // argument to its corresponding parameter.
50
+ argumentParam := func(param *types.Field, arg ir.Node) {
51
+ e.rewriteArgument(arg, call, fn)
52
+ argument(e.tagHole(ks, fn, param), arg)
53
+ }
54
+
55
+ if call.IsCompilerVarLive {
56
+ // Don't escape compiler-inserted KeepAlive.
57
+ argumentParam = func(param *types.Field, arg ir.Node) {
58
+ argument(e.discardHole(), arg)
59
+ }
60
+ }
61
+
62
+ fntype := call.Fun.Type()
63
+ if fn != nil {
64
+ fntype = fn.Type()
65
+ }
66
+
67
+ if ks != nil && fn != nil && e.inMutualBatch(fn) {
68
+ for i, result := range fn.Type().Results() {
69
+ e.expr(ks[i], result.Nname.(*ir.Name))
70
+ }
71
+ }
72
+
73
+ var recvArg ir.Node
74
+ if call.Op() == ir.OCALLFUNC {
75
+ // Evaluate callee function expression.
76
+ calleeK := e.discardHole()
77
+ if fn == nil { // unknown callee
78
+ for _, k := range ks {
79
+ if k.dst != &e.blankLoc {
80
+ // The results flow somewhere, but we don't statically
81
+ // know the callee function. If a closure flows here, we
82
+ // need to conservatively assume its results might flow to
83
+ // the heap.
84
+ calleeK = e.calleeHole().note(call, "callee operand")
85
+ break
86
+ }
87
+ }
88
+ }
89
+ e.expr(calleeK, call.Fun)
90
+ } else {
91
+ recvArg = call.Fun.(*ir.SelectorExpr).X
92
+ }
93
+
94
+ // internal/abi.EscapeNonString forces its argument to be on
95
+ // the heap, if it contains a non-string pointer.
96
+ // This is used in hash/maphash.Comparable, where we cannot
97
+ // hash pointers to local variables, as the address of the
98
+ // local variable might change on stack growth.
99
+ // Strings are okay as the hash depends on only the content,
100
+ // not the pointer.
101
+ // This is also used in unique.clone, to model the data flow
102
+ // edge on the value with strings excluded, because strings
103
+ // are cloned (by content).
104
+ // The actual call we match is
105
+ // internal/abi.EscapeNonString[go.shape.T](dict, go.shape.T)
106
+ if fn != nil && fn.Sym().Pkg.Path == "internal/abi" && strings.HasPrefix(fn.Sym().Name, "EscapeNonString[") {
107
+ ps := fntype.Params()
108
+ if len(ps) == 2 && ps[1].Type.IsShape() {
109
+ if !hasNonStringPointers(ps[1].Type) {
110
+ argumentParam = func(param *types.Field, arg ir.Node) {
111
+ argument(e.discardHole(), arg)
112
+ }
113
+ } else {
114
+ argumentParam = func(param *types.Field, arg ir.Node) {
115
+ argument(e.heapHole(), arg)
116
+ }
117
+ }
118
+ }
119
+ }
120
+
121
+ args := call.Args
122
+ if recvParam := fntype.Recv(); recvParam != nil {
123
+ if recvArg == nil {
124
+ // Function call using method expression. Receiver argument is
125
+ // at the front of the regular arguments list.
126
+ recvArg, args = args[0], args[1:]
127
+ }
128
+
129
+ argumentParam(recvParam, recvArg)
130
+ }
131
+
132
+ for i, param := range fntype.Params() {
133
+ argumentParam(param, args[i])
134
+ }
135
+
136
+ case ir.OINLCALL:
137
+ call := call.(*ir.InlinedCallExpr)
138
+ e.stmts(call.Body)
139
+ for i, result := range call.ReturnVars {
140
+ k := e.discardHole()
141
+ if ks != nil {
142
+ k = ks[i]
143
+ }
144
+ e.expr(k, result)
145
+ }
146
+
147
+ case ir.OAPPEND:
148
+ call := call.(*ir.CallExpr)
149
+ args := call.Args
150
+
151
+ // Appendee slice may flow directly to the result, if
152
+ // it has enough capacity. Alternatively, a new heap
153
+ // slice might be allocated, and all slice elements
154
+ // might flow to heap.
155
+ appendeeK := e.teeHole(ks[0], e.mutatorHole())
156
+ if args[0].Type().Elem().HasPointers() {
157
+ appendeeK = e.teeHole(appendeeK, e.heapHole().deref(call, "appendee slice"))
158
+ }
159
+ argument(appendeeK, args[0])
160
+
161
+ if call.IsDDD {
162
+ appendedK := e.discardHole()
163
+ if args[1].Type().IsSlice() && args[1].Type().Elem().HasPointers() {
164
+ appendedK = e.heapHole().deref(call, "appended slice...")
165
+ }
166
+ argument(appendedK, args[1])
167
+ } else {
168
+ for i := 1; i < len(args); i++ {
169
+ argument(e.heapHole(), args[i])
170
+ }
171
+ }
172
+ e.discard(call.RType)
173
+
174
+ // Model the new backing store that might be allocated by append.
175
+ // Its address flows to the result.
176
+ // Users of escape analysis can look at the escape information for OAPPEND
177
+ // and use that to decide where to allocate the backing store.
178
+ backingStore := e.spill(ks[0], call)
179
+ // As we have a boolean to prevent reuse, we can treat these allocations as outside any loops.
180
+ backingStore.dst.loopDepth = 0
181
+
182
+ case ir.OCOPY:
183
+ call := call.(*ir.BinaryExpr)
184
+ argument(e.mutatorHole(), call.X)
185
+
186
+ copiedK := e.discardHole()
187
+ if call.Y.Type().IsSlice() && call.Y.Type().Elem().HasPointers() {
188
+ copiedK = e.heapHole().deref(call, "copied slice")
189
+ }
190
+ argument(copiedK, call.Y)
191
+ e.discard(call.RType)
192
+
193
+ case ir.OPANIC:
194
+ call := call.(*ir.UnaryExpr)
195
+ argument(e.heapHole(), call.X)
196
+
197
+ case ir.OCOMPLEX:
198
+ call := call.(*ir.BinaryExpr)
199
+ e.discard(call.X)
200
+ e.discard(call.Y)
201
+
202
+ case ir.ODELETE, ir.OPRINT, ir.OPRINTLN, ir.ORECOVER:
203
+ call := call.(*ir.CallExpr)
204
+ for _, arg := range call.Args {
205
+ e.discard(arg)
206
+ }
207
+ e.discard(call.RType)
208
+
209
+ case ir.OMIN, ir.OMAX:
210
+ call := call.(*ir.CallExpr)
211
+ for _, arg := range call.Args {
212
+ argument(ks[0], arg)
213
+ }
214
+ e.discard(call.RType)
215
+
216
+ case ir.OLEN, ir.OCAP, ir.OREAL, ir.OIMAG, ir.OCLOSE:
217
+ call := call.(*ir.UnaryExpr)
218
+ e.discard(call.X)
219
+
220
+ case ir.OCLEAR:
221
+ call := call.(*ir.UnaryExpr)
222
+ argument(e.mutatorHole(), call.X)
223
+
224
+ case ir.OUNSAFESTRINGDATA, ir.OUNSAFESLICEDATA:
225
+ call := call.(*ir.UnaryExpr)
226
+ argument(ks[0], call.X)
227
+
228
+ case ir.OUNSAFEADD, ir.OUNSAFESLICE, ir.OUNSAFESTRING:
229
+ call := call.(*ir.BinaryExpr)
230
+ argument(ks[0], call.X)
231
+ e.discard(call.Y)
232
+ e.discard(call.RType)
233
+ }
234
+ }
235
+
236
+ // goDeferStmt analyzes a "go" or "defer" statement.
237
+ func (e *escape) goDeferStmt(n *ir.GoDeferStmt) {
238
+ k := e.heapHole()
239
+ if n.Op() == ir.ODEFER && e.loopDepth == 1 && n.DeferAt == nil {
240
+ // Top-level defer arguments don't escape to the heap,
241
+ // but they do need to last until they're invoked.
242
+ k = e.later(e.discardHole())
243
+
244
+ // force stack allocation of defer record, unless
245
+ // open-coded defers are used (see ssa.go)
246
+ n.SetEsc(ir.EscNever)
247
+ }
248
+
249
+ // If the function is already a zero argument/result function call,
250
+ // just escape analyze it normally.
251
+ //
252
+ // Note that the runtime is aware of this optimization for
253
+ // "go" statements that start in reflect.makeFuncStub or
254
+ // reflect.methodValueCall.
255
+
256
+ call, ok := n.Call.(*ir.CallExpr)
257
+ if !ok || call.Op() != ir.OCALLFUNC {
258
+ base.FatalfAt(n.Pos(), "expected function call: %v", n.Call)
259
+ }
260
+ if sig := call.Fun.Type(); sig.NumParams()+sig.NumResults() != 0 {
261
+ base.FatalfAt(n.Pos(), "expected signature without parameters or results: %v", sig)
262
+ }
263
+
264
+ if clo, ok := call.Fun.(*ir.ClosureExpr); ok && n.Op() == ir.OGO {
265
+ clo.IsGoWrap = true
266
+ }
267
+
268
+ e.expr(k, call.Fun)
269
+ }
270
+
271
+ // rewriteArgument rewrites the argument arg of the given call expression.
272
+ // fn is the static callee function, if known.
273
+ func (e *escape) rewriteArgument(arg ir.Node, call *ir.CallExpr, fn *ir.Name) {
274
+ if fn == nil || fn.Func == nil {
275
+ return
276
+ }
277
+ pragma := fn.Func.Pragma
278
+ if pragma&(ir.UintptrKeepAlive|ir.UintptrEscapes) == 0 {
279
+ return
280
+ }
281
+
282
+ // unsafeUintptr rewrites "uintptr(ptr)" arguments to syscall-like
283
+ // functions, so that ptr is kept alive and/or escaped as
284
+ // appropriate. unsafeUintptr also reports whether it modified arg0.
285
+ unsafeUintptr := func(arg ir.Node) {
286
+ // If the argument is really a pointer being converted to uintptr,
287
+ // arrange for the pointer to be kept alive until the call
288
+ // returns, by copying it into a temp and marking that temp still
289
+ // alive when we pop the temp stack.
290
+ conv, ok := arg.(*ir.ConvExpr)
291
+ if !ok || conv.Op() != ir.OCONVNOP {
292
+ return // not a conversion
293
+ }
294
+ if !conv.X.Type().IsUnsafePtr() || !conv.Type().IsUintptr() {
295
+ return // not an unsafe.Pointer->uintptr conversion
296
+ }
297
+
298
+ // Create and declare a new pointer-typed temp variable.
299
+ //
300
+ // TODO(mdempsky): This potentially violates the Go spec's order
301
+ // of evaluations, by evaluating arg.X before any other
302
+ // operands.
303
+ tmp := e.copyExpr(conv.Pos(), conv.X, call.PtrInit())
304
+ conv.X = tmp
305
+
306
+ k := e.mutatorHole()
307
+ if pragma&ir.UintptrEscapes != 0 {
308
+ k = e.heapHole().note(conv, "//go:uintptrescapes")
309
+ }
310
+ e.flow(k, e.oldLoc(tmp))
311
+
312
+ if pragma&ir.UintptrKeepAlive != 0 {
313
+ tmp.SetAddrtaken(true) // ensure SSA keeps the tmp variable
314
+ call.KeepAlive = append(call.KeepAlive, tmp)
315
+ }
316
+ }
317
+
318
+ // For variadic functions, the compiler has already rewritten:
319
+ //
320
+ // f(a, b, c)
321
+ //
322
+ // to:
323
+ //
324
+ // f([]T{a, b, c}...)
325
+ //
326
+ // So we need to look into slice elements to handle uintptr(ptr)
327
+ // arguments to variadic syscall-like functions correctly.
328
+ if arg.Op() == ir.OSLICELIT {
329
+ list := arg.(*ir.CompLitExpr).List
330
+ for _, el := range list {
331
+ if el.Op() == ir.OKEY {
332
+ el = el.(*ir.KeyExpr).Value
333
+ }
334
+ unsafeUintptr(el)
335
+ }
336
+ } else {
337
+ unsafeUintptr(arg)
338
+ }
339
+ }
340
+
341
+ // copyExpr creates and returns a new temporary variable within fn;
342
+ // appends statements to init to declare and initialize it to expr;
343
+ // and escape analyzes the data flow.
344
+ func (e *escape) copyExpr(pos src.XPos, expr ir.Node, init *ir.Nodes) *ir.Name {
345
+ if ir.HasUniquePos(expr) {
346
+ pos = expr.Pos()
347
+ }
348
+
349
+ tmp := typecheck.TempAt(pos, e.curfn, expr.Type())
350
+
351
+ stmts := []ir.Node{
352
+ ir.NewDecl(pos, ir.ODCL, tmp),
353
+ ir.NewAssignStmt(pos, tmp, expr),
354
+ }
355
+ typecheck.Stmts(stmts)
356
+ init.Append(stmts...)
357
+
358
+ e.newLoc(tmp, true)
359
+ e.stmts(stmts)
360
+
361
+ return tmp
362
+ }
363
+
364
+ // tagHole returns a hole for evaluating an argument passed to param.
365
+ // ks should contain the holes representing where the function
366
+ // callee's results flows. fn is the statically-known callee function,
367
+ // if any.
368
+ func (e *escape) tagHole(ks []hole, fn *ir.Name, param *types.Field) hole {
369
+ // If this is a dynamic call, we can't rely on param.Note.
370
+ if fn == nil {
371
+ return e.heapHole()
372
+ }
373
+
374
+ if e.inMutualBatch(fn) {
375
+ if param.Nname == nil {
376
+ return e.discardHole()
377
+ }
378
+ return e.addr(param.Nname.(*ir.Name))
379
+ }
380
+
381
+ // Call to previously tagged function.
382
+
383
+ var tagKs []hole
384
+ esc := parseLeaks(param.Note)
385
+
386
+ if x := esc.Heap(); x >= 0 {
387
+ tagKs = append(tagKs, e.heapHole().shift(x))
388
+ }
389
+ if x := esc.Mutator(); x >= 0 {
390
+ tagKs = append(tagKs, e.mutatorHole().shift(x))
391
+ }
392
+ if x := esc.Callee(); x >= 0 {
393
+ tagKs = append(tagKs, e.calleeHole().shift(x))
394
+ }
395
+
396
+ if ks != nil {
397
+ for i := 0; i < numEscResults; i++ {
398
+ if x := esc.Result(i); x >= 0 {
399
+ tagKs = append(tagKs, ks[i].shift(x))
400
+ }
401
+ }
402
+ }
403
+
404
+ return e.teeHole(tagKs...)
405
+ }
406
+
407
+ func hasNonStringPointers(t *types.Type) bool {
408
+ if !t.HasPointers() {
409
+ return false
410
+ }
411
+ switch t.Kind() {
412
+ case types.TSTRING:
413
+ return false
414
+ case types.TSTRUCT:
415
+ for _, f := range t.Fields() {
416
+ if hasNonStringPointers(f.Type) {
417
+ return true
418
+ }
419
+ }
420
+ return false
421
+ case types.TARRAY:
422
+ return hasNonStringPointers(t.Elem())
423
+ }
424
+ return true
425
+ }
go/src/cmd/compile/internal/escape/escape.go ADDED
@@ -0,0 +1,672 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2018 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 escape
6
+
7
+ import (
8
+ "fmt"
9
+ "go/constant"
10
+ "go/token"
11
+ "internal/goexperiment"
12
+
13
+ "cmd/compile/internal/base"
14
+ "cmd/compile/internal/ir"
15
+ "cmd/compile/internal/logopt"
16
+ "cmd/compile/internal/typecheck"
17
+ "cmd/compile/internal/types"
18
+ "cmd/internal/src"
19
+ )
20
+
21
+ // Escape analysis.
22
+ //
23
+ // Here we analyze functions to determine which Go variables
24
+ // (including implicit allocations such as calls to "new" or "make",
25
+ // composite literals, etc.) can be allocated on the stack. The two
26
+ // key invariants we have to ensure are: (1) pointers to stack objects
27
+ // cannot be stored in the heap, and (2) pointers to a stack object
28
+ // cannot outlive that object (e.g., because the declaring function
29
+ // returned and destroyed the object's stack frame, or its space is
30
+ // reused across loop iterations for logically distinct variables).
31
+ //
32
+ // We implement this with a static data-flow analysis of the AST.
33
+ // First, we construct a directed weighted graph where vertices
34
+ // (termed "locations") represent variables allocated by statements
35
+ // and expressions, and edges represent assignments between variables
36
+ // (with weights representing addressing/dereference counts).
37
+ //
38
+ // Next we walk the graph looking for assignment paths that might
39
+ // violate the invariants stated above. If a variable v's address is
40
+ // stored in the heap or elsewhere that may outlive it, then v is
41
+ // marked as requiring heap allocation.
42
+ //
43
+ // To support interprocedural analysis, we also record data-flow from
44
+ // each function's parameters to the heap and to its result
45
+ // parameters. This information is summarized as "parameter tags",
46
+ // which are used at static call sites to improve escape analysis of
47
+ // function arguments.
48
+
49
+ // Constructing the location graph.
50
+ //
51
+ // Every allocating statement (e.g., variable declaration) or
52
+ // expression (e.g., "new" or "make") is first mapped to a unique
53
+ // "location."
54
+ //
55
+ // We also model every Go assignment as a directed edges between
56
+ // locations. The number of dereference operations minus the number of
57
+ // addressing operations is recorded as the edge's weight (termed
58
+ // "derefs"). For example:
59
+ //
60
+ // p = &q // -1
61
+ // p = q // 0
62
+ // p = *q // 1
63
+ // p = **q // 2
64
+ //
65
+ // p = **&**&q // 2
66
+ //
67
+ // Note that the & operator can only be applied to addressable
68
+ // expressions, and the expression &x itself is not addressable, so
69
+ // derefs cannot go below -1.
70
+ //
71
+ // Every Go language construct is lowered into this representation,
72
+ // generally without sensitivity to flow, path, or context; and
73
+ // without distinguishing elements within a compound variable. For
74
+ // example:
75
+ //
76
+ // var x struct { f, g *int }
77
+ // var u []*int
78
+ //
79
+ // x.f = u[0]
80
+ //
81
+ // is modeled simply as
82
+ //
83
+ // x = *u
84
+ //
85
+ // That is, we don't distinguish x.f from x.g, or u[0] from u[1],
86
+ // u[2], etc. However, we do record the implicit dereference involved
87
+ // in indexing a slice.
88
+
89
+ // A batch holds escape analysis state that's shared across an entire
90
+ // batch of functions being analyzed at once.
91
+ type batch struct {
92
+ allLocs []*location
93
+ closures []closure
94
+ reassignOracles map[*ir.Func]*ir.ReassignOracle
95
+
96
+ heapLoc location
97
+ mutatorLoc location
98
+ calleeLoc location
99
+ blankLoc location
100
+ }
101
+
102
+ // A closure holds a closure expression and its spill hole (i.e.,
103
+ // where the hole representing storing into its closure record).
104
+ type closure struct {
105
+ k hole
106
+ clo *ir.ClosureExpr
107
+ }
108
+
109
+ // An escape holds state specific to a single function being analyzed
110
+ // within a batch.
111
+ type escape struct {
112
+ *batch
113
+
114
+ curfn *ir.Func // function being analyzed
115
+
116
+ labels map[*types.Sym]labelState // known labels
117
+
118
+ // loopDepth counts the current loop nesting depth within
119
+ // curfn. It increments within each "for" loop and at each
120
+ // label with a corresponding backwards "goto" (i.e.,
121
+ // unstructured loop).
122
+ loopDepth int
123
+ }
124
+
125
+ func Funcs(all []*ir.Func) {
126
+ // Make a cache of ir.ReassignOracles. The cache is lazily populated.
127
+ // TODO(thepudds): consider adding a field on ir.Func instead. We might also be able
128
+ // to use that field elsewhere, like in walk. See discussion in https://go.dev/cl/688075.
129
+ reassignOracles := make(map[*ir.Func]*ir.ReassignOracle)
130
+
131
+ ir.VisitFuncsBottomUp(all, func(list []*ir.Func, recursive bool) {
132
+ Batch(list, reassignOracles)
133
+ })
134
+ }
135
+
136
+ // Batch performs escape analysis on a minimal batch of
137
+ // functions.
138
+ func Batch(fns []*ir.Func, reassignOracles map[*ir.Func]*ir.ReassignOracle) {
139
+ var b batch
140
+ b.heapLoc.attrs = attrEscapes | attrPersists | attrMutates | attrCalls
141
+ b.mutatorLoc.attrs = attrMutates
142
+ b.calleeLoc.attrs = attrCalls
143
+ b.reassignOracles = reassignOracles
144
+
145
+ // Construct data-flow graph from syntax trees.
146
+ for _, fn := range fns {
147
+ if base.Flag.W > 1 {
148
+ s := fmt.Sprintf("\nbefore escape %v", fn)
149
+ ir.Dump(s, fn)
150
+ }
151
+ b.initFunc(fn)
152
+ }
153
+ for _, fn := range fns {
154
+ if !fn.IsClosure() {
155
+ b.walkFunc(fn)
156
+ }
157
+ }
158
+
159
+ // We've walked the function bodies, so we've seen everywhere a
160
+ // variable might be reassigned or have its address taken. Now we
161
+ // can decide whether closures should capture their free variables
162
+ // by value or reference.
163
+ for _, closure := range b.closures {
164
+ b.flowClosure(closure.k, closure.clo)
165
+ }
166
+ b.closures = nil
167
+
168
+ for _, loc := range b.allLocs {
169
+ // Try to replace some non-constant expressions with literals.
170
+ b.rewriteWithLiterals(loc.n, loc.curfn)
171
+
172
+ // Check if the node must be heap allocated for certain reasons
173
+ // such as OMAKESLICE for a large slice.
174
+ if why := HeapAllocReason(loc.n); why != "" {
175
+ b.flow(b.heapHole().addr(loc.n, why), loc)
176
+ }
177
+ }
178
+
179
+ b.walkAll()
180
+ b.finish(fns)
181
+ }
182
+
183
+ func (b *batch) with(fn *ir.Func) *escape {
184
+ return &escape{
185
+ batch: b,
186
+ curfn: fn,
187
+ loopDepth: 1,
188
+ }
189
+ }
190
+
191
+ func (b *batch) initFunc(fn *ir.Func) {
192
+ e := b.with(fn)
193
+ if fn.Esc() != escFuncUnknown {
194
+ base.Fatalf("unexpected node: %v", fn)
195
+ }
196
+ fn.SetEsc(escFuncPlanned)
197
+ if base.Flag.LowerM > 3 {
198
+ ir.Dump("escAnalyze", fn)
199
+ }
200
+
201
+ // Allocate locations for local variables.
202
+ for _, n := range fn.Dcl {
203
+ e.newLoc(n, true)
204
+ }
205
+
206
+ // Also for hidden parameters (e.g., the ".this" parameter to a
207
+ // method value wrapper).
208
+ if fn.OClosure == nil {
209
+ for _, n := range fn.ClosureVars {
210
+ e.newLoc(n.Canonical(), true)
211
+ }
212
+ }
213
+
214
+ // Initialize resultIndex for result parameters.
215
+ for i, f := range fn.Type().Results() {
216
+ e.oldLoc(f.Nname.(*ir.Name)).resultIndex = 1 + i
217
+ }
218
+ }
219
+
220
+ func (b *batch) walkFunc(fn *ir.Func) {
221
+ e := b.with(fn)
222
+ fn.SetEsc(escFuncStarted)
223
+
224
+ // Identify labels that mark the head of an unstructured loop.
225
+ ir.Visit(fn, func(n ir.Node) {
226
+ switch n.Op() {
227
+ case ir.OLABEL:
228
+ n := n.(*ir.LabelStmt)
229
+ if n.Label.IsBlank() {
230
+ break
231
+ }
232
+ if e.labels == nil {
233
+ e.labels = make(map[*types.Sym]labelState)
234
+ }
235
+ e.labels[n.Label] = nonlooping
236
+
237
+ case ir.OGOTO:
238
+ // If we visited the label before the goto,
239
+ // then this is a looping label.
240
+ n := n.(*ir.BranchStmt)
241
+ if e.labels[n.Label] == nonlooping {
242
+ e.labels[n.Label] = looping
243
+ }
244
+ }
245
+ })
246
+
247
+ e.block(fn.Body)
248
+
249
+ if len(e.labels) != 0 {
250
+ base.FatalfAt(fn.Pos(), "leftover labels after walkFunc")
251
+ }
252
+ }
253
+
254
+ func (b *batch) flowClosure(k hole, clo *ir.ClosureExpr) {
255
+ for _, cv := range clo.Func.ClosureVars {
256
+ n := cv.Canonical()
257
+ loc := b.oldLoc(cv)
258
+ if !loc.captured {
259
+ base.FatalfAt(cv.Pos(), "closure variable never captured: %v", cv)
260
+ }
261
+
262
+ // Capture by value for variables <= 128 bytes that are never reassigned.
263
+ n.SetByval(!loc.addrtaken && !loc.reassigned && n.Type().Size() <= 128)
264
+ if !n.Byval() {
265
+ n.SetAddrtaken(true)
266
+ if n.Sym().Name == typecheck.LocalDictName {
267
+ base.FatalfAt(n.Pos(), "dictionary variable not captured by value")
268
+ }
269
+ }
270
+
271
+ if base.Flag.LowerM > 1 {
272
+ how := "ref"
273
+ if n.Byval() {
274
+ how = "value"
275
+ }
276
+ base.WarnfAt(n.Pos(), "%v capturing by %s: %v (addr=%v assign=%v width=%d)", n.Curfn, how, n, loc.addrtaken, loc.reassigned, n.Type().Size())
277
+ }
278
+
279
+ // Flow captured variables to closure.
280
+ k := k
281
+ if !cv.Byval() {
282
+ k = k.addr(cv, "reference")
283
+ }
284
+ b.flow(k.note(cv, "captured by a closure"), loc)
285
+ }
286
+ }
287
+
288
+ func (b *batch) finish(fns []*ir.Func) {
289
+ // Record parameter tags for package export data.
290
+ for _, fn := range fns {
291
+ fn.SetEsc(escFuncTagged)
292
+
293
+ for i, param := range fn.Type().RecvParams() {
294
+ param.Note = b.paramTag(fn, 1+i, param)
295
+ }
296
+ }
297
+
298
+ for _, loc := range b.allLocs {
299
+ n := loc.n
300
+ if n == nil {
301
+ continue
302
+ }
303
+
304
+ if n.Op() == ir.ONAME {
305
+ n := n.(*ir.Name)
306
+ n.Opt = nil
307
+ }
308
+
309
+ // Update n.Esc based on escape analysis results.
310
+
311
+ // Omit escape diagnostics for go/defer wrappers, at least for now.
312
+ // Historically, we haven't printed them, and test cases don't expect them.
313
+ // TODO(mdempsky): Update tests to expect this.
314
+ goDeferWrapper := n.Op() == ir.OCLOSURE && n.(*ir.ClosureExpr).Func.Wrapper()
315
+
316
+ if loc.hasAttr(attrEscapes) {
317
+ if n.Op() == ir.ONAME {
318
+ if base.Flag.CompilingRuntime {
319
+ base.ErrorfAt(n.Pos(), 0, "%v escapes to heap, not allowed in runtime", n)
320
+ }
321
+ if base.Flag.LowerM != 0 {
322
+ base.WarnfAt(n.Pos(), "moved to heap: %v", n)
323
+ }
324
+ } else {
325
+ if base.Flag.LowerM != 0 && !goDeferWrapper {
326
+ if n.Op() == ir.OAPPEND {
327
+ base.WarnfAt(n.Pos(), "append escapes to heap")
328
+ } else {
329
+ base.WarnfAt(n.Pos(), "%v escapes to heap", n)
330
+ }
331
+ }
332
+ if logopt.Enabled() {
333
+ var e_curfn *ir.Func // TODO(mdempsky): Fix.
334
+ logopt.LogOpt(n.Pos(), "escape", "escape", ir.FuncName(e_curfn))
335
+ }
336
+ }
337
+ n.SetEsc(ir.EscHeap)
338
+ } else {
339
+ if base.Flag.LowerM != 0 && n.Op() != ir.ONAME && !goDeferWrapper {
340
+ if n.Op() == ir.OAPPEND {
341
+ base.WarnfAt(n.Pos(), "append does not escape")
342
+ } else {
343
+ base.WarnfAt(n.Pos(), "%v does not escape", n)
344
+ }
345
+ }
346
+ n.SetEsc(ir.EscNone)
347
+ if !loc.hasAttr(attrPersists) {
348
+ switch n.Op() {
349
+ case ir.OCLOSURE:
350
+ n := n.(*ir.ClosureExpr)
351
+ n.SetTransient(true)
352
+ case ir.OMETHVALUE:
353
+ n := n.(*ir.SelectorExpr)
354
+ n.SetTransient(true)
355
+ case ir.OSLICELIT:
356
+ n := n.(*ir.CompLitExpr)
357
+ n.SetTransient(true)
358
+ }
359
+ }
360
+ }
361
+
362
+ // If the result of a string->[]byte conversion is never mutated,
363
+ // then it can simply reuse the string's memory directly.
364
+ if base.Debug.ZeroCopy != 0 {
365
+ if n, ok := n.(*ir.ConvExpr); ok && n.Op() == ir.OSTR2BYTES && !loc.hasAttr(attrMutates) {
366
+ if base.Flag.LowerM >= 1 {
367
+ base.WarnfAt(n.Pos(), "zero-copy string->[]byte conversion")
368
+ }
369
+ n.SetOp(ir.OSTR2BYTESTMP)
370
+ }
371
+ }
372
+ }
373
+
374
+ if goexperiment.RuntimeFreegc {
375
+ // Look for specific patterns of usage, such as appends
376
+ // to slices that we can prove are not aliased.
377
+ for _, fn := range fns {
378
+ a := aliasAnalysis{}
379
+ a.analyze(fn)
380
+ }
381
+ }
382
+
383
+ }
384
+
385
+ // inMutualBatch reports whether function fn is in the batch of
386
+ // mutually recursive functions being analyzed. When this is true,
387
+ // fn has not yet been analyzed, so its parameters and results
388
+ // should be incorporated directly into the flow graph instead of
389
+ // relying on its escape analysis tagging.
390
+ func (b *batch) inMutualBatch(fn *ir.Name) bool {
391
+ if fn.Defn != nil && fn.Defn.Esc() < escFuncTagged {
392
+ if fn.Defn.Esc() == escFuncUnknown {
393
+ base.FatalfAt(fn.Pos(), "graph inconsistency: %v", fn)
394
+ }
395
+ return true
396
+ }
397
+ return false
398
+ }
399
+
400
+ const (
401
+ escFuncUnknown = 0 + iota
402
+ escFuncPlanned
403
+ escFuncStarted
404
+ escFuncTagged
405
+ )
406
+
407
+ // Mark labels that have no backjumps to them as not increasing e.loopdepth.
408
+ type labelState int
409
+
410
+ const (
411
+ looping labelState = 1 + iota
412
+ nonlooping
413
+ )
414
+
415
+ func (b *batch) paramTag(fn *ir.Func, narg int, f *types.Field) string {
416
+ name := func() string {
417
+ if f.Nname != nil {
418
+ return f.Nname.Sym().Name
419
+ }
420
+ return fmt.Sprintf("arg#%d", narg)
421
+ }
422
+
423
+ // Only report diagnostics for user code;
424
+ // not for wrappers generated around them.
425
+ // TODO(mdempsky): Generalize this.
426
+ diagnose := base.Flag.LowerM != 0 && !(fn.Wrapper() || fn.Dupok())
427
+
428
+ if len(fn.Body) == 0 {
429
+ // Assume that uintptr arguments must be held live across the call.
430
+ // This is most important for syscall.Syscall.
431
+ // See golang.org/issue/13372.
432
+ // This really doesn't have much to do with escape analysis per se,
433
+ // but we are reusing the ability to annotate an individual function
434
+ // argument and pass those annotations along to importing code.
435
+ fn.Pragma |= ir.UintptrKeepAlive
436
+
437
+ if f.Type.IsUintptr() {
438
+ if diagnose {
439
+ base.WarnfAt(f.Pos, "assuming %v is unsafe uintptr", name())
440
+ }
441
+ return ""
442
+ }
443
+
444
+ if !f.Type.HasPointers() { // don't bother tagging for scalars
445
+ return ""
446
+ }
447
+
448
+ var esc leaks
449
+
450
+ // External functions are assumed unsafe, unless
451
+ // //go:noescape is given before the declaration.
452
+ if fn.Pragma&ir.Noescape != 0 {
453
+ if diagnose && f.Sym != nil {
454
+ base.WarnfAt(f.Pos, "%v does not escape", name())
455
+ }
456
+ esc.AddMutator(0)
457
+ esc.AddCallee(0)
458
+ } else {
459
+ if diagnose && f.Sym != nil {
460
+ base.WarnfAt(f.Pos, "leaking param: %v", name())
461
+ }
462
+ esc.AddHeap(0)
463
+ }
464
+
465
+ return esc.Encode()
466
+ }
467
+
468
+ if fn.Pragma&ir.UintptrEscapes != 0 {
469
+ if f.Type.IsUintptr() {
470
+ if diagnose {
471
+ base.WarnfAt(f.Pos, "marking %v as escaping uintptr", name())
472
+ }
473
+ return ""
474
+ }
475
+ if f.IsDDD() && f.Type.Elem().IsUintptr() {
476
+ // final argument is ...uintptr.
477
+ if diagnose {
478
+ base.WarnfAt(f.Pos, "marking %v as escaping ...uintptr", name())
479
+ }
480
+ return ""
481
+ }
482
+ }
483
+
484
+ if !f.Type.HasPointers() { // don't bother tagging for scalars
485
+ return ""
486
+ }
487
+
488
+ // Unnamed parameters are unused and therefore do not escape.
489
+ if f.Sym == nil || f.Sym.IsBlank() {
490
+ var esc leaks
491
+ return esc.Encode()
492
+ }
493
+
494
+ n := f.Nname.(*ir.Name)
495
+ loc := b.oldLoc(n)
496
+ esc := loc.paramEsc
497
+ esc.Optimize()
498
+
499
+ if diagnose && !loc.hasAttr(attrEscapes) {
500
+ b.reportLeaks(f.Pos, name(), esc, fn.Type())
501
+ }
502
+
503
+ return esc.Encode()
504
+ }
505
+
506
+ func (b *batch) reportLeaks(pos src.XPos, name string, esc leaks, sig *types.Type) {
507
+ warned := false
508
+ if x := esc.Heap(); x >= 0 {
509
+ if x == 0 {
510
+ base.WarnfAt(pos, "leaking param: %v", name)
511
+ } else {
512
+ // TODO(mdempsky): Mention level=x like below?
513
+ base.WarnfAt(pos, "leaking param content: %v", name)
514
+ }
515
+ warned = true
516
+ }
517
+ for i := 0; i < numEscResults; i++ {
518
+ if x := esc.Result(i); x >= 0 {
519
+ res := sig.Result(i).Nname.Sym().Name
520
+ base.WarnfAt(pos, "leaking param: %v to result %v level=%d", name, res, x)
521
+ warned = true
522
+ }
523
+ }
524
+
525
+ if base.Debug.EscapeMutationsCalls <= 0 {
526
+ if !warned {
527
+ base.WarnfAt(pos, "%v does not escape", name)
528
+ }
529
+ return
530
+ }
531
+
532
+ if x := esc.Mutator(); x >= 0 {
533
+ base.WarnfAt(pos, "mutates param: %v derefs=%v", name, x)
534
+ warned = true
535
+ }
536
+ if x := esc.Callee(); x >= 0 {
537
+ base.WarnfAt(pos, "calls param: %v derefs=%v", name, x)
538
+ warned = true
539
+ }
540
+
541
+ if !warned {
542
+ base.WarnfAt(pos, "%v does not escape, mutate, or call", name)
543
+ }
544
+ }
545
+
546
+ // rewriteWithLiterals attempts to replace certain non-constant expressions
547
+ // within n with a literal if possible.
548
+ func (b *batch) rewriteWithLiterals(n ir.Node, fn *ir.Func) {
549
+ if n == nil || fn == nil {
550
+ return
551
+ }
552
+
553
+ assignTemp := func(pos src.XPos, n ir.Node, init *ir.Nodes) {
554
+ // Preserve any side effects of n by assigning it to an otherwise unused temp.
555
+ tmp := typecheck.TempAt(pos, fn, n.Type())
556
+ init.Append(typecheck.Stmt(ir.NewDecl(pos, ir.ODCL, tmp)))
557
+ init.Append(typecheck.Stmt(ir.NewAssignStmt(pos, tmp, n)))
558
+ }
559
+
560
+ switch n.Op() {
561
+ case ir.OMAKESLICE:
562
+ // Check if we can replace a non-constant argument to make with
563
+ // a literal to allow for this slice to be stack allocated if otherwise allowed.
564
+ n := n.(*ir.MakeExpr)
565
+
566
+ r := &n.Cap
567
+ if n.Cap == nil {
568
+ r = &n.Len
569
+ }
570
+
571
+ if (*r).Op() != ir.OLITERAL {
572
+ // Look up a cached ReassignOracle for the function, lazily computing one if needed.
573
+ ro := b.reassignOracle(fn)
574
+ if ro == nil {
575
+ base.Fatalf("no ReassignOracle for function %v with closure parent %v", fn, fn.ClosureParent)
576
+ }
577
+
578
+ s := ro.StaticValue(*r)
579
+ switch s.Op() {
580
+ case ir.OLITERAL:
581
+ lit, ok := s.(*ir.BasicLit)
582
+ if !ok || lit.Val().Kind() != constant.Int {
583
+ base.Fatalf("unexpected BasicLit Kind")
584
+ }
585
+ if constant.Compare(lit.Val(), token.GEQ, constant.MakeInt64(0)) {
586
+ if !base.LiteralAllocHash.MatchPos(n.Pos(), nil) {
587
+ // De-selected by literal alloc optimizations debug hash.
588
+ return
589
+ }
590
+ // Preserve any side effects of the original expression, then replace it.
591
+ assignTemp(n.Pos(), *r, n.PtrInit())
592
+ *r = ir.NewBasicLit(n.Pos(), (*r).Type(), lit.Val())
593
+ }
594
+ case ir.OLEN:
595
+ x := ro.StaticValue(s.(*ir.UnaryExpr).X)
596
+ if x.Op() == ir.OSLICELIT {
597
+ x := x.(*ir.CompLitExpr)
598
+ // Preserve any side effects of the original expression, then update the value.
599
+ assignTemp(n.Pos(), *r, n.PtrInit())
600
+ *r = ir.NewBasicLit(n.Pos(), types.Types[types.TINT], constant.MakeInt64(x.Len))
601
+ }
602
+ }
603
+ }
604
+ case ir.OCONVIFACE:
605
+ // Check if we can replace a non-constant expression in an interface conversion with
606
+ // a literal to avoid heap allocating the underlying interface value.
607
+ conv := n.(*ir.ConvExpr)
608
+ if conv.X.Op() != ir.OLITERAL && !conv.X.Type().IsInterface() {
609
+ // TODO(thepudds): likely could avoid some work by tightening the check of conv.X's type.
610
+ // Look up a cached ReassignOracle for the function, lazily computing one if needed.
611
+ ro := b.reassignOracle(fn)
612
+ if ro == nil {
613
+ base.Fatalf("no ReassignOracle for function %v with closure parent %v", fn, fn.ClosureParent)
614
+ }
615
+ v := ro.StaticValue(conv.X)
616
+ if v != nil && v.Op() == ir.OLITERAL && ir.ValidTypeForConst(conv.X.Type(), v.Val()) {
617
+ if !base.LiteralAllocHash.MatchPos(n.Pos(), nil) {
618
+ // De-selected by literal alloc optimizations debug hash.
619
+ return
620
+ }
621
+ if base.Debug.EscapeDebug >= 3 {
622
+ base.WarnfAt(n.Pos(), "rewriting OCONVIFACE value from %v (%v) to %v (%v)", conv.X, conv.X.Type(), v, v.Type())
623
+ }
624
+ // Preserve any side effects of the original expression, then replace it.
625
+ assignTemp(conv.Pos(), conv.X, conv.PtrInit())
626
+ v := v.(*ir.BasicLit)
627
+ conv.X = ir.NewBasicLit(conv.Pos(), conv.X.Type(), v.Val())
628
+ typecheck.Expr(conv)
629
+ }
630
+ }
631
+ }
632
+ }
633
+
634
+ // reassignOracle returns an initialized *ir.ReassignOracle for fn.
635
+ // If fn is a closure, it returns the ReassignOracle for the ultimate parent.
636
+ //
637
+ // A new ReassignOracle is initialized lazily if needed, and the result
638
+ // is cached to reduce duplicative work of preparing a ReassignOracle.
639
+ func (b *batch) reassignOracle(fn *ir.Func) *ir.ReassignOracle {
640
+ if ro, ok := b.reassignOracles[fn]; ok {
641
+ return ro // Hit.
642
+ }
643
+
644
+ // For closures, we want the ultimate parent's ReassignOracle,
645
+ // so walk up the parent chain, if any.
646
+ f := fn
647
+ for f.ClosureParent != nil && !f.ClosureParent.IsPackageInit() {
648
+ f = f.ClosureParent
649
+ }
650
+
651
+ if f != fn {
652
+ // We found a parent.
653
+ ro := b.reassignOracles[f]
654
+ if ro != nil {
655
+ // Hit, via a parent. Before returning, store this ro for the original fn as well.
656
+ b.reassignOracles[fn] = ro
657
+ return ro
658
+ }
659
+ }
660
+
661
+ // Miss. We did not find a ReassignOracle for fn or a parent, so lazily create one.
662
+ ro := &ir.ReassignOracle{}
663
+ ro.Init(f)
664
+
665
+ // Cache the answer for the original fn.
666
+ b.reassignOracles[fn] = ro
667
+ if f != fn {
668
+ // Cache for the parent as well.
669
+ b.reassignOracles[f] = ro
670
+ }
671
+ return ro
672
+ }
go/src/cmd/compile/internal/escape/expr.go ADDED
@@ -0,0 +1,341 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2018 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 escape
6
+
7
+ import (
8
+ "cmd/compile/internal/base"
9
+ "cmd/compile/internal/ir"
10
+ "cmd/compile/internal/types"
11
+ )
12
+
13
+ // expr models evaluating an expression n and flowing the result into
14
+ // hole k.
15
+ func (e *escape) expr(k hole, n ir.Node) {
16
+ if n == nil {
17
+ return
18
+ }
19
+ e.stmts(n.Init())
20
+ e.exprSkipInit(k, n)
21
+ }
22
+
23
+ func (e *escape) exprSkipInit(k hole, n ir.Node) {
24
+ if n == nil {
25
+ return
26
+ }
27
+
28
+ lno := ir.SetPos(n)
29
+ defer func() {
30
+ base.Pos = lno
31
+ }()
32
+
33
+ if k.derefs >= 0 && !n.Type().IsUntyped() && !n.Type().HasPointers() {
34
+ k.dst = &e.blankLoc
35
+ }
36
+
37
+ switch n.Op() {
38
+ default:
39
+ base.Fatalf("unexpected expr: %s %v", n.Op().String(), n)
40
+
41
+ case ir.OLITERAL, ir.ONIL, ir.OGETG, ir.OGETCALLERSP, ir.OTYPE, ir.OMETHEXPR, ir.OLINKSYMOFFSET:
42
+ // nop
43
+
44
+ case ir.ONAME:
45
+ n := n.(*ir.Name)
46
+ if n.Class == ir.PFUNC || n.Class == ir.PEXTERN {
47
+ return
48
+ }
49
+ e.flow(k, e.oldLoc(n))
50
+
51
+ case ir.OPLUS, ir.ONEG, ir.OBITNOT, ir.ONOT:
52
+ n := n.(*ir.UnaryExpr)
53
+ e.discard(n.X)
54
+ case ir.OADD, ir.OSUB, ir.OOR, ir.OXOR, ir.OMUL, ir.ODIV, ir.OMOD, ir.OLSH, ir.ORSH, ir.OAND, ir.OANDNOT, ir.OEQ, ir.ONE, ir.OLT, ir.OLE, ir.OGT, ir.OGE:
55
+ n := n.(*ir.BinaryExpr)
56
+ e.discard(n.X)
57
+ e.discard(n.Y)
58
+ case ir.OANDAND, ir.OOROR:
59
+ n := n.(*ir.LogicalExpr)
60
+ e.discard(n.X)
61
+ e.discard(n.Y)
62
+ case ir.OADDR:
63
+ n := n.(*ir.AddrExpr)
64
+ e.expr(k.addr(n, "address-of"), n.X) // "address-of"
65
+ case ir.ODEREF:
66
+ n := n.(*ir.StarExpr)
67
+ e.expr(k.deref(n, "indirection"), n.X) // "indirection"
68
+ case ir.ODOT, ir.ODOTMETH, ir.ODOTINTER:
69
+ n := n.(*ir.SelectorExpr)
70
+ e.expr(k.note(n, "dot"), n.X)
71
+ case ir.ODOTPTR:
72
+ n := n.(*ir.SelectorExpr)
73
+ e.expr(k.deref(n, "dot of pointer"), n.X) // "dot of pointer"
74
+ case ir.ODOTTYPE, ir.ODOTTYPE2:
75
+ n := n.(*ir.TypeAssertExpr)
76
+ e.expr(k.dotType(n.Type(), n, "dot"), n.X)
77
+ case ir.ODYNAMICDOTTYPE, ir.ODYNAMICDOTTYPE2:
78
+ n := n.(*ir.DynamicTypeAssertExpr)
79
+ e.expr(k.dotType(n.Type(), n, "dot"), n.X)
80
+ // n.T doesn't need to be tracked; it always points to read-only storage.
81
+ case ir.OINDEX:
82
+ n := n.(*ir.IndexExpr)
83
+ if n.X.Type().IsArray() {
84
+ e.expr(k.note(n, "fixed-array-index-of"), n.X)
85
+ } else {
86
+ // TODO(mdempsky): Fix why reason text.
87
+ e.expr(k.deref(n, "dot of pointer"), n.X)
88
+ }
89
+ e.discard(n.Index)
90
+ case ir.OINDEXMAP:
91
+ n := n.(*ir.IndexExpr)
92
+ e.discard(n.X)
93
+ e.discard(n.Index)
94
+ case ir.OSLICE, ir.OSLICEARR, ir.OSLICE3, ir.OSLICE3ARR, ir.OSLICESTR:
95
+ n := n.(*ir.SliceExpr)
96
+ e.expr(k.note(n, "slice"), n.X)
97
+ e.discard(n.Low)
98
+ e.discard(n.High)
99
+ e.discard(n.Max)
100
+
101
+ case ir.OCONV, ir.OCONVNOP:
102
+ n := n.(*ir.ConvExpr)
103
+ if (ir.ShouldCheckPtr(e.curfn, 2) || ir.ShouldAsanCheckPtr(e.curfn)) && n.Type().IsUnsafePtr() && n.X.Type().IsPtr() {
104
+ // When -d=checkptr=2 or -asan is enabled,
105
+ // treat conversions to unsafe.Pointer as an
106
+ // escaping operation. This allows better
107
+ // runtime instrumentation, since we can more
108
+ // easily detect object boundaries on the heap
109
+ // than the stack.
110
+ e.assignHeap(n.X, "conversion to unsafe.Pointer", n)
111
+ } else if n.Type().IsUnsafePtr() && n.X.Type().IsUintptr() {
112
+ e.unsafeValue(k, n.X)
113
+ } else {
114
+ e.expr(k, n.X)
115
+ }
116
+ case ir.OCONVIFACE:
117
+ n := n.(*ir.ConvExpr)
118
+ if !n.X.Type().IsInterface() && !types.IsDirectIface(n.X.Type()) {
119
+ k = e.spill(k, n)
120
+ }
121
+ e.expr(k.note(n, "interface-converted"), n.X)
122
+ case ir.OMAKEFACE:
123
+ n := n.(*ir.BinaryExpr)
124
+ // Note: n.X is not needed because it can never point to memory that might escape.
125
+ e.expr(k, n.Y)
126
+ case ir.OITAB, ir.OIDATA, ir.OSPTR:
127
+ n := n.(*ir.UnaryExpr)
128
+ e.expr(k, n.X)
129
+ case ir.OSLICE2ARR:
130
+ // Converting a slice to array is effectively a deref.
131
+ n := n.(*ir.ConvExpr)
132
+ e.expr(k.deref(n, "slice-to-array"), n.X)
133
+ case ir.OSLICE2ARRPTR:
134
+ // the slice pointer flows directly to the result
135
+ n := n.(*ir.ConvExpr)
136
+ e.expr(k, n.X)
137
+ case ir.ORECV:
138
+ n := n.(*ir.UnaryExpr)
139
+ e.discard(n.X)
140
+
141
+ case ir.OCALLMETH, ir.OCALLFUNC, ir.OCALLINTER, ir.OINLCALL,
142
+ ir.OLEN, ir.OCAP, ir.OMIN, ir.OMAX, ir.OCOMPLEX, ir.OREAL, ir.OIMAG, ir.OAPPEND, ir.OCOPY, ir.ORECOVER,
143
+ ir.OUNSAFEADD, ir.OUNSAFESLICE, ir.OUNSAFESTRING, ir.OUNSAFESTRINGDATA, ir.OUNSAFESLICEDATA:
144
+ e.call([]hole{k}, n)
145
+
146
+ case ir.ONEW:
147
+ n := n.(*ir.UnaryExpr)
148
+ e.spill(k, n)
149
+
150
+ case ir.OMAKESLICE:
151
+ n := n.(*ir.MakeExpr)
152
+ e.spill(k, n)
153
+ e.discard(n.Len)
154
+ e.discard(n.Cap)
155
+ case ir.OMAKECHAN:
156
+ n := n.(*ir.MakeExpr)
157
+ e.discard(n.Len)
158
+ case ir.OMAKEMAP:
159
+ n := n.(*ir.MakeExpr)
160
+ e.spill(k, n)
161
+ e.discard(n.Len)
162
+
163
+ case ir.OMETHVALUE:
164
+ // Flow the receiver argument to both the closure and
165
+ // to the receiver parameter.
166
+
167
+ n := n.(*ir.SelectorExpr)
168
+ closureK := e.spill(k, n)
169
+
170
+ m := n.Selection
171
+
172
+ // We don't know how the method value will be called
173
+ // later, so conservatively assume the result
174
+ // parameters all flow to the heap.
175
+ //
176
+ // TODO(mdempsky): Change ks into a callback, so that
177
+ // we don't have to create this slice?
178
+ var ks []hole
179
+ for i := m.Type.NumResults(); i > 0; i-- {
180
+ ks = append(ks, e.heapHole())
181
+ }
182
+ name, _ := m.Nname.(*ir.Name)
183
+ paramK := e.tagHole(ks, name, m.Type.Recv())
184
+
185
+ e.expr(e.teeHole(paramK, closureK), n.X)
186
+
187
+ case ir.OPTRLIT:
188
+ n := n.(*ir.AddrExpr)
189
+ e.expr(e.spill(k, n), n.X)
190
+
191
+ case ir.OARRAYLIT:
192
+ n := n.(*ir.CompLitExpr)
193
+ for _, elt := range n.List {
194
+ if elt.Op() == ir.OKEY {
195
+ elt = elt.(*ir.KeyExpr).Value
196
+ }
197
+ e.expr(k.note(n, "array literal element"), elt)
198
+ }
199
+
200
+ case ir.OSLICELIT:
201
+ n := n.(*ir.CompLitExpr)
202
+ k = e.spill(k, n)
203
+
204
+ for _, elt := range n.List {
205
+ if elt.Op() == ir.OKEY {
206
+ elt = elt.(*ir.KeyExpr).Value
207
+ }
208
+ e.expr(k.note(n, "slice-literal-element"), elt)
209
+ }
210
+
211
+ case ir.OSTRUCTLIT:
212
+ n := n.(*ir.CompLitExpr)
213
+ for _, elt := range n.List {
214
+ e.expr(k.note(n, "struct literal element"), elt.(*ir.StructKeyExpr).Value)
215
+ }
216
+
217
+ case ir.OMAPLIT:
218
+ n := n.(*ir.CompLitExpr)
219
+ e.spill(k, n)
220
+
221
+ // Map keys and values are always stored in the heap.
222
+ for _, elt := range n.List {
223
+ elt := elt.(*ir.KeyExpr)
224
+ e.assignHeap(elt.Key, "map literal key", n)
225
+ e.assignHeap(elt.Value, "map literal value", n)
226
+ }
227
+
228
+ case ir.OCLOSURE:
229
+ n := n.(*ir.ClosureExpr)
230
+ k = e.spill(k, n)
231
+ e.closures = append(e.closures, closure{k, n})
232
+
233
+ if fn := n.Func; fn.IsClosure() {
234
+ for _, cv := range fn.ClosureVars {
235
+ if loc := e.oldLoc(cv); !loc.captured {
236
+ loc.captured = true
237
+
238
+ // Ignore reassignments to the variable in straightline code
239
+ // preceding the first capture by a closure.
240
+ if loc.loopDepth == e.loopDepth {
241
+ loc.reassigned = false
242
+ }
243
+ }
244
+ }
245
+
246
+ for _, n := range fn.Dcl {
247
+ // Add locations for local variables of the
248
+ // closure, if needed, in case we're not including
249
+ // the closure func in the batch for escape
250
+ // analysis (happens for escape analysis called
251
+ // from reflectdata.methodWrapper)
252
+ if n.Op() == ir.ONAME && n.Opt == nil {
253
+ e.with(fn).newLoc(n, true)
254
+ }
255
+ }
256
+ e.walkFunc(fn)
257
+ }
258
+
259
+ case ir.ORUNES2STR, ir.OBYTES2STR, ir.OSTR2RUNES, ir.OSTR2BYTES, ir.ORUNESTR:
260
+ n := n.(*ir.ConvExpr)
261
+ e.spill(k, n)
262
+ e.discard(n.X)
263
+
264
+ case ir.OADDSTR:
265
+ n := n.(*ir.AddStringExpr)
266
+ e.spill(k, n)
267
+
268
+ // Arguments of OADDSTR never escape;
269
+ // runtime.concatstrings makes sure of that.
270
+ e.discards(n.List)
271
+
272
+ case ir.ODYNAMICTYPE:
273
+ // Nothing to do - argument is a *runtime._type (+ maybe a *runtime.itab) pointing to static data section
274
+ }
275
+ }
276
+
277
+ // unsafeValue evaluates a uintptr-typed arithmetic expression looking
278
+ // for conversions from an unsafe.Pointer.
279
+ func (e *escape) unsafeValue(k hole, n ir.Node) {
280
+ if n.Type().Kind() != types.TUINTPTR {
281
+ base.Fatalf("unexpected type %v for %v", n.Type(), n)
282
+ }
283
+ if k.addrtaken {
284
+ base.Fatalf("unexpected addrtaken")
285
+ }
286
+
287
+ e.stmts(n.Init())
288
+
289
+ switch n.Op() {
290
+ case ir.OCONV, ir.OCONVNOP:
291
+ n := n.(*ir.ConvExpr)
292
+ if n.X.Type().IsUnsafePtr() {
293
+ e.expr(k, n.X)
294
+ } else {
295
+ e.discard(n.X)
296
+ }
297
+ case ir.ODOTPTR:
298
+ n := n.(*ir.SelectorExpr)
299
+ if ir.IsReflectHeaderDataField(n) {
300
+ e.expr(k.deref(n, "reflect.Header.Data"), n.X)
301
+ } else {
302
+ e.discard(n.X)
303
+ }
304
+ case ir.OPLUS, ir.ONEG, ir.OBITNOT:
305
+ n := n.(*ir.UnaryExpr)
306
+ e.unsafeValue(k, n.X)
307
+ case ir.OADD, ir.OSUB, ir.OOR, ir.OXOR, ir.OMUL, ir.ODIV, ir.OMOD, ir.OAND, ir.OANDNOT:
308
+ n := n.(*ir.BinaryExpr)
309
+ e.unsafeValue(k, n.X)
310
+ e.unsafeValue(k, n.Y)
311
+ case ir.OLSH, ir.ORSH:
312
+ n := n.(*ir.BinaryExpr)
313
+ e.unsafeValue(k, n.X)
314
+ // RHS need not be uintptr-typed (#32959) and can't meaningfully
315
+ // flow pointers anyway.
316
+ e.discard(n.Y)
317
+ default:
318
+ e.exprSkipInit(e.discardHole(), n)
319
+ }
320
+ }
321
+
322
+ // discard evaluates an expression n for side-effects, but discards
323
+ // its value.
324
+ func (e *escape) discard(n ir.Node) {
325
+ e.expr(e.discardHole(), n)
326
+ }
327
+
328
+ func (e *escape) discards(l ir.Nodes) {
329
+ for _, n := range l {
330
+ e.discard(n)
331
+ }
332
+ }
333
+
334
+ // spill allocates a new location associated with expression n, flows
335
+ // its address to k, and returns a hole that flows values to it. It's
336
+ // intended for use with most expressions that allocate storage.
337
+ func (e *escape) spill(k hole, n ir.Node) hole {
338
+ loc := e.newLoc(n, false)
339
+ e.flow(k.addr(n, "spill"), loc)
340
+ return loc.asHole()
341
+ }
go/src/cmd/compile/internal/escape/graph.go ADDED
@@ -0,0 +1,360 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2018 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 escape
6
+
7
+ import (
8
+ "cmd/compile/internal/base"
9
+ "cmd/compile/internal/ir"
10
+ "cmd/compile/internal/logopt"
11
+ "cmd/compile/internal/types"
12
+ "fmt"
13
+ )
14
+
15
+ // Below we implement the methods for walking the AST and recording
16
+ // data flow edges. Note that because a sub-expression might have
17
+ // side-effects, it's important to always visit the entire AST.
18
+ //
19
+ // For example, write either:
20
+ //
21
+ // if x {
22
+ // e.discard(n.Left)
23
+ // } else {
24
+ // e.value(k, n.Left)
25
+ // }
26
+ //
27
+ // or
28
+ //
29
+ // if x {
30
+ // k = e.discardHole()
31
+ // }
32
+ // e.value(k, n.Left)
33
+ //
34
+ // Do NOT write:
35
+ //
36
+ // // BAD: possibly loses side-effects within n.Left
37
+ // if !x {
38
+ // e.value(k, n.Left)
39
+ // }
40
+
41
+ // A location represents an abstract location that stores a Go
42
+ // variable.
43
+ type location struct {
44
+ n ir.Node // represented variable or expression, if any
45
+ curfn *ir.Func // enclosing function
46
+ edges []edge // incoming edges
47
+ loopDepth int // loopDepth at declaration
48
+
49
+ // resultIndex records the tuple index (starting at 1) for
50
+ // PPARAMOUT variables within their function's result type.
51
+ // For non-PPARAMOUT variables it's 0.
52
+ resultIndex int
53
+
54
+ // derefs and walkgen are used during walkOne to track the
55
+ // minimal dereferences from the walk root.
56
+ derefs int // >= -1
57
+ walkgen uint32
58
+
59
+ // dst and dstEdgeindex track the next immediate assignment
60
+ // destination location during walkone, along with the index
61
+ // of the edge pointing back to this location.
62
+ dst *location
63
+ dstEdgeIdx int
64
+
65
+ // queuedWalkAll is used by walkAll to track whether this location is
66
+ // in its work queue.
67
+ queuedWalkAll bool
68
+
69
+ // queuedWalkOne is used by walkOne to track whether this location is
70
+ // in its work queue. The value is the walkgen when this location was
71
+ // last queued for walkOne, or 0 if it's not currently queued.
72
+ queuedWalkOne uint32
73
+
74
+ // attrs is a bitset of location attributes.
75
+ attrs locAttr
76
+
77
+ // paramEsc records the represented parameter's leak set.
78
+ paramEsc leaks
79
+
80
+ captured bool // has a closure captured this variable?
81
+ reassigned bool // has this variable been reassigned?
82
+ addrtaken bool // has this variable's address been taken?
83
+ param bool // is this variable a parameter (ONAME of class ir.PPARAM)?
84
+ paramOut bool // is this variable an out parameter (ONAME of class ir.PPARAMOUT)?
85
+ }
86
+
87
+ type locAttr uint8
88
+
89
+ const (
90
+ // attrEscapes indicates whether the represented variable's address
91
+ // escapes; that is, whether the variable must be heap allocated.
92
+ attrEscapes locAttr = 1 << iota
93
+
94
+ // attrPersists indicates whether the represented expression's
95
+ // address outlives the statement; that is, whether its storage
96
+ // cannot be immediately reused.
97
+ attrPersists
98
+
99
+ // attrMutates indicates whether pointers that are reachable from
100
+ // this location may have their addressed memory mutated. This is
101
+ // used to detect string->[]byte conversions that can be safely
102
+ // optimized away.
103
+ attrMutates
104
+
105
+ // attrCalls indicates whether closures that are reachable from this
106
+ // location may be called without tracking their results. This is
107
+ // used to better optimize indirect closure calls.
108
+ attrCalls
109
+ )
110
+
111
+ func (l *location) hasAttr(attr locAttr) bool { return l.attrs&attr != 0 }
112
+
113
+ // An edge represents an assignment edge between two Go variables.
114
+ type edge struct {
115
+ src *location
116
+ derefs int // >= -1
117
+ notes *note
118
+ }
119
+
120
+ func (l *location) asHole() hole {
121
+ return hole{dst: l}
122
+ }
123
+
124
+ // leak records that parameter l leaks to sink.
125
+ func (l *location) leakTo(sink *location, derefs int) {
126
+ // If sink is a result parameter that doesn't escape (#44614)
127
+ // and we can fit return bits into the escape analysis tag,
128
+ // then record as a result leak.
129
+ if !sink.hasAttr(attrEscapes) && sink.isName(ir.PPARAMOUT) && sink.curfn == l.curfn {
130
+ ri := sink.resultIndex - 1
131
+ if ri < numEscResults {
132
+ // Leak to result parameter.
133
+ l.paramEsc.AddResult(ri, derefs)
134
+ return
135
+ }
136
+ }
137
+
138
+ // Otherwise, record as heap leak.
139
+ l.paramEsc.AddHeap(derefs)
140
+ }
141
+
142
+ func (l *location) isName(c ir.Class) bool {
143
+ return l.n != nil && l.n.Op() == ir.ONAME && l.n.(*ir.Name).Class == c
144
+ }
145
+
146
+ // A hole represents a context for evaluation of a Go
147
+ // expression. E.g., when evaluating p in "x = **p", we'd have a hole
148
+ // with dst==x and derefs==2.
149
+ type hole struct {
150
+ dst *location
151
+ derefs int // >= -1
152
+ notes *note
153
+
154
+ // addrtaken indicates whether this context is taking the address of
155
+ // the expression, independent of whether the address will actually
156
+ // be stored into a variable.
157
+ addrtaken bool
158
+ }
159
+
160
+ type note struct {
161
+ next *note
162
+ where ir.Node
163
+ why string
164
+ }
165
+
166
+ func (k hole) note(where ir.Node, why string) hole {
167
+ if where == nil || why == "" {
168
+ base.Fatalf("note: missing where/why")
169
+ }
170
+ if base.Flag.LowerM >= 2 || logopt.Enabled() {
171
+ k.notes = &note{
172
+ next: k.notes,
173
+ where: where,
174
+ why: why,
175
+ }
176
+ }
177
+ return k
178
+ }
179
+
180
+ func (k hole) shift(delta int) hole {
181
+ k.derefs += delta
182
+ if k.derefs < -1 {
183
+ base.Fatalf("derefs underflow: %v", k.derefs)
184
+ }
185
+ k.addrtaken = delta < 0
186
+ return k
187
+ }
188
+
189
+ func (k hole) deref(where ir.Node, why string) hole { return k.shift(1).note(where, why) }
190
+ func (k hole) addr(where ir.Node, why string) hole { return k.shift(-1).note(where, why) }
191
+
192
+ func (k hole) dotType(t *types.Type, where ir.Node, why string) hole {
193
+ if !t.IsInterface() && !types.IsDirectIface(t) {
194
+ k = k.shift(1)
195
+ }
196
+ return k.note(where, why)
197
+ }
198
+
199
+ func (b *batch) flow(k hole, src *location) {
200
+ if k.addrtaken {
201
+ src.addrtaken = true
202
+ }
203
+
204
+ dst := k.dst
205
+ if dst == &b.blankLoc {
206
+ return
207
+ }
208
+ if dst == src && k.derefs >= 0 { // dst = dst, dst = *dst, ...
209
+ return
210
+ }
211
+ if dst.hasAttr(attrEscapes) && k.derefs < 0 { // dst = &src
212
+ if base.Flag.LowerM >= 2 || logopt.Enabled() {
213
+ pos := base.FmtPos(src.n.Pos())
214
+ if base.Flag.LowerM >= 2 {
215
+ fmt.Printf("%s: %v escapes to heap in %v:\n", pos, src.n, ir.FuncName(src.curfn))
216
+ }
217
+ explanation := b.explainFlow(pos, dst, src, k.derefs, k.notes, []*logopt.LoggedOpt{})
218
+ if logopt.Enabled() {
219
+ var e_curfn *ir.Func // TODO(mdempsky): Fix.
220
+ logopt.LogOpt(src.n.Pos(), "escapes", "escape", ir.FuncName(e_curfn), fmt.Sprintf("%v escapes to heap", src.n), explanation)
221
+ }
222
+
223
+ }
224
+ src.attrs |= attrEscapes | attrPersists | attrMutates | attrCalls
225
+ return
226
+ }
227
+
228
+ // TODO(mdempsky): Deduplicate edges?
229
+ dst.edges = append(dst.edges, edge{src: src, derefs: k.derefs, notes: k.notes})
230
+ }
231
+
232
+ func (b *batch) heapHole() hole { return b.heapLoc.asHole() }
233
+ func (b *batch) mutatorHole() hole { return b.mutatorLoc.asHole() }
234
+ func (b *batch) calleeHole() hole { return b.calleeLoc.asHole() }
235
+ func (b *batch) discardHole() hole { return b.blankLoc.asHole() }
236
+
237
+ func (b *batch) oldLoc(n *ir.Name) *location {
238
+ if n.Canonical().Opt == nil {
239
+ base.FatalfAt(n.Pos(), "%v has no location", n)
240
+ }
241
+ return n.Canonical().Opt.(*location)
242
+ }
243
+
244
+ func (e *escape) newLoc(n ir.Node, persists bool) *location {
245
+ if e.curfn == nil {
246
+ base.Fatalf("e.curfn isn't set")
247
+ }
248
+ if n != nil && n.Type() != nil && n.Type().NotInHeap() {
249
+ base.ErrorfAt(n.Pos(), 0, "%v is incomplete (or unallocatable); stack allocation disallowed", n.Type())
250
+ }
251
+
252
+ if n != nil && n.Op() == ir.ONAME {
253
+ if canon := n.(*ir.Name).Canonical(); n != canon {
254
+ base.FatalfAt(n.Pos(), "newLoc on non-canonical %v (canonical is %v)", n, canon)
255
+ }
256
+ }
257
+ loc := &location{
258
+ n: n,
259
+ curfn: e.curfn,
260
+ loopDepth: e.loopDepth,
261
+ }
262
+ if loc.isName(ir.PPARAM) {
263
+ loc.param = true
264
+ } else if loc.isName(ir.PPARAMOUT) {
265
+ loc.paramOut = true
266
+ }
267
+
268
+ if persists {
269
+ loc.attrs |= attrPersists
270
+ }
271
+ e.allLocs = append(e.allLocs, loc)
272
+ if n != nil {
273
+ if n.Op() == ir.ONAME {
274
+ n := n.(*ir.Name)
275
+ if n.Class == ir.PPARAM && n.Curfn == nil {
276
+ // ok; hidden parameter
277
+ } else if n.Curfn != e.curfn {
278
+ base.FatalfAt(n.Pos(), "curfn mismatch: %v != %v for %v", n.Curfn, e.curfn, n)
279
+ }
280
+
281
+ if n.Opt != nil {
282
+ base.FatalfAt(n.Pos(), "%v already has a location", n)
283
+ }
284
+ n.Opt = loc
285
+ }
286
+ }
287
+ return loc
288
+ }
289
+
290
+ // teeHole returns a new hole that flows into each hole of ks,
291
+ // similar to the Unix tee(1) command.
292
+ func (e *escape) teeHole(ks ...hole) hole {
293
+ if len(ks) == 0 {
294
+ return e.discardHole()
295
+ }
296
+ if len(ks) == 1 {
297
+ return ks[0]
298
+ }
299
+ // TODO(mdempsky): Optimize if there's only one non-discard hole?
300
+
301
+ // Given holes "l1 = _", "l2 = **_", "l3 = *_", ..., create a
302
+ // new temporary location ltmp, wire it into place, and return
303
+ // a hole for "ltmp = _".
304
+ loc := e.newLoc(nil, false)
305
+ for _, k := range ks {
306
+ // N.B., "p = &q" and "p = &tmp; tmp = q" are not
307
+ // semantically equivalent. To combine holes like "l1
308
+ // = _" and "l2 = &_", we'd need to wire them as "l1 =
309
+ // *ltmp" and "l2 = ltmp" and return "ltmp = &_"
310
+ // instead.
311
+ if k.derefs < 0 {
312
+ base.Fatalf("teeHole: negative derefs")
313
+ }
314
+
315
+ e.flow(k, loc)
316
+ }
317
+ return loc.asHole()
318
+ }
319
+
320
+ // later returns a new hole that flows into k, but some time later.
321
+ // Its main effect is to prevent immediate reuse of temporary
322
+ // variables introduced during Order.
323
+ func (e *escape) later(k hole) hole {
324
+ loc := e.newLoc(nil, true)
325
+ e.flow(k, loc)
326
+ return loc.asHole()
327
+ }
328
+
329
+ // Fmt is called from node printing to print information about escape analysis results.
330
+ func Fmt(n ir.Node) string {
331
+ text := ""
332
+ switch n.Esc() {
333
+ case ir.EscUnknown:
334
+ break
335
+
336
+ case ir.EscHeap:
337
+ text = "esc(h)"
338
+
339
+ case ir.EscNone:
340
+ text = "esc(no)"
341
+
342
+ case ir.EscNever:
343
+ text = "esc(N)"
344
+
345
+ default:
346
+ text = fmt.Sprintf("esc(%d)", n.Esc())
347
+ }
348
+
349
+ if n.Op() == ir.ONAME {
350
+ n := n.(*ir.Name)
351
+ if loc, ok := n.Opt.(*location); ok && loc.loopDepth != 0 {
352
+ if text != "" {
353
+ text += " "
354
+ }
355
+ text += fmt.Sprintf("ld(%d)", loc.loopDepth)
356
+ }
357
+ }
358
+
359
+ return text
360
+ }
go/src/cmd/compile/internal/escape/leaks.go ADDED
@@ -0,0 +1,144 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2018 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 escape
6
+
7
+ import (
8
+ "cmd/compile/internal/base"
9
+ "math"
10
+ "strings"
11
+ )
12
+
13
+ // A leaks represents a set of assignment flows from a parameter to
14
+ // the heap, mutator, callee, or to any of its function's (first
15
+ // numEscResults) result parameters.
16
+ type leaks [8]uint8
17
+
18
+ const (
19
+ leakHeap = iota
20
+ leakMutator
21
+ leakCallee
22
+ leakResult0
23
+ )
24
+
25
+ const numEscResults = len(leaks{}) - leakResult0
26
+
27
+ // Heap returns the minimum deref count of any assignment flow from l
28
+ // to the heap. If no such flows exist, Heap returns -1.
29
+ func (l leaks) Heap() int { return l.get(leakHeap) }
30
+
31
+ // Mutator returns the minimum deref count of any assignment flow from
32
+ // l to the pointer operand of an indirect assignment statement. If no
33
+ // such flows exist, Mutator returns -1.
34
+ func (l leaks) Mutator() int { return l.get(leakMutator) }
35
+
36
+ // Callee returns the minimum deref count of any assignment flow from
37
+ // l to the callee operand of call expression. If no such flows exist,
38
+ // Callee returns -1.
39
+ func (l leaks) Callee() int { return l.get(leakCallee) }
40
+
41
+ // Result returns the minimum deref count of any assignment flow from
42
+ // l to its function's i'th result parameter. If no such flows exist,
43
+ // Result returns -1.
44
+ func (l leaks) Result(i int) int { return l.get(leakResult0 + i) }
45
+
46
+ // AddHeap adds an assignment flow from l to the heap.
47
+ func (l *leaks) AddHeap(derefs int) { l.add(leakHeap, derefs) }
48
+
49
+ // AddMutator adds a flow from l to the mutator (i.e., a pointer
50
+ // operand of an indirect assignment statement).
51
+ func (l *leaks) AddMutator(derefs int) { l.add(leakMutator, derefs) }
52
+
53
+ // AddCallee adds an assignment flow from l to the callee operand of a
54
+ // call expression.
55
+ func (l *leaks) AddCallee(derefs int) { l.add(leakCallee, derefs) }
56
+
57
+ // AddResult adds an assignment flow from l to its function's i'th
58
+ // result parameter.
59
+ func (l *leaks) AddResult(i, derefs int) { l.add(leakResult0+i, derefs) }
60
+
61
+ func (l leaks) get(i int) int { return int(l[i]) - 1 }
62
+
63
+ func (l *leaks) add(i, derefs int) {
64
+ if old := l.get(i); old < 0 || derefs < old {
65
+ l.set(i, derefs)
66
+ }
67
+ }
68
+
69
+ func (l *leaks) set(i, derefs int) {
70
+ v := derefs + 1
71
+ if v < 0 {
72
+ base.Fatalf("invalid derefs count: %v", derefs)
73
+ }
74
+ if v > math.MaxUint8 {
75
+ v = math.MaxUint8
76
+ }
77
+
78
+ l[i] = uint8(v)
79
+ }
80
+
81
+ // Optimize removes result flow paths that are equal in length or
82
+ // longer than the shortest heap flow path.
83
+ func (l *leaks) Optimize() {
84
+ // If we have a path to the heap, then there's no use in
85
+ // keeping equal or longer paths elsewhere.
86
+ if x := l.Heap(); x >= 0 {
87
+ for i := 1; i < len(*l); i++ {
88
+ if l.get(i) >= x {
89
+ l.set(i, -1)
90
+ }
91
+ }
92
+ }
93
+ }
94
+
95
+ var leakTagCache = map[leaks]string{}
96
+
97
+ // Encode converts l into a binary string for export data.
98
+ func (l leaks) Encode() string {
99
+ if l.Heap() == 0 {
100
+ // Space optimization: empty string encodes more
101
+ // efficiently in export data.
102
+ return ""
103
+ }
104
+ if s, ok := leakTagCache[l]; ok {
105
+ return s
106
+ }
107
+
108
+ n := len(l)
109
+ for n > 0 && l[n-1] == 0 {
110
+ n--
111
+ }
112
+ s := "esc:" + string(l[:n])
113
+ leakTagCache[l] = s
114
+ return s
115
+ }
116
+
117
+ // parseLeaks parses a binary string representing a leaks.
118
+ func parseLeaks(s string) leaks {
119
+ var l leaks
120
+ if !strings.HasPrefix(s, "esc:") {
121
+ l.AddHeap(0)
122
+ return l
123
+ }
124
+ copy(l[:], s[4:])
125
+ return l
126
+ }
127
+
128
+ func ParseLeaks(s string) leaks {
129
+ return parseLeaks(s)
130
+ }
131
+
132
+ // Any reports whether the value flows anywhere at all.
133
+ func (l leaks) Any() bool {
134
+ // TODO: do mutator/callee matter?
135
+ if l.Heap() >= 0 || l.Mutator() >= 0 || l.Callee() >= 0 {
136
+ return true
137
+ }
138
+ for i := range numEscResults {
139
+ if l.Result(i) >= 0 {
140
+ return true
141
+ }
142
+ }
143
+ return false
144
+ }
go/src/cmd/compile/internal/escape/solve.go ADDED
@@ -0,0 +1,397 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2018 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 escape
6
+
7
+ import (
8
+ "cmd/compile/internal/base"
9
+ "cmd/compile/internal/ir"
10
+ "cmd/compile/internal/logopt"
11
+ "cmd/internal/src"
12
+ "fmt"
13
+ "math/bits"
14
+ "strings"
15
+ )
16
+
17
+ // walkAll computes the minimal dereferences between all pairs of
18
+ // locations.
19
+ func (b *batch) walkAll() {
20
+ // We use a work queue to keep track of locations that we need
21
+ // to visit, and repeatedly walk until we reach a fixed point.
22
+ //
23
+ // We walk once from each location (including the heap), and
24
+ // then re-enqueue each location on its transition from
25
+ // !persists->persists and !escapes->escapes, which can each
26
+ // happen at most once. So we take Θ(len(e.allLocs)) walks.
27
+
28
+ // Queue of locations to walk. Has enough room for b.allLocs
29
+ // plus b.heapLoc, b.mutatorLoc, b.calleeLoc.
30
+ todo := newQueue(len(b.allLocs) + 3)
31
+
32
+ enqueue := func(loc *location) {
33
+ if !loc.queuedWalkAll {
34
+ loc.queuedWalkAll = true
35
+ if loc.hasAttr(attrEscapes) {
36
+ // Favor locations that escape to the heap,
37
+ // which in some cases allows attrEscape to
38
+ // propagate faster.
39
+ todo.pushFront(loc)
40
+ } else {
41
+ todo.pushBack(loc)
42
+ }
43
+ }
44
+ }
45
+
46
+ for _, loc := range b.allLocs {
47
+ todo.pushFront(loc)
48
+ // TODO(thepudds): clean up setting queuedWalkAll.
49
+ loc.queuedWalkAll = true
50
+ }
51
+ todo.pushFront(&b.mutatorLoc)
52
+ todo.pushFront(&b.calleeLoc)
53
+ todo.pushFront(&b.heapLoc)
54
+
55
+ b.mutatorLoc.queuedWalkAll = true
56
+ b.calleeLoc.queuedWalkAll = true
57
+ b.heapLoc.queuedWalkAll = true
58
+
59
+ var walkgen uint32
60
+ for todo.len() > 0 {
61
+ root := todo.popFront()
62
+ root.queuedWalkAll = false
63
+ walkgen++
64
+ b.walkOne(root, walkgen, enqueue)
65
+ }
66
+ }
67
+
68
+ // walkOne computes the minimal number of dereferences from root to
69
+ // all other locations.
70
+ func (b *batch) walkOne(root *location, walkgen uint32, enqueue func(*location)) {
71
+ // The data flow graph has negative edges (from addressing
72
+ // operations), so we use the Bellman-Ford algorithm. However,
73
+ // we don't have to worry about infinite negative cycles since
74
+ // we bound intermediate dereference counts to 0.
75
+
76
+ root.walkgen = walkgen
77
+ root.derefs = 0
78
+ root.dst = nil
79
+
80
+ if root.hasAttr(attrCalls) {
81
+ if clo, ok := root.n.(*ir.ClosureExpr); ok {
82
+ if fn := clo.Func; b.inMutualBatch(fn.Nname) && !fn.ClosureResultsLost() {
83
+ fn.SetClosureResultsLost(true)
84
+
85
+ // Re-flow from the closure's results, now that we're aware
86
+ // we lost track of them.
87
+ for _, result := range fn.Type().Results() {
88
+ enqueue(b.oldLoc(result.Nname.(*ir.Name)))
89
+ }
90
+ }
91
+ }
92
+ }
93
+
94
+ todo := newQueue(1)
95
+ todo.pushFront(root)
96
+
97
+ for todo.len() > 0 {
98
+ l := todo.popFront()
99
+ l.queuedWalkOne = 0 // no longer queued for walkOne
100
+
101
+ derefs := l.derefs
102
+ var newAttrs locAttr
103
+
104
+ // If l.derefs < 0, then l's address flows to root.
105
+ addressOf := derefs < 0
106
+ if addressOf {
107
+ // For a flow path like "root = &l; l = x",
108
+ // l's address flows to root, but x's does
109
+ // not. We recognize this by lower bounding
110
+ // derefs at 0.
111
+ derefs = 0
112
+
113
+ // If l's address flows somewhere that
114
+ // outlives it, then l needs to be heap
115
+ // allocated.
116
+ if b.outlives(root, l) {
117
+ if !l.hasAttr(attrEscapes) && (logopt.Enabled() || base.Flag.LowerM >= 2) {
118
+ if base.Flag.LowerM >= 2 {
119
+ fmt.Printf("%s: %v escapes to heap in %v:\n", base.FmtPos(l.n.Pos()), l.n, ir.FuncName(l.curfn))
120
+ }
121
+ explanation := b.explainPath(root, l)
122
+ if logopt.Enabled() {
123
+ var e_curfn *ir.Func // TODO(mdempsky): Fix.
124
+ logopt.LogOpt(l.n.Pos(), "escape", "escape", ir.FuncName(e_curfn), fmt.Sprintf("%v escapes to heap", l.n), explanation)
125
+ }
126
+ }
127
+ newAttrs |= attrEscapes | attrPersists | attrMutates | attrCalls
128
+ } else
129
+ // If l's address flows to a persistent location, then l needs
130
+ // to persist too.
131
+ if root.hasAttr(attrPersists) {
132
+ newAttrs |= attrPersists
133
+ }
134
+ }
135
+
136
+ if derefs == 0 {
137
+ newAttrs |= root.attrs & (attrMutates | attrCalls)
138
+ }
139
+
140
+ // l's value flows to root. If l is a function
141
+ // parameter and root is the heap or a
142
+ // corresponding result parameter, then record
143
+ // that value flow for tagging the function
144
+ // later.
145
+ if l.param {
146
+ if b.outlives(root, l) {
147
+ if !l.hasAttr(attrEscapes) && (logopt.Enabled() || base.Flag.LowerM >= 2) {
148
+ if base.Flag.LowerM >= 2 {
149
+ fmt.Printf("%s: parameter %v leaks to %s for %v with derefs=%d:\n", base.FmtPos(l.n.Pos()), l.n, b.explainLoc(root), ir.FuncName(l.curfn), derefs)
150
+ }
151
+ explanation := b.explainPath(root, l)
152
+ if logopt.Enabled() {
153
+ var e_curfn *ir.Func // TODO(mdempsky): Fix.
154
+ logopt.LogOpt(l.n.Pos(), "leak", "escape", ir.FuncName(e_curfn),
155
+ fmt.Sprintf("parameter %v leaks to %s with derefs=%d", l.n, b.explainLoc(root), derefs), explanation)
156
+ }
157
+ }
158
+ l.leakTo(root, derefs)
159
+ }
160
+ if root.hasAttr(attrMutates) {
161
+ l.paramEsc.AddMutator(derefs)
162
+ }
163
+ if root.hasAttr(attrCalls) {
164
+ l.paramEsc.AddCallee(derefs)
165
+ }
166
+ }
167
+
168
+ if newAttrs&^l.attrs != 0 {
169
+ l.attrs |= newAttrs
170
+ enqueue(l)
171
+ if l.attrs&attrEscapes != 0 {
172
+ continue
173
+ }
174
+ }
175
+
176
+ for i, edge := range l.edges {
177
+ if edge.src.hasAttr(attrEscapes) {
178
+ continue
179
+ }
180
+ d := derefs + edge.derefs
181
+ if edge.src.walkgen != walkgen || edge.src.derefs > d {
182
+ edge.src.walkgen = walkgen
183
+ edge.src.derefs = d
184
+ edge.src.dst = l
185
+ edge.src.dstEdgeIdx = i
186
+ // Check if already queued in todo.
187
+ if edge.src.queuedWalkOne != walkgen {
188
+ edge.src.queuedWalkOne = walkgen // Mark queued for this walkgen.
189
+
190
+ // Place at the back to possibly give time for
191
+ // other possible attribute changes to src.
192
+ todo.pushBack(edge.src)
193
+ }
194
+ }
195
+ }
196
+ }
197
+ }
198
+
199
+ // explainPath prints an explanation of how src flows to the walk root.
200
+ func (b *batch) explainPath(root, src *location) []*logopt.LoggedOpt {
201
+ visited := make(map[*location]bool)
202
+ pos := base.FmtPos(src.n.Pos())
203
+ var explanation []*logopt.LoggedOpt
204
+ for {
205
+ // Prevent infinite loop.
206
+ if visited[src] {
207
+ if base.Flag.LowerM >= 2 {
208
+ fmt.Printf("%s: warning: truncated explanation due to assignment cycle; see golang.org/issue/35518\n", pos)
209
+ }
210
+ break
211
+ }
212
+ visited[src] = true
213
+ dst := src.dst
214
+ edge := &dst.edges[src.dstEdgeIdx]
215
+ if edge.src != src {
216
+ base.Fatalf("path inconsistency: %v != %v", edge.src, src)
217
+ }
218
+
219
+ explanation = b.explainFlow(pos, dst, src, edge.derefs, edge.notes, explanation)
220
+
221
+ if dst == root {
222
+ break
223
+ }
224
+ src = dst
225
+ }
226
+
227
+ return explanation
228
+ }
229
+
230
+ func (b *batch) explainFlow(pos string, dst, srcloc *location, derefs int, notes *note, explanation []*logopt.LoggedOpt) []*logopt.LoggedOpt {
231
+ ops := "&"
232
+ if derefs >= 0 {
233
+ ops = strings.Repeat("*", derefs)
234
+ }
235
+ print := base.Flag.LowerM >= 2
236
+
237
+ flow := fmt.Sprintf(" flow: %s ← %s%v:", b.explainLoc(dst), ops, b.explainLoc(srcloc))
238
+ if print {
239
+ fmt.Printf("%s:%s\n", pos, flow)
240
+ }
241
+ if logopt.Enabled() {
242
+ var epos src.XPos
243
+ if notes != nil {
244
+ epos = notes.where.Pos()
245
+ } else if srcloc != nil && srcloc.n != nil {
246
+ epos = srcloc.n.Pos()
247
+ }
248
+ var e_curfn *ir.Func // TODO(mdempsky): Fix.
249
+ explanation = append(explanation, logopt.NewLoggedOpt(epos, epos, "escflow", "escape", ir.FuncName(e_curfn), flow))
250
+ }
251
+
252
+ for note := notes; note != nil; note = note.next {
253
+ if print {
254
+ fmt.Printf("%s: from %v (%v) at %s\n", pos, note.where, note.why, base.FmtPos(note.where.Pos()))
255
+ }
256
+ if logopt.Enabled() {
257
+ var e_curfn *ir.Func // TODO(mdempsky): Fix.
258
+ notePos := note.where.Pos()
259
+ explanation = append(explanation, logopt.NewLoggedOpt(notePos, notePos, "escflow", "escape", ir.FuncName(e_curfn),
260
+ fmt.Sprintf(" from %v (%v)", note.where, note.why)))
261
+ }
262
+ }
263
+ return explanation
264
+ }
265
+
266
+ func (b *batch) explainLoc(l *location) string {
267
+ if l == &b.heapLoc {
268
+ return "{heap}"
269
+ }
270
+ if l.n == nil {
271
+ // TODO(mdempsky): Omit entirely.
272
+ return "{temp}"
273
+ }
274
+ if l.n.Op() == ir.ONAME {
275
+ return fmt.Sprintf("%v", l.n)
276
+ }
277
+ return fmt.Sprintf("{storage for %v}", l.n)
278
+ }
279
+
280
+ // outlives reports whether values stored in l may survive beyond
281
+ // other's lifetime if stack allocated.
282
+ func (b *batch) outlives(l, other *location) bool {
283
+ // The heap outlives everything.
284
+ if l.hasAttr(attrEscapes) {
285
+ return true
286
+ }
287
+
288
+ // Pseudo-locations that don't really exist.
289
+ if l == &b.mutatorLoc || l == &b.calleeLoc {
290
+ return false
291
+ }
292
+
293
+ // We don't know what callers do with returned values, so
294
+ // pessimistically we need to assume they flow to the heap and
295
+ // outlive everything too.
296
+ if l.paramOut {
297
+ // Exception: Closures can return locations allocated outside of
298
+ // them without forcing them to the heap, if we can statically
299
+ // identify all call sites. For example:
300
+ //
301
+ // var u int // okay to stack allocate
302
+ // fn := func() *int { return &u }()
303
+ // *fn() = 42
304
+ if ir.ContainsClosure(other.curfn, l.curfn) && !l.curfn.ClosureResultsLost() {
305
+ return false
306
+ }
307
+
308
+ return true
309
+ }
310
+
311
+ // If l and other are within the same function, then l
312
+ // outlives other if it was declared outside other's loop
313
+ // scope. For example:
314
+ //
315
+ // var l *int
316
+ // for {
317
+ // l = new(int) // must heap allocate: outlives for loop
318
+ // }
319
+ if l.curfn == other.curfn && l.loopDepth < other.loopDepth {
320
+ return true
321
+ }
322
+
323
+ // If other is declared within a child closure of where l is
324
+ // declared, then l outlives it. For example:
325
+ //
326
+ // var l *int
327
+ // func() {
328
+ // l = new(int) // must heap allocate: outlives call frame (if not inlined)
329
+ // }()
330
+ if ir.ContainsClosure(l.curfn, other.curfn) {
331
+ return true
332
+ }
333
+
334
+ return false
335
+ }
336
+
337
+ // queue implements a queue of locations for use in WalkAll and WalkOne.
338
+ // It supports pushing to front & back, and popping from front.
339
+ // TODO(thepudds): does cmd/compile have a deque or similar somewhere?
340
+ type queue struct {
341
+ locs []*location
342
+ head int // index of front element
343
+ tail int // next back element
344
+ elems int
345
+ }
346
+
347
+ func newQueue(capacity int) *queue {
348
+ capacity = max(capacity, 2)
349
+ capacity = 1 << bits.Len64(uint64(capacity-1)) // round up to a power of 2
350
+ return &queue{locs: make([]*location, capacity)}
351
+ }
352
+
353
+ // pushFront adds an element to the front of the queue.
354
+ func (q *queue) pushFront(loc *location) {
355
+ if q.elems == len(q.locs) {
356
+ q.grow()
357
+ }
358
+ q.head = q.wrap(q.head - 1)
359
+ q.locs[q.head] = loc
360
+ q.elems++
361
+ }
362
+
363
+ // pushBack adds an element to the back of the queue.
364
+ func (q *queue) pushBack(loc *location) {
365
+ if q.elems == len(q.locs) {
366
+ q.grow()
367
+ }
368
+ q.locs[q.tail] = loc
369
+ q.tail = q.wrap(q.tail + 1)
370
+ q.elems++
371
+ }
372
+
373
+ // popFront removes the front of the queue.
374
+ func (q *queue) popFront() *location {
375
+ if q.elems == 0 {
376
+ return nil
377
+ }
378
+ loc := q.locs[q.head]
379
+ q.head = q.wrap(q.head + 1)
380
+ q.elems--
381
+ return loc
382
+ }
383
+
384
+ // grow doubles the capacity.
385
+ func (q *queue) grow() {
386
+ newLocs := make([]*location, len(q.locs)*2)
387
+ for i := range q.elems {
388
+ // Copy over our elements in order.
389
+ newLocs[i] = q.locs[q.wrap(q.head+i)]
390
+ }
391
+ q.locs = newLocs
392
+ q.head = 0
393
+ q.tail = q.elems
394
+ }
395
+
396
+ func (q *queue) len() int { return q.elems }
397
+ func (q *queue) wrap(i int) int { return i & (len(q.locs) - 1) }