Debian Codegraph @

arm64/instgen/generator.go

raw symbols SCIP
1 // Copyright 2026 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 main
6
7 import (
8 "bytes"
9 "fmt"
10 "go/format"
11 "log"
12 "math/rand/v2"
13 "os"
14 "os/exec"
15 "path/filepath"
16 "regexp"
17 "slices"
18 "sort"
19 "strings"
20 "text/template"
21
22 "golang.org/x/arch/arm64/instgen/xmlspec"
23 )
24
25 type tmplData struct {
26 EncodingFuncs []funcData
27 Insts []instData
28 InstsByName []instsByName
29 // All possible arg patterns are aggregated here.
30 // They are unique with regard to [Class] and [Elms].
31 // [Asm] is not considered for uniqueness.
32 UniqueArgs []argData
33 // All possible operand combinations are aggregated here.
34 // They are unique with regard to the list of [Args].
35 UniqueOpCombs []opCombData
36 Constants []constantData
37 }
38
39 type instsByName struct {
40 Name string
41 Insts []instData // All these insts share the same GoOp code.
42 }
43
44 type constantData struct {
45 ConstName string
46 BinName string
47 }
48
49 type funcData struct {
50 Comments []string
51 Body string
52 Name string
53 }
54
55 type instData struct {
56 GoOp string
57 FixedBits string
58 Args []argData
59 Ops opCombData
60 Asm string
61 highFeat int
62 }
63
64 type argData struct {
65 // The global variable name of this arg pattern.
66 Name string
67 Class string
68 Asm string
69 Elms []elmData
70 }
71
72 type opCombData struct {
73 Name string
74 OpAsms string
75 ArgNames []string
76 BetterName string
77 }
78
79 type elmData struct {
80 FuncName string
81 EncName string
82 }
83
84 type e2eData struct {
85 GoOp string
86 Asm string
87 Binary string
88 // highFeat is the feature order (see [operandTypeOrders]), it's used to
89 // sort the e2e test data.
90 highFeat int
91 }
92
93 const genTmpl = `// Code generated by 'instgen -o=$GOROOT # from go install golang.org/x/arch/arm64/instgen@latest'. DO NOT EDIT.
94
95 // The following constants are generated from the XML specification.
96
97 package arm64
98
99 // insts are grouped by [goOp].
100 var insts = [][]instEncoder{
101 {{- range .InstsByName}}
102 // {{.Name}}
103 {
104 {{- range .Insts}}
105 // {{.Asm}} {{.Ops.OpAsms}}
106 {
107 goOp: {{.GoOp}},
108 fixedBits: {{.FixedBits}},
109 args: {{.Ops.BetterName}},
110 },
111 {{- end}}
112 },
113 {{- end}}
114 }
115
116 {{range .UniqueArgs}}
117 var {{.Name}} = operand{
118 class: {{.Class}}, elemEncoders: []elemEncoder{
119 {{- range .Elms}}
120 {{"{"}}{{.FuncName}}, {{.EncName}}{{"}"}},
121 {{- end}}
122 },
123 }
124 {{end}}
125
126 {{range .UniqueOpCombs}}
127 var {{.BetterName}} = []operand{
128 {{- range .ArgNames}}
129 {{.}},
130 {{- end}}
131 }
132 {{end}}
133 `
134
135 const encodingTmpl = `// Code generated by 'instgen -o=$GOROOT # from go install golang.org/x/arch/arm64/instgen@latest'.
136
137 package arm64
138
139 import "cmd/internal/obj"
140
141 // stripRawZ first checks if v is a raw register number(0 to 31).
142 // If v is not a raw Z register, it will check if it's a Z register in the ARM64 range:
143 // - if within the range, it returns true, and set v to be the raw Z register.
144 // - otherwise it returns false
145 // If v is a raw register number, it returns true and leaves v unchanged.
146 func stripRawZ(v *uint32) (bool) {
147 if *v >= obj.RBaseARM64 {
148 if !(*v >= REG_Z0 && *v <= REG_Z31) && !(*v >= REG_ZARNG && *v < REG_ZARNGELEM) {
149 return false
150 }
151 }
152 *v = *v & 31
153 return true
154 }
155
156 // checkIsR checks if v is a scalar register:
157 // - if v is a raw register number or is within the ARM64 scalar register range,
158 // it returns true.
159 // - otherwise it returns false.
160 func checkIsR(v uint32) (bool) {
161 if v > REG_R31 && v != REG_RSP {
162 return false
163 }
164 return true
165 }
166
167 const (
168 enc_NIL component = iota
169 {{- range .Constants}}
170 {{.ConstName}}
171 {{- end}}
172 )
173 {{- range .EncodingFuncs}}
174 // {{.Name}} is the implementation of the following encoding logic:
175 {{- range .Comments}}
176 // {{.}}
177 {{- end}}
178 func {{.Name}}(v uint32) (uint32, bool) {
179 {{.Body}}
180 }
181 {{- end}}
182 `
183
184 const goopsTmpl = `// Code generated by 'instgen -o=$GOROOT # from go install golang.org/x/arch/arm64/instgen@latest'. DO NOT EDIT.
185
186 package arm64
187
188 import "cmd/internal/obj"
189
190 const (
191 {{- range .}}
192 {{.}}
193 {{- end}}
194 ALAST
195 )
196 `
197
198 const anamesTmpl = `// Code generated by 'instgen -o=$GOROOT # from go install golang.org/x/arch/arm64/instgen@latest'. DO NOT EDIT.
199
200 package arm64
201
202 var sveAnames = []string{
203 "SVESTART",
204 {{- range .}}
205 "{{.}}",
206 {{- end}}
207 "LAST",
208 }
209
210 func init() {
211 Anames = append(Anames, sveAnames...)
212 }
213 `
214
215 const e2edataTmpl = `// Code generated by 'instgen -o=$GOROOT # from go install golang.org/x/arch/arm64/instgen@latest'. DO NOT EDIT.
216
217 #include "../../../../../runtime/textflag.h"
218
219 TEXT asmtest(SB),DUPOK|NOSPLIT,$-8
220 {{- range .}}
221 {{.Asm}}{{.Binary}}
222 {{- end}}
223 RET
224 `
225
226 var operandTypeOrders = map[string]int{
227 "AC_ARNG": 0,
228 "AC_PREG": 0,
229 "AC_PREGZ": 0,
230 "AC_PREGZM": 0,
231 "AC_ZREG": 0,
232 "AC_SPZGREG": 1,
233 "AC_VREG": 1,
234 "AC_ARNGIDX": 2,
235 "AC_ZREGIDX": 2,
236 "AC_PREGIDX": 2,
237 "AC_IMM": 3,
238 "AC_REGLIST1": 4,
239 "AC_REGLIST2": 4,
240 "AC_REGLIST3": 4,
241 "AC_REGLIST4": 4,
242 "AC_MEMEXT": 5,
243 "AC_SPECIAL": 6,
244 "AC_MEMOFF": 7,
245 "AC_MEMOFFMULVL": 8,
246 "AC_REGLIST_RANGE": 9,
247 }
248
249 func readExistingGoOps(aoutPath string) map[string]bool {
250 ops := make(map[string]bool)
251 content, err := os.ReadFile(aoutPath)
252 if err != nil {
253 return ops
254 }
255 re := regexp.MustCompile(`\b(A[A-Z0-9_]+)\b`)
256 matches := re.FindAllStringSubmatch(string(content), -1)
257 for _, m := range matches {
258 ops[m[1]] = true
259 }
260 return ops
261 }
262
263 func convertToGoID(v string) string {
264 v = strings.ReplaceAll(v, " :: ", "_")
265 v = strings.ReplaceAll(v, "(", "")
266 v = strings.ReplaceAll(v, ")", "")
267 v = strings.ReplaceAll(v, "[", "")
268 v = strings.ReplaceAll(v, "]", "")
269 v = strings.ReplaceAll(v, "#", "c")
270 v = strings.ReplaceAll(v, "-", "_")
271 return v
272 }
273
274 // formatAndFlush executes the given template and writes it to the given file,
275 // the go file is formatted using gofmt.
276 // If outputDir is empty, it does nothing.
277 func formatAndFlush(outputDir string, filename string, data any, tmpl string) {
278 if outputDir == "" {
279 return
280 }
281 t, err := template.New("template").Parse(tmpl)
282 if err != nil {
283 log.Fatalf("Failed to parse template %s: %v", filename, err)
284 }
285
286 var buf bytes.Buffer
287 if err := t.Execute(&buf, data); err != nil {
288 log.Fatalf("Failed to execute template %s: %v", filename, err)
289 }
290
291 formatted := buf.Bytes()
292 if strings.HasSuffix(filename, ".go") {
293 formatted, err = format.Source(formatted)
294 if err != nil {
295 log.Printf("Failed to format generated source: %v", err)
296 formatted = buf.Bytes()
297 }
298 }
299
300 outputPath := filepath.Join(outputDir, filename)
301 if err := os.WriteFile(outputPath, formatted, 0644); err != nil {
302 log.Fatalf("Failed to write output file %s: %v", outputPath, err)
303 }
304 log.Printf("Generated %s", outputPath)
305 }
306
307 // Generate generates the Go code for the instruction table.
308 func Generate(insts []*xmlspec.InstructionParsed, outputDir string, genE2E bool) {
309 // process encodingImpls, field them to make the comparison easier
310 for k, v := range encodingImpls {
311 uniformed := strings.Join(strings.Fields(k), " ")
312 encodingImpls[uniformed] = v
313 }
314
315 // Collect constants
316 encodingFuncs := make(map[string]int) // Map textExp to index
317 encodingFuncComments := make(map[string][]string)
318
319 // Pre-populate EncodingFuncs
320 sortedEncodings := make([]string, 0, len(xmlspec.AllEncodingDescs))
321 for k := range xmlspec.AllEncodingDescs {
322 sortedEncodings = append(sortedEncodings, k)
323 }
324 sort.Strings(sortedEncodings)
325
326 // Create map to store names early
327 funcNames := make(map[int]string)
328 encNames := make(map[int]string)
329
330 for i, k := range sortedEncodings {
331 encodingFuncs[k] = i + 1
332 encodingFuncComments[k] = strings.Split(k, "\n")
333
334 kUniformed := strings.Join(strings.Fields(k), " ")
335 if b, ok := encodingImpls[kUniformed]; ok {
336 funcNames[i+1] = b.name
337 encNames[i+1] = b.encodedIn
338 } else {
339 funcNames[i+1] = fmt.Sprintf("encodeGen%d", i+1)
340 }
341 }
342
343 // Collect A64Types and A64Feats, and Insts
344 var instsData []instData
345 newGoOps := make(map[string]bool)
346 existingGoOps := readExistingGoOps(filepath.Join(outputDir, "a.out.go"))
347
348 usedFuncIndices := make(map[int]bool)
349
350 e2eTestData := make([]e2eData, 0)
351 e2eErrorData := make([]e2eData, 0)
352 for _, inst := range insts {
353 if inst == nil {
354 continue
355 }
356 isAlias := false
357 for _, doc := range inst.DocVars {
358 if doc.Key == "alias_mnemonic" {
359 isAlias = true
360 break
361 }
362 }
363 if isAlias {
364 // Alias instructions are not fully specified in their own XML files,
365 // skip them.
366 continue
367 }
368
369 for _, iclass := range inst.Classes.Iclass {
370 if !iclass.RegDiagram.Parsed {
371 continue
372 }
373
374 for _, encodingRaw := range iclass.Encodings {
375 if !encodingRaw.Parsed {
376 continue
377 }
378
379 if encodingRaw.Alias {
380 // Alias encodings are not fully specified in their own section,
381 // skip them.
382 continue
383 }
384
385 encodings := xmlspec.SplitInstByRegWidth(encodingRaw)
386 for _, encoding := range encodings {
387 // Filtering logic:
388 // 1. If 0 operands (len <= 1), keep with warning.
389 // 2. If > 0 operands, ALL must be in operandTypeOrders.
390 keep := true
391 if len(encoding.Operands) <= 1 {
392 log.Printf("Warning: instruction with 0 operands kept: %s", encoding.Asm)
393 } else {
394 for _, op := range encoding.Operands[1:] {
395 if _, ok := operandTypeOrders[op.Typ]; !ok {
396 keep = false
397 break
398 }
399 }
400 }
401
402 if !keep {
403 continue
404 }
405
406 if !existingGoOps[encoding.GoOp] {
407 newGoOps[encoding.GoOp] = true
408 } else {
409 log.Printf("Warning: goOp %s already exists in a.out.go", encoding.GoOp)
410 }
411
412 validData, errData := constructInstance(&encoding)
413 e2eTestData = append(e2eTestData, *validData)
414 if errData != nil {
415 e2eErrorData = append(e2eErrorData, *errData)
416 }
417 highFeat := 0
418 for _, op := range encoding.Operands[1:] {
419 highFeat = max(highFeat, operandTypeOrders[op.Typ])
420 }
421 instData := instData{
422 Asm: encoding.GoOp[1:],
423 GoOp: encoding.GoOp,
424 FixedBits: fmt.Sprintf("%#x", encoding.Binary),
425 highFeat: highFeat,
426 }
427
428 for _, op := range encoding.Operands[1:] {
429 arg := argData{
430 Asm: op.Name,
431 Class: op.Typ,
432 }
433 if len(op.Elems) > 0 {
434 for _, elm := range op.Elems {
435 idx, ok := encodingFuncs[elm.TextExpWithRanges]
436 if !ok {
437 log.Printf("Warning: encoding func not found for %s", elm.TextExpWithRanges)
438 continue
439 }
440
441 enc := encNames[idx]
442 if enc == "" {
443 // Fallback
444 sym := xmlspec.EncodingDescsToEncodedIn[elm.TextExpWithRanges]
445 // We actually do not have encodedInMap here yet, so just prefix "enc_"
446 if sym == "" || sym == "nil" {
447 enc = "enc_NIL"
448 } else {
449 enc = fmt.Sprintf("enc_%s", convertToGoID(sym))
450 }
451 }
452 arg.Elms = append(arg.Elms, elmData{
453 FuncName: funcNames[idx],
454 EncName: enc,
455 })
456 usedFuncIndices[idx] = true
457 }
458 }
459 instData.Args = append(instData.Args, arg)
460 }
461 instsData = append(instsData, instData)
462 }
463 }
464 }
465 }
466
467 // Prepare template data
468 data := tmplData{
469 Insts: instsData,
470 }
471
472 // Collect constants
473 encodedInMap := make(map[string]string) // raw string -> constant name
474 var uniqueEncodedIn []string
475
476 // Collect ALL constants from global map to ensure invariant names (enc_X)
477 for _, v := range xmlspec.EncodingDescsToEncodedIn {
478 if v == "" || v == "nil" {
479 continue
480 }
481 if _, ok := encodedInMap[v]; !ok {
482 encodedInMap[v] = ""
483 uniqueEncodedIn = append(uniqueEncodedIn, v)
484 }
485 }
486 sort.Strings(uniqueEncodedIn)
487
488 // Identify used constants
489 neededEncodedIn := make(map[string]bool)
490 for k, idx := range encodingFuncs {
491 if usedFuncIndices[idx] {
492 if v := xmlspec.EncodingDescsToEncodedIn[k]; v != "" && v != "nil" {
493 neededEncodedIn[v] = true
494 }
495 }
496 }
497
498 var constants []constantData
499 for _, v := range uniqueEncodedIn {
500 name := fmt.Sprintf("enc_%s", convertToGoID(v))
501 encodedInMap[v] = name
502 // Only add to output if used
503 if neededEncodedIn[v] {
504 constants = append(constants, constantData{
505 ConstName: name,
506 BinName: v,
507 })
508 }
509 }
510 for i, k := range sortedEncodings {
511 if !usedFuncIndices[i+1] {
512 continue
513 }
514 sym := xmlspec.EncodingDescsToEncodedIn[k]
515 if name, ok := encodedInMap[sym]; ok {
516 sym = name
517 } else {
518 sym = "enc_NIL"
519 }
520 var body string
521 kUniformed := strings.Join(strings.Fields(k), " ")
522 var name string
523 if b, ok := encodingImpls[kUniformed]; ok {
524 body = b.body
525 name = b.name
526 } else {
527 log.Printf("Warning: encoding func not found for\n%s\n", k)
528 body = defaultEncodingTmpl
529 name = fmt.Sprintf("encodeGen%d", i+1)
530 }
531 data.EncodingFuncs = append(data.EncodingFuncs, funcData{
532 Comments: encodingFuncComments[k],
533 Body: body,
534 Name: name,
535 })
536 }
537 data.Constants = constants
538
539 // Now aggregate all arg patterns to unique globals.
540 argMap := make(map[string]bool)
541 var uniqueArgs []argData
542 for i, inst := range instsData {
543 for j, arg := range inst.Args {
544 name := "a_" + arg.Class[3:] // remove AC_ prefix
545 for _, elm := range arg.Elms {
546 name += "_" + strings.TrimPrefix(elm.FuncName, "encode")
547 }
548 instsData[i].Args[j].Name = name
549 arg.Name = name
550 if !argMap[name] {
551 argMap[name] = true
552 uniqueArgs = append(uniqueArgs, arg)
553 }
554 }
555 }
556 data.UniqueArgs = uniqueArgs
557 // Now aggregate all arg lists to unique globals.
558 opCombMap := make(map[string]opCombData)
559 var uniqueOpCombs []opCombData
560 for i, inst := range instsData {
561 name := "oc"
562 argNames := []string{}
563 argAsms := []string{}
564 for _, arg := range inst.Args {
565 name += "_" + arg.Name[2:] // remove a_ prefix
566 for _, elm := range arg.Elms {
567 name += "_" + strings.TrimPrefix(elm.FuncName, "encode")
568 }
569 argNames = append(argNames, arg.Name)
570 argAsms = append(argAsms, arg.Asm)
571 }
572 if ops, ok := opCombMap[name]; ok {
573 instsData[i].Ops = ops
574 } else {
575 ops := opCombData{
576 Name: name,
577 ArgNames: argNames,
578 OpAsms: strings.Join(argAsms, ", "),
579 }
580 opCombMap[name] = ops
581 uniqueOpCombs = append(uniqueOpCombs, ops)
582 instsData[i].Ops = ops
583 }
584 }
585 data.UniqueOpCombs = uniqueOpCombs
586
587 // Figure out better names for the slices of asm operand
588 // checkers/encoders.
589
590 // Goal is to replace an "ugly name" with a sanitized
591 // version of the instruction operand types; however, sometimes
592 // there is more than one ugly name mapping to the same
593 // nominal operands (an ugly name corresponds to an encoding).
594 // Detect this, and for those cases where there's more than
595 // one ugly name for the same operands, append a sequence
596 // number.
597 operandsToName := func(s string) string {
598 s = strings.Replace(s, "<", "", -1)
599 s = strings.Replace(s, ">", "", -1)
600 s = strings.Replace(s, "/", "", -1)
601 s = strings.Replace(s, ",", "_", -1)
602 s = strings.Replace(s, ".", "_", -1)
603 s = strings.Replace(s, " ", "_", -1)
604 s = strings.Replace(s, "|", "", -1)
605 s = strings.Replace(s, "[", "_", -1)
606 s = strings.Replace(s, "]", "_", -1)
607 s = strings.Replace(s, "{", "", -1)
608 s = strings.Replace(s, "}", "", -1)
609 s = strings.Replace(s, "#", "c", -1)
610 s = strings.Replace(s, "-", "_", -1)
611 s = strings.TrimPrefix(s, "_")
612 return s
613 }
614
615 ot2ugly2Count := make(map[string]map[string]int)
616 otSlice := []string{} // insertion order of operand types
617 uglyInsertionOrder := make(map[string]int)
618
619 for _, inst := range data.Insts {
620 uglyName := inst.Ops.Name
621 if x := uglyInsertionOrder[uglyName]; x == 0 {
622 uglyInsertionOrder[uglyName] = 1 + len(uglyInsertionOrder)
623 }
624 operandTypes := inst.Ops.OpAsms
625 if ot2ugly2Count[operandTypes] == nil {
626 otSlice = append(otSlice, operandTypes)
627 ot2ugly2Count[operandTypes] = make(map[string]int)
628 }
629 // keep track of how many instructions with this operand type
630 // sequence use the exact same encoding.
631 ot2ugly2Count[operandTypes][uglyName] += 1
632 }
633
634 // Map from ugly name to better name
635 ugly2better := make(map[string]string)
636 // There is sometimes only one ugly name for multiple operand type sequences
637 // that have different semantics, we need to assign them version numbers.
638 usedNames := make(map[string]bool)
639
640 for _, x := range otSlice {
641 // Get a canonical order of ugly names
642 var uglies []string
643 u2c := ot2ugly2Count[x]
644 for c := range u2c {
645 uglies = append(uglies, c)
646 }
647
648 baseName := operandsToName(x)
649
650 if len(uglies) > 1 {
651 // if there is more than one, sort into decreasing
652 // frequency order, then sort by insertion order.
653 sort.Slice(uglies, func(i, j int) bool {
654 if c := u2c[uglies[j]] - u2c[uglies[i]]; c != 0 {
655 return c < 0
656 }
657 return uglyInsertionOrder[uglies[i]] < uglyInsertionOrder[uglies[j]]
658 })
659 for j, u := range uglies {
660 name := fmt.Sprintf("%s__%d", baseName, j+1)
661 if usedNames[name] {
662 v := 2
663 for usedNames[fmt.Sprintf("%s_V%d__%d", baseName, v, j+1)] {
664 v++
665 }
666 name = fmt.Sprintf("%s_V%d__%d", baseName, v, j+1)
667 }
668 ugly2better[u] = name
669 usedNames[name] = true
670 }
671 } else {
672 // if only one, do not add a __N suffix.
673 name := baseName
674 if usedNames[name] {
675 v := 2
676 for usedNames[fmt.Sprintf("%s_V%d", baseName, v)] {
677 v++
678 }
679 name = fmt.Sprintf("%s_V%d", baseName, v)
680 }
681 ugly2better[uglies[0]] = name
682 usedNames[name] = true
683 }
684 }
685
686 // Apply better name translations.
687 for i, inst := range data.Insts {
688 if arg := ugly2better[inst.Ops.Name]; arg != "" {
689 data.Insts[i].Ops.BetterName = arg
690 } else {
691 data.Insts[i].Ops.BetterName = inst.Ops.Name
692 }
693 }
694
695 for i, uoc := range data.UniqueOpCombs {
696 if arg := ugly2better[uoc.Name]; arg != "" {
697 data.UniqueOpCombs[i].BetterName = arg
698 } else {
699 data.UniqueOpCombs[i].BetterName = uoc.Name
700 }
701 }
702
703 // Put these two slices into sensible orders.
704 sort.Slice(data.UniqueOpCombs, func(i, j int) bool {
705 return data.UniqueOpCombs[i].BetterName < data.UniqueOpCombs[j].BetterName
706 })
707
708 sort.Slice(data.UniqueArgs, func(i, j int) bool {
709 return data.UniqueArgs[i].Name < data.UniqueArgs[j].Name
710 })
711
712 // Group instructions by name
713 // Also sort them by their Go mnemonic, stably.
714 slices.SortFunc(data.Insts, func(i, j instData) int {
715 if c := strings.Compare(i.GoOp, j.GoOp); c != 0 {
716 return c
717 }
718 if i.highFeat != j.highFeat {
719 return i.highFeat - j.highFeat
720 }
721 if c := strings.Compare(i.Ops.BetterName, j.Ops.BetterName); c != 0 {
722 return c
723 }
724 if c := strings.Compare(i.Ops.OpAsms, j.Ops.OpAsms); c != 0 {
725 return c
726 }
727 return strings.Compare(i.FixedBits, j.FixedBits)
728 })
729 ibn := []instsByName{}
730 prevGoOp := ""
731 for _, inst := range data.Insts {
732 if inst.GoOp != prevGoOp {
733 ibn = append(ibn, instsByName{
734 Name: inst.GoOp[1:],
735 Insts: []instData{},
736 })
737 prevGoOp = inst.GoOp
738 }
739 ibn[len(ibn)-1].Insts = append(ibn[len(ibn)-1].Insts, inst)
740 }
741 data.InstsByName = ibn
742
743 // Generate inst_gen.go
744 formatAndFlush(outputDir, "src/cmd/internal/obj/arm64/inst_gen.go", data, genTmpl)
745
746 // Generate encoding_gen.go
747 formatAndFlush(outputDir, "src/cmd/internal/obj/arm64/encoding_gen.go", data, encodingTmpl)
748
749 // Generate goops_gen.go
750 var sortedNewGoOps []string
751 for k := range newGoOps {
752 sortedNewGoOps = append(sortedNewGoOps, k)
753 }
754 sort.Strings(sortedNewGoOps)
755 goopsPrefix := " obj.As = ASVESTART + 1 + iota"
756 sortedNewGoOps[0] += goopsPrefix
757 formatAndFlush(outputDir, "src/cmd/internal/obj/arm64/goops_gen.go", sortedNewGoOps, goopsTmpl)
758
759 // Generate anames_gen.go
760 for i := range sortedNewGoOps {
761 sortedNewGoOps[i] = strings.TrimSuffix(sortedNewGoOps[i], goopsPrefix)
762 sortedNewGoOps[i] = strings.TrimPrefix(sortedNewGoOps[i], "A")
763 }
764 formatAndFlush(outputDir, "src/cmd/internal/obj/arm64/anames_gen.go", sortedNewGoOps, anamesTmpl)
765
766 if genE2E {
767 slices.SortStableFunc(e2eTestData, func(i, j e2eData) int {
768 if i.highFeat != j.highFeat {
769 return i.highFeat - j.highFeat
770 }
771 return strings.Compare(i.GoOp, j.GoOp)
772 })
773 slices.SortStableFunc(e2eErrorData, func(i, j e2eData) int {
774 if i.highFeat != j.highFeat {
775 return i.highFeat - j.highFeat
776 }
777 return strings.Compare(i.GoOp, j.GoOp)
778 })
779 // Generate arm64sveenc.s
780 formatAndFlush(outputDir, "src/cmd/asm/internal/asm/testdata/arm64sveenc.s", e2eTestData, e2edataTmpl)
781 // Generate arm64sveerror.s
782 formatAndFlush(outputDir, "src/cmd/asm/internal/asm/testdata/arm64sveerror.s", e2eErrorData, e2edataTmpl)
783 }
784 }
785
786 // Mappings for operand patterns to concrete registers
787 var regMap = map[string]string{
788 "Zd": "Z",
789 "Zda": "Z",
790 "Zdn": "Z",
791 "Zn": "Z",
792 "Zm": "Z",
793 "Za": "Z",
794 "Zk": "Z",
795 "Zt": "Z",
796
797 "Pd": "P",
798 "Pdn": "P",
799 "Pdm": "P",
800 "Pn": "P",
801 "Pm": "P",
802 "Pg": "P",
803 "Pt": "P",
804 "PNd": "PN",
805 "PNn": "PN",
806 "PNg": "PN",
807 "Pv": "P",
808
809 "Vd": "V",
810 "Vn": "V",
811 "Vm": "V",
812 }
813
814 // Arrangement variables, also includes predication cases.
815 var arrMap = map[string]bool{
816 "Tb": true, // arrangement variables
817 "T": true, // arrangement variables
818 "ZM": true, // predication variables
819 }
820
821 // Z, P reg arrangements, used for variable mutation.
822 var sveArr = []string{"B", "H", "S", "D", "Q"}
823 var svePred = []string{"M", "Z"}
824
825 // V reg arrangements, used for variable mutation.
826 var neonArrGNU = []string{"16B", "1D", "4H", "8H", "2S", "4S", "2D", "1Q"}
827 var neonArrGo = []string{"B16", "D1", "H4", "H8", "S2", "S4", "D2", "Q1"}
828
829 // assembleGNU assembles the given assembly string using GNU toolchain and returns the hex.
830 func assembleGNU(s string) (string, error) {
831 // Create temp file
832 tmpName := "temp_probe.s"
833 if err := os.WriteFile(tmpName, []byte(s+"\n"), 0644); err != nil {
834 return "", err
835 }
836 defer os.Remove(tmpName)
837
838 // Run as
839 cmd := exec.Command("aarch64-linux-gnu-as", "-march=all", tmpName, "-o", "temp_probe.o")
840 if out, err := cmd.CombinedOutput(); err != nil {
841 return "", fmt.Errorf("as failed: %s", out)
842 }
843 defer exec.Command("rm", "temp_probe.o").Run()
844
845 // Run objdump
846 cmd = exec.Command("aarch64-linux-gnu-objdump", "-d", "temp_probe.o")
847 out, err := cmd.CombinedOutput()
848 if err != nil {
849 return "", err
850 }
851
852 // Parse output
853 lines := strings.Split(string(out), "\n")
854 for _, l := range lines {
855 l = strings.TrimSpace(l)
856 // The first text line contains the hex.
857 if strings.Contains(l, "0:") {
858 parts := strings.Fields(l)
859 // parts[0] is offset:, parts[1] is hex
860 if len(parts) >= 2 {
861 if len(parts[1]) == 8 {
862 return parts[1], nil
863 }
864 }
865 }
866 }
867 return "", fmt.Errorf("no hex found")
868 }
869
870 // reverseHex reverses the byte order of a hex string.
871 // this is required for Go's e2e test.
872 func reverseHex(h string) string {
873 if len(h) != 8 {
874 return h
875 }
876 return h[6:8] + h[4:6] + h[2:4] + h[0:2]
877 }
878
879 var prefetchOps = []string{
880 "PLDL1KEEP", "PLDL1STRM", "PLDL2KEEP", "PLDL2STRM",
881 "PLDL3KEEP", "PLDL3STRM", "PSTL1KEEP", "PSTL1STRM",
882 "PSTL2KEEP", "PSTL2STRM", "PSTL3KEEP", "PSTL3STRM",
883 }
884 var vlOps = []string{"VLx2", "VLx4"}
885
886 // constructInstance takes an [Encoding] and tries to generate a
887 // valid Go assembly instance of it and returns the e2eData for this instance.
888 // The construction is deterministic.
889 //
890 // This function requires the availablity of the GNU toolchain.
891 // Special instructions are elided, they are documented in the comments.
892 // Technically we can skip them early before we do the construction, but
893 // we kept them after the construction for future verification.
894 func constructInstance(enc *xmlspec.EncodingParsed) (*e2eData, *e2eData) {
895 var name string
896 // Try to construct two assembly, one in Go the other in GNU.
897 // The trial succeeds once the GNU one is accepted by the GNU toolchain.
898 rng := rand.New(rand.NewPCG(uint64(42), uint64(1024)))
899 // Try 100 times until we find one that's accepted by the GNU toolchain.
900 // constructInstance does not understand the encoding level constraint, so
901 // it just try until a valid one is found.
902 var highFeat int
903 var gnuErr error
904 var errCase *e2eData
905 var validCase *e2eData
906 for range 100 {
907 goAsmOps := make([]string, 0)
908 gnuAsmOps := make([]string, 0)
909 // Useful for pruning AC_ARNG, AC_PREG, AC_PREGZM, AC_ZREG.
910 // ABS <Zd>.<T>, <Pg>/Z, <Zn>.<T>
911 // the 2 instances of <T> should be exactly the same...
912 // Key is the random number selected.
913 regCache := map[string]int{}
914 arrCache := map[string]int{}
915 immCache := map[string]int{}
916 cachedOrNew := func(cache map[string]int, key string, n int) int {
917 if v, ok := cache[key]; ok {
918 if errCase != nil || len(enc.Operands) == 0 {
919 // Give the error case a chance to be triggered.
920 return v
921 }
922 }
923 v := rng.IntN(n)
924 cache[key] = v
925 return v
926 }
927 for i, op := range enc.Operands {
928 if i == 0 {
929 // First operand is the instruction name.
930 name = op.Name
931 continue
932 }
933 opName := op.Name
934 if _, ok := operandTypeOrders[op.Typ]; !ok {
935 log.Fatalf("Unsupported operand type in constructInstance: %s, enc: %s", op.Typ, enc.String())
936 }
937 highFeat = max(highFeat, operandTypeOrders[op.Typ])
938 generateSVERegOp := func(opName string) (string, string, string, int, string) {
939 var parts []string
940 var isPred bool
941 if strings.Contains(opName, ".") {
942 parts = strings.Split(opName, ".")
943 } else {
944 parts = strings.Split(opName, "/")
945 isPred = true
946 }
947 if len(parts) == 0 {
948 log.Fatalf("Unrecognized operand: %s", opName)
949 }
950 regName := strings.TrimSuffix(strings.TrimPrefix(parts[0], "<"), ">")
951 var arrName string
952 if len(parts) > 1 {
953 arrName = strings.TrimSuffix(strings.TrimPrefix(parts[1], "<"), ">")
954 }
955 resolvedArr := arrName
956 regNameSanitized := strings.TrimRight(regName, "0123456789")
957 reg := regMap[regNameSanitized]
958 if reg == "" {
959 reg = regMap[regName]
960 }
961 var goAsmOp, gnuAsmOp string
962 var regIdx int
963 if arrMap[arrName] || errCase == nil {
964 // Give error case a random mutation to trigger an error.
965 // Variables, needs mutation
966 switch reg {
967 case "Z":
968 regIdx = cachedOrNew(regCache, regName, 32)
969 arrIdx := cachedOrNew(arrCache, arrName, len(sveArr))
970 resolvedArr = sveArr[arrIdx]
971 goAsmOp = fmt.Sprintf("Z%d.%s", regIdx, resolvedArr)
972 gnuAsmOp = goAsmOp
973 case "P", "PN":
974 regIdx = cachedOrNew(regCache, regName, 15)
975 if isPred {
976 arrIdx := cachedOrNew(arrCache, arrName, len(svePred))
977 resolvedArr = svePred[arrIdx]
978 gnuAsmOp = fmt.Sprintf("%s%d/%s", reg, regIdx, resolvedArr)
979 goAsmOp = fmt.Sprintf("%s%d.%s", reg, regIdx, resolvedArr)
980 } else {
981 arrIdx := cachedOrNew(arrCache, arrName, len(sveArr))
982 resolvedArr = sveArr[arrIdx]
983 goAsmOp = fmt.Sprintf("%s%d.%s", reg, regIdx, resolvedArr)
984 gnuAsmOp = goAsmOp
985 }
986 case "V":
987 regIdx = cachedOrNew(regCache, regName, 32)
988 arrIdx := cachedOrNew(arrCache, arrName, len(neonArrGNU))
989 resolvedArr = neonArrGNU[arrIdx]
990 gnuAsmOp = fmt.Sprintf("V%d.%s", regIdx, neonArrGNU[arrIdx])
991 goAsmOp = fmt.Sprintf("V%d.%s", regIdx, neonArrGo[arrIdx])
992 }
993 } else {
994 // Fixed arrangement or predications
995 var dotArr string
996 if arrName != "" {
997 dotArr = "." + arrName
998 }
999 switch reg {
1000 case "Z":
1001 regIdx = cachedOrNew(regCache, regName, 32)
1002 goAsmOp = fmt.Sprintf("Z%d%s", regIdx, dotArr)
1003 gnuAsmOp = goAsmOp
1004 case "P", "PN":
1005 regIdx = cachedOrNew(regCache, regName, 15)
1006 if isPred {
1007 var arrNameGNU string
1008 if arrName != "" {
1009 arrNameGNU = "/" + arrName
1010 }
1011 gnuAsmOp = fmt.Sprintf("%s%d%s", reg, regIdx, arrNameGNU)
1012 goAsmOp = fmt.Sprintf("%s%d%s", reg, regIdx, dotArr)
1013 } else {
1014 goAsmOp = fmt.Sprintf("%s%d%s", reg, regIdx, dotArr)
1015 gnuAsmOp = goAsmOp
1016 }
1017 case "V":
1018 log.Fatalf("Unexpected V with fixed arrangement: %s", opName)
1019 }
1020 }
1021 return goAsmOp, gnuAsmOp, reg, regIdx, resolvedArr
1022 }
1023
1024 if op.Typ == "AC_ARNG" || op.Typ == "AC_PREG" || op.Typ == "AC_PREGZM" || op.Typ == "AC_ZREG" {
1025 goAsmOp, gnuAsmOp, _, _, _ := generateSVERegOp(opName)
1026 gnuAsmOps = append([]string{gnuAsmOp}, gnuAsmOps...)
1027 goAsmOps = append(goAsmOps, goAsmOp)
1028 } else if op.Typ == "AC_ARNGIDX" || op.Typ == "AC_ZREGIDX" || op.Typ == "AC_PREGIDX" {
1029 // Operands that takes SVE/SIMD registers and arrangement with index.
1030 // reg.T[index]
1031 var regPrefix string
1032 var regName string
1033 var arrangement string
1034 index := rng.IntN(4)
1035
1036 if op.Typ == "AC_ARNGIDX" {
1037 parts := strings.Split(opName, ".")
1038 regName = strings.TrimSuffix(strings.TrimPrefix(parts[0], "<"), ">")
1039 regPrefix = regMap[regName]
1040 if regPrefix == "" {
1041 log.Fatalf("Unknown register prefix: %s", regName)
1042 }
1043
1044 parts2 := strings.Split(parts[1], "[")
1045 arrangement = strings.TrimSuffix(strings.TrimPrefix(parts2[0], "<"), ">")
1046 } else if op.Typ == "AC_ZREGIDX" || op.Typ == "AC_PREGIDX" {
1047 re := regexp.MustCompile(`<([A-Z][A-Za-z0-9]*)>`)
1048 matches := re.FindStringSubmatch(opName)
1049 if len(matches) > 1 {
1050 regName = matches[1]
1051 regPrefix = regMap[regName]
1052 if regPrefix == "" {
1053 log.Fatalf("Unknown register: %s", regName)
1054 }
1055 } else {
1056 log.Fatalf("Unknown AC_[PZ]REGIDX: %s", opName)
1057 }
1058 }
1059
1060 var goAsmOp, gnuAsmOp string
1061 limit := 32
1062 if regPrefix == "P" || regPrefix == "PN" {
1063 limit = 16
1064 }
1065 regIdx := cachedOrNew(regCache, regName, limit)
1066 if regPrefix == "V" {
1067 log.Fatalf("Unexpected V with index: %s", opName)
1068 }
1069
1070 if arrangement != "" {
1071 if arrMap[arrangement] {
1072 arrIdx := cachedOrNew(arrCache, arrangement, len(sveArr))
1073 goAsmOp = fmt.Sprintf("%s%d.%s[%d]", regPrefix, regIdx, sveArr[arrIdx], index)
1074 gnuAsmOp = goAsmOp
1075 } else {
1076 // Fixed arrangement
1077 goAsmOp = fmt.Sprintf("%s%d.%s[%d]", regPrefix, regIdx, arrangement, index)
1078 gnuAsmOp = goAsmOp
1079 }
1080 } else {
1081 goAsmOp = fmt.Sprintf("%s%d[%d]", regPrefix, regIdx, index)
1082 gnuAsmOp = goAsmOp
1083 }
1084 gnuAsmOps = append([]string{gnuAsmOp}, gnuAsmOps...)
1085 goAsmOps = append(goAsmOps, goAsmOp)
1086 } else if op.Typ == "AC_SPZGREG" || op.Typ == "AC_VREG" {
1087 // Operands that takes scalar or NEON vector registers.
1088 // There arn't that much of shapes, just enumerate them...
1089 var goPrefix string
1090 switch op.Typ {
1091 case "AC_SPZGREG":
1092 goPrefix = "R"
1093 case "AC_VREG":
1094 goPrefix = "V"
1095 }
1096 var gnuPrefix string
1097 switch op.Typ {
1098 case "AC_SPZGREG":
1099 if strings.Contains(op.Name, "W") {
1100 gnuPrefix = "W"
1101 } else if strings.Contains(op.Name, "<R>") {
1102 // We know the parser will append the width to the GoOp as a suffix.
1103 switch enc.GoOp[len(enc.GoOp)-1] {
1104 case 'W':
1105 gnuPrefix = "W"
1106 default:
1107 // X does not have a suffix, as we know from the parser rules.
1108 gnuPrefix = "X"
1109 }
1110 } else {
1111 gnuPrefix = "X"
1112 }
1113 case "AC_VREG":
1114 if strings.Contains(op.Name, "<V>") || strings.Contains(op.Name, "<Dd>") {
1115 // We know the parser will append the width to the GoOp as a suffix.
1116 // Also <Dd> literally means the width is D.
1117 suffix := enc.GoOp[len(enc.GoOp)-1]
1118 switch suffix {
1119 case 'B', 'H', 'S', 'D':
1120 gnuPrefix = string(suffix)
1121 default:
1122 log.Fatalf("Unrecognized SIMD vector width: %c, enc: %s", suffix, enc.String())
1123 }
1124 } else {
1125 gnuPrefix = "V"
1126 }
1127 }
1128 var goAsmOp, gnuAsmOp string
1129 switch op.Name {
1130 case "<R><n|SP>", "<Xd|SP>", "<Xn|SP>", "<R><d>", "<R><dn>", "<R><m>",
1131 "<R><n>", "<Wdn>", "<Xd>", "<Xdn>", "<Xm>", "<Xn>", "<Dd>", "<V><d>",
1132 "<V><dn>", "<V><m>", "<V><n>":
1133 // R32 is RSP
1134 regIdx := cachedOrNew(regCache, op.Name, 64)
1135 goAsmOp = fmt.Sprintf("%s%d", goPrefix, regIdx)
1136 gnuAsmOp = fmt.Sprintf("%s%d", gnuPrefix, regIdx)
1137 if regIdx >= 31 && regIdx < 48 {
1138 goAsmOp = "RSP"
1139 if gnuPrefix == "W" {
1140 gnuAsmOp = "WSP"
1141 } else {
1142 gnuAsmOp = "SP"
1143 }
1144 }
1145 if regIdx >= 56 {
1146 goAsmOp = "ZR"
1147 if gnuPrefix == "W" {
1148 gnuAsmOp = "WZR"
1149 } else if gnuPrefix == "X" {
1150 gnuAsmOp = "XZR"
1151 }
1152 }
1153 default:
1154 log.Fatalf("Unrecognized operand: %s", op.Name)
1155 }
1156 gnuAsmOps = append([]string{gnuAsmOp}, gnuAsmOps...)
1157 goAsmOps = append(goAsmOps, goAsmOp)
1158 } else if op.Typ == "AC_IMM" {
1159 var imm string
1160 var isFloat bool
1161 // Check if this is a float imm or an integer imm.
1162 if op.Name == "#0.0" {
1163 imm = "0.0"
1164 isFloat = true
1165 } else {
1166 for _, e := range op.Elems {
1167 if strings.Contains(e.TextExpWithRanges, "float") {
1168 isFloat = true
1169 break
1170 }
1171 }
1172 if isFloat {
1173 // Usually these floats are 0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5...
1174 imm = fmt.Sprintf("%.1f", float64(cachedOrNew(immCache, op.Name, 20))/5.0)
1175 } else {
1176 intImm := cachedOrNew(immCache, op.Name, 16)
1177 if intImm > 12 {
1178 // Some instructions likes 90, 270; let's generate them to make those instructions happy.
1179 imm = fmt.Sprintf("%d", (intImm-12)*90)
1180 } else {
1181 imm = fmt.Sprintf("%d", intImm)
1182 }
1183 }
1184 }
1185 if isFloat {
1186 goAsmOps = append(goAsmOps, fmt.Sprintf("$(%s)", imm))
1187 } else {
1188 goAsmOps = append(goAsmOps, fmt.Sprintf("$%s", imm))
1189 }
1190 gnuAsmOps = append([]string{fmt.Sprintf("#%s", imm)}, gnuAsmOps...)
1191 } else if op.Typ == "AC_SPECIAL" {
1192 var opStr string
1193 if op.Name == "<prfop>" {
1194 idx := cachedOrNew(immCache, op.Name, len(prefetchOps))
1195 opStr = prefetchOps[idx]
1196 } else if op.Name == "<vl>" {
1197 idx := cachedOrNew(immCache, op.Name, len(vlOps))
1198 opStr = vlOps[idx]
1199 } else {
1200 log.Fatalf("Unrecognized AC_SPECIAL operand: %s", op.Name)
1201 }
1202 goAsmOps = append(goAsmOps, opStr)
1203 gnuAsmOps = append([]string{opStr}, gnuAsmOps...)
1204 } else if op.Typ == "AC_REGLIST1" || op.Typ == "AC_REGLIST2" || op.Typ == "AC_REGLIST3" || op.Typ == "AC_REGLIST4" {
1205 // Register list, they must be contiguous modulo 32 (16 for P registers).
1206 // Only AC_REGLIST2 has a P register variant though.
1207 // { <Zn>.<T> }
1208 // { <Pd1>.<T>, <Pd2>.<T> }
1209 // { <Zn1>.B, <Zn2>.B }
1210 // { <Zt1>.B, <Zt2>.B, <Zt3>.B }
1211 // { <Zt1>.B, <Zt2>.B, <Zt3>.B, <Zt4>.B }
1212 // We can probably reuse the logic for these registers in AC_ARNG case.
1213 // In Go, the register list is wrapped around [], while in GNU it's wrapped around {}.
1214 nRegs := 1
1215 switch op.Typ {
1216 case "AC_REGLIST2":
1217 nRegs = 2
1218 case "AC_REGLIST3":
1219 nRegs = 3
1220 case "AC_REGLIST4":
1221 nRegs = 4
1222 }
1223
1224 // Extract the first operand inside the list.
1225 trimmedName := strings.Trim(op.Name, "{} ")
1226 parts := strings.Split(trimmedName, ",")
1227 firstOp := strings.TrimSpace(parts[0])
1228
1229 _, _, regPrefix, regIdx, arr := generateSVERegOp(firstOp)
1230
1231 limit := 32
1232 if regPrefix == "P" || regPrefix == "PN" {
1233 limit = 16
1234 }
1235
1236 goRegs := []string{}
1237 gnuRegs := []string{}
1238 for i := 0; i < nRegs; i++ {
1239 currIdx := (regIdx + i) % limit
1240 var goReg, gnuReg string
1241 if arr != "" {
1242 goReg = fmt.Sprintf("%s%d.%s", regPrefix, currIdx, arr)
1243 gnuReg = goReg
1244 } else {
1245 goReg = fmt.Sprintf("%s%d", regPrefix, currIdx)
1246 gnuReg = goReg
1247 }
1248 goRegs = append(goRegs, goReg)
1249 gnuRegs = append(gnuRegs, gnuReg)
1250 }
1251
1252 goAsmOp := "[" + strings.Join(goRegs, ", ") + "]"
1253 gnuAsmOp := "{" + strings.Join(gnuRegs, ", ") + "}"
1254
1255 goAsmOps = append(goAsmOps, goAsmOp)
1256 gnuAsmOps = append([]string{gnuAsmOp}, gnuAsmOps...)
1257 } else if op.Typ == "AC_REGLIST_RANGE" {
1258 nRegs := 2
1259 if strings.Contains(op.Name, "4") {
1260 nRegs = 4
1261 }
1262
1263 trimmedName := strings.Trim(op.Name, "{} ")
1264 parts := strings.Split(trimmedName, "-")
1265 firstOp := strings.TrimSpace(parts[0])
1266
1267 _, _, regPrefix, regIdx, arr := generateSVERegOp(firstOp)
1268 limit := 32
1269 if regPrefix == "P" || regPrefix == "PN" {
1270 limit = 16
1271 }
1272
1273 reg1Idx := regIdx
1274 reg2Idx := (regIdx + nRegs - 1) % limit
1275
1276 var goReg1, goReg2, gnuReg1, gnuReg2 string
1277 if arr != "" {
1278 goReg1 = fmt.Sprintf("%s%d.%s", regPrefix, reg1Idx, arr)
1279 goReg2 = fmt.Sprintf("%s%d.%s", regPrefix, reg2Idx, arr)
1280 gnuReg1 = goReg1
1281 gnuReg2 = goReg2
1282 } else {
1283 goReg1 = fmt.Sprintf("%s%d", regPrefix, reg1Idx)
1284 goReg2 = fmt.Sprintf("%s%d", regPrefix, reg2Idx)
1285 gnuReg1 = goReg1
1286 gnuReg2 = goReg2
1287 }
1288
1289 goAsmOp := fmt.Sprintf("[%s-%s]", goReg1, goReg2)
1290 gnuAsmOp := fmt.Sprintf("{%s-%s}", gnuReg1, gnuReg2)
1291
1292 goAsmOps = append(goAsmOps, goAsmOp)
1293 gnuAsmOps = append([]string{gnuAsmOp}, gnuAsmOps...)
1294 } else if op.Typ == "AC_PREGSEL" {
1295 // GNU: <preg>.<T>[<selreg>, <imm>]
1296 // Go: [selreg.T1, $idximm](preg.T2)
1297 regIdx := cachedOrNew(regCache, "P_pregsel", 16)
1298 arrIdx := rng.IntN(len(sveArr))
1299 resolvedArr := sveArr[arrIdx]
1300 selIdx := cachedOrNew(regCache, "sel_pregsel", 32)
1301 if selIdx == 18 {
1302 selIdx = 19
1303 }
1304 immVal := cachedOrNew(immCache, "imm_pregsel", 4)
1305 gnuAsmOp := fmt.Sprintf("P%d.%s[W%d, %d]", regIdx, resolvedArr, selIdx, immVal)
1306 goAsmOp := fmt.Sprintf("[R%d, $%d](P%d.%s)", selIdx, immVal, regIdx, resolvedArr)
1307 gnuAsmOps = append([]string{gnuAsmOp}, gnuAsmOps...)
1308 goAsmOps = append(goAsmOps, goAsmOp)
1309 } else if op.Typ == "AC_MEMEXT" {
1310 var goReg1, gnuReg1 string
1311 var goReg2, gnuReg2 string
1312 var mod, amount string
1313
1314 // 1. Determine reg1 (Base)
1315 if strings.Contains(op.Name, "<Xn|SP>") {
1316 regIdx := cachedOrNew(regCache, "Xn|SP", 40)
1317 if regIdx > 31 {
1318 goReg1 = "RSP"
1319 gnuReg1 = "SP"
1320 } else {
1321 if regIdx == 18 {
1322 // R18 is reserved as the platform register.
1323 regIdx = 19
1324 }
1325 goReg1 = fmt.Sprintf("R%d", regIdx)
1326 gnuReg1 = fmt.Sprintf("X%d", regIdx)
1327 }
1328 } else if strings.Contains(op.Name, "<Zn>") {
1329 regIdx := cachedOrNew(regCache, "Zn", 32)
1330 arr := "D"
1331 if strings.Contains(op.Name, ".S") {
1332 arr = "S"
1333 } else if strings.Contains(op.Name, ".D") {
1334 arr = "D"
1335 } else if strings.Contains(op.Name, ".<T>") {
1336 arr = sveArr[rng.IntN(len(sveArr))]
1337 }
1338 goReg1 = fmt.Sprintf("Z%d.%s", regIdx, arr)
1339 gnuReg1 = goReg1
1340 }
1341
1342 // 2. Determine reg2 (Offset)
1343 if strings.Contains(op.Name, "<Xm>") {
1344 regIdx := cachedOrNew(regCache, "Xm", 32)
1345 if regIdx == 18 {
1346 regIdx = 19
1347 }
1348 goReg2 = fmt.Sprintf("R%d", regIdx)
1349 gnuReg2 = fmt.Sprintf("X%d", regIdx)
1350 } else if strings.Contains(op.Name, "<Zm>") {
1351 regIdx := cachedOrNew(regCache, "Zm", 32)
1352 arr2 := "D"
1353 if strings.Contains(op.Name, ".S") {
1354 arr2 = "S"
1355 } else if strings.Contains(op.Name, ".D") {
1356 arr2 = "D"
1357 } else if strings.Contains(op.Name, ".<T>") {
1358 arr2 = sveArr[rng.IntN(len(sveArr))]
1359 }
1360 goReg2 = fmt.Sprintf("Z%d.%s", regIdx, arr2)
1361 gnuReg2 = goReg2
1362 }
1363
1364 // 3. Determine mod
1365 if strings.Contains(op.Name, "LSL") {
1366 mod = "LSL"
1367 } else if strings.Contains(op.Name, "UXTW") {
1368 mod = "UXTW"
1369 } else if strings.Contains(op.Name, "SXTW") {
1370 mod = "SXTW"
1371 } else if strings.Contains(op.Name, "<mod>") {
1372 mods := []string{"", "LSL", "UXTW", "SXTW"}
1373 mod = mods[rng.IntN(len(mods))]
1374 }
1375
1376 // 4. Determine amount
1377 if strings.Contains(op.Name, "#1") {
1378 amount = "1"
1379 } else if strings.Contains(op.Name, "#2") {
1380 amount = "2"
1381 } else if strings.Contains(op.Name, "#3") {
1382 amount = "3"
1383 } else if strings.Contains(op.Name, "#4") {
1384 amount = "4"
1385 } else if strings.Contains(op.Name, "<amount>") || strings.Contains(op.Name, "{<amount>}") {
1386 if mod != "" {
1387 amount = fmt.Sprintf("%d", rng.IntN(3)+1) // 1, 2, 3
1388 }
1389 }
1390
1391 // Enforce rule: mod and amount must be nil together, or non nil together
1392 if strings.Contains(op.Name, "<mod>") && strings.Contains(op.Name, "<amount>") {
1393 if mod == "" {
1394 amount = ""
1395 } else if amount == "" {
1396 amount = fmt.Sprintf("%d", rng.IntN(3)+1)
1397 }
1398 }
1399
1400 // 5. Construct GNU string
1401 gnuParts := []string{gnuReg1}
1402 if gnuReg2 != "" {
1403 gnuParts = append(gnuParts, gnuReg2)
1404 }
1405 if mod != "" && amount != "" {
1406 gnuParts = append(gnuParts, fmt.Sprintf("%s #%s", mod, amount))
1407 } else if mod != "" {
1408 gnuParts = append(gnuParts, mod)
1409 }
1410 gnuAsmOp := "[" + strings.Join(gnuParts, ", ") + "]"
1411
1412 // 6. Construct Go string
1413 var goOffset string
1414 if goReg2 != "" {
1415 goOffset = goReg2
1416 if mod == "LSL" {
1417 if amount != "" {
1418 goOffset = fmt.Sprintf("%s<<%s", goReg2, amount)
1419 }
1420 } else if mod != "" {
1421 if amount != "" {
1422 goOffset = fmt.Sprintf("%s.%s<<%s", goReg2, mod, amount)
1423 } else {
1424 goOffset = fmt.Sprintf("%s.%s", goReg2, mod)
1425 }
1426 }
1427 }
1428
1429 var goAsmOp string
1430 if goOffset != "" {
1431 goAsmOp = fmt.Sprintf("(%s)(%s)", goOffset, goReg1)
1432 } else {
1433 goAsmOp = fmt.Sprintf("(%s)", goReg1)
1434 }
1435
1436 goAsmOps = append(goAsmOps, goAsmOp)
1437 gnuAsmOps = append([]string{gnuAsmOp}, gnuAsmOps...)
1438 } else if op.Typ == "AC_MEMOFF" {
1439 var goReg, gnuReg string
1440 var imm string
1441
1442 if strings.Contains(op.Name, "<Xn|SP>") {
1443 regIdx := cachedOrNew(regCache, "Xn|SP", 40)
1444 if regIdx > 31 {
1445 goReg = "RSP"
1446 gnuReg = "SP"
1447 } else {
1448 if regIdx == 18 {
1449 regIdx = 19
1450 }
1451 if regIdx == 28 {
1452 // R28 is G...
1453 regIdx = 29
1454 }
1455 goReg = fmt.Sprintf("R%d", regIdx)
1456 gnuReg = fmt.Sprintf("X%d", regIdx)
1457 }
1458 } else if strings.Contains(op.Name, "<Zn>") {
1459 regIdx := cachedOrNew(regCache, "Zn", 32)
1460 arr := "D"
1461 if strings.Contains(op.Name, ".S") {
1462 arr = "S"
1463 } else if strings.Contains(op.Name, ".D") {
1464 arr = "D"
1465 }
1466 goReg = fmt.Sprintf("Z%d.%s", regIdx, arr)
1467 gnuReg = goReg
1468 }
1469
1470 intImm := rng.IntN(16)
1471 if intImm == 0 {
1472 imm = ""
1473 } else {
1474 imm = fmt.Sprintf("%d", intImm)
1475 }
1476
1477 var goAsmOp, gnuAsmOp string
1478 if imm != "" {
1479 goAsmOp = fmt.Sprintf("%s(%s)", imm, goReg)
1480 gnuAsmOp = fmt.Sprintf("[%s, #%s]", gnuReg, imm)
1481 } else {
1482 goAsmOp = fmt.Sprintf("(%s)", goReg)
1483 gnuAsmOp = fmt.Sprintf("[%s]", gnuReg)
1484 }
1485
1486 goAsmOps = append(goAsmOps, goAsmOp)
1487 gnuAsmOps = append([]string{gnuAsmOp}, gnuAsmOps...)
1488 } else if op.Typ == "AC_MEMOFFMULVL" {
1489 var goReg, gnuReg string
1490 var imm string
1491
1492 if strings.Contains(op.Name, "<Xn|SP>") {
1493 regIdx := cachedOrNew(regCache, "Xn|SP", 40)
1494 if regIdx > 31 {
1495 goReg = "RSP"
1496 gnuReg = "SP"
1497 } else {
1498 if regIdx == 18 {
1499 regIdx = 19
1500 }
1501 if regIdx == 28 {
1502 regIdx = 29
1503 }
1504 goReg = fmt.Sprintf("R%d", regIdx)
1505 gnuReg = fmt.Sprintf("X%d", regIdx)
1506 }
1507 }
1508
1509 intImm := rng.IntN(16) - 8
1510 if intImm == 0 {
1511 intImm = 1
1512 }
1513 imm = fmt.Sprintf("%d", intImm)
1514
1515 var goAsmOp, gnuAsmOp string
1516 if intImm < 0 {
1517 goAsmOp = fmt.Sprintf("(-VL*%d)(%s)", -intImm, goReg)
1518 } else {
1519 goAsmOp = fmt.Sprintf("(VL*%d)(%s)", intImm, goReg)
1520 }
1521 gnuAsmOp = fmt.Sprintf("[%s, #%s, MUL VL]", gnuReg, imm)
1522
1523 goAsmOps = append(goAsmOps, goAsmOp)
1524 gnuAsmOps = append([]string{gnuAsmOp}, gnuAsmOps...)
1525 }
1526 }
1527 // Try to assemble the GNU version.
1528 // Stores are not reversed in Go, so we reverse them back.
1529 if strings.HasPrefix(name, "ST") {
1530 for i, j := 0, len(gnuAsmOps)-1; i < j; i, j = i+1, j-1 {
1531 gnuAsmOps[i], gnuAsmOps[j] = gnuAsmOps[j], gnuAsmOps[i]
1532 }
1533 }
1534 gnuAsm := fmt.Sprintf(".arch_extension sve2p1\n%s %s", name, strings.Join(gnuAsmOps, ", "))
1535 hex, err := assembleGNU(gnuAsm)
1536 goAsmStr := fmt.Sprintf("%s %s", enc.GoOp[1:], strings.Join(goAsmOps, ", "))
1537 if err != nil {
1538 gnuErr = err
1539 if errCase == nil {
1540 errCase = &e2eData{
1541 GoOp: enc.GoOp[1:],
1542 Asm: fmt.Sprintf("%-50s", goAsmStr),
1543 Binary: "// ERROR \"illegal combination from SVE\"",
1544 highFeat: highFeat,
1545 }
1546 }
1547 continue
1548 }
1549 if validCase == nil {
1550 validCase = &e2eData{
1551 GoOp: enc.GoOp[1:],
1552 Asm: fmt.Sprintf("%-50s", goAsmStr),
1553 Binary: "// " + reverseHex(hex),
1554 highFeat: highFeat,
1555 }
1556 }
1557 if name == "CMPLT" || name == "CMPLE" || name == "CMPLO" || name == "CMPLS" {
1558 // These instructions has an aliased instruction that's not accepted by the GNU assembler.
1559 // However at this moment Go does not support the aliased instruction.
1560 // These e2e test cases will be compared to another non-aliased instruction of the same
1561 // mnemonic, causing a test failure.
1562 // Before we support alias in Go, we skip these test cases.
1563 todoCase := e2eData{GoOp: enc.GoOp[1:], Asm: fmt.Sprintf("// TODO: %s", name), highFeat: highFeat}
1564 return &todoCase, errCase
1565 }
1566 if validCase == nil || (errCase == nil && len(gnuAsmOps) != 0) {
1567 // We must collect at least one valid and one error case.
1568 // if the instruction has 0 operands, we can't generate an error case.
1569 continue
1570 }
1571
1572 if enc.Asm == "INDEX <Zd>.<T>, <R><n>, #<imm>" {
1573 // Don't generate error case for this, the GNU assembler has a strict scalar and vector register width
1574 // constraint, i.e. <R> must be W if <T> is B, H, S. The Go assembler doesn't have this constraint.
1575 // So we can't generate an error case for this.
1576 errCase = &e2eData{GoOp: enc.GoOp[1:], Asm: fmt.Sprintf("// TODO: %s", name), highFeat: highFeat}
1577 }
1578 return validCase, errCase
1579 }
1580 if name == "ADDQP" || name == "ADDSUBP" || name == "SCVTFLT" || name == "UCVTFLT" || name == "LUTI6" || name == "FCVTZSN" ||
1581 name == "FCVTZUN" {
1582 // Very new instructions
1583 // GNU toolchain 2.45 doesn't know about these instruction yet.
1584 todoCase := e2eData{GoOp: enc.GoOp[1:], Asm: fmt.Sprintf("// TODO: %s", name), highFeat: highFeat}
1585 return &todoCase, &todoCase
1586 }
1587 if enc.Asm == "BFMMLA <Zda>.H, <Zn>.H, <Zm>.H" ||
1588 enc.Asm == "FMMLA <Zda>.H, <Zn>.H, <Zm>.H" ||
1589 enc.Asm == "SABAL <Zda>.<T>, <Zn>.<Tb>, <Zm>.<Tb>" ||
1590 enc.Asm == "SCVTF <Zd>.<T>, <Zn>.<Tb>" ||
1591 enc.Asm == "SDOT <Zda>.H, <Zn>.B, <Zm>.B" ||
1592 enc.Asm == "SUBP <Zdn>.<T>, <Pg>/M, <Zdn>.<T>, <Zm>.<T>" ||
1593 enc.Asm == "UABAL <Zda>.<T>, <Zn>.<Tb>, <Zm>.<Tb>" ||
1594 enc.Asm == "UCVTF <Zd>.<T>, <Zn>.<Tb>" ||
1595 enc.Asm == "UDOT <Zda>.H, <Zn>.B, <Zm>.B" ||
1596 enc.Asm == "SDOT <Zda>.H, <Zn>.B, <Zm>.B[<imm>]" ||
1597 enc.Asm == "UDOT <Zda>.H, <Zn>.B, <Zm>.B[<imm>]" ||
1598 enc.Asm == "SQRSHRN <Zd>.B, { <Zn1>.H-<Zn2>.H }, #<const>" ||
1599 enc.Asm == "SQRSHRUN <Zd>.B, { <Zn1>.H-<Zn2>.H }, #<const>" ||
1600 enc.Asm == "SQSHRN <Zd>.<T>, { <Zn1>.<Tb>-<Zn2>.<Tb> }, #<const>" ||
1601 enc.Asm == "SQSHRUN <Zd>.<T>, { <Zn1>.<Tb>-<Zn2>.<Tb> }, #<const>" ||
1602 enc.Asm == "UQRSHRN <Zd>.B, { <Zn1>.H-<Zn2>.H }, #<const>" ||
1603 enc.Asm == "UQSHRN <Zd>.<T>, { <Zn1>.<Tb>-<Zn2>.<Tb> }, #<const>" {
1604 // Very new instruction encodings
1605 // GNU toolchain 2.45 doesn't know about these specific encodings yet.
1606 todoCase := e2eData{GoOp: enc.GoOp[1:], Asm: fmt.Sprintf("// TODO: %s", enc.Asm), highFeat: highFeat}
1607 return &todoCase, &todoCase
1608 }
1609 log.Fatalf("Failed to construct instance for %s: %v", enc.Asm, gnuErr)
1610 return &e2eData{GoOp: enc.GoOp[1:]}, &e2eData{GoOp: enc.GoOp[1:]}
1611 }