Debian Codegraph @

arm64/instgen/xmlspec/parser.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 xmlspec implements the parser of the A64 instruction set XML specification.
6 // It parses the XML files and returns a list of Instruction objects.
7 // The expected data is fetched from:
8 //
9 // https://developer.arm.com/-/cdn-downloads/permalink/Exploration-Tools-A64-ISA/ISA_A64/ISA_A64_xml_A_profile-2025-12.tar.gz
10 //
11 // Pass directory ISA_A64_xml_A_profile-2025-12 to ParseXMLFiles to get the instructions.
12 //
13 // Currently the parser only processes SVE and SVE2 instructions.
14 // Other instructions will still be unmarshalled but they won't have processing logics.
15 package xmlspec
16
17 import (
18 "encoding/xml"
19 "flag"
20 "fmt"
21 "io"
22 "log"
23 "os"
24 "path"
25 "regexp"
26 "sort"
27 "strconv"
28 "strings"
29 "sync"
30 )
31
32 var debug = flag.Int("debug", 0, "enable debug output")
33
34 var (
35 reZREG = regexp.MustCompile(`(^|[^/])<Z[A-Za-z1-9]+>`)
36 rePREG = regexp.MustCompile(`<P[A-Za-z1-9]+>`)
37 )
38
39 type fixedElemType int
40
41 const (
42 FixedArrangement fixedElemType = iota
43 FixedLSL
44 FixedSXTW
45 FixedUXTW
46 FixedModAmt
47 )
48
49 type fixedElemRule struct {
50 re *regexp.Regexp
51 t fixedElemType
52 val string
53 }
54
55 var fixedElemRules = []fixedElemRule{
56 {regexp.MustCompile(`\.B`), FixedArrangement, "B"},
57 {regexp.MustCompile(`\.H`), FixedArrangement, "H"},
58 {regexp.MustCompile(`\.S`), FixedArrangement, "S"},
59 {regexp.MustCompile(`\.D`), FixedArrangement, "D"},
60 {regexp.MustCompile(`\.Q`), FixedArrangement, "Q"},
61 {regexp.MustCompile(`\.N`), FixedArrangement, "N"},
62 {regexp.MustCompile(`LSL #1`), FixedLSL, "1"},
63 {regexp.MustCompile(`LSL #2`), FixedLSL, "2"},
64 {regexp.MustCompile(`LSL #3`), FixedLSL, "3"},
65 {regexp.MustCompile(`LSL #4`), FixedLSL, "4"},
66 {regexp.MustCompile(`SXTW`), FixedSXTW, "SXTW"},
67 {regexp.MustCompile(`UXTW`), FixedUXTW, "UXTW"},
68 // FixedModAmt rules are special, they requires a mapping of
69 // the preceding elem's symbol to be <mod>.
70 {regexp.MustCompile(`#1`), FixedModAmt, "1"},
71 {regexp.MustCompile(`#2`), FixedModAmt, "2"},
72 {regexp.MustCompile(`#3`), FixedModAmt, "3"},
73 {regexp.MustCompile(`#4`), FixedModAmt, "4"},
74 {regexp.MustCompile(`#8`), FixedModAmt, "8"},
75 }
76
77 type operandRule struct {
78 re *regexp.Regexp
79 class string
80 }
81
82 var operandRules = []operandRule{
83 // AC_ARNG: Registers with arrangement (e.g. .B, .D, .S) or type variable (<T>).
84 {regexp.MustCompile(`^<[PVZ][a-zA-Z]+>\.([1-9]*[BDHQS]|<T[a-z]*>)$`), "AC_ARNG"},
85 // AC_ZREG: Scalable vector registers (Z).
86 {regexp.MustCompile(`^<Z[a-z]+>$`), "AC_ZREG"},
87 // AC_PREG: Predicate registers (P).
88 {regexp.MustCompile(`^<P[a-z]{1}>$`), "AC_PREG"},
89 // AC_PREG: Predicate-as-counter registers (PN).
90 {regexp.MustCompile(`^<PN[a-z]{1}>$`), "AC_PREG"},
91 // AC_PREGZM: Predicate registers with merging predication (/M).
92 {regexp.MustCompile(`^<P[N]?[a-z]{1}>\/M$`), "AC_PREGZM"},
93 // AC_PREGZM: Predicate registers with zeroing predication (/Z).
94 {regexp.MustCompile(`^<P[N]?[a-z]{1}>\/(Z|<ZM>)$`), "AC_PREGZM"},
95 // AC_SPZGREG: Standard scalar registers (W, X, R).
96 {regexp.MustCompile(`^(<[WX][a-z]+>!?|<R><[a-z]+>|X[0-9]+|{<[WX][a-z]+>})$`), "AC_SPZGREG"},
97 // AC_SPZGREG: Scalar registers or stack pointer (SP).
98 {regexp.MustCompile(`^<([WX][a-z]{1}|R><n)\|[W]?SP>$`), "AC_SPZGREG"},
99 // AC_VREG: V registers (SIMD).
100 {regexp.MustCompile(`(^<Dd>|^<V>.*)$`), "AC_VREG"},
101 // AC_ARNGIDX: Register arrangement with index.
102 {regexp.MustCompile(`^<[VZ][a-zA-Z]*>\.([1-9]*[BDHQS]|<T[a-z]*>)\[(<(index|imm)[1-9]*>|[0-9]+)\]$`), "AC_ARNGIDX"},
103 {regexp.MustCompile(`^{[\s]+<[PVZ][a-z]+[1-4]*>\.[BDHQS],*[\s]*}\[<index>\]$`), "AC_ARNGIDX"},
104 // AC_PREGIDX: P Registers with immediate index.
105 {regexp.MustCompile(`^(<P[N]?[a-z]{1}>)\[<[a-z]+>\]$`), "AC_PREGIDX"},
106 // AC_ZREGIDX: Z Registers with (optional) immediate index.
107 {regexp.MustCompile(`^(<Z[a-z]{1}>)\{?\[<[a-z]+>\]\}?$`), "AC_ZREGIDX"},
108 // AC_REGLIST1: List of 1 register with arrangement.
109 {regexp.MustCompile(`^{[\s]+<[PVZ][a-z]+>\.([1-9]*[BDHQS]|<T[a-z]*>)[\s]+}$`), "AC_REGLIST1"},
110 // AC_REGLIST2: List of 2 registers with arrangement.
111 {regexp.MustCompile(`^{[\s]+(<[PVZ][a-z]+([1-2]|\+[1-2])*>\.([1-9]*[BDHQS]|<T[a-z]*>),*[\s]*){2}}$`), "AC_REGLIST2"},
112 // AC_REGLIST3: List of 3 registers with arrangement.
113 {regexp.MustCompile(`^{[\s]+(<[PVZ][a-z]+([1-3]|\+[1-3])*>\.([1-9]*[BDHQS]|<T[a-z]*>)(,|-)*[\s]*){3}}$`), "AC_REGLIST3"},
114 // AC_REGLIST4: List of 4 registers with arrangement.
115 {regexp.MustCompile(`^{[\s]+(<[PVZ][a-z]+([1-4]|\+[1-4])*>\.([1-9]*[BDHQS]|<T[a-z]*>),*[\s]*){4}}$`), "AC_REGLIST4"},
116 // AC_REGLIST_RANGE: List of registers in a range.
117 {regexp.MustCompile(`^{[\s]+(<[PVZ][a-z]+[1-2]*>\.([1-9]*[BDHQS]|<T[a-z]*>)-*[\s]*){2}}$`), "AC_REGLIST_RANGE"},
118 {regexp.MustCompile(`^{[\s]+(<[PVZ][a-z]+[14]>\.([BDHQS]|<T[a-z]*>)-*[\s]*){2}}$`), "AC_REGLIST_RANGE"}, // It's 4 registers, but in the mnemonic it's 2.
119 // AC_MEMOFF: Memory operand with immediate offset.
120 {regexp.MustCompile(`^\[<Xn\|SP>([\s]*\{,[\s]*#([0-9]+|<[a-z]+>)\})*\]$`), "AC_MEMOFF"},
121 {regexp.MustCompile(`^\[<Z[a-z]+>\.[BDHQS](\{,[\s]*#<[a-z]+>\})*\]$`), "AC_MEMOFF"},
122 // AC_MEMOFFMULVL: Memory operand with immediate offset that is multiplied by the vector's in-memory size.
123 {regexp.MustCompile(`^\[<Xn\|SP>[\s]*\{,[\s]*#<[a-z]+>,[\s]*MUL[\s]+VL[\s]*\}\]$`), "AC_MEMOFFMULVL"},
124 // AC_MEMEXT: Memory operand with register offset and optional extension (signed or unsigned) or shift (logical shift left).
125 {regexp.MustCompile(`^\[<Xn\|SP>,[\s]*(<X[a-z]+>|<Z[a-z]+>\.[BDHQS])\]$`), "AC_MEMEXT"},
126 {regexp.MustCompile(`^\[<Xn\|SP>\{?,[\s]*<X[a-z]+>\{?,[\s]*LSL[\s]+(<amount>|#[0-9]+)\}?\]$`), "AC_MEMEXT"},
127 {regexp.MustCompile(`^\[(<Xn\|SP>|<Z[a-z]+>\.[BDHQS])\{,[\s]*<X[a-z]+>\}\]$`), "AC_MEMEXT"},
128 {regexp.MustCompile(`^\[<Xn\|SP>,[\s]*<Z[a-z]+>\.[BDHQS],[\s]*(<mod>([\s]+#[0-9]+)*|LSL[\s]+#[0-9]+)\]$`), "AC_MEMEXT"},
129 {regexp.MustCompile(`^\[<Z[a-z]+>\.(<T>|[BDHQS]),[\s]*<Z[a-z]+>\.(<T>|[BDHQS])\{?,[\s]*(<mod>|SXTW\{?|UXTW\{?)[\s]*<amount>\}?\]$`), "AC_MEMEXT"},
130 // AC_SPECIAL: Prefetch operation.
131 {regexp.MustCompile(`^<prfop>$`), "AC_SPECIAL"},
132 // AC_SPECIAL: Vector length.
133 {regexp.MustCompile(`^<vl>$`), "AC_SPECIAL"},
134 // AC_REG_PATTERN: Register with rotate/replication pattern.
135 {regexp.MustCompile(`^<[WX][dn]+>(\{\s*,\s*<pattern>(\{\s*,\s*MUL\s+#<imm>\s*\})?\s*\})?$`), "AC_REG_PATTERN"},
136 // AC_ZREG_PATTERN: Z register with rotate/replication pattern.
137 {regexp.MustCompile(`^<Z[dn]+>\.(<T>|[BDHQS])(\{\s*,\s*<pattern>(\{\s*,\s*MUL\s+#<imm>\s*\})?\s*\})?$`), "AC_ZREG_PATTERN"},
138 // AC_PREGSEL: Predicate register with selector register and immediate index.
139 {regexp.MustCompile(`^<P[nm]>\.<T>\[\s*<Wv>\s*,\s*<imm>\s*\]$`), "AC_PREGSEL"},
140 // AC_PREG_PATTERN: Predicate register with pattern.
141 {regexp.MustCompile(`^<P[dn]>\.<T>(\{\s*,\s*<pattern>\s*\})?$`), "AC_PREG_PATTERN"},
142 // AC_IMM: Immediate value.
143 {regexp.MustCompile(`(^#.*)|(<const>)$`), "AC_IMM"},
144 }
145
146 // warmUpCache initializes the XML decoding cache for the Instruction type.
147 // This is necessary because encoding/xml uses reflect to build a cache of
148 // struct fields, and this process is not thread-safe if multiple goroutines
149 // attempt to unmarshal into the same type for the first time concurrently.
150 func warmUpCache() {
151 var inst InstructionParsed
152 // Unmarshal a more complete XML to warm up the cache for nested types.
153 // This ensures that reflection data for all referenced types is initialized
154 // sequentially before parallel workers start.
155 dummyXML := `
156 <instructionsection>
157 <docvars>
158 <docvar key="a" value="b"/>
159 </docvars>
160 <classes>
161 <iclass>
162 <encoding name="e">
163 <box hibit="31" width="1" name="n">
164 <c>1</c>
165 </box>
166 <asmtemplate>
167 <text>ADD</text>
168 <a link="s" hover="h">X0</a>
169 </asmtemplate>
170 </encoding>
171 </iclass>
172 </classes>
173 <explanations>
174 <explanation>
175 <symbol link="s">X0</symbol>
176 <account encodedin="e">
177 <intro>
178 <para>text</para>
179 </intro>
180 </account>
181 <definition encodedin="e">
182 <intro>text</intro>
183 <table>
184 <tgroup cols="1">
185 <thead>
186 <row>
187 <entry>Val</entry>
188 </row>
189 </thead>
190 <tbody>
191 <row>
192 <entry>1</entry>
193 </row>
194 </tbody>
195 </tgroup>
196 </table>
197 </definition>
198 </explanation>
199 </explanations>
200 </instructionsection>
201 `
202 _ = xml.Unmarshal([]byte(dummyXML), &inst)
203 }
204
205 func init() {
206 warmUpCache()
207 }
208
209 func ParseXMLFiles(dir string) []*InstructionParsed {
210 log.Println("Start parsing the xml files")
211 files, err := os.ReadDir(dir)
212 if err != nil {
213 log.Fatal(err)
214 }
215
216 var wg sync.WaitGroup
217 insts := make([]*InstructionParsed, len(files))
218
219 for i, file := range files {
220 fileName := file.Name()
221 if ext := path.Ext(fileName); ext != ".xml" {
222 continue
223 }
224 wg.Add(1)
225 fileName = path.Join(dir, fileName)
226 go func(name string, i int) {
227 defer wg.Done()
228 if inst := parse(name); inst != nil {
229 insts[i] = inst
230 }
231 }(fileName, i)
232 }
233 wg.Wait()
234
235 log.Println("Finish parsing the xml files")
236 return insts
237 }
238
239 // parse parses an xml file and returns the instruction.
240 func parse(f string) *InstructionParsed {
241 xmlFile, err := os.Open(f)
242 if err != nil {
243 log.Fatalf("Open file %s failed: %v\n", f, err)
244 }
245 defer xmlFile.Close()
246 byteValue, err := io.ReadAll(xmlFile)
247 if err != nil {
248 log.Fatalf("io.ReadAll %s failed: %v\n", f, err)
249 }
250
251 var inst = new(InstructionParsed)
252 inst.file = f
253 if err = xml.Unmarshal(byteValue, inst); err != nil {
254 // Ignore non-instruction files.
255 if strings.HasPrefix(err.Error(), "expected element type <instructionsection>") {
256 return nil
257 }
258 log.Fatalf("Unmarshal %s failed: %v\n", f, err)
259 }
260 if inst.Type != "instruction" && inst.Type != "alias" {
261 return nil
262 }
263
264 return inst
265 }
266
267 func (inst *InstructionParsed) setBinary(code, bitVal uint32, value string) uint32 {
268 switch value {
269 case "0", "(0)":
270 code &^= bitVal
271 case "1", "(1)":
272 code |= bitVal
273 case "x":
274 // unspecified bits, just ignore
275 default:
276 log.Fatalf("unexpected binary value %s in %s\n", value, inst.file)
277 }
278 return code
279 }
280
281 func (inst *InstructionParsed) setMask(code, bitVal uint32, value string) uint32 {
282 switch value {
283 // See the comment of [Regdiagram.mask]
284 case "0", "1", "(0)", "(1)":
285 code |= bitVal
286 case "x":
287 // unspecified bits, just ignore
288 default:
289 log.Fatalf("unexpected mask value %s in %s\n", value, inst.file)
290 }
291 return code
292 }
293
294 func (inst *InstructionParsed) boxEncoding(b Box, callBack func(uint32, uint32, string) uint32) uint32 {
295 code := uint32(0)
296 hi, err := strconv.Atoi(b.HiBit)
297 if err != nil {
298 log.Fatalf("convert HiBit to int failed, HiBit = %s in %s\n", b.HiBit, inst.file)
299 }
300 for _, c := range b.Cs {
301 if c.ColSpan != "" {
302 log.Fatalf("unexpected colspan in %s\n", inst.file)
303 }
304 code = callBack(code, uint32(1<<hi), c.Value)
305 hi--
306 }
307 return code
308 }
309
310 func (inst *InstructionParsed) supported() bool {
311 foundSVE := false
312 hasInstClass := false
313 for _, doc := range inst.DocVars {
314 if doc.Key == "instr-class" {
315 hasInstClass = true
316 if doc.Value == "sve" || doc.Value == "sve2" {
317 foundSVE = true
318 }
319 }
320 }
321 if !foundSVE && !hasInstClass {
322 // A fall back solution, check all encodings has arch variants FEAT_SVE
323 hasNonSVE := false
324 Outer:
325 for _, ic := range inst.Classes.Iclass {
326 for _, av := range ic.ArchVariants {
327 if !strings.Contains(av.Feature, "FEAT_SVE") {
328 hasNonSVE = true
329 break Outer
330 }
331 }
332 }
333 return !hasNonSVE
334 }
335 return foundSVE
336 }
337
338 // extractBinary extracts the known bits of instruction encoding in regdiagram,
339 // and assign the binary to inst.regdiagram.binary.
340 func (inst *InstructionParsed) extractBinary() {
341 if !inst.supported() {
342 return
343 }
344 for i := range inst.Classes.Iclass {
345 bin, mask := uint32(0), uint32(0)
346 regDiagram := &inst.Classes.Iclass[i].RegDiagram
347 for _, box := range regDiagram.Boxes {
348 if len(box.Cs) > 1 || (len(box.Cs) == 1 && box.Cs[0].ColSpan == "") {
349 // Fixed bits
350 bin |= inst.boxEncoding(box, inst.setBinary)
351 mask |= inst.boxEncoding(box, inst.setMask)
352 } else if len(box.Cs) == 1 && box.Cs[0].ColSpan != "" {
353 // Named variable bits
354 h, err := strconv.Atoi(box.HiBit)
355 h++ // Arm provided high bit to be inclusive, but we need to make it exclusive.
356 if err != nil {
357 log.Fatalf("convert HiBit to int failed, HiBit = %s in %s\n", box.HiBit, inst.file)
358 }
359 cs, err := strconv.Atoi(box.Cs[0].ColSpan)
360 if err != nil {
361 log.Fatalf("convert ColSpan to int failed, ColSpan = %s in %s\n", box.Cs[0].ColSpan, inst.file)
362 }
363 if box.Name == "" {
364 log.Fatalf("empty name in named box in %s\n", inst.file)
365 }
366 if regDiagram.varBin == nil {
367 regDiagram.varBin = make(map[string]bitRange)
368 }
369 if _, ok := regDiagram.varBin[box.Name]; ok {
370 log.Fatalf("duplicate name in named box in %s\n", inst.file)
371 }
372 regDiagram.varBin[box.Name] = bitRange{
373 hi: h,
374 lo: h - cs,
375 }
376 } else {
377 log.Fatalf("unrecognized box in %s\n", inst.file)
378 }
379 }
380 regDiagram.fixedBin = bin
381 regDiagram.mask = mask
382 regDiagram.Parsed = true
383 if inst.Title == "URSQRTE -- A64" || inst.Title == "URECPE -- A64" {
384 // Special case, its "size" box is actually not specified in the assembler symbol section.
385 // By reading the decoding ASL we know that this "size" box should be 0b10...
386 regDiagram.fixedBin |= uint32(1 << 23)
387 }
388 if len(inst.Classes.Iclass[i].PsSection) == 1 {
389 squashedPs := inst.Classes.Iclass[i].PsSection[0].Ps[0].PSText
390 if strings.Contains(strings.Join(squashedPs, "\n"), "if size IN {'0x'} then EndOfDecode") {
391 // Very ugly encoding specification in the decoding ASL. We have to set
392 // the high bit of the size box to 1.
393 // Example instruction is "Unsigned divide (predicated)":
394 // UDIV <Zdn>.<T>, <Pg>/M, <Zdn>.<T>, <Zm>.<T>
395 if _, ok := regDiagram.varBin["size"]; !ok {
396 log.Fatalf("size box not found in %s", inst.file)
397 }
398 if regDiagram.varBin["size"].hi != 24 || regDiagram.varBin["size"].lo != 22 {
399 log.Fatalf("unexpecetd size box in %s", inst.file)
400 }
401 regDiagram.fixedBin |= uint32(1 << 23)
402 }
403 }
404 }
405 }
406
407 // processEncoding handles each encoding element of a inst.
408 func (inst *InstructionParsed) processEncodings() {
409 if !inst.supported() {
410 return
411 }
412 for i := range inst.Classes.Iclass {
413 iclass := &inst.Classes.Iclass[i]
414 for j := 0; j < len(iclass.Encodings); j++ {
415 enc := &iclass.Encodings[j]
416 // Set instruction class.
417 if !enc.instClass() {
418 // Unsupported instruction class.
419 continue
420 }
421 // Set alias
422 enc.Alias = inst.Type == "alias"
423 // Refine the known bits and mask of the binary.
424 bin, mask := iclass.RegDiagram.fixedBin, iclass.RegDiagram.mask
425 for _, box := range enc.Boxes {
426 bin |= inst.boxEncoding(box, inst.setBinary)
427 mask |= inst.boxEncoding(box, inst.setMask)
428 }
429 enc.Binary = bin
430 enc.mask = mask
431
432 inst.parseOperands(enc)
433 inst.arm64Opcode(enc)
434 inst.goOpcode(enc)
435 inst.template(enc)
436 inst.operandsType(enc)
437 enc.sortOperands()
438 if inst.Title == "REVB, REVH, REVW -- A64" ||
439 inst.Title == "SXTB, SXTH, SXTW -- A64" ||
440 inst.Title == "UXTB, UXTH, UXTW -- A64" {
441 // Special case, its "size" box is not specified in the assembler symbol
442 // section for the [B] and [W] variants, which for [B] it's 0b00 (no-op)
443 // and for [W] it's 0b11.
444 imnemonic := enc.Operands[0].Name
445 if imnemonic[len(imnemonic)-1] == 'W' {
446 enc.Binary |= uint32(0b11 << 22)
447 }
448 }
449 enc.Parsed = true
450 }
451 }
452 }
453
454 func (inst *InstructionParsed) findExplanation(link string) *Explanation {
455 for _, exp := range inst.Explanations.Explanations {
456 if exp.Symbol.Link == link {
457 return &exp
458 }
459 }
460 return nil
461 }
462
463 func trimXMLEscape(s string) string {
464 return strings.ReplaceAll(strings.ReplaceAll(s, "&lt;", "<"), "&gt;", ">")
465 }
466
467 // key is the fixed symbol, value is its attached symbols (the currently parsed part of the operand)
468 // and the instruction that contains this fixed symbol.
469 // This data is just used for debugging.
470 var allFixedSymbolsLock sync.Mutex
471 var allFixedSymbols = map[string]map[string]*InstructionParsed{}
472
473 func (inst *InstructionParsed) parseOperands(enc *EncodingParsed) {
474 // This is the most vulnerable part.
475 //
476 // The mnemonic and operands of an instruction are sequentially recorded
477 // in TextA, and we need to parse them out. According to the following rules:
478 // 1. The mnemonic and the operand are separated by " ".
479 // 2. The operands are separated by ", ". Symbols without intervals belong to
480 // the same operand.
481 // 3, An operand may contain [] and {}, and the brackets contained in the
482 // operand must be in pairs. For example <R><m>{, <extend> {#<amount>}}
483 // is one operand, not two.
484 //
485 // After this step we'll get all operands of this instruction encoding, the
486 // operand interval symbol ", " will be discarded.
487 asm, oprAsm := "", ""
488 leftCurly, leftSquare := 0, 0
489 elems := []Element{}
490 recordFixedSymbol := func(symbol, val string) {
491 allFixedSymbolsLock.Lock()
492 if _, ok := allFixedSymbols[symbol]; !ok {
493 allFixedSymbols[symbol] = make(map[string]*InstructionParsed)
494 }
495 if _, ok := allFixedSymbols[symbol][val]; ok {
496 allFixedSymbolsLock.Unlock()
497 return
498 }
499 allFixedSymbols[symbol][val] = inst
500 allFixedSymbolsLock.Unlock()
501 }
502
503 for m, ta := range enc.AsmTemplate.TextA {
504 val := ta.Value
505 if link := ta.Link; link != "" { // An <a> element
506 // Check if it's a special operand with fixed candidates.
507 exp := inst.findExplanation(link)
508 if exp == nil {
509 log.Fatalf("explanation not found for link %s in %s\n", link, inst.file)
510 }
511 var explanation, encodedin string
512 if tblClass := exp.Definition.Table.Class; tblClass != "" {
513 switch tblClass {
514 case "valuetable":
515 heads := []string{}
516 for _, entry := range exp.Definition.Table.TGroup.THead.Row.Entries {
517 heads = append(heads, trimXMLEscape(entry.Value))
518 }
519 bodies := [][]string{}
520 for i, row := range exp.Definition.Table.TGroup.TBody.Row {
521 bodies = append(bodies, []string{})
522 for _, entry := range row.Entries {
523 bodies[i] = append(bodies[i], entry.Value)
524 }
525 }
526 explanation = strings.Join(heads, "\t")
527 for _, body := range bodies {
528 explanation += "\n" + strings.Join(body, "\t")
529 }
530 if explanation == "" {
531 log.Fatalf("explanation is empty in %s\n", inst.file)
532 }
533 explanation = trimXMLEscape(exp.Definition.Intro) + "\n" + explanation
534 encodedin = exp.Definition.Encodedin
535 if encodedin == "" {
536 log.Fatalf("definition.encodedin is empty in %s\n", inst.file)
537 }
538 default:
539 log.Fatalf("unknown table class %s in %s\n", tblClass, inst.file)
540 }
541 } else if exp.Account.Encodedin != "" {
542 explanation = trimXMLEscape(exp.Account.Intro)
543 if explanation == "" {
544 log.Fatalf("account.intro.para is empty in %s\n", inst.file)
545 }
546 encodedin = exp.Account.Encodedin
547 if encodedin == "" {
548 log.Fatalf("account.encodedin is empty in %s\n", inst.file)
549 }
550 }
551 val = trimXMLEscape(val)
552 elem := Element{encodedIn: encodedin, textExp: explanation, symbol: val}
553 // Some hardcoded logic to populate register type and the presence
554 // of <mod> for deduplication purposes
555 if strings.HasPrefix(val, "<X") {
556 elem.fixedScalarWidth = 64
557 recordFixedSymbol("X", val)
558 } else if strings.HasPrefix(val, "<W") {
559 elem.fixedScalarWidth = 32
560 recordFixedSymbol("W", val)
561 } else if val == "<mod>" {
562 recordFixedSymbol("mod", val)
563 elem.hasMod = true
564 } else if strings.HasPrefix(val, "<P") {
565 recordFixedSymbol("P", val)
566 elem.isP = true
567 } else if strings.HasPrefix(val, "<Z") {
568 recordFixedSymbol("Z", val)
569 elem.isZ = true
570 }
571 elems = append(elems, elem)
572 } else {
573 // It's a text section, we want to extract fixed symbols if any.
574 for _, rule := range fixedElemRules {
575 matchCnt := 0
576 if rule.re.MatchString(val) {
577 if len(elems) == 0 {
578 // These instructions are just named UXTW and SXTW
579 if rule.t == FixedUXTW && inst.Title == "UXTB, UXTH, UXTW -- A64" {
580 continue
581 }
582 if rule.t == FixedSXTW && inst.Title == "SXTB, SXTH, SXTW -- A64" {
583 continue
584 }
585 log.Fatalf("fixed arrangement symbol %s without preceding element in %s\n", val, inst.file)
586 }
587 if matchCnt != 0 {
588 log.Fatalf("fixed arrangement symbol %s with multiple match in %s\n", val, inst.file)
589 }
590 matchCnt++
591 lastElem := &elems[len(elems)-1]
592 switch rule.t {
593 case FixedArrangement:
594 lastElem.fixedArng = rule.val
595 case FixedLSL:
596 lastElem.fixedLSL = rule.val
597 case FixedSXTW:
598 lastElem.fixedSXTW = true
599 case FixedUXTW:
600 lastElem.fixedUXTW = true
601 case FixedModAmt:
602 if lastElem.symbol == "<mod>" {
603 lastElem.fixedModAmt = rule.val
604 }
605 }
606 // Also book keep the fixed symbol in the global map.
607 recordFixedSymbol(rule.val, fmt.Sprintf("%s in %s", lastElem.symbol, oprAsm+val))
608 }
609 }
610 }
611 asm += val
612
613 appendOperand := func() {
614 elemsCopy := make([]Element, len(elems))
615 copy(elemsCopy, elems)
616 opr := Operand{Name: oprAsm, Elems: elemsCopy}
617 enc.Operands = append(enc.Operands, opr)
618 oprAsm = ""
619 elems = elems[:0]
620 }
621
622 // Parse operands
623 for n := 0; n < len(val); n++ {
624 ch := val[n]
625 switch ch {
626 case ',':
627 if leftCurly == 0 && leftSquare == 0 {
628 // This "," is an interval.
629 continue
630 }
631 case ' ':
632 if leftCurly == 0 && leftSquare == 0 {
633 if oprAsm == "" {
634 // Consecutive space separators.
635 continue
636 }
637 // This first one is mnemonic, followed by operands.
638 appendOperand()
639 continue
640 }
641 case '{':
642 leftCurly++
643 case '[':
644 leftSquare++
645 case '}':
646 leftCurly--
647 case ']':
648 leftSquare--
649 }
650 oprAsm += string(ch)
651 }
652 // The last operand.
653 if m == len(enc.AsmTemplate.TextA)-1 && leftCurly == 0 && leftSquare == 0 && oprAsm != "" {
654 appendOperand()
655 }
656 }
657 if oprAsm != "" || len(elems) != 0 {
658 log.Fatalf("malformed Asmtemplate, oprAsm: %v, elems: %v in %s\n", oprAsm, elems, inst.file)
659 }
660 enc.Asm = asm
661 }
662
663 // template resets the arm64 assembly template of an encoding, to make it cleaner.
664 func (inst *InstructionParsed) template(enc *EncodingParsed) {
665 asm := enc.Operands[0].Name
666 if len(enc.Operands) > 1 { // Has operands
667 asm += " "
668 i := 1
669 for ; i < len(enc.Operands)-1; i++ {
670 asm += enc.Operands[i].Name + ", "
671 }
672 asm += enc.Operands[i].Name
673 }
674 enc.Asm = asm
675 }
676
677 // arm64Opcode sets the arm64 opcode of an encoding.
678 func (inst *InstructionParsed) arm64Opcode(enc *EncodingParsed) {
679 if len(enc.Operands) == 0 {
680 log.Fatalf("Miss mnemonic: %v in %s\n", enc, inst.file)
681 }
682 // Add a prefix "A64", to differ with the "A" prefix of Go opcode.
683 enc.arm64Op = "A64" + enc.Operands[0].Name
684 }
685
686 func (enc *EncodingParsed) classString() string {
687 val := ""
688 for _, d := range enc.DocVars {
689 if d.Key == "instr-class" {
690 val = d.Value
691 break
692 }
693 }
694 return val
695 }
696
697 func (enc *EncodingParsed) instClass() bool {
698 val := enc.classString()
699 switch val {
700 case "sve":
701 enc.class = C_SVE
702 case "sve2":
703 enc.class = C_SVE2
704 default:
705 return false
706 }
707 return true
708 }
709
710 func (enc *EncodingParsed) hasZREG() bool {
711 // Special case: <Pg>/<ZM>, <ZM> is not Z register.
712 return reZREG.MatchString(enc.Asm)
713 }
714
715 func (enc *EncodingParsed) hasPREG() bool {
716 return rePREG.MatchString(enc.Asm)
717 }
718
719 func (enc *EncodingParsed) goOpcodePrefix(inst *InstructionParsed) string {
720 if enc.prefix != "" {
721 return enc.prefix
722 }
723 prefix := ""
724 switch enc.class {
725 case C_SVE, C_SVE2:
726 if enc.hasZREG() {
727 prefix = "Z"
728 } else if enc.hasPREG() {
729 prefix = "P"
730 }
731 default:
732 log.Fatalf("unknown instruction class %v in %s\n", enc.class, inst.file)
733 }
734 return prefix
735 }
736
737 // goOpcode determines the Go opcode representation of an encoding.
738 func (inst *InstructionParsed) goOpcode(enc *EncodingParsed) {
739 if len(enc.Operands) == 0 {
740 log.Fatalf("Missing mnemonic: %v in %s\n", enc, inst.file)
741 }
742 if enc.GoOp != "" {
743 return
744 }
745 prefix, opcode := "A", ""
746 prefix += enc.goOpcodePrefix(inst)
747 opcode = enc.Operands[0].Name
748 enc.GoOp = prefix + opcode
749 enc.prefix = prefix
750 }
751
752 // sortOperands reorders the operands of an encoding according to Go assembly syntax.
753 func (enc *EncodingParsed) sortOperands() {
754 // For stores, we need to make sure the memory is the destination.
755 // The original order fits just naturally, so no-op.
756 if strings.HasPrefix(enc.Operands[0].Name, "ST") {
757 return
758 }
759 // Reverse args, placing dest last.
760 for i, j := 1, len(enc.Operands)-1; i < j; i, j = i+1, j-1 {
761 enc.Operands[i], enc.Operands[j] = enc.Operands[j], enc.Operands[i]
762 }
763 }
764
765 func (inst *InstructionParsed) operandType(opr Operand) string {
766 if opr.Typ != "" {
767 return opr.Typ
768 }
769 name := opr.Name
770 for i := 0; i < len(operandRules); i++ {
771 if operandRules[i].re.MatchString(name) {
772 return operandRules[i].class
773 }
774 }
775 inst.ParseError = fmt.Sprintf("unrecognized operand type: %s in %s\n", name, inst.file)
776 return "AC_NONE"
777 }
778
779 // operandsType classifies all operands of an encoding.
780 func (inst *InstructionParsed) operandsType(enc *EncodingParsed) {
781 for i := 1; i < len(enc.Operands); i++ {
782 enc.Operands[i].Typ = inst.operandType(enc.Operands[i])
783 }
784 }
785
786 func ProcessXMLFiles(insts []*InstructionParsed) {
787 var wg sync.WaitGroup
788 sort.Slice(insts, func(i, j int) bool {
789 if insts[i] == nil {
790 return false
791 }
792 if insts[j] == nil {
793 return true
794 }
795 return insts[i].Title < insts[j].Title
796 })
797 for i, inst := range insts {
798 if inst == nil {
799 insts = insts[:i]
800 break
801 }
802 }
803 for _, inst := range insts {
804 wg.Add(1)
805 go func(inst *InstructionParsed) {
806 defer wg.Done()
807 inst.extractBinary()
808 inst.processEncodings()
809 }(inst)
810 }
811 wg.Wait()
812 validate(insts)
813 debugInfo(*debug)
814 }
815
816 // The operand constraints, the value is an example instruction.
817 var allOpConstraints = map[string]*InstructionParsed{}
818
819 // The encoding function descriptions with their references to named bit ranges expanded.
820 // The value is an example instruction.
821 var AllEncodingDescs = map[string]*InstructionParsed{}
822
823 // The mapping from encoding function description to encoded-in.
824 var EncodingDescsToEncodedIn = map[string]string{}
825 var concatedRangeRe = regexp.MustCompile(`\((.*?) :: (.*?)(?: :: (.*?))?\)`)
826 var rangeIndexRe = regexp.MustCompile(`(.*?)\[(\d+)\]`)
827
828 func (inst *InstructionParsed) expandNamedBitRanges(elm *Element, varBin map[string]bitRange) string {
829 ranges := map[string]string{}
830 textExp := elm.textExp
831 br, ok := varBin[elm.encodedIn]
832 if !ok {
833 if matches := concatedRangeRe.FindStringSubmatch(elm.encodedIn); len(matches) > 1 {
834 for _, key := range matches[1:] {
835 br, ok2 := varBin[key]
836 if ok2 {
837 ranges[key] = fmt.Sprintf("[%d:%d)", br.lo, br.hi)
838 }
839 ok = true
840 }
841 } else if matches := rangeIndexRe.FindStringSubmatch(elm.encodedIn); len(matches) > 2 {
842 key := matches[1]
843 idx := matches[2]
844 idxI, err := strconv.Atoi(idx)
845 if err != nil {
846 log.Fatalf("invalid index: %s in %s, available: %v in %s\n", idx, elm.encodedIn, varBin, inst.file)
847 }
848 br, ok2 := varBin[key]
849 if ok2 {
850 ok = true
851 ranges[key] = fmt.Sprintf("[%d:%d)", br.lo+idxI, br.lo+idxI+1)
852 }
853 }
854 } else {
855 ranges[elm.encodedIn] = fmt.Sprintf("[%d:%d)", br.lo, br.hi)
856 }
857 if !ok {
858 if inst.Title == "SDOT (4-way, vectors) -- A64" || inst.Title == "UDOT (4-way, vectors) -- A64" {
859 // Known inconsistencies, the box contains a fixed bit, and the parsing logic missed it.
860 ranges["size"] = "[22:23)"
861 ok = true
862 } else {
863 log.Printf("unknown bit range: %s in %s, available: %v in %s\n", elm.encodedIn, elm.textExp, varBin, inst.file)
864 }
865 }
866 textExp += "\nbit range mappings:\n"
867 // Sort keys to ensure deterministic order
868 keys := make([]string, 0, len(ranges))
869 for k := range ranges {
870 keys = append(keys, k)
871 }
872 sort.Strings(keys)
873 for _, k := range keys {
874 textExp += fmt.Sprintf("%s: %s\n", k, ranges[k])
875 }
876 return textExp
877 }
878
879 // validate does the following:
880 // 1. checks if all instruction encodings are unique with regard to this tuple:
881 //
882 // (assembly mnemonic, [operand info])
883 //
884 // Note: variable arrangements are not checked, as before we reason about the encoding
885 // semantics we cannot fully deduplicate them, e.g.:
886 //
887 // SDOT <Zda>.<T>, <Zn>.<Tb>, <Zm>.<Tb>
888 // SDOT <Zda>.H, <Zn>.B, <Zm>.B
889 // SDOT <Zda>.S, <Zn>.H, <Zm>.H
890 //
891 // <T> and <Tb> are specified in the encoding text, that there is a constraint "T = 4*Tb".
892 // We don't know this fact by looking at the <asmtemplate> solely, without this information
893 // the first encoding domain entails the rest 2.
894 // We defer this deduplication to the assembler.
895 //
896 // 2. populates the constraints field of each operand.
897 // 3. bookkeep the encoding function descriptions and operand constraints.
898 func validate(insts []*InstructionParsed) {
899 allEncodings := map[string][]string{}
900 for _, inst := range insts {
901 for i, iclass := range inst.Classes.Iclass {
902 for j, encoding := range iclass.Encodings {
903 if encoding.Parsed == false {
904 continue
905 }
906 key := encoding.arm64Op
907 for k, operand := range encoding.Operands {
908 key += " " + operand.Typ
909 for l, elem := range operand.Elems {
910 constraints := []string{fmt.Sprintf("COP_%s__%d_", operand.Typ, l)}
911 if elem.fixedArng != "" {
912 key += "_(Arng:" + elem.fixedArng + ")"
913 constraints = append(constraints, "ARNG"+elem.fixedArng)
914 }
915 if elem.fixedModAmt != "" {
916 key += "_(ModAmt:" + elem.fixedModAmt + ")"
917 constraints = append(constraints, "MODAMT"+elem.fixedModAmt)
918 }
919 if elem.fixedScalarWidth != 0 {
920 key += fmt.Sprintf("_(ScalarWidth:%d)", elem.fixedScalarWidth)
921 constraints = append(constraints, fmt.Sprintf("R%d", elem.fixedScalarWidth))
922 }
923 if elem.fixedLSL != "" {
924 key += "_(LSL:" + elem.fixedLSL + ")"
925 constraints = append(constraints, "LSL"+elem.fixedLSL)
926 }
927 if elem.fixedSXTW {
928 key += "_(SXTW)"
929 constraints = append(constraints, "SXTW")
930 }
931 if elem.fixedUXTW {
932 key += "_(UXTW)"
933 constraints = append(constraints, "UXTW")
934 }
935 if elem.hasMod {
936 key += "_(mod)"
937 }
938 if elem.isP {
939 key += "_(P)"
940 }
941 if elem.isZ {
942 key += "_(Z)"
943 }
944 var cStr = "COP_NONE"
945 if len(constraints) > 1 {
946 cStr = strings.Join(constraints, "_")
947 allOpConstraints[cStr] = inst
948 }
949 inst.Classes.Iclass[i].Encodings[j].Operands[k].constraints = append(
950 inst.Classes.Iclass[i].Encodings[j].Operands[k].constraints, cStr)
951 textExpWithRanges := inst.expandNamedBitRanges(&elem, iclass.RegDiagram.varBin)
952 AllEncodingDescs[textExpWithRanges] = inst
953 if existing, ok := EncodingDescsToEncodedIn[textExpWithRanges]; ok && existing != elem.encodedIn {
954 log.Fatalf("duplicate encoding description for two different encoded-ins: %s for %s and %s in %s\n",
955 textExpWithRanges, existing, elem.encodedIn, inst.file)
956 }
957 EncodingDescsToEncodedIn[textExpWithRanges] = elem.encodedIn
958 inst.Classes.Iclass[i].Encodings[j].Operands[k].Elems[l].TextExpWithRanges = textExpWithRanges
959 }
960 inst.Classes.Iclass[i].Encodings[j].Operands[k].resolveConstraints()
961 }
962 allEncodings[key] = append(allEncodings[key], encoding.Asm)
963 }
964 }
965 }
966 keys := make([]string, 0, len(allEncodings))
967 for k := range allEncodings {
968 keys = append(keys, k)
969 }
970 sort.Strings(keys)
971 for _, k := range keys {
972 v := allEncodings[k]
973 if len(v) > 1 {
974 if strings.HasPrefix(k, "A64MOV") {
975 // These currently are:
976 // MOV <Zd>.<T>, #<const> (mov_dupm_z_i.xml)
977 // MOV <Zd>.<T>, #<imm>{, <shift>} (mov_dup_z_i.xml)
978 // These 2 instructions actually overlaps their domain!
979 // Although <shift> is optional here, we can force the user
980 // to always specify <shift> to manually deduplicate.
981 // Otherwise the assembler will just panic.
982 continue
983 }
984 if strings.HasPrefix(k, "A64FMOV") || strings.HasPrefix(k, "A64COMPACT") {
985 // Their domains does not overlap, it's ok to ignore.
986 continue
987 }
988 if len(v) == 2 {
989 var z2Cnt, z4Cnt int
990 for _, s := range v {
991 if strings.Contains(s, "-<Zt2>") || strings.Contains(s, "-<Zdn2>") {
992 z2Cnt++
993 }
994 if strings.Contains(s, "-<Zt4>") || strings.Contains(s, "-<Zdn4>") {
995 z4Cnt++
996 }
997 }
998 // These are reglists of 2 or 4 registers, they will be deduplicated by the assembler
999 // at encoding stage.
1000 if z2Cnt == 1 && z4Cnt == 1 {
1001 continue
1002 }
1003 }
1004 // If the diff is only by Pg/M or Pg/Z, it's ok to ignore, they are handled by the assembler.
1005 if len(v) == 2 {
1006 var hasPgM, hasPgZ bool
1007 for _, s := range v {
1008 if strings.Contains(s, "/M") {
1009 hasPgM = true
1010 }
1011 if strings.Contains(s, "/Z") {
1012 hasPgZ = true
1013 }
1014 }
1015 if hasPgM && hasPgZ {
1016 continue
1017 }
1018 }
1019 sort.Strings(v)
1020 log.Printf("%s:\n\t%v\n", k, strings.Join(v, "\n\t"))
1021 }
1022 }
1023 }
1024
1025 // expectedElemCount is the expected number of elements for each
1026 // operand class (AClass in the assembler).
1027 // The comments on the map elems are the GNU mnemonic forms;
1028 // the arrow-bracket enclosed parts are elements.
1029 var expectedElemCount = map[string]int{
1030 // <reg>.<T>
1031 "AC_ARNG": 2,
1032 "AC_PREG": 2,
1033 "AC_PREGZM": 2,
1034 "AC_ZREG": 2,
1035 // <reg>.<T>[<index>]
1036 "AC_ARNGIDX": 3,
1037 "AC_ZREGIDX": 3,
1038 "AC_PREGIDX": 3,
1039 // #<imm>, <shift>
1040 "AC_IMM": 1,
1041 // [<reg1>.<T1>, <reg2>.<T2>, <mod> <amount>]
1042 "AC_MEMEXT": 6,
1043 // [<reg>.<T>, #<imm>]
1044 "AC_MEMOFF": 3,
1045 // [<xn|sp>{, #<imm>, MUL VL}]
1046 // xn implies the constraint that it's an X reg, so one additional encoding func to check.
1047 "AC_MEMOFFMULVL": 3,
1048 // <preg>.<T>[<selreg>, <imm>]
1049 // selreg must be a W reg, so one additional encoding func to check.
1050 "AC_PREGSEL": 5,
1051 // <width><reg>
1052 "AC_SPZGREG": 2,
1053 "AC_VREG": 2,
1054 // {<reg>.<T>}
1055 "AC_REGLIST1": 2,
1056 // {<reg1>.<T1>, <reg2>.<T2>}
1057 "AC_REGLIST2": 4,
1058 // {<reg1>.<T1>, <reg2>.<T2>, <reg3>.<T3>}
1059 "AC_REGLIST3": 6,
1060 // {<reg1>.<T1>, <reg2>.<T2>, <reg3>.<T3>, <reg4>.<T4>}
1061 "AC_REGLIST4": 8,
1062 // {<reg1>.<T1>-<reg2>.<T2>}
1063 "AC_REGLIST_RANGE": 4,
1064 // <vl> or <prfop>
1065 "AC_SPECIAL": 1,
1066 // {<Reg>.<T>, <pattern>, MUL #<imm>}
1067 "AC_PREG_PATTERN": 4,
1068 "AC_REG_PATTERN": 4,
1069 "AC_ZREG_PATTERN": 4,
1070 }
1071
1072 // unresolvedConstraints stores the constraints that are not resolved.
1073 var unresolvedConstraints = map[string]struct{}{}
1074 var noOpCheck = "No-op check, returns true"
1075
1076 // resolveConstraints resolves the constraints for the given operand,
1077 // It understands the logic and expands the constraints to encoding functions
1078 // with proper comments. Resolving constraints is done by replacing the
1079 // constrained element with more elements in place, and adding the constraints
1080 // to the new element's encoding function.
1081 // This function also checks that the operand has the expected number of elements
1082 // after resolving the constraints.
1083 func (op *Operand) resolveConstraints() {
1084 // insertElmAt takes idx as the index in the old op.Elems slice.
1085 // we need to keep track of the index shifts brought by prior insertions.
1086 insertionHistory := make([]int, expectedElemCount[op.Typ])
1087 insertElmAt := func(idx int, symbol, textExpWithRanges string, needOffset bool) {
1088 if needOffset {
1089 offset := 0
1090 for i := range idx + 1 {
1091 offset += insertionHistory[i]
1092 }
1093 insertionHistory[idx]++
1094 idx += offset
1095 }
1096 op.Elems = append(op.Elems[:idx], append([]Element{
1097 {
1098 encodedIn: "nil",
1099 TextExpWithRanges: textExpWithRanges,
1100 symbol: symbol,
1101 },
1102 }, op.Elems[idx:]...)...)
1103 AllEncodingDescs[textExpWithRanges] = nil
1104 }
1105 // Constraint format: COP_<AClass>__<index>_(_<constraintTypes>)*
1106 // <AClass> is the operand class, e.g. AC_SPZGREG, AC_IMM, etc.
1107 // <index> is the index of the constrained element in the operand, e.g. 0, 1, 2, etc.
1108 // <constraintTypes> is the type of the constraint, e.g. ARNG, MODAMT, etc.
1109 for _, constraint := range op.constraints {
1110 constraint = strings.TrimPrefix(constraint, "COP_")
1111 parts := strings.Split(constraint, "__")
1112 if len(parts) != 3 {
1113 if constraint != "NONE" {
1114 log.Printf("Invalid constraint format: %s", constraint)
1115 }
1116 continue
1117 }
1118 acl := parts[0]
1119 index, err := strconv.Atoi(parts[1])
1120 if err != nil {
1121 log.Printf("Invalid constraint format: %s", constraint)
1122 }
1123 constraintTypes := strings.Split(parts[2], "_")
1124 for _, constraintType := range constraintTypes {
1125 switch constraintType {
1126 case "ARNGB":
1127 insertElmAt(index+1, "B", "Check this is a B arrangement", true)
1128 case "ARNGD":
1129 insertElmAt(index+1, "D", "Check this is a D arrangement", true)
1130 case "ARNGH":
1131 insertElmAt(index+1, "H", "Check this is a H arrangement", true)
1132 case "ARNGQ":
1133 insertElmAt(index+1, "Q", "Check this is a Q arrangement", true)
1134 case "ARNGS":
1135 insertElmAt(index+1, "S", "Check this is a S arrangement", true)
1136 case "R64":
1137 if acl == "AC_SPZGREG" {
1138 // Width constraints are preceeding the element.
1139 insertElmAt(index, "X", "Check this is a 64-bit scalar register", true)
1140 } else {
1141 insertElmAt(index+1, "nil", noOpCheck, true)
1142 }
1143 case "R32":
1144 if acl == "AC_SPZGREG" {
1145 // Width constraints are preceeding the element.
1146 insertElmAt(index, "W", "Check this is a 32-bit scalar register", true)
1147 } else {
1148 insertElmAt(index+1, "nil", noOpCheck, true)
1149 }
1150 case "LSL1", "LSL2", "LSL3", "LSL4", "SXTW", "UXTW", "MODAMT1", "MODAMT2", "MODAMT3":
1151 if acl == "AC_MEMEXT" {
1152 switch constraintType {
1153 case "LSL1", "LSL2", "LSL3", "LSL4":
1154 insertElmAt(index+1, "LSL", "Check this is mod and is LSL", true)
1155 case "UXTW":
1156 insertElmAt(index+1, "UXTW", "Check this is mod and is UXTW", true)
1157 case "SXTW":
1158 insertElmAt(index+1, "SXTW", "Check this is mod and is SXTW", true)
1159 }
1160 switch constraintType {
1161 case "LSL1", "MODAMT1":
1162 insertElmAt(index+1, "#1", "Check this is mod amount and is 1", true)
1163 case "LSL2", "MODAMT2":
1164 insertElmAt(index+1, "#2", "Check this is mod amount and is 2", true)
1165 case "LSL3", "MODAMT3":
1166 insertElmAt(index+1, "#3", "Check this is mod amount and is 3", true)
1167 case "LSL4":
1168 insertElmAt(index+1, "#4", "Check this is mod amount and is 4", true)
1169 }
1170 } else {
1171 log.Printf("Unknown constraint: %s", constraint)
1172 }
1173 default:
1174 log.Printf("Unknown constraint: %s", constraint)
1175 }
1176 }
1177 }
1178 // Check the number of elements
1179 if el := expectedElemCount[op.Typ]; len(op.Elems) != el {
1180 resolved := false
1181 switch op.Name {
1182 case "#0.0":
1183 if el == 1 && len(op.Elems) == 0 {
1184 op.Elems = make([]Element, 0, 1)
1185 insertElmAt(0, "#0.0", "Check this is immediate 0.0", false)
1186 resolved = true
1187 }
1188 case "#<imm>{, <shift>}":
1189 if el == 1 && len(op.Elems) == 2 {
1190 // The 2 elements explanation need to be merged
1191 insertElmAt(0, "#<imm>{, <shift>}", op.Elems[0].TextExpWithRanges+"\n"+op.Elems[1].TextExpWithRanges, false)
1192 op.Elems = op.Elems[:1]
1193 resolved = true
1194 }
1195 case "<Pd>", "<Pg>", "<Pn>", "<PNg>", "<Pt>", "<Pv>", "<Zd>", "<Zm>", "<Zn>", "<Zt>":
1196 if el == 2 && len(op.Elems) == 1 {
1197 insertElmAt(1, "nil", noOpCheck, false)
1198 resolved = true
1199 }
1200 case "<Dd>":
1201 if el == 2 && len(op.Elems) == 1 {
1202 insertElmAt(0, "nil", "Check this SIMD vector register is of width 64-bit.", false)
1203 resolved = true
1204 }
1205 case "<PNg>/Z", "<Pg>/Z":
1206 if el == 2 && len(op.Elems) == 1 {
1207 insertElmAt(1, "Z", "Check this is a zeroing predication", false)
1208 resolved = true
1209 }
1210 case "<Pg>/M", "<Pv>/M":
1211 if el == 2 && len(op.Elems) == 1 {
1212 insertElmAt(1, "M", "Check this is a merging predication", false)
1213 resolved = true
1214 }
1215 case "<PNn>[<imm>]":
1216 if el == 3 && len(op.Elems) == 2 {
1217 insertElmAt(1, "nil", noOpCheck, false)
1218 resolved = true
1219 }
1220 case "<Pd>.<T>{, <pattern>}":
1221 if el == 4 && len(op.Elems) == 3 {
1222 insertElmAt(3, "nil", noOpCheck, false)
1223 resolved = true
1224 }
1225 case "<Zd>{[<imm>]}", "<Zm>[<index>]", "<Zn>{[<imm>]}":
1226 if el == 3 && len(op.Elems) == 2 {
1227 insertElmAt(1, "nil", noOpCheck, false)
1228 resolved = true
1229 }
1230 case "[<Xn|SP>, <Xm>]", "[<Xn|SP>, <Zm>.D]", "[<Xn|SP>{, <Xm>}]", "[<Zn>.D{, <Xm>}]", "[<Zn>.S{, <Xm>}]":
1231 if el == 6 && len(op.Elems) == 4 {
1232 insertElmAt(4, "nil", "Check that there is no modifier (UXTW, SXTW, LSL)", false)
1233 insertElmAt(5, "nil", "Check that there is no modifier amount", false)
1234 resolved = true
1235 }
1236 case "[<Xn|SP>, <Zm>.S, <mod>]", "[<Xn|SP>, <Zm>.D, <mod>]":
1237 if el == 6 && len(op.Elems) == 5 {
1238 insertElmAt(5, "nil", "Check that there is no modifier amount", false)
1239 resolved = true
1240 }
1241 }
1242 if !resolved {
1243 unresolvedConstraints[fmt.Sprintf("Operand %s has %d elements, expected %d", op.Name, len(op.Elems), expectedElemCount[op.Typ])] = struct{}{}
1244 }
1245 }
1246 }
1247
1248 var noOpWidthDescInterpreter = func(enc EncodingParsed, nonSVEIndices []int) []EncodingParsed {
1249 for _, idx := range nonSVEIndices {
1250 enc.Operands[idx].Elems[0].TextExpWithRanges = noOpCheck
1251 }
1252 return []EncodingParsed{enc}
1253 }
1254
1255 var widthDescInterpreters = map[string]func(enc EncodingParsed, nonSVEIndices []int) []EncodingParsed{
1256 "No-op check, returns true": noOpWidthDescInterpreter,
1257 `
1258 Is a width specifier,
1259 size <V>
1260 00 B
1261 01 H
1262 10 S
1263 11 D
1264 bit range mappings:
1265 size: [22:24)`: func(enc EncodingParsed, nonSVEIndices []int) []EncodingParsed {
1266 encs := []EncodingParsed{}
1267 for i, suffix := range []string{"B", "H", "S", "D"} {
1268 newEnc := enc
1269 // Hard code the width into the fixed binary.
1270 newEnc.Binary |= uint32(i) << 22
1271 newEnc.GoOp = enc.GoOp + suffix
1272 // Nullify the width specifier element.
1273 for _, idx := range nonSVEIndices {
1274 newEnc.Operands[idx].Elems[0].TextExpWithRanges = noOpCheck
1275 }
1276 encs = append(encs, newEnc)
1277 }
1278 return encs
1279 },
1280 `
1281 Is a width specifier,
1282 size <R>
1283 00 W
1284 01 W
1285 10 W
1286 11 X
1287 bit range mappings:
1288 size: [22:24)`: func(enc EncodingParsed, nonSVEIndices []int) []EncodingParsed {
1289 encs := []EncodingParsed{}
1290 // X doesn't need a suffix.
1291 for i, suffix := range []string{"W", ""} {
1292 newEnc := enc
1293 // It looks like GNU assembler prefers 00 for W.
1294 newEnc.Binary |= uint32(i*3) << 22
1295 newEnc.GoOp = enc.GoOp + suffix
1296 for _, idx := range nonSVEIndices {
1297 newEnc.Operands[idx].Elems[0].TextExpWithRanges = noOpCheck
1298 }
1299 encs = append(encs, newEnc)
1300 }
1301 return encs
1302 },
1303 `
1304 Is a width specifier,
1305 sz <R>
1306 0 W
1307 1 X
1308 bit range mappings:
1309 sz: [22:23)`: func(enc EncodingParsed, nonSVEIndices []int) []EncodingParsed {
1310 encs := []EncodingParsed{}
1311 for i, suffix := range []string{"W", ""} {
1312 newEnc := enc
1313 newEnc.Binary |= uint32(i) << 22
1314 newEnc.GoOp = enc.GoOp + suffix
1315 for _, idx := range nonSVEIndices {
1316 newEnc.Operands[idx].Elems[0].TextExpWithRanges = noOpCheck
1317 }
1318 encs = append(encs, newEnc)
1319 }
1320 return encs
1321 },
1322 `
1323 Is a width specifier,
1324 size <V>
1325 00 RESERVED
1326 01 H
1327 10 S
1328 11 D
1329 bit range mappings:
1330 size: [22:24)`: func(enc EncodingParsed, nonSVEIndices []int) []EncodingParsed {
1331 encs := []EncodingParsed{}
1332 for i, suffix := range []string{"H", "S", "D"} {
1333 newEnc := enc
1334 newEnc.Binary |= uint32(i+1) << 22
1335 newEnc.GoOp = enc.GoOp + suffix
1336 for _, idx := range nonSVEIndices {
1337 newEnc.Operands[idx].Elems[0].TextExpWithRanges = noOpCheck
1338 }
1339 encs = append(encs, newEnc)
1340 }
1341 return encs
1342 },
1343 "Check this SIMD vector register is of width 64-bit.": func(enc EncodingParsed, nonSVEIndices []int) []EncodingParsed {
1344 enc.GoOp = enc.GoOp + "D"
1345 for _, idx := range nonSVEIndices {
1346 enc.Operands[idx].Elems[0].TextExpWithRanges = noOpCheck
1347 }
1348 return []EncodingParsed{enc}
1349 },
1350 `
1351 Is a width specifier,
1352 sf <R>
1353 0 W
1354 1 X
1355 bit range mappings:
1356 sf: [12:13)`: func(enc EncodingParsed, nonSVEIndices []int) []EncodingParsed {
1357 encs := []EncodingParsed{}
1358 for i, suffix := range []string{"W", ""} {
1359 newEnc := enc
1360 newEnc.Binary |= uint32(i) << 12
1361 newEnc.GoOp = enc.GoOp + suffix
1362 for _, idx := range nonSVEIndices {
1363 newEnc.Operands[idx].Elems[0].TextExpWithRanges = noOpCheck
1364 }
1365 encs = append(encs, newEnc)
1366 }
1367 return encs
1368 },
1369 "Check this is a 64-bit scalar register": noOpWidthDescInterpreter,
1370 "Check this is a 32-bit scalar register": func(enc EncodingParsed, nonSVEIndices []int) []EncodingParsed {
1371 enc.GoOp = enc.GoOp + "W"
1372 for _, idx := range nonSVEIndices {
1373 enc.Operands[idx].Elems[0].TextExpWithRanges = noOpCheck
1374 }
1375 return []EncodingParsed{enc}
1376 },
1377 }
1378
1379 // SplitInstByRegWidth splits an instruction encoding into multiple instruction
1380 // encodings based on the register width. This takes an instruction encoding that's
1381 // already validated and returns a list of instruction encodings that are split by
1382 // register width. The expected instruction encoding should only contain one elem of
1383 // type AC_SPZGREG, AC_VREG, and the first element is a width specifier.
1384 // The width specifier needs to be understood by this function.
1385 func SplitInstByRegWidth(enc EncodingParsed) []EncodingParsed {
1386 widthDesc := []string{}
1387 nonSVEIndices := []int{}
1388 for i, op := range enc.Operands {
1389 if op.Typ == "AC_SPZGREG" || op.Typ == "AC_VREG" {
1390 widthDesc = append(widthDesc, op.Elems[0].TextExpWithRanges)
1391 nonSVEIndices = append(nonSVEIndices, i)
1392 }
1393 }
1394 if len(widthDesc) == 0 {
1395 return []EncodingParsed{enc}
1396 }
1397 if len(widthDesc) > 1 {
1398 // Manually handle them...
1399 switch enc.Name {
1400 case "addpl_r_ri_", "addvl_r_ri_":
1401 // They are fixed X registers, so OK to do nothing.
1402 return []EncodingParsed{enc}
1403 case "clasta_v_p_z_", "clasta_r_p_z_", "clastb_v_p_z_", "clastb_r_p_z_",
1404 "ctermeq_rr_", "ctermne_rr_", "fadda_v_p_z_", "index_z_rr_":
1405 // The 2 non-sve registers are the same width, so OK to slip it through to the interpreter.
1406 case "sqdecp_r_p_r_sx", "sqincp_r_p_r_sx":
1407 // These 2 instructions have 2 variants:
1408 // e.g. for SQINCP:
1409 // 1. SQINCP <Xdn>, <Pm>.<T>, <Wdn> (these are the ones we see in this case)
1410 // 2. SQINCP <Xdn>, <Pm>.<T> (these has encoding name without _sx, and they slip through)
1411 // The logic following will rename the first one as SQINCPW, the second one unchanged.
1412 // So it's also safe to slip it through to the interpreter.
1413 default:
1414 if !strings.HasPrefix(enc.Name, "while") {
1415 // The series of while instructions all have the same width for their 2 non-sve registers, so
1416 // also safe to slip through.
1417 log.Printf("Warning: instruction %s has %d width descriptors", enc.Name, len(widthDesc))
1418 return []EncodingParsed{enc}
1419 }
1420 }
1421 }
1422 for knownWD := range widthDescInterpreters {
1423 if strings.Join(strings.Fields(widthDesc[0]), " ") == strings.Join(strings.Fields(knownWD), " ") {
1424 return widthDescInterpreters[knownWD](enc, nonSVEIndices)
1425 }
1426 }
1427 log.Printf("Warning: unknown width descriptor: %s", widthDesc[0])
1428 return []EncodingParsed{enc}
1429 }
1430
1431 // debugInfo prints all fixed symbols, operand constraints and encoding function descriptions
1432 // in deterministic order.
1433 func debugInfo(debug int) {
1434 log.Printf("len(allFixedSymbols) = %v\n", len(allFixedSymbols))
1435 if debug > 0 {
1436 keys := make([]string, 0, len(allFixedSymbols))
1437 for k := range allFixedSymbols {
1438 keys = append(keys, k)
1439 }
1440 sort.Strings(keys)
1441 for _, k := range keys {
1442 fmt.Printf("%s:\n", k)
1443 for v2 := range allFixedSymbols[k] {
1444 fmt.Printf("\t%s\n", v2)
1445 if debug > 1 {
1446 fmt.Printf("Example Inst at %s\n", allFixedSymbols[k][v2].file)
1447 }
1448 }
1449 }
1450 }
1451 log.Printf("len(allOpConstraints) = %v\n", len(allOpConstraints))
1452 if debug > 0 {
1453 keys := make([]string, 0, len(allOpConstraints))
1454 for k := range allOpConstraints {
1455 keys = append(keys, k)
1456 }
1457 sort.Strings(keys)
1458 for _, k := range keys {
1459 fmt.Printf("%s\n", k)
1460 if debug > 1 {
1461 fmt.Printf("Example Inst at %s\n", allOpConstraints[k].file)
1462 }
1463 }
1464 }
1465 log.Printf("len(AllEncodingDescs) = %v\n", len(AllEncodingDescs))
1466 if debug > 0 {
1467 keys := make([]string, 0, len(AllEncodingDescs))
1468 for k := range AllEncodingDescs {
1469 keys = append(keys, k)
1470 }
1471 sort.Strings(keys)
1472 for _, k := range keys {
1473 fmt.Printf("%s\n", k)
1474 if debug > 1 {
1475 fmt.Printf("Example Inst at %s\n", AllEncodingDescs[k].file)
1476 }
1477 }
1478 }
1479 keys := make([]string, 0, len(unresolvedConstraints))
1480 for k := range unresolvedConstraints {
1481 keys = append(keys, k)
1482 }
1483 sort.Strings(keys)
1484 for _, k := range keys {
1485 log.Printf("%s\n", k)
1486 }
1487 }